Serialize an object to disk using pickle protocol.

    Args:
        obj: The object to serialize.
        filename: Path to the output file.
        protocol: Version of the pickle protocol.
352299
def save(obj, filename, protocol=4):
    

    with open(filename, 'wb') as f:
        pickle.dump(obj, f, protocol=protocol)
522519
function serializeObject(obj) {
  var seen = [];

  return JSON.stringify(obj, function(key, val) {
    val = toJsonReplacer(key, val);
    if (isObject(val)) {

      if (seen.indexOf(val) >= 0) return '...';

      seen.push(val);
    }
    return val;
  });
}
436786
def pickle(self) -> None:
        

        pickle_path = self.tgt_dir / "corpus.p"
        logger.debug("pickling %r object and saving it to path %s", self, pickle_path)
        with pickle_path.open("wb") as f:
            pickle.dump(self, f)
1103059
def dump(self, obj, key=None):
        """"""
        if key is None:
            key = '_pickle'
        with preserve_current_directory():
            self.__file.cd()
            if sys.version_info[0] < 3:
                pickle.Pickler.dump(self, obj)
            else:
                super(Pickler, self).dump(obj)
            s = ROOT.TObjString(self.__io.getvalue())
            self.__io.reopen()
            s.Write(key)
            self.__file.GetFile().Flush()
            self.__pmap.clear()
130887
def serialize(obj, **options):
    '''
    
    '''

    try:
        if 'file_out' in options:
            return toml.dump(obj, options['file_out'], **options)
        else:
            return toml.dumps(obj, **options)
    except Exception as error:
        raise SerializationError(error)
95922
def serialize_to_file(obj, file_name, append=False):
  """"""
  logging.info("Serializing to file %s.", file_name)
  with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file:
    pickle.dump(obj, output_file)
  logging.info("Done serializing to file %s.", file_name)
987600
public static String serialize(final Object obj) throws IOException {
		final ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
		return mapper.writeValueAsString(obj);
		
	}
1170580
def model_to_file(model, filename):
    
    with open(filename, 'wb') as f:
        pickle.dump(model, f)
683864
public byte[] serialize(final Object obj, final int bufferSize) {
    return kryoOutputPool.run(output -> {
      return kryoPool.run(kryo -> {
        kryo.writeClassAndObject(output, obj);
        output.flush();
        return output.getByteArrayOutputStream().toByteArray();
      });
    }, bufferSize);
  }
1159784
def _compress_obj(obj, level):
    
    return zlib.compress(pickle.dumps(obj, protocol=2), level)
1314264
def save_json(obj, filename, **kwargs):
    

    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(obj, f, **kwargs)
1240859
public static File toFile(Object obj) throws PageException {
	if (obj instanceof File) return (File) obj;
	return FileUtil.toFile(Caster.toString(obj));
    }
1127941
def _serialize_function(obj):
    
    try:
        obj = inspect.getsource(obj)
    except (TypeError, IOError):
        try:
            obj = marshal.dumps(obj)
        except ValueError:
            if hasattr(obj, '__dict__'):
                obj = _serialize_dict(obj.__dict__)
    return obj
810470
def save_object(filename, obj):
    """"""
    logging.info('saving {}...'.format(filename))
    try:
        with gzip.GzipFile(filename, 'wb') as f:
            f.write(pickle.dumps(obj, 1))
    except Exception as e:
        logging.error('save failure: {}'.format(e))
        raise
125069
def to_data(self, obj, partitioning_strategy=None):
        
        if obj is None:
            return None

        if isinstance(obj, Data):
            return obj

        out = self._create_data_output()
        try:
            serializer = self._registry.serializer_for(obj)
            partitioning_hash = self._calculate_partitioning_hash(obj, partitioning_strategy)

            out.write_int_big_endian(partitioning_hash)
            out.write_int_big_endian(serializer.get_type_id())
            serializer.write(out, obj)
            return Data(out.to_byte_array())
        except:
            handle_exception(sys.exc_info()[1], sys.exc_info()[2])
        finally:
            pass
67525
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True):
    '''

    '''
    # import json
    # with open(filename, mode='w') as f:
    #    json.dump(annotation,f)
    if ndarray_to_list:
        obj = ndarray_to_list_in_structure(obj, squeeze=squeeze)

    # write to yaml
    d = os.path.dirname(os.path.abspath(filename))
    if not os.path.exists(d):
        os.makedirs(d)

    if filetype == 'auto':
        _, ext = os.path.splitext(filename)
        filetype = ext[1:]

    if filetype in ('yaml', 'yml'):
        # import yaml
        from ruamel.yaml import YAML
        yaml = YAML(typ="unsafe")
        with open(filename, 'wt', encoding="utf-8") as f:
            yaml.dump(obj, f)
        # if sys.version_info.major == 2:
        #     with open(filename, 'wb') as f:
        #         yaml.dump(obj, f, encoding="utf-8")
        # else:
        #     with open(filename, "w", encoding="utf-8") as f:
        #         yaml.dump(obj, f)
    elif filetype in ('pickle', 'pkl'):
        f = open(filename, 'wb')
        logger.info("filename " + filename)
        # if sys.version_info[0] < 3: import cPickle as pickle
        # else: import _pickle as pickle
        import pickle
        pickle.dump(obj, f, -1)
        f.close
    elif filetype in ('streamingpicklezip', 'spklz'):
        # this is not working :-(
        import gzip
        import sPickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.s_dump(obj, f)
        f.close
    elif filetype in ('picklezip', 'pklz'):
        import gzip
        if sys.version_info[0] < 3: import cPickle as pickle
        else: import _pickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.dump(obj, f)
        f.close
    elif filetype in('mat'):

        import scipy.io as sio
        sio.savemat(filename, obj)
    else:
        logger.error('Unknown filetype ' + filetype)
364656
def save(self, filename, format=None, **kwargs):
        
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename, 'wb') as fp:
            self.save_to_file_object(fp, format, **kwargs)