saves a grid to file as ASCII text
428213
def save(self, fname):
        
        try:
            with open(fname, "w") as f:
                f.write(str(self))
        except Exception as ex:
            print('ERROR = cant save grid results to ' + fname + str(ex))
1049980
def to_column_format(self, high_density_vertical=True):
        
        im = self._im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
        line_height = 24 if high_density_vertical else 8
        width_pixels, height_pixels = im.size
        top = 0
        left = 0
        while left < width_pixels:
            box = (left, top, left + line_height, top + height_pixels)
            im_slice = im.transform((line_height, height_pixels), Image.EXTENT, box)
            im_bytes = im_slice.tobytes()
            yield(im_bytes)
            left += line_height
730628
def grid_list(data):
    '''
    
    '''
    a = []
    b = []
    M = []
    for i in data:
        a.append(i[0])  # np.array([i[1] for i in data], dtype=np.float64)
        b.append(i[1])  # np.array([i[0] for i in data], dtype=np.float64)
        M.append(i[2])  # np.array([i[2] for i in data], dtype=np.float64)
    a = np.array(a, dtype=np.float64).tolist()
    b = np.array(b, dtype=np.float64).tolist()
    M = np.array(M, dtype=np.float64).tolist()
    a = list(set(a))
    b = list(set(b))
    return a, b, M
873305
def save(self, filename):
        """"""
        filename = pathlib.Path(filename)
        out = []
        keys = sorted(list(self.keys()))
        for key in keys:
            out.append("[{}]".format(key))
            section = self[key]
            ikeys = list(section.keys())
            ikeys.sort()
            for ikey in ikeys:
                var, val = keyval_typ2str(ikey, section[ikey])
                out.append("{} = {}".format(var, val))
            out.append("")

        with filename.open("w") as f:
            for i in range(len(out)):
                # win-like line endings
                out[i] = out[i]+"\n"
            f.writelines(out)
158461
def store_lines(self, key, content):
        ''''''
        return self.store_iter(
            key,
            (data + '\n'.encode('utf-8') for data in content))
9541
def DumpAsCSV (self, separator=",", file=sys.stdout):
                """"""
                for row in range(1, self.maxRow + 1):
                        sep = ""
                        for column in range(1, self.maxColumn + 1):
                                file.write("%s\"%s\"" % (sep, self.GetCellValue(column, row, "")))
                                sep = separator
                        file.write("\n")
1277409
def ascii(graph):
    """"""
    from .._ascii import DAG
    from .._echo import echo_via_pager

    echo_via_pager(str(DAG(graph)))
71660
def save_to_file(self, filename_prefix):
    """"""
    # Wrap in single quotes to make it easier to see the full subword when
    # it has spaces and make it easier to search with ctrl+f.
    filename = self._filename(filename_prefix)
    lines = ["'%s'" % s for s in self._subwords]
    self._write_lines_to_file(filename, lines)
934723
def _read_ascii(self):
        """"""
        # NOTE: ascii files store binned data using C-like ordering.
        # Dimensions are iterated like x, y, z (so z changes fastest)

        header_str = ''
        with open(self.path) as f:
            for line in f:
                if line.startswith('#'):
                    header_str += line
        self._read_header(header_str)

        data = np.loadtxt(self.path, delimiter=',', unpack=True, ndmin=1)

        # separate data by statistic (neglecting bin columns when necessary)
        n_dim = len(self.dimensions)
        data = {stat: data[n_dim+i] for i, stat in enumerate(self.statistics)}

        # reshape data according to binning
        data_shape = [dim.n_bins for dim in self.dimensions]
        data = {k: v.reshape(data_shape) for k, v in data.items()}

        self.data = data
1040259
def slice_save(self, astr_outputFile):
        '''
        
        '''
        self._log('Outputfile = %s\n' % astr_outputFile)
        fformat = astr_outputFile.split('.')[-1]
        if fformat == 'dcm':
            if self._dcm:
                self._dcm.pixel_array.flat = self._Mnp_2Dslice.flat
                self._dcm.PixelData = self._dcm.pixel_array.tostring()
                self._dcm.save_as(astr_outputFile)
            else:
                raise ValueError('dcm output format only available for DICOM files')
        else:
            pylab.imsave(astr_outputFile, self._Mnp_2Dslice, format=fformat, cmap = cm.Greys_r)
85274
def save_file(data_file, data, dry_run=None):
    """"""
    if dry_run:
        return

    with open(data_file, 'w', encoding='utf-8') as f:
        if sys.version_info > (3, 0):
            f.write(json.dumps(data))
        else:
            f.write(json.dumps(data).decode('utf-8'))
1321569
function saveAsFile(editor, data, range) {
	return new Promise((resolve, reject) => {
		const fileName = atom.getCurrentWindow().showSaveDialog();
		if (!fileName) {
			return reject(new Error('User cancelled file dialog'));
		}

		fs.writeFile(fileName, Buffer.from(data, 'base64'), err => {
			if (err) {
				return reject(err);
			}

			const editorPath = editor.getPath();
			let displayPath = editorPath
				? path.relative(editorPath, fileName)
				: `file://${fileName}`;

			editor.transact(() => {
				// Convert Windows path separators to Unix
				editor.setTextInBufferRange(range, displayPath.replace(/\\+/g, '/'));
			});

			resolve(fileName);
		});
	});
}
675974
def toxls(tbl, filename, sheet, encoding=None, style_compression=0,
          styles=None):
    

    import xlwt
    if encoding is None:
        encoding = locale.getpreferredencoding()
    wb = xlwt.Workbook(encoding=encoding, style_compression=style_compression)
    ws = wb.add_sheet(sheet)

    if styles is None:
        # simple version, don't worry about styles
        for r, row in enumerate(tbl):
            for c, v in enumerate(row):
                ws.write(r, c, label=v)
    else:
        # handle styles
        it = iter(tbl)
        hdr = next(it)
        flds = list(map(str, hdr))
        for c, f in enumerate(flds):
            ws.write(0, c, label=f)
            if f not in styles or styles[f] is None:
                styles[f] = xlwt.Style.default_style
        # convert to list for easy zipping
        styles = [styles[f] for f in flds]
        for r, row in enumerate(it):
            for c, (v, style) in enumerate(izip_longest(row, styles,
                                                        fillvalue=None)):
                ws.write(r+1, c, label=v, style=style)

    wb.save(filename)
262202
def save_as(self):
        """"""
        filename = splitext(self.filename)[0]
        filename, _ = QFileDialog.getSaveFileName(self, 'Export events',
                                                  filename)
        if filename == '':
            return

        self.filename = filename
        short_filename = short_strings(basename(self.filename))
        self.idx_filename.setText(short_filename)
915798
def save(self, filename, addnormalised=False):
        """"""
        f = io.open(filename,'w',encoding='utf-8')
        for line in self.output("\t", addnormalised):
            f.write(line + '\n')
        f.close()
380381
def _readASCII(self, filename):
        
        self.waveunits = units.Units('angstrom')
        self.fluxunits = units.Units('flam')
        wlist, flist = self._columnsFromASCII(filename)
        self._wavetable = N.array(wlist, dtype=N.float64)
        self._fluxtable = N.array(flist, dtype=N.float64)
108601
def save_grid_data(self):
        
        if not self.grid.changes:
            print('-I- No changes to save')
            return

        starred_cols = self.grid.remove_starred_labels()
        # locks in value in cell currently edited
        self.grid.SaveEditControlValue()
        # changes is a dict with key values == row number
        if self.grid.changes:
            new_data = self.grid.save_items()
            # HugeMagicGrid will return a pandas dataframe
            if self.huge:
                self.magic_dataframe.df = new_data
            # MagicGrid will return a dictionary with
            # new/updated data that must be incorporated
            # into the dataframe
            else:
                for key in new_data:
                    data = new_data[key]
                    # update the row if it exists already,
                    # otherwise create a new row

                    updated = self.magic_dataframe.update_row(key, data)
                    if not isinstance(updated, pd.DataFrame):
                        if self.grid_type == 'ages':
                            label = key
                        else:
                            label = self.grid_type[:-1]
                        self.magic_dataframe.add_row(label, data,
                                                     self.grid.col_labels)
            # update the contribution with the new dataframe
            self.contribution.tables[self.grid_type] = self.magic_dataframe
            # *** probably don't actually want to write to file, here (but maybe)

            self.contribution.write_table_to_file(self.grid_type)
            #self.magic_dataframe.write_magic_file("{}.txt".format(self.grid_type),
            #                                      self.contribution.directory)
            # propagate age info if age table was edited
            if self.grid_type == 'ages':
                self.contribution.propagate_ages()
            return