Backbone `set` extended with support for schema

TODO @ptshih Extend with lodash `set` (nested/deep)

@return {*}
431335
function(key, val, options) {
    var attrs;
    if (key === null) return this;

    if (typeof key === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }

    options || (options = {});

    // Don't override unset
    if (options.unset) {
      return Backbone.Model.prototype.set.apply(this, arguments);
    }

    // Apply schema
    this._validateAttributes(attrs, this._schema, this._defaults);

    return Backbone.Model.prototype.set.call(this, attrs, options);
  }
202758
function(model, options) {
      if (!(model instanceof Backbone.Model)) {
        var attrs = model;
        model = new this.model(attrs, {collection: this});
        if (model.validate && !model._performValidation(attrs, options)) model = false;
      } else if (!model.collection) {
        model.collection = this;
      }
      return model;
    }
420124
function() {
    this.model.set({
      content:  {
        fields: [{
          title: null,
          alternative_name: null,
          value: 'Loading content...',
          index: null,
          type: "loading"
        }],
        data: {}
      }
    })
    return this;
  }
195762
function (options) {
                var ret = {};
                for (var k in this.schema) {
                    if (this.schema.hasOwnProperty(k)) {
                        ret[k] = this.getTransformedValue(k);
                    }
                }

                this.set(ret, options);
            }
690898
function getModel(model) {
  const schemaPaths = model.schema.paths;
  const name = model.modelName;

  const fields = extractPaths(schemaPaths, { name });

  return {
    name,
    fields,
    model
  };
}
98206
function getset(key, value, req) {
  var val = this.getKey(key, req);
  this.setKey(key, value, undefined, undefined, undefined, req);
  return val || null;
}
60676
function createSet(values) {
    var set = new Set();
    Lazy(values || []).flatten().each(function(e) {
      set.add(e);
    });
    return set;
  }
803380
function extend(source, target, deep) {
    if (deep) {
        return lodash.merge(lodash.cloneDeep(source), target);
    } else {
        return lodash.assignIn(source, target);
    }
}
811155
function ensureMap(set) {
            if (!set['[[SetData]]']) {
              var m = set['[[SetData]]'] = new collectionShims.Map();
              Object.keys(set._storage).forEach(function(k) {
                // fast check for leading '$'
                if (k.charCodeAt(0) === 36) {
                  k = k.substring(1);
                } else {
                  k = +k;
                }
                m.set(k, k);
              });
              set._storage = null; // free old backing storage
            }
          }
1285177
function() {
    const Utils = this.definition.store.utils
    const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy!

    const existingConditions = self.getInternal('conditions') || []
    const existingMap = {}

    existingConditions.forEach(function(cond) {
      const key =
        cond.type +
        '|' +
        cond.attribute +
        '|' +
        cond.operator +
        '|' +
        JSON.stringify(cond.value)
      existingMap[key] = true
    })

    var attributeNames = Object.keys(self.definition.attributes)

    attributeNames = attributeNames.concat(attributeNames.map(function(name){
      return self.definition.attributes[name].name
    }))

    const parentRelations = self.getInternal('parent_relations')
    const conditions = Utils.toConditionList(
      Utils.args(arguments),
      attributeNames
    )

    conditions.forEach(function(cond) {
      if (
        cond.type === 'relation' &&
        !self.definition.relations[cond.relation] &&
        !self.options.polymorph
      ) {
        throw new Error(
          'Can\'t find attribute or relation "' +
            cond.relation +
            '" for ' +
            self.definition.modelName
        )
      }
      // used for joins only
      if (parentRelations) {
        cond.parents = parentRelations
        if (cond.value && cond.value.$attribute && !cond.value.$parents) {
          cond.value.$parents = parentRelations
        }
      }

      if(cond.attribute) cond.attribute = self.store.toInternalAttributeName(cond.attribute)

      const key =
        cond.type +
        '|' +
        cond.attribute +
        '|' +
        cond.operator +
        '|' +
        JSON.stringify(cond.value)
      if (existingMap[key] && cond.type !== 'raw') return

      self.addInternal('conditions', cond)
    })

    return self
  }
1106631
function(method) {
		return function(object, options) {
			//console.log("client-store schema validation", this.schema);
			var schema = this.schema;
			if (!schema)
				return deep.Arguments([object, options]);
			options = options || {};
			var id = options.id || object.id,
				query = null;
			if (id) {
				query = id.split("/");
				if (query.length > 1) {
					id = query.shift();
					query = "/" + query.join("/");
				} else
					query = null;
			}
			var finalise = function(schema) {
				if (!query) { // validate whole object
					var report = deep.validate(object, schema);
					if (!report.valid)
						return deep.errors.PreconditionFail(method + " failed", report);
				} else { // partial validation : could be unrelevant as it could depend of whole item structure
					// what TODO here...? : if nothing : it should be validated remotely
				}
				return deep.Arguments([object, options]);
			};
			if (typeof schema === 'string')
				return deep.get(schema)
					.done(finalise);
			return finalise(schema);
		};
	}
576036
public Set<String> keySet() {

		// Copy key set, so return value is independent from the object's internal data structure
		final Set<String> retVal = new HashSet<String>();

		synchronized (this.confData) {

			final Iterator<String> it = this.confData.keySet().iterator();
			while (it.hasNext()) {
				retVal.add(it.next());
			}
		}

		return retVal;
	}
901
function( key, options ) {
			options || ( options = {} );
			var rel = this.getRelation( key ),
				keyContents = rel && rel.keyContents,
				toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
						var id = _.isString( item ) || _.isNumber( item ) ? item : item[ rel.relatedModel.prototype.idAttribute ];
						return id && !Backbone.Relational.store.find( rel.relatedModel, id );
					}, this );
			
			if ( toFetch && toFetch.length ) {
				// Create a model for each entry in 'keyContents' that is to be fetched
				var models = _.map( toFetch, function( item ) {
						if ( typeof( item ) === 'object' ) {
							var model = new rel.relatedModel( item );
						}
						else {
							var attrs = {};
							attrs[ rel.relatedModel.prototype.idAttribute ] = item;
							var model = new rel.relatedModel( attrs );
						}
						return model;
					}, this );
				
				// Try if the 'collection' can provide a url to fetch a set of models in one request.
				if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
					var setUrl = rel.related.url( models );
				}
				
				// An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
				// To make sure it can, test if the url we got by supplying a list of models to fetch is different from
				// the one supplied for the default fetch action (without args to 'url').
				if ( setUrl && setUrl !== rel.related.url() ) {
					var opts = _.defaults( {
							error: function() {
									var args = arguments;
									_.each( models, function( model ) {
											model.destroy();
											options.error && options.error.apply( model, args );
										})
								},
							url: setUrl
						},
						options,
						{ add: true }
					);
					
					var requests = [ rel.related.fetch( opts ) ];
				}
				else {
					var requests = _.map( models, function( model ) {
							var opts = _.defaults( {
								error: function() {
										model.destroy();
										options.error && options.error.apply( model, arguments );
									}
								},
								options
							);
							return model.fetch( opts );
						}, this );
				}
			}
			
			return _.isUndefined( requests ) ? [] : requests;
		}
469642
function schema(opts: Options): Object {
    const constructedSchema = {
        blocks: {
            [opts.typeItem]: {
                parent: { types: opts.types },
                nodes: [{ objects: ['block'] }],

                normalize: normalize({
                    parent_type_invalid: (change, context) =>
                        change.unwrapBlockByKey(context.node.key, {
                            normalize: false
                        }),
                    child_object_invalid: (change, context) =>
                        wrapChildrenInDefaultBlock(opts, change, context.node)
                })
            }
        }
    };

    // validate all list types, ensure they only have list item children
    opts.types.forEach(type => {
        constructedSchema.blocks[type] = {
            nodes: [{ types: [opts.typeItem] }],
            normalize: normalize({
                child_type_invalid: (change, context) =>
                    change.wrapBlockByKey(context.child.key, opts.typeItem, {
                        normalize: false
                    })
            })
        };
    });

    return constructedSchema;
}
337834
def extend(dset, array, **attrs):
    
    length = len(dset)
    if len(array) == 0:
        return length
    newlength = length + len(array)
    if array.dtype.name == 'object':  # vlen array
        shape = (newlength,) + preshape(array[0])
    else:
        shape = (newlength,) + array.shape[1:]
    dset.resize(shape)
    dset[length:newlength] = array
    for key, val in attrs.items():
        dset.attrs[key] = val
    return newlength
53453
function hashSet(key, value) {
      var data = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data[key] = (nativeCreate && value === undefined$1) ? HASH_UNDEFINED : value;
      return this;
    }
948682
function(model, collection, options) {
          options = options ? _.clone(options) : {};
          options.success =
            _.isFunction(options.success) ? options.success : function() {};
          var childRef = this.firebase.child(model.id);
          Backbone.Firebase._setWithCheck(childRef, null, _.bind(options.success, model));
        }