How to use the humanize.naturalsize function in humanize

To help you get started, we’ve selected a few humanize examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MetPX / sarracenia / sarra / plugins / msg_total.py View on Github external
parent.msg_total_msgcount = parent.msg_total_msgcount + 1

        lag=now-msgtime
        parent.msg_total_lag = parent.msg_total_lag + lag

        # guess the size of the message payload, ignoring overheads.
        parent.msg_total_bytecount += ( len(parent.msg.exchange) + len(parent.msg.topic) + len(parent.msg.notice) + len(parent.msg.hdrstr) )
        
        #not time to report yet.
        if parent.msg_total_interval > now-parent.msg_total_last :
           return True

        logger.info("msg_total: %3d messages received: %5.2g msg/s, %s bytes/s, lag: %4.2g s" % ( 
            parent.msg_total_msgcount,
	    parent.msg_total_msgcount/(now-parent.msg_total_start),
	    humanize.naturalsize(parent.msg_total_bytecount/(now-parent.msg_total_start),binary=True,gnu=True),
            parent.msg_total_lag/parent.msg_total_msgcount ))
        # Set the maximum age, in seconds, of a message to retrieve.

        if lag > parent.msg_total_maxlag :
           logger.warn("total: Excessive lag! Messages posted %s " % 
               humanize.naturaltime(datetime.timedelta(seconds=lag)))

        parent.msg_total_last = now

        if ( parent.msg_total_count > 0 ) and (parent.msg_total_msgcount >= parent.msg_total_count) :
           os._exit(0)

        return True
github abbeyokgo / PyOne / app / utils / header.py View on Github external
item['id']=fdata.get('id')
                    item['size']=humanize.naturalsize(fdata.get('size'), gnu=True)
                    item['size_order']=fdata.get('size')
                    item['lastModtime']=date_to_char(parse(fdata['lastModifiedDateTime']))
                    item['grandid']=idx
                    item['parent']=pid
                    item['path']=path
                    mon_db.items.insert_one(item)
                    pid=fdata.get('id')
    #插入数据
    item={}
    item['type']=GetExt(data.get('name'))
    item['name']=data.get('name')
    item['user']=user
    item['id']=data.get('id')
    item['size']=humanize.naturalsize(data.get('size'), gnu=True)
    item['size_order']=data.get('size')
    item['lastModtime']=date_to_char(parse(data.get('lastModifiedDateTime')))
    item['parent']=parent_id
    if grand_path=='':
        path=user+':/'+convert2unicode(data['name'])
    else:
        path=user+':/'+grand_path+'/'+convert2unicode(data['name'])
    path=path.replace('//','/')
    path=urllib.unquote(path).decode('utf-8')
    grandid=len(path.split('/'))-2
    item['grandid']=grandid
    item['path']=path
    InfoLogger().print_r('AddResource: name:{};path:{};grandid:{}'.format(data.get('name'),path,grandid))
    if GetExt(data['name']) in ['bmp','jpg','jpeg','png','gif']:
        item['order']=3
    elif data['name']=='.password':
github XiaomiFirmwareUpdater / miui-updates-tracker / miui_updates_tracker / social / facebook_page.py View on Github external
def generate_post(update: Update) -> (str, str):
        short_codename = update.codename.split('_')[0]
        link = f"{website}/miui/{short_codename}"
        message: str = f"New {update.branch} {update.method} update available for " \
                       f"{get_full_name(update.codename)} ({short_codename})!\n\n"
        message += f"Version: {update.version} | {update.android}\n" \
                   f"Size: {naturalsize(update.size)}\n"
        if update.md5:
            message += f"MD5: {update.md5}\n"
        message += f"\nFull Update: {update.link}\n"
        # incremental update
        if update.method == "Recovery":
            incremental = get_incremental(update.version)
            if incremental:
                message += f"\nIncremental Update: {incremental.link}\n"
        if update.changelog != "Bug fixes and system optimizations.":
            message += f"\nChangelog:\n{update.changelog}\n"
        message += f"\n#MIUI_Updates #Xiaomi #MIUI #{get_device_name(update.codename).replace(' ', '')}"
        if update.version.startswith("V"):
            message += f" #MIUI{update.version.split('V')[1].split('.')[0]}"
        message += f" #Android{update.android.split('.')[0]}"
        return message, link
github furlongm / openvpn-monitor / openvpn-monitor.py View on Github external
if 'country' in session and session['country'] is not None:
                    country = session['country']
                    full_location = country
                if 'region' in session and session['region'] is not None:
                    region = session['region']
                    full_location = '{0!s}, {1!s}'.format(region, full_location)
                if 'city' in session and session['city'] is not None:
                    city = session['city']
                    full_location = '{0!s}, {1!s}'.format(city, full_location)
                output('<img alt="{1!s}" title="{1!s}" src="{0!s}"> '.format(flag, full_location))
                output('{0!s}'.format(full_location))
        else:
            output('Unknown')

        output('{0!s} ({1!s})'.format(bytes_recv, naturalsize(bytes_recv, binary=True)))
        output('{0!s} ({1!s})'.format(bytes_sent, naturalsize(bytes_sent, binary=True)))
        output('{0!s}'.format(
            session['connected_since'].strftime(self.datetime_format)))
        if 'last_seen' in session:
            output('{0!s}'.format(
                session['last_seen'].strftime(self.datetime_format)))
        else:
            output('ERROR')
        output('{0!s}'.format(total_time))
        if show_disconnect:
            output('<form method="post">')
            output('<input value="{0!s}" name="vpn_id" type="hidden">'.format(vpn_id))
            if 'port' in session:
                output('<input value="{0!s}" name="ip" type="hidden">'.format(session['remote_ip']))
                output('<input value="{0!s}" name="port" type="hidden">'.format(session['port']))
            if 'client_id' in session:
                output('<input value="{0!s}" name="client_id" type="hidden">'.format(session['client_id']))</form>
github osm2vectortiles / osm2vectortiles / src / merge-jobs / merge-jobs.py View on Github external
def download_mbtiles(download_url):
    """Download MBTiles specified in message and return local filepath"""
    merge_source = os.path.basename(download_url)
    urlretrieve(download_url, merge_source)

    if not os.path.isfile(merge_source):
        raise ValueError('File {} does not exist'.format(merge_source))

    merge_source_size = os.path.getsize(merge_source)
    print('Download {} ({})'.format(
        download_url,
        humanize.naturalsize(merge_source_size))
    )
    return merge_source
github albanie / collaborative-experts / utils / util.py View on Github external
def memory_summary():
    vmem = psutil.virtual_memory()
    msg = (
        f">>> Currently using {vmem.percent}% of system memory "
        f"{humanize.naturalsize(vmem.used)}/{humanize.naturalsize(vmem.available)}"
    )
    print(msg)
github tskit-dev / tsinfer / tsinfer / cli.py View on Github external
def summarise_usage():
    wall_time = humanize.naturaldelta(time.time() - __before)
    user_time = humanize.naturaldelta(os.times().user)
    sys_time = os.times().system
    if resource is None:
        # Don't report max memory on Windows. We could do this using the psutil lib, via
        # psutil.Process(os.getpid()).get_ext_memory_info().peak_wset if demand exists
        maxmem_str = ""
    else:
        max_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        if sys.platform != "darwin":
            max_mem *= 1024  # Linux and other OSs (e.g. freeBSD) report maxrss in kb
        maxmem_str = "; max memory={}".format(
            humanize.naturalsize(max_mem, binary=True)
        )
    logger.info("wall time = {}".format(wall_time))
    logger.info("rusage: user={}; sys={:.2f}s".format(user_time, sys_time) + maxmem_str)
github Prodiguer / synda / sdt / bin / sdinstall.py View on Github external
# what to do if no match
    if count_new&lt;1:

        if count_total&gt;0:
            sdlog.info("SYNDINST-027","Nothing to install (matching files are already installed or waiting in the download queue). To monitor transfers status and progress, use 'synda queue' command.",stderr=interactive)
        else:
            sdlog.info("SYNDINST-028",'Nothing to install (0 file found).',stderr=interactive)

        return (0,0)

    # ask user for confirmation
    if interactive:
        import humanize
        print_stderr('%i file(s) will be added to the download queue.'%count_new)
        print_stderr('Once downloaded, %s of additional disk space will be used.'%humanize.naturalsize(size_new,gnu=False))

        import sdutils
        if sdutils.query_yes_no('Do you want to continue?', default="yes"):
            installation_confirmed=True
        else:
            installation_confirmed=False
    else:
        installation_confirmed=True

    sdlog.info("SYNDINST-002","Store metadata in database..")

    # install
    if installation_confirmed:
        import sdenqueue
        sdenqueue.run(metadata,timestamp_right_boundary)
github terbo / sigmon / app / sigmon.py View on Github external
def commify(num):
  if not num:
    return
  if num &lt; 8000:
    return humanize.intcomma(num)
  
  return humanize.naturalsize(num,gnu=True,format='%.2f')