Restore a record and all its associations.
359606
def restore_record(record, attributes)
      primary_key = record.class.primary_key
      primary_key = [primary_key].compact unless primary_key.is_a?(Array)
      primary_key.each do |key|
        record.send("#{key.to_s}=", attributes[key.to_s])
      end

      attrs, association_attrs = attributes_and_associations(record.class, attributes)
      attrs.each_pair do |key, value|
        begin
          record.send("#{key}=", value)
        rescue
          record.errors.add(key.to_sym, "could not be restored to #{value.inspect}")
        end
      end

      association_attrs.each_pair do |key, values|
        restore_association(record, key, values) if values
      end
      
      # Check if the record already exists in the database and restore its state.
      # This must be done last because otherwise associations on an existing record
      # can be deleted when a revision is restored to memory.
      exists = record.class.find(record.send(record.class.primary_key)) rescue nil
      if exists
        record.instance_variable_set(:@new_record, nil) if record.instance_variable_defined?(:@new_record)
        # ActiveRecord 3.0.2 and 3.0.3 used @persisted instead of @new_record
        record.instance_variable_set(:@persisted, true) if record.instance_variable_defined?(:@persisted)
      end
    end
246540
def update_record(self, zeroconf, now, record):
        """"""
        if record.type == _TYPE_PTR and record.name == self.type:
            expired = record.is_expired(now)
            try:
                oldrecord = self.services[record.alias.lower()]
                if not expired:
                    oldrecord.reset_ttl(record)
                else:
                    del(self.services[record.alias.lower()])
                    callback = lambda x: self.listener.remove_service(x,
                            self.type, record.alias)
                    self.list.append(callback)
                    return
            except:
                if not expired:
                    self.services[record.alias.lower()] = record
                    callback = lambda x: self.listener.add_service(x,
                            self.type, record.alias)
                    self.list.append(callback)

            expires = record.get_expiration_time(75)
            if expires < self.next_time:
                self.next_time = expires
1121441
def restore(self):
        """"""
        current, self.nlp.pipeline = self.nlp.pipeline, self.original_pipeline
        unexpected = [name for name, pipe in current if not self.nlp.has_pipe(name)]
        if unexpected:
            # Don't change the pipeline if we're raising an error.
            self.nlp.pipeline = current
            raise ValueError(Errors.E008.format(names=unexpected))
        self[:] = []
183201
def MultiResolve(self, records):
    """"""
    for value, timestamp in data_store.DB.CollectionReadItems(records):
      rdf_value = self.RDF_TYPE.FromSerializedString(value)
      rdf_value.age = timestamp
      yield rdf_value
1373641
def call(record, reflection:, skip_record:)
      if reflection.collection?
        _reindex_collection(reflection, record, skip_record)
      else
        _reindex_single(reflection, record, skip_record)
      end
    end
70165
def save(self):
        
        with Repo.db:
            self._do_save()
            our_name = inflector.singularize(Repo.table_name(self.__class__))
            for record in self._related_records:
                if not self._id:
                    related_key = associations.foreign_keys_for(
                        record.__class__)[our_name]
                    setattr(record, related_key, self.__id)
                record._do_save()
            for record in self._delete_related_records:
                record._do_destroy()
        self._finish_save()
581977
public function restore() 
    {
        $state = array_pop($this->savedStates);
        if ($state != NULL) {
            $this->transform = $state['transform'];
            $this->fillStyle = $state['fillStyle'];
        }
    }
1284132
def restore(self):
        """"""
        if not self._snapshot:
            return
        yield from self.set_muted(self._snapshot['muted'])
        yield from self.set_volume(self._snapshot['volume'])
        yield from self.set_stream(self._snapshot['stream'])
        self.callback()
        _LOGGER.info('restored snapshot of state of %s', self.friendly_name)
471808
public function restore() {
        // if database, import database
        if ($this->_hasDatabaseDump()) {
            $this->restoreDatabase();
        } else {
            // Execute a spawn call in batch mode, to make sure all new columns are there
            $spawnCmd = new Garp_Cli_Command_Spawn();
            $spawnCmd->main(array('b' => true, 'only' => 'db'));
        }

        // set permissions on folders
        $this->setWritePermissions();

        // create snippets
        $this->createSnippets();

        // disable under construction
        Garp_Application::setUnderConstruction(false);
    }
446070
def restore(self, request, *args, **kwargs):
        
        paths = request.path_info.split('/')
        object_id_index = paths.index("restore") - 2
        object_id = paths[object_id_index]

        obj = super(VersionedAdmin, self).get_object(request, object_id)
        obj.restore()
        admin_wordIndex = object_id_index - 3
        path = "/%s" % ("/".join(paths[admin_wordIndex:object_id_index]))

        opts = self.model._meta
        msg_dict = {
            'name': force_text(opts.verbose_name),
            'obj': format_html('<a href="{}">{}</a>',
                               urlquote(request.path), obj),
        }

        msg = format_html(_('The {name} "{obj}" was restored successfully.'),
                          **msg_dict)
        self.message_user(request, msg, messages.SUCCESS)
        return HttpResponseRedirect(path)
646908
def cleanup_relations(self):
        """"""
        collections = self.collections
        for relation in [x for col in collections.values()
                         for x in col.model.relations.values()]:
            db.session.query(relation)\
                       .filter(~relation.listing.any())\
                       .delete(synchronize_session=False)
        db.session.commit()
1240873
public function restore()
    {
        //translate model data to sql data
        if (is_null($this->schema)) {
            throw Exception::forNoSchema();
        }

        $data = $this->schema->toSql();

        //queries to run
        $queries = [];

        // check if table is already archived
        if ($this->exists($data['name'])) {
            throw Exception::forSchemaAlreadyExists($data['name']);
        }

        //if there's no system
        if (!$this->exists('_' . $data['name'])) {
            //go to create mode
            return $this->create($data, true);
        }

        $queries[] = 'RENAME TABLE `_' . $data['name'] . '` TO `' . $data['name'] . '`;';

        //determine the relation schema
        foreach ($data['relations'] as $table => $relation) {
            $queries[] = 'RENAME TABLE `_' . $table . '` TO `' . $table . '`;';
        }

        //execute queries
        $results = [];
        foreach ($queries as $query) {
            $results[] = [
                'query' => $query,
                'results' => $this->resource->query($query)
            ];
        }

        return $results;
    }
716028
def reset(self):
        
        ttype = self.tableType()
        if ( not ttype ):
            return False
        
        values = self.saveValues()
        self.setRecord(ttype())
        restore_values = {}
        for column in self.savedColumnsOnReset():
            if column in restore_values:
                restore_values[column] = values[column]
        if restore_values:
            self.loadValues(restore_values)
        
        return True
356470
def restore(self, state):
        """"""

        storage_data = state.get(u'storage_data', [])
        streaming_data = state.get(u'streaming_data', [])

        if len(storage_data) > self.storage_length or len(streaming_data) > self.streaming_length:
            raise ArgumentError("Cannot restore InMemoryStorageEngine, too many readings",
                                storage_size=len(storage_data), storage_max=self.storage_length,
                                streaming_size=len(streaming_data), streaming_max=self.streaming_length)

        self.storage_data = [IOTileReading.FromDict(x) for x in storage_data]
        self.streaming_data = [IOTileReading.FromDict(x) for x in streaming_data]
247027
def restore_row(self, row, schema):
        
        row = list(row)
        for index, field in enumerate(schema.fields):
            if self.__dialect == 'postgresql':
                if field.type in ['array', 'object']:
                    continue
            row[index] = field.cast_value(row[index])
        return row
357492
def load_saved_records(self, status, records):
        """"""
        if isinstance(status, ALDBStatus):
            self._status = status
        else:
            self._status = ALDBStatus(status)
        for mem_addr in records:
            rec = records[mem_addr]
            control_flags = int(rec.get('control_flags', 0))
            group = int(rec.get('group', 0))
            rec_addr = rec.get('address', '000000')
            data1 = int(rec.get('data1', 0))
            data2 = int(rec.get('data2', 0))
            data3 = int(rec.get('data3', 0))
            self[int(mem_addr)] = ALDBRecord(int(mem_addr), control_flags,
                                             group, rec_addr,
                                             data1, data2, data3)
        if self._status == ALDBStatus.LOADED:
            keys = list(self._records.keys())
            keys.sort(reverse=True)
            first_key = keys[0]
            self._mem_addr = first_key
232543
def restore(self):
        """"""
        if self.current_editor is not None:
            self.collapseAll()
            editor_id = self.editor_ids[self.current_editor]
            self.root_item_selected(self.editor_items[editor_id])