save waypoints to a file in a human readable CSV file
540921
def save_waypoints_csv(self, filename):
        ''''''
        try:
            #need to remove the leading and trailing quotes in filename
            self.wploader.savecsv(filename.strip('"'))
        except Exception as msg:
            print("Failed to save %s - %s" % (filename, msg))
            return
        print("Saved %u waypoints to CSV %s" % (self.wploader.count(), filename))
1116311
def update_waypoints(self, filename, wpnum):
        ''''''
        self.wploader.target_system = self.target_system
        self.wploader.target_component = self.target_component
        try:
            self.wploader.load(filename)
        except Exception as msg:
            print("Unable to load %s - %s" % (filename, msg))
            return
        if self.wploader.count() == 0:
            print("No waypoints found in %s" % filename)
            return
        if wpnum == -1:
            print("Loaded %u updated waypoints from %s" % (self.wploader.count(), filename))
        elif wpnum >= self.wploader.count():
            print("Invalid waypoint number %u" % wpnum)
            return
        else:
            print("Loaded updated waypoint %u from %s" % (wpnum, filename))

        self.loading_waypoints = True
        self.loading_waypoint_lasttime = time.time()
        if wpnum == -1:
            start = 0
            end = self.wploader.count()-1
        else:
            start = wpnum
            end = wpnum
        self.master.mav.mission_write_partial_list_send(self.target_system,
                                                             self.target_component,
                                                             start, end)
1053609
def save(filepath=None, **kwargs):
    
    if filepath is None:
        filepath = os.path.join('.env')

    with open(filepath, 'wb') as file_handle:
        file_handle.writelines(
            '{0}={1}\n'.format(key.upper(), val)
            for key, val in kwargs.items()
        )
479069
def dump_to_path(self, cnf, filepath, **kwargs):
        
        with self.wopen(filepath) as out:
            self.dump_to_stream(cnf, out, **kwargs)
807122
def save_file(self, filename, encoding='utf8', headers=None,
                  convertors=None, display=True, **kwargs):
        
        global save_file
        
        convertors = convertors or {}
        headers = headers or []
        
        fields = self.get_fields()
        _header = []
        for i, column in enumerate(fields):
            if column.name not in convertors:
                if display:
                    def f(value, data):
                        return column.get_display_value(value)

                    convertors[column.name] = f
            flag = False
            for j in headers:
                if not isinstance(j, dict):
                    raise ValueError("Header should be a list of dict, but {} type found".format(type(j)))
                if j['name'] == column.name:
                    _header.append(j)
                    flag = True
                    break
            if not flag:
                d = {'name':column.name}
                if display:
                    d['title'] = column.verbose_name or column.name
                else:
                    d['title'] = column.name
                _header.append(d)

        return save_file(self.run(), filename, encoding=encoding,
                         headers=_header, convertors=convertors, **kwargs)
346474
def dump_to_path(self, cnf, filepath, **kwargs):
        
        with self.wopen(filepath) as out:
            out.write(self.dump_to_string(cnf, **kwargs))
909350
def save(self, out_path):
        

        out = {
            'selectors': [str(x) for x in self.selectors],
            'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]
        }

        with open(out_path, "wb") as outfile:
            json.dump(out, outfile, indent=4)
15926
def to_file(self, path, mode="w"):
        
        with open(path, mode=mode) as f:
            for tree in self:
                for label, line in tree.to_labeled_lines():
                    f.write(line + "\n")
114581
def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str:
    
    with codecs.open(fpath, mode='w', encoding=encoding) as f:
        f.write(dump_yaml(data))
        return fpath
1228024
def save(yaml_dict, filepath):
    '''
    
    '''
    yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
489762
def woa_track_from_file(d, lat, lon, filename, varnames=None):
    
    d = np.asanyarray(d)
    lat = np.asanyarray(lat)
    lon = np.asanyarray(lon)

    lon[lon < 0] += 360

    doy = np.array([int(dd.strftime('%j')) for dd in d])

    nc = netCDF4.Dataset(expanduser(filename), 'r')

    if varnames is None:
        varnames = {}
        for v in nc.variables.keys():
            if nc.variables[v].dimensions == \
                    (u'time', u'depth', u'lat', u'lon'):
                        varnames[v] = v

    output = {}
    for v in varnames:
        output[v] = []

    for d_n, lat_n, lon_n in zip(doy, lat, lon):
        # Get the nearest point. In the future interpolate.
        n_d = (np.abs(d_n - nc.variables['time'][:])).argmin()
        n_x = (np.abs(lon_n - nc.variables['lon'][:])).argmin()
        n_y = (np.abs(lat_n - nc.variables['lat'][:])).argmin()

        for v in varnames:
            output[v].append(nc.variables[varnames[v]][n_d, 0, n_y, n_x])

    for v in varnames:
        output[v] = ma.fix_invalid(output[v])

    return output
758291
def csv2yaml(in_file, out_file=None):
    
    if out_file is None:
        out_file = "%s.yaml" % os.path.splitext(in_file)[0]
    barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))
    lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids)
    with open(out_file, "w") as out_handle:
        out_handle.write(yaml.safe_dump(lanes, default_flow_style=False))
    return out_file
835481
def to_file(self, path, precision='%.2g'):
        
        table_info = self.get_table_info()

        def dump_rows(rows):
            if len(rows) > 1:
                for row in rows:
                    csv_writer.writerow(row)
                csv_writer.writerow([])

        with open(path, 'wb') as _f:
            csv_writer = csv.writer(_f)

            state_rows = [['States']]
            state_rows += [['Name', 'Description', 'State', 'Number of Changes']]
            for state in self.states:
                state_rows.append([state.name, table_info[state.name]['description'], state.state, state.count])
            dump_rows(state_rows)

            stat_rows = [['Statistics']]
            stat_rows += [['Name', 'Description', 'Total', 'Average']]
            for stat in self.statistics:
                if stat.name == '__submissions__':
                    continue
                stat_rows.append([stat.name, table_info[stat.name]['description'], stat.count, stat.get_average(0)])
                dump_rows(stat_rows)

            timer_rows = [['Timers']]
            timer_rows += [['Name', 'Description', 'Average Seconds', 'Total Seconds', 'Total Minutes', 'Total Hours', 'Total Days']]
            for timer in self.timers:
                timer_rows.append([timer.name, table_info[timer.name]['description'],
                                   precision % timer.get_average(0), precision % timer.total_seconds, precision % timer.total_minutes,
                                   precision % timer.total_hours, precision % timer.total_days])
                dump_rows(timer_rows)

            sequence_rows = [['Sequences']]
            sequence_rows += [['Name', 'Description', 'Sequence', 'Number of Completions']]
            for sequence in self.sequences:
                checkpoints = '-->'.join(map(str, sequence.get_checkpoints()))
                sequence_rows.append([sequence.name, table_info[sequence.name]['description'], checkpoints, sequence.count])
                dump_rows(sequence_rows)
898964
def save_plot(cls, data, columns, plottype, fmt='json', **kwargs):
        
        cls._verify_export_dir()
        plot = {"use_visavis_type": plottype, "payload": {}}

        if isinstance(data, pd.DataFrame):
            iter_data = data.iterrows
            pointers = columns
        else:
            iter_data = lambda: enumerate(data)
            pointers = range(len(data[0]))

        if fmt == 'csv':
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".csv")
            f_export = open(fmt_export, "w")
            f_export.write("%s\n" % ",".join(map(str, columns)))
            for _, row in iter_data():
                f_export.write("%s\n" % ",".join([str(row[i]) for i in pointers]))
            f_export.close()

        else:
            fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".json")
            f_export = open(fmt_export, "w")

            if plottype == 'bar':

                plot["payload"] = {"x": [], "y": [], "xtitle": cls._get_title(columns[0]), "ytitle": cls._get_title(columns[1])}

                for _, row in iter_data():
                    plot["payload"]["x"].append(row[pointers[0]])
                    plot["payload"]["y"].append(row[pointers[1]])

            elif plottype == 'plot3d':

                plot["payload"]["points"] = {"x": [], "y": [], "z": [], "labels": []}
                plot["payload"]["meshes"] = []
                plot["payload"]["xtitle"] = cls._get_title(columns[0])
                plot["payload"]["ytitle"] = cls._get_title(columns[1])
                plot["payload"]["ztitle"] = cls._get_title(columns[2])
                recent_mesh = 0

                for _, row in iter_data():
                    plot["payload"]["points"]["x"].append(row[pointers[0]])
                    plot["payload"]["points"]["y"].append(row[pointers[1]])
                    plot["payload"]["points"]["z"].append(row[pointers[2]])
                    plot["payload"]["points"]["labels"].append(row[pointers[3]])

                    if row[4] != recent_mesh:
                        plot["payload"]["meshes"].append({"x": [], "y": [], "z": []})
                    recent_mesh = row[4]

                    if plot["payload"]["meshes"]:
                        plot["payload"]["meshes"][-1]["x"].append(row[pointers[0]])
                        plot["payload"]["meshes"][-1]["y"].append(row[pointers[1]])
                        plot["payload"]["meshes"][-1]["z"].append(row[pointers[2]])

            if kwargs:
                plot["payload"].update(kwargs)

            else: raise RuntimeError("\r\nError: %s is an unknown plot type" % plottype)

            f_export.write(json.dumps(plot, escape_forward_slashes=False, indent=4))
            f_export.close()

        return fmt_export
11510
def save(self, filename):
        ''''''
        f = open(filename, mode='w')
        for p in self.points:
            f.write("%f\t%f\n" % (p.lat, p.lng))
        f.close()
1349701
def save(self, filename):
        ''''''
        f = open(filename, mode='w')
        f.write("QGC WPL 110\n")
        for w in self.wpoints:
            if getattr(w, 'comment', None):
                f.write("# %s\n" % w.comment)
            f.write("%u\t%u\t%u\t%u\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%u\n" % (
                w.seq, w.current, w.frame, w.command,
                w.param1, w.param2, w.param3, w.param4,
                w.x, w.y, w.z, w.autocontinue))
        f.close()
481139
def record_to_fs(self):
        """"""

        fr = self.record

        fn_path = self.file_name

        if fr.contents:
            if six.PY2:
                with self._fs.open(fn_path, 'wb') as f:
                    self.record_to_fh(f)
            else:
                # py3
                with self._fs.open(fn_path, 'w', newline='') as f:
                    self.record_to_fh(f)