_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q55500
raw
train
function raw(cmd, args = []) { if (!Array.isArray(args)) throw new Error('`args` must be an array!'); return knex.raw(cmd, args); }
javascript
{ "resource": "" }
q55501
createTables
train
function createTables() { return bluebird.all(getComponents().map(component => client.createTable(`components.${component}`))) .then(() => bluebird.all(getLayouts().map(layout => client.createTableWithMeta(`layouts.${layout}`)))) .then(() => client.createTableWithMeta('pages')) .then(() => client.raw('CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );', ['uris'])) .then(() => createRemainingTables()); }
javascript
{ "resource": "" }
q55502
createClient
train
function createClient(testRedisUrl) { const redisUrl = testRedisUrl || REDIS_URL; if (!redisUrl) { return bluebird.reject(new Error('No Redis URL set')); } log('debug', `Connecting to Redis at ${redisUrl}`); return new bluebird(resolve => { module.exports.client = bluebird.promisifyAll(new Redis(redisUrl)); module.exports.client.on('error', logGenericError(__filename)); resolve({ server: redisUrl }); }); }
javascript
{ "resource": "" }
q55503
put
train
function put(key, value) { if (!shouldProcess(key)) return bluebird.resolve(); return module.exports.client.hsetAsync(REDIS_HASH, key, value); }
javascript
{ "resource": "" }
q55504
get
train
function get(key) { if (!module.exports.client) { return bluebird.reject(notFoundError(key)); } return module.exports.client.hgetAsync(REDIS_HASH, key) .then(data => data || bluebird.reject(notFoundError(key))); }
javascript
{ "resource": "" }
q55505
createBundler
train
function createBundler(opts, file, transform) { // omit file contents to make browserify-incremental work propery // on main entry (#4) opts.entries = file.path opts.basedir = path.dirname(file.path) let bundler = bundlers[file.path] if (bundler) { bundler.removeAllListeners('log') bundler.removeAllListeners('time') } else { bundler = browserify(Object.assign(opts, incremental.args)) // only available via method call (#25) if (opts.external) { bundler.external(opts.external) } incremental(bundler) bundlers[file.path] = bundler } bundler.on('log', message => transform.emit('log', message)) bundler.on('time', time => transform.emit('time', time)) return bundler }
javascript
{ "resource": "" }
q55506
createErrorHandler
train
function createErrorHandler(opts, transform) { return err => { if ('emit' === opts.error) { transform.emit('error', err) } else if ('function' === typeof opts.error) { opts.error(err) } else { const message = colors.red(err.name) + '\n' + err.toString() .replace(/(ParseError.*)/, colors.red('$1')) log(message) } transform.emit('end') if (opts.callback) { opts.callback(through2()) } } }
javascript
{ "resource": "" }
q55507
train
function (options, callback) { let me = this let tunnel let sshcfg = { host: this.host + ':' + (options.sshport || 22), user: options.username, remoteport: this.port } if (options.password) { sshcfg.password = options.password } if (options.key) { sshcfg.key = options.key } // Dynamically determine port by availability or via option. // Then open the tunnel. if (options.port) { sshcfg.port = options.port tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { NGN.BUS.emit('sshtunnel.create', tunnel) callback && callback(me.host, options.port) }) tunnel.connect() } else { // Create a quick TCP server on random port to secure the port, // then shut it down and use the newly freed port. let tmp = net.createServer().listen(0, '127.0.0.1', function () { sshcfg.port = this.address().port tmp.close() }) tmp.on('close', function () { // Launch the tunnel tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { callback && callback('127.0.0.1', sshcfg.port) }) tunnel.connect() }) } }
javascript
{ "resource": "" }
q55508
getTemplate
train
function getTemplate(template, options) { stack.clear(); parser.reset(); let opts = typeof options === 'undefined' ? {} : options; opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true; opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false; opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict'; opts.logger = opts.logger != null ? opts.logger : {}; let lambdas = {}; if (_.isArray(opts.lambdas)) { for (let i = 0; i < opts.lambdas.length; i++) { lambdas[opts.lambdas[i]] = true; } } opts.lambdas = lambdas; opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true; compilerLogger.setStrictMode(opts.strict); compilerLogger.setOverrides(opts.logger); stack.setHtmlValidation(opts.validateHtml); let templateStr = template.toString(); processTemplate(templateStr, opts); let output = {}; if (stack.stack.length > 0) { compilerErrors.notAllTagsWereClosedProperly(stack.stack); } parser.end(); output.templateObj = stack.getOutput(); const Template = require('../template'); output.template = new Template(output.templateObj); output.source = template; output.tokens = {}; _.each(stack.tokens, function(values, type) { output.tokens[type] = _.keys(values); }); return output; }
javascript
{ "resource": "" }
q55509
train
function(name, absoluteTime) { this.name = name; this.startTime = now(); this.absoluteTime = !!absoluteTime; this.adjust = 0; this.running = true; }
javascript
{ "resource": "" }
q55510
logStat
train
function logStat(stat, value) { if (!statsTracker[stat]) { statsTracker[stat] = []; } statsTracker[stat].push(value); clearTimeout(statsTimer); statsTimer = setTimeout(printStats, 100); }
javascript
{ "resource": "" }
q55511
printStats
train
function printStats() { _.each(statsTracker, function(vals, stat) { var numStats = vals.length; var total = _.reduce(vals, function(memo, num) { return memo + num; }, 0); var avg = parseFloat(total / numStats).toFixed(4) + 'ms'; var printableTotal = parseFloat(total).toFixed(4) + 'ms'; logger.log(stat + ': ' + avg + ' (' + printableTotal + ' / ' + numStats + ')'); }); statsTracker = {}; }
javascript
{ "resource": "" }
q55512
WEvent
train
function WEvent(evt) { if (evt) { this.originalEvent = evt; this.type = evt.type; this.which = evt.which || evt.charCode || evt.keyCode; if (!this.which && evt.button !== undefined) { this.which = ( evt.button & 1 ? 1 : ( evt.button & 2 ? 3 : ( evt.button & 4 ? 2 : 0 ) ) ); } this.button = evt.button; this.currentTarget = evt.currentTarget; this.delegateTarget = null; this.target = evt.target || evt.srcElement; this.shiftKey = evt.shiftKey; this.altKey = evt.altKey; this.ctrlKey = evt.ctrlKey; this.metaKey = evt.metaKey; } this.current = undefined; this.previous = undefined; this.eventId = _.uniqueId('e'); this.propagationStopped = false; this.immediatePropagationStopped = false; }
javascript
{ "resource": "" }
q55513
getDefaultConsole
train
function getDefaultConsole() { if (console && typeof console.log === 'function') { return console.log; } else { return function() { // Console isn't available until dev tools is open in old IE, so keep checking if (console && typeof console.log === 'function') { console.log.apply(console, arguments); } }; } }
javascript
{ "resource": "" }
q55514
updateNestedModels
train
function updateNestedModels() { nestedRegistry.models = []; _.each(nestedRegistry.views, function(view) { var data = (view.obj.model || view.obj.collection); if (data) { nestedRegistry.models.push(flatRegistry.models[data.getDebugName()]); } }); }
javascript
{ "resource": "" }
q55515
registerView
train
function registerView(view) { var name = view.getDebugName(); var wrapped = new RegistryWrapper(view, 'views'); flatRegistry.views[name] = wrapped; if (!view.parentView && !view.isComponentView) { nestedRegistry.views[name] = wrapped; } if (typeof view.destroy === 'function') { wrapped.destroy = _.bind(view.destroy, view); view.destroy = _.bind(function() { var name = this.obj.getDebugName(); delete nestedRegistry.views[name]; delete flatRegistry.views[name]; updateNestedModels(); triggerChange(); this.destroy(); }, wrapped); } updateNestedModels(); triggerChange(); }
javascript
{ "resource": "" }
q55516
registerModel
train
function registerModel(model) { var name = model.getDebugName(); var wrapped = flatRegistry.models[name] = new RegistryWrapper(model, 'models'); if (typeof model.destroy === 'function') { wrapped.destroy = _.bind(model.destroy, model); model.destroy = _.bind(function() { var name = this.obj.getDebugName(); delete flatRegistry.models[name]; updateNestedModels(); triggerChange(); this.destroy(); }, wrapped); } triggerChange(); }
javascript
{ "resource": "" }
q55517
injectStyles
train
function injectStyles() { if (_stylesInjected) return; _stylesInjected = true; let node = doc.createElement('style'); node.innerHTML = css; node.type = 'text/css'; if (doc.head.childNodes.length > 0) { doc.head.insertBefore(node, doc.head.childNodes[0]); } else { doc.head.appendChild(node); } }
javascript
{ "resource": "" }
q55518
getOutsideHandler
train
function getOutsideHandler(method) { var lastEventId = null; /** * If the event that is firing is not the same as the event that was fired on the element * execute the method * @param {object} evt the event that's firing */ var documentHandler = function(evt) { if (evt.eventId !== lastEventId) { method(evt); } }; /** * Store the id of the event for comparison when documentHandler fires * @param {object} evt the event firing on the element */ var elementHandler = function(evt) { lastEventId = evt.eventId; }; return { documentHandler: documentHandler, elementHandler: elementHandler }; }
javascript
{ "resource": "" }
q55519
getIntentHandler
train
function getIntentHandler(method, options) { var lastEvent = null; var timeout = null; var opts = extend({ intentDelay: 200 }, options); var triggerIntent = function() { method(lastEvent); }; var startIntent = function(evt) { lastEvent = evt; clearTimeout(timeout); timeout = setTimeout(triggerIntent, opts.intentDelay); }; var stopIntent = function() { lastEvent = null; clearTimeout(timeout); }; return { startIntent: startIntent, stopIntent: stopIntent }; }
javascript
{ "resource": "" }
q55520
train
function(text) { let el = stack.peek(); if (el && el.type === types.COMMENT) { stack.createObject(text); stack.closeElement(el); } else { stack.createComment(text); } }
javascript
{ "resource": "" }
q55521
pollForParentOpen
train
function pollForParentOpen() { /* jshint validthis:true */ if (this.pollNum > 0) { if (this.opener && !this.opener.OLD_TUNGSTEN_MASTER && typeof this.opener.attachTungstenDebugPane === 'function') { this.opener.attachTungstenDebugPane(this); } else { this.pollNum -= 1; this.loadingCounter.textContent = '' + this.pollNum; this.setTimeout(pollForParentOpen, POLL_INTERVAL); } } else { this.window.close(); } }
javascript
{ "resource": "" }
q55522
train
function(nativeEvent, typeOverride) { var evt = eventWrapper(nativeEvent); if (typeOverride !== undefined) { evt.type = typeOverride; } var activePath = []; var elem = evt.target; var events; /** * Handle calling bound functions with the proper targets set * @TODO move this outside eventHandler * @param {Element} elem DOM element to trigger events on * @param {Array<Function>} funcArr Array of bound functions to trigger * @param {String} selector Selector string that the event was bound to * @param {Element} delegate DOM element this event was bound to for delegation */ var triggerEventFunctions = function(elem, funcArr, selector, delegate) { var result; evt.currentTarget = elem; evt.delegateTarget = delegate; for (var i = 0; i < funcArr.length; i++) { if (!evt.isImmediatePropagationStopped()) { evt.vEvent = { handler: funcArr[i].method, selector: selector }; result = funcArr[i].method(evt); if (result === false) { falseHandler(evt); } } } }; /** * Checks if bound events should fire * @param {Object} typeEvents Event object of events to check if should fire */ var checkEvents = function(typeEvents) { var elemClasses, elemClass; // Iterate over previously passed elements to check for any delegated events var activePathLength = activePath.length; for (var i = 0; i < activePathLength; i++) { elemClasses = activePath[i].classes; // Once stopPropagation is called stop if (!evt.isPropagationStopped()) { var elemClassesLength = elemClasses.length; for (var j = 0; j < elemClassesLength; j++) { elemClass = elemClasses[j]; if (typeEvents[elemClass]) { triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem); } } } } // Check for any non-delegated events if (!evt.isPropagationStopped() && typeEvents.self) { triggerEventFunctions(elem, typeEvents.self); } }; while (elem && !evt.isPropagationStopped()) { events = module.exports.getEvents(elem); if (events) { // Generic events if (events[evt.type]) { checkEvents(events[evt.type]); } } // Create array of class names that match our pattern to check for delegation later var elemActiveClasses = module.exports.getActiveClasses(elem); if (elemActiveClasses.length) { activePath.push({ element: elem, classes: elemActiveClasses }); } elem = elem.parentNode; } }
javascript
{ "resource": "" }
q55523
train
function(elem, funcArr, selector, delegate) { var result; evt.currentTarget = elem; evt.delegateTarget = delegate; for (var i = 0; i < funcArr.length; i++) { if (!evt.isImmediatePropagationStopped()) { evt.vEvent = { handler: funcArr[i].method, selector: selector }; result = funcArr[i].method(evt); if (result === false) { falseHandler(evt); } } } }
javascript
{ "resource": "" }
q55524
train
function(typeEvents) { var elemClasses, elemClass; // Iterate over previously passed elements to check for any delegated events var activePathLength = activePath.length; for (var i = 0; i < activePathLength; i++) { elemClasses = activePath[i].classes; // Once stopPropagation is called stop if (!evt.isPropagationStopped()) { var elemClassesLength = elemClasses.length; for (var j = 0; j < elemClassesLength; j++) { elemClass = elemClasses[j]; if (typeEvents[elemClass]) { triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem); } } } } // Check for any non-delegated events if (!evt.isPropagationStopped() && typeEvents.self) { triggerEventFunctions(elem, typeEvents.self); } }
javascript
{ "resource": "" }
q55525
train
function(eventName, handler, elem) { if (elem.addEventListener) { // Setting useCapture to true so that this virtual handler is always fired first // Also handles events that don't bubble correctly like focus/blur elem.addEventListener(eventName, handler, true); } else { elem.attachEvent('on' + eventName, handler); } }
javascript
{ "resource": "" }
q55526
getTrackableFunction
train
function getTrackableFunction(obj, name, trackedFunctions) { var debugName = obj.getDebugName(); var originalFn = obj[name]; var fnName = `${debugName}.${name}`; var instrumentedFn = instrumentFunction(fnName, originalFn); var fn = function tungstenTrackingPassthrough() { // Since objects are passed by reference, it can be updated without loosing reference if (trackedFunctions[name]) { return instrumentedFn.apply(this, arguments); } else { return originalFn.apply(this, arguments); } }; fn.original = originalFn; return fn; }
javascript
{ "resource": "" }
q55527
RegistryWrapper
train
function RegistryWrapper(obj, type) { this.obj = obj; this.type = type; this.selected = false; this.collapsed = false; this.customEvents = []; this.debugName = obj.getDebugName(); if (obj.el) { this.elString = Object.prototype.toString.call(obj.el); } if (typeof obj.getFunctions === 'function') { this.trackedFunctions = {}; this.objectFunctions = obj.getFunctions(this.trackedFunctions, getTrackableFunction); } // Add history tracking to top level views if (type === 'views' && typeof obj.getState === 'function' && !obj.parentView) { this.state = new StateHistory(obj); } if (typeof obj.getEvents === 'function') { this.objectEvents = obj.getEvents(); } _.bindAll(this, 'isParent', 'getChildren'); }
javascript
{ "resource": "" }
q55528
transformPropertyName
train
function transformPropertyName(attributeName) { if (propertiesToTransform[attributeName]) { return propertiesToTransform[attributeName]; } if (nonTransformedProperties[attributeName] !== true) { return false; } return attributeName; }
javascript
{ "resource": "" }
q55529
registerWidget
train
function registerWidget(name, constructor) { if (typeof name !== 'string' || typeof constructor !== 'function' || typeof constructor.getTemplate !== 'function' || constructor.prototype.type !== 'Widget') { throw 'Invalid arguments passed for registerWidget'; } widgets[name] = constructor; }
javascript
{ "resource": "" }
q55530
parseStringAttrs
train
function parseStringAttrs(templates, context) { var stringAttrs = ''; var toString = new ToString(true, true); for (var i = 0; i < templates.length; i++) { toString.clear(); render(toString, templates[i], context); stringAttrs += ' ' + toString.getOutput() + ' '; } if (whitespaceOnlyRegex.test(stringAttrs)) { return null; } var node = htmlParser('<div ' + stringAttrs + '></div>'); return node.properties.attributes; }
javascript
{ "resource": "" }
q55531
renderAttributeString
train
function renderAttributeString(values, context) { if (typeof values === 'string' || typeof values === 'boolean') { return values; } var buffer = ''; var toString = new ToString(); for (var i = 0; i < values.length; i++) { toString.clear(); render(toString, values[i], context); buffer += toString.getOutput(); } return buffer; }
javascript
{ "resource": "" }
q55532
train
function() { var properties = { normal: [], relational: [], derived: [] }; var privateProps = this._private || {}; var relations = _.result(this, 'relations') || {}; var derived = _.result(this, 'derived') || {}; var isEditable = function(value) { if (!_.isObject(value)) { return true; } else if (_.isArray(value)) { var result = true; _.each(value, function(i) { result = result && isEditable(i); }); return result; } else { try { JSON.stringify(value); return true; } catch (ex) { return false; } } }; _.each(this.attributes, function(value, key) { if (privateProps[key]) { return; } var prop; if (relations && relations[key]) { properties.relational.push({ key: key, data: { isRelation: true, name: value.getDebugName() } }); } else if (derived && derived[key]) { properties.derived.push({ key: key, data: { isDerived: derived[key], value: value, displayValue: isEditable(value) ? JSON.stringify(value) : Object.prototype.toString.call(value) } }); } else { prop = { key: key, data: { isEditable: isEditable(value), isEditing: false, isRemovable: true, value: value } }; prop.data.displayValue = prop.data.isEditable ? JSON.stringify(value) : Object.prototype.toString.call(value); properties.normal.push(prop); } }); properties.normal = _.sortBy(properties.normal, 'key'); properties.relational = _.sortBy(properties.relational, 'key'); properties.derived = _.sortBy(properties.derived, 'key'); return properties; }
javascript
{ "resource": "" }
q55533
hasAtLeastOneKey
train
function hasAtLeastOneKey(target, attrs) { var attrsLen = attrs.length; var i = 0; var counter = 0; for (; i < attrsLen; i++) { if (target[attrs[i]] !== undefined) { counter++; } } return !!counter; }
javascript
{ "resource": "" }
q55534
train
function() { var doc = document.documentElement; return { x: (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0), y: (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0) }; }
javascript
{ "resource": "" }
q55535
processAttributeArray
train
function processAttributeArray(attrArray) { let attrs = { 'static': {}, 'dynamic': [] }; let name = []; let value = []; let item; let pushingTo = name; for (let i = 0; i < attrArray.length; i++) { item = attrArray[i]; if (item.type === 'attributenameend') { pushingTo = value; } else if (item.type === 'attributeend') { // Ensure there are no tokens in a non-dynamic attribute name for (let j = 0; j < name.length; j++) { if (typeof name[j] !== 'string') { compilerErrors.mustacheTokenCannotBeInAttributeNames(name[j]); } } if (name.length === 1) { if (value.length) { if (value.length === 1 && typeof value[0] === 'string') { value = value[0]; } } else { value = true; } attrs.static[name[0]] = flattenAttributeValues(value); } else { attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues)); if (value.length) { attrs.dynamic.push('="'); attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues)); attrs.dynamic.push('"'); } } name = []; value = []; pushingTo = name; } else if (item.type === 'attributename' || item.type === 'attributevalue') { pushingTo.push(item.value); } else if (pushingTo === name) { if (name.length === 0) { if (item.type === types.INTERPOLATOR) { compilerErrors.doubleCurlyInterpolatorsCannotBeInAttributes(item.value); } else if (item.type === types.SECTION) { attrs.dynamic.push(templateStack.processObject(item)); continue; } } pushingTo.push(item); } else { pushingTo.push(item); } } attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues)); attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues)); mergeStrings(attrs.dynamic); return attrs; }
javascript
{ "resource": "" }
q55536
loggerize
train
function loggerize(message, type) { return function() { let output = message.apply(message, arguments); if (_.isArray(output)) { logger[type].apply(logger, output); } else { logger[type](output); } // Return the message in case it's needed. (I.E. for utils.alert) return output; }; }
javascript
{ "resource": "" }
q55537
recursiveDiff
train
function recursiveDiff(vtree, elem) { var output = ''; if (vtree == null && elem != null) { // If the VTree ran out but DOM still exists output += '<ins>' + utils.elementToString(elem, chars) + '</ins>'; } else if (isVNode(vtree)) { if (!elem || elem.nodeType !== utils.NODE_TYPES.ELEMENT) { // If vtree is a VNode, but elem isn't an Element output += '<del>' + vNodeToString(vtree, true, false) + '</del>'; if (elem) { output += '<ins>' + utils.elementToString(elem, chars) + '</ins>'; } } else { // Diff elements and recurse output += diffElements(vtree, elem); } } else if (isVText(vtree)) { if (!elem || elem.nodeType !== utils.NODE_TYPES.TEXT) { // If vtree is a VText, but elem isn't a textNode output += '<del>' + escapeString(vtree.text) + '</del>'; if (elem) { output += '<ins>' + utils.elementToString(elem, chars) + '</ins>'; } } else { output += textDiff(vtree.text, elem.textContent); } } else if (isWidget(vtree)) { var widgetName; // Widgets are the construct that hold childViews if (vtree.constructor === HTMLCommentWidget) { // HTMLCommentWidget is a special case if (!elem || elem.nodeType !== utils.NODE_TYPES.COMMENT) { output += '<del>' + utils.getCommentString(escapeString(vtree.text), chars) + '</del>'; if (elem) { output += '<ins>' + utils.elementToString(elem, chars) + '</ins>'; } } else { output += utils.getCommentString(textDiff(escapeString(vtree.text), elem.textContent), chars); } } else if (vtree && vtree.view) { widgetName = vtree.view.getDebugName(); if (typeof vtree.templateToString === 'function') { widgetName = vtree.templateToString(recursiveDiff); } if (vtree.view.el !== elem) { // If the view at this position isn't bound to elem, something has gone terribly wrong output += '<del><ins>' + widgetName + '</ins></del>'; } else { output += widgetName; } } else if (vtree && typeof vtree.diff === 'function') { output += vtree.diff(elem, recursiveDiff); } else { output += '<del>[Uninitialized child view]</del>'; output += '<ins>' + utils.elementToString(elem, chars) + '</ins>'; } } return output; }
javascript
{ "resource": "" }
q55538
train
function(model, options) { Backbone.Collection.prototype._addReference.call(this, model, options); if (ComponentWidget.isComponent(model) && model.exposedEvents) { var events = model.exposedEvents; if (events === true) { model.model.on('all', this._onModelEvent, this); } else if (events.length) { for (let i = 0; i < events.length; i++) { this.bindExposedEvent(events[i], model); } } } }
javascript
{ "resource": "" }
q55539
train
function(model, options) { if (ComponentWidget.isComponent(model) && model.model && model.exposedEvents) { var events = model.exposedEvents; if (events === true) { model.model.off('all', this._onModelEvent, this); } else if (events.length) { for (let i = 0; i < events.length; i++) { this.stopListening(model.model, events[i]); } } } Backbone.Collection.prototype._removeReference.call(this, model, options); }
javascript
{ "resource": "" }
q55540
train
function() { if (!this.cid) { this.cid = _.uniqueId('collection'); } return this.constructor.debugName ? this.constructor.debugName + this.cid.replace('collection', '') : this.cid; }
javascript
{ "resource": "" }
q55541
atDelim
train
function atDelim(str, position, delim) { if (str.charAt(position) !== delim.charAt(0)) { return false; } for (let i = 1, l = delim.length; i < l; i++) { if (str.charAt(position + i) !== delim.charAt(i)) { return false; } } return true; }
javascript
{ "resource": "" }
q55542
trimWhitespace
train
function trimWhitespace(line) { let whitespaceIndicies = []; let allWhitespace = true; let seenAnyTag = false; let newLine = new Array(line.length); for (let i = 0; i < line.length; i++) { let obj = line[i]; newLine[i] = obj; if (typeof obj === 'string') { if (!nonWhitespace.test(obj)) { whitespaceIndicies.push(i); } else { allWhitespace = false; } } else { seenAnyTag = true; if (nonWhitespaceNodes[obj.type] === true) { allWhitespace = false; } } // Bail out if we've seen a non-whitespace if (!allWhitespace) { return line; } } // Remove the whitespace nodes if this line consists of: // - only whitespace text // - no Interpolators or Unescaped Interpolators // - at least one Mustache tag if (allWhitespace && seenAnyTag) { for (let i = 0; i < whitespaceIndicies.length; i++) { let index = whitespaceIndicies[i]; let obj = newLine[index]; newLine[index] = { type: types.TEXT, original: obj, length: obj.length }; } } return newLine; }
javascript
{ "resource": "" }
q55543
train
function (opt) { var cap = new Captcha(opt); cap.use(drawBackground); cap.use(drawLines); cap.use(drawText); cap.use(drawLines); return cap; }
javascript
{ "resource": "" }
q55544
train
function() { this._super.init && this._super.init.apply(this, arguments); var baseOptions = this.baseOptions(); var optionsFromConfig = this.config().options; var mergedOptions = baseOptions.map(function(availableOption) { var option = merge(true, availableOption); if ((optionsFromConfig[option.name] !== undefined) && (option.default !== undefined)) { option.default = optionsFromConfig[option.name]; option.description = option.description + ' (configured in ' + configPath + ')'; } return option; }); // Merge custom strategy options if specified var strategy = optionsFromConfig.strategy; if (typeof strategy === 'object' && Array.isArray(strategy.availableOptions)) { mergedOptions = mergedOptions.concat(strategy.availableOptions); } this.registerOptions({ availableOptions: mergedOptions }); }
javascript
{ "resource": "" }
q55545
train
function() { if (this._baseOptions) { return this._baseOptions; } var strategies = this.strategies(); var strategyOptions = Object.keys(strategies).reduce(function(result, strategyName) { var options = strategies[strategyName].availableOptions; if (Array.isArray(options)) { // Add strategy qualifier to option descriptions options.forEach(function(option) { option.description = "when strategy is '" + strategyName + "', " + option.description; }); result = result.concat(options); } return result; }, []); return this._baseOptions = availableOptions.concat(strategyOptions); }
javascript
{ "resource": "" }
q55546
train
function(entity) { assert(entity.PartitionKey, 'entity is missing \'PartitionKey\''); assert(entity.RowKey, 'entity is missing \'RowKey\''); assert(entity['odata.etag'], 'entity is missing \'odata.etag\''); assert(entity.Version, 'entity is missing \'Version\''); this._partitionKey = entity.PartitionKey; this._rowKey = entity.RowKey; this._version = entity.Version; this._properties = this.__deserialize(entity); this._etag = entity['odata.etag']; }
javascript
{ "resource": "" }
q55547
train
function(b1, b2) { var mismatch = 0; mismatch |= !(b1 instanceof Buffer); mismatch |= !(b2 instanceof Buffer); mismatch |= b1.length !== b2.length; if (mismatch === 1) { return false; } var n = b1.length; for (var i = 0; i < n; i++) { mismatch |= b1[i] ^ b2[i]; } return mismatch === 0; }
javascript
{ "resource": "" }
q55548
train
function(result) { if (!result.nextPartitionKey && !result.nextRowKey) { return null; } return ( encodeURIComponent(result.nextPartitionKey || '').replace(/~/g, '%7e') + '~' + encodeURIComponent(result.nextRowKey || '').replace(/~/g, '%7e') ); }
javascript
{ "resource": "" }
q55549
train
function(token) { if (token === undefined || token === null) { return { nextPartitionKey: undefined, nextRowKey: undefined, }; } assert(typeof token === 'string', 'Continuation token must be a string if ' + 'not undefined'); // Split at tilde (~) token = token.split('~'); assert(token.length === 2, 'Expected an encoded continuation token with ' + 'a single tilde as separator'); return { nextPartitionKey: decodeURIComponent(token[0]), nextRowKey: decodeURIComponent(token[1]), }; }
javascript
{ "resource": "" }
q55550
train
function(continuation) { var continuation = decodeContinuationToken(continuation); return ClassProps.__aux.queryEntities({ filter: filter, top: Math.min(options.limit, 1000), nextPartitionKey: continuation.nextPartitionKey, nextRowKey: continuation.nextRowKey, }).then(function(data) { return { entries: data.entities.map(function(entity) { return new Class(entity); }), continuation: encodeContinuationToken(data), }; }); }
javascript
{ "resource": "" }
q55551
realIP
train
function realIP (request) { return request.ip || request.headers['x-real-ip'] || request.headers['x-forwarded-for'] || request.info['remoteAddress'] }
javascript
{ "resource": "" }
q55552
getAllKeys
train
function getAllKeys (objArray) { let keys = [] _.forEach(objArray, function (row) { if (!row || typeof row === 'string') return keys = keys.concat(Object.keys(row)) }) return _.union(keys) }
javascript
{ "resource": "" }
q55553
getMaxLength
train
function getMaxLength (keys, objArray) { const maxRowLength = {} _.forEach(keys, function (key) { maxRowLength[key] = cleanString(key).length }) _.forEach(objArray, function (objRow) { _.forEach(objRow, function (val, key) { const rowLength = cleanString(val).length if (maxRowLength[key] < rowLength) { maxRowLength[key] = rowLength } }) }) return maxRowLength }
javascript
{ "resource": "" }
q55554
train
function (printArray, format, preProcessor, settings) { format = format || '' preProcessor = preProcessor || [] settings = settings || defaultSettings const INDENT = emptyString(settings.indent) const ROW_SPACER = emptyString(settings.rowSpace) const headings = getAllKeys(printArray) const maxLength = getMaxLength(headings, printArray) const maxLengths = Object.keys(maxLength).reduce((s, k) => s + maxLength[k], 0) // print headline const headline = [] const seperator = [] _.forEach(headings, function (header, i) { headline.push(toLength(header, maxLength[header], 'c')) seperator.push(new Array(maxLength[header] + 1).join('-')) }) console.log(INDENT + seperator.join(ROW_SPACER)) console.log(INDENT + headline.join(ROW_SPACER)) console.log(INDENT + seperator.join(ROW_SPACER)) // print rows _.forEach(printArray, function (row) { const line = [] if (row === null || typeof row === 'string') { if (row === null || row === '') { return console.log('') } return console.log(chalk.grey.bold(toLength(row || '', maxLengths, 'l'))) } _.forEach(headings, function (header, i) { let str = row[header] || '' if (_.isFunction(preProcessor[i])) { str = preProcessor[i](str) || str } line.push(toLength(str, maxLength[header], format.substr(i, 1))) }) console.log(INDENT + line.join(ROW_SPACER)) }) }
javascript
{ "resource": "" }
q55555
setHeaders
train
function setHeaders (headers, ratelimit, XHeaders = false) { if (XHeaders) { headers['X-Rate-Limit-Limit'] = ratelimit.limit headers['X-Rate-Limit-Remaining'] = ratelimit.remaining > 0 ? ratelimit.remaining : 0 headers['X-Rate-Limit-Reset'] = ratelimit.reset } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After headers['Retry-After'] = Math.ceil(ratelimit.reset / 1000) }
javascript
{ "resource": "" }
q55556
train
function(name, property, value, types) { if (!(types instanceof Array)) { types = [types]; } if (types.indexOf(typeof value) === -1) { debug('%s \'%s\' expected %j got: %j', name, property, types, value); throw new Error(name + ' \'' + property + '\' expected one of type(s): \'' + types.join(',') + '\' got type: \'' + typeof value + '\''); } }
javascript
{ "resource": "" }
q55557
train
function(slug) { var base64 = slug .replace(/-/g, '+') .replace(/_/g, '/') + '=='; return Buffer.from(base64, 'base64'); }
javascript
{ "resource": "" }
q55558
train
function(bufferView, entryIndex) { return bufferView.toString('base64', entryIndex * SLUGID_SIZE, SLUGID_SIZE * (entryIndex + 1)) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/==/g, ''); }
javascript
{ "resource": "" }
q55559
train
function(str) { // Check for empty string if (str === '') { return '!'; } // 1. URL encode // 2. URL encode all exclamation marks (replace ! with %21) // 3. URL encode all tilde (replace ~ with %7e) // This ensures that when using ~ as separator in CompositeKey we can // do prefix matching // 4. Replace % with exclamation marks for Azure compatibility return encodeURIComponent(str) .replace(/!/g, '%21') .replace(/~/g, '%7e') .replace(/%/g, '!'); }
javascript
{ "resource": "" }
q55560
train
function(mapping, key) { // Set key this.key = key; // Set key type assert(mapping[this.key], 'key \'' + key + '\' is not defined in mapping'); assert(mapping[this.key] instanceof Types.PositiveInteger, 'key \'' + key + '\' must be a PositiveInteger type'); this.type = mapping[this.key]; // Set covers this.covers = [key]; }
javascript
{ "resource": "" }
q55561
train
function(mapping, keys) { assert(keys instanceof Array, 'keys must be an array'); assert(keys.length > 0, 'CompositeKey needs at least one key'); // Set keys this.keys = keys; // Set key types this.types = []; for (var i = 0; i < keys.length; i++) { assert(mapping[keys[i]], 'key \'' + keys[i] + '\' is not defined in mapping'); this.types[i] = mapping[keys[i]]; } // Set covers this.covers = keys; }
javascript
{ "resource": "" }
q55562
assembleUrl
train
function assembleUrl (parts, insertPort = false) { let result; if (insertPort) { result = `${parts.protocol}://${parts.host}:${parts.port}`; } else { result = `${parts.protocol}://${parts.host}`; } if (parts.path) { result = `${result}/${parts.path}`; } return result; }
javascript
{ "resource": "" }
q55563
logConnectionEvents
train
function logConnectionEvents (conn) { // Emitted after getting disconnected from the db. // _readyState: 0 conn.on('disconnected', () => { conn.$logger.debug('Disconnected!') }) // Emitted when this connection successfully connects to the db. // May be emitted multiple times in reconnected scenarios. // _readyState: 1 conn.on('connected', () => { conn.$logger.success('Connected!') }) // Emitted when connection.{open,openSet}() is executed on this connection. // _readyState: 2 conn.on('connecting', () => { conn.$logger.info('Connecting...') }) // Emitted when connection.close() was executed. // _readyState: 3 conn.on('disconnecting', () => { conn.$logger.debug('Disconnecting...') }) // Emitted when an error occurs on this connection. conn.on('error', (error) => { conn.$logger.error(error) }) // Emitted after we connected and onOpen is executed // on all of this connections models. conn.on('open', () => { conn.$logger.debug('Connection opened!') }) // Emitted after we connected and subsequently disconnected, // followed by successfully another successfull connection. conn.on('reconnected', () => { conn.$logger.debug('Reconnected!') }) // Emitted in a replica-set scenario, when all nodes specified // in the connection string are connected. conn.on('fullsetup', () => { conn.$logger.debug('ReplicaSet ready!') }) }
javascript
{ "resource": "" }
q55564
connect
train
async function connect (mongoose, connectionName, connectionOpts) { const isDefault = connectionName === 'default' // Normalize and destructure connection options if (typeof connectionOpts === 'string') { connectionOpts = { uri: connectionOpts } } let { uri, options, forceReconnect } = connectionOpts // Apply default options // https://mongoosejs.com/docs/connections.html#options options = { useNewUrlParser: true, useCreateIndex: true, ...options } // Manualy create connection let conn if (isDefault) { conn = mongoose.connection } else { conn = new mongoose.Connection(mongoose) mongoose.connections.push(conn) } // $logger helper conn.$logger = isDefault ? consola : consola.withTag(connectionName) // Log connection events logConnectionEvents(conn) // $connect helper conn.$connect = () => { return new Promise((resolve, reject) => { conn.openUri(uri, options, (error) => { if (error) { reject(error) } else { resolve(conn) } }) }) } // Make accessable via mongoose.$connectionName mongoose['$' + connectionName] = conn // Setup force reconnect if (forceReconnect) { const timeout = forceReconnect === true ? 1000 : forceReconnect conn.on('error', () => { conn.close() }) conn.on('disconnected', () => { setTimeout(() => { conn.$connect() }, timeout) }) } // Connect await conn.$connect() await conn.$initialConnection }
javascript
{ "resource": "" }
q55565
positionOfMigration
train
function positionOfMigration(migrations, filename) { for (var i = 0; i < migrations.length; ++i) { if (migrations[i].title == filename) { return i; } } return -1; }
javascript
{ "resource": "" }
q55566
migrations
train
function migrations(direction, lastMigrationNum, migrateTo) { var isDirectionUp = direction === 'up', hasMigrateTo = !!migrateTo, migrateToNum = hasMigrateTo ? parseInt(migrateTo, 10) : undefined, migrateToFound = !hasMigrateTo; var migrationsToRun = fs.readdirSync('migrations') .filter(function (file) { var formatCorrect = file.match(/^\d+.*\.js$/), migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10), isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum, isFile = fs.statSync(path.join('migrations', file)).isFile(); if (isFile && !formatCorrect) { console.log('"' + file + '" ignored. Does not match migration naming schema'); } return formatCorrect && isRunnable && isFile; }).sort(function (a, b) { var aMigrationNum = parseInt(a.match(/^\d+/)[0], 10), bMigrationNum = parseInt(b.match(/^\d+/)[0], 10); if (aMigrationNum > bMigrationNum) { return isDirectionUp ? 1 : -1; } if (aMigrationNum < bMigrationNum) { return isDirectionUp ? -1 : 1; } return 0; }).filter(function(file){ var formatCorrect = file.match(/^\d+.*\.js$/), migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10), isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum; if (hasMigrateTo) { if (migrateToNum === migrationNum) { migrateToFound = true; } if (isDirectionUp) { isRunnable = isRunnable && migrateToNum >= migrationNum; } else { isRunnable = isRunnable && migrateToNum < migrationNum; } } return formatCorrect && isRunnable; }).map(function(file){ return 'migrations/' + file; }); if (!migrateToFound) { return abort('migration `'+ migrateTo + '` not found!'); } return migrationsToRun; }
javascript
{ "resource": "" }
q55567
create
train
function create(name) { var path = 'migrations/' + name + '.js'; log('create', join(process.cwd(), path)); fs.writeFileSync(path, template); }
javascript
{ "resource": "" }
q55568
performMigration
train
function performMigration(direction, migrateTo, next) { if (!next && Object.prototype.toString.call(migrateTo) === '[object Function]') { next = migrateTo; migrateTo = undefined; } if (!next) { next = function(err) { if (err) { console.error(err); process.exit(1); } else { process.exit(); } } } var db = require('./lib/db'); db.getConnection(dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) { if (err) { return next(new verror.WError(err, 'Error connecting to database')); } var migrationCollection = db.migrationCollection, dbConnection = db.connection; migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) { if (err) { return next(new verror.WError(err, 'Error querying migration collection')); } var lastMigration = migrationsRun[0], lastMigrationNum = lastMigration ? lastMigration.num : 0; migrate({ migrationTitle: 'migrations/.migrate', db: dbConnection, migrationCollection: migrationCollection }); migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){ var mod = require(process.cwd() + '/' + path); migrate({ num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10), title: path, up: mod.up, down: mod.down}); }); //Revert working directory to previous state process.chdir(previousWorkingDirectory); var set = migrate(); set.on('migration', function(migration, direction){ log(direction, migration.title); }); set.on('save', function(){ log('migration', 'complete'); return next(); }); set[direction](null, lastMigrationNum); }); }); }
javascript
{ "resource": "" }
q55569
on
train
function on(el, eventName, callback) { if (el.addEventListener) { el.addEventListener(eventName, callback, false); } else if (el.attachEvent) { el.attachEvent('on'+eventName, function(e) { callback.call(el, e || window.event); }); } }
javascript
{ "resource": "" }
q55570
sightglass
train
function sightglass(obj, keypath, callback, options) { return new Observer(obj, keypath, callback, options) }
javascript
{ "resource": "" }
q55571
Observer
train
function Observer(obj, keypath, callback, options) { this.options = options || {} this.options.adapters = this.options.adapters || {} this.obj = obj this.keypath = keypath this.callback = callback this.objectPath = [] this.update = this.update.bind(this) this.parse() if (isObject(this.target = this.realize())) { this.set(true, this.key, this.target, this.callback) } }
javascript
{ "resource": "" }
q55572
train
function () { var player = this; // This is the original normal protocol, used while in record mode but not recording. this.stopProtocol = this.controller.connection.protocol; // This consumes all frame data, making the device act as if not streaming this.playbackProtocol = function (data) { // The old protocol still needs to emit events, so we use it, but intercept Frames var eventOrFrame = player.stopProtocol(data); if (eventOrFrame instanceof Leap.Frame) { if (player.pauseOnHand) { if (data.hands.length > 0) { player.userHasControl = true; player.controller.emit('playback.userTakeControl'); player.setGraphic(); player.idle(); } else if (data.hands.length == 0) { if (player.userHasControl && player.resumeOnHandLost) { player.userHasControl = false; player.controller.emit('playback.userReleaseControl'); player.setGraphic('wave'); } } } // prevent the actual frame from getting through return {type: 'playback'} } else { return eventOrFrame; } }; // This pushes frame data, and watches for hands to auto change state. // Returns the eventOrFrame without modifying it. this.recordProtocol = function (data) { var eventOrFrame = player.stopProtocol(data); if (eventOrFrame instanceof Leap.Frame) { player.recordFrameHandler(data); } return eventOrFrame; }; // Copy methods/properties from the default protocol over for (var property in this.stopProtocol) { if (this.stopProtocol.hasOwnProperty(property)) { this.playbackProtocol[property] = this.stopProtocol[property] this.recordProtocol[property] = this.stopProtocol[property] } } // todo: this is messy. Should cover all cases, not just active playback! if (this.state == 'playing') { this.controller.connection.protocol = this.playbackProtocol } }
javascript
{ "resource": "" }
q55573
train
function (options) { var player = this; // otherwise, the animation loop may try and play non-existant frames: this.pause(); // this is called on the context of the recording var loadComplete = function (frames) { this.setFrames(frames); if (player.recording != this){ console.log('recordings changed during load'); return } if (player.autoPlay) { player.play(); if (player.pauseOnHand && !player.controller.streaming() ) { player.setGraphic('connect'); } } player.controller.emit('playback.recordingSet', this); }; this.recording = options; // Here we turn the existing argument in to a recording // this allows frames to be added to the existing object via ajax // saving ajax requests if (!(options instanceof Recording)){ this.recording.__proto__ = Recording.prototype; Recording.call(this.recording, { timeBetweenLoops: this.options.timeBetweenLoops, loop: this.options.loop, loadProgress: function(recording, percentage, oEvent){ player.controller.emit('playback.ajax:progress', recording, percentage, oEvent); } }); } if ( this.recording.loaded() ) { loadComplete.call(this.recording, this.recording.frameData); } else if (options.url) { this.controller.emit('playback.ajax:begin', this, this.recording); // called in the context of the recording this.recording.loadFrameData(function(frames){ loadComplete.call(this, frames); player.controller.emit('playback.ajax:complete', player, this); }); } else if (options.compressedRecording) { this.recording.loadCompressedRecording(options.compressedRecording, function(frames){ loadComplete.call(this, frames); }); } return this; }
javascript
{ "resource": "" }
q55574
createBadgeStyle
train
function createBadgeStyle(style) { return React.createClass({ displayName: Badge.displayName + style, render() { return <Badge {...this.props} style={style.toLowerCase()} />; } }); }
javascript
{ "resource": "" }
q55575
createLabelStyle
train
function createLabelStyle(style) { return React.createClass({ displayName: Label.displayName + style, render() { return <Label {...this.props} style={style.toLowerCase()} />; } }); }
javascript
{ "resource": "" }
q55576
train
function() { var str = this.trim(); str = this.charAt(0).toUpperCase() + this.slice(1); if (!str.match(/[?!\.]$/)) str = str+'.'; return str; }
javascript
{ "resource": "" }
q55577
train
function() { //Pluralizes the first part in "<x> of <y>" var bundle = this.match(/(\w+)\sof\s\w+/); if (bundle) return this.replace(bundle[1], bundle[1].getPlural()); str = this.replace(/([^aeiou])y$/, '$1ies'); if (str==this) str = str.replace(/([ch|sh|x|s|o])$/, '$1es'); if (str==this) str += 's'; return str; }
javascript
{ "resource": "" }
q55578
train
function() { var n = this; if (n<20) { return [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ][n]; } else if (n<100) { var tens = Math.floor(n/10); var ones = n%10; return [ 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ][tens-2]+((ones>0) ? '-'+ones.toWord() : ''); } else if (n<1000) { var hundreds = Math.floor(n/100); var tens = n%100; return hundreds.toWord()+' hundred and '+tens.toWord(); } var places = ['thousand', 'million', 'billion', 'trillion']; var d = Math.floor(new String(n).length/3); var pow = Math.pow(1000, d); var principle = Math.floor(n/pow); var remainder = n%pow; return principle.toWord()+' '+places[d-1]+' '+remainder.toWord(); }
javascript
{ "resource": "" }
q55579
train
function() { if (this.length==0) return false; //Don't want to modify the list! var items = this; if (items.length>1) items[items.length-1] = 'and '+items.getLast(); if (items.length>2) return items.join(', '); return items.join(' '); }
javascript
{ "resource": "" }
q55580
train
function(config) { var required = ['world_path', 'start_room']; required.each(function(key) { if (!config[key]) { sys.puts("Required config option \""+key+"\" not supplied."); process.exit(); } }); this.set('name', config.world_name); this.config = config; this.worldPath = require('path').join(config.world_path); this.defaultRoom = config.start_room; this.players = this.players; this.rooms = this.rooms; this.items = this.items; this.initializeRooms(); }
javascript
{ "resource": "" }
q55581
train
function(player) { player.world = this; this.players[player.name.toLowerCase()] = player; this.announce(player.name+" has entered the world."); this.loadPlayerData(player); }
javascript
{ "resource": "" }
q55582
train
function(name, player, target) { if (!name) return; var that = this; if (!this.menus[name]) { var path; //If there's a target, we'll assume it's a conversation. if (target) path = this.scriptPath+name; else path = this.menuPath+name; this.loadFile(path, function(e,menu) { if (e) log_error(e); if (!menu) return; that.menus[name] = menu; player.enterMenu(menu, target); }); } else { player.enterMenu(this.menus[name], target); } }
javascript
{ "resource": "" }
q55583
train
function(path, callback, opts) { if (!callback) callback = function() { }; var fallbacks = []; if (path.each) { if (path.length==0) return; fallbacks = path; path = fallbacks.shift()+""; } //Stuff that will make us not want to load files. if (this.failedFiles.contains(path)) return; opts = opts || {}; var file = this.worldPath+path+'.js'; if (opts.rootPath) file = path+'.js'; var my = this; var err; var handleData = function(e,raw) { data = false; if (!raw) { err = e; my.failedFiles.push(path); /* Continue down our list of fallbacks. */ if (fallbacks.length>0) { my.loadFile(fallbacks, callback, opts); } else { log_error("File not found: "+file); } } else { try { eval('data='+raw); } catch (e) { log_error(e); } } callback(err, data); return data; }; if (opts.sync) { try { var data = fs.readFileSync(file); } catch (e) { this.failedFiles.push(path); /* Continue down our list of fallbacks. */ if (fallbacks.length>0) { return this.loadFile(fallbacks, callback, opts); } else return e; } return handleData(false,data); } else { fs.readFile(file, handleData); } }
javascript
{ "resource": "" }
q55584
Gauge
train
function Gauge (el, opts) { if (!(this instanceof Gauge)) return new Gauge(el, opts); this._el = el; this._opts = xtend(defaultOpts, opts); this._size = this._opts.size; this._radius = this._size * 0.9 / 2; this._cx = this._size / 2; this._cy = this._cx; this._preserveAspectRatio = this._opts.preserveAspectRatio; this._min = this._opts.min; this._max = this._opts.max; this._range = this._max - this._min; this._majorTicks = this._opts.majorTicks; this._minorTicks = this._opts.minorTicks; this._needleWidthRatio = this._opts.needleWidthRatio; this._needleContainerRadiusRatio = this._opts.needleContainerRadiusRatio; this._transitionDuration = this._opts.transitionDuration; this._label = this._opts.label; this._zones = this._opts.zones || []; this._clazz = opts.clazz; this._initZones(); this._render(); }
javascript
{ "resource": "" }
q55585
_parseSoapFaultDetail
train
function _parseSoapFaultDetail(detailNode){ var errors = []; var i, childNodes = detailNode.childNodes, n = childNodes.length, childNode; for (i = 0; i < n; i++) { childNode = childNodes[i]; if (childNode.nodeType !== 1) { continue; } switch (childNode.nodeName){ case "Error": errors.push({ ErrorCode: _getAttribute(childNode, "ErrorCode"), Description: _getAttribute(childNode, "Description"), Source: _getAttribute(childNode, "Source"), HelpFile: _getAttribute(childNode, "HelpFile") }); break; default: } } return errors; }
javascript
{ "resource": "" }
q55586
train
function(){ var fieldNames = [], i, n = this._fieldCount; for (i = 0; i < n; i++) fieldNames[i] = this.fieldOrder[i]; return fieldNames; }
javascript
{ "resource": "" }
q55587
train
function(index){ var fieldName = this.fieldOrder[index]; if (!fieldName) Xmla.Exception._newError( "INVALID_FIELD", "Xmla.Rowset.fieldDef", index )._throw(); return fieldName; }
javascript
{ "resource": "" }
q55588
train
function(name){ if (_isNum(name)) name = this.fieldName(name); return this.fieldDef(name).getter.call(this); }
javascript
{ "resource": "" }
q55589
train
function(){ if (this._cellset) this._cellset.reset(); if (this._axes) { var i, n, axis; for (i = 0, n = this.axisCount(); i < n; i++){ this.getAxis(i).reset(); } } }
javascript
{ "resource": "" }
q55590
train
function(){ if (this._slicer) { this._slicer.close(); } var i, n = this._numAxes; for (i = 0; i < n; i++) { this.getAxis(i).close(); } this._cellset.close(); this._cellset = null; this._root = null; this._axes = null; this._axesOrder = null; this._numAxes = null; this._slicer = null; }
javascript
{ "resource": "" }
q55591
train
function(){ var hierarchyNames = [], i, n = this.numHierarchies; for (i = 0; i < n; i++) hierarchyNames[i] = this._hierarchyOrder[i]; return hierarchyNames; }
javascript
{ "resource": "" }
q55592
train
function(callback, scope, args) { var mArgs = [null]; if (!scope) { scope = this; } if (args) { if (!_isArr(args)) { args = [args]; } mArgs = mArgs.concat(args); } var ord; while (ord !== -1 && this.hasMoreCells()){ ord = this.nextCell(); mArgs[0] = this.readCell(); if (callback.apply(scope, mArgs)===false) { return false; } } this._idx = 0; return true; }
javascript
{ "resource": "" }
q55593
train
function(){ var cell, cells = {}, i = 0, count = this._cellCount; for (i = 0; i < count; i++){ cell = this.readCell(); cells[cell.ordinal] = cell; this.nextCell(); } return cells; }
javascript
{ "resource": "" }
q55594
train
function(ordinal, object) { var node, ord, idx, lastIndex = this.cellCount() - 1; idx = ordinal > lastIndex ? lastIndex : ordinal; while(true) { node = this._cellNodes[idx]; ord = this._getCellOrdinal(node); if (ord === ordinal) return this.getByIndex(idx, object); else if (ord > ordinal) idx--; else return null; } }
javascript
{ "resource": "" }
q55595
train
function(ordinal){ var cellNodes = this._cellNodes, n = cellNodes.length, index = Math.min(ordinal, n-1), cellOrdinal, node ; while(index >= 0) { //get the node at the current index node = cellNodes[index]; cellOrdinal = this._getCellOrdinal(node); if (cellOrdinal === ordinal) { return index; } else if (cellOrdinal > ordinal) { index--; } else { return -1; } } return -1; }
javascript
{ "resource": "" }
q55596
train
function(){ var funcstring, stack = ""; if (this.args) { var func = this.args.callee; while (func){ funcstring = String(func); func = func.caller; } } return stack; }
javascript
{ "resource": "" }
q55597
wk
train
function wk(dt) { var jan1 = new Date(Date.UTC(y(dt), 0, 1)); return trunc(daydiff(jan1, dt)/7); }
javascript
{ "resource": "" }
q55598
check_bymonth
train
function check_bymonth(rules, dt) { if(!rules || !rules.length) return true; return rules.indexOf(m(dt)) !== -1; }
javascript
{ "resource": "" }
q55599
bymonth
train
function bymonth(rules, dt) { if(!rules || !rules.length) return dt; var candidates = rules.map(function(rule) { var delta = rule-m(dt); if(delta < 0) delta += 12; var newdt = add_m(new Date(dt), delta); set_d(newdt, 1); return newdt; }); var newdt = sort_dates(candidates).shift(); return newdt || dt; }
javascript
{ "resource": "" }