def update_view(self): try: self.ui.sliderYscale.setValue(int(self.graphics_view.transform().m22())) except AttributeError: return txt = self.ui.txtEditErrors.toPlainText() new_messages = self.device.read_messages() self.__parse_error_messages(new_messages) if len(new_messages) > 1: self.ui.txtEditErrors.setPlainText(txt + new_messages) self.ui.lSamplesCaptured.setText(Formatter.big_value_with_suffix(self.device.current_index, decimals=1)) self.ui.lSignalSize.setText(locale.format_string("%.2f", (8 * self.device.current_index) / (1024 ** 2))) self.ui.lTime.setText(locale.format_string("%.2f", self.device.current_index / self.device.sample_rate)) if self.is_rx and self.device.data is not None and len(self.device.data) > 0: self.ui.labelReceiveBufferFull.setText("{0}%".format(int(100 * self.device.current_index / len(self.device.data)))) if self.device.current_index == 0: return False return True
def latex_length_costs(self, avarage): if self.costs and self.length: return format_string("%0.2f Mio & %s", (self.costs / self.length, dev(avarage.length_costs,self.costs/ self.length) )) elif self.estimated_costs and self.length: return format_string("%0.2f Mio \\footnotemark[2] & %s", (self.estimated_costs/ self.length, dev(avarage.length_costs,self.estimated_costs/ self.length) )) else: return "-"
def latex_stations_costs(self, avarage): if self.costs and self.stations: return format_string("%0.2f Mio & %s ", (self.costs/ self.stations, dev(avarage.stations_costs,self.costs/ self.stations))) elif self.estimated_costs and self.stations: return format_string("%0.2f Mio \\footnotemark[2] & %s", (self.estimated_costs/ self.stations, dev(avarage.stations_costs,self.estimated_costs/ self.stations))) else: return "-"
def updateWordCount(self): """ Updates the word count of the template, and displays it in a label. Also, updates self.template, which is used to create the items when calling self.createFile. """ total = 1 # Searching for every spinboxes on the widget, and multiplying # their values to get the number of words. for s in self.findChildren(QSpinBox, QRegExp(".*"), Qt.FindChildrenRecursively): total = total * s.value() # Update self.template to reflect the changed values templateIndex = s.property("templateIndex") self.template[1][templateIndex] = ( s.value(), self.template[1][templateIndex][1]) if total == 1: total = 0 self.lblTotal.setText(self.tr("<b>Total:</b> {} words (~ {} pages)").format( locale.format_string("%d", total, grouping=True), locale.format_string("%d", total / 250, grouping=True) ))
def regression(filename, data, name): x = [d.get_length_vector() + [1] for d in data] y = [d.get_costs() for d in data] names = [d.description + " in " + d.place for d in data] clf = linear_model.ARDRegression(compute_score=True) clf.fit(x, y) result = clf.coef_ print name print result with open(filename, "w") as out: lines = [ format_string("\\newcommand{\\%snormal}{%0.2f}", (name, result[1])), format_string("\\newcommand{\\%stunnel}{%0.2f}", (name, result[0])), "\\begin{tabular}{llll}", "Strecke & \multicolumn{2}{c}{Kosten} & Fehler\\\\", "& geschätzt & tatsächlich & \\\\", "\\hline", ] for name, xv, yv in zip(names, x, y): pred = 0 for xi, ci in zip(xv, result): pred += xi * ci lines.append(format_string("%s & %0.2f & %0.2f & %d \\%%\\\\", (name, pred, yv, (pred - yv) * 100 / yv))) lines.append("\\end{tabular}") out.write("\n".join(lines))
def big_value_with_suffix(value: float, decimals=3) -> str: fmt_str = "%.{0:d}f".format(decimals) if abs(value) >= 1e9: return locale.format_string(fmt_str+"G", value / 1e9) elif abs(value) >= 1e6: return locale.format_string(fmt_str+"M", value / 1e6) elif abs(value) >= 1e3: return locale.format_string(fmt_str+"k", value / 1e3) else: return locale.format_string(fmt_str, value)
def fmtTimeSpanPair(time1, time2, short=False): (type, point) = optimalPeriod(time1, 0) time1 = convertSecondsTo(time1, type) time2 = convertSecondsTo(time2, type) # a pair is always should always be read as plural if short: fmt = shortTimeTable[type] else: fmt = timeTable[type](2) timestr = "%(a)d.%(b)df" % {"a": pad, "b": point} finalstr = "%s-%s" % (locale.format_string("%" + timestr, time1), locale.format_string("%" + timestr, time2)) return fmt % finalstr
def stats(self): wc = self.data(enums.Outline.wordCount) goal = self.data(enums.Outline.goal) progress = self.data(enums.Outline.goalPercentage) if not wc: wc = 0 if goal: return qApp.translate("outlineItem", "{} words / {} ({})").format( locale.format_string("%d", wc, grouping=True), locale.format_string("%d", goal, grouping=True), "{}%".format(str(int(progress * 100)))) else: return qApp.translate("outlineItem", "{} words").format( locale.format_string("%d", wc, grouping=True))
def print_results(): locale.setlocale(locale.LC_ALL, '') # Analyze blocks block_total = 0 for block_id,block_count in block_counts.items(): print(locale.format_string("%20s: %12d", (block_id, block_count))) block_total += block_count solid_blocks = block_total - block_counts ['air'] solid_ratio = (solid_blocks+0.0)/block_total print(locale.format_string("%d total blocks in world, %d are non-air (%0.4f", (block_total, solid_blocks, 100.0*solid_ratio))+"%)")
def _format_size(size): """Convert a given size in bytes to a nicer better readable unit""" if size == 0: # TRANS: download size is 0 return _('None') elif size < 1024: # TRANS: download size of very small updates return _('1 KB') elif size < 1024 * 1024: # TRANS: download size of small updates, e.g. '250 KB' return locale.format_string(_('%.0f KB'), size / 1024.0) else: # TRANS: download size of updates, e.g. '2.3 MB' return locale.format_string(_('%.1f MB'), size / 1024.0 / 1024)
def update_view(self): try: self.ui.sliderYscale.setValue(int(self.graphics_view.transform().m22())) except AttributeError: return txt = self.ui.txtEditErrors.toPlainText() new_messages = self.device.read_messages() if "No devices found for" in new_messages: self.device.stop_on_error("Could not establish connection to USRP") Errors.usrp_found() self.on_clear_clicked() elif any(e in new_messages for e in ("HACKRF_ERROR_NOT_FOUND", "HACKRF_ERROR_LIBUSB")): self.device.stop_on_error("Could not establish connection to HackRF") Errors.hackrf_not_found() self.on_clear_clicked() elif "No module named gnuradio" in new_messages: self.device.stop_on_error("Did not find gnuradio.") Errors.gnuradio_not_installed() self.on_clear_clicked() elif "RTLSDR-open: Error Code: -1" in new_messages: self.device.stop_on_error("Could not open a RTL-SDR device.") self.on_clear_clicked() elif "Address already in use" in new_messages: self._restart_device_thread() if len(new_messages) > 1: self.ui.txtEditErrors.setPlainText(txt + new_messages) self.ui.progressBar.setValue(self.device.current_index) self.ui.lSamplesCaptured.setText("{0:n}".format(self.device.current_index)) self.ui.lSignalSize.setText(locale.format_string("%.2f", (8 * self.device.current_index) / (1024 ** 2))) self.ui.lTime.setText(locale.format_string("%.2f", self.device.current_index / self.device.sample_rate)) if self.is_rx and self.device.data is not None and len(self.device.data) > 0: self.ui.labelReceiveBufferFull.setText("{0}%".format(int(100 * self.device.current_index / len(self.device.data)))) if self.device.current_index == 0: return False return True
def test(): helper.dividing_with_title(' start ') # repr import repr print repr.repr(set('abcdedabc')) print repr.repr(dict({'name' : 'wjh', 'age' : 11})) # pprint import pprint t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]] pprint.pprint(t,None,1,80) # textwrap import textwrap doc = """The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines.""" print textwrap.fill(doc,50) # locale import locale locale.setlocale(locale.LC_ALL,'English_United States.1252') conv=locale.localeconv() x = 1234.6 print locale.format("%d", x, grouping=True) print locale.format_string("%s%.*f", (conv['currency_symbol'], conv['frac_digits'], x), grouping=True) # Template from string import Template t = Template('${village}folk send $$10 to $cause.') print t.substitute(village='Nottingham', cause='the ditch fund') d = dict(name='wjh',age=20) t = Template('name: $name and age: $age') print t.substitute(d) print t.safe_substitute(d) import time, os.path photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] # fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ') # print fmt # struct import struct data = open(helper.getfile('test.txt'), 'rb') print data.readline() data.close()
def from_float(self, value, group=False, prec=-1): """ Format the float value according to the locale. Parameters ---------- value : float The float to convert a string. group : bool, optional Whether or not to add group separators in the result. The default is False. prec : int, optional The number of signficant digits to display in the string. The default is -1 which means the decision is left up to the implementor. Returns ------- result : unicode string The locale formatted integer string. """ if prec < 0: s = '%g' else: s = '%' + '.%dg' % prec return unicode(locale.format_string(s, value, group))
def humanize_size(bytes): """ Convert a given size in bytes to a nicer better readable unit """ if bytes == 0: # TRANSLATORS: download size is 0 return _("0 kB") elif bytes < 1000: # TRANSLATORS: download size of very small updates return _("1 kB") elif bytes < 1000 * 1000: # TRANSLATORS: download size of small updates, e.g. "250 kB" return locale.format_string(_("%.0f kB"), bytes/1000) else: # TRANSLATORS: download size of updates, e.g. "2.3 MB" return locale.format_string(_("%.1f MB"), bytes / 1000.0 / 1000.0)
def __init__(self, signal, parent=None): super().__init__(parent) self.signal = signal self.ui = Ui_SignalDetails() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) file = self.signal.filename self.ui.lblName.setText(self.signal.name) if os.path.isfile(file): self.ui.lblFile.setText(file) self.ui.lblFileSize.setText(locale.format_string("%.2fMB", os.path.getsize(file) / (1024 ** 2))) self.ui.lFileCreated.setText(time.ctime(os.path.getctime(file))) else: self.ui.lblFile.setText(self.tr("signal file not found")) self.ui.lblFileSize.setText("-") self.ui.lFileCreated.setText("-") self.ui.lblSamplesTotal.setText("{0:n}".format(self.signal.num_samples).replace(",", " ")) self.ui.dsb_sample_rate.setValue(self.signal.sample_rate) self.set_duration() self.ui.dsb_sample_rate.valueChanged.connect(self.on_dsb_sample_rate_value_changed) try: self.restoreGeometry(constants.SETTINGS.value("{}/geometry".format(self.__class__.__name__))) except TypeError: pass
def update(self): self.progress_.show() n_text = DB.fetchone("""select count(*) from text""", (0,))[0] self.progress_.inc(2) n_res = DB.fetchone("""select count(*) from result""", (0,))[0] self.progress_.inc(2) n_words = DB.fetchall( """select count(*),sum(count) from statistic group by type order by type""" ) self.progress_.inc(2) if len(n_words) != 3: n_words = [(0, 0), (0, 0), (0, 0)] n_first = DB.fetchone("""select w from result order by w asc limit 1""", (time.time(),))[0] self.progress_.hide() self.stats_.setText( locale.format_string( """Texts: %d Results: %d Analysis data: %d (%d keys, %d trigrams, %d words) %d characters and %d words typed total\n""" + ("First result was %.2f days ago.\n" % ((time.time() - n_first) / 86400.0)), tuple( [n_text, n_res, sum(map(lambda x: x[0], n_words))] + map(lambda x: x[0], n_words) + [n_words[0][1], n_words[2][1]] ), True, ) )
def show_download_done(self, total_points_paid): if self.bytes_downloaded_label is not None and self.bytes_downloaded_label.winfo_exists(): self.bytes_downloaded_label.destroy() if self.cost_label is not None and self.cost_label.winfo_exists(): self.cost_label.config(text=locale.format_string("%.2f LBC", (round(total_points_paid, 2),), grouping=True))
def pprint_val(self, x): xp = (x-self.offset)/10**self.orderOfMagnitude if np.absolute(xp) < 1e-8: xp = 0 if self._useLocale: return locale.format_string(self.format, (xp,)) else: return self.format % xp
def format_data(self,value): 'return a formatted string representation of a number' if self._useLocale: s = locale.format_string('%1.10e', (value,)) else: s = '%1.10e' % value s = self._formatSciNotation(s) return self.fix_minus(s)
def _show_first_run_result(credits_received): if credits_received != 0.0: points_string = locale.format_string("%.2f LBC", (round(credits_received, 2),), grouping=True) alert.info("\n\nThank you for testing the alpha version of LBRY!\n\n" "You have been given %s for free because we love you.\n" "Please give them a few minutes to show up while you\n" "catch up with our blockchain.\n", points_string)
def format_string(self, format, val, grouping=False): """ Format a string in the current numeric locale. See python's locale.format_string for details. ICU's message formatting codes are incompatible with locale's, so just use locale.format_string for now. """ return locale.format_string(format, val, grouping)
def toString(self, val_t, context="current", addLabel=True, useThisFormat=None, NONE_string=None): """Format the value as a string. val_t: The value to be formatted as a value tuple. context: A time context (eg, 'day'). [Optional. If not given, context 'current' will be used.] addLabel: True to add a unit label (eg, 'mbar'), False to not. [Optional. If not given, a label will be added.] useThisFormat: An optional string or strftime format to be used. [Optional. If not given, the format given in the initializer will be used.] NONE_string: A string to be used if the value val is None. [Optional. If not given, the string given unit_format_dict['NONE'] will be used.] """ if val_t is None or val_t[0] is None: if NONE_string is not None: return NONE_string else: return self.unit_format_dict.get("NONE", "N/A") if val_t[1] == "unix_epoch": # Different formatting routines are used if the value is a time. if useThisFormat is not None: val_str = time.strftime(useThisFormat, time.localtime(val_t[0])) else: val_str = time.strftime(self.time_format_dict.get(context, "%d-%b-%Y %H:%M"), time.localtime(val_t[0])) elif val_t[2] == "group_deltatime": # Get a delta-time format string. Use a default if the user did not supply one: if useThisFormat is not None: format_string = useThisFormat else: format_string = self.time_format_dict.get("delta_time", default_time_format_dict["delta_time"]) # Now format the delta time, using the function delta_secs_to_string: val_str = self.delta_secs_to_string(val_t[0], format_string) # Return it right away, because it does not take a label return val_str else: # It's not a time. It's a regular value. Get a suitable # format string: if useThisFormat is None: # No user-specified format string. Go get one: format_string = self.get_format_string(val_t[1]) else: # User has specified a string. Use it. format_string = useThisFormat # Now use the format string to format the value: val_str = locale.format_string(format_string, val_t[0]) # Add a label, if requested: if addLabel: val_str += self.get_label_string(val_t[1], plural=(not val_t[0] == 1)) return val_str
def idle(): if self.current != directory: # Modified from another thread. return model = self.model view = self.tree if cursor_file: cursor_uri = cursor_file.get_uri() cursor_row = -1 model.clear() row = 0 for sortname, name, f in subdirs: model.append((f, self.directory, name, '', True)) uri = f.get_uri() if ( cursor_file and cursor_row == -1 and (cursor_uri == uri or cursor_uri.startswith(uri + '/')) ): cursor_row = row row += 1 for sortname, name, f in subfiles: size = ( f.query_info( 'standard::size', Gio.FileQueryInfoFlags.NONE, None ).get_size() // 1000 ) # locale.format_string does not support unicode objects # correctly, so we call it with an str and convert the # locale-dependent output to unicode. size = locale.format_string('%d', size, True) # TRANSLATORS: File size (1 kB = 1000 bytes) size = _('%s kB') % unicode(size, locale.getpreferredencoding()) model.append((f, self.track, name, size, False)) if cursor_file and cursor_row == -1 and cursor_uri == f.get_uri(): cursor_row = row row += 1 if cursor_file and cursor_row != -1: view.set_cursor((cursor_row,)) else: view.set_cursor((0,)) if view.get_realized(): view.scroll_to_point(0, 0) self.entry.set_text(directory.get_parse_name()) if history: self.back.set_sensitive(True) self.history[self.i + 1 :] = [self.current] self.i = len(self.history) - 1 self.forward.set_sensitive(False) self.up.set_sensitive(bool(directory.get_parent()))
def __repr__( self ): format = textwrap.dedent( """ %s %s """ ) return locale.format_string( format, ( self.in_, self.out ), True )
def show_progress(self, total_bytes, bytes_left_to_download, points_paid, points_remaining): if self.bytes_downloaded_label is None: self.remove_download_buttons() self.button_frame.destroy() self.estimated_cost_frame.destroy() for option, frame in self.option_frames: frame.destroy() self.options_frame.destroy() #self.show_options_button.destroy() self.progress_frame = ttk.Frame(self.outer_button_frame, style="F.TFrame") self.progress_frame.grid(row=0, column=0, sticky=tk.W, pady=(0, 8)) self.bytes_downloaded_label = ttk.Label( self.progress_frame, text="" ) self.bytes_downloaded_label.grid(row=0, column=0) self.cost_frame = ttk.Frame(self.outer_button_frame, style="F.TFrame") self.cost_frame.grid(row=1, column=0, sticky=tk.W, pady=(0, 4)) self.cost_label = ttk.Label( self.cost_frame, text="", foreground="red" ) self.cost_label.grid(row=0, column=1, padx=(1, 0)) self.outer_button_frame.grid_columnconfigure(2, weight=0, uniform="") if self.bytes_downloaded_label.winfo_exists(): percent_done = 0 if total_bytes > 0: percent_done = 100.0 * (total_bytes - bytes_left_to_download) / total_bytes percent_done_string = locale.format_string(" (%.2f%%)", percent_done) self.bytes_downloaded_label.config( text=self.get_formatted_stream_size(total_bytes - bytes_left_to_download) + percent_done_string ) if self.cost_label.winfo_exists(): total_points = points_remaining + points_paid self.cost_label.config(text=locale.format_string("%.2f/%.2f LBC", (round(points_paid, 2), round(total_points, 2)), grouping=True))
def __repr__( self ): items = sorted( self.break_down.items() ) generator = ( locale.format_string( "\t%s %.2f", ( key, value ), True ) for key, value in items ) content = "\n".join( generator ) format = textwrap.dedent( "%3s: %s\n%s" ) return format % ( self.name, self.total, content )
def dev(avarage, val): diff = val - avarage dev = diff / avarage if dev > 0: sign = "+" elif dev < 0: sign = "\\textminus" else: sign = "\\textpm" return format_string("%s %d \\%%", (sign, int(abs(dev)*100)))
def decimal_l10n(value, digits=2): """Returns the decimal value of value based on current locale. """ try: value = float(value) except ValueError: return value format_str = "%%.%sf" % digits return locale.format_string(format_str, value)
def fmtTimeSpan(time, pad=0, point=0, short=False): "Return a string representing a time span (eg '2 days')." (type, point) = optimalPeriod(time, point) time = convertSecondsTo(time, type) if short: fmt = shortTimeTable[type] else: fmt = timeTable[type](_pluralCount(round(time, point))) timestr = "%(a)d.%(b)df" % {"a": pad, "b": point} return locale.format_string("%" + (fmt % timestr), time)
def main(): num_tries = get_args() print(locale.format_string("\nSimulating game %d times.", num_tries, grouping=True)) chunk_size = 10**4 game = Game() pool = Pool() final_result = Result() for num_turns in get_num_runs_chunk(num_tries, chunk_size): results = pool.map(game.run, range(num_turns)) for result in results: final_result.first += result.first final_result.switch += result.switch final_result.random += result.random print(locale.format_string("\nAlways keeping first choice resulted in %d cars, or cars %.2f%% of the time.", (final_result.first, final_result.first/num_tries * 100), grouping=True)) print(locale.format_string("Always switching resulted in %d cars, or cars %.2f%% of the time.", (final_result.switch, final_result.switch/num_tries * 100), grouping=True)) print(locale.format_string("Randomly switching resulted in %d cars, or cars %.2f%% of the time.\n", (final_result.random, final_result.random/num_tries * 100), grouping=True))
def filter_format_number(val, places: int = None, grouping: bool = True) -> str: """Formats a number according to the user's locale.""" if not isinstance(val, (int, float)): return val if places is not None: format_str = f'%.{places}f' elif isinstance(val, int): format_str = '%d' else: format_str = '%.02f' locale.setlocale(locale.LC_ALL, '') return locale.format_string(format_str, val, grouping)
def notify_proc(context): job = context.job chat_id = job.context if chat_id not in portfolios: context.bot.send_message(chat_id, text='Your portfolio is empty! Use /add <symbol> <balance>') return val = api.get_portfolio_value(portfolios[chat_id]) old_val = old_balances[chat_id] change = ((val / old_val) - 1) * 100 emoji = ("\U0001F680" if change > 0 else "\U0001F4A9") text = locale.format_string("Portfolio: %.2f€ %+.2f%% %s", (val, change, emoji), grouping=True) if abs(change) >= min_changes[chat_id]: context.bot.send_message(chat_id, text=text) old_balances[chat_id] = val
def science_time(time_in_seconds: float) -> str: if time_in_seconds < 1e-6: suffix = "n" value = time_in_seconds * 1e9 elif time_in_seconds < 1e-3: suffix = "µ" value = time_in_seconds * 1e6 elif time_in_seconds < 1: suffix = "m" value = time_in_seconds * 1e3 else: suffix = "" value = time_in_seconds return locale.format_string("%.2f " + suffix, value) + "s"
def transfer(self, amount, recipient, comment=''): self.withdraw(amount, comment, recipient) recipient.deposit(amount, comment, self) amount = amount.replace(",", "") self.balance -= int(amount) ## Adds deposit value to balance locale.setlocale(locale.LC_ALL, 'en_US') str_balance = locale.format_string("%d", self.balance, grouping=True) print( f'Congrats {self.name} your transfer of ₦{amount} to {recipient.name} was successful. Your new balance is ₦{str_balance}. ' )
def from_int(self, value, base=10, group=False): """ Format the integer value according to the locale. Parameters ---------- value : int The integer to convert a string. base : int, optional The number base to use when parsing the string. The valid values are the same as those passed to Python's builtin 'int'. The default is 10. group : bool, optional Whether or not to add group separators in the result. The default is False. Returns ------- result : unicode string The locale formatted integer string. """ # We can specially format bases 2, 8, 16. The others we format # as normal integers after converting them to a proper base. if base == 2: r = bin(value) elif base == 8: r = locale.format_string('%#o', value, group) elif base == 10: r = locale.format_string('%d', value, group) elif base == 16: r = locale.format_string('%#X', value, group) else: r = _convert_base(value, base) return unicode(r)
def printf(cls, format, s, _locale=None): """Print the formatted string to stdout. :param format: format for the string. :param s: string to print :param locale: If locale is given, prints using the given locale. :return: """ if _locale is not None: locale.setlocale(locale.LC_ALL, _locale) formatted_s = locale.format_string(format, s) print(formatted_s, flush=True) locale.resetlocale() else: print(format % s, flush=True)
def fmtTimeSpan(time, pad=0, point=0, short=False, after=False): "Return a string representing a time span (eg '2 days')." (type, point) = optimalPeriod(time, point) time = convertSecondsTo(time, type) if not point: time = math.floor(time) if short: fmt = shortTimeTable[type] else: if after: fmt = afterTimeTable[type](_pluralCount(time, point)) else: fmt = timeTable[type](_pluralCount(time, point)) timestr = "%(a)d.%(b)df" % {'a': pad, 'b': point} return locale.format_string("%" + (fmt % timestr), time)
def format_field(self, j, h, fieldlen): if isinstance(j, float): if is_pct(h): j *= 100.0 fmt = "%.2f" j = scale_val(j) elif is_str(j): fmt = "%s" else: fmt = "%d" j = scale_val(j) num = locale.format_string(fmt, j, grouping=True) if len(num) >= fieldlen: num += " " return num
def ajukanPinjaman(self): print("Ajukan Pinjaman") query = str(input("ID: ")) cust = self.customer.getWhere("uid",query) if len(cust)>0: if cust[0].pinjaman != 0: print("Anda masih memiliki pinjaman yang harus dilunasi") return False pinjaman = abs(int(input("Jumlah pinjaman: "))) print("biaya Admin: Rp.1.000.000") print("total bunga: Rp.",locale.format_string("%d",pinjaman*0.14,True),sep='') print("Total pinjaman: Rp.",locale.format_string("%d",pinjaman*1.14+1000000,True),sep='') print("Cicilan perbulan: Rp.",locale.format_string("%d",(pinjaman*1.14+1000000)/12,True),sep='') c ='a' while not (c=='y' or c=='n'): c = input("Ajukan? (y/n)") if c=='y': self.customer.update("uid",query,"pinjaman",int(pinjaman*1.14+1000000)) self.transaction.addTrx(query,1,int(pinjaman*1.14+1000000)) print("Pengajuan pinjaman berhasil.") return True else: print("Pengajuan pinjaman ditolak.") return False
def refresh_estimated_time(self): c = self.table_model.protocol if c.num_messages == 0: self.ui.lEstimatedTime.setText("Estimated Time: ") return avg_msg_len = numpy.mean([len(msg.encoded_bits) for msg in c.messages]) avg_bit_len = numpy.mean([m.samples_per_bit for m in self.modulators]) avg_sample_rate = numpy.mean([m.sample_rate for m in self.modulators]) pause_samples = sum(c.pauses) nsamples = c.num_messages * avg_msg_len * avg_bit_len + pause_samples self.ui.lEstimatedTime.setText( locale.format_string("Estimated Time: %.04f seconds", nsamples / avg_sample_rate))
def get_value_with_suffix(value, unit=""): decimal_point = locale.localeconv()["decimal_point"] if abs(value) >= 10**9: target_val, suffix = value / 10**9, "G" elif abs(value) >= 10**6: target_val, suffix = value / 10**6, "M" elif abs(value) >= 10**3: target_val, suffix = value / 10**3, "k" else: target_val, suffix = value, "" return locale.format_string( "%.3f", target_val).rstrip("0").rstrip(decimal_point) + suffix + unit
def fmtTimeSpan(time, pad=0, point=0, short=False, inTime=False, unit=99): "Return a string representing a time span (eg '2 days')." (type, point) = optimalPeriod(time, point, unit) time = convertSecondsTo(time, type) if not point: time = int(round(time)) if short: fmt = shortTimeFmt(type) else: if inTime: fmt = inTimeTable[type](_pluralCount(time, point)) else: fmt = timeTable[type](_pluralCount(time, point)) timestr = "%%%(a)d.%(b)df" % {'a': pad, 'b': point} return locale.format_string(fmt % timestr, time)
def humanize_size(bytes): """ Convert a given size in bytes to a nicer better readable unit """ if bytes < 1000 * 1000: # to have 0 for 0 bytes, 1 for 0-1000 bytes and for 1 and above # round up size_in_kb = int(ceil(bytes / float(1000))) # TRANSLATORS: download size of small updates, e.g. "250 kB" return ngettext("%(size).0f kB", "%(size).0f kB", size_in_kb) % { "size": size_in_kb} else: # TRANSLATORS: download size of updates, e.g. "2.3 MB" return locale.format_string(_("%.1f MB"), bytes / 1000.0 / 1000.0)
def localized_size(num_bytes): """ Return pretty localized size string for num_bytes size (given in bytes). The output will be in kibibytes. """ # always round up, so that small files don't end up as '0 KiB' num_kib = math.ceil(num_bytes / 1024) try: formatted_num = locale.format_string("%d", num_kib, grouping=True) except UnicodeDecodeError: # failure to decode locale data formatted_num = str(num_kib) unicode_num = _unicode_decode(formatted_num, encoding=_encodings["stdio"]) return f"{unicode_num} KiB"
def idle(): if self.current != directory: # Modified from another thread. return model = self.model view = self.tree if cursor_file: cursor_uri = cursor_file.get_uri() cursor_row = -1 model.clear() row = 0 for sortname, name, f in subdirs: model.append((f, self.directory, name, '', True)) uri = f.get_uri() if (cursor_file and cursor_row == -1 and (cursor_uri == uri or cursor_uri.startswith(uri + '/'))): cursor_row = row row += 1 for sortname, name, f in subfiles: size = ( f.query_info('standard::size', Gio.FileQueryInfoFlags.NONE, None).get_size() // 1000) # TRANSLATORS: File size (1 kB = 1000 bytes) size = _('%s kB') % locale.format_string('%d', size, True) model.append((f, self.track, name, size, False)) if cursor_file and cursor_row == -1 and cursor_uri == f.get_uri( ): cursor_row = row row += 1 if cursor_file and cursor_row != -1: view.set_cursor((cursor_row, )) else: view.set_cursor((0, )) if view.get_realized(): view.scroll_to_point(0, 0) self.entry.set_text(directory.get_parse_name()) if history: self.back.set_sensitive(True) self.history[self.i + 1:] = [self.current] self.i = len(self.history) - 1 self.forward.set_sensitive(False) self.up.set_sensitive(bool(directory.get_parent()))
def on_button_velocity_calculate_clicked(self, widget): distunit = self.widgets.combobox_velocity_distance.get_unit() speedunit = self.widgets.combobox_velocity_speed.get_unit() distance = self.widgets.spinbutton_velocity_distance.get_value() hours = self.widgets.spinbutton_velocity_hours.get_value_as_int() minutes = self.widgets.spinbutton_velocity_minutes.get_value_as_int() seconds = self.widgets.spinbutton_velocity_seconds.get_value_as_int() seconds_total = (hours * 3600) + (minutes * 60) + seconds if seconds_total == 0: self.widgets.spinbutton_velocity_seconds.set_value(1) seconds_total = 1 speed = (distance * distunit) / (seconds_total * speedunit) self.widgets.entry_velocity_result.set_text( locale.format_string("%.4f", speed))
def demoCounty(results): print("..........................................................................................") print("................................. DEMOGRAPHICS OF A COUNTY ................................") print("..........................................................................................") print("\n") stateInput = getCorrectState(results) countyList = results.getListioCountiesUnderState(stateInput) if not countyList: exit() elif countyList == -1: exit() else: for i in countyList: print(i[0]) print("\n") county = getCorrectCounty(results) demographics = results.demographicsByCounty(stateInput, county) if not demographics: print("Error: Check if county exists and is spelled correctly.\n") elif demographics == -1: exit() elif demographics == -2: print("Demographic info for the state Alaska does not exist. Please try another state.\n") else: print("\n") for i in demographics: print("-- ", locale.format_string("%s", i[1], grouping=True), " Demographics --") print("Total Population - ", locale.format_string("%d", i[2], grouping=True)) print("Men - ", locale.format_string("%s", i[3], grouping=True), "%") print("Women - ", locale.format_string("%s", i[4], grouping=True), "%") print("White - ", locale.format_string("%s", i[5], grouping=True), "%") print("Black - ", locale.format_string("%s", i[6], grouping=True), "%") print("Hispanic - ", locale.format_string("%s", i[7], grouping=True), "%") print("Asian - ", locale.format_string("%s", i[8], grouping=True), "%") print("Native - ", locale.format_string("%s", i[9], grouping=True), "%") print("\n")
def update_text(CCAA_types, PROV_types,municipio_types ): if CCAA_types == 'TODAS' and PROV_types == 'TODAS' and municipio_types == 'TODOS': value=df_final_pob['Población 2018'].sum() elif CCAA_types != 'TODAS' and PROV_types == 'TODAS' and municipio_types == 'TODOS': value = df_final_pob.loc[df_final_pob['CCAA'] == CCAA_types,'Población 2018'].sum() elif PROV_types != 'TODAS' and municipio_types == 'TODOS': value = df_final_pob.loc[df_final_pob['Provincia']==PROV_types,'Población 2018'].sum() else: value=df_final_pob.loc[df_final_pob['Nombre Ente Principal'] == municipio_types,'Población 2018'].sum() value=locale.format_string('%.0f', value, True) return f'{value} hab.'
def currency_calc(): currency_code = get_currency_code() if request.method == 'GET': return render_template("currency.html", items=currency_code) elif request.method == 'POST': currency_count = request.form['currency_count'] selected_currency_code = request.form['currency'] curr_value = get_currency_exchange(selected_currency_code, currency_count) if curr_value != None: curr_value = locale.format_string('%.2f', curr_value, True) return render_template("currency_pay.html", items=currency_code, curr_value=curr_value, selected_currency_code=selected_currency_code, currency_count=currency_count)
def bayarPinjaman(self): print("Bayar Pinjaman") query = str(input("ID: ")) cust = self.customer.getWhere("uid",query) if len(cust)>0: print("Sisa tagihan: Rp.",locale.format_string("%d",cust[0].pinjaman,True),sep='') pinjaman = abs(int(input("Jumlah pembayaran: "))) pinjaman_awal = cust[0].pinjaman pinjaman_akhir = pinjaman_awal - pinjaman self.customer.update("uid",query,"pinjaman",int(pinjaman_akhir)) self.transaction.addTrx(query,1,(-1)*pinjaman) print("Pembayaran pinjaman berhasil.") return True else: print("Pembayaran pinjaman ditolak.") return False
def populateScaleChoices(self): """ When the template type combo is initialised or changes, update the layout of scales for the various map elements in layout. """ # Clear previous for i in reversed(list(range(self.ui.scalesGridLayout.count()))): item = self.ui.scalesGridLayout.itemAt(i) if type(item) == QSpacerItem: self.ui.scalesGridLayout.removeItem(item) else: item.widget().setParent(None) print_layout = self.get_print_layout() map_elements = [ item for item in print_layout.items() if isinstance(item, QgsLayoutItemMap) ] i = 0 for elem in map_elements: label_1 = QLabel(elem.displayName()) self.ui.scalesGridLayout.addWidget(label_1, i, 0) spacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.ui.scalesGridLayout.addItem(spacer, i, 1) label_2 = QLabel('1:') self.ui.scalesGridLayout.addWidget(label_2, i, 2) comboBox = QComboBox() comboBox.setEditable(True) # Add current canvas scale locale.setlocale(locale.LC_ALL, '') currentMapCanvasScale = self.iface.mapCanvas().scale() scaleString = locale.format_string('%d', currentMapCanvasScale, grouping=True) comboBox.addItem(f'{scaleString} (Current map canvas)') for scale in self.presetScales: comboBox.addItem(str(scale)) self.ui.scalesGridLayout.addWidget(comboBox, i, 3) i += 1 if len(map_elements) == 0: label = QLabel('No layout map elements found. Limited usability.') self.ui.scalesGridLayout.addWidget(label, i, 1)
def adjust_increment(price, minpriceinc): try: price = Decimal(price) print( f'>> adjust_increment, input price: {price}, minpriceinc: {minpriceinc}\n' ) print( f'Type of minpriceinc {type(minpriceinc)}, price: {type(price)}\n') if 'e' in str(minpriceinc): p = Decimal(locale.format_string("%f", minpriceinc)) else: p = Decimal(str(minpriceinc)) min_price_decimals = len(str(p).split(".")[1]) minpriceinc = Decimal(minpriceinc) print(f'Inside Adjust_increment: min price inc: {minpriceinc},' + f' number of decimals allowed: {min_price_decimals}\n\n') print(f' Type of min_price_decimals: {type(min_price_decimals)}') deci = price - math.floor(price) if deci == 0: adjusted_price = price print(f'\n Deci - adjusted price is price: {price}') return adjusted_price remainder = Decimal(deci) % minpriceinc # type of minprice in is float by default? print(f'Type of minpriceinc {type(minpriceinc)}, deci: {type(deci)}\n') print(f'Type of remainder {type(remainder)}\n') if remainder == 0.0: # we are at no remainder so obeys step. adjusted_price = price print(f'remainder - adjusted price is price: {price}') else: near_price = round_nearest(price, minpriceinc) adjusted_price = round(near_price, min_price_decimals) print( f'round_nearest price: {near_price}, adj_price: {adjusted_price}' ) return adjusted_price except Exception as e: print(f'Exception thrown in adjust_increment: {e}') return e
def processfile(inputfile): filesize = 0 lineno = 1 try: with open(inputfile, 'r') as f: print('File Name : %s' % inputfile) read_data = f.read(16) while read_data: filesize += len(read_data) outputdata(read_data, lineno) lineno += 1 read_data = f.read(16) except IOError as e: print('Error %s : %s' % (e.errno, e.strerror)) sys.exit(2) f.close() print('File size (bytes) : ' + locale.format_string('%i', filesize, grouping=True))
def update_view(self): self.ui.sliderYscale.setValue(int( self.graphics_view.transform().m22())) txt = self.ui.txtEditErrors.toPlainText() new_errors = self.device.read_errors() if "No devices found for" in new_errors: self.device.stop_on_error("Could not establish connection to USRP") Errors.usrp_ip_not_found() self.on_clear_clicked() elif "FATAL: No supported devices found" in new_errors or \ "HACKRF_ERROR_NOT_FOUND" in new_errors or \ "HACKRF_ERROR_LIBUSB" in new_errors: self.device.stop_on_error( "Could not establish connection to HackRF") Errors.hackrf_not_found() self.on_clear_clicked() elif "No module named gnuradio" in new_errors: self.device.stop_on_error("Did not find gnuradio.") Errors.gnuradio_not_installed() self.on_clear_clicked() elif "Address already in use" in new_errors: self._restart_device_thread() if len(new_errors) > 1: self.ui.txtEditErrors.setPlainText(txt + new_errors) self.ui.progressBar.setValue(self.device.current_index) self.ui.lSamplesCaptured.setText("{0:n}".format( self.device.current_index)) self.ui.lSignalSize.setText("{0:n}".format( (8 * self.device.current_index) / (1024**2))) self.ui.lTime.setText( locale.format_string( "%.2f", self.device.current_index / self.device.sample_rate)) if self.device.current_index == 0: return False return True
def show_score(self): self.mybuilder.get_object('labellifes').set_label(str(self.scoredata.lifes)) self.mybuilder.get_object('labelscore').set_label(locale.format_string('%0d', self.scoredata.score, grouping = True)) self.mybuilder.get_object('labelpuzzlesplayed').set_label(str(len(self.scoredata.puzzlesplayed))) widget = self.mybuilder.get_object('labelforresult') if self.scoredata.lastresult == 'Solved!': if widget.get_style_context().has_class('uncolorizeR'): pass else: widget.get_style_context().remove_class('colorizeR') widget.get_style_context().add_class('uncolorizeR') else: if widget.get_style_context().has_class('uncolorizeR'): widget.get_style_context().remove_class('uncolorizeR') widget.get_style_context().add_class('colorizeR') widget.set_label(self.scoredata.lastresult)
def setupHbarPlot(df, cdf, type, ginfo, ax, color): vals = list(df.values) y_pos = list(range(len(df))) ax.text(0.985, 0.06, '© 2020 bgeneto', transform=ax.transAxes, ha='right', color='#777777', bbox=dict(facecolor='white', alpha=0.75, edgecolor='white')) ax.text(0.985, 0.02, 'Fonte: www.worldometers.info', transform=ax.transAxes, ha='right', color='#777777', bbox=dict(facecolor='white', alpha=0.75, edgecolor='white')) ax.margins(0.15, 0.01) ax.barh(y_pos, vals, align='center', color=color) ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:n}')) ax.set_yticks(y_pos) # uggly but required in order to keep original keys order uggly = pd.DataFrame({ 'name': df.keys() }).merge(cdf[['name', 'translation']])['translation'].values ax.set_yticklabels(uggly, fontsize=14) nvals = len(vals) # add text and flags to every bar for i, v in enumerate(vals): val = locale.format_string(ginfo['fmt'][type['name']], round(vals[i], 2), True) ax.text(v, i, " " + val + " (P" + str(nvals - i) + ")", va='center', ha='left', fontsize=12) ccode = cdf[cdf['name'] == df.keys()[i]].index[0] addFlag2Plot((v, i), ccode, ax) ax.set_xlabel(ginfo['label'][type['name']], fontsize=16) ax.set_title(ginfo['title'][type['name']].format(df.name).upper(), fontsize=18) ax.xaxis.grid(which='major', alpha=0.5) ax.xaxis.grid(which='minor', alpha=0.2)
def get_svg_export_area_param_contour_inner(scanarium, svg_path): # We want to determine the white inner area of the rect with id # `contour` in user coordinates. Ideally, Inkscape would allow to access # that directly. However, its `--query*` arguments only allow to get the # rect's /outer/ dimensions. But we need the rect's inner dimensions # (without border). So we have to compute that manually by moving the # rect's stroke-width inwards. # # (At this point we do not make up for scalings/rotations in the document # tree above the rect.) tree = ET.parse(svg_path) stroke_width = get_svg_contour_rect_stroke_width(tree) inkscape_args = [ '--query-all', svg_path, ] x = None y_top = None width = None height = None element_sizes = run_inkscape(scanarium, inkscape_args)['stdout'].split('\n') for element_size in element_sizes: if x is None or element_size.startswith('contour,'): # We're at either the first element (ie.: page), or the contour x, y_top, width, height = map(float, element_size.split(',')[1:]) # When querying through Inkscape (as above), svg uses the top-left corner # as origin (as SVG does), but for `--export-area` it expects the # bottom-left corner as origin. So we need to re-compute the y from the # paper's bottom edge. paper_height = root_attribute_to_px(tree, 'height') y_bottom = paper_height - y_top - height # And as Inkscape reports the rect's outer coordinates, but we need the # inner coordinates (as that is what we extract when scanning a user # picture) we need to move the stroke-width inwards. return locale.format_string('%f:%f:%f:%f', ( (x + stroke_width), (y_bottom + stroke_width), (x + width - stroke_width), (y_bottom + height - stroke_width), ))
def create(self, **kwargs) -> 'Figure': ''' Parameters ---------- delta : list values of delta between rating in the scenario and status quo ''' labels = kwargs['columns'] y = np.arange(len(labels)) data = kwargs['delta'] figure, ax = plt.subplots() colors = np.full(len(data), 'g') colors[data < 0] = 'r' bars = ax.barh(y, data, align='center', color=colors) ax.set_yticks(y) #categories = u_categories(kwargs['categories']) #ax.minorticks_on() #ax.set_yticks(y, minor=True) #ax.set_yticks(np.arange(len(categories)), minor=False) #ax.set_yticklabels(labels, minor=True) #ax.set_yticklabels(categories, minor=False) #ax.tick_params(axis='y', which='major', pad=150, labelsize=12) ax.set_xlabel('Bewertung im Planfall minus Bewertung im Nullfall') ax.set_title(kwargs['title']) max_rating = kwargs.get('max_rating', 0) min_val = -max_rating or min(-3, min(data)) max_val = max_rating or max(3, max(data)) ax.set_xlim(left=min_val - 1, right=max_val + 1) ax.set_xticks(range(min_val, max_val + 1, 1)) ax.set_yticklabels(labels) ax.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter( lambda x, p: locale.format_string('%+d', x))) ax.axvline(linewidth=1, color='grey') ax.legend() horizontal_label_values(bars, ax, force_signum=True) figure.tight_layout() return figure
def get_yaml_data(self): member_data = { 'to': self.address.replace('\n', ' \n'), 'sum': locale.format_string("%.2f", self.account_sum), 'opening': self.opening, 'email': self.vorname + ' ' + self.name + ' <' + self.email + '>' } member_data['position'] = [] for i in range(self.account.height): member_data['position'].append({ 'description': self.account['description'][i], 'value': self.account['value'][i] }) return member_data
def maxData(self): try: conn = MySQLdb.connect(**config) cursor = conn.cursor() # SQL 문 수행을 위한 커서 객체 생성 sang = self.txtSang.GetValue() su = self.txtSu.GetValue() dan = self.txtDan.GetValue() sql = "insert into sangdata(code,sang,su,dan) values((select max(code)+1 as a from sangdata ALIAS_FOR_SUBQUERY),%s,%s,%s)" cursor.execute(sql, (sang, su, dan)) conn.commit() sql = ''' select * from sangdata ''' cursor.execute(sql) sql = ''' select code,sang,su,dan,(su*dan) from sangdata ''' #print(sql) cursor.execute(sql) datas = cursor.fetchall() for d in datas: i = self.lstGogek.InsertItem(1000, 0) self.lstGogek.SetItem(i, 0, str(d[0])) self.lstGogek.SetItem(i, 1, str(d[1])) self.lstGogek.SetItem(i, 2, str(d[2])) self.lstGogek.SetItem(i, 3, str(d[3])) self.lstGogek.SetItem(i, 4, locale.format_string('%d', d[4], 1)) self.staCount.SetLabelText('건수' + str(len(datas))) except Exception as e: print('Logcheck err:' + e) finally: cursor.close() conn.close()