[Git][NTPsec/ntpsec][wip-ntpq-peers-display] 3 commits: Fixed float handling, again. Scaled floats now rounded to base unit.

Ian Bruene gitlab at mg.gitlab.com
Thu Mar 30 21:07:00 UTC 2017


Ian Bruene pushed to branch wip-ntpq-peers-display at NTPsec / ntpsec


Commits:
e1e2b664 by Ian Bruene at 2017-03-30T15:57:16-05:00
Fixed float handling, again. Scaled floats now rounded to base unit.

99 buggy floats in the code.. fix one, pass the source around..

98 buggy floats in the code..

- - - - -
9ca47478 by Ian Bruene at 2017-03-30T16:00:21-05:00
ntpmon now works with units.

ntpmon has been updated to use the new unit handling code.

ntpmon responds to -u and --units.

- - - - -
ae964441 by Ian Bruene at 2017-03-30T16:06:37-05:00
Updated ntpmon docs.

- - - - -


3 changed files:

- docs/includes/ntpmon-body.txt
- ntpclients/ntpmon
- pylib/util.py


Changes:

=====================================
docs/includes/ntpmon-body.txt
=====================================
--- a/docs/includes/ntpmon-body.txt
+++ b/docs/includes/ntpmon-body.txt
@@ -81,6 +81,8 @@ x:: Cleanly terminate the program.
 
 == Options ==
 
+-u:: Show units
+
 -V:: Display version and exit.
 
 == Known Bugs ==


=====================================
ntpclients/ntpmon
=====================================
--- a/ntpclients/ntpmon
+++ b/ntpclients/ntpmon
@@ -71,17 +71,6 @@ def statline(_peerlist, _mrulist, nyquist):
     return leader + spacer + trailer
 
 
-def filtcooker(data):
-    "Cooks the string of space seperated numbers with units"
-    parts = data.split()
-    cooked = []
-    for part in parts:
-        part = float(part)
-        cooked.append(ntp.util.f8unit(part, ntp.util.UNIT_MS))
-    rendered = "".join(cooked)
-    return rendered
-
-
 def peer_detail(variables, showunits=False):
     "Show the things a peer summary doesn't, cooked slightly differently"
     # All of an rv display except refid, reach, delay, offset, jitter.
@@ -99,15 +88,19 @@ def peer_detail(variables, showunits=False):
     if showunits:
         for name in ntp.util.MS_VARS:
             if name in vcopy:
-                vcopy[name] = ntp.util.f8unit(vcopy[name],
-                                              ntp.util.UNIT_MS,
-                                              True)
+                vcopy[name] = ntp.util.unitformatter(vcopy[name],
+                                                     ntp.util.UNITS_SEC,
+                                                     ntp.util.UNIT_MS,
+                                                     strip=True)
         for name in ntp.util.PPM_VARS:
             if name in vcopy:
-                vcopy[name] = ntp.util.ppmformathack(vcopy[name], True)
-        vcopy['filtdelay'] = filtcooker(vcopy['filtdelay'])
-        vcopy['filtoffset'] = filtcooker(vcopy['filtoffset'])
-        vcopy['filtdisp'] = filtcooker(vcopy['filtdisp'])
+                vcopy[name] = ntp.util.unitformatter(vcopy[name],
+                                                     ntp.util.UNIT_PPM,
+                                                     ntp.util.UNITS_PPX,
+                                                     strip=True)
+        vcopy['filtdelay'] = ntp.util.filtcooker(vcopy['filtdelay'])
+        vcopy['filtoffset'] = ntp.util.filtcooker(vcopy['filtoffset'])
+        vcopy['filtdisp'] = ntp.util.filtcooker(vcopy['filtdisp'])
     else:
         vcopy['filtdelay'] = vcopy['filtdelay'].replace(' ', '\t')
         vcopy['filtoffset'] = vcopy['filtoffset'].replace(' ', '\t')
@@ -162,7 +155,7 @@ USAGE: ntpmon [-V] [host]
 if __name__ == '__main__':
     try:
         (options, arguments) = getopt.getopt(sys.argv[1:],
-                                             "V", ["version"])
+                                             "Vu", ["version", "units"])
     except getopt.GetoptError as e:
         sys.stderr.write("%s\n" % e)
         sys.stderr.write(usage)
@@ -180,6 +173,8 @@ if __name__ == '__main__':
         if switch in ("-V", "--version"):
             print("ntpmon %s" % ntp.util.stdversion())
             raise SystemExit(0)
+        elif switch in ("-u", "--units"):
+            showunits = True
 
     poll_interval = 1
     helpmode = selectmode = detailmode = False


=====================================
pylib/util.py
=====================================
--- a/pylib/util.py
+++ b/pylib/util.py
@@ -40,10 +40,11 @@ UNIT_MS = 2
 UNIT_S = 3
 UNIT_KS = 4
 UNITS_SEC = ["ns", "us", "ms", "s", "ks"]
-UNIT_PPB = 0
-UNIT_PPM = 1
-UNIT_PPT = 2
-UNITS_PPX = ["ppb", "ppm", "ppt"]
+UNIT_PPT = 0
+UNIT_PPB = 1
+UNIT_PPM = 2
+UNIT_PPT = 3
+UNITS_PPX = ["ppt", "ppb", "ppm", "ppt"]
 
 
 # Variables that have units
@@ -112,8 +113,10 @@ def filtcooker(data):
     # Shift all values to the new unit
     cooked = []
     for part in floatyparts:
+        # The scaled values aren't being saved for the formatter <<<<<<<<<
+        part = rescaleunit(part, mostcommon)
         fmt = formatdigitsplit(part, 7)
-        temp = fmt % rescaleunit(part, mostcommon)
+        temp = fmt % part
         cooked.append(temp)
     rendered = " ".join(cooked) + " " + UNITS_SEC[newunit]
     return rendered
@@ -148,15 +151,17 @@ def scaleforunit(f):
 
 def formatdigitsplit(f, fieldsize):
     "Create a format string for a float without adding fake precision."
-    if f.is_integer():  # This also catches f == 0.0
-        return "%" + str(fieldsize) + "d"
     af = abs(f)
+    if f.is_integer() or (af < timefuzz):
+        return "%" + str(fieldsize) + "d"
     if af >= 100.0:
         maxdigits = fieldsize - 4  # xxx.
     elif af >= 10.0:
         maxdigits = fieldsize - 3  # xx.
     elif af >= 1.0:
         maxdigits = fieldsize - 2  # x.
+    else:  # Yes, this can happen with filts
+        maxdigits = fieldsize - 2  # 0.
     if f < 0.0:
         maxdigits -= 1  # need to fit a negative symbol
     sig = len(str(f).split(".")[1])  # count digits after the decimal point
@@ -165,6 +170,10 @@ def formatdigitsplit(f, fieldsize):
     return formatter
 
 
+def oomsbetweenunits(a, b):
+    return abs((a - b) * 3)
+
+
 def unitformatter(f, unitgroup, startingunit, baseunit=None,
                   strip=False, width=8):
     "Formatting for unit associated values in N characters."
@@ -180,21 +189,32 @@ def unitformatter(f, unitgroup, startingunit, baseunit=None,
         if not strip:
             rendered = padder(rendered)
         return rendered
-    oldf = f
+    oldf = f  # keep this in case we don't fit in the units
     f, unitsmoved = scaleforunit(f)
     unitget = startingunit + unitsmoved
+    rounddigits = oomsbetweenunits(unitget, baseunit)
+    f = round(f, rounddigits)
     if (0 <= unitget < len(unitgroup)):
         unit = unitgroup[unitget]
-        if width is None:
-            rendered = repr(f) + unit
+        if width is None:  # Don't care about size, just display everything
+            if unitget == baseunit:  # Don't want fake decimals
+                formatter = "%d"
+                rendered = (formatter % f) + unit
+            else:
+                rendered = repr(f) + unit
+            if strip:
+                rendered = rendered.strip()
+            return rendered
+        else:  # Do care about size, crop value so it will fit
+            displaysize = width - len(unit)
+            if unitget == baseunit:  # Don't want fake decimals
+                formatter = "%" + str(displaysize) + "d"
+            else:
+                formatter = formatdigitsplit(f, displaysize)
+            rendered = (formatter % f) + unit
+            if strip:
+                rendered = rendered.strip()
             return rendered
-        displaysize = width - len(unit)
-        # Ok, not zero, and in unit range. Can finally format
-        formatter = formatdigitsplit(f, displaysize)
-        rendered = (formatter % f) + unit
-        if strip:
-            rendered = rendered.strip()
-        return rendered
     else:  # Out of units so revert to the original. Ugly but there are very
         rendered = repr(oldf) + unitgroup[startingunit]  # few options here
         if not strip:



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/compare/472f1b3761f863e7d4ef2c0e080fba97610de62b...ae9644413de2e3f70f8fc834a0d1618936b568f6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20170330/964bcc64/attachment.html>


More information about the vc mailing list