Write the data to the given NetCDF file.

        See the general documentation on class |NetCDFVariableFlat|
        for some examples.
763881
def write(self, ncfile) -> None:
        
        self.insert_subdevices(ncfile)
        create_variable(ncfile, self.name, 'f8', self.dimensions)
        ncfile[self.name][:] = self.array
456340
def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
        
        # only add if user adds
        if rivid_lat_lon_z_file and os.path.exists(rivid_lat_lon_z_file):
            # get list of COMIDS
            lookup_table = np.loadtxt(
                rivid_lat_lon_z_file,
                delimiter=",",
                usecols=(0, 1, 2),
                skiprows=1,
                dtype={
                    'names': ('rivid', 'lat', 'lon'),
                    'formats': ('i8', 'f8', 'f8'),
                },
            )

            # Get relevant arrays while we update them
            nc_rivids = data_out_nc.variables['rivid'][:]
            lats = data_out_nc.variables['lat'][:]
            lons = data_out_nc.variables['lon'][:]

            lat_min = None
            lat_max = None
            lon_min = None
            lon_max = None

            # Process each row in the lookup table
            for nc_index, nc_rivid in enumerate(nc_rivids):
                try:
                    lookup_index = \
                        np.where(lookup_table['rivid'] == nc_rivid)[0][0]
                except Exception:
                    raise Exception('rivid {0} misssing in '
                                    'comid_lat_lon_z file'.format(nc_rivid))

                lat = float(lookup_table['lat'][lookup_index])
                lats[nc_index] = lat
                if lat_min is None or lat < lat_min:
                    lat_min = lat
                if lat_max is None or lat > lat_max:
                    lat_max = lat

                lon = float(lookup_table['lon'][lookup_index])
                lons[nc_index] = lon
                if lon_min is None or lon < lon_min:
                    lon_min = lon
                if lon_max is None or lon > lon_max:
                    lon_max = lon

            # Overwrite netCDF variable values
            data_out_nc.variables['lat'][:] = lats
            data_out_nc.variables['lon'][:] = lons

            # Update metadata
            if lat_min is not None:
                data_out_nc.geospatial_lat_min = lat_min
            if lat_max is not None:
                data_out_nc.geospatial_lat_max = lat_max
            if lon_min is not None:
                data_out_nc.geospatial_lon_min = lon_min
            if lon_max is not None:
                data_out_nc.geospatial_lon_max = lon_max
        else:
            print('No comid_lat_lon_z file. Not adding values ...')
915718
def write_data_file(self, data, fn, sort_cols=False, data_format=None):
        
        report.saved_raw_data[fn] = data
        util_functions.write_data_file(data, fn, sort_cols, data_format)
732701
def savenetcdf(dataarray, filename=None):
    
    if filename is None:
        if dataarray.name is not None:
            filename = dataarray.name
        else:
            filename = uuid4().hex[:8]
    else:
        filename = str(Path(filename).expanduser())

    if not filename.endswith('.nc'):
        filename += '.nc'

    dataarray.to_netcdf(filename)
    logger.info('{} has been created.'.format(filename))
979456
def cdfout(data, file):
    
    f = open(file, "w")
    data.sort()
    for j in range(len(data)):
        y = old_div(float(j), float(len(data)))
        out = str(data[j]) + ' ' + str(y) + '\n'
        f.write(out)
    f.close()
277356
def write(self, file_or_filename, prog=None, format='xdot'):
        
        if prog is None:
            file = super(DotWriter, self).write(file_or_filename)
        else:
            buf = StringIO.StringIO()
            super(DotWriter, self).write(buf)
            buf.seek(0)
            data = self.create(buf.getvalue(), prog, format)

            if isinstance(file_or_filename, basestring):
                file = None
                try:
                    file = open(file_or_filename, "wb")
                except:
                    logger.error("Error opening %s." % file_or_filename)
                finally:
                    if file is not None:
                        file.write(data)
                        file.close()
            else:
                file = file_or_filename
                file.write(data)

        return file
991501
def _write_csv(self, df, csv_path, chunksize=10**5):
        
        logger.info("Saving DataFrame to %s", csv_path)
        df.to_csv(csv_path, index=False, chunksize=chunksize)
1146256
def write(self, data):
    
    ctx = context.get()
    if len(data) != 2:
      logging.error("Got bad tuple of length %d (2-tuple expected): %s",
                    len(data), data)

    try:
      key = str(data[0])
      value = str(data[1])
    except TypeError:
      logging.error("Expecting a tuple, but got %s: %s",
                    data.__class__.__name__, data)

    file_index = key.__hash__() % len(self._filehandles)

    # Work-around: Since we don't have access to the context in the to_json()
    # function, but we need to flush each pool before we serialize the
    # filehandle, we rely on a member variable instead of using context for
    # pool management.
    pool = self._pools[file_index]
    if pool is None:
      filehandle = self._filehandles[file_index]
      pool = output_writers.GCSRecordsPool(filehandle=filehandle, ctx=ctx)
      self._pools[file_index] = pool

    proto = kv_pb.KeyValue()
    proto.set_key(key)
    proto.set_value(value)
    pool.append(proto.Encode())
1145884
def write_csvs(dirname: PathLike, adata: AnnData, skip_data: bool = True, sep: str = ','):
    
    dirname = Path(dirname)
    if dirname.suffix == '.csv':
        dirname = dirname.with_suffix('')
    logger.info("writing '.csv' files to %s", dirname)
    if not dirname.is_dir():
        dirname.mkdir(parents=True, exist_ok=True)
    dir_uns = dirname / 'uns'
    if not dir_uns.is_dir():
        dir_uns.mkdir(parents=True, exist_ok=True)
    d = dict(
        obs=adata._obs,
        var=adata._var,
        obsm=adata._obsm.to_df(),
        varm=adata._varm.to_df(),
    )
    if not skip_data:
        d['X'] = pd.DataFrame(
            adata._X.toarray() if issparse(adata._X) else adata._X)
    d_write = {**d, **adata._uns}
    not_yet_raised_sparse_warning = True
    for key, value in d_write.items():
        if issparse(value):
            if not_yet_raised_sparse_warning:
                warnings.warn('Omitting to write sparse annotation.')
                not_yet_raised_sparse_warning = False
            continue
        filename = dirname
        if key not in {'X', 'var', 'obs', 'obsm', 'varm'}:
            filename = dir_uns
        filename /= '{}.csv'.format(key)
        df = value
        if not isinstance(value, pd.DataFrame):
            value = np.array(value)
            if np.ndim(value) == 0:
                value = value[None]
            try:
                df = pd.DataFrame(value)
            except Exception as e:
                warnings.warn('Omitting to write {!r}.'.format(key), type(e))
                continue
        df.to_csv(
            filename, sep=sep,
            header=key in {'obs', 'var', 'obsm', 'varm'},
            index=key in {'obs', 'var'},
        )
225179
def _write_vxr(self, f, numEntries=None):
        '''
        
        '''

        f.seek(0, 2)
        byte_loc = f.tell()
        section_type = CDF.VXR_
        nextVXR = 0
        if (numEntries == None):
            nEntries = CDF.NUM_VXR_ENTRIES
        else:
            nEntries = int(numEntries)
        block_size = CDF.VXR_BASE_SIZE64 + (4 + 4 + 8) * nEntries
        nUsedEntries = 0
        firsts = [-1] * nEntries
        lasts = [-1] * nEntries
        offsets = [-1] * nEntries

        vxr = bytearray(block_size)
        vxr[0:8] = struct.pack('>q', block_size)
        vxr[8:12] = struct.pack('>i', section_type)
        vxr[12:20] = struct.pack('>q', nextVXR)
        vxr[20:24] = struct.pack('>i', nEntries)
        vxr[24:28] = struct.pack('>i', nUsedEntries)
        estart = 28 + 4*nEntries
        vxr[28:estart] = struct.pack('>%si' % nEntries, *firsts)
        eend = estart + 4*nEntries
        vxr[estart:eend] = struct.pack('>%si' % nEntries, *lasts)
        vxr[eend:block_size] = struct.pack('>%sq' % nEntries, *offsets)
        f.write(vxr)
        return byte_loc
944528
def write_file(path, data, mode='w'):  # type: (str, str, str) -> None
    
    with open(path, mode) as f:
        f.write(data)
1157010
def output_compressed_dinf(dinfflowang, compdinffile, weightfile):
        
        dinf_r = RasterUtilClass.read_raster(dinfflowang)
        data = dinf_r.data
        xsize = dinf_r.nCols
        ysize = dinf_r.nRows
        nodata_value = dinf_r.noDataValue

        cal_dir_code = frompyfunc(DinfUtil.compress_dinf, 2, 3)
        updated_angle, dir_code, weight = cal_dir_code(data, nodata_value)

        RasterUtilClass.write_gtiff_file(dinfflowang, ysize, xsize, updated_angle,
                                         dinf_r.geotrans, dinf_r.srs, DEFAULT_NODATA, GDT_Float32)
        RasterUtilClass.write_gtiff_file(compdinffile, ysize, xsize, dir_code,
                                         dinf_r.geotrans, dinf_r.srs, DEFAULT_NODATA, GDT_Int16)
        RasterUtilClass.write_gtiff_file(weightfile, ysize, xsize, weight,
                                         dinf_r.geotrans, dinf_r.srs, DEFAULT_NODATA, GDT_Float32)
985296
def write_tf_examples(filename, tf_examples, serialize=True):
    
    with tf.python_io.TFRecordWriter(
            filename, options=TF_RECORD_CONFIG) as writer:
        for ex in tf_examples:
            if serialize:
                writer.write(ex.SerializeToString())
            else:
                writer.write(ex)
567535
public void writeData(String data) {
        _buffer.append("<![CDATA[");
        _buffer.append( data);
        _buffer.append( "]]>");
    }
129313
def write_vcf(path, callset, rename=None, number=None, description=None,
              fill=None, write_header=True):
    """"""

    names, callset = normalize_callset(callset)

    with open(path, 'w') as vcf_file:
        if write_header:
            write_vcf_header(vcf_file, names, callset=callset, rename=rename,
                             number=number, description=description)
        write_vcf_data(vcf_file, names, callset=callset, rename=rename, fill=fill)
978214
def write(self,f):
        
        f.write("* singular value decomposition\n")
        f.write(IFMT(self.svdmode)+'\n')
        f.write(IFMT(self.maxsing)+' '+FFMT(self.eigthresh)+"\n")
        f.write('{0}\n'.format(self.eigwrite))
1024924
def save_datasets(self, datasets, filename=None, **kwargs):
        """"""
        logger.info('Saving datasets to NetCDF4/CF.')
        # XXX: Should we combine the info of all datasets?
        filename = filename or self.get_filename(**datasets[0].attrs)
        datas, start_times, end_times = self._collect_datasets(datasets, kwargs)

        dataset = xr.Dataset(datas)
        try:
            dataset['time_bnds'] = make_time_bounds(dataset,
                                                    start_times,
                                                    end_times)
            dataset['time'].attrs['bounds'] = "time_bnds"
        except KeyError:
            logger.warning('No time dimension in datasets, skipping time bounds creation.')

        header_attrs = kwargs.pop('header_attrs', None)

        if header_attrs is not None:
            dataset.attrs.update({k: v for k, v in header_attrs.items() if v})

        dataset.attrs['history'] = ("Created by pytroll/satpy on " +
                                    str(datetime.utcnow()))
        dataset.attrs['conventions'] = 'CF-1.7'
        engine = kwargs.pop("engine", 'h5netcdf')
        for key in list(kwargs.keys()):
            if key not in ['mode', 'format', 'group', 'encoding', 'unlimited_dims', 'compute']:
                kwargs.pop(key, None)
        return dataset.to_netcdf(filename, engine=engine, **kwargs)