_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q100
train
function() { var behaviorEvents = _.result(this, 'events'); var viewEvents = this.view.events; if (!viewEvents) { if (!behaviorEvents) { return; } else { viewEvents = {}; } } var namespacedEvents = this.__namespaceEvents(behaviorEvents); var boundBehaviorEvents = this.__bindEventCallbacksToBehavior(namespacedEvents); if (_.isFunction(viewEvents)) { this.view.events = _.wrap(_.bind(viewEvents, this.view), function(viewEventFunction) { return _.extend(boundBehaviorEvents, viewEventFunction()); }); } else if (_.isObject(viewEvents)) { this.view.events = _.extend(boundBehaviorEvents, viewEvents); } }
javascript
{ "resource": "" }
q101
train
function(eventHash) { // coped from Backbone var delegateEventSplitter = /^(\S+)\s*(.*)$/; var namespacedEvents = {}; var behaviorId = this.cid; _.each(eventHash, function(value, key) { var splitEventKey = key.match(delegateEventSplitter); var eventName = splitEventKey[1]; var selector = splitEventKey[2]; var namespacedEventName = eventName + '.behavior.' + behaviorId; namespacedEvents[[namespacedEventName, selector].join(' ')] = value; }); return namespacedEvents; }
javascript
{ "resource": "" }
q102
train
function(name) { if (name === 'change' || name.indexOf('change:') === 0) { View.prototype.trigger.apply(this.view, arguments); } if (name.indexOf('change:hide:') === 0) { this.view.render(); } NestedCell.prototype.trigger.apply(this, arguments); }
javascript
{ "resource": "" }
q103
train
function(el, template, context, opts) { opts = opts || {}; if (_.isString(template)) { opts.newHTML = template; } templateRenderer.render(el, template, context, opts); }
javascript
{ "resource": "" }
q104
train
function() { this.undelegateEvents(); // always undelegate events - backbone sometimes doesn't. Backbone.View.prototype.delegateEvents.call(this); this.__generateFeedbackBindings(); this.__generateFeedbackCellCallbacks(); _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.delegateEvents(); } }); }
javascript
{ "resource": "" }
q105
train
function() { Backbone.View.prototype.undelegateEvents.call(this); _.each(this.getTrackedViews(), function(view) { view.undelegateEvents(); }); }
javascript
{ "resource": "" }
q106
train
function($el, options) { options = options || {}; var view = this; if (!this.isAttachedToParent()) { this.__pendingAttachInfo = { $el: $el, options: options }; return this.render().done(function() { if (!view.__attachedCallbackInvoked && view.isAttached()) { view.__invokeAttached(); } view.__isAttachedToParent = true; }); } return $.Deferred().resolve().promise(); }
javascript
{ "resource": "" }
q107
train
function() { var wasAttached; if (this.isAttachedToParent()) { wasAttached = this.isAttached(); // Detach view from DOM this.trigger('before-dom-detach'); if (this.injectionSite) { this.$el.replaceWith(this.injectionSite); this.injectionSite = undefined; } else { this.$el.detach(); } if (wasAttached) { this.__invokeDetached(); } this.undelegateEvents(); this.__isAttachedToParent = false; } }
javascript
{ "resource": "" }
q108
train
function() { this.trigger('before-dispose'); this.trigger('before-dispose-callback'); this._dispose(); // Detach DOM and deactivate the view this.detach(); this.deactivate(); // Clean up child views first this.__disposeChildViews(); // Remove view from DOM if (this.$el) { this.remove(); } // Unbind all local event bindings this.off(); this.stopListening(); if (this.viewState) { this.viewState.off(); this.viewState.stopListening(); } if (this.feedbackCell) { this.feedbackCell.off(); this.feedbackCell.stopListening(); } // Delete the dom references delete this.$el; delete this.el; this.__isDisposed = true; this.trigger('after-dispose'); }
javascript
{ "resource": "" }
q109
train
function(view, options) { options = options || {}; this.unregisterTrackedView(view); if (options.child || !options.shared) { this.__childViews[view.cid] = view; } else { this.__sharedViews[view.cid] = view; } return view; }
javascript
{ "resource": "" }
q110
train
function(options) { var trackedViewsHash = this.getTrackedViews(options); _.each(trackedViewsHash, function(view) { this.unregisterTrackedView(view, options); }, this); }
javascript
{ "resource": "" }
q111
train
function(to, evt, indexMap) { var result, feedbackToInvoke = _.find(this.feedback, function(feedback) { var toToCheck = feedback.to; if (_.isArray(toToCheck)) { return _.contains(toToCheck, to); } else { return to === toToCheck; } }), feedbackCellField = to; if (feedbackToInvoke) { if (indexMap) { feedbackCellField = this.__substituteIndicesUsingMap(to, indexMap); } result = feedbackToInvoke.then.call(this, evt, indexMap); this.__processFeedbackThenResult(result, feedbackCellField); } }
javascript
{ "resource": "" }
q112
train
function(viewOptions) { var view = this; if (!_.isEmpty(this.behaviors)) { view.__behaviorInstances = {}; _.each(this.behaviors, function(behaviorDefinition, alias) { if (!_.has(behaviorDefinition, 'behavior')) { behaviorDefinition = {behavior: behaviorDefinition}; } var BehaviorClass = behaviorDefinition.behavior; if (!(BehaviorClass && _.isFunction(BehaviorClass))) { throw new Error('Incorrect behavior definition. Expected key "behavior" to be a class but instead got ' + String(BehaviorClass)); } var behaviorOptions = _.pick(behaviorDefinition, function(value, key) { return key !== 'behavior'; }); behaviorOptions.view = view; behaviorOptions.alias = alias; var behaviorAttributes = behaviorDefinition.attributes || {}; var behaviorInstance = view.__behaviorInstances[alias] = new BehaviorClass(behaviorAttributes, behaviorOptions, viewOptions); // Add the behavior's mixin fields to the view's public API if (behaviorInstance.mixin) { var mixin = _.result(behaviorInstance, 'mixin'); _.each(mixin, function(field, fieldName) { // Default to a view's field over a behavior mixin if (_.isUndefined(view[fieldName])) { if (_.isFunction(field)) { // Behavior mixin functions will be behavior-scoped - the context will be the behavior. view[fieldName] = _.bind(field, behaviorInstance); } else { view[fieldName] = field; } } }); } }); } }
javascript
{ "resource": "" }
q113
train
function(injectionSiteName, previousView, newView, options) { var newInjectionSite, currentPromise, previousDeferred = $.Deferred(); this.attachView(injectionSiteName, previousView, options); options.cachedInjectionSite = previousView.injectionSite; newInjectionSite = options.newInjectionSite = $('<span inject="' + injectionSiteName + '">'); if (options.addBefore) { previousView.$el.before(newInjectionSite); } else { previousView.$el.after(newInjectionSite); } // clear the injections site so it isn't replaced back into the dom. previousView.injectionSite = undefined; // transition previous view out previousView.transitionOut(previousDeferred.resolve, options); // transition new current view in currentPromise = this.__transitionInView(newInjectionSite, newView, options); // return a combined promise return $.when(previousDeferred.promise(), currentPromise); }
javascript
{ "resource": "" }
q114
train
function($el, newView, options) { var currentDeferred = $.Deferred(), parentView = this; options = _.extend({}, options); _.defaults(options, { parentView: this, newView: newView }); newView.transitionIn(function() { parentView.attachView($el, newView, options); }, currentDeferred.resolve, options); return currentDeferred.promise(); }
javascript
{ "resource": "" }
q115
train
function() { var parentView = this; this.__injectionSiteMap = {}; this.__lastTrackedViews = {}; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent() && view.injectionSite) { parentView.__injectionSiteMap[view.injectionSite.attr('inject')] = view; } parentView.__lastTrackedViews[view.cid] = view; }); }
javascript
{ "resource": "" }
q116
train
function() { // Need to check if each view is attached because there is no guarentee that if parent is attached, child is attached. if (!this.__attachedCallbackInvoked) { this.trigger('before-attached-callback'); this._attached(); this.__attachedCallbackInvoked = true; _.each(this.getTrackedViews(), function(view) { if (view.isAttachedToParent()) { view.__invokeAttached(); } }); } }
javascript
{ "resource": "" }
q117
train
function() { if (this.__attachedCallbackInvoked) { this.trigger('before-detached-callback'); this._detached(); this.__attachedCallbackInvoked = false; } _.each(this.getTrackedViews(), function(view) { // If the tracked view is currently attached to the parent, then invoke detatched on it. if (view.isAttachedToParent()) { view.__invokeDetached(); } }); }
javascript
{ "resource": "" }
q118
train
function(result, feedbackCellField) { var newState = $.extend({}, result); this.feedbackCell.set(feedbackCellField, newState, {silent: true}); this.feedbackCell.trigger('change:' + feedbackCellField); }
javascript
{ "resource": "" }
q119
train
function(bindInfo, eventKey) { return function() { var result, args = [{ args: arguments, type: eventKey }]; args.push(bindInfo.indices); result = bindInfo.fn.apply(this, args); this.__processFeedbackThenResult(result, bindInfo.feedbackCellField); }; }
javascript
{ "resource": "" }
q120
train
function(whenMap, indexMap) { var self = this, events = []; _.each(whenMap, function(whenEvents, whenField) { var substitutedWhenField, qualifiedFields = [whenField], useAtNotation = (whenField.charAt(0) === '@'); if (whenField !== 'on' || whenField !== 'listenTo') { if (useAtNotation) { whenField = whenField.substring(1); // substitute indices in to "when" placeholders // [] -> to all, [0] -> to specific, [x] -> [x's value] substitutedWhenField = self.__substituteIndicesUsingMap(whenField, indexMap); qualifiedFields = _.flatten(self.__generateSubAttributes(substitutedWhenField, self.model)); } // For each qualified field _.each(qualifiedFields, function(qualifiedField) { _.each(whenEvents, function(eventType) { var backboneEvent = eventType + ' ' + qualifiedField; if (useAtNotation) { backboneEvent = eventType + ' [data-model="' + qualifiedField + '"]'; } events.push(backboneEvent); }); }); } }); return events; }
javascript
{ "resource": "" }
q121
train
function(model, attr) { var attrValidationSet = model.validation ? _.result(model, 'validation')[attr] || {} : {}; // If the validator is a function or a string, wrap it in a function validator if (_.isFunction(attrValidationSet) || _.isString(attrValidationSet)) { attrValidationSet = { fn: attrValidationSet }; } // Stick the validator object into an array if(!_.isArray(attrValidationSet)) { attrValidationSet = [attrValidationSet]; } // Reduces the array of validators into a new array with objects // with a validation method to call, the value to validate against // and the specified error message, if any return _.reduce(attrValidationSet, function(memo, attrValidation) { _.each(_.without(_.keys(attrValidation), 'msg', 'msgKey'), function(validator) { memo.push({ fn: defaultValidators[validator], val: attrValidation[validator], msg: attrValidation.msg, msgKey: attrValidation.msgKey }); }); return memo; }, []); }
javascript
{ "resource": "" }
q122
train
function(model, attrs, validatedAttrs) { var error, invalidAttrs = {}, isValid = true, computed = _.clone(attrs); _.each(validatedAttrs, function(val, attr) { error = validateAttrWithOpenArray(model, attr, val, computed); if (error) { invalidAttrs[attr] = error; isValid = false; } }); return { invalidAttrs: invalidAttrs, isValid: isValid }; }
javascript
{ "resource": "" }
q123
train
function(model, value, attr) { var indices, validators, validations = model.validation ? _.result(model, 'validation') || {} : {}; // If the validations hash contains an entry for the attr if (_.contains(_.keys(validations), attr)) { return validateAttrWithOpenArray(model, attr, value, _.extend({}, model.attributes)); } else { indices = extractIndices(attr); attr = stripIndices(attr); validators = getValidators(model, attr); return invokeValidator(validators, model, value, attr, _.extend({}, model.attributes), indices); } }
javascript
{ "resource": "" }
q124
train
function(attr, value) { var self = this, result = {}, error; if (_.isArray(attr)) { _.each(attr, function(attr) { error = self.preValidate(attr); if (error) { result[attr] = error; } }); return _.isEmpty(result) ? undefined : result; } else if (_.isObject(attr)) { _.each(attr, function(value, key) { error = self.preValidate(key, value); if (error) { result[key] = error; } }); return _.isEmpty(result) ? undefined : result; } else { if (_.isUndefined(value) && isNestedModel(this)) { value = this.get(attr); } return validateAttr(this, value, attr); } }
javascript
{ "resource": "" }
q125
train
function(value, attr, fn, model, computed, indices) { return fn.call(this, value, attr, model, computed, indices); }
javascript
{ "resource": "" }
q126
train
function(value, attr, required, model, computed) { var isRequired = _.isFunction(required) ? required.call(model, value, attr, computed) : required; if(!isRequired && !hasValue(value)) { return false; // overrides all other validators } if (isRequired && !hasValue(value)) { return this.format(getMessageKey(this.msgKey, defaultMessages.required), this.formatLabel(attr, model)); } }
javascript
{ "resource": "" }
q127
train
function(value, attr, maxValue, model) { if (!isNumber(value) || value > maxValue) { return this.format(getMessageKey(this.msgKey, defaultMessages.max), this.formatLabel(attr, model), maxValue); } }
javascript
{ "resource": "" }
q128
train
function(value, attr, range, model) { if(!isNumber(value) || value < range[0] || value > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.range), this.formatLabel(attr, model), range[0], range[1]); } }
javascript
{ "resource": "" }
q129
train
function(value, attr, minLength, model) { if (!_.isString(value) || value.length < minLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.minLength), this.formatLabel(attr, model), minLength); } }
javascript
{ "resource": "" }
q130
train
function(value, attr, maxLength, model) { if (!_.isString(value) || value.length > maxLength) { return this.format(getMessageKey(this.msgKey, defaultMessages.maxLength), this.formatLabel(attr, model), maxLength); } }
javascript
{ "resource": "" }
q131
train
function(value, attr, range, model) { if (!_.isString(value) || value.length < range[0] || value.length > range[1]) { return this.format(getMessageKey(this.msgKey, defaultMessages.rangeLength), this.formatLabel(attr, model), range[0], range[1]); } }
javascript
{ "resource": "" }
q132
train
function(value, attr, pattern, model) { if (!hasValue(value) || !value.toString().match(defaultPatterns[pattern] || pattern)) { return this.format(getMessageKey(this.msgKey, defaultMessages[pattern]) || defaultMessages.inlinePattern, this.formatLabel(attr, model), pattern); } }
javascript
{ "resource": "" }
q133
train
function(alias, model, copy) { this.__currentObjectModels[alias] = model; this.__updateCache(model); this.resetUpdating(); if (copy) { _.each(this.getMappings(), function(config, mappingAlias) { var modelAliases; if (alias === mappingAlias) { this.__pull(mappingAlias); } if (config.computed) { modelAliases = this.__getModelAliases(mappingAlias); if (_.contains(modelAliases, alias)) { this.__pull(mappingAlias); } } }, this); } }
javascript
{ "resource": "" }
q134
train
function(models, copy) { _.each(models, function(instance, alias) { this.trackModel(alias, instance, copy); }, this); }
javascript
{ "resource": "" }
q135
train
function(aliasOrModel) { var model, alias = this.__findAlias(aliasOrModel); if (alias) { model = this.__currentObjectModels[alias]; delete this.__currentObjectModels[alias]; this.__updateCache(model); } this.resetUpdating(); }
javascript
{ "resource": "" }
q136
train
function() { _.each(this.__currentUpdateEvents, function(eventConfig) { this.stopListening(eventConfig.model, eventConfig.eventName); }, this); this.__currentUpdateEvents = []; }
javascript
{ "resource": "" }
q137
train
function(computedAlias) { var hasAllModels = true, config = this.getMapping(computedAlias), modelConfigs = []; _.each(this.__getModelAliases(computedAlias), function(modelAlias) { var modelConfig = this.__createModelConfig(modelAlias, config.mapping[modelAlias]); if (modelConfig) { modelConfigs.push(modelConfig); } else { hasAllModels = false; } }, this); return hasAllModels ? modelConfigs : undefined; }
javascript
{ "resource": "" }
q138
train
function(deferred, options) { var staleModels, formModel = this, responsesSucceeded = 0, responsesFailed = 0, responses = {}, oldValues = {}, models = formModel.getTrackedModels(), numberOfSaves = models.length; // If we're not forcing a save, then throw an error if the models are stale if (!options.force) { staleModels = formModel.checkIfModelsAreStale(); if (staleModels.length > 0) { throw { name: 'Stale data', staleModels: staleModels }; } } // Callback for each response function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } } // Grab the current values of the object models _.each(models, function(model) { oldValues[model.cid] = formModel.__getTrackedModelFields(model); }); // Push the form model values to the object models formModel.push(); // Call save on each object model _.each(models, function(model) { model.save().fail(function() { responsesFailed++; responseCallback(arguments, model, false); }).done(function() { responsesSucceeded++; responseCallback(arguments, model, true); }); }); }
javascript
{ "resource": "" }
q139
responseCallback
train
function responseCallback(response, model, success) { // Add response to a hash that will eventually be returned through the promise responses[model.cid] = { success: success, response: response }; // If we have reached the total of number of expected responses, then resolve or reject the promise if (responsesFailed + responsesSucceeded === numberOfSaves) { if (responsesFailed > 0) { // Rollback if any responses have failed if (options.rollback) { _.each(formModel.getTrackedModels(), function(model) { model.set(oldValues[model.cid]); if (responses[model.cid].success) { model.save(); } }); } formModel.trigger('save-fail', responses); deferred.reject(responses); } else { formModel.trigger('save-success', responses); deferred.resolve(responses); } } }
javascript
{ "resource": "" }
q140
train
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.pull) { this.__invokeComputedPull.call({formModel: this, alias: alias}); } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], this, model); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, this, model); } } }
javascript
{ "resource": "" }
q141
train
function(alias) { var config = this.getMapping(alias); if (config.computed && config.mapping.push) { var models = this.__getComputedModels(alias); if (models) { config.mapping.push.call(this, models); } } else if (config.computed) { var modelAliases = this.__getModelAliases(alias); _.each(modelAliases, function(modelAlias) { var model = this.getTrackedModel(modelAlias); if (model) { this.__copyFields(config.mapping[modelAlias], model, this); } }, this); } else { var model = this.getTrackedModel(alias); if (model) { this.__copyFields(config.mapping, model, this); } } }
javascript
{ "resource": "" }
q142
train
function(model) { if (!model) { this.__cache = {}; _.each(this.getTrackedModels(), function(model) { if (model) { this.__updateCache(model); } }, this); } else { this.__cache[model.cid] = this.__generateHashValue(model); } }
javascript
{ "resource": "" }
q143
train
function(val) { var seed; if (_.isArray(val)) { seed = []; } else if (_.isObject(val)) { seed = {}; } else { return val; } return $.extend(true, seed, val); }
javascript
{ "resource": "" }
q144
train
function(options) { var mapping, models, defaultMapping = _.result(this, 'mapping'), defaultModels = _.result(this, 'models'); mapping = options.mapping || defaultMapping; models = options.models || defaultModels; if (mapping) { this.setMappings(mapping, models); } }
javascript
{ "resource": "" }
q145
train
function(model) { var allFields, fieldsUsed = {}, modelFields = {}, modelConfigs = []; _.each(this.__getAllModelConfigs(), function(modelConfig) { if (modelConfig.model && modelConfig.model.cid === model.cid) { modelConfigs.push(modelConfig); } }); allFields = _.reduce(modelConfigs, function(result, modelConfig) { return result || !modelConfig.fields; }, false); if (allFields) { modelFields = this.__cloneVal(model.attributes); } else { _.each(modelConfigs, function(modelConfig) { _.each(modelConfig.fields, function(field) { if (!fieldsUsed[field]) { fieldsUsed[field] = true; modelFields[field] = this.__cloneVal(model.get(field)); } }, this); }, this); } return modelFields; }
javascript
{ "resource": "" }
q146
train
function(modelAlias, fields) { var model = this.getTrackedModel(modelAlias); if (model) { return { fields: fields, model: model }; } }
javascript
{ "resource": "" }
q147
train
function() { var modelConfigs = []; _.each(this.getMappings(), function(config, alias) { if (config.computed) { var computedModelConfigs = this.__getComputedModelConfigs(alias); if (computedModelConfigs) { modelConfigs = modelConfigs.concat(computedModelConfigs); } } else { var modelConfig = this.__createModelConfig(alias, config.mapping); if (modelConfig) { modelConfigs.push(modelConfig); } } }, this); return modelConfigs; }
javascript
{ "resource": "" }
q148
train
function(args) { View.apply(this, arguments); args = args || {}; var collection = args.collection || this.collection; this.template = args.template || this.template; this.emptyTemplate = args.emptyTemplate || this.emptyTemplate; this.itemView = args.itemView || this.itemView; this.itemContainer = args.itemContainer || this.itemContainer; if (this.template && !this.itemContainer) { throw 'Item container is required when using a template'; } this.modelsToRender = args.modelsToRender || this.modelsToRender; this.__itemContext = args.itemContext || this.__itemContext; this.__modelToViewMap = {}; this.__renderWait = args.renderWait || this.__renderWait; this.__modelId = args.modelId || this.modelId || 'cid'; this.__modelName = args.modelName || this.modelName || 'model'; this.__orderedModelIdList = []; this.__createItemViews(); this.__delayedRender = aggregateRenders(this.__renderWait, this); if (collection) { this.setCollection(collection, true); } this.on('render:after-dom-update', this.__cleanupItemViewsAfterAttachedToParent); }
javascript
{ "resource": "" }
q149
train
function(collection, preventUpdate) { this.stopListening(this.collection, 'remove', removeItemView); this.stopListening(this.collection, 'add', addItemView); this.stopListening(this.collection, 'sort', this.reorder); this.stopListening(this.collection, 'reset', this.update); this.collection = collection; this.listenTo(this.collection, 'remove', removeItemView); this.listenTo(this.collection, 'add', addItemView); this.listenTo(this.collection, 'sort', this.reorder); this.listenTo(this.collection, 'reset', this.update); if (!preventUpdate) { this.update(); } }
javascript
{ "resource": "" }
q150
train
function() { _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { itemView.delegateEvents(); if (!itemView.__attachedCallbackInvoked && itemView.isAttached()) { itemView.__invokeAttached(); } itemView.activate(); } else { // Shouldn't get here. Item view is missing... } }, this); }
javascript
{ "resource": "" }
q151
train
function() { var oldViews = this.getItemViews(); var newViews = this.__createItemViews(); var staleViews = this.__getStaleItemViews(); var sizeOfOldViews = _.size(oldViews); var sizeOfNewViews = _.size(newViews); var sizeOfStaleViews = _.size(staleViews); var sizeOfFinalViews = sizeOfOldViews - sizeOfStaleViews + sizeOfNewViews; var changes = sizeOfNewViews + sizeOfStaleViews; var percentChange = changes / Math.max(sizeOfFinalViews, 1); var fromEmptyToNotEmpty = !sizeOfOldViews && sizeOfNewViews; var fromNotEmptyToEmpty = sizeOfOldViews && sizeOfOldViews === sizeOfStaleViews && !sizeOfNewViews; var threshold = this.updateThreshold || 0.5; var signficantChanges = percentChange >= threshold; if (changes <= 0) { return this.reorder(); } // A switch from empty to not empty or vise versa, needs a new render var renderNeeded = fromEmptyToNotEmpty || fromNotEmptyToEmpty || signficantChanges; if (renderNeeded) { this.__removeStaleItemViews(staleViews); this.__delayedRender(); } else { this.__updateByAddingRemoving(oldViews, newViews, staleViews); } }
javascript
{ "resource": "" }
q152
train
function(model, noUpdateToIdList) { var itemView, ItemViewClass = this.itemView; if (!_.isFunction(this.itemView.extend)) { ItemViewClass = this.itemView(model); } itemView = new ItemViewClass(this.__generateItemViewArgs(model)); this.registerTrackedView(itemView, { shared: false }); this.__modelToViewMap[model[this.__modelId]] = itemView.cid; if (!noUpdateToIdList) { this.__updateOrderedModelIdList(); } this.trigger('child-view-added', {model: model, view: itemView}); this.trigger('item-view-added', {model: model, view: itemView}); return itemView; }
javascript
{ "resource": "" }
q153
train
function() { var staleItemViews = []; var modelsWithViews = _.clone(this.__modelToViewMap); _.each(this.modelsToRender(), function(model) { var itemView = this.getItemViewFromModel(model); if (itemView) { delete modelsWithViews[model[this.__modelId]]; } }, this); _.each(modelsWithViews, function(viewId, modelId) { var itemView = this.getTrackedView(viewId); if (itemView) { staleItemViews.push({ view: itemView, modelId: modelId }); } }, this); return staleItemViews; }
javascript
{ "resource": "" }
q154
train
function(oldViews, newViews, staleViews) { var firstItemViewLeft, injectionSite, view = this, sizeOfOldViews = _.size(oldViews), sizeOfNewViews = _.size(newViews), sizeOfStaleViews = _.size(staleViews); if (view.itemContainer && sizeOfOldViews && sizeOfOldViews == sizeOfStaleViews) { // we removed all the views! injectionSite = $('<span>'); _.first(oldViews).$el.before(injectionSite); } view.__removeStaleItemViews(staleViews); _.each(newViews, function(createdViewInfo, indexOfView) { if (createdViewInfo.indexOfModel === 0) { // need to handle this case uniquely. var replaceMethod; if (!view.itemContainer) { replaceMethod = _.bind(view.$el.prepend, view.$el); } else { if (injectionSite) { replaceMethod = _.bind(injectionSite.replaceWith, injectionSite); } else { var staleModelIdMap = _.indexBy(staleViews, 'modelId'); var firstModelIdLeft = _.find(view.__orderedModelIdList, function(modelId) { return !staleModelIdMap[modelId]; }); firstItemViewLeft = view.getTrackedView(view.__modelToViewMap[firstModelIdLeft]); replaceMethod = _.bind(firstItemViewLeft.$el.prepend, firstItemViewLeft.$el); } } view.attachView(null, createdViewInfo.view, { replaceMethod: replaceMethod, discardInjectionSite: true }); } else { // There will always the view before this one because we are adding new views in order // and we took care of the initial case. _addItemView.call(view, createdViewInfo.view, createdViewInfo.indexOfModel); } }); this.reorder(); }
javascript
{ "resource": "" }
q155
normalizeIds
train
function normalizeIds(ids) { if (_.isArray(ids)) { // remove any nesting of arrays - it is assumed that the resulting ids will be simple string or number values. ids = _.flatten(ids); // remove any duplicate ids. return _.uniq(ids); } else if (_.isString(ids) || _.isNumber(ids)) { // individual id - convert to array for consistency. return [ids]; } else if (ids && ids.skipObjectRetrieval) { return ids; } }
javascript
{ "resource": "" }
q156
undefinedOrNullToEmptyArray
train
function undefinedOrNullToEmptyArray(valueToConvert) { if (_.isUndefined(valueToConvert) || _.isNull(valueToConvert)) { valueToConvert = []; } return valueToConvert; }
javascript
{ "resource": "" }
q157
getNestedProperty
train
function getNestedProperty(rootObject, propertyString) { propertyString = propertyString.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties propertyString = propertyString.replace(/^\./, ''); // strip a leading dot var propertyStringParts = propertyString.split(PROPERTY_SEPARATOR); return _.reduce(propertyStringParts, function(currentBaseObject, currentPropertyName) { return _.isUndefined(currentBaseObject) ? undefined : currentBaseObject[currentPropertyName]; }, rootObject); }
javascript
{ "resource": "" }
q158
train
function() { var behaviorContext = Behavior.prototype.prepare.apply(this) || {}; behaviorContext.data = this.data.toJSON(); behaviorContext.loading = this.isLoading(); behaviorContext.loadingIds = this.isLoadingIds(); behaviorContext.loadingObjects = this.isLoadingObjects(); return behaviorContext; }
javascript
{ "resource": "" }
q159
train
function() { if (!_.isUndefined(this.ids.property)) { this.stopListeningToIdsPropertyChangeEvent(); var idsPropertyNameAndContext = this.__parseIdsPropertyNameAndIdContainer(); var idContainer = idsPropertyNameAndContext.idContainer; var canListenToEvents = idContainer && _.isFunction(idContainer.on); if (canListenToEvents) { this.__currentContextWithListener = idContainer; this.__currentContextEventName = 'change:' + idsPropertyNameAndContext.idsPropertyName; this.listenTo(this.__currentContextWithListener, this.__currentContextEventName, this.retrieve); this.listenTo(this.__currentContextWithListener, 'fetched:ids', this.retrieve); } } }
javascript
{ "resource": "" }
q160
train
function() { this._undelegateUpdateEvents(); var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.listenTo(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
javascript
{ "resource": "" }
q161
train
function() { var updateEvents = this.__parseUpdateEvents(); _.each(updateEvents, function(parsedUpdateEvent) { this.stopListening(parsedUpdateEvent.idContainer, parsedUpdateEvent.eventName, this.retrieve); }, this); }
javascript
{ "resource": "" }
q162
train
function() { this.__normalizeAndValidateUpdateEvents(); var updateEvents = _.flatten(_.map(this.updateEvents, this.__parseUpdateEvent, this)); return _.compact(updateEvents); }
javascript
{ "resource": "" }
q163
train
function() { var updateEventsIsArray = _.isArray(this.updateEvents); var updateEventsIsSingleValue = !updateEventsIsArray && (_.isObject(this.updateEvents) || _.isString(this.updateEvents)); var updateEventsIsUndefined = _.isUndefined(this.updateEvents); var updateEventsIsValidType = updateEventsIsArray || updateEventsIsSingleValue || updateEventsIsUndefined; if (updateEventsIsSingleValue) { this.updateEvents = [this.updateEvents]; } if (!updateEventsIsValidType) { throw new Error('Update events are not an array, string or object. Please see parameters for examples of how to define updateEvents. Configured UpdateEvents: ', this.updateEvents); } // Remove any random falsey values (mostly to get rid of undefined events). this.updateEvents = _.compact(this.updateEvents); _.each(this.updateEvents, this.__validUpdateEvent); }
javascript
{ "resource": "" }
q164
train
function(updateEventConfiguration) { var validStringConfig = _.isString(updateEventConfiguration); var validObjectConfig = _.isObject(updateEventConfiguration) && _.keys(updateEventConfiguration).length > 0; if (!validStringConfig && !validObjectConfig) { throw new Error('Not a valid updateEvent configuration. Update events need to either be strings or objects with a single property: ' + JSON.stringify(updateEventConfiguration)); } }
javascript
{ "resource": "" }
q165
train
function() { var propertyName = this.ids.property; var propertyNameContainsIdContainer = containsContainerDefinition(propertyName); var hasIdContainerProperty = !_.isUndefined(this.ids.idContainer); var idContainer; if (hasIdContainerProperty) { idContainer = this.__parseIdContainer(); } if (propertyNameContainsIdContainer) { var containerAndDetail = this.__parseContainerDetailString(propertyName); propertyName = containerAndDetail.detail; idContainer = containerAndDetail.idContainer; } if (_.isUndefined(idContainer)) { idContainer = this.view; } return { idsPropertyName: propertyName, idContainer: idContainer }; }
javascript
{ "resource": "" }
q166
train
function() { var idContainerDefinition = this.ids.idContainer; var idContainer; if (_.isUndefined(idContainerDefinition)) { idContainer = undefined; } else if (_.isFunction(idContainerDefinition)) { var idContainerFxn = _.bind(idContainerDefinition, this); idContainer = idContainerFxn(); } else if (_.isObject(idContainerDefinition)) { idContainer = idContainerDefinition; } else { throw new Error('Invalid idContainer. Not an object or function: ' + JSON.stringify(this.ids)); } return idContainer; }
javascript
{ "resource": "" }
q167
train
function() { var resultDeferred = $.Deferred(); if (this.isDisposed()) { var rejectArguments = Array.prototype.slice.call(arguments); rejectArguments.push('Data Behavior disposed, aborting.'); resultDeferred.reject.apply(resultDeferred, rejectArguments); } else { resultDeferred.resolve.apply(resultDeferred, arguments); } return resultDeferred.promise(); }
javascript
{ "resource": "" }
q168
train
function(idsResult) { if (_.isEmpty(idsResult) && _.isEmpty(this.data.privateCollection.getTrackedIds())) { return { skipObjectRetrieval: true, forceFetchedEvent: true }; } else { return idsResult; } }
javascript
{ "resource": "" }
q169
train
function() { var privateCollection = this.privateCollection; if (!this.parentBehavior.returnSingleResult) { return privateCollection.toJSON(); } if (privateCollection.length === 0) { return undefined; } else if (privateCollection.length === 1) { var singleResultModel = privateCollection.at(0); return singleResultModel.toJSON(); } else { throw new Error('Multiple results found, but single result expected: ' + JSON.stringify(privateCollection.toJSON())); } }
javascript
{ "resource": "" }
q170
train
function(args) { args = args || {}; /* Listen to model validation callbacks */ var FormModelClass = args.FormModelClass || this.FormModelClass || FormModel; this.model = args.model || this.model || (new FormModelClass()); /* Override template */ this.template = args.template || this.template; /* Merge events, fields, bindings, and computeds */ this.events = _.extend({}, this.events || {}, args.events || {}); this.fields = _.extend({}, this.fields || {}, args.fields || {}); this._errors = []; this._success = false; // this._bindings is a snapshot of the original bindings this._bindings = _.extend({}, this.bindings || {}, args.bindings || {}); View.apply(this, arguments); this.resetModelListeners(this.model); }
javascript
{ "resource": "" }
q171
train
function() { var templateContext = View.prototype.prepare.apply(this); templateContext.formErrors = (_.size(this._errors) !== 0) ? this._errors : null; templateContext.formSuccess = this._success; return templateContext; }
javascript
{ "resource": "" }
q172
train
function(model, stopListening) { if (this.model && stopListening) { this.stopListening(this.model); } this.model = model; this.listenTo(this.model, 'validated:valid', this.valid); this.listenTo(this.model, 'validated:invalid', this.invalid); }
javascript
{ "resource": "" }
q173
deltaE
train
function deltaE(labA, labB) { var deltaL = labA[0] - labB[0]; var deltaA = labA[1] - labB[1]; var deltaB = labA[2] - labB[2]; return Math.sqrt(Math.pow(deltaL, 2) + Math.pow(deltaA, 2) + Math.pow(deltaB, 2)); }
javascript
{ "resource": "" }
q174
autoLayout
train
function autoLayout() { if (!clay.meta.activeWatchInfo || clay.meta.activeWatchInfo.firmware.major === 2 || ['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && !self.config.allowGray) { return standardLayouts.BLACK_WHITE; } if (['aplite', 'diorite'].indexOf(clay.meta.activeWatchInfo.platform) > -1 && self.config.allowGray) { return standardLayouts.GRAY; } return standardLayouts.COLOR; }
javascript
{ "resource": "" }
q175
sources
train
function sources(k) { (src[k] || []).forEach(function(s) { deps[s] = k; sources(s); }); }
javascript
{ "resource": "" }
q176
lib
train
function lib(val) { var p = path.join(process.cwd(), val); return require(p); }
javascript
{ "resource": "" }
q177
highlight
train
function highlight(value) { var html = ngPrettyJsonFunctions.syntaxHighlight(value) || ""; html = html .replace(/\{/g, "<span class='sep'>{</span>") .replace(/\}/g, "<span class='sep'>}</span>") .replace(/\[/g, "<span class='sep'>[</span>") .replace(/\]/g, "<span class='sep'>]</span>") .replace(/\,/g, "<span class='sep'>,</span>"); return isDefined(value) ? scope.tmplElt.find('pre').html(html) : scope.tmplElt.find('pre').empty(); }
javascript
{ "resource": "" }
q178
_populateMeta
train
function _populateMeta() { self.meta = { activeWatchInfo: Pebble.getActiveWatchInfo && Pebble.getActiveWatchInfo(), accountToken: Pebble.getAccountToken(), watchToken: Pebble.getWatchToken(), userData: deepcopy(options.userData || {}) }; }
javascript
{ "resource": "" }
q179
initCasperCli
train
function initCasperCli(casperArgs) { var baseTestsPath = fs.pathJoin(phantom.casperPath, 'tests'); if (!!casperArgs.options.version) { return __terminate(phantom.casperVersion.toString()) } else if (casperArgs.get(0) === "test") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperTest = true; casperArgs.drop("test"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(0)); } else if (casperArgs.get(0) === "selftest") { phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js')); phantom.casperSelfTest = phantom.casperTest = true; casperArgs.options.includes = fs.pathJoin(baseTestsPath, 'selftest.js'); if (casperArgs.args.length <= 1) { casperArgs.args.push(fs.pathJoin(baseTestsPath, 'suites')); } casperArgs.drop("selftest"); phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(1) || fs.dirname(phantom.casperScript)); } else if (casperArgs.args.length === 0 || !!casperArgs.options.help) { return printHelp(); } if (!phantom.casperScript) { phantom.casperScript = casperArgs.get(0); } if (!fs.isFile(phantom.casperScript)) { return __die('Unable to open file: ' + phantom.casperScript); } if (!phantom.casperScriptBaseDir) { var scriptDir = fs.dirname(phantom.casperScript); if (scriptDir === phantom.casperScript) { scriptDir = '.'; } phantom.casperScriptBaseDir = fs.absolute(scriptDir); } // filter out the called script name from casper args casperArgs.drop(phantom.casperScript); }
javascript
{ "resource": "" }
q180
setValueDisplay
train
function setValueDisplay() { var value = self.get().toFixed(self.precision); $value.set('value', value); $valuePad.set('innerHTML', value); }
javascript
{ "resource": "" }
q181
keysInObject
train
function keysInObject(obj, keys) { for (var i in keys) { if (keys[i] in obj) return true; } return false; }
javascript
{ "resource": "" }
q182
setValueDisplay
train
function setValueDisplay() { var selectedIndex = self.$manipulatorTarget.get('selectedIndex'); var $options = self.$manipulatorTarget.select('option'); var value = $options[selectedIndex] && $options[selectedIndex].innerHTML; $value.set('innerHTML', value); }
javascript
{ "resource": "" }
q183
coerceElementMatchingCallback
train
function coerceElementMatchingCallback(value) { // Element Name if (typeof value === 'string') { return element => element.element === value; } // Element Type if (value.constructor && value.extend) { return element => element instanceof value; } return value; }
javascript
{ "resource": "" }
q184
inFromVoid
train
function inFromVoid(from, to) { return to !== null && to !== 'nofx' && from === 'void' && to !== 'void' ? true : false; }
javascript
{ "resource": "" }
q185
train
function(event_type) { var rest_args = arguments.length > 1 ? rest(arguments) : root, // no parent, no filter by default event = new CJSEvent(false, false, function(transition) { var targets = [], timeout_id = false, event_type_val = [], listener = bind(this._fire, this), fsm = transition.getFSM(), from = transition.getFrom(), state_selector = new StateSelector(from), from_state_selector = new TransitionSelector(true, state_selector, new AnyStateSelector()), on_listener = function() { each(event_type_val, function(event_type) { // If the event is 'timeout' if(event_type === timeout_event_type) { // clear the previous timeout if(timeout_id) { cTO(timeout_id); timeout_id = false; } // and set a new one var delay = cjs.get(rest_args[0]); if(!isNumber(delay) || delay < 0) { delay = 0; } timeout_id = sTO(listener, delay); } else { each(targets, function(target) { // otherwise, add the event listener to every one of my targets aEL(target, event_type, listener); }); } }); }, off_listener = function() { each(event_type_val, function(event_type) { each(targets, function(target) { if(event_type === timeout_event_type) { // If the event is 'timeout' if(timeout_id) { cTO(timeout_id); timeout_id = false; } } else { rEL(target, event_type, listener); } }); }); }, live_fn = cjs.liven(function() { off_listener(); event_type_val = split_and_trim(cjs.get(event_type)); // only use DOM elements (or the window) as my target targets = flatten(map(filter(get_dom_array(rest_args), isElementOrWindow), getDOMChildren , true)); // when entering the state, add the event listeners, then remove them when leaving the state fsm .on(state_selector, on_listener) .on(from_state_selector, off_listener); if(fsm.is(from)) { // if the FSM is already in the transition's starting state on_listener(); } }); return live_fn; }); return event; }
javascript
{ "resource": "" }
q186
train
function () { var args = slice.call(arguments), constraint = options.args_map.getOrPut(args, function() { return new Constraint(function () { return getter_fn.apply(options.context, args); }); }); return constraint.get(); }
javascript
{ "resource": "" }
q187
train
function (silent) { if(options.on_destroy) { options.on_destroy.call(options.context, silent); } node.destroy(silent); }
javascript
{ "resource": "" }
q188
train
function () { if(paused === true) { paused = false; node.onChangeWithPriority(options.priority, do_get); if(options.run_on_create !== false) { if (constraint_solver.semaphore >= 0) { node.get(false); } else { each(node._changeListeners, constraint_solver.add_in_call_stack, constraint_solver); } } return true; // successfully resumed } return false; }
javascript
{ "resource": "" }
q189
train
function(options) { this.options = options; this.targets = options.targets; // the DOM nodes var setter = options.setter, // a function that sets the attribute value getter = options.getter, // a function that gets the attribute value init_val = options.init_val, // the value of the attribute before the binding was set curr_value, // used in live fn last_value, // used in live fn old_targets = [], // used in live fn do_update = function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }; this._throttle_delay = false; // Optional throttling to improve performance this._timeout_id = false; // tracks the timeout that helps throttle if(isFunction(init_val)) { // If init_val is a getter, call it on the first element last_value = init_val(get_dom_array(this.targets[0])); } else { // Otherwise, just take it as is last_value = init_val; } this.$live_fn = cjs.liven(function() { curr_value = getter(); // get the value once and inside of live fn to make sure a dependency is added if(this._throttle_delay) { // We shouldn't update values right away if(!this._timeout_id) { // If there isn't any timeout set yet, then set a timeout to delay the call to do update this._timeout_id = sTO(bind(do_update, this), this._throttle_delay); } } else { // we can update the value right away if no throttle delay is set do_update.call(this); } }, { context: this }); }
javascript
{ "resource": "" }
q190
train
function() { this._timeout_id = false; // Make it clear that I don't have a timeout set var new_targets = filter(get_dom_array(this.targets), isAnyElement); // update the list of targets if(has(options, "onChange")) { options.onChange.call(this, curr_value, last_value); } // For every target, update the attribute each(new_targets, function(target) { setter.call(this, target, curr_value, last_value); }, this); // track the last value so that next time we call diff last_value = curr_value; }
javascript
{ "resource": "" }
q191
train
function (infos, silent) { each(infos, function (info) { info.key.destroy(silent); info.value.destroy(silent); info.index.destroy(silent); }); }
javascript
{ "resource": "" }
q192
train
function (index, silent) { var info = this._ordered_values[index]; _destroy_info(this._ordered_values.splice(index, 1), silent); if(silent !== true) { this.$size.invalidate(); } }
javascript
{ "resource": "" }
q193
train
function(dom_node) { var index = get_template_instance_index(getFirstDOMChild(dom_node)), instance = index >= 0 ? template_instances[index] : false; if(instance) { delete template_instances[index]; instance.destroy(); } return this; }
javascript
{ "resource": "" }
q194
train
function(str, context) { return cjs(function() { try { var node = jsep(cjs.get(str)); if(node.type === LITERAL) { return node.value; } else { return get_node_value(node, context, [context]); } } catch(e) { console.error(e); } }); }
javascript
{ "resource": "" }
q195
promisify
train
function promisify(f, args) { return new Promise((resolve, reject) => f.apply(this, args.concat((err, x) => err ? reject(err) : resolve(x)))); }
javascript
{ "resource": "" }
q196
getKernelResources
train
function getKernelResources(kernelInfo) { return promisify(fs.readdir, [kernelInfo.resourceDir]).then(files => { const kernelJSONIndex = files.indexOf('kernel.json'); if (kernelJSONIndex === -1) { throw new Error('kernel.json not found'); } return promisify(fs.readFile, [path.join(kernelInfo.resourceDir, 'kernel.json')]).then(data => ({ name: kernelInfo.name, files: files.map(x => path.join(kernelInfo.resourceDir, x)), resources_dir: kernelInfo.resourceDir, // eslint-disable-line camelcase spec: JSON.parse(data), })); }); }
javascript
{ "resource": "" }
q197
getKernelInfos
train
function getKernelInfos(directory) { return promisify(fs.readdir, [directory]).then(files => files.map(fileName => ({ name: fileName, resourceDir: path.join(directory, fileName), })) ); }
javascript
{ "resource": "" }
q198
find
train
function find(kernelName) { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { const kernelInfos = dirs.map(dir => ({ name: kernelName, resourceDir: path.join(dir, 'kernels', kernelName), })) return extractKernelResources(kernelInfos); }).then(kernelResource => kernelResource[kernelName]) }
javascript
{ "resource": "" }
q199
findAll
train
function findAll() { return jp.dataDirs({ withSysPrefix: true }).then(dirs => { return Promise.all(dirs // get kernel infos for each directory and ignore errors .map(dir => getKernelInfos(path.join(dir, 'kernels')).catch(() => {})) ).then(extractKernelResources) }); }
javascript
{ "resource": "" }