Owned mongoengine.pre_save signal handler
    Need to fetch original owner before the new one erase it.
499654
def owned_pre_save(sender, document, **kwargs):
    '''
    
    '''
    if not isinstance(document, Owned):
        return
    changed_fields = getattr(document, '_changed_fields', [])
    if 'organization' in changed_fields:
        if document.owner:
            # Change from owner to organization
            document._previous_owner = document.owner
            document.owner = None
        else:
            # Change from org to another
            # Need to fetch previous value in base
            original = sender.objects.only('organization').get(pk=document.pk)
            document._previous_owner = original.organization
    elif 'owner' in changed_fields:
        if document.organization:
            # Change from organization to owner
            document._previous_owner = document.organization
            document.organization = None
        else:
            # Change from owner to another
            # Need to fetch previous value in base
            original = sender.objects.only('owner').get(pk=document.pk)
            document._previous_owner = original.owner
154973
def reload(self):
        ''' '''
        key = self.key()
        redis = type(self).get_redis()

        if not redis.exists(key):
            raise ModelNotFoundError('This object has been deleted')

        data = debyte_hash(redis.hgetall(key))

        for fieldname, field in self.proxy:
            value = field.recover(data, redis)

            setattr(
                self,
                fieldname,
                value
            )

        return self
775894
def delete(self, using=None):
        
        from organizations.exceptions import OwnershipRequired

        try:
            if self.organization.owner.organization_user.pk == self.pk:
                raise OwnershipRequired(
                    _(
                        "Cannot delete organization owner "
                        "before organization or transferring ownership."
                    )
                )
        # TODO This line presumes that OrgOwner model can't be modified
        except self._org_owner_model.DoesNotExist:
            pass
        super(AbstractBaseOrganizationUser, self).delete(using=using)
898890
function toStorableUnusableRecordState(unusableRecordState, unusableRecord, context) {
  if (!unusableRecordState) {
    context.warn(`Skipping save of state for unusable record, since it has no state - record (${JSON.stringify(unusableRecord)})`);
    return undefined;
  }

  // Convert the record's state into a safely storable object to get a clean, simplified version of its state
  const state = dynamoDBUtils.toStorableObject(unusableRecordState);

  // If state has no record identifier then have no way to identify the unusable record ... so attach a safely storable
  // copy of its original user record or record (if any) (without its legacy state, if any) for later matching!
  if (!hasUnusableRecordIdentifier(unusableRecordState)) {
    unusableRecord = unusableRecord || unusableRecordState.unusableRecord;

    if (unusableRecord) {
      // Make a storable copy of the unusable record & attach it to the storable state
      state.unusableRecord = dynamoDBUtils.toStorableObject(unusableRecord);
      // Remove the unusable record copy's LEGACY state (if any) to get back to the original unusable record
      tracking.deleteLegacyState(unusableRecord, context);
    }
    if (unusableRecordState.userRecord) {
      // Make a storable copy of the unusable record's user record & attach it to the storable state
      state.userRecord = dynamoDBUtils.toStorableObject(unusableRecordState.userRecord);
      // Remove the unusable record's user record copy's LEGACY state (if any) to get back to the original user record
      tracking.deleteLegacyState(state.userRecord, context);
    }
    else if (unusableRecordState.record) {
      // Make a storable copy of the unusable record's record & attach it to the storable state
      state.record = dynamoDBUtils.toStorableObject(unusableRecordState.record);
      // remove the unusable record's record copy's LEGACY state (if any) to get back to the original record
      tracking.deleteLegacyState(state.record, context);
    }
  }
  return state;
}
643727
def old(self):
        
        ori = self.original.action
        if isinstance(ori, (
                types.ChannelAdminLogEventActionChangeAbout,
                types.ChannelAdminLogEventActionChangeTitle,
                types.ChannelAdminLogEventActionChangeUsername
        )):
            return ori.prev_value
        elif isinstance(ori, types.ChannelAdminLogEventActionChangePhoto):
            return ori.prev_photo
        elif isinstance(ori, types.ChannelAdminLogEventActionChangeStickerSet):
            return ori.prev_stickerset
        elif isinstance(ori, types.ChannelAdminLogEventActionEditMessage):
            return ori.prev_message
        elif isinstance(ori, (
                types.ChannelAdminLogEventActionParticipantToggleAdmin,
                types.ChannelAdminLogEventActionParticipantToggleBan
        )):
            return ori.prev_participant
        elif isinstance(ori, (
                types.ChannelAdminLogEventActionToggleInvites,
                types.ChannelAdminLogEventActionTogglePreHistoryHidden,
                types.ChannelAdminLogEventActionToggleSignatures
        )):
            return not ori.new_value
        elif isinstance(ori, types.ChannelAdminLogEventActionDeleteMessage):
            return ori.message
        elif isinstance(ori, types.ChannelAdminLogEventActionDefaultBannedRights):
            return ori.prev_banned_rights
951385
function (sid, callback) {
        var cb = callback || _.noop;

        // ensureIndex is already called on start-up
        mongooseModel.findOne(_applyProp(propSid, sid), function(err, doc) {

          if(err || !doc) { // exit immediately
            cb(err, null);
            return;
          }

          if(_checkExpiration(doc) && doc[propData] !== undefined) { // we're still valid:
            cb(null, unserializer(doc[propData]));
          }
          else { // needs clean-up
            me.destroy(sid, cb);
          }
        });
      }
1366669
def invalidate_previous_tokens(sender, instance, **kwargs):
    
    active_tokens = None
    if isinstance(instance, CallbackToken):
        active_tokens = CallbackToken.objects.active().filter(user=instance.user).exclude(id=instance.id)

    # Invalidate tokens
    if active_tokens:
        for token in active_tokens:
            token.is_active = False
            token.save()
1053124
def _take_ownership(self):
        

        if self:
            ptr = cast(self.value, GIBaseInfo)
            _UnrefFinalizer.track(self, ptr)
            self.__owns = True
381247
def _remove_till_caught_up_3pc(self, last_caught_up_3PC):
        
        outdated_pre_prepares = {}
        for key, pp in self.prePrepares.items():
            if compare_3PC_keys(key, last_caught_up_3PC) >= 0:
                outdated_pre_prepares[key] = pp
        for key, pp in self.sentPrePrepares.items():
            if compare_3PC_keys(key, last_caught_up_3PC) >= 0:
                outdated_pre_prepares[key] = pp

        self.logger.trace('{} going to remove messages for {} 3PC keys'.format(
            self, len(outdated_pre_prepares)))

        for key, pp in outdated_pre_prepares.items():
            self.batches.pop(key, None)
            self.sentPrePrepares.pop(key, None)
            self.prePrepares.pop(key, None)
            self.prepares.pop(key, None)
            self.commits.pop(key, None)
            self._discard_ordered_req_keys(pp)
800874
function(fields, oldValue) {
            fields = this.__resolveFields(fields);

            var prop, key;

            this.__checkEmitEvent(true);

            if (fields.length) {
                prop = fields.slice(0, -1).join('.');
                key  = _.last(fields);

                this.__emitEvent('property.' + prop + '.item_removed', key, oldValue);
                this.__emitEvent('property.item_removed', prop, key, oldValue);
            }

            prop = fields.join('.');

            this.__emitEvent('property.' + prop + '.remove',  oldValue);
            this.__emitEvent('property.remove', prop, oldValue);

            return this;
        }
480852
function removeOthers(mongoose, model, retainedNames) {
    //console.log('here collectionname' + Object.keys(model));
    //console.log('here collectionname' + model.collectionname);
    return model.aggregate({ $project: { modelname: 1 } }).then((r) => r.map(o => o.modelname)).then((modelnames) => {
        debuglog(" present models " + modelnames.length + ' ' + modelnames);
        var delta = _.difference(modelnames, retainedNames);
        debuglog(' spurious models' + delta.length + ' ' + delta);
        if (delta.length === 0) {
            return Promise.resolve(true);
        }
        return Promise.all(delta.map(modelname => model.remove({ modelname: modelname })));
    });
}
540706
def pre_save_config(sender, instance, *args, **kwargs):
    
    logger.debug("Received pre_save from {}".format(instance))
    if not instance.pk:
        # new model being created
        return
    try:
        old_instance = AutogroupsConfig.objects.get(pk=instance.pk)

        # Check if enable was toggled, delete groups?
        if old_instance.alliance_groups is True and instance.alliance_groups is False:
            instance.delete_alliance_managed_groups()

        if old_instance.corp_groups is True and instance.corp_groups is False:
            instance.delete_corp_managed_groups()
    except AutogroupsConfig.DoesNotExist:
        pass
181078
def change_owner(ctx, owner, uuid):
    """"""

    objects = ctx.obj['objects']
    database = ctx.obj['db']

    if uuid is True:
        owner_filter = {'uuid': owner}
    else:
        owner_filter = {'name': owner}

    owner = database.objectmodels['user'].find_one(owner_filter)
    if owner is None:
        log('User unknown.', lvl=error)
        return

    for item in objects:
        item.owner = owner.uuid
        item.save()

    log('Done')
629836
def unregister_signals(self):
        """"""
        from .models import Collection
        from .percolator import collection_inserted_percolator, \
            collection_removed_percolator, collection_updated_percolator
        # Unregister Record signals
        if hasattr(self, 'update_function'):
            signals.before_record_insert.disconnect(self.update_function)
            signals.before_record_update.disconnect(self.update_function)
        # Unregister collection signals
        if contains(Collection, 'after_insert',
                    collection_inserted_percolator):
            remove(Collection, 'after_insert', collection_inserted_percolator)
            remove(Collection, 'after_update', collection_updated_percolator)
            remove(Collection, 'after_delete', collection_removed_percolator)
422047
def pre_save(self, instance, add):
        
        # get currently entered slug
        value = self.value_from_object(instance)
        slug = None

        # auto populate (if the form didn't do that already).
        # If you want unique_with logic, use django-autoslug instead.
        # This model field only allows parameters which can be passed to the form widget too.
        if self.populate_from and (self.always_update or not value):
            value = getattr(instance, self.populate_from)

        # Make sure the slugify logic is applied,
        # even on manually entered input.
        if value:
            value = force_text(value)
            slug = self.slugify(value)
            if self.max_length < len(slug):
                slug = slug[:self.max_length]

        # make the updated slug available as instance attribute
        setattr(instance, self.name, slug)
        return slug
497187
function setBeforeRouteChangeHandler(handler) {
            if (null == handler) {
                return _beforeRouteChange;
            }
            else {
                var oldHandler = _beforeRouteChange;
                _beforeRouteChange = handler;
                return oldHandler;
            }
        }
1079500
function () {
			this.saveOperation = {};
			this.saveOperation.entity = this.ctrl.editor.getPlainValue();
			this.saveOperation.oldEntity = this.ctrl.editor.getOldValue();
			var me =this;
			var args = arguments;
			this.ctrl.editor.bufferChange(function() {
				me.inherited(args);
			});

		}