Process some basic formatting to the entity data before save
- automatically set the modifiedOn property to current date (if exists on schema)
- convert object with latitude/longitude to Datastore GeoPoint
161310
function prepareData() {
            updateModifiedOn.call(this);
            convertGeoPoints.call(this);

            return this.entityData;

            //--------------------------

            /**
             * If the schema has a "modifiedOn" property we automatically
             * update its value to the current dateTime
            */
            function updateModifiedOn() {
                if ({}.hasOwnProperty.call(this.schema.paths, 'modifiedOn')) {
                    this.entityData.modifiedOn = new Date();
                }
            }

            /**
             * If the entityData has some property of type 'geoPoint'
             * and its value is an js object with "latitude" and "longitude"
             * we convert it to a datastore GeoPoint.
            */
            function convertGeoPoints() {
                if (!{}.hasOwnProperty.call(this.schema.__meta, 'geoPointsProps')) {
                    return;
                }

                this.schema.__meta.geoPointsProps.forEach((property) => {
                    if ({}.hasOwnProperty.call(_this.entityData, property)
                        && _this.entityData[property] !== null
                        && _this.entityData[property].constructor.name !== 'GeoPoint') {
                        _this.entityData[property] = _this.gstore.ds.geoPoint(_this.entityData[property]);
                    }
                });
            }
        }
918267
def _prepare_record(record, index, doc_type):
        
        if current_app.config['INDEXER_REPLACE_REFS']:
            data = copy.deepcopy(record.replace_refs())
        else:
            data = record.dumps()

        data['_created'] = pytz.utc.localize(record.created).isoformat() \
            if record.created else None
        data['_updated'] = pytz.utc.localize(record.updated).isoformat() \
            if record.updated else None

        # Allow modification of data prior to sending to Elasticsearch.
        before_record_index.send(
            current_app._get_current_object(),
            json=data,
            record=record,
            index=index,
            doc_type=doc_type,
        )

        return data
806138
function (store, type, fixture) {
    var now = (new Date()).toISOString(), attributes = slice.call(arguments, 3);
    this._parseModelOrType(store, type).eachAttribute(function (name, meta) {
      if (attributes.indexOf(name) !== -1 && (!meta.type || meta.type === 'date')) {
        fixture[name] = now;
      }
    });
  }
633668
function timestamp(schema, options) {
	options = options || {};
	// Set defaults
	options = Object.assign({
		createdName: 'createdAt',
		updatedName: 'updatedAt',
		disableCreated: false,
		disableUpdated: false
	}, options);

	// Add fields if not disabled
	if (!options.disableCreated) {
		addSchemaField(schema, options.createdName, {type: Date});
	}
	if (!options.disableUpdated) {
		addSchemaField(schema, options.updatedName, {type: Date});
	}

	// Add pre-save hook to save dates of creation and modification
	schema.pre('save', preSave);

	/**
	 * Callback for the schema pre save
	 *
	 * @this mongoose.Schema
	 * @param {Function} next The next pre save callback in chain
	 * @returns {undefined}
	 */
	function preSave(next) {
		const _ref = this.get(options.createdName);

		if (!options.disableUpdated) {
			this[options.updatedName] = new Date();
		}
		if (!options.disableCreated && (_ref === undefined || _ref === null)) {
			this[options.createdName] = new Date();
		}

		next();
	}
}
1282566
function convertData(objectBody, objectChange) {
    const keysChange = Object.keys(objectChange);
    let objectReturn = {};
    keysChange.map(keyChange => {
        let changeOption = objectChange[keyChange];
        let valueKeyReturn = getValueChangeOption(objectBody, keyChange, changeOption, objectReturn);
        if(valueKeyReturn !== undefined && valueKeyReturn !== null){
            objectReturn[keyChange] = valueKeyReturn;
        }
        return keyChange;
    });
    return objectReturn;
}
841215
protected function process()
    {

        // prepare the static entity values
        $customerAddress = $this->initializeCustomerAddress($this->prepareAttributes());

        // insert the entity and set the entity ID
        $this->setLastEntityId($this->persistCustomerAddress($customerAddress));
    }
391506
function(o, callback) {
    var self = this;
    
    // Data is validated prior to being inserted
    var err = this.validateProperties(o);

    if (err) callback.call(self, err);
    
    else {
      
      // Convert object types to strings
      this.convertTypes(o);

      // Set model defaults
      this.setDefaults(o);

      // Save data into the database
      this.driver.insertInto({
        table: this.context,
        values: o
      }, function(err, id) {
        if (err) callback.call(self, err, null);
        else {
          callback.call(self, null, id);
        }
      });
      
    }

  }
1180370
function (mappingObject) {
			this.writeDebug('mapping',arguments);
			var _this = this;
			var orig_lat, orig_lng, geocodeData, origin, originPoint, page;
			if (!this.isEmptyObject(mappingObject)) {
				orig_lat = mappingObject.lat;
				orig_lng = mappingObject.lng;
				geocodeData = mappingObject.geocodeResult;
				origin = mappingObject.origin;
				page = mappingObject.page;
			}

			// Set the initial page to zero if not set
			if ( _this.settings.pagination === true ) {
				if (typeof page === 'undefined' || originalOrigin !== addressInput ) {
					page = 0;
				}
			}

			// Data request
			if (typeof origin === 'undefined' && this.settings.nameSearch === true) {
				dataRequest = _this._getData();
			}
			else {
				// Setup the origin point
				originPoint = new google.maps.LatLng(orig_lat, orig_lng);

				// If the origin hasn't changed use the existing data so we aren't making unneeded AJAX requests
				if ((typeof originalOrigin !== 'undefined') && (origin === originalOrigin) && (typeof originalData !== 'undefined')) {
					origin = originalOrigin;
					dataRequest = originalData;
				}
				else {
					// Do the data request - doing this in mapping so the lat/lng and address can be passed over and used if needed
					dataRequest = _this._getData(olat, olng, origin, geocodeData, mappingObject);
				}
			}

			// Check filters here to handle selected filtering after page reload
			if (_this.settings.taxonomyFilters !== null && _this.hasEmptyObjectVals(filters)) {
				_this.checkFilters();
			}
			/**
			 * Process the location data
			 */
			// Raw data
			if ( _this.settings.dataRaw !== null ) {
				_this.processData(mappingObject, originPoint, dataRequest, page);
			}
			// Remote data
			else {
				dataRequest.done(function (data) {
					_this.processData(mappingObject, originPoint, data, page);
				});
			}
		}
437524
def update(instance, full_clean=True, post_save=False, **kwargs):
    ""

    # apply the updated args to the instance to mimic the change
    # note that these might slightly differ from the true database values
    # as the DB could have been updated by another thread. callers should
    # retrieve a new copy of the object if up-to-date values are required
    for k, v in kwargs.iteritems():
        if isinstance(v, ExpressionNode):
            v = resolve_expression_node(instance, v)
        setattr(instance, k, v)

    # clean instance before update
    if full_clean:
        instance.full_clean()

    # fields that use auto_now=True should be updated corrected, too!
    for field in instance._meta.fields:
        if hasattr(field, 'auto_now') and field.auto_now and field.name not in kwargs:
            kwargs[field.name] = field.pre_save(instance, False)

    rows_affected = instance.__class__._default_manager.filter(
        pk=instance.pk).update(**kwargs)

    if post_save:
        signals.post_save.send(sender=instance.__class__, instance=instance)

    return rows_affected
382762
function(field, value) {
        if (field in this) {
            if (this.get(field) !== value && !([
                null,
                undefined
            ].indexOf(this.get(field)) > -1 && [
                null,
                undefined
            ].indexOf(value) > -1)) {
                if (CRUD.EntityManager.entities[this.getType()].autoSerialize.indexOf(field) > -1) {
                    if (JSON.stringify(this.get(field)) != JSON.stringify(value)) {
                        this.__dirtyValues__[field] = value;
                    }
                } else {
                    this.__dirtyValues__[field] = value;
                }
            }
        } else {
            CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for set)');
        }
    }
653783
def save(self):
        """"""
        check_bind(self)

        creating = self.id is None
        if creating and not self.__class__._has_schema_method("create"):
            raise MethodNotSupported("{} do not support creating.".format(self.__class__.__name__))
        if not creating and not self.__class__._has_schema_method("update"):
            raise MethodNotSupported("{} do not support updating.".format(self.__class__.__name__))

        try:
            self._resource.save()
        except HTTPError as e:
            if e.response.status_code == 400:
                err_json = e.response.json().get("errors", [])
                msg = pretty_print_error(err_json)
                raise ServerError(msg)
            elif e.response.status_code == 404:
                action = "creating" if creating else "updating"
                raise MethodNotSupported(
                    "{} do not support {}.".format(self.__class__.__name__, action)
                )
            elif e.response.status_code == 409:
                raise ServerError("This {} object already exists".format(self.__class__.__name__))
            else:
                raise e
902487
function convertRawDate(rawColumnValue, column, context)
{
  return new SfTimestamp(
      Number(rawColumnValue) * 86400, // convert to seconds
      0,                              // no nano seconds
      0,                              // no scale required
      'UTC',                          // use utc as the timezone
      context.format).toSfDate();
}
310835
def from_json(self, document):
        
        # The timestamp is optional (e.g., in cases where model definitions are
        # loaded from file).
        if 'timestamp' in document:
            timestamp = datetime.datetime.strptime(
                document['timestamp'],
                '%Y-%m-%dT%H:%M:%S.%f'
            )
        else:
            timestamp = None
        # Create handle for database object
        return ModelHandle(
            document['_id'],
            document['properties'],
            [AttributeDefinition.from_json(el) for el in document['parameters']],
            ModelOutputs.from_json(document['outputs']),
            timestamp=timestamp
        )
1064355
def save(self, force_eav=False, **kwargs):
        
        # save entity
        super(BaseEntity, self).save(**kwargs)

        # TODO: think about use cases; are we doing it right?
        #if not self.check_eav_allowed():
        #    import warnings
        #    warnings.warn('EAV attributes are going to be saved along with entity'
        #                  ' despite %s.check_eav_allowed() returned False.'
        #                  % type(self), RuntimeWarning)


        # create/update EAV attributes
        for schema in self.get_schemata():
            value = getattr(self, schema.name, None)
            schema.save_attr(self, value)
173671
function(db_schema) {

        // add existing object store
        if (schema instanceof ydn.db.schema.EditableDatabase) {
          var editable = /** @type {ydn.db.schema.EditableDatabase} */ (schema);
          for (var i = 0; i < db_schema.stores.length; i++) {
            if (!editable.hasStore(db_schema.stores[i].getName())) {
              editable.addStore(db_schema.stores[i].clone());
            }
          }
        }

        var diff_msg = schema.difference(db_schema, false, true);
        if (diff_msg.length > 0) {
          goog.log.log(me.logger, goog.log.Level.FINER, 'Schema change require for difference in ' +
              diff_msg);

          var on_completed = function(t, e) {
            if (t == ydn.db.base.TxEventTypes.COMPLETE) {
              setDb(db);
            } else {
              goog.log.error(me.logger, 'Fail to update version on ' + db.name + ':' +
                  db.version);
              setDb(null, e);
            }
          };

          var next_version = goog.isNumber(db.version) ? db.version + 1 : 1;

          if (!ydn.db.base.OLD_INDEXEDDB_SUPPORT || 'IDBOpenDBRequest' in goog.global) {
            db.close();
            var req = ydn.db.base.indexedDb.open(
                dbname, /** @type {number} */ (next_version));
            req.onupgradeneeded = function(ev) {
              var db = ev.target.result;
              goog.log.log(me.logger, goog.log.Level.FINER, 're-open for version ' + db.version);
              updateSchema(db, req['transaction'], false);

            };
            req.onsuccess = function(ev) {
              setDb(ev.target.result);
            };
            req.onerror = function(e) {
              goog.log.log(me.logger, goog.log.Level.FINER, me + ': fail.');
              setDb(null);
            };
          } else if (ydn.db.base.OLD_INDEXEDDB_SUPPORT) {
            var ver_request = db.setVersion(next_version + '');

            ver_request.onfailure = function(e) {
              goog.log.warning(me.logger, 'migrating from ' + db.version + ' to ' +
                  next_version + ' failed.');
              setDb(null, e);
            };


            var trans = ver_request['transaction'];
            ver_request.onsuccess = function(e) {

              ver_request['transaction'].oncomplete = tr_on_complete;

              updateSchema(db, ver_request['transaction'], true);
            };

            var tr_on_complete = function(e) {

              // for old format.
              // by reopening the database, we make sure that we are not in
              // version change state since transaction cannot open during
              // version change state.
              // db.close(); // necessary - cause error ?
              var reOpenRequest = ydn.db.base.indexedDb.open(dbname);
              reOpenRequest.onsuccess = function(rev) {
                var db = rev.target.result;
                goog.log.log(me.logger, goog.log.Level.FINER, me + ': OK.');
                setDb(db);
              };

              reOpenRequest.onerror = function(e) {
                goog.log.log(me.logger, goog.log.Level.FINER, me + ': fail.');
                setDb(null);
              };
            };

            if (goog.isDefAndNotNull(ver_request['transaction'])) {
              ver_request['transaction'].oncomplete = tr_on_complete;
            }

          }

        } else {
          setDb(db);
        }
      }
1199745
def prepare_date(data, schema):
    """"""
    if isinstance(data, datetime.date):
        return data.toordinal() - DAYS_SHIFT
    else:
        return data
624997
function timestampsPlugin(schema, options) {

  // Add the fields to the schema
  schema.add({
    createdAt: {
      type: Date,
      'default': Date.now
    },
    updatedAt: {
      type: Date,
      'default': Date.now
    },
    deletedAt: {
      type: Date,
      sparse: true
    }
  });

  // Define the pre save hook
  schema.pre('save', function (next) {
    this.updatedAt = new Date();
    next();
  });

  // Create an index on all the paths
  schema.path('createdAt').index(true);
  schema.path('updatedAt').index(true);
  schema.path('deletedAt').index(true);
}