Get csv export file of Accounts from Tempo
        :return: csv file
4389
def tempo_account_export_accounts(self):
        
        headers = self.form_token_headers
        url = 'rest/tempo-accounts/1/export'
        return self.get(url, headers=headers, not_json_response=True)
920054
def export_freq(xfreq, filename, desc=None):
    """
    '"""
    heading_row_1 = ['Segment index',
                   'Start time',
                   'End time',
                   'Duration',
                   'Stitches',
                   'Stage',
                   'Cycle',
                   'Event type',
                   'Channel',
                   ]
    spacer = [''] * (len(heading_row_1) - 1)
    freq = list(xfreq[0]['data'].axis['freq'][0])

    with open(filename, 'w', newline='') as f:
        lg.info('Writing to ' + str(filename))
        csv_file = writer(f)
        csv_file.writerow(['Wonambi v{}'.format(__version__)])
        csv_file.writerow(heading_row_1 + freq)

        if desc:
            csv_file.writerow(['Mean'] + spacer + list(desc['mean']))
            csv_file.writerow(['SD'] + spacer + list(desc['sd']))
            csv_file.writerow(['Mean of ln'] + spacer + list(
                    desc['mean_log']))
            csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log']))

        idx = 0
        for seg in xfreq:

            for chan in seg['data'].axis['chan'][0]:
                idx += 1

                cyc = None
                if seg['cycle'] is not None:
                    cyc = seg['cycle'][2]

                data_row = list(seg['data'](chan=chan)[0])
                csv_file.writerow([idx,
                                   seg['start'],
                                   seg['end'],
                                   seg['duration'],
                                   seg['n_stitch'],
                                   seg['stage'],
                                   cyc,
                                   seg['name'],
                                   chan,
                                   ] + data_row)
993750
def database_to_csv(self, path, orderby='type'):
        
        tableinfo = self.get_table_info()
        stats_master = database_to_json(self.dbcon_master, tableinfo)
        stats_partial = database_to_json(self.dbcon_part, tableinfo)
        with open(path, 'w') as f:
            csvfile = csv.writer(f)
            csvfile.writerow(['Name', 'Type', 'Value', 'Description'])
            rows = []
            for tablename, info in tableinfo.iteritems():
                # Attempt to get the latest stat (from partial), if it doesn't exist get it from master
                value = stats_partial.get(tablename, {}).get('data', ValueError) or stats_master.get(tablename, {}).get('data', ValueError)
                if value is ValueError:
                    # The trackable was registered but no table values are found
                    value = self[tablename].current_value
                    if value is NO_STATE:
                        value = 'No Initial State'

                rows.append([tablename, info['type'], value, info['description']])

            if orderby == 'type':
                rows.sort(key=lambda x: x[1]) # Sort by type
            elif orderby == 'name':
                rows.sort(key=lambda x: x[0])  # Sort by type
            csvfile.writerows(rows)
477433
def _export_csv(self, filepath, data, preview_data):
        

        # Get csv info

        csv_info = \
            self.main_window.interfaces.get_csv_export_info(preview_data)

        if csv_info is None:
            return

        try:
            dialect, digest_types, has_header = csv_info
        except TypeError:
            return

        # Export CSV file

        csv_interface = CsvInterface(self.main_window, filepath, dialect,
                                     digest_types, has_header)

        try:
            csv_interface.write(data)

        except IOError, err:
            msg = _("The file {filepath} could not be fully written\n \n"
                    "Error message:\n{msg}")
            msg = msg.format(filepath=filepath, msg=err)
            short_msg = _('Error writing CSV file')
            self.main_window.interfaces.display_warning(msg, short_msg)
243710
def export(self):
        
        return {'id': self.id, 'name': self.name, 'artist': self._artist_name,
                'artist_id': self._artist_id, 'album': self._album_name,
                'album_id': self._album_id, 'track': self.track,
                'duration': self.duration, 'popularity': self.popularity,
                'cover': self._cover_url}
509404
def export_to_csv(
    table,
    filename_or_fobj=None,
    encoding="utf-8",
    dialect=unicodecsv.excel,
    batch_size=100,
    callback=None,
    *args,
    **kwargs
):
    
    # TODO: will work only if table.fields is OrderedDict
    # TODO: should use fobj? What about creating a method like json.dumps?

    return_data, should_close = False, None
    if filename_or_fobj is None:
        filename_or_fobj = BytesIO()
        return_data = should_close = True

    source = Source.from_file(
        filename_or_fobj,
        plugin_name="csv",
        mode="wb",
        encoding=encoding,
        should_close=should_close,
    )

    # TODO: may use `io.BufferedWriter` instead of `ipartition` so user can
    # choose the real size (in Bytes) when to flush to the file system, instead
    # number of rows
    writer = unicodecsv.writer(source.fobj, encoding=encoding, dialect=dialect)

    if callback is None:
        for batch in ipartition(serialize(table, *args, **kwargs), batch_size):
            writer.writerows(batch)

    else:
        serialized = serialize(table, *args, **kwargs)
        writer.writerow(next(serialized))  # First, write the header
        total = 0
        for batch in ipartition(serialized, batch_size):
            writer.writerows(batch)
            total += len(batch)
            callback(total)

    if return_data:
        source.fobj.seek(0)
        result = source.fobj.read()
    else:
        source.fobj.flush()
        result = source.fobj

    if source.should_close:
        source.fobj.close()

    return result
696049
def _get_csv_from_model(models, crumbs, csvs):
    
    logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
    _idx = 0
    try:
        for _name, _model in models.items():
            if "distributionTable" in _model:
                models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"), csvs)

            if "summaryTable" in _model:
                models[_name]["summaryTable"], csvs = _get_csv_from_table(_model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"), csvs)

            if "ensembleTable" in _model:
                models[_name]["ensembleTable"], csvs = _get_csv_from_table(_model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"), csvs)
            _idx += 1
    except Exception as e:
        print("Error: get_csv_from_model: {}, {}".format(crumbs, e))
        logger_csvs.error("Error: get_csv_from_model: {}, {}".format(crumbs, e))
    return models, csvs
510176
def get_csv_export_info(self, preview_data):
        

        preview_rows = 100
        preview_cols = 100

        export_preview = list(list(islice(col, None, preview_cols))
                              for col in islice(preview_data, None,
                                                preview_rows))

        filterdlg = CsvExportDialog(self.main_window, data=export_preview)

        if filterdlg.ShowModal() == wx.ID_OK:
            dialect, has_header = filterdlg.csvwidgets.get_dialect()
            digest_types = [types.StringType]
        else:
            filterdlg.Destroy()
            return

        filterdlg.Destroy()

        return dialect, has_header, digest_types
478965
def export_data(self):
        

        # We need to remove spaces for TW-1504, use custom separators
        data_tuples = ((key, self._serialize(key, value))
                       for key, value in six.iteritems(self._data))

        # Empty string denotes empty serialized value, we do not want
        # to pass that to TaskWarrior.
        data_tuples = filter(lambda t: t[1] is not '', data_tuples)
        data = dict(data_tuples)
        return json.dumps(data, separators=(',', ':'))
890177
def totsv(table, source=None, encoding=None, errors='strict',
          write_header=True, **csvargs):
    

    csvargs.setdefault('dialect', 'excel-tab')
    return tocsv(table, source=source, encoding=encoding, errors=errors,
                 write_header=write_header, **csvargs)
1363439
def to_csv(args):
    
    result_file = args.result_file
    output_file = args.output_file
    delimiter = args.delimiter
    if not os.path.isfile(result_file):
        raise OSError("Results file does not exists")
    headers = ['elapsed', 'epoch', 'turret_name', 'scriptrun_time', 'error']
    headers_row = {}

    set_database(result_file, db, {})

    results = Result.select()

    for item in results:
        result_item = item.to_dict()
        for k in result_item['custom_timers'].keys():
            if k not in headers:
                headers.append(k)
                headers_row[k] = k

    with open(output_file, "w+") as f:
        writer = csv.DictWriter(f, fieldnames=headers, delimiter=delimiter)
        headers_row.update({
            'elapsed': 'elapsed time',
            'epoch': 'epoch (in seconds)',
            'turret_name': 'turret name',
            'scriptrun_time': 'transaction time',
            'error': 'error'
        })
        writer.writerow(headers_row)
        for result_item in results:
            line = result_item.to_dict()
            for key, value in line['custom_timers'].items():
                line[key] = value
            del line['custom_timers']
            writer.writerow(line)
370506
def _get_export_mgr(self):
        
        return (
            DiskExportManager.get_instance_by_type(
                dst=self._dst,
                disk=disk,
                do_compress=self._compress,
                *self._args,
                **self._kwargs
            ) for disk in self._collect()
        )
548696
def fastq_to_csv(in_file, fastq_format, work_dir):
    
    out_file = "%s.csv" % (os.path.splitext(os.path.basename(in_file))[0])
    out_file = os.path.join(work_dir, out_file)
    if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
        with open(in_file) as in_handle:
            with open(out_file, "w") as out_handle:
                writer = csv.writer(out_handle)
                for rec in SeqIO.parse(in_handle, fastq_format):
                    writer.writerow([rec.id] + rec.letter_annotations["phred_quality"])
    return out_file
95995
def token(cls: Type[CSVType], time: int) -> CSVType:
        
        csv = cls()
        csv.time = str(time)
        return csv
981279
def get_as_csv(self, output_file_path: Optional[str] = None) -> str:
        
        output = StringIO() if not output_file_path else open(output_file_path, 'w')
        try:
            csv_writer = csv.writer(output)

            csv_writer.writerow(self.columns)
            for row in self.rows:
                csv_writer.writerow(row)
            output.seek(0)
            return output.read()
        finally:
            output.close()
640589
def output_to_csv(sources, csv_writeable_file):
    """"""
    file_exists = os.path.isfile(csv_writeable_file)

    with open(csv_writeable_file, 'a') as csvfile:
        csv_dict = OrderedDict()
        csv_dict.update({'Time': time.strftime("%Y-%m-%d_%H:%M:%S")})
        summaries = [val for key, val in sources.items()]
        for summarie in summaries:
            csv_dict.update(summarie.source.get_sensors_summary())

        fieldnames = [key for key, val in csv_dict.items()]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        if not file_exists:
            writer.writeheader()  # file doesn't exist yet, write a header
        writer.writerow(csv_dict)
636428
def download(csvpath, asset_manager_id, data_id_type, data_id_list):
        """"""
        interface = interface_direct_csvpath(csvpath)
        logging.config.dictConfig(DEFAULT_LOGGING)
        logger = logging.getLogger(__name__)
        objs = []
        for data_id in data_id_list:
            Dict = dict()
            Dict[data_id_type] = data_id
            objs.append(interface.retrieve(asset_manager_id=asset_manager_id, **Dict))
        return objs