Serialize and save a model.

        Example:
            end_model = EndModel(...)
            end_model.train_model(...)
            end_model.save("my_end_model.pkl")
342843
def save(self, destination, **kwargs):
        
        with open(destination, "wb") as f:
            torch.save(self, f, **kwargs)
1127380
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
    
    if action == "post_add":
        try:
            wrapped_instance = site_offline_models.get_wrapped_instance(instance)
        except ModelNotRegistered:
            pass
        else:
            wrapped_instance.to_outgoing_transaction(using, created=True)
1192262
def save(self):
        
        logger.debug(
            f'Saving `{self.__class__.__name__}` object')

        # Fetch Model class and connected repository from Repository Factory
        model_cls = repo_factory.get_model(self.__class__)
        repository = repo_factory.get_repository(self.__class__)

        try:
            # Do unique checks, update the record and return the Entity
            self._validate_unique(create=False)

            # Perform Pre-Save Actions
            self.pre_save()

            # Build the model object and create it
            model_obj = repository.create(model_cls.from_entity(self))

            # Update the auto fields of the entity
            for field_name, field_obj in self.meta_.declared_fields.items():
                if isinstance(field_obj, Auto):
                    if isinstance(model_obj, dict):
                        field_val = model_obj[field_name]
                    else:
                        field_val = getattr(model_obj, field_name)
                    setattr(self, field_name, field_val)

            # Set Entity status to saved
            self.state_.mark_saved()

            # Perform Post-Save Actions
            self.post_save()

            return self
        except Exception:
            # FIXME Log Exception
            raise
499322
def save(self, model, path=''):
        """"""
        if model['type'] != 'notebook':
            return super(TextFileContentsManager, self).save(model, path)

        nbk = model['content']
        try:
            metadata = nbk.get('metadata')
            rearrange_jupytext_metadata(metadata)
            jupytext_metadata = metadata.setdefault('jupytext', {})
            jupytext_formats = jupytext_metadata.get('formats') or self.default_formats(path)

            if not jupytext_formats:
                text_representation = jupytext_metadata.get('text_representation', {})
                ext = os.path.splitext(path)[1]
                fmt = {'extension': ext}

                if ext == text_representation.get('extension') and text_representation.get('format_name'):
                    fmt['format_name'] = text_representation.get('format_name')

                jupytext_formats = [fmt]

            jupytext_formats = long_form_multiple_formats(jupytext_formats, metadata)

            # Set preferred formats if not format name is given yet
            jupytext_formats = [preferred_format(fmt, self.preferred_jupytext_formats_save) for fmt in jupytext_formats]

            base, fmt = find_base_path_and_format(path, jupytext_formats)
            self.update_paired_notebooks(path, fmt, jupytext_formats)
            self.set_default_format_options(jupytext_metadata)

            if not jupytext_metadata:
                metadata.pop('jupytext')

            # Save as ipynb first
            return_value = None
            value = None
            for fmt in jupytext_formats[::-1]:
                if fmt['extension'] != '.ipynb':
                    continue

                alt_path = full_path(base, fmt)
                self.create_prefix_dir(alt_path, fmt)
                self.log.info("Saving %s", os.path.basename(alt_path))
                value = super(TextFileContentsManager, self).save(model, alt_path)
                if alt_path == path:
                    return_value = value

            # And then to the other formats, in reverse order so that
            # the first format is the most recent
            for fmt in jupytext_formats[::-1]:
                if fmt['extension'] == '.ipynb':
                    continue

                alt_path = full_path(base, fmt)
                self.create_prefix_dir(alt_path, fmt)
                if 'format_name' in fmt and fmt['extension'] not in ['.Rmd', '.md']:
                    self.log.info("Saving %s in format %s:%s",
                                  os.path.basename(alt_path), fmt['extension'][1:], fmt['format_name'])
                else:
                    self.log.info("Saving %s", os.path.basename(alt_path))
                with mock.patch('nbformat.writes', _jupytext_writes(fmt)):
                    value = super(TextFileContentsManager, self).save(model, alt_path)
                    if alt_path == path:
                        return_value = value

            # Update modified timestamp to match that of the pair #207
            return_value['last_modified'] = value['last_modified']
            return return_value

        except Exception as err:
            raise HTTPError(400, str(err))
670047
def _save_model(self, section):
        
        checkpoint_name = self.flags['LOGGING_DIRECTORY'] + 'part_%d' % section + '.ckpt'
        save_path = self.saver.save(self.sess, checkpoint_name)
        print("Model saved in file: %s" % save_path)
668970
def serialize(self, value, primitive=False):
        """"""
        if hasattr(value, 'serialize'):
            # i.e. value is a nested model
            return value.serialize(primitive=primitive)
        else:
            return value
1298083
def store_model(factory, name, record)
      store_record(record.class.name, name, record) unless pickle_parser.canonical(factory) == pickle_parser.canonical(record.class.name)
      store_record(factory, name, record)
    end
560690
def save_model(self, file_name='model.sbgn'):
        
        model = self.print_model()
        with open(file_name, 'wb') as fh:
            fh.write(model)
751397
def save_pkl(self, filename):
        
        with open(filename, 'wb') as fout:
            pickle.dump(self, fout)
257286
def save_model(self, net):
        
        if self.f_params is not None:
            f = self._format_target(net, self.f_params, -1)
            self._save_params(f, net, "f_params", "model parameters")

        if self.f_optimizer is not None:
            f = self._format_target(net, self.f_optimizer, -1)
            self._save_params(f, net, "f_optimizer", "optimizer state")

        if self.f_history is not None:
            f = self.f_history_
            self._save_params(f, net, "f_history", "history")

        if self.f_pickle:
            f_pickle = self._format_target(net, self.f_pickle, -1)
            with open_file_like(f_pickle, 'wb') as f:
                pickle.dump(net, f)
844729
def field_definition_post_save(sender, instance, created, raw, **kwargs):
    
    model_class = instance.model_def.model_class().render_state()
    field = instance.construct_for_migrate()
    field.model = model_class
    if created:
        if hasattr(instance._state, '_creation_default_value'):
            field.default = instance._state._creation_default_value
            delattr(instance._state, '_creation_default_value')
        add_column = popattr(instance._state, '_add_column', True)
        if add_column:
            perform_ddl('add_field', model_class, field)
            # If the field definition is raw we must re-create the model class
            # since ModelDefinitionAttribute.save won't be called
            if raw:
                instance.model_def.model_class().mark_as_obsolete()
    else:
        old_field = instance._state._pre_save_field
        delattr(instance._state, '_pre_save_field')
        perform_ddl('alter_field', model_class, old_field, field, strict=True)
295398
def save(self, **kwargs):
        
        validated_data = [
            dict(list(attrs.items()) + list(kwargs.items()))
            for attrs in self.validated_data
        ]

        if "id" in validated_data:
            ModelClass = self.Meta.model

            try:
                self.instance = ModelClass.objects.get(id=validated_data["id"])
            except ModelClass.DoesNotExist:
                pass

        return super(VideohubVideoSerializer, self).save(**kwargs)
419575
def serialize_model(model):
    

    result = ''

    # First serialize the macros
    for macro in model['macros']:
        if macro.get('options', None):
            result += '~o '
            for option in macro['options']['definition']:
                result += _serialize_option(option)

        elif macro.get('transition', None):
            result += '~t "{}"\n'.format(macro['transition']['name'])
            result += _serialize_transp(macro['transition']['definition'])

        elif macro.get('variance', None):
            result += '~v "{}"\n'.format(macro['variance']['name'])
            result += _serialize_variance(macro['variance']['definition'])

        elif macro.get('state', None):
            result += '~s "{}"\n'.format(macro['state']['name'])
            result += _serialize_stateinfo(macro['state']['definition'])

        elif macro.get('mean', None):
            result += '~u "{}"\n'.format(macro['mean']['name'])
            result += _serialize_mean(macro['mean']['definition'])

        elif macro.get('duration', None):
            result += '~d "{}"\n'.format(macro['duration']['name'])
            result += _serialize_duration(macro['duration']['definition'])

        else:
            raise NotImplementedError('Cannot serialize {}'.format(macro))

    for hmm in model['hmms']:
        if hmm.get('name', None) is not None:
            result += '~h "{}"\n'.format(hmm['name'])

        result += _serialize_hmm(hmm['definition'])

    return result
830824
public String save(long start, long end) throws PiliException {
        SaveOptions args = new SaveOptions(start, end);
        return save(args);
    }
619982
def save_models(self, models_file):
        
        if self.model_parameters_iterations is None:
            raise ValueError("No iterations have been carried out yet and hence no iterations of the BO can be saved")

        iterations = np.array(range(1,self.model_parameters_iterations.shape[0]+1))[:,None]
        results = np.hstack((iterations,self.model_parameters_iterations))
        header = ['Iteration'] + self.model.get_model_parameters_names()

        data = [header] + results.tolist()
        self._write_csv(models_file, data)
713581
def save_state(state, output_dir, keep=False):
  """"""
  params_file = os.path.join(output_dir, "model.pkl")
  with gfile.GFile(params_file, "wb") as f:
    pickle.dump((state.params, state.step, state.history), f)
  if keep:
    params_file = os.path.join(output_dir, "model_{}.pkl".format(state.step))
    with gfile.GFile(params_file, "wb") as f:
      pickle.dump((state.params, state.step, state.history), f)
  log("Model saved to %s" % params_file, stdout=False)
106559
def finalize(self, params, rep):
    
    if params.get("saveNet", True):
      saveDir = os.path.join(params["path"], params["name"],
                             "model_{}.pt".format(rep))
      torch.save(self.model, saveDir)