Change an existing object
969430
def change(self, event):
        """"""

        try:
            data, schema, user, client = self._get_args(event)
        except AttributeError:
            return

        try:
            uuid = data['uuid']
            change = data['change']
            field = change['field']
            new_data = change['value']
        except KeyError as e:
            self.log("Update request with missing arguments!", data, e,
                     lvl=critical)
            self._cancel_by_error(event, 'missing_args')
            return

        storage_object = None

        try:
            storage_object = objectmodels[schema].find_one({'uuid': uuid})
        except Exception as e:
            self.log('Change for unknown object requested:', schema, data, lvl=warn)

        if storage_object is None:
            self._cancel_by_error(event, 'not_found')
            return

        if not self._check_permissions(user, 'write', storage_object):
            self._cancel_by_permission(schema, data, event)
            return

        self.log("Changing object:", storage_object._fields, lvl=debug)
        storage_object._fields[field] = new_data

        self.log("Storing object:", storage_object._fields, lvl=debug)
        try:
            storage_object.validate()
        except ValidationError:
            self.log("Validation of changed object failed!",
                     storage_object, lvl=warn)
            self._cancel_by_error(event, 'invalid_object')
            return

        storage_object.save()

        self.log("Object stored.")

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'change',
            'data': {
                'schema': schema,
                'uuid': uuid
            }
        }

        self._respond(None, result, event)
608794
function renameKey(obj, oldKey, newKey) {
    var retObject = {};
    var index, ptr;

    if (typeof obj != "object") {
        return retObject;
    }

    var oldKeyType = typeof oldKey;
    var newKeyType = typeof newKey;
    if (oldKeyType == "string"
        && newKeyType == "string") {
        for (index in obj) {
            if (obj.hasOwnProperty(index)) {
                if (index == oldKey) {
                    retObject[newKey] = obj[index];
                } else {
                    retObject[index] = obj[index];
                }
            }
        }
    } else if (oldKeyType == "object"
        && newKeyType == "object"
        && oldKey.hasOwnProperty("length")
        && newKey.hasOwnProperty("length")
        && oldKey.length <= newKey.length
        ) {
        for (index in obj) {
            if (obj.hasOwnProperty(index)) {
                ptr = oldKey.indexOf(index);
                if (ptr >= 0) {
                    retObject[newKey[ptr]] = obj[index];
                } else {
                    retObject[index] = obj[index];
                }
            }
        }
    }

    return retObject;
}
591381
private boolean updateExistingObject(DBObject dbObj, Map<String, String> currScalarMap) {
        if (objectIsChangingShards(dbObj, currScalarMap)) {
            return updateShardedObjectMove(dbObj);
        } else {
            return updateObjectSameShard(dbObj, currScalarMap);
        }
    }
1336361
def modify(ctx, schema, uuid, object_filter, field, value):
    """"""
    database = ctx.obj['db']

    model = database.objectmodels[schema]
    obj = None

    if uuid:
        obj = model.find_one({'uuid': uuid})
    elif object_filter:
        obj = model.find_one(literal_eval(object_filter))
    else:
        log('No object uuid or filter specified.',
            lvl=error)

    if obj is None:
        log('No object found',
            lvl=error)
        return

    log('Object found, modifying', lvl=debug)
    try:
        new_value = literal_eval(value)
    except ValueError:
        log('Interpreting value as string')
        new_value = str(value)

    obj._fields[field] = new_value
    obj.validate()
    log('Changed object validated', lvl=debug)
    obj.save()
    log('Done')
89905
function setProto (oldObj, newObj) {
  Object.keys(newObj).forEach(key => {
    if (!oldObj[key]) {
      oldObj[key] = JSON.parse(JSON.stringify(newObj[key]))
    }
  })
}
698215
def put_object(request, old_pid):
    """"""
    if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE:
        d1_gmn.app.auth.assert_create_update_delete_permission(request)
    d1_gmn.app.util.coerce_put_post(request)
    d1_gmn.app.views.assert_db.post_has_mime_parts(
        request, (('field', 'newPid'), ('file', 'object'), ('file', 'sysmeta'))
    )
    d1_gmn.app.views.assert_db.is_valid_pid_to_be_updated(old_pid)
    sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta'])
    new_pid = request.POST['newPid']
    d1_gmn.app.views.assert_sysmeta.matches_url_pid(sysmeta_pyxb, new_pid)
    d1_gmn.app.views.assert_sysmeta.obsoletes_matches_pid_if_specified(
        sysmeta_pyxb, old_pid
    )
    sysmeta_pyxb.obsoletes = old_pid
    sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId')
    d1_gmn.app.views.assert_sysmeta.is_valid_sid_for_chain(old_pid, sid)
    d1_gmn.app.views.create.create_sciobj(request, sysmeta_pyxb)
    # The create event for the new object is added in create_sciobj(). The update
    # event on the old object is added here.
    d1_gmn.app.event_log.log_update_event(
        old_pid,
        request,
        timestamp=d1_common.date_time.normalize_datetime_to_utc(
            sysmeta_pyxb.dateUploaded
        ),
    )
    d1_gmn.app.sysmeta.update_modified_timestamp(old_pid)
    return new_pid
610190
def patch_object(obj, attr, value):
    
    orig = getattr(obj, attr, no_value)

    try:
        setattr(obj, attr, value)

        yield obj
    finally:
        try:
            if orig is no_value:
                delattr(obj, attr)
            else:
                setattr(obj, attr, orig)
        except:
            pass
811163
public static void rename(ObjectNode obj, String oldFieldName, String newFieldName) {
		if (obj != null && isNotBlank(oldFieldName) && isNotBlank(newFieldName)) {
			JsonNode node = remove(obj, oldFieldName);
			if (node != null) {
				obj.set(newFieldName, node);
			}
		}
	}
757920
def replace(self, request, id):
        """"""
        try:
            object = self.model.objects.get(id=id)
        except self.model.DoesNotExist:
            return self._render(
                request = request,
                template = '404',
                context = {
                    'error': 'The %s could not be found.' % self.model.__name__.lower()
                },
                status = 404,
                prefix_template_path = False
            )

        form = (self.form or generate_form(self.model))(request.PUT, instance=object)

        if form.is_valid():
            object = form.save()

            return self.show(request, id)
        else:
            return self._render(
                request = request,
                template = 'edit',
                context = {
                    'form': form
                },
                status = 400
            )
25026
public Object setValue(Object obj)
    {
        Object old = valueRealSubject;

        valueRealSubject = obj;
        return old;
    }
805035
def change_keys(obj, convert):
    
    if isinstance(obj, (str, int, float)):
        return obj
    if isinstance(obj, dict):
        new = obj.__class__()
        for k, v in obj.items():
            new[convert(k)] = change_keys(v, convert)
    elif isinstance(obj, (list, set, tuple)):
        new = obj.__class__(change_keys(v, convert) for v in obj)
    else:
        return obj
    return new
724558
def setattr(self, attr, new_value, close_the_changeset=True):
        """"""
        existing_value = getattr(self, attr, None)
        if existing_value != new_value:
            setattr(self, attr, new_value)
            self._changeset[attr] = new_value

        if close_the_changeset and self._changeset:
            self._call_callbacks()
1012810
def add_object(self, obj):
        ''''''
        state = self.state
        if not obj.layer in state.layers:
            # its a new layer
            state.layers[obj.layer] = {}
        state.layers[obj.layer][obj.key] = obj
        state.need_redraw = True
794
function(obj, type, name, nameIsUnique, oldName) {
    var nameMap, objList

    this._store[type] = nameMap = this._store[type] || {}
    nameMap[name] = objList = nameMap[name] || []

    // Adding new mapping
    if (objList.indexOf(obj) === -1) {
      if (nameIsUnique && objList.length > 0)
        throw new Error('there is already a ' + type + ' with name "' + name + '"')
      objList.push(obj)
    }

    // Removing old mapping
    if (oldName) {
      objList = nameMap[oldName]
      objList.splice(objList.indexOf(obj), 1)
    }

    exports.emitter.emit('namedObjects:registered:' + type, obj)
  }
1001254
function objectObserver(changes) {
    changes.forEach(({type, name}) => {
      switch (type) {
      case 'add':    o[name] = u[name]; break;
      case 'delete': delete o[name];    break;
      }
    });
  }
1293060
def change_view(self, request, object_id, form_url='', extra_context=None):
        """"""

        obj = self.get_object(request, unquote(object_id))

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
                'name': force_text(self.opts.verbose_name),
                'key': escape(object_id),
            })

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        content_block = obj.content_block
        version = content_block.obj_version

        # Version must not be saved, and must belong to this user
        if version.version_number or version.owner != request.user:
            raise PermissionDenied

        return super().change_view(request, object_id, form_url, extra_context)
1357345
def clean_existing(self, value):
        
        existing_pk = value[self.pk_field]
        try:
            obj = self.fetch_existing(existing_pk)
        except ReferenceNotFoundError:
            raise ValidationError('Object does not exist.')
        orig_data = self.get_orig_data_from_existing(obj)

        # Clean the data (passing the new data dict and the original data to
        # the schema).
        value = self.schema_class(value, orig_data).full_clean()

        # Set cleaned data on the object (except for the pk_field).
        for field_name, field_value in value.items():
            if field_name != self.pk_field:
                setattr(obj, field_name, field_value)

        return obj