_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11000
manageEvents
train
function manageEvents(els, evList, cb, method, options) { els = domToArray(els) split(evList).forEach((e) => { els.forEach(el => el[method](e, cb, options || false)) }) }
javascript
{ "resource": "" }
q11001
WriteData
train
function WriteData(Register, ByteArray, Callback) { i2cdevice.writeBytes(Register, ByteArray, function(err) { Callback(err); }); }
javascript
{ "resource": "" }
q11002
createLazyBlock
train
function createLazyBlock( { resolver, chunkName, initModel, loadingView, messages } = {} ) { const resolveState = { resolver: null, block: null, msgs: [], chunkName }; resolveState.resolver = createBlockResolver(resolver, resolveState); const lazyLogic = createLazyLogic(resolveState, initModel); const lazyView = createLazyView(resolveState, loadingView); const lazyMessages = createLazyMessages(resolveState, messages); return { resolver: resolveState.resolver, Logic: lazyLogic, View: lazyView, Messages: lazyMessages }; }
javascript
{ "resource": "" }
q11003
train
function(arg) { var hash = crypto.createHash('md5') .update(JSON.stringify(arg)) .digest('hex'); return path.join(this.dir, hash); }
javascript
{ "resource": "" }
q11004
error
train
function error(opts) { //define your custom views opts = opts || {}; //custom views if(!opts.custom) opts.custom={}; // better to disable layout in not explicity set, in case there are error in it if(!opts.layout) opts.layout= false; // @todo to be easier to install, should render from this module path if(!opts.view) opts.view= 'error'; return function *error(next){ var env= this.app.env; try { yield next; if (this.response.status==404 && !this.response.body) this.throw(404); } catch (err) { this.status = err.status || 500; // application this.app.emit('error', err, this); // accepted types switch (this.accepts('html', 'text', 'json')) { case 'text': if (env==='development') this.body= err.message else if (err.expose) this.body= err.message else this.body= http.STATUS_CODES[this.status]; break; case 'json': if (env==='development') this.body= {error: err.message} else if (err.expose) this.body= {error: err.message} else this.body= {error: http.STATUS_CODES[this.status]} break; case 'html': var view= typeof opts.custom[this.status]!=='undefined' ? opts.custom[this.status] : opts.view; var options= { layout: opts.layout, env: env, ctx: this, request: this.request, response: this.response, error: err.message, stack: err.stack, status: this.status, code: err.code }; //in case of any error view error try{ yield this.render(view, options); }catch(e){ this.body= '<h1>'+e.code+'</h1><h3>'+e.message+'</h3><pre><code>'+e.stack+'</code></pre>' } break; } } } }
javascript
{ "resource": "" }
q11005
train
function(addresses) { var defered = q.defer(); var currentStep = 0; var numSteps = addresses.length; var results = []; var handleReadSuccess = function(res) { results.push({'address': addresses[currentStep], 'isErr': false, 'data': res}); if(currentStep < numSteps) { currentStep += 1; performRead(); } else { defered.resolve(results); } }; var handleReadError = function(err) { results.push({'address': addresses[currentStep], 'isErr': true, 'data': err}); if(currentStep < numSteps) { currentStep += 1; performRead(); } else { defered.resolve(results); } }; var performRead = function() { self.qRead(addresses[currentStep]) .then(handleReadSuccess, handleReadError); }; performRead(); return defered.promise; }
javascript
{ "resource": "" }
q11006
unpack
train
function unpack(kind, root, target, proto, source){ if (ownp(kind)) do_unpack(proto, source, methodize) if (genericp(kind)) do_unpack(target, source) if (utilsp(kind)) do_unpack(root, source.$black_utils) }
javascript
{ "resource": "" }
q11007
unpack_all
train
function unpack_all(kind, global) { keys(this).forEach(function(module) { module = this[module] if (!fnp(module)) unpack( kind , global || top , module.$black_box , module.$black_proto , module) }, this) }
javascript
{ "resource": "" }
q11008
methodize
train
function methodize(fn) { return function() { var args args = slice.call(arguments) return fn.apply(this, [this].concat(args)) } }
javascript
{ "resource": "" }
q11009
createReadManufacturingInfoBundle
train
function createReadManufacturingInfoBundle() { debugRMIOps('in createReadManufacturingInfoBundle'); // Initialize the bundle object with some basic data. var bundle = { 'info': {}, 'infoString': '', 'manufacturingData': manufacturingData, 'isError': false, 'errorStep': '', 'error': undefined, 'errorCode': 0, }; // Initialize the manufacturing info object with dummy data. manufacturingData.forEach(function(manData) { if(manData.type === 'str') { bundle.info[manData.key] = ''; } else if(manData.type === 'fl4') { bundle.info[manData.key] = 0.000; } else if(manData.type === 'int') { bundle.info[manData.key] = 0; } else { bundle.info[manData.key] = ''; } }); return bundle; }
javascript
{ "resource": "" }
q11010
readManufacturingInfoFlashData
train
function readManufacturingInfoFlashData(bundle) { debugRMIOps('in readManufacturingInfoFlashData'); var defered = q.defer(); var startingAddress = 0x3C6000; var numIntsToRead = 8*8; self.readFlash(startingAddress, numIntsToRead) .then(function(res) { // res is an object with an attribute "results" that is an array // of bytes. Therefore this debug call outputs a lot of data: // debugRMIOps('in readManufacturingInfoFlashData res', res); var str = ''; var rawData = []; res.results.forEach(function(val) { var bA = (val >> 24) & 0xFF; rawData.push(bA); var bB = (val >> 16) & 0xFF; rawData.push(bB); var bC = (val >> 8) & 0xFF; rawData.push(bC); var bD = (val >> 0) & 0xFF; rawData.push(bD); }); function isASCII(str, extended) { return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str); } // debugRMIOps('in readManufacturingInfoFlashData', rawData); rawData.forEach(function(raw) { var newStrPartial = String.fromCharCode(raw); if(isASCII(newStrPartial)) { str += newStrPartial; } }); debugRMIOps('in readManufacturingInfoFlashData', str); // console.log('Data:'); // console.log(str); var noReturnChars = str.split('\r').join(''); strPartials = noReturnChars.split('\n'); var manufacturingInfoStr = ''; // console.log('Processing partials'); strPartials.forEach(function(strPartial) { try { // console.log('Checking partial', strPartial); if(isData.test(strPartial)) { // console.log('Parsing partial', strPartial); var parsedInfo = parseManufacturingInfo(strPartial); // console.log('Saving partial', strPartial, parsedInfo); manufacturingInfoStr += parsedInfo.str; manufacturingInfoStr += ': '; manufacturingInfoStr += parsedInfo.rawData; manufacturingInfoStr += '\n'; bundle = saveParsedDataToBundle(bundle, parsedInfo); } else { // console.log('Not Checking partial', strPartial); } } catch(err) { errorLog('Error parsing partial (t7_manufacturing_info_ops.js)', err, strPartial); errorLog(err.stack); console.error('Error parsing partial (t7_manufacturing_info_ops.js)', err, strPartial); } }); // console.log(noReturnChars); bundle.infoString = manufacturingInfoStr; // console.log(bundle.info); defered.resolve(bundle); }, function(err) { debugRMIOps('in readManufacturingInfoFlashData err', err); bundle.isError = true; bundle.errorStep = 'readManufacturingInfoFlashData'; bundle.error = modbusMap.getErrorInfo(err); bundle.errorCode = err; defered.reject(bundle); }); return defered.promise; }
javascript
{ "resource": "" }
q11011
train
function(element, rule){ var elementClassName = element.className, elementID = element.id, elementTagName = element.tagName, elementDisplayName = element.constructor.displayName; if(rule.tagName && !this.tagName(rule.tagName, elementTagName, elementDisplayName)){ return false; } if(rule.id && !this.id(rule.id, elementID)){ return false; } if(rule.classNames && !this.className(rule.classNames, elementClassName)){ return false; } if(rule.pseudos && !this.pseudoMatcher(rule.pseudos, element, elementTagName)){ return false; } if(rule.attrs && !this.attributeMatcher(rule.attrs, element)){ return false; } return true; }
javascript
{ "resource": "" }
q11012
train
function(pseudoRule, element, elementTagName){ if(pseudoRule.name === 'checked'){ return this.checked(element, elementTagName); } if(pseudoRule.name === 'empty'){ return this.empty(element); } }
javascript
{ "resource": "" }
q11013
train
function(attributeRules, element){ for(var i = 0; i < attributeRules.length; i++){ var attributeName = attributeRules[i].name, objectToCheck = element; if(typeof element.context === 'undefined'){ //Native DOM node if(_.startsWith(attributeName, 'data-')){ objectToCheck = element.dataset; attributeName = attributeName.split('-')[1]; } } else{ //React component instance objectToCheck = element.props; } var elementProperty = objectToCheck[attributeName], operator = attributeRules[i].operator, value = attributeRules[i].value; //Only checking for existance, don't care about the value if(!operator && elementProperty === undefined){ return false; } var doesValueMatch = this.compareElementProperty(elementProperty, operator, value); if(!doesValueMatch){ return false; } } return true; }
javascript
{ "resource": "" }
q11014
train
function(ruleClassName, elementClassName){ if(!elementClassName){ return false; } for(var i = 0; i < ruleClassName.length; i++){ if((' ' + elementClassName + ' ').indexOf(' ' + ruleClassName[i] + ' ') === -1){ return false; } } return true; }
javascript
{ "resource": "" }
q11015
train
function(element, tagName){ if(!tagName || tagName.toLowerCase() !== 'input'){ return false; } var inputType = element.type.toLowerCase(); if(inputType !== 'checkbox' && inputType !== 'radio'){ return false; } return element.checked !== false; }
javascript
{ "resource": "" }
q11016
train
function(property, operator, value){ if(operator === '='){ return this.compareElementPropertyEquality(property, value); } if(operator === '~='){ return String(property).split(" ").indexOf(value) !== -1; } if(operator === '^='){ return _.startsWith(property, value); } if(operator === '$='){ return _.endsWith(property, value); } if(operator === '*='){ return property && property.indexOf(value) !== -1; } return true; }
javascript
{ "resource": "" }
q11017
train
function(property, value){ //When doing direct comparisons, do some conversions between numbers, booleans, null/undefined since //the value in the selector always comes through as a string if(_.isNumber(property)){ return property === parseInt(value); } else if(_.isBoolean(property)){ return property === (value === 'true' ? true : false); } else if(value === "null"){ return property === null; } return property === value; }
javascript
{ "resource": "" }
q11018
isVersionAtLeast
train
function isVersionAtLeast(dottedVersion, major, minor, patch){ var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }), testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); }); for( i = 0; i < testParts.length; i++ ){ v = verParts[i] || 0; t = testParts[i] || 0; if( v !== t ){ return ( v > t ); } } return true; }
javascript
{ "resource": "" }
q11019
train
function(targetNode, mode, map) { if(mode === undefined || mode === "over"){ mode = "child"; } var pos, prevParent = this.parent, targetParent = (mode === "child") ? targetNode : targetNode.parent; if(this === targetNode){ return; }else if( !this.parent ){ throw "Cannot move system root"; }else if( targetParent.isDescendantOf(this) ){ throw "Cannot move a node to its own descendant"; } // Unlink this node from current parent if( this.parent.children.length === 1 ) { if( this.parent === targetParent ){ return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos+1, 0, this); break; default: throw "Invalid mode " + mode; } } else { targetParent.children = [ this ]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // }^ // Let caller modify the nodes if( map ){ targetNode.visit(map, true); } // Handle cross-tree moves if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimantal!"); this.visit(function(n){ // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } // Update HTML markup if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }
javascript
{ "resource": "" }
q11020
train
function(stopOnParents) { var nodeList = []; this.rootNode.visit(function(node){ if( node.selected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }
javascript
{ "resource": "" }
q11021
train
function(setFocus) { var node = this.activeNode; if( node ) { this.activeNode = null; // Force re-activating node.setActive(); if( setFocus ){ node.setFocus(); } } }
javascript
{ "resource": "" }
q11022
train
function(ctx) { // TODO: return promise? if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if( ctx.targetType === "title" ) { ctx.originalEvent.preventDefault(); } }
javascript
{ "resource": "" }
q11023
train
function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.ul){ if( node.isRoot() ) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n){ n.li = n.ul = null; }); } }
javascript
{ "resource": "" }
q11024
train
function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node; flag = (flag !== false); // Blur previous node if any if(tree.focusNode){ if(tree.focusNode === node && flag){ // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, {node: tree.focusNode}); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if(flag){ if( !this.hasFocus() ){ node.debug("nodeSetFocus: forcing container focus"); // Note: we pass _calledByNodeSetFocus=true this._callHook("treeSetFocus", ctx, true, true); } // this.nodeMakeVisible(ctx); node.makeVisible({scrollIntoView: false}); tree.focusNode = node; // node.debug("FOCUS..."); // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if(ctx.options.autoActivate){ // tree.nodeSetActive(ctx, true); // } if(ctx.options.autoScroll){ node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }
javascript
{ "resource": "" }
q11025
train
function(el){ if(el instanceof FancytreeNode){ return el; // el already was a FancytreeNode }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } while( el ) { if(el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }
javascript
{ "resource": "" }
q11026
train
function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title this._super(ctx, title); // Append a counter badge if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count)); } }
javascript
{ "resource": "" }
q11027
train
function(event) { var sourceNode = $.ui.fancytree.getNode(event.target); if(!sourceNode){ // Dynatree issue 211 // might happen, if dragging a table *header* return "<div>ERROR?: helper requested but sourceNode not found</div>"; } return sourceNode.tree.ext.dnd._onDragEvent("helper", sourceNode, null, event, null, null); }
javascript
{ "resource": "" }
q11028
isResolved
train
function isResolved(schema, schemas) { return (schema.deps || []).every(_.partial(function (tableNames, tableName) { return tableNames.indexOf(tableName) > -1; }, _.pluck(schemas, 'tableName'))); }
javascript
{ "resource": "" }
q11029
listDir
train
function listDir (path, originalPath) { if (!originalPath) { originalPath = path + separator; } // promises for sub listDir calls var dirs = []; return Promise.resolve(fs.readdir(path)) // include only files .filter(function (item) { var absolutePath = join(path, item); return fs.stat(absolutePath).then(function (stat) { var isDirectory = stat.isDirectory(); // if directory, read it if (isDirectory) { var list = listDir(absolutePath, originalPath); dirs.push(list); } return !isDirectory; }); }) // return relative paths .map(function (file) { var absolutePath = join(path, file); var relativePath = absolutePath.replace(originalPath, ''); return relativePath; }) // add files from sub-directories .then(function (files) { // wait for all listDir() to complete // and merge their results return Promise .all(dirs) .then(function () { dirs.forEach(function (promise) { var subFiles = promise.value(); files = files.concat(subFiles); }); return files; }); }); }
javascript
{ "resource": "" }
q11030
read
train
function read(src, basedir, callback){ var page = new Page(src, basedir) page.read(callback) }
javascript
{ "resource": "" }
q11031
apier
train
function apier(config) { // on server start.. db.connect(config.mongoUrl); accessVerifier.init(config.access); schemaExtender.handleErrors = true; reqlog.info('apier initialized!!'); var app = function(req, res) { // this is the final handler if no match found router(req, res, function(error) { if (error) { reqlog.error(error); responseBuilder.error(req, res, 'INTERNAL_SERVER_ERROR'); } else { reqlog.info('NOT_FOUND:', req.method + ' ' + req.url); responseBuilder.error(req, res, 'NOT_FOUND'); } }); }; app.endpoint = endpoint; return app; }
javascript
{ "resource": "" }
q11032
endpoint
train
function endpoint(options) { // find the middlewares options.permissions = options.permissions || ['null']; options.middlewares = options.middlewares || []; options.middlewares.unshift([permissioner(options.permissions)]); for (var i = 0, length = options.methods.length; i < length; i++) { var method = options.methods[i].toLowerCase(); reqlog.log('setup endpoint', method + ' ' + options.url); router[method](options.url, options.middlewares, function(req, res) { routerCallback(req, res, options.callback); }); } }
javascript
{ "resource": "" }
q11033
routerCallback
train
function routerCallback(req, res, callback) { var innerSelf = { req: req, res: res, send: function(data) { send.call(this, data); }, setStatusCode: function(statusCode) { setStatusCode.call(this, statusCode); } }; reqlog.info('inside routerCallback for endpoint: ', req.url); callback.call(innerSelf, req, res); }
javascript
{ "resource": "" }
q11034
sync
train
function sync(schemas) { var resolver = new Resolver(schemas); // Reduce force sequential execution. return Promise.resolve(Promise.reduce(resolver.resolve(), syncSchema.bind(this), [])) .tap(function () { var knex = this.knex; return Promise.map(schemas || [], function(schema) { return (schema.postBuild || _.noop)(knex); }); }.bind(this)); }
javascript
{ "resource": "" }
q11035
syncSchema
train
function syncSchema(result, schema) { var knex = this.knex; return knex.schema.hasTable(schema.tableName) .then(function (exists) { if (exists) return result; return knex.schema.createTable(schema.tableName, defineSchemaTable(schema)) .then(function () { return result.concat([schema]); }); }); }
javascript
{ "resource": "" }
q11036
defineSchemaTable
train
function defineSchemaTable(schema) { return function (table) { table.timestamps(); (schema.build || _.noop)(table); }; }
javascript
{ "resource": "" }
q11037
train
function( data ) { var read_buffer = read_buffers_by_connection[tcp_connection]; read_buffer += data; //split by new lines, var messages = read_buffer.split('\n'); //last element is either a partial message, or '' read_buffer = messages.pop(); for ( var i = 0; i < messages.length; i++ ) { //TODO error handling var message = messages[i]; var components = message.split( ' ' ); var path = components[0]; var value = components[1]; var timestamp = components[2]; that.emit( path, value, timestamp ); } }
javascript
{ "resource": "" }
q11038
isArrayLikeObject
train
function isArrayLikeObject (subject) { var length = subject.length if ( typeof subject === 'function' || Object(subject) !== subject || typeof length !== 'number' // `window` already has a property `length` || 'setInterval' in subject ) { return false } return length === 0 || length > 0 && (length - 1) in subject }
javascript
{ "resource": "" }
q11039
clonePureArray
train
function clonePureArray (subject, host) { var i = subject.length var start = host.length while (i --) { host[start + i] = subject[i] } return host }
javascript
{ "resource": "" }
q11040
MerkleTree
train
function MerkleTree(leaves, hasher) { if (!(this instanceof MerkleTree)) { return new MerkleTree(leaves, hasher); } this._hasher = hasher || this._hasher; this._leaves = []; this._depth = 0; this._rows = []; this._count = 0; assert(Array.isArray(leaves), 'Invalid leaves array supplied'); assert(typeof this._hasher === 'function', 'Invalid hash function supplied'); for (var i = 0; i < leaves.length; i++) { this._feed(leaves[i]); } this._compute(); }
javascript
{ "resource": "" }
q11041
queueTasks
train
function queueTasks (testTasks, buildTasks) { // Queue up test tasks, removing them if already queued up _.forEach({ test: testTasks, build: buildTasks }, (queuingTasks, type) => { _.forEach(queuingTasks, (task) => { // Remove if already queued const removed = _.remove(queue[type], (queuedTask) => { return (queuedTask === task); }); // Queue task ... queue[type].push(task); // Reorder tasks by original configuration ordering queue[type] = _.sortBy(queue[type], (queuedTask) => { return _.findIndex(orderedTasks, (originalTask) => { return (originalTask === queuedTask); }); }); // Prompt queued task console.log(`> ${removed.length ? 'Requeued' : 'Queued'} ${ type } task for execution: "${ task.blue }"`); console.log(` Queue: ${ [...queue.test, ...queue.build].join(', ').gray }`); }); }); // Execute tasks from the queue executeQueuedTasks(); }
javascript
{ "resource": "" }
q11042
executeQueuedTasks
train
function executeQueuedTasks () { // Delay execution to allow for more tasks to queue up setTimeout(() => { // Check if already executing and if any tasks ready for execution if (!executing && (queue.test.length || queue.build.length)) { // Flag executing status executing = true; // Pop a task from the execution queue const task = (queue.test.length ? queue.test.splice(0, 1)[0] : queue.build.splice(0, 1)[0]); // Execute task gulp.series([task])(() => { // Flag executing status executing = false; // Execute next task from the queue executeQueuedTasks(); }); } }, 250); // If no tasks queued up, prompt watcher done if (!executing && !(queue.test.length || queue.build.length)) { console.log(); console.log(`> WATCHER(S) DONE PROCESSING - WAITING FOR CHANGES ...`.green); console.log(); } }
javascript
{ "resource": "" }
q11043
train
function () { return { lineSeparator: '\n', // done maxLength: 120, // TODO wrapIfLong: false, // TODO indent: 4, // done useTabIndent: false, // done spaces: { around: { unaryOperators: false, // TODO binaryOperators: true, // done ternaryOperators: true // done }, before: { functionDeclarationParentheses: false, // done function foo() { functionExpressionParentheses: true, // done var foo = function () { parentheses: true, // done if (), for (), while (), ... leftBrace: true, // done function () {, if () {, do {, try { ... keywords: true // done if {} else {}, do {} while (), try {} catch () {} finally }, within: { // function call, function declaration, if, for, while, switch, catch parentheses: false // done }, other: { beforePropertyNameValueSeparator: false, // done {key: value} {key : value} {key:value} afterPropertyNameValueSeparator: true // done } }, bracesPlacement: { // 1. same line 2. next line functionDeclaration: 1, // TODO other: 1 // TODO }, blankLines: { keepMaxBlankLines: 1, // done atEndOfFile: true // done }, other: { keepArraySingleLine: false // TODO default formatted array multi line }, fix: { prefixSpaceToLineComment: false, // done alterCommonBlockCommentToLineComment: false, // done singleVariableDeclarator: false, // done fixInvalidTypeof: false, // done removeEmptyStatement: false, // done autoSemicolon: false, // done singleQuotes: false, // done eqeqeq: false, // done invalidConstructor: false, // done addCurly: false, // done removeDebugger: false, // done noElseReturn: false } }; }
javascript
{ "resource": "" }
q11044
train
function (defaults, configure) { for (var key in defaults) { if (defaults.hasOwnProperty(key)) { if (typeof defaults[key] === 'object') { // recursive if (typeof configure[key] === 'object') { overwriteConfig(defaults[key], configure[key]); } } else { // copy directly if (typeof configure[key] !== 'undefined') { defaults[key] = configure[key]; } } } } }
javascript
{ "resource": "" }
q11045
train
function () { var indentStr = ''; for (var i = 0; i < indentLevel; i++) { indentStr += INDENT; } return { type: 'WhiteSpace', value: indentStr }; }
javascript
{ "resource": "" }
q11046
train
function (token) { var inline = false; if (token) { if (token.type === 'LineComment') { inline = true; } else if (token.type === 'BlockComment') { inline = (token.value.indexOf('\n') === -1); } } return inline; }
javascript
{ "resource": "" }
q11047
train
function (startToken, endToken, types) { var is = true; var token = startToken; while (token.next && token.next !== endToken) { token = token.next; if (types.indexOf(token.type) === -1) { is = false; break; } } return is; }
javascript
{ "resource": "" }
q11048
pathExpression
train
function pathExpression (token, tokens) { const expression = [] while (true) { if (!token) { break } if (token === ')') { tokens.unshift(token) break } if (includes('}]', token)) { throw new Error(`A fragment can't contain "${token}"`) } if (token === ',') { break } if (token === '[') { expression.push(escapedFragment(token, tokens)) } else if (token === '(') { expression.push(pathExpressions(token, tokens)) } else if (token === '{') { expression.push(customFragment(token, tokens)) } else { expression.push(unescapedFragment(token, tokens)) } token = tokens.shift() } return { _type: pathExpression.name, expression } }
javascript
{ "resource": "" }
q11049
context
train
function context(str) { var arr = code(str); var len = arr.length, i = 0; var res = {}; while (len--) { var ele = arr[i++]; if (ele.type !== 'comment') { res[ele.name] = ele.begin; } } return res; }
javascript
{ "resource": "" }
q11050
format
train
function format(obj, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } opts = opts || {}; if (Array.isArray(opts.filter) || typeof opts.filter === 'string') { obj = filter(obj, opts.filter); } var keys = Object.keys(obj); var len = keys.length, i = 0; var str = ''; var total = len; while (len--) { var fp = keys[i++]; var ctx = context(read(fp), fn); var name = basename(fp); str += heading(name, fp); var list = obj[fp]; var methods = Object.keys(list); total += methods.length; str += listify(fp, methods, ctx); } var res = {}; res.list = str; res.total = total; return res; }
javascript
{ "resource": "" }
q11051
listify
train
function listify(fp, methods, ctx) { var len = methods.length, i = 0; var res = ['']; while (len--) { var method = methods[i++]; var line = ctx[method]; var item = line ? linkify('.' + method, fp, '#L' + line) : method; item = ' - ' + item; res.push(item); } return res.sort().join('\n'); }
javascript
{ "resource": "" }
q11052
tableize
train
function tableize(tableData) { var table = new Table({ head: Object.keys(tableData[0]), chars: {'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''}, style: { 'padding-left': 0, 'padding-right': 0 } }); _.each(tableData, function(row, index) { table.push(_.values(row)); }); return table; }
javascript
{ "resource": "" }
q11053
CreateSchemedProperty
train
function CreateSchemedProperty(object, scheme, schema_name, index) { if (object[schema_name]) return; Object.defineProperty(object, schema_name, { configurable: false, enumerable: true, get: function() { return this.getHook(schema_name, this.prop_array[index]); }, set: function(value) { let result = { valid: false }; let val = scheme.parse(value); scheme.verify(val, result); if (result.valid && this.prop_array[index] != val) { this.prop_array[index] = this.setHook(schema_name, val); this.scheduleUpdate(schema_name); this._changed_ = true; } } }); }
javascript
{ "resource": "" }
q11054
CreateModelProperty
train
function CreateModelProperty(object, model, schema_name, index) { Object.defineProperty(object, schema_name, { configurable: false, enumerable: true, get: function() { let m = this.prop_array[index]; if (!m) { let address = this.address.slice(); address.push(index); m = new model(null, this.root, address); m.par = this; m.prop_name = schema_name; m.MUTATION_ID = this.MUTATION_ID; this.prop_array[index] = m; } return this.getHook(schema_name, m); } }); }
javascript
{ "resource": "" }
q11055
train
function(node = this.fch) { if (node && node.nxt != this.fch && this.fch) return node.nxt; return null; }
javascript
{ "resource": "" }
q11056
train
function(index, node = this.fch) { if(node.par !== this) node = this.fch; let first = node; let i = 0; while (node && node != first) { if (i++ == index) return node; node = node.nxt; } return null; }
javascript
{ "resource": "" }
q11057
JSExpressionIdentifiers
train
function JSExpressionIdentifiers(lex) { let _identifiers_ = []; let model_cache = {}; let IN_OBJ = false, CAN_BE_ID = true; while (!lex.END) { switch (lex.ty) { case lex.types.id: if (!IN_OBJ || CAN_BE_ID) { let id = lex.tx; if (!model_cache[id]) { _identifiers_.push(lex.tx); model_cache[id] = true; } } break; case lex.types.op: case lex.types.sym: case lex.types.ob: case lex.types.cb: switch (lex.ch) { case "+": case ">": case "<": case "/": case "*": case "-": CAN_BE_ID = true; break; case "[": IN_OBJ = false; CAN_BE_ID = true; break; case "{": case ".": //Property Getters CAN_BE_ID = false; IN_OBJ = true; break; case "]": case ";": case "=": case "}": case "(": IN_OBJ = false; break; case ",": if (IN_OBJ) CAN_BE_ID = false; else IN_OBJ = false; break; case ":": case "=": CAN_BE_ID = true; } break; } lex.n; } return _identifiers_; }
javascript
{ "resource": "" }
q11058
TransformTo
train
function TransformTo(element_from, element_to, duration = 500, easing = Animation.easing.linear, HIDE_OTHER) { let rect = element_from.getBoundingClientRect(); let cs = window.getComputedStyle(element_from, null); let margin_left = parseFloat(cs.getPropertyValue("margin")); let seq = Animation.createSequence({ obj: element_from, width: { value: "0px"}, height: { value: "0px"}, backgroundColor: { value: "rgb(1,1,1)"}, left: [{value:rect.left+"px"},{ value: "0px"}], top: [{value:rect.top+"px"},{ value: "0px"}] }); if (!element_to) { let a = (seq) => (element_to, duration = 500, easing = Animation.easing.linear, HIDE_OTHER = false) => { setTo(element_to, seq, duration, easing); seq.duration = duration; return seq; }; return a(seq); } setTo(element_to, duration, easing); seq.duration = duration; return seq; }
javascript
{ "resource": "" }
q11059
CreateHTMLNode
train
function CreateHTMLNode(tag) { //jump table. switch (tag[0]) { case "w": switch (tag) { case "w-s": return new SourceNode$1(); //This node is used to case "w-c": return new SourceTemplateNode$1(); //This node is used to } break; default: switch (tag) { case "a": return new LinkNode$1(); /** void elements **/ case "template": return new VoidNode$1(); case "style": return new StyleNode$1(); case "script": return new ScriptNode$1(); case "svg": case "path": return new SVGNode(); } } return new RootNode(); }
javascript
{ "resource": "" }
q11060
CompileSource
train
function CompileSource(SourcePackage, presets, element, url, win = window) { let lex; if (element instanceof whind$1.constructor) { lex = element; } else if (typeof(element) == "string") lex = whind$1(element); else if (element instanceof EL) { if (element.tagName == "TEMPLATE") { let temp = document.createElement("div"); temp.appendChild(element.content); element = temp; } lex = whind$1(element.innerHTML); } else { let e = new Error("Cannot compile component"); SourcePackage._addError_(e); SourcePackage._complete_(); } return parseText(lex, SourcePackage, presets, url, win); }
javascript
{ "resource": "" }
q11061
parseCSSSelector
train
function parseCSSSelector(selector) { const match = SELECTOR_RE.exec(selector); if (!match) { throw new Error("Unsupported or invalid CSS selector: " + selector); } const res = { nodeName: match[1].trim() }; if (match[2]) { const attr = [match[2]]; if (match[3]) { attr.push(match[3]); } // Decode the attribute value if(match[4]) { attr.push(match[4].replace(/\\([nrtf"\\])/g, function(_, k) { return valueDecodeTable[k]; })); } res.attributes = [attr]; } return res; }
javascript
{ "resource": "" }
q11062
train
function(type, listener) { checkListener(listener); var events = this.$e; var listeners; if (events && (listeners = events[type])) { if (isFunction(listeners)) { if (listeners === listener) { delete events[type]; } } else { for (var i=listeners.length-1; i>=0; i--) { if (listeners[i] === listener) { listeners.splice(i, 1); } } } } return this; }
javascript
{ "resource": "" }
q11063
FindFreePortSync
train
function FindFreePortSync(options = {}) { this.defaultOptions = { // port start for scan start: 1, // port end for scan end: 65534, // ports number for scan num: 1, // specify ip for scan ip: '0.0.0.0|127.0.0.1', // for inner usage, some platforms like darkwin shows commom address 0.0.0.0:10000 as *.10000 _ipSpecial: '\\*|127.0.0.1', // scan this port port: null }; this.msg = { error: 'Cannot find free port' } this.adjustOptions(options); }
javascript
{ "resource": "" }
q11064
train
function(name, val, options) { debug('.generator', name, val); if (this.hasGenerator(name)) { return this.getGenerator(name); } this.setGenerator.apply(this, arguments); return this.getGenerator(name); }
javascript
{ "resource": "" }
q11065
train
function(name, val, options) { debug('.setGenerator', name); if (this.hasGenerator(name)) { return this.findGenerator(name); } // ensure local sub-generator paths are resolved if (typeof val === 'string' && val.charAt(0) === '.' && this.env) { val = path.resolve(this.env.dirname, val); } return generator(name, val, options, this); }
javascript
{ "resource": "" }
q11066
fn
train
function fn(name, options) { debug('.findGenerator', name); if (utils.isObject(name)) { return name; } if (Array.isArray(name)) { name = name.join('.'); } if (typeof name !== 'string') { throw new TypeError('expected name to be a string'); } if (cache.hasOwnProperty(name)) { return cache[name]; } var app = this.generators[name] || this.base.generators[name] || this._findGenerator(name, options); // if no app, check the `base` instance if (typeof app === 'undefined' && this.hasOwnProperty('parent')) { app = this.base._findGenerator(name, options); } if (app) { cache[app.name] = app; cache[app.alias] = app; cache[name] = app; return app; } var search = {name, options}; this.base.emit('unresolved', search, this); if (search.app) { cache[search.app.name] = search.app; cache[search.app.alias] = search.app; return search.app; } cache[name] = null; }
javascript
{ "resource": "" }
q11067
train
function(name, options) { if (this.generators.hasOwnProperty(name)) { return this.generators[name]; } if (~name.indexOf('.')) { return this.getSubGenerator.apply(this, arguments); } var opts = utils.extend({}, this.options, options); if (typeof opts.lookup === 'function') { var app = this.lookupGenerator(name, opts, opts.lookup); if (app) { return app; } } return this.matchGenerator(name); }
javascript
{ "resource": "" }
q11068
train
function(name, options) { debug('.getSubGenerator', name); var segs = name.split('.'); var len = segs.length; var idx = -1; var app = this; while (++idx < len) { var key = segs[idx]; app = app.getGenerator(key, options); if (!app) { break; } } return app; }
javascript
{ "resource": "" }
q11069
train
function(name, options, fn) { debug('.lookupGenerator', name); if (typeof options === 'function') { fn = options; options = {}; } if (typeof fn !== 'function') { throw new TypeError('expected `fn` to be a lookup function'); } options = options || {}; // remove `lookup` fn from options to prevent self-recursion delete this.options.lookup; delete options.lookup; var names = fn(name); debug('looking up generator "%s" with "%j"', name, names); var len = names.length; var idx = -1; while (++idx < len) { var gen = this.findGenerator(names[idx], options); if (gen) { this.options.lookup = fn; return gen; } } this.options.lookup = fn; }
javascript
{ "resource": "" }
q11070
train
function(name, options) { if (typeof name === 'function') { this.use(name, options); return this; } if (Array.isArray(name)) { var len = name.length; var idx = -1; while (++idx < len) { this.extendWith(name[idx], options); } return this; } var app = name; if (typeof name === 'string') { app = this.generators[name] || this.findGenerator(name, options); if (!app && utils.exists(name)) { var fn = utils.tryRequire(name, this.cwd); if (typeof fn === 'function') { app = this.register(name, fn); } } } if (!utils.isValidInstance(app)) { throw new Error('cannot find generator: "' + name + '"'); } var alias = app.env ? app.env.alias : 'default'; debug('extending "%s" with "%s"', alias, name); app.run(this); app.invoke(options, this); return this; }
javascript
{ "resource": "" }
q11071
train
function(name, options) { if (typeof options === 'function') { return options(name); } if (options && typeof options.toAlias === 'function') { return options.toAlias(name); } if (typeof app.options.toAlias === 'function') { return app.options.toAlias(name); } return name; }
javascript
{ "resource": "" }
q11072
map
train
function map() { var cache = {}; if (!cache.extensions) cache.extensions = require('./lib/exts.json'); if (!cache.languages) cache.languages = require('./lib/lang.json'); return cache; }
javascript
{ "resource": "" }
q11073
isUrl
train
function isUrl(url, error) { if (!Assertions.urlPattern.test(url)) { if (error) { throw new Error("Given url is not valid ! URL :" + url); } return false; } return true; }
javascript
{ "resource": "" }
q11074
isReactComponent
train
function isReactComponent(instance, error) { /* disable-eslint no-underscore-dangle */ if (!(instance && instance.$$typeof)) { if (error) { throw new Error("Given component is not a react component ! Component :" + instance); } return false; } return true; }
javascript
{ "resource": "" }
q11075
extractVerticalComponent
train
function extractVerticalComponent(accelerometerData, attitudeData) { var res=[]; var rm; for (var i=0;i<accelerometerData.length;i++){ rm=new Matrix(module.exports.composeRotation(attitudeData[i][0],attitudeData[i][1],0)); res[i]=new Matrix([accelerometerData[i][0],accelerometerData[i][1],accelerometerData[i][2]]).dot(rm).data[0][2]; } return res; }
javascript
{ "resource": "" }
q11076
Filter
train
function Filter(options) { this.options = options || {}; for (var group in operators) { var prop = group.toLowerCase(); this[prop] = this.mask(group, this.options[prop]); } }
javascript
{ "resource": "" }
q11077
errorPage
train
function errorPage(res, err) { if (err) { console.error(err.message); res.send(err, {'Content-Type': 'text/plain'}, 500); } else { res.send(404); } }
javascript
{ "resource": "" }
q11078
compileAndRender
train
function compileAndRender(templatePath, content, callback) { if (templatePath in templates) { return callback(null, templates[templatePath].render(content)); } fs.readFile(templatePath, 'utf8', function(err, template) { if (err) { return callback(err) } templates[templatePath] = hogan.compile(template); callback(null, templates[templatePath].render(content)); }) }
javascript
{ "resource": "" }
q11079
search
train
function search(searched, callback) { var root = pathUtils.resolve(options.root); // search command is platform dependant: use grep on linux, and findstr on windaube. var command = os.platform() === 'win32' ? 'findstr /spin /c:"'+searched+'" '+ pathUtils.join(root, '*.*') : 'grep -rin "'+searched+'" '+root; // exec the command line. exec(command, function (err, stdout, stderr) { if (err) { // a 1 error code means no results. if (err.code === 1) { err = null; } return callback(err, []); } // each line an occurence. var lines = stdout.toString().split(root); // remove files that are not markdown. lines = _.filter(lines, function(val) { return val.trim().length > 0; }); // regroups by files var grouped = {}; for(var i = 0; i < lines.length; i++) { var numStart = lines[i].indexOf(':'); var numEnd = lines[i].indexOf(':', numStart+1); // remove leading \ var fileName = lines[i].substring(1, numStart); // ignore assets files if (/^_assets/.test(fileName)) { continue } if (!(fileName in grouped)) { grouped[fileName] = []; } grouped[fileName].push({hit:lines[i].substring(numEnd+1).replace(new RegExp(searched, 'gi'), '<b>$&</b>')}); } // sort by relevance var files = []; for(var key in grouped) { files.push({ path: key, hits: grouped[key] }); } callback(null, files.sort(function(a, b) { return b.hits.length - a.hits.length; })); }); }
javascript
{ "resource": "" }
q11080
train
function(aggregate, vm, callback) { if(aggregate.get('destroyed')) { var reason = { name: 'AggregateDestroyed', message: 'Aggregate has already been destroyed!', aggregateRevision: aggregate.get('revision'), aggregateId: aggregate.id }; return callback(reason); } callback(null, aggregate, vm); }
javascript
{ "resource": "" }
q11081
train
function(aggregate, vm, callback) { self.validate(cmd.command, cmd.payload, function(err) { callback(err, aggregate, vm); }); }
javascript
{ "resource": "" }
q11082
train
function(aggregate, vm, callback) { aggregate[cmd.command](cmd.payload, function(err) { callback(err, aggregate, vm); }); }
javascript
{ "resource": "" }
q11083
train
function(aggregate, vm, callback) { vm.set(aggregate.toJSON()); self.commit(vm, function(err) { callback(err, aggregate, cmd); }); }
javascript
{ "resource": "" }
q11084
acceptMatcher
train
function acceptMatcher(acc, actual) { /* Exact match or full wildcard match on both type and subtype */ if (actual.contentType === acc.item || acc.item === '*/*') return true; /* Otherwise check for "*" wildcard matches */ const a = acc.item.split(MIME_SUBTYPE_SEPARATOR); const accepted = { type: a[0], subtype: a[1], }; /* Exact match type, wildcard subtype */ if (actual.type === accepted.type && accepted.subtype === '*') { return true; } /* Wildcard type, exact match subtype */ if (accepted.type === '*' && accepted.subtype === actual.subtype) { return true; } }
javascript
{ "resource": "" }
q11085
train
function (property) { var isString; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { return this[property]; } // avoid split if possible var chain = isString ? property.split(".") : property, currentValue = this, currentProperty; // go through all the properties for (var i = 0, n = chain.length - 1; i < n; i++) { currentValue = currentValue[chain[i]]; if (!currentValue) return; } // might be a bindable object if(currentValue) return currentValue[chain[i]]; }
javascript
{ "resource": "" }
q11086
train
function (property, value) { var isString, hasChanged, oldValue, chain; // optimal if ((isString = (typeof property === "string")) && !~property.indexOf(".")) { hasChanged = (oldValue = this[property]) !== value; if (hasChanged) this[property] = value; } else { // avoid split if possible chain = isString ? property.split(".") : property; var currentValue = this, previousValue, currentProperty, newChain; for (var i = 0, n = chain.length - 1; i < n; i++) { currentProperty = chain[i]; previousValue = currentValue; currentValue = currentValue[currentProperty]; // need to take into account functions - easier not to check // if value exists if (!currentValue /* || (typeof currentValue !== "object")*/) { currentValue = previousValue[currentProperty] = {}; } // is the previous value bindable? pass it on if (currentValue.__isBindable) { newChain = chain.slice(i + 1); // check if the value has changed hasChanged = (oldValue = currentValue.get(newChain)) !== value; currentValue.set(newChain, value); currentValue = oldValue; break; } } if (!newChain && (hasChanged = (currentValue !== value))) { currentProperty = chain[i]; oldValue = currentValue[currentProperty]; currentValue[currentProperty] = value; } } if (!hasChanged) return value; var prop = chain ? chain.join(".") : property; this.emit("change:" + prop, value, oldValue); this.emit("change", prop, value, oldValue); return value; }
javascript
{ "resource": "" }
q11087
train
function () { var obj = {}, value; var keys = Object.keys(this); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; if (key.substr(0, 2) === "__") continue; value = this[key]; if(value && value.__isBindable) { value = value.toJSON(); } obj[key] = value; } return obj; }
javascript
{ "resource": "" }
q11088
cast
train
function cast(data, EntityClass) { // Check if/how EntityClass is defined or implied if (!EntityClass && !_lodash2.default.isArray(data)) { // No explicit class definition, casting data not array return _dataManagement2.default.cast(data, this); } else if (!EntityClass && _lodash2.default.isArray(data)) { // No explicit class definition, casting data is array return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isArray(EntityClass) && EntityClass.length === 0) { // Explicit class definition as array with implicit members return _dataManagement2.default.cast(data, [this]); } else if (_lodash2.default.isObject(EntityClass) && !_lodash2.default.isFunction(EntityClass) && _lodash2.default.values(EntityClass).length === 0) { // Explicit class definition as hashmap with implicit members return _dataManagement2.default.cast(data, _defineProperty({}, this.name, this)); } else { // Explicit class definition return _dataManagement2.default.cast(data, EntityClass); } }
javascript
{ "resource": "" }
q11089
getClassExtensions
train
function getClassExtensions(classes) { // Extract property definitions from all inherited classes' static ".props" property var extensions = _lodash2.default.reduceRight(classes, function (extensions, current) { var extensionsArray = current.includes ? _lodash2.default.isArray(current.includes) ? current.includes : [current.includes] : []; _lodash2.default.forEach(extensionsArray, function (extension) { extensions.push(extension); }); return extensions; }, []); // Return extracted properties return extensions; }
javascript
{ "resource": "" }
q11090
getClassProperties
train
function getClassProperties(classes) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, extensionsManager = _ref.extensionsManager; // Define checks for shorthand casting configurations var isPropertyShorthandCastAsSingleEntity = function isPropertyShorthandCastAsSingleEntity(propertyConfiguration) { if (propertyConfiguration // Check if class extending EnTT && propertyConfiguration.prototype instanceof EnTT) { return propertyConfiguration; } }; var isPropertyShorthandCastAsEntityArray = function isPropertyShorthandCastAsEntityArray(propertyConfiguration) { if (propertyConfiguration // Check if array && _lodash2.default.isArray(propertyConfiguration) // Check if array has a single member && propertyConfiguration.length === 1 // Check if single array memeber is a class extending EnTT && propertyConfiguration[0].prototype instanceof EnTT) { return propertyConfiguration[0]; } }; var isPropertyShorthandCastAsEntityHashmap = function isPropertyShorthandCastAsEntityHashmap(propertyConfiguration) { if (propertyConfiguration // Check if object && _lodash2.default.isObject(propertyConfiguration) // Check if object has a single member && _lodash2.default.values(propertyConfiguration).length // Check if single object member is a class extending EnTT && _lodash2.default.values(propertyConfiguration)[0].prototype instanceof EnTT // Check if single object member's property key equals class name && _lodash2.default.keys(propertyConfiguration)[0] === _lodash2.default.values(propertyConfiguration)[0].name) { return _lodash2.default.values(propertyConfiguration)[0]; } }; // Extract property definitions from all inherited classes' static ".props" property var properties = _lodash2.default.reduceRight(classes, function (properties, current) { // Extract currentProperties var currentProperties = current.props, CastClass = void 0; // Edit short-hand configuration syntax where possible _lodash2.default.forEach(currentProperties, function (propertyConfiguration, propertyName) { // Replace "casting properties" short-hand configuration syntax for single entity CastClass = isPropertyShorthandCastAsSingleEntity(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-single-entity syntax currentProperties[propertyName] = { cast: propertyConfiguration }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityArray(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-array syntax currentProperties[propertyName] = { cast: [CastClass] }; return; } // Replace "casting properties" short-hand configuration syntax for entity array CastClass = isPropertyShorthandCastAsEntityHashmap(propertyConfiguration); if (CastClass) { // Replace shorthand cast-as-entity-hashmap syntax currentProperties[propertyName] = { cast: _defineProperty({}, new CastClass().constructor.name, CastClass) }; return; } // EXTENSIONS HOOK: .processShorthandPropertyConfiguration(...) // Lets extensions process short-hand property configuration currentProperties[propertyName] = extensionsManager.processShorthandPropertyConfiguration(propertyConfiguration); }); // Merge with existing properties return _lodash2.default.merge(properties, currentProperties || {}); }, {}); // Update property configuration with default configuration values _lodash2.default.forEach(properties, function (propertyConfiguration, key) { properties[key] = _lodash2.default.merge({}, EnTT.default, propertyConfiguration); }); // Return extracted properties return properties; }
javascript
{ "resource": "" }
q11091
train
function ( settings, opts ) { // Sanity check that we are using DataTables 1.10 or newer if ( ! DataTable.versionCheck || ! DataTable.versionCheck( '1.10.1' ) ) { throw 'DataTables Responsive requires DataTables 1.10.1 or newer'; } this.s = { dt: new DataTable.Api( settings ), columns: [] }; // Check if responsive has already been initialised on this table if ( this.s.dt.settings()[0].responsive ) { return; } // details is an object, but for simplicity the user can give it as a string if ( opts && typeof opts.details === 'string' ) { opts.details = { type: opts.details }; } this.c = $.extend( true, {}, Responsive.defaults, DataTable.defaults.responsive, opts ); settings.responsive = this; this._constructor(); }
javascript
{ "resource": "" }
q11092
train
function ( colIdx, name ) { var includeIn = columns[ colIdx ].includeIn; if ( $.inArray( name, includeIn ) === -1 ) { includeIn.push( name ); } }
javascript
{ "resource": "" }
q11093
train
function () { var that = this; var dt = this.s.dt; var details = this.c.details; // The inline type always uses the first child as the target if ( details.type === 'inline' ) { details.target = 'td:first-child'; } // type.target can be a string jQuery selector or a column index var target = details.target; var selector = typeof target === 'string' ? target : 'td'; // Click handler to show / hide the details rows when they are available $( dt.table().body() ).on( 'click', selector, function (e) { // If the table is not collapsed (i.e. there is no hidden columns) // then take no action if ( ! $(dt.table().node()).hasClass('collapsed' ) ) { return; } // Check that the row is actually a DataTable's controlled node if ( ! dt.row( $(this).closest('tr') ).length ) { return; } // For column index, we determine if we should act or not in the // handler - otherwise it is already okay if ( typeof target === 'number' ) { var targetIdx = target < 0 ? dt.columns().eq(0).length + target : target; if ( dt.cell( this ).index().column !== targetIdx ) { return; } } // $().closest() includes itself in its check var row = dt.row( $(this).closest('tr') ); if ( row.child.isShown() ) { row.child( false ); $( row.node() ).removeClass( 'parent' ); } else { var info = that.c.details.renderer( dt, row[0] ); row.child( info, 'child' ).show(); $( row.node() ).addClass( 'parent' ); } } ); }
javascript
{ "resource": "" }
q11094
train
function () { var that = this; var dt = this.s.dt; // Find how many columns are hidden var hiddenColumns = dt.columns().indexes().filter( function ( idx ) { var col = dt.column( idx ); if ( col.visible() ) { return null; } // Only counts as hidden if it doesn't have the `never` class return $( col.header() ).hasClass( 'never' ) ? null : idx; } ); var haveHidden = true; if ( hiddenColumns.length === 0 || ( hiddenColumns.length === 1 && this.s.columns[ hiddenColumns[0] ].control ) ) { haveHidden = false; } if ( haveHidden ) { // Show all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { var row = dt.row( idx ); if ( row.child() ) { var info = that.c.details.renderer( dt, row[0] ); // The renderer can return false to have no child row if ( info === false ) { row.child.hide(); } else { row.child( info, 'child' ).show(); } } } ); } else { // Hide all existing child rows dt.rows( { page: 'current' } ).eq(0).each( function (idx) { dt.row( idx ).child.hide(); } ); } }
javascript
{ "resource": "" }
q11095
train
function ( name ) { var breakpoints = this.c.breakpoints; for ( var i=0, ien=breakpoints.length ; i<ien ; i++ ) { if ( breakpoints[i].name === name ) { return breakpoints[i]; } } }
javascript
{ "resource": "" }
q11096
train
function () { var dt = this.s.dt; var width = $(window).width(); var breakpoints = this.c.breakpoints; var breakpoint = breakpoints[0].name; var columns = this.s.columns; var i, ien; // Determine what breakpoint we are currently at for ( i=breakpoints.length-1 ; i>=0 ; i-- ) { if ( width <= breakpoints[i].width ) { breakpoint = breakpoints[i].name; break; } } // Show the columns for that break point var columnsVis = this._columnsVisiblity( breakpoint ); // Set the class before the column visibility is changed so event // listeners know what the state is. Need to determine if there are // any columns that are not visible but can be shown var collapsedClass = false; for ( i=0, ien=columns.length ; i<ien ; i++ ) { if ( columnsVis[i] === false && ! columns[i].never ) { collapsedClass = true; break; } } $( dt.table().node() ).toggleClass('collapsed', collapsedClass ); dt.columns().eq(0).each( function ( colIdx, i ) { dt.column( colIdx ).visible( columnsVis[i] ); } ); }
javascript
{ "resource": "" }
q11097
train
function () { var dt = this.s.dt; var columns = this.s.columns; // Are we allowed to do auto sizing? if ( ! this.c.auto ) { return; } // Are there any columns that actually need auto-sizing, or do they all // have classes defined if ( $.inArray( true, $.map( columns, function (c) { return c.auto; } ) ) === -1 ) { return; } // Clone the table with the current data in it var tableWidth = dt.table().node().offsetWidth; var columnWidths = dt.columns; var clonedTable = dt.table().node().cloneNode( false ); var clonedHeader = $( dt.table().header().cloneNode( false ) ).appendTo( clonedTable ); var clonedBody = $( dt.table().body().cloneNode( false ) ).appendTo( clonedTable ); $( dt.table().footer() ).clone( false ).appendTo( clonedTable ); // This is a bit slow, but we need to get a clone of each row that // includes all columns. As such, try to do this as little as possible. dt.rows( { page: 'current' } ).indexes().flatten().each( function ( idx ) { var clone = dt.row( idx ).node().cloneNode( true ); if ( dt.columns( ':hidden' ).flatten().length ) { $(clone).append( dt.cells( idx, ':hidden' ).nodes().to$().clone() ); } $(clone).appendTo( clonedBody ); } ); var cells = dt.columns().header().to$().clone( false ); $('<tr/>') .append( cells ) .appendTo( clonedHeader ); // In the inline case extra padding is applied to the first column to // give space for the show / hide icon. We need to use this in the // calculation if ( this.c.details.type === 'inline' ) { $(clonedTable).addClass( 'dtr-inline collapsed' ); } var inserted = $('<div/>') .css( { width: 1, height: 1, overflow: 'hidden' } ) .append( clonedTable ); // Remove columns which are not to be included inserted.find('th.never, td.never').remove(); inserted.insertBefore( dt.table().node() ); // The cloned header now contains the smallest that each column can be dt.columns().eq(0).each( function ( idx ) { columns[idx].minWidth = cells[ idx ].offsetWidth || 0; } ); inserted.remove(); }
javascript
{ "resource": "" }
q11098
Content
train
function Content(mimeType, content) { var obj = {}; obj.type = mimeType + '; charset=utf-8'; obj.value = content; obj.length = content.length; return obj; }
javascript
{ "resource": "" }
q11099
train
function(cmdPointer, next) { // Publish it now... commandDispatcher.dispatch(cmdPointer.command, function(err) { if (cmdPointer.callback) cmdPointer.callback(null); next(); }); }
javascript
{ "resource": "" }