export all vouchers from a voucher series as csv-file with Code, Datecreated and UsedUp-Information.
760905
public function ExportVoucherCodes()
    {
        $sReturn = '';

        if ($this->AllowExportingVoucherCodes()) {
            $oVouchers = TdbShopVoucherList::GetList("SELECT * FROM `shop_voucher` WHERE `shop_voucher_series_id`='".MySqlLegacySupport::getInstance()->real_escape_string($this->sId)."'");
            $oVouchers->GoToStart();
            $count = 0;
            while ($oVoucher = $oVouchers->Next()) {
                $aCsvVouchers[$count][0] = str_replace('"', '""', $oVoucher->fieldCode);
                if ('0000-00-00 00:00:00' != $oVoucher->fieldDatecreated) {
                    $aCsvVouchers[$count][1] = date('d.m.Y H:i', strtotime($oVoucher->fieldDatecreated));
                } else {
                    $aCsvVouchers[$count][3] = '';
                }
                $aCsvVouchers[$count][2] = $oVoucher->fieldIsUsedUp;
                if ('0000-00-00 00:00:00' != $oVoucher->fieldDateUsedUp) {
                    $aCsvVouchers[$count][3] = date('d.m.Y H:i', strtotime($oVoucher->fieldDateUsedUp));
                } else {
                    $aCsvVouchers[$count][3] = '';
                }
                ++$count;
            }

            $sCsv = '';
            for ($i = 0; $i < count($aCsvVouchers); ++$i) {
                $sCsv .= '"'.implode('";"', $aCsvVouchers[$i])."\"\n";
            }
            $sCsv = '"'.TGlobal::OutHTML(TGlobal::Translate('chameleon_system_shop.voucher.export_column_code')).'";"'.TGlobal::OutHTML(TGlobal::Translate('chameleon_system_shop.voucher.export_column_created')).'";"'.TGlobal::OutHTML(TGlobal::Translate('chameleon_system_shop.voucher.export_column_spent')).'";"'.TGlobal::OutHTML(TGlobal::Translate('chameleon_system_shop.voucher.export_column_spent_date'))."\"\n".$sCsv;

            while (@ob_end_clean()) {
            }
            header('Cache-Control: must-revalidate');
            header('Pragma: must-revalidate');
            header('Content-type: application/csv');
            header('Content-disposition: attachment; filename=ShopVouchers.csv');

            echo $sCsv;

            exit(0);
        } else {
            echo 'Keine Berechtigung';
        }
    }
359674
def export_csv(ekey, dstore):
    
    name = ekey[0] + '.csv'
    try:
        array = dstore[ekey[0]].value
    except AttributeError:
        # this happens if the key correspond to a HDF5 group
        return []  # write a custom exporter in this case
    if len(array.shape) == 1:  # vector
        array = array.reshape((len(array), 1))
    return [write_csv(dstore.export_path(name), array)]
505230
def save_csv(self):
        
        # Sort results so we can start to see patterns right in the raw CSV.
        self.results.sort_values(by=self.column_ids, inplace=True)
        # Gotcha: integers seems to be promoted to float64 because of
        # reindexation. See: https://pandas.pydata.org/pandas-docs/stable
        # /gotchas.html#na-type-promotions
        self.results.reindex(columns=self.column_ids).to_csv(
            self.csv_filepath, index=False)
813290
def csvdir_bundle(environ,
                  asset_db_writer,
                  minute_bar_writer,
                  daily_bar_writer,
                  adjustment_writer,
                  calendar,
                  start_session,
                  end_session,
                  cache,
                  show_progress,
                  output_dir,
                  tframes=None,
                  csvdir=None):
    
    if not csvdir:
        csvdir = environ.get('CSVDIR')
        if not csvdir:
            raise ValueError("CSVDIR environment variable is not set")

    if not os.path.isdir(csvdir):
        raise ValueError("%s is not a directory" % csvdir)

    if not tframes:
        tframes = set(["daily", "minute"]).intersection(os.listdir(csvdir))

        if not tframes:
            raise ValueError("'daily' and 'minute' directories "
                             "not found in '%s'" % csvdir)

    divs_splits = {'divs': DataFrame(columns=['sid', 'amount',
                                              'ex_date', 'record_date',
                                              'declared_date', 'pay_date']),
                   'splits': DataFrame(columns=['sid', 'ratio',
                                                'effective_date'])}
    for tframe in tframes:
        ddir = os.path.join(csvdir, tframe)

        symbols = sorted(item.split('.csv')[0]
                         for item in os.listdir(ddir)
                         if '.csv' in item)
        if not symbols:
            raise ValueError("no <symbol>.csv* files found in %s" % ddir)

        dtype = [('start_date', 'datetime64[ns]'),
                 ('end_date', 'datetime64[ns]'),
                 ('auto_close_date', 'datetime64[ns]'),
                 ('symbol', 'object')]
        metadata = DataFrame(empty(len(symbols), dtype=dtype))

        if tframe == 'minute':
            writer = minute_bar_writer
        else:
            writer = daily_bar_writer

        writer.write(_pricing_iter(ddir, symbols, metadata,
                     divs_splits, show_progress),
                     show_progress=show_progress)

        # Hardcode the exchange to "CSVDIR" for all assets and (elsewhere)
        # register "CSVDIR" to resolve to the NYSE calendar, because these
        # are all equities and thus can use the NYSE calendar.
        metadata['exchange'] = "CSVDIR"

        asset_db_writer.write(equities=metadata)

        divs_splits['divs']['sid'] = divs_splits['divs']['sid'].astype(int)
        divs_splits['splits']['sid'] = divs_splits['splits']['sid'].astype(int)
        adjustment_writer.write(splits=divs_splits['splits'],
                                dividends=divs_splits['divs'])
1041968
def export(*methods)
      methods.flatten.map do |method|
        case value = (eval("self.#{method}", binding) rescue nil)
          when Date, Time
            value.strftime("%m/%d/%y")
          when TrueClass
            'Y'
          when FalseClass
            'N'
          else value.to_s
        end
      end
    end
278453
def to_csv(self, fileobj=sys.stdout):
        """"""
        openclose = is_string(fileobj)

        if openclose:
            fileobj = open(fileobj, "w")

        for idx, section in enumerate(self.sections):
            fileobj.write(section.to_csvline(with_header=(idx == 0)))
        fileobj.flush()

        if openclose:
            fileobj.close()
542653
def QA_SU_save_financial_files():
    
    download_financialzip()
    coll = DATABASE.financial
    coll.create_index(
        [("code", ASCENDING), ("report_date", ASCENDING)], unique=True)
    for item in os.listdir(download_path):
        if item[0:4] != 'gpcw':
            print(
                "file ", item, " is not start with gpcw , seems not a financial file , ignore!")
            continue

        date = int(item.split('.')[0][-8:])
        print('QUANTAXIS NOW SAVING {}'.format(date))
        if coll.find({'report_date': date}).count() < 3600:

            print(coll.find({'report_date': date}).count())
            data = QA_util_to_json_from_pandas(parse_filelist([item]).reset_index(
            ).drop_duplicates(subset=['code', 'report_date']).sort_index())
            # data["crawl_date"] = str(datetime.date.today())
            try:
                coll.insert_many(data, ordered=False)

            except Exception as e:
                if isinstance(e, MemoryError):
                    coll.insert_many(data, ordered=True)
                elif isinstance(e, pymongo.bulk.BulkWriteError):
                    pass
        else:
            print('ALL READY IN DATABASE')

    print('SUCCESSFULLY SAVE/UPDATE FINANCIAL DATA')
200237
def clean(self, data):
        """"""
        cleaned_data = list()

        if not isinstance(data, list):
            data = [data]

        for item in data:
            date = datetime.datetime.strptime(item['Date'], '%Y-%m-%d').date()
            cleaned_data.append(dict(price=item['Adj_Close'], date=date))

        return cleaned_data
271180
def catCSVs(folder, ouputFileName, removeDups = False) :
	""""""
	strCmd = r"""cat %s/*.csv > %s""" %(folder, ouputFileName)
	os.system(strCmd)

	if removeDups :
		removeDuplicates(ouputFileName, ouputFileName)
1037004
def export(self):
        
        data = {}
        for key in self._specification:
            data[key] = self[key]
        return data
290803
def copy(self):
        """"""
        if not self.selectedIndexes():
            return
        (row_min, row_max,
         col_min, col_max) = get_idx_rect(self.selectedIndexes())
        index = header = False
        df = self.model().df
        obj = df.iloc[slice(row_min, row_max + 1),
                      slice(col_min, col_max + 1)]
        output = io.StringIO()
        obj.to_csv(output, sep='\t', index=index, header=header)
        if not PY2:
            contents = output.getvalue()
        else:
            contents = output.getvalue().decode('utf-8')
        output.close()
        clipboard = QApplication.clipboard()
        clipboard.setText(contents)
814238
def serialize(self):
        """"""
        import datetime
        items = []
        time_begin = datetime.datetime.now()
        for href in self.list():
            items.append(self.get(href).item)
        time_end = datetime.datetime.now()
        self.logger.info(
            "Collection read %d items in %s sec from %s", len(items),
            (time_end - time_begin).total_seconds(), self.path)
        if self.get_meta("tag") == "VCALENDAR":
            collection = vobject.iCalendar()
            for item in items:
                for content in ("vevent", "vtodo", "vjournal"):
                    if content in item.contents:
                        for item_part in getattr(item, "%s_list" % content):
                            collection.add(item_part)
                        break
            return collection.serialize()
        elif self.get_meta("tag") == "VADDRESSBOOK":
            return "".join([item.serialize() for item in items])
        return ""
198388
def export_txt(cls, feed):
        ''''''
        objects = cls.objects.in_feed(feed)

        # If no records, return None
        if not objects.exists():
            return

        # Get the columns used in the dataset
        column_map = objects.populated_column_map()
        columns, fields = zip(*column_map)
        extra_columns = feed.meta.get(
            'extra_columns', {}).get(cls.__name__, [])

        # Get sort order
        if hasattr(cls, '_sort_order'):
            sort_fields = cls._sort_order
        else:
            sort_fields = []
            for field in fields:
                base_field = field.split('__', 1)[0]
                point_match = re_point.match(base_field)
                if point_match:
                    continue
                field_type = cls._meta.get_field(base_field)
                assert not isinstance(field_type, ManyToManyField)
                sort_fields.append(field)

        # Create CSV writer
        out = StringIO()
        csv_writer = writer(out, lineterminator='\n')

        # Write header row
        header_row = [text_type(c) for c in columns]
        header_row.extend(extra_columns)
        write_text_rows(csv_writer, [header_row])

        # Report the work to be done
        total = objects.count()
        logger.info(
            '%d %s to export...',
            total, cls._meta.verbose_name_plural)

        # Populate related items cache
        model_to_field_name = {}
        cache = {}
        for field_name in fields:
            if '__' in field_name:
                local_field_name, subfield_name = field_name.split('__', 1)
                field = cls._meta.get_field(local_field_name)
                field_type = field.related_model
                model_name = field_type.__name__
                if model_name in model_to_field_name:
                    # Already loaded this model under a different field name
                    cache[field_name] = cache[model_to_field_name[model_name]]
                else:
                    # Load all feed data for this model
                    pairs = field_type.objects.in_feed(
                        feed).values_list('id', subfield_name)
                    cache[field_name] = dict(
                        (i, text_type(x)) for i, x in pairs)
                    cache[field_name][None] = u''
                    model_to_field_name[model_name] = field_name

        # Assemble the rows, writing when we hit batch size
        count = 0
        rows = []
        for item in objects.order_by(*sort_fields).iterator():
            row = []
            for csv_name, field_name in column_map:
                obj = item
                point_match = re_point.match(field_name)
                if '__' in field_name:
                    # Return relations from cache
                    local_field_name = field_name.split('__', 1)[0]
                    field_id = getattr(obj, local_field_name + '_id')
                    row.append(cache[field_name][field_id])
                elif point_match:
                    # Get the lat or long from the point
                    name, index = point_match.groups()
                    field = getattr(obj, name)
                    row.append(field.coords[int(index)])
                else:
                    # Handle other field types
                    field = getattr(obj, field_name) if obj else ''
                    if isinstance(field, date):
                        formatted = field.strftime(u'%Y%m%d')
                        row.append(text_type(formatted))
                    elif isinstance(field, bool):
                        row.append(1 if field else 0)
                    elif field is None:
                        row.append(u'')
                    else:
                        row.append(text_type(field))
            for col in extra_columns:
                row.append(obj.extra_data.get(col, u''))
            rows.append(row)
            if len(rows) % batch_size == 0:  # pragma: no cover
                write_text_rows(csv_writer, rows)
                count += len(rows)
                logger.info(
                    "Exported %d %s",
                    count, cls._meta.verbose_name_plural)
                rows = []

        # Write rows smaller than batch size
        write_text_rows(csv_writer, rows)
        return out.getvalue()
254570
def export(self):
        
        data = {}
        for key, value in self.items():
            data[key] = value

        return data
92548
def csv_list(models, attr, link=False, separator=", "):
    """"""
    values = []
    for model in models:
        value = getattr(model, attr)
        if link and hasattr(model, "get_admin_url") and callable(model.get_admin_url):
            value = get_admin_html_link(model, label=value)
        values.append(value)
    return separator.join(values)
726951
def StatsToCSV(campaign, model='nPLD'):
    '''
    
    '''
    statsfile = os.path.join(EVEREST_SRC, 'missions', 'k2',
                             'tables', 'c%02d_%s.cdpp' % (campaign, model))
    csvfile = os.path.join(os.path.dirname(EVEREST_SRC), 'docs',
                           'c%02d.csv' % campaign)
    epic, kp, cdpp6r, cdpp6, _, _, _, _, saturated = \
        np.loadtxt(statsfile, unpack=True, skiprows=2)

    with open(csvfile, 'w') as f:
        print('c%02d' % campaign, file=f)
        for i in range(len(epic)):
            print('%09d,%.3f,%.3f,%.3f,%d' % (epic[i], kp[i],
                                              cdpp6r[i], cdpp6[i],
                                              int(saturated[i])),
                                              file=f)
878427
def export_as_csv(admin_model, request, queryset):
    
    # everyone has perms to export as csv unless explicitly defined
    if getattr(settings, 'DJANGO_EXPORTS_REQUIRE_PERM', None):
        admin_opts = admin_model.opts
        codename = '%s_%s' % ('csv', admin_opts.object_name.lower())
        has_csv_permission = request.user.has_perm("%s.%s" % (admin_opts.app_label, codename))
    else:
        has_csv_permission = admin_model.has_csv_permission(request) \
            if (hasattr(admin_model, 'has_csv_permission') and callable(getattr(admin_model, 'has_csv_permission'))) \
            else True
    if has_csv_permission:
        opts = admin_model.model._meta
        if getattr(admin_model, 'csv_fields', None):
            field_names = admin_model.csv_fields
        else:
            field_names = [field.name for field in opts.fields]
            field_names.sort()

        if django.VERSION[0] == 1 and django.VERSION[1] <= 5:
            response = HttpResponse(mimetype='text/csv')
        else:
            response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % text(opts).replace('.', '_')

        queryset = queryset.values_list(*field_names)
        pandas.DataFrame(list(queryset), columns=field_names).to_csv(response, index=False, encoding='utf-8')
        return response
    return HttpResponseForbidden()