_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q60800
atomSerialize
validation
function atomSerialize () { var options = {isUnloading: true} if (atom.serialize != null) return atom.serialize(options) // Atom <= 1.6 return { version: atom.constructor.version, project: atom.project.serialize(options), workspace: atom.workspace.serialize(), packageStates: packageStatesSerialize(), grammars: {grammarOverridesByPath: atom.grammars.grammarOverridesByPath}, fullScreen: atom.isFullScreen(), windowDimensions: atom.windowDimensions } }
javascript
{ "resource": "" }
q60801
splitUnique
validation
function splitUnique (string) { string = string && string.trim(); if (string) { return unique(string.split(/\s+/)); } else { return undefined; } }
javascript
{ "resource": "" }
q60802
walkNodes
validation
function walkNodes ($nodes, currentItem) { $nodes.each(function (i, node) { var $node = $(node); var props = splitUnique($node.attr('itemprop')); if (props && currentItem) { var value = null; if ($node.is('[itemscope]')) { value = parseItem(node, currentItem); } else { value = parsePropertyValue(node); walkNodes($node.children(), currentItem); } currentItem.addProperties(props, value); } else if ($node.is('[itemscope]') && !$node.is('[itemprop]')) { var newItem = parseItem(node, currentItem); if (newItem !== Item.ERROR) { items.push(newItem); } } else { walkNodes($node.children(), currentItem); } }); }
javascript
{ "resource": "" }
q60803
parseItem
validation
function parseItem (node, currentItem) { // REMARK: note the raw dom node instead of $node to guarantee uniqueness if (currentItem && currentItem.hasMemoryOf(node)) { return Item.ERROR; } var $node = $(node); var type = splitUnique($node.attr('itemtype')); type = type && type.filter(isAbsoluteUrl); var item = new Item({ type: type, id: $node.attr('itemid'), node: node, parent: currentItem }); walkNodes($node.children(), item); // visit all nodes referenced by the current one var refs = splitUnique($node.attr('itemref')); if (refs) { var refsSelector = refs .map(function makeIdSelector (id) { return '#' + id; }) .join(','); walkNodes($(refsSelector), item); } return item; }
javascript
{ "resource": "" }
q60804
resolveUrlAttribute
validation
function resolveUrlAttribute ($node, attr) { var url = $node.attr(attr); if (url === undefined) return ''; if (isAbsoluteUrl(url)) { return url; } else { return urlUtil.resolve(base, url); } }
javascript
{ "resource": "" }
q60805
parsePropertyValue
validation
function parsePropertyValue (node) { var $node = $(node); if ($node.is('meta')) { return resolveAttribute($node, 'content'); } else if ($node.is('audio,embed,iframe,img,source,track,video')) { return resolveUrlAttribute($node, 'src'); } else if ($node.is('a,area,link')) { return resolveUrlAttribute($node, 'href'); } else if ($node.is('object')) { return resolveUrlAttribute($node, 'data'); } else if ($node.is('data,meter')) { return resolveAttribute($node, 'value'); } else if ($node.is('time')) { return resolveAttribute($node, 'datetime'); } else { var text = $node.text(); return text || ''; } }
javascript
{ "resource": "" }
q60806
processPatterns
validation
function processPatterns(patterns, fn) { // Filepaths to return. var result = []; // Iterate over flattened patterns array. _.flattenDeep(patterns).forEach(function(pattern) { // If the first character is ! it should be omitted var exclusion = pattern.indexOf('!') === 0; // If the pattern is an exclusion, remove the ! if (exclusion) { pattern = pattern.slice(1); } // Find all matching files for this pattern. var matches = fn(pattern); if (exclusion) { // If an exclusion, remove matching files. result = _.difference(result, matches); } else { // Otherwise add matching files. result = _.union(result, matches); } }); return result; }
javascript
{ "resource": "" }
q60807
sendMessage
validation
function sendMessage( args ){ last = new Date(); fs.write( tmpfile, JSON.stringify( args ) + '\n', 'a' ); // Exit when all done. if( /^done/.test( args[0] ) ){ phantom.exit(); } }
javascript
{ "resource": "" }
q60808
validation
function( url ){ grunt.verbose.write( 'Running PhantomJS...' ).or.write( '...' ); grunt.log.error(); grunt.warn( 'PhantomJS unable to load "' + url + '" URI.', 90 ); }
javascript
{ "resource": "" }
q60809
F
validation
function F(type, term) { let original = term; if (term && !term.__meta) { term = type.wrap ? type.wrap(term) : term; term.__meta = {}; term.__name = function(name) { term.__meta.name = name; return term; }; term.__desc = function(desc) { term.__meta.desc = desc; return term; }; if (term.__meta) { term.__meta.term = original; term.__meta.name = "anon"; term.__meta.desc = "no description"; }; }; F.check(type, term); return term; }
javascript
{ "resource": "" }
q60810
validation
function (json, delimiter) { var result = []; var recurse = function (cur, prop) { for (var key in cur) { if (cur.hasOwnProperty(key)) { var item = cur[key]; result.push({ match: prop ? prop + delimiter + key : key, replacement: item, expression: false }); // deep scan if (typeof item === 'object') { recurse(item, prop ? prop + delimiter + key : key); } } } }; recurse(json); return result; }
javascript
{ "resource": "" }
q60811
ld
validation
function ld(date, long = true, options = null) { return Localizer.Singleton.formatDate(date, long, options) }
javascript
{ "resource": "" }
q60812
ldt
validation
function ldt(date, long = true, options = null) { return Localizer.Singleton.formatDateTime(date, long, options) }
javascript
{ "resource": "" }
q60813
getStyle
validation
function getStyle (element, property) { if (window.getComputedStyle) { return getStyleProperty(element, property).original; } else if (element.currentStyle) { return element.currentStyle[property]; } return null; }
javascript
{ "resource": "" }
q60814
hasChanged
validation
function hasChanged(newData, oldData) { var changed = false for (var i = 0; i < scope.length; i++) { var k = scope[i], newVal = _.get(newData, k), oldVal = _.get(oldData, k) if (!_.isEqual(newVal, oldVal)) { changed = true break } } return changed }
javascript
{ "resource": "" }
q60815
validation
function(initValues, element, notCreate) { if (element === undefined) { if (notCreate) { item.values(initValues, notCreate); } else { item.values(initValues); } } else { item.elm = element; var values = templater.get(item, initValues); item.values(values); } }
javascript
{ "resource": "" }
q60816
checkUrl
validation
function checkUrl(url, method, routes){ method=method.toLowerCase(); for (var i=0; i<routes.length; i++){ var route=routes[i]; if ((matchPath(route.url,url)) && (method==route.method)) return route; } return false; }
javascript
{ "resource": "" }
q60817
eatBraces
validation
function eatBraces(stream, root) { if (stream.eat(LBRACE)) { let stack = 1, token; while (!stream.eof()) { if (stream.eat(RBRACE)) { stack--; if (!stack) { break; } } else if (stream.eat(LBRACE)) { stack++; } else if (eatUrl(stream) || eatString(stream)) { continue; } else if (token = comment(stream)) { root.addComment(token); continue; } else { stream.next(); } } return true; } return false; }
javascript
{ "resource": "" }
q60818
underscore
validation
function underscore(baseQuery) { return _.mapKeys(baseQuery, function(v, k) { return tableColumnRenamer.underscore(k) }) }
javascript
{ "resource": "" }
q60819
filterQueryParams
validation
function filterQueryParams (baseClause, request) { _.forEach(request.query, function(v, k) { addWhereClause(baseClause, k, v) }) return baseClause }
javascript
{ "resource": "" }
q60820
addWhereClause
validation
function addWhereClause(baseClause, k, v) { if (v.startsWith('>')) { baseClause.where(k, '>=', v.substring(1)); return } if (v.startsWith('<')) { baseClause.where(k, '<=', v.substring(1)); return } if (v.startsWith('~')) { baseClause.where(k, 'LIKE', v.substring(1)); return } if (k.endsWith('Id')) { baseClause.where(k.substring(0, k.length - 2) + '_id', '=', v); return } baseClause.where(k, '=', v); return }
javascript
{ "resource": "" }
q60821
findByIdQueryParams
validation
function findByIdQueryParams (request, config) { return typeof config.baseQuery === 'undefined' ? {'id': request.params.id} : _.merge({'id': request.params.id}, underscore(config.baseQuery(request))) }
javascript
{ "resource": "" }
q60822
empty
validation
function empty (entity, schema, Empty) { if (typeof entity === 'undefined' || entity === null) { return } _.forEach(schema, function(v, k) { if (v === Empty) { delete entity[k] } }) }
javascript
{ "resource": "" }
q60823
initModel
validation
function initModel (config) { if (typeof config.bookshelfModel.prototype.schema === 'undefined') { config.bookshelfModel.prototype.schema = {} } addConstraintsForForeignKeys(config.bookshelfModel, config.baseQuery) config.bookshelfModel.prototype.format = tableColumnRenamer.renameOnFormat config.bookshelfModel.prototype.parse = tableColumnRenamer.renameOnParse initJsonDateFormat(config.bookshelfModel) }
javascript
{ "resource": "" }
q60824
initJsonDateFormat
validation
function initJsonDateFormat (bookshelfModel) { const schema = bookshelfModel.prototype.schema const originalFunction = bookshelfModel.prototype.toJSON // read from MySQL date, based on https://github.com/tgriesser/bookshelf/issues/246#issuecomment-35498066 bookshelfModel.prototype.toJSON = function () { const attrs = originalFunction.apply(this, arguments) _.forEach(attrs, function(v, k) { if (v !== null && typeof schema[k] !== 'undefined' && schema[k]._type === 'date') { attrs[k] = moment(v).format(schema[k]._flags.format) } }) return attrs } }
javascript
{ "resource": "" }
q60825
formatNumber
validation
function formatNumber (payload, schema) { _.forEach(schema, function(v, k) { if (v !== null && v._type === 'number') { if (typeof payload[k] === 'undefined' || payload[k] === null) { payload[k] = 0 } } }) }
javascript
{ "resource": "" }
q60826
formatDate
validation
function formatDate (payload, schema) { _.forEach(schema, function(v, k) { if (v !== null && v._type === 'date') { if (payload[k] !== null) { payload[k] = new Date(payload[k]) } } }) }
javascript
{ "resource": "" }
q60827
setForeignKeys
validation
function setForeignKeys (request, baseQuery) { if (typeof baseQuery === 'undefined') { return } _.forEach(baseQuery(request), function(v, k) { request.payload[k] = request.params[k] }) }
javascript
{ "resource": "" }
q60828
transformConstraintViolationMessages
validation
function transformConstraintViolationMessages (input) { return { validationErrors: _.chain(input.details) .mapKeys(function(v, k) { // Use '.' as the key if the entire object is erroneous return (input.details.length == 1 && input.details[0].path === 'value' && input.details[0].type === 'object.base') ? '.' : v.path }) .mapValues(function (v) { return { attributes: _.chain(v.context) .pickBy(function(v, k) { return typeof v !== 'undefined' && v !== null && k !== 'key' }) .mapValues(function(i) { return i.toString() }), constraintClassName: v.type, invalidValue: v.context.value, messageTemplate: v.type, } }) } }
javascript
{ "resource": "" }
q60829
lazyConsForce
validation
function lazyConsForce() { /* jshint validthis:true */ var val = this.tailFn(); /* eslint-disable no-use-before-define */ this.tailValue = Array.isArray(val) ? fromArray(val) : val; /* eslint-enable no-use-before-define */ delete this.tail; delete this.force; return this; }
javascript
{ "resource": "" }
q60830
isEmptyTag
validation
function isEmptyTag(node) { if(node.constructor === Element && !node.hasChildNodes()) return true return Boolean(EMPTY_TAG_SET[node.tagName]) }
javascript
{ "resource": "" }
q60831
LogWatcher
validation
function LogWatcher(dirpath, maxfiles, ignoreInitial) { _classCallCheck(this, LogWatcher); var _this = _possibleConstructorReturn(this, (LogWatcher.__proto__ || Object.getPrototypeOf(LogWatcher)).call(this)); _this._dirpath = dirpath || DEFAULT_SAVE_DIR; _this._filter = isCommanderLog; _this._maxfiles = maxfiles || 3; _this._logDetailMap = {}; _this._ops = []; _this._op = null; _this._startTime = new Date(); _this._timer = null; _this._die = false; _this._ignoreInitial = ignoreInitial || false; _this.stopped = false; _this._loop(); _this.emit('Started'); return _this; }
javascript
{ "resource": "" }
q60832
loadImage
validation
function loadImage(image) { $scope.$applyAsync(function () { if ($scope.reversed) $scope.flipContext(); $scope.signatureReady = true; ctxBackground.clearRect(0, 0, canvas.width, canvas.height); ctxBackground.drawImage(image, 0, 0, canvasBackground.width, canvasBackground.height); }); }
javascript
{ "resource": "" }
q60833
validation
function() { if(this.read) { // 1. parse value this.computed_observable = new Observer(this.createFunction("return ("+this.value+");", ["m", "p"], [this.context.model, this.context.parent], this.context.domElement), { /* for debugging only */ domElement: this.context.domElement, attribute: this.name, value: this.value }); // 2. add subscribers this.read_binded = this.read.bind(this); this.computed_observable.subscribe(this.read_binded); // 3. initial element update this.read(this.computed_observable.currentValue); } if(this.event) { this.event(this.createEventFunction()); } /*if(registeredAttributes[i].event) { // It is a data handler's job this.event(name, eventFunctionFactory(value, context), context); }*/ }
javascript
{ "resource": "" }
q60834
validation
function(functionBody, argNames, argValues, context) { // store context var functionArgs = argNames.concat(functionBody); var fn = Function.apply(null, functionArgs); // return function return function() { // mix predefined arguments with passed var args = argValues.concat(Array.prototype.slice.call(arguments)); return fn.apply(context, args); } }
javascript
{ "resource": "" }
q60835
validation
function( expected, actual, optionsOrMsg ) { var options = optionsOrMsg instanceof Object ? optionsOrMsg : { message: optionsOrMsg }, msg = options.message, compatHtml = bender.tools && bender.tools.compatHtml; if ( !options.skipCompatHtml ) { var sortAttributes = ( 'sortAttributes' in options ) ? options.sortAttributes : true, fixZWS = ( 'fixZWS' in options ) ? options.fixZWS : true, fixNbsp = ( 'fixNbsp' in options ) ? options.fixNbsp : true; if ( !compatHtml ) { throw new Error( 'Missing bender.tools.compatHtml' ); } expected = compatHtml( expected, options.noInterWS, sortAttributes, fixZWS, options.fixStyles, fixNbsp, options.noTempElements, options.customFilters ); actual = compatHtml( actual, options.noInterWS, sortAttributes, fixZWS, options.fixStyles, fixNbsp, options.noTempElements, options.customFilters ); } bender.assert.areSame( html_beautify( expected, this._config ), html_beautify( actual, this._config ), msg ); }
javascript
{ "resource": "" }
q60836
validation
function( expected, actual, msg ) { bender.assert.areSame( js_beautify( expected, this._config ), js_beautify( actual, this._config ), msg ); }
javascript
{ "resource": "" }
q60837
validation
function( expected, actual, msg ) { var assert = bender.assert; assert.isTypeOf( 'object', expected, 'Expected is not an object' ); assert.isTypeOf( 'object', actual, 'Actual is not an object' ); // Simply convert to JSON strings for a good diff in case of fails. expected = JSON.stringify( objectHelpers.sortObjectProperties( expected ) ); actual = JSON.stringify( objectHelpers.sortObjectProperties( actual ) ); this.js( expected, actual, msg ); }
javascript
{ "resource": "" }
q60838
checkIfShouldStick
validation
function checkIfShouldStick() { if (mediaQuery && !matchMedia('(' + mediaQuery + ')').matches) return; var scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var shouldStick = scrollTop >= stickyLine; // Switch the sticky modes if the element has crossed the sticky line if (shouldStick && !isSticking) stickElement();else if (!shouldStick && isSticking) unstickElement(); }
javascript
{ "resource": "" }
q60839
buildServicesInternal
validation
function buildServicesInternal() { if (_.isFunction(subdivision.buildServices)) { subdivision.vent.trigger('before:buildServices'); return subdivision.buildServices().then(function () { subdivision.vent.trigger('after:buildServices'); }); } else { return Promise.resolve(); } }
javascript
{ "resource": "" }
q60840
validation
function(path) { var node = this.$getNode(path, false); if (node !== null){ return _.keys(node.nodes); } else { return null; } }
javascript
{ "resource": "" }
q60841
validation
function(obj) { if(obj == null || typeof obj != 'object' || Object.isFrozen(obj) || obj._keepHot) return; Object.freeze(obj); // First freeze the object. for (var key in obj) { if(obj.hasOwnProperty(key)) deepFreeze(obj[key]); // Recursively call deepFreeze. } }
javascript
{ "resource": "" }
q60842
validation
function(parentClass, constructor) { // inherits methods from parent class constructor.prototype = Object.create(parentClass.prototype); // inherits methods from Subscribable class for(var key in Subscribable.prototype) { constructor.prototype[key] = Subscribable.prototype[key]; } constructor.prototype.constructor = constructor; constructor.prototype._keepHot = true; return constructor; }
javascript
{ "resource": "" }
q60843
BinarySearchTreeIterator
validation
function BinarySearchTreeIterator(tree, type) { type = type || 'v'; if (type !== 'k' && type !== 'v' && type !== 'e') { throw new Error('Incorrect binary search tree iterator type "' + type + '"!'); } this._type = type; this._tree = tree; this._last = null; this._done = false; }
javascript
{ "resource": "" }
q60844
validation
function (xhr, options, promise) { var instance = this, url = options.url, method = options.method || GET, headers = options.headers ? options.headers.itsa_deepClone() : {}, // all request will get some headers async = !options.sync, data = options.data, reject = promise.reject, sendPayload, additionalData; // xhr will be null in case of a CORS-request when no CORS is possible if (!xhr) { console.error(NAME, "_initXHR fails: "+ERROR_NO_XHR); reject(ERROR_NO_XHR); return; } // adding default headers (when set): headers.itsa_merge(instance._standardHeaders); // method-name should be in uppercase: method = method.toUpperCase(); // in case of BODY-method: eliminate any data behind querystring: // else: append data-object behind querystring if (BODY_METHODS[method]) { url = url.split("?"); // now url is an array url[1] && (additionalData=instance._queryStringToDataObject(url[1])); if (additionalData && !additionalData.itsa_isEmpty()) { data || (data={}); data.itsa_merge(additionalData); } url = url[0]; // now url is a String again } else if (data && (headers[CONTENT_TYPE]!==MIME_BLOB)) { url += (url.itsa_contains("?") ? "&" : "?") + instance._toQueryString(data); } xhr.open(method, url, async); options.responseType && (xhr.responseType=options.responseType); options.withCredentials && (xhr.withCredentials=true); // more initialisation might be needed by extended modules: instance._xhrInitList.forEach( function(fn) { fn(xhr, promise, headers, method); } ); if (BODY_METHODS[method] && data) { if (headers[CONTENT_TYPE]===MIME_BLOB) { if (!xhr._isXDR) { sendPayload = data; } } else { sendPayload = ((headers[CONTENT_TYPE]===MIME_JSON) || xhr._isXDR) ? JSON.stringify(data) : instance._toQueryString(data); } } // send the request: xhr.send(sendPayload); // now add xhr.abort() to the promise, so we can call from within the returned promise-instance promise.abort = function() { reject(ABORTED); xhr._aborted = true; // must be set: IE9 won"t allow to read anything on xhr after being aborted xhr.abort(); }; // in case synchronous transfer: force an xhr.onreadystatechange: async || xhr.onreadystatechange(); }
javascript
{ "resource": "" }
q60845
validation
function(xhr, promise, headers, method) { // XDR cannot set requestheaders, only XHR: if (!xhr._isXDR) { var name; if ((method!=="POST") && (method!=="PUT")) { // force GET-request to make a request instead of using cache (like IE does): headers["If-Modified-Since"] = "Wed, 15 Nov 1995 01:00:00 GMT"; // header "Content-Type" should only be set with POST or PUT requests: delete headers[CONTENT_TYPE]; } // set all headers for (name in headers) { xhr.setRequestHeader(name, headers[name]); } // in case of POST or PUT method: always make sure "Content-Type" is specified !BODY_METHODS[method] || (headers && (CONTENT_TYPE in headers)) || xhr.setRequestHeader(CONTENT_TYPE, DEF_CONTENT_TYPE_POST); } }
javascript
{ "resource": "" }
q60846
validation
function(data) { var paramArray = [], key, value; for (key in data) { value = data[key]; key = ENCODE_URI_COMPONENT(key); paramArray.push((value === null) ? key : (key + "=" + ENCODE_URI_COMPONENT(value))); } return paramArray.join("&"); }
javascript
{ "resource": "" }
q60847
validation
function(queryString) { var args = queryString.split("&"), data = {}; args.forEach(function(arg) { var item = arg.split("="); (item.length===2) && (data[item[0]]=item[1]); }); return data; }
javascript
{ "resource": "" }
q60848
validation
function() { var instance = this; instance._runningRequests.forEach(function(promise) { promise.abort(); }); instance._runningRequests.length = 0; }
javascript
{ "resource": "" }
q60849
invokeConfigFn
validation
function invokeConfigFn(tasks) { for (var taskName in tasks) { if (tasks.hasOwnProperty(taskName)) { tasks[taskName](grunt); } } }
javascript
{ "resource": "" }
q60850
ensureProperties
validation
function ensureProperties(str) { str = str || ''; t.ok(hasPropertyDefinition(view, 'value'), 'has `value` property' + str); t.equal(typeof view.name, 'string', 'has `name` property that is a string' + str); t.notEqual(view.name, '', '`name` property should not be empty string' + str); t.ok(isFunction(view.setValue), 'has `setValue` method' + str); t.equal(typeof view.valid, 'boolean', 'has `valid` property that is a boolean' + str); t.equal(parent, view.parent, 'has same `parent` property' + str); }
javascript
{ "resource": "" }
q60851
printEnvironment
validation
function printEnvironment(environment, path, outputFile) { // print sub-objects in an environment. if (path) environment = traverse(environment).get(path.split('.')); path = path ? '.' + path : ''; if (argv.format === 'json' || outputFile) { var json = JSON.stringify(environment, null, 2); if (outputFile) fs.writeFileSync(outputFile, json, 'utf-8'); else console.log(JSON.stringify(environment, null, 2)); } else { environment = _.mapValues(environment, function(v) { return util.inspect(v, {colors: true}); }); console.log(chalk.blue('==> ') + chalk.bold(renv.environment + path)); console.log(columnify(environment, {showHeaders: false, config: { key: {minWidth: parseInt(width * 0.4), maxWidth: parseInt(width * 0.4)}, value: {minWidth: parseInt(width * 0.6), maxWidth: parseInt(width * 0.6)}, }})); } }
javascript
{ "resource": "" }
q60852
rte
validation
function rte(src, dest, data) { if (typeof dest === 'object') { data = dest; dest = src; } var rte = new Rte(src, data); return rte.stringify(dest); }
javascript
{ "resource": "" }
q60853
Component
validation
function Component(domElement) { this.domElement = domElement; this.template = ""; this.templateNodes = []; this.model = []; this.parentModel = null; this.built = false; }
javascript
{ "resource": "" }
q60854
validation
function(template) { // unbind old models from old dom elements this.unbindAll(); if(template == null) { // save template html this.template = this.domElement.innerHTML; } else { // set template string this.template = template; // fill element.innerHTML with the template //this.domElement.innerHTML = template; htmlToElem(this.domElement, this.template); } // set built flag as false this.built = false; // save template nodes this.templateNodes = [Array.prototype.slice.call(this.domElement.childNodes)]; }
javascript
{ "resource": "" }
q60855
validation
function(newModel) { var oldPos; for(var i = 0; i < newModel.length; i++) { oldPos = this.model.indexOf(newModel[i]); if(oldPos >= 0) { // model already in the DOM if(i != oldPos) { // adjust template this.moveTemplateNodes(oldPos, i); // and model this.model.splice(i, 0, this.model.splice(oldPos, 1)[0]); } } else { // check whether current old model is in a new model array if(this.templateNodes[i] && newModel.indexOf(this.model[i]) == -1) { // just replace model at i this.model[i] = newModel[i]; // bind model and template nodes this.bindModel(i); } else { // insert templateNodes at i this.cloneTemplateNodes(i); // insert model at i this.model.splice(i, 0, newModel[i]); // bind model and template nodes this.bindModel(i); } } } if(this.model.length > newModel.length) { // remove redundant template nodes for(var i = this.templateNodes.length-1; newModel.length <= i; i--) { this.unbindModel(i); this.removeTemplateNodes(i); } // and models this.model.splice(newModel.length, this.model.length-newModel.length); } }
javascript
{ "resource": "" }
q60856
validation
function(position) { if(!this.templateNodes[0]) { // fill element.innerHTML with the template //this.domElement.innerHTML = this.template; htmlToElem(this.domElement, this.template); // save template nodes this.templateNodes.push(Array.prototype.slice.call(this.domElement.childNodes)); return; } /*var clonedNode, clonedNodes = []; var templateNodes = this.templateNodes[0]; // need to be changed, because this.templateNodes[0] doesn't have to exist. if(position == null || position == this.templateNodes.length) { // insert at the end for(var i = 0; i < templateNodes.length; i++) { clonedNode = templateNodes[i].cloneNode(true); this.domElement.appendChild(clonedNode); clonedNodes.push(clonedNode); } this.templateNodes.push(clonedNodes); } else { // insert at the position (before nodes of this.templateNodes[position]) for(var i = 0; i < templateNodes.length; i++) { clonedNode = templateNodes[i].cloneNode(true); this.domElement.insertBefore(clonedNode, this.templateNodes[position][0]); clonedNodes.push(clonedNode); } this.templateNodes.splice(position, 0, clonedNodes); }*/ var dummyWrapper = document.createElement("div"); //dummyWrapper.innerHTML = this.template; htmlToElem(dummyWrapper, this.template); var templateNodes = Array.prototype.slice.call(dummyWrapper.childNodes); if(position == null || position == this.templateNodes.length) { // insert at the end for(var i = 0; i < templateNodes.length; i++) { this.domElement.appendChild(templateNodes[i]); } this.templateNodes.push(templateNodes); } else { // insert at the position (before nodes of this.templateNodes[position]) for(var i = 0; i < templateNodes.length; i++) { this.domElement.insertBefore(templateNodes[i], this.templateNodes[position][0]); } this.templateNodes.splice(position, 0, templateNodes); } }
javascript
{ "resource": "" }
q60857
validation
function(from, to) { var templateNodes = this.templateNodes[from]; // insert at the position (before nodes of this.templateNodes[position]) for(var i = 0; i < templateNodes.length; i++) { this.domElement.insertBefore(templateNodes[i], this.templateNodes[to][0]); } this.templateNodes.splice(from, 1); this.templateNodes.splice(to, 0, templateNodes); }
javascript
{ "resource": "" }
q60858
BaseImporter
validation
function BaseImporter () { this._schema = null; this._export = null; this._types = {}; this._model = { properties:{}, definitions:{}, ids:{} }; this.error = null; var baseImporter = this; //setup listeners this.on('readyStateChanged', function (readyState) { //state changed if(readyStates.complete === readyState){ //state says loading has finished if(baseImporter.error){ baseImporter.emit('failed', baseImporter.error); } else { baseImporter.emit('success', null, baseImporter.getModel()); } //send general complete notification baseImporter.emit('complete', baseImporter.error, baseImporter.getModel()); } }); }
javascript
{ "resource": "" }
q60859
validation
function(nextSchema, nextScope, nextIndex, nextPath, nextCBack){ var nSchema = nextSchema || false; var nScope = nextScope; var nIndex = nextIndex; var nPath = nextPath; var nCBack = nextCBack || function(){}; if(false === nSchema){ return function(){}; }else{ return function(){ baseimporter.indexIDs.call(baseimporter, nSchema, nScope, nIndex, nPath, nCBack); }; } }
javascript
{ "resource": "" }
q60860
loadFormatter
validation
function loadFormatter(formatterPath) { try { // @TODO: deprecate formatterPath = (formatterPath === 'jslint_xml') ? 'jslint' : formatterPath; return require('./lib/' + formatterPath + '_emitter'); } catch (e) { console.error('Unrecognized format: %s', formatterPath); console.error('This emitter was not found on lib folder.\nYou can always create yours :)\n'); throw e; } }
javascript
{ "resource": "" }
q60861
createDirectory
validation
function createDirectory(filePath, cb) { var dirname = path.dirname(filePath); mkdirp(dirname, function (err) { if (!err) { cb(); } else { console.error('Error creating directory: ', err); } }); }
javascript
{ "resource": "" }
q60862
binb_sha1
validation
function binb_sha1 (x, len) { // append padding x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; var t, oa, ob, oc, od, oe, i = 0, j = 0; for (i; i < x.length; i += 16) { oa = a; ob = b; oc = c; od = d; oe = e; for (j; j < 80; j++) { if (j < 16) w[j] = x[i + j]; else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = bit_rol(b, 30); b = a; a = t; } a = safe_add(a, oa); b = safe_add(b, ob); c = safe_add(c, oc); d = safe_add(d, od); e = safe_add(e, oe); } return Array(a, b, c, d, e); }
javascript
{ "resource": "" }
q60863
Observer
validation
function Observer(fn, observerInfo) { // call Subscribable constructor Subscribable.call(this); this.fn = fn; this.dependency = []; this.currentValue = null; this.observerInfo = observerInfo; // hard binded callbacks this._dependencyGetter = this.dependencyGetter.bind(this); this.call(); }
javascript
{ "resource": "" }
q60864
validation
function(directory) { var git, gitRef, packagePath, packageInfos; packagePath = path.join(directory, "package.json"); // Check directory is a git repository return Q.nfcall(exec, "cd "+directory+" && git config --get remote.origin.url").then(function(output) { git = output.join("").replace(/(\r\n|\n|\r)/gm, ""); // Check package.json exists if (!fs.existsSync(packagePath)) { return Q.reject(new Error("package.json not found")); } else { return Q(); } }).then(function() { // Read current commit return Q.nfcall(exec, "cd "+directory+" && git rev-parse HEAD").then(function(output) { gitRef = output.join("").replace(/(\r\n|\n|\r)/gm, ""); }); }).then(function() { // Read package.json return Q.nfcall(fs.readFile, packagePath, 'utf8'); }).then(function(output) { packageInfos = JSON.parse(output); return Q({ 'git': git+"#"+gitRef, 'package': packageInfos }); }); }
javascript
{ "resource": "" }
q60865
validation
function (payload, next) { jira.getProject(options.project, handleGetProject(options, payload, next)); }
javascript
{ "resource": "" }
q60866
validation
function(localImagePath) { // Read the file in and convert it. var imageFile = fs.readFileSync(localImagePath); var mimeType = mime.lookup(localImagePath); var ret = "data:"; ret += mimeType; ret += ";base64,"; ret += imageFile.toString("base64"); return ret; }
javascript
{ "resource": "" }
q60867
end
validation
function end() { try { this.queue(transformCss(filePath, data, opts)); } catch(err) { this.emit("error", new Error(err)); } this.queue(null); }
javascript
{ "resource": "" }
q60868
apilist
validation
function apilist(items) { return ul(items.map(item => li({ // use innerHTML to generate nested links innerHTML : item.replace(/(\w+)/g, apilink) }))) }
javascript
{ "resource": "" }
q60869
validation
function(property, callback) { if(typeof property != "string") { callback = property; property = "__all__"; } this._subscribers[property] = this._subscribers[property] || []; if(this._subscribers[property].indexOf(callback) == -1) { this._subscribers[property].push(callback); } }
javascript
{ "resource": "" }
q60870
validation
function(property, callback) { if(typeof property != "string") { callback = property; property = "__all__"; } // empty, don't remove anything if(!this._subscribers[property]) return; // remove everything if(callback == null) this._subscribers[property] = []; // find callback and remove it var ind = this._subscribers[property].indexOf(callback); if(ind >= 0) this._subscribers[property].splice(ind, 1); }
javascript
{ "resource": "" }
q60871
validation
function(property, val) { if(val === undefined) { // if second argument is missing, use property as value val = (property === undefined) ? this : property; property = "__all__"; } if(property == "__all__") { // notify global subscribers notify(this._subscribers["__all__"], val); } else { // notify all subscribers of property notify(this._subscribers[property], val); // notify global subscribers as well this.notify(/*TODO: some usefull value*/); } }
javascript
{ "resource": "" }
q60872
rowgroup
validation
function rowgroup(items, name) { return items.map(([htmlterm, ariaterm], i) => { htmlcount += htmlterm.split(', ').length ariacount += ariaterm.split(', ').length return tr([ !i && th({ rowSpan : items.length, children : name, }), td(htmlterm), td(ariaterm) ]) }) }
javascript
{ "resource": "" }
q60873
addStats
validation
function addStats(database, cb){ // If a databaseName is present, it's a single db. No need to switch. var changeDB = database.databaseName ? database : db.db(database.name); // Get the stats changeDB.stats(function(err, stats){ // Remove 1 from collection count, unless it's zero. Not sure why it's 1 off. if (stats.collections) { stats.collections--; } // Add the db name as the _id stats._id = stats.db; stats.name = stats.db; // Rename collections to avoid collisions on the client app. stats.collectionCount = stats.collections; delete stats.collections; // Add the stats to the corresponding database. dbList.push(stats); cb(null, database); }); }
javascript
{ "resource": "" }
q60874
tail
validation
function tail(array) { var length = array ? array.length : 0; return length ? baseSlice(array, 1, length) : []; }
javascript
{ "resource": "" }
q60875
basePick
validation
function basePick(object, props) { object = Object(object); return basePickBy(object, props, function(value, key) { return key in object; }); }
javascript
{ "resource": "" }
q60876
arrayAggregator
validation
function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array ? array.length : 0; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; }
javascript
{ "resource": "" }
q60877
createHybrid
validation
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), isFlip = bitmask & FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; }
javascript
{ "resource": "" }
q60878
baseXor
validation
function baseXor(arrays, iteratee, comparator) { var index = -1, length = arrays.length; while (++index < length) { var result = result ? arrayPush( baseDifference(result, arrays[index], iteratee, comparator), baseDifference(arrays[index], result, iteratee, comparator) ) : arrays[index]; } return (result && result.length) ? baseUniq(result, iteratee, comparator) : []; }
javascript
{ "resource": "" }
q60879
baseMean
validation
function baseMean(array, iteratee) { var length = array ? array.length : 0; return length ? (baseSum(array, iteratee) / length) : NAN; }
javascript
{ "resource": "" }
q60880
baseIsTypedArray
validation
function baseIsTypedArray(value) { return isObjectLike$1(value) && isLength(value.length) && !!typedArrayTags[objectToString$1.call(value)]; }
javascript
{ "resource": "" }
q60881
baseUnset
validation
function baseUnset(object, path) { path = isKey(path, object) ? [path] : castPath(path); object = parent(object, path); var key = toKey(last(path)); return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; }
javascript
{ "resource": "" }
q60882
basePullAt
validation
function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else if (!isKey(index, array)) { var path = castPath(index), object = parent(array, path); if (object != null) { delete object[toKey(last(path))]; } } else { delete array[toKey(index)]; } } } return array; }
javascript
{ "resource": "" }
q60883
isError
validation
function isError(value) { if (!isObjectLike(value)) { return false; } return (objectToString.call(value) == errorTag) || (typeof value.message == 'string' && typeof value.name == 'string'); }
javascript
{ "resource": "" }
q60884
createWrap
validation
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] == null ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); }
javascript
{ "resource": "" }
q60885
forInRight
validation
function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, baseIteratee(iteratee, 3), keysIn); }
javascript
{ "resource": "" }
q60886
basePickBy
validation
function basePickBy(object, props, predicate) { var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (predicate(value, key)) { baseAssignValue(result, key, value); } } return result; }
javascript
{ "resource": "" }
q60887
SelectQuery
validation
function SelectQuery(request, context) { this.request = request; this.domain = new Domain({ source: request, context: context }); this.filters = []; this.matchExpression = ''; this.noResult = false; this.parse(); }
javascript
{ "resource": "" }
q60888
validation
function(fieldName) { var field; if (this.domain && fieldName) { field = this.domain.getIndexField(fieldName); if (!field.exists()) { this.throwValidationError( 'CS-UnknownFieldInMatchExpression', 'Field \'' + fieldName + '\' is not defined in the metadata for this ' + 'collection. All fields used in the match expression must be ' + 'defined in the metadata.' ); } else if (!field.searchEnabled) { this.available = false; } } if (!field) field = new IndexField(fieldName).setType("text"); return field; }
javascript
{ "resource": "" }
q60889
formatTable
validation
function formatTable(table, links, notes) { var widths = []; var rows = table.map(function (row) { var cells = row.map(function (cell) { return formatSpans(cell, links, notes); }); cells.forEach(function (cell, index) { widths[index] = Math.max(cell.length, widths[index] || 5); widths[index] = Math.min(widths[index], 50); }); return cells.join(' & '); }); var totalWidth = widths.reduce(function sum(val, width) { return val + width; }, 0); totalWidth = Math.max(totalWidth, 100); widths = widths.map(function (width) { var relativeWidth = width / totalWidth; return 'p{' + relativeWidth + '\\textwidth}'; }).join(' | '); var str = '\\begin{longtable}{ | ' + widths + ' |}\n' + '\\hline\n' + rows.join(' \\\\\n\\hline\n') + ' \\\\\n' + '\\hline\n' + '\\end{longtable}'; return str; }
javascript
{ "resource": "" }
q60890
validation
function(plugins, config) { var self = this; var aliasMap = Object.keys(plugins) .reduce(function(aliases, pluginName) { if (!aliases[pluginName] || !aliases[pluginName].as) { aliases[pluginName] = { as: [pluginName] }; } aliases[pluginName].as = self._castArray(aliases[pluginName].as); return aliases; }, config); var unknownConfigKeys = _.difference(Object.keys(aliasMap), Object.keys(plugins)); if (unknownConfigKeys.length) { this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.alias'); } return aliasMap; }
javascript
{ "resource": "" }
q60891
validation
function(aliasMap, config) { var aliases = this._flattenAliasMap(aliasMap); var allExcept = null; if (typeof config.allExcept !== 'undefined') { allExcept = this._castArray(config.allExcept); delete config.allExcept; } var keys = Object.keys(config); if (allExcept) { keys = keys.concat(allExcept); } var unknownConfigKeys = _.difference(keys, aliases); if (unknownConfigKeys.length) { this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.disabled'); } var disabledMap = aliases.reduce(function(map, alias) { if (map[alias] === undefined) { if (allExcept && allExcept.length) { if (allExcept.indexOf(alias) >= 0) { map[alias] = false; } else { map[alias] = true; } } else { map[alias] = false; } } return map; }, config); return disabledMap; }
javascript
{ "resource": "" }
q60892
validation
function(config, aliasMap, pluginInstances) { var self = this; pluginInstances.forEach(function(instance) { if (instance.runBefore) { var befores = self._castArray(instance.runBefore); config = self._mergeAuthorProvidedOrderWithConfigOrder('before', instance.name, befores, config, aliasMap); } if (instance.runAfter) { var afters = self._castArray(instance.runAfter); config = self._mergeAuthorProvidedOrderWithConfigOrder('after', instance.name, afters, config, aliasMap); } }); var aliases = this._flattenAliasMap(aliasMap); var configNames = Object.keys(config).reduce(function(arr, key) { arr.push(key); var befores = self._castArray(config[key].before); var afters = self._castArray(config[key].after); return arr.concat(befores).concat(afters); }, []) .reduce(function(arr, key) { if (arr.indexOf(key) === -1) { arr.push(key); } return arr; }, []); var unknownConfigKeys = _.difference(configNames, aliases); if (unknownConfigKeys.length) { this._logUnknownPlugins(unknownConfigKeys, 'config.pipeline.runOrder'); } return config; }
javascript
{ "resource": "" }
q60893
validation
function(options, params) { // Create connection to qps var qpsApi = qps(options); // Returned object var task = new Task(); // Ticket flow Rx.Observable .from(qpsApi.ticket.post(params)) .catch((err) => { if (err.match(/^Specified targetId .* was unknown$/)) { // if there was a problem with the target Id, try to generate another ticket by reseting target Id task.running('warning', `Wrong targetId: '${params.TargetId}', generating a ticket to default location`); delete params.TargetId; return Rx.Observable.from(module.exports.getTicket(options, params)); } else { return Rx.Observable.throw(new Error(err)); } }) .subscribe(task); if (returnObservable) { return task; } else { return task.toPromise(extPromise); } }
javascript
{ "resource": "" }
q60894
exportCubeMixin
validation
function exportCubeMixin(cubeDef) { var app = this; var task = new Task(); promise().then(function() { // Start task.running('info', 'Starting!'); }).then(function(reply) { // Create cube return app.createSessionObject({ qHyperCubeDef: cubeDef, qInfo: { qType: 'mashup' } }).then(function(reply) { task.running('info', 'Cube generated'); return reply; }) }).then(function(sessionObject) { // Get cube layout return promise.all([ sessionObject, sessionObject.getLayout().then(function(reply) { task.running('info', 'Got cube layout'); return reply; }) ]) }).then(function([sessionObject, cubeLayout]) { // Get cube pages var columns = cubeLayout.qHyperCube.qSize.qcx; var totalheight = cubeLayout.qHyperCube.qSize.qcy; var pageheight = Math.floor(10000 / columns); var numberOfPages = Math.ceil(totalheight / pageheight); var pages = Array.apply(null, new Array(numberOfPages)).map(function(data, index) { return sessionObject.getHyperCubeData( '/qHyperCubeDef', [{ qTop: (pageheight * index), qLeft: 0, qWidth: columns, qHeight: pageheight }] ).then((page) => { task.running('page', page); return page; }); }, this); return promise.all(pages).then(function(pages) { return promise.all([ sessionObject, cubeLayout, pages ]); }); }).then(function([sessionObject, cubeLayout, pages]) { pages = [].concat.apply([], pages.map(function(item) { return item[0].qMatrix; })); task.done(pages); return pages; }).fail(function(err) { task.failed(err); return promise.reject(err); }); if (returnObservable) { return task; } else { return task.toPromise(extPromise); } }
javascript
{ "resource": "" }
q60895
createListBoxMixin
validation
function createListBoxMixin({ id, field }) { return this.createObject({ qInfo: { qType: 'ListObject' }, qListObjectDef: { qStateName: '$', qLibraryId: undef.if(id, ''), qDef: { qFieldDefs: undef.if(field, [field], []) }, qInitialDataFetch: [{ qTop: 0, qLeft: 0, qHeight: 5, qWidth: 1 }] } }).then((object) => { return object.getLayout(); }) }
javascript
{ "resource": "" }
q60896
grayTransform
validation
function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1) }
javascript
{ "resource": "" }
q60897
directionSequence
validation
function directionSequence(i, dim) { // :: Int -> Int -> Int if (i == 0) return 0 if (i % 2 == 0) return bitwise.trailingSetBits(i - 1) % dim return bitwise.trailingSetBits(i) % dim }
javascript
{ "resource": "" }
q60898
nthRoot
validation
function nthRoot(num, nArg, precArg) { // : Int -> Int -> Int -> Int var n = nArg || 2; var prec = precArg || 12; var x = 1; // Initial guess. for (var i=0; i<prec; i++) { x = 1/n * ((n-1)*x + (num / Math.pow(x, n-1))); } return x; }
javascript
{ "resource": "" }
q60899
hilbertIndex
validation
function hilbertIndex(point, options) { // :: [Int, Int, ..] -> {} -> Int options = options || {} var index = 0, code, entry = options.entry || 0, direction = options.direction || 0, i = options.precision || bitwise.bitPrecision(Math.max.apply(null, point)) - 1, dim = point.length console.log(i) while (i >= 0) { var bits = 0 var mask = 1 << dim - 1 for (var k = 0; k < point.length; k++) { if (point[dim - (k+1)] & (1 << i)) { bits |= mask } mask >>>= 1 } bits = grayTransform(entry, direction, bits, dim) code = grayInverse(bits) entry = entry ^ bitwise.rotateLeft(entrySequence(code), dim, 0, direction + 1) direction = (direction + directionSequence(code, dim) + 1) % dim index = (index << dim) | code i-- } return index }
javascript
{ "resource": "" }