[chirp_devel] [PATCH 00/22] Got Style?

This series of patches address the style issues in all of the Python files except for the radio drivers. All of them are trivial patches, as 99% of the changes are adjusting whitespace in one form or another. I did introduce temporary variables here or there or rewrite a lambda to a def, but I double-checked those spots carefully (and all tests pass).
The most notable change is the first patch to allow exceptions, as some allowance was needed in a few files.
Zach Welch (22): Allow cpep8.py script to make exceptions (#2355) Fix style issues in run_tests (#2355) Fix style issues in unit tests (#2355) Fix style issues in csvdump scripts (#2355) Fix style issues in make_supported.py (#2355) Fix style issues in chirp_common.py (#2355) Fix style issues in bitwise.py (#2355) Fix style issues in settings.py (#2355) Fix style issues in elib_intl.py (#2355) Fix style issues in pyPEG.py (#2355) Fix style issues in bandplans (#2355) Fix style issues in chirp module (#2355) Fix style issues in common.py (#2355) Fix style issues in editorset.py (#2355) Fix style issues in importdialog.py (#2355) Fix style issues in mainapp.py (#2355) Fix style issues in memdetail.py (#2355) Fix style issues in memedit.py (#2355) Fix style issues in miscwidgits.py (#2355) Fix style issues in reporting.py (#2355) Fix style issues in fips.py (#2355) Fix style issues in tools (#2355)
chirp/__init__.py | 4 +- chirp/bandplan_au.py | 5 +- chirp/bandplan_iaru_r1.py | 19 +- chirp/bandplan_na.py | 25 +- chirp/bitwise.py | 145 +++++----- chirp/chirp_common.py | 270 ++++++++++-------- chirp/elib_intl.py | 575 ++++++++++++++++++++------------------- chirp/pyPEG.py | 127 ++++++--- chirp/settings.py | 46 ++-- chirpui/common.py | 53 ++-- chirpui/editorset.py | 46 ++-- chirpui/fips.py | 373 +++++++++++++------------ chirpui/importdialog.py | 92 ++++--- chirpui/mainapp.py | 303 ++++++++++++--------- chirpui/memdetail.py | 114 ++++---- chirpui/memedit.py | 284 ++++++++++--------- chirpui/miscwidgets.py | 104 +++---- chirpui/reporting.py | 22 +- csvdump/csvapp.py | 36 +-- csvdump/csvdump.py | 55 ++-- share/make_supported.py | 25 +- tests/run_tests | 173 +++++++----- tests/unit/test_import_logic.py | 11 +- tests/unit/test_memedit_edits.py | 11 +- tests/unit/test_settings.py | 7 +- tools/bitdiff.py | 171 +++++++----- tools/cpep8.blacklist | 29 -- tools/cpep8.exceptions | 7 + tools/cpep8.py | 40 ++- tools/img2thd72.py | 36 +-- 30 files changed, 1776 insertions(+), 1432 deletions(-) create mode 100644 tools/cpep8.exceptions

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 13e436ae19e0b0ac7a0a9646247e4306216f4707
Allow cpep8.py script to make exceptions (#2355)
This patch enhances the cpep8.py script with the ability to ignore a list of style rules on per-file basis. There are cases where it may be too disruptive to eliminate all style issues, so this mechanism allows the style checker to enforce the remainder of the style rules. The new --strict option will cause the script to ignore the exception list.
As a bonus, this change improves interactivity, so --verbose will cause the name of the file to be printed as it is checked (rather than printing one long list before it started). The downside: the pep8 module catches KeyboardInterrpt, so it's hard impossible to stop once it gets started.
diff --git a/tools/cpep8.exceptions b/tools/cpep8.exceptions new file mode 100644 index 0000000..6fcce63 --- /dev/null +++ b/tools/cpep8.exceptions @@ -0,0 +1,4 @@ +# This file contains a list of per-file exceptions to the pep8 style rules +# Each line must contain the file name, a tab, and a comma-separated list +# of style rules to ignore in that file. This mechanism should be used +# sparingly and as a measure of last resort. diff --git a/tools/cpep8.py b/tools/cpep8.py index db33ab1..fb1ff48 100755 --- a/tools/cpep8.py +++ b/tools/cpep8.py @@ -30,6 +30,8 @@ parser.add_argument("-d", "--dir", action="store", default=".", help="Root directory of source tree") parser.add_argument("-s", "--stats", action="store_true", help="Only show statistics") +parser.add_argument("--strict", action="store_true", + help="Ignore listed exceptions") parser.add_argument("-S", "--scan", action="store_true", help="Scan for additional files") parser.add_argument("-u", "--update", action="store_true", @@ -52,6 +54,7 @@ def file_to_lines(name): scriptdir = os.path.dirname(sys.argv[0]) manifest_filename = os.path.join(scriptdir, "cpep8.manifest") blacklist_filename = os.path.join(scriptdir, "cpep8.blacklist") +exceptions_filename = os.path.join(scriptdir, "cpep8.exceptions")
manifest = [] if args.scan: @@ -68,10 +71,28 @@ if args.scan: else: manifest += file_to_lines(manifest_filename)
+ +# unless we are being --strict, load per-file style exceptions +exceptions = {} +if not args.strict: + exception_lines = file_to_lines(exceptions_filename) + exception_lists = [x.split('\t') + for x in exception_lines if not x.startswith('#')] + for filename, codes in exception_lists: + exceptions[filename] = codes + + +def get_exceptions(f): + try: + ignore = exceptions[f] + except KeyError: + ignore = None + return ignore + if args.update: bad = [] for f in manifest: - checker = pep8.StyleGuide(quiet=True) + checker = pep8.StyleGuide(quiet=True, ignore=get_exceptions(f)) results = checker.check_files([f]) if results.total_errors: bad.append(f) @@ -100,12 +121,15 @@ for f in manifest: check_list.append(f) check_list = sorted(check_list)
-if args.verbose: - print "Checking the following files:\n", "\n".join(check_list) +total_errors = 0 +for f in check_list: + if args.verbose: + print "Checking %s" % f
-checker = pep8.StyleGuide(quiet=args.stats) -results = checker.check_files(check_list) -if args.stats: - results.print_statistics() + checker = pep8.Checker(f, quiet=args.stats, ignore=get_exceptions(f)) + results = checker.check_all() + if args.stats: + checker.report.print_statistics() + total_errors += results
-sys.exit(results.total_errors and 1 or 0) +sys.exit(total_errors and 1 or 0)

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 7ff534747894b9ed3fa356ae9c724a4eac01e471
Fix style issues in run_tests (#2355)
The run_tests script contains logic to set the path for importing the chirp modules. This violates the style rule that all module-level imports must be at the top of the file, so I added it as an exception for this file.
diff --git a/tests/run_tests b/tests/run_tests index c6d801e..7edeecc 100755 --- a/tests/run_tests +++ b/tests/run_tests @@ -15,7 +15,13 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/.
-import traceback, sys, os, shutil, glob, tempfile, time +import traceback +import sys +import os +import shutil +import glob +import tempfile +import time from optparse import OptionParser from serial import Serial
@@ -27,20 +33,23 @@ sys.path.insert(0, "../")
from chirp import CHIRP_VERSION from chirp import * -from chirp import chirp_common, directory, generic_csv, import_logic, memmap, settings -from chirp import errors +from chirp import chirp_common, directory, generic_csv +from chirp import import_logic, memmap, settings, errors
TESTS = {}
time.sleep = lambda s: None
+ class TestError(Exception): def get_detail(self): return str(self)
+ class TestInternalError(TestError): pass
+ class TestCrashError(TestError): def __init__(self, tb, exc, args): Exception.__init__(self, str(exc)) @@ -58,10 +67,10 @@ class TestCrashError(TestError): self.__tb + os.linesep + \ "Called from:" + os.linesep + self.__mytb
- def get_original_exception(self): return self.__exc
+ class TestFailedError(TestError): def __init__(self, msg, detail=""): TestError.__init__(self, msg) @@ -70,12 +79,15 @@ class TestFailedError(TestError): def get_detail(self): return self._detail
+ class TestSkippedError(TestError): pass
+ def get_tb(): return traceback.format_exc()
+ class TestWrapper: def __init__(self, dstclass, filename): self._ignored_exceptions = [] @@ -120,8 +132,8 @@ class TestWrapper: for arg in args: if isinstance(arg, chirp_common.Memory): details += os.linesep + \ - os.linesep.join(["%s:%s" % (k,v) \ - for k,v in arg.__dict__.items()]) + os.linesep.join(["%s:%s" % (k, v) for k, v + in arg.__dict__.items()]) raise TestCrashError(get_tb(), e, details)
if self._make_reload: @@ -140,6 +152,7 @@ class TestWrapper: def get_radio(self): return self._dst
+ class TestCase: def __init__(self, wrapper): self._wrapper = wrapper @@ -162,12 +175,12 @@ class TestCase:
for k, v in a.__dict__.items(): if k == "power": - continue # FIXME + continue # FIXME elif k == "immutable": continue elif k == "name": if not rf.has_name: - continue # Don't complain about name, if not supported + continue # Don't complain about name, if not supported else: # Name mismatch fair if filter_name() is right v = self._wrapper.do("filter_name", v).rstrip() @@ -177,24 +190,24 @@ class TestCase: a.tmode == "Tone" or (a.tmode == "TSQL" and not rf.has_ctone) or (a.tmode == "Cross" and tx_mode == "Tone") or - (a.tmode == "Cross" and rx_mode == "Tone" and not rf.has_ctone) + (a.tmode == "Cross" and rx_mode == "Tone" and + not rf.has_ctone) ): continue elif k == "ctone" and (not rf.has_ctone or - not ( - a.tmode == "TSQL" or - (a.tmode == "Cross" and rx_mode == "Tone") - ) - ): + not (a.tmode == "TSQL" or + (a.tmode == "Cross" and + rx_mode == "Tone"))): continue elif k == "dtcs" and not ( - (a.tmode == "DTCS" and not rf.has_rx_dtcs) or - (a.tmode == "Cross" and tx_mode == "DTCS") or - (a.tmode == "Cross" and rx_mode == "DTCS" and not rf.has_rx_dtcs) - ): + (a.tmode == "DTCS" and not rf.has_rx_dtcs) or + (a.tmode == "Cross" and tx_mode == "DTCS") or + (a.tmode == "Cross" and rx_mode == "DTCS" and + not rf.has_rx_dtcs)): continue elif k == "rx_dtcs" and (not rf.has_rx_dtcs or - not (a.tmode == "Cross" and rx_mode == "DTCS")): + not (a.tmode == "Cross" and + rx_mode == "DTCS")): continue elif k == "offset" and not a.duplex: continue @@ -209,17 +222,18 @@ class TestCase:
details = msg details += os.linesep + "### Wanted:" + os.linesep - details += os.linesep.join(["%s:%s" % (k,v) for k,v in \ - a.__dict__.items()]) + details += os.linesep.join(["%s:%s" % (k, v) for k, v + in a.__dict__.items()]) details += os.linesep + "### Got:" + os.linesep - details += os.linesep.join(["%s:%s" % (k,v) for k,v in \ - b.__dict__.items()]) + details += os.linesep.join(["%s:%s" % (k, v) for k, v + in b.__dict__.items()]) raise TestFailedError(msg, details) except KeyError, e: print sorted(a.__dict__.keys()) print sorted(b.__dict__.keys()) raise
+ class TestCaseCopyAll(TestCase): "Copy Memories From CSV"
@@ -245,9 +259,9 @@ class TestCaseCopyAll(TestCase):
try: dst_mem = import_logic.import_mem(self._wrapper.get_radio(), - src_rf, - src_mem, - overrides={"number":dst_number}) + src_rf, src_mem, + overrides={ + "number": dst_number}) import_logic.import_bank(self._wrapper.get_radio(), self._src, dst_mem, @@ -255,8 +269,8 @@ class TestCaseCopyAll(TestCase): except import_logic.DestNotCompatible: continue except import_logic.ImportError, e: - failures.append(TestFailedError("<%i>: Import Failed: %s" %\ - (dst_number, e))) + failures.append(TestFailedError("<%i>: Import Failed: %s" % + (dst_number, e))) continue except Exception, e: raise TestCrashError(get_tb(), e, "[Import]") @@ -267,11 +281,13 @@ class TestCaseCopyAll(TestCase): try: self.compare_mem(dst_mem, ret_mem) except TestFailedError, e: - failures.append(TestFailedError("<%i>: %s" % (number, e), e.get_detail())) + failures.append( + TestFailedError("<%i>: %s" % (number, e), e.get_detail()))
return failures TESTS["CopyAll"] = TestCaseCopyAll
+ class TestCaseBruteForce(TestCase): def __str__(self): return "BruteForce" @@ -281,7 +297,9 @@ class TestCaseBruteForce(TestCase): if msgs:
raise TestFailedError("Radio did not validate a valid memory", - os.linesep.join(["%s:%s" % (k,v) for k,v in m.__dict__.items()]) + os.linesep + os.linesep.join(msgs)) + os.linesep.join(["%s:%s" % (k, v) for k, v + in m.__dict__.items()]) + + os.linesep + os.linesep.join(msgs))
self._wrapper.do("set_memory", m) ret_m = self._wrapper.do("get_memory", m.number) @@ -289,7 +307,8 @@ class TestCaseBruteForce(TestCase): # Damned Baofeng radios don't seem to properly store # shift and direction, so be gracious here if m.duplex == "split" and ret_m.duplex in ["-", "+"]: - ret_m.offset = ret_m.freq + (ret_m.offset * int(ret_m.duplex + "1")) + ret_m.offset = ret_m.freq + \ + (ret_m.offset * int(ret_m.duplex + "1")) ret_m.duplex = "split"
self.compare_mem(m, ret_m) @@ -301,7 +320,7 @@ class TestCaseBruteForce(TestCase): if tmode not in chirp_common.TONE_MODES: continue elif tmode in ["DTCS", "DTCS-R", "Cross"]: - continue # We'll test DCS and Cross tones separately + continue # We'll test DCS and Cross tones separately
m.tmode = tmode if tmode == "": @@ -413,6 +432,7 @@ class TestCaseBruteForce(TestCase):
def run(self): rf = self._wrapper.do("get_features") + def clean_mem(): m = chirp_common.Memory() m.number = rf.memory_bounds[0] @@ -444,6 +464,7 @@ class TestCaseBruteForce(TestCase): return [] TESTS["BruteForce"] = TestCaseBruteForce
+ class TestCaseEdges(TestCase): def __str__(self): return "Edges" @@ -458,7 +479,7 @@ class TestCaseEdges(TestCase):
def do_longname(self, rf): m = self._mem(rf) - m.name = ("X" * 256) # Should be longer than any radio can handle + m.name = ("X" * 256) # Should be longer than any radio can handle m.name = self._wrapper.do("filter_name", m.name)
self._wrapper.do("set_memory", m) @@ -489,9 +510,9 @@ class TestCaseEdges(TestCase):
def do_oddsteps(self, rf): odd_steps = { - 145 : [145.85625, 145.86250], - 445 : [445.85625, 445.86250], - 862 : [862.73125, 862.73750], + 145: [145.85625, 145.86250], + 445: [445.85625, 445.86250], + 862: [862.73125, 862.73750], }
m = self._mem(rf) @@ -510,7 +531,6 @@ class TestCaseEdges(TestCase): n = self._wrapper.do("get_memory", m.number) self.compare_mem(m, n)
- def run(self): rf = self._wrapper.do("get_features")
@@ -526,6 +546,7 @@ class TestCaseEdges(TestCase):
TESTS["Edges"] = TestCaseEdges
+ class TestCaseSettings(TestCase): def __str__(self): return "Settings" @@ -606,9 +627,8 @@ class TestCaseBanks(TestCase): # Truncation is allowed, but not failure if not testname.lower().startswith(str(newbanks[i]).lower()): raise TestFailedError("Bank names not properly truncated", - "Tried: %s on %i\nGot: %s" % (testname, - i, - newbanks[i])) + "Tried: %s on %i\nGot: %s" % + (testname, i, newbanks[i]))
def do_bank_names_no_trailing_whitespace(self, rf): banks, newbanks = self._do_bank_names(rf, "foo ") @@ -635,9 +655,8 @@ class TestCaseBanks(TestCase):
mem_banks = model.get_memory_mappings(mem) if len(mem_banks) != 0: - raise TestFailedError("Freshly-created memory has banks and " +\ - "should not", - "Banks: %s" % str(mem_banks)) + raise TestFailedError("Freshly-created memory has banks and " + + "should not", "Banks: %s" % str(mem_banks))
banks = model.get_mappings()
@@ -654,10 +673,10 @@ class TestCaseBanks(TestCase): reason = verify(banks[0]) if reason is not None: raise TestFailedError("Setting memory bank does not persist", - "%s\nMemory banks:%s\nBank memories:%s" %\ - (reason, - model.get_memory_mappings(mem), - model.get_mapping_memories(banks[0]))) + "%s\nMemory banks:%s\nBank memories:%s" % + (reason, + model.get_memory_mappings(mem), + model.get_mapping_memories(banks[0])))
model.remove_memory_from_mapping(mem, banks[0]) reason = verify(banks[0]) @@ -672,8 +691,8 @@ class TestCaseBanks(TestCase): did_error = True
if not did_error: - raise TestFailedError("Removing memory from non-member bank " +\ - "did not raise Exception") + raise TestFailedError("Removing memory from non-member bank " + + "did not raise Exception")
def do_bank_index(self, rf): if not rf.has_bank_index: @@ -697,7 +716,7 @@ class TestCaseBanks(TestCase): raise TestFailedError("Bank index not persisted")
suggested_index = model.get_next_mapping_index(banks[0]) - if suggested_index not in range(*index_bounds): + if suggested_index not in range(*index_bounds): raise TestFailedError("Suggested bank index not in valid range", "Got %i, range is %s" % (suggested_index, index_bounds)) @@ -712,13 +731,15 @@ class TestCaseBanks(TestCase): self.do_bank_names_toolong(rf) self.do_bank_names_no_trailing_whitespace(rf) self.do_bank_store(rf) - self.do_bank_store(rf) # Again to make sure we clear bank info on delete + # Again to make sure we clear bank info on delete + self.do_bank_store(rf) self.do_bank_index(rf)
return []
TESTS["Banks"] = TestCaseBanks
+ class TestCaseDetect(TestCase): def __str__(self): return "Detect" @@ -737,31 +758,37 @@ class TestCaseDetect(TestCase): if issubclass(self._wrapper._dstclass, radio.__class__): pass elif radio.__class__ != self._wrapper._dstclass: - raise TestFailedError("%s detected as %s" % \ - (self._wrapper._dstclass, - radio.__class__)) + raise TestFailedError("%s detected as %s" % + (self._wrapper._dstclass, radio.__class__)) return []
TESTS["Detect"] = TestCaseDetect
+ class TestCaseClone(TestCase): class SerialNone: def read(self, size): return "" + def write(self, data): pass + def setBaudrate(self, rate): pass + def setTimeout(self, timeout): pass + def setParity(self, parity): pass + def __str__(self): - return self.__class__.__name__.replace("Serial","") + return self.__class__.__name__.replace("Serial", "")
class SerialError(SerialNone): def read(self, size): raise Exception("Foo") + def write(self, data): raise Exception("Bar")
@@ -797,7 +824,7 @@ class TestCaseClone(TestCase): if not isinstance(error, errors.RadioError): raise TestFailedError("Live radio didn't notice serial " + "was dead on init") - return [] # Nothing more to test on an error'd live radio + return [] # Nothing more to test on an error'd live radio
error = None try: @@ -812,8 +839,9 @@ class TestCaseClone(TestCase): elif not isinstance(error, errors.RadioError): raise TestFailedError("Radio did not raise RadioError " + "with %s data" % serial, - "sync_in() Got: %s (%s)\n%s" % (\ - error.__class__.__name__, error, get_tb())) + "sync_in() Got: %s (%s)\n%s" % + (error.__class__.__name__, + error, get_tb()))
radio._mmap = memmap.MemoryMap("\x00" * (1024 * 128))
@@ -830,8 +858,8 @@ class TestCaseClone(TestCase): elif not isinstance(error, errors.RadioError): raise TestFailedError("Radio did not raise RadioError " + "with %s data" % serial, - "sync_out(): Got: %s (%s)" % (\ - error.__class__.__name__, error)) + "sync_out(): Got: %s (%s)" % + (error.__class__.__name__, error))
return []
@@ -844,11 +872,13 @@ class TestCaseClone(TestCase):
TESTS["Clone"] = TestCaseClone
+ class TestOutput: def __init__(self, output=None): if not output: output = sys.stdout self._out = output + def prepare(self): pass
@@ -865,14 +895,15 @@ class TestOutput: tc, msg, e))
+ class TestOutputANSI(TestOutput): def __init__(self, output=None): TestOutput.__init__(self, output) self.__counts = { - "PASSED" : 0, - "FAILED" : 0, - "CRASHED" : 0, - "SKIPPED" : 0, + "PASSED": 0, + "FAILED": 0, + "CRASHED": 0, + "SKIPPED": 0, } self.__total = 0
@@ -898,9 +929,10 @@ class TestOutputANSI(TestOutput): self._print("-" * 70) self._print("Results:") self._print(" %-7s: %i" % ("TOTAL", self.__total)) - for t,c in self.__counts.items(): + for t, c in self.__counts.items(): self._print(" %-7s: %i" % (t, c))
+ class TestOutputHTML(TestOutput): def __init__(self, filename): self._filename = filename @@ -946,7 +978,8 @@ td.SKIPPED { <h3>Generated on %s (%s)</h3> <table class="testlist"> <tr> - <th>Vendor</th><th>Model</th><th>Test Case</th><th>Status</th><th>Message</th> + <th>Vendor</th><th>Model</th><th>Test Case</th> + <th>Status</th><th>Message</th> </tr> """ % (CHIRP_VERSION, CHIRP_VERSION, time.strftime("%x at %X"), os.name) print >>self._out, s @@ -959,15 +992,17 @@ td.SKIPPED { def report(self, rclass, tc, msg, e): s = ("<tr class='%s'>" % msg) + \ ("<td class='vendor'>%s</td>" % rclass.VENDOR) + \ - ("<td class='model'>%s %s</td>" % (rclass.MODEL, rclass.VARIANT))+\ + ("<td class='model'>%s %s</td>" % + (rclass.MODEL, rclass.VARIANT)) + \ ("<td class='tc'>%s</td>" % tc) + \ - ("<td class='%s'>%s</td>" % (msg,msg)) + \ + ("<td class='%s'>%s</td>" % (msg, msg)) + \ ("<td class='error'>%s</td>" % e) + \ "</tr>" print >>self._out, s sys.stdout.write(".") sys.stdout.flush()
+ class TestRunner: def __init__(self, images_dir, test_list, test_out): self._images_dir = images_dir @@ -1007,7 +1042,7 @@ class TestRunner: nfailed = 0 for tcclass in self._test_list: nprinted = 0 - tw = TestWrapper(rclass,parm) + tw = TestWrapper(rclass, parm) tc = tcclass(tw)
self.nuke_log(rclass, tc) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 5dd6174..1df7274 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -93,7 +93,6 @@ ./csvdump/csvapp.py ./csvdump/csvdump.py ./share/make_supported.py -./tests/run_tests ./tests/unit/test_import_logic.py ./tests/unit/test_memedit_edits.py ./tests/unit/test_settings.py diff --git a/tools/cpep8.exceptions b/tools/cpep8.exceptions index 6fcce63..394634f 100644 --- a/tools/cpep8.exceptions +++ b/tools/cpep8.exceptions @@ -2,3 +2,4 @@ # Each line must contain the file name, a tab, and a comma-separated list # of style rules to ignore in that file. This mechanism should be used # sparingly and as a measure of last resort. +./tests/run_tests E402

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 0769bf2afdf672f5b5b00bfbbba88a5e24f19214
Fix style issues in unit tests (#2355)
The memedit unit tests needed an exception, as that module uses a lambda to fake localization when importing the UI module.
diff --git a/tests/unit/test_import_logic.py b/tests/unit/test_import_logic.py index eff56b5..ecd9aa9 100644 --- a/tests/unit/test_import_logic.py +++ b/tests/unit/test_import_logic.py @@ -3,6 +3,7 @@ from chirp import import_logic from chirp import chirp_common from chirp import errors
+ class FakeRadio(chirp_common.Radio): def __init__(self, arg): self.POWER_LEVELS = list([chirp_common.PowerLevel('lo', watts=5), @@ -26,9 +27,11 @@ class FakeRadio(chirp_common.Radio): rf.has_rx_dtcs = self.HAS_RX_DTCS return rf
+ class FakeDstarRadio(FakeRadio, chirp_common.IcomDstarSupport): pass
+ class DstarTests(base.BaseTest): def _test_ensure_has_calls(self, mem, ini_urcalls, ini_rptcalls, @@ -87,7 +90,7 @@ class DstarTests(base.BaseTest): exp_rptcalls[4] = mem.dv_rpt2call self._test_ensure_has_calls(mem, ini_urcalls, ini_rptcalls, exp_urcalls, exp_rptcalls) - + def test_ensure_has_calls_urcall_full(self): mem = chirp_common.DVMemory() mem.dv_urcall = 'KK7DS' @@ -138,7 +141,8 @@ class DstarTests(base.BaseTest): self._test_ensure_has_calls, mem, ini_urcalls, ini_rptcalls, exp_urcalls, exp_rptcalls) - + + class ImportFieldTests(base.BaseTest): def test_import_name(self): mem = chirp_common.Memory() @@ -164,7 +168,7 @@ class ImportFieldTests(base.BaseTest):
def test_import_power_no_dst(self): radio = FakeRadio(None) - src_rf = radio.get_features() # Steal a copy before we stub out + src_rf = radio.get_features() # Steal a copy before we stub out self.mox.StubOutWithMock(radio, 'get_features') radio.get_features().AndReturn(chirp_common.RadioFeatures()) self.mox.ReplayAll() @@ -244,7 +248,6 @@ class ImportFieldTests(base.BaseTest): import_logic._import_mode(radio, None, mem) self.assertEqual(mem.mode, 'AM')
- def test_import_mode_invalid(self): radio = FakeRadio(None) radio.MODES.remove('AM') diff --git a/tests/unit/test_memedit_edits.py b/tests/unit/test_memedit_edits.py index c717013..decd667 100644 --- a/tests/unit/test_memedit_edits.py +++ b/tests/unit/test_memedit_edits.py @@ -26,17 +26,20 @@ class TestEdits(base.BaseTest): memedit.MemoryEditor.ed_tone_field(editor, None, 'path', None, col)
def _test_auto_tone_mode(self, col, exp_tmode, exp_cmode): + cross_exp_cmode = (exp_tmode == "Cross" and exp_cmode or None) + # No tmode -> expected tmode, maybe requires cross mode change self._test_tone_column_change(col, exp_tmode=exp_tmode, - exp_cmode=(exp_tmode=="Cross" and exp_cmode or None)) + exp_cmode=cross_exp_cmode)
# Expected tmode does not re-set tmode, may change cmode self._test_tone_column_change(col, ini_tmode=exp_tmode, - exp_cmode=(exp_tmode=="Cross" and exp_cmode or None)) + exp_cmode=cross_exp_cmode)
# Invalid tmode -> expected, may change cmode - self._test_tone_column_change(col, ini_tmode="foo", exp_tmode=exp_tmode, - exp_cmode=(exp_tmode=="Cross" and exp_cmode or None)) + self._test_tone_column_change(col, ini_tmode="foo", + exp_tmode=exp_tmode, + exp_cmode=cross_exp_cmode)
# Expected cmode does not re-set cmode self._test_tone_column_change(col, ini_tmode="Cross", diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index e130a95..ccc4308 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -16,6 +16,7 @@ from tests.unit import base from chirp import settings
+ class TestSettingValues(base.BaseTest): def _set_and_test(self, rsv, *values): for value in values: @@ -26,7 +27,7 @@ class TestSettingValues(base.BaseTest): for value in values: self.assertRaises(settings.InvalidValueError, rsv.set_value, value) - + def test_radio_setting_value_integer(self): value = settings.RadioSettingValueInteger(0, 10, 5) self.assertEqual(value.get_value(), 5) @@ -65,6 +66,7 @@ class TestSettingValues(base.BaseTest): pass
value = settings.RadioSettingValueString(0, 5, "foo", autopad=False) + def test_validate(val): if val == "bar": raise TestException() @@ -80,6 +82,7 @@ class TestSettingValues(base.BaseTest): value.set_value(True) self.assertTrue(value.changed())
+ class TestSettingContainers(base.BaseTest): def test_radio_setting_group(self): s1 = settings.RadioSetting("s1", "Setting 1") @@ -97,6 +100,7 @@ class TestSettingContainers(base.BaseTest): self.assertEqual(group.values(), [s1, s2, s3]) self.assertEqual(group.keys(), ["s1", "s2", "s3"]) self.assertEqual([x for x in group], [s1, s2, s3]) + def set_dupe(): group["s3"] = s3 self.assertRaises(KeyError, set_dupe) @@ -125,6 +129,7 @@ class TestSettingContainers(base.BaseTest):
rs = settings.RadioSetting("foo", "Foo") self.assertFalse(rs.has_apply_callback()) + def test_cb(setting, data1, data2): self.assertEqual(setting, rs) self.assertEqual(data1, "foo") diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 1df7274..5cf2b23 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -93,8 +93,5 @@ ./csvdump/csvapp.py ./csvdump/csvdump.py ./share/make_supported.py -./tests/unit/test_import_logic.py -./tests/unit/test_memedit_edits.py -./tests/unit/test_settings.py ./tools/bitdiff.py ./tools/img2thd72.py diff --git a/tools/cpep8.exceptions b/tools/cpep8.exceptions index 394634f..3aafd1d 100644 --- a/tools/cpep8.exceptions +++ b/tools/cpep8.exceptions @@ -3,3 +3,4 @@ # of style rules to ignore in that file. This mechanism should be used # sparingly and as a measure of last resort. ./tests/run_tests E402 +./tests/unit/test_memedit_edits.py E402

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 6abe32d19ca3ba161e896624f4a1ec6b0479d1c7
Fix style issues in csvdump scripts (#2355)
diff --git a/csvdump/csvapp.py b/csvdump/csvapp.py index 2d675cc..aaae614 100644 --- a/csvdump/csvapp.py +++ b/csvdump/csvapp.py @@ -24,19 +24,19 @@ import os import csvdump from chirpui import inputdialog, cloneprog
-gobject.threads_init() - import chirp from chirp import ic9x, id800, ic2820, ic2200, errors - from chirp import platform
-RADIOS = { "ic9x:A": ic9x.IC9xRadioA, - "ic9x:B": ic9x.IC9xRadioB, - "id800" : id800.ID800v2Radio, - "ic2820": ic2820.IC2820Radio, - "ic2200": ic2200.IC2200Radio, -} +gobject.threads_init() + +RADIOS = {"ic9x:A": ic9x.IC9xRadioA, + "ic9x:B": ic9x.IC9xRadioB, + "id800": id800.ID800v2Radio, + "ic2820": ic2820.IC2820Radio, + "ic2200": ic2200.IC2200Radio, + } +
class CsvDumpApp: def update_status(self, s): @@ -57,7 +57,7 @@ class CsvDumpApp:
print "Sync done, saving to: %s" % fn radio.save_mmap(fn) - + self.refresh_radio() except serial.SerialException, e: gobject.idle_add(self.mainwin.set_status, @@ -107,7 +107,7 @@ class CsvDumpApp: def upload_img(self): t = threading.Thread(target=self._upload_img) t.start() - + def _export_file_mmap(self, fname): count = 0
@@ -173,7 +173,6 @@ class CsvDumpApp: return low, high else: return None, None -
def export_file(self, fname): if not fname.lower().endswith(".csv"): @@ -185,7 +184,7 @@ class CsvDumpApp: return
t = threading.Thread(target=self._export_file_live, - args=(fname,l,h)) + args=(fname, l, h)) t.start() else: self._export_file_mmap(fname) @@ -200,7 +199,7 @@ class CsvDumpApp: except Exception, e: print "Failed to parse `%s': %s" % (line, e) return None - + return m
def _import_file_live(self, fname): @@ -226,7 +225,7 @@ class CsvDumpApp: continue except Exception, e: print "Parse error on line %i: %s" % (lineno, e) - break # FIXME: Report error here + break # FIXME: Report error here
lineno += 1 memories.append(m) @@ -242,7 +241,7 @@ class CsvDumpApp: # try: # self.radio.get_memory(m.number, 2) # except errors.InvalidMemoryLocation: -# m +# m
try: self.radio.set_memory(m) @@ -333,7 +332,7 @@ class CsvDumpApp: self.rtype = radio self.rport = port self.refresh_radio() - + def __init__(self): self.mainwin = csvdump.CsvDumpWindow(self.select_radio, self.download_img, @@ -344,7 +343,7 @@ class CsvDumpApp: self.progwin = cloneprog.CloneProg() self.progwin.set_transient_for(self.mainwin) self.progwin.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG) - + self.radio = None
def run(self): @@ -353,6 +352,7 @@ class CsvDumpApp:
gtk.main()
+ if __name__ == "__main__": a = CsvDumpApp() a.run() diff --git a/csvdump/csvdump.py b/csvdump/csvdump.py index 3b1f550..048cac9 100644 --- a/csvdump/csvdump.py +++ b/csvdump/csvdump.py @@ -19,7 +19,8 @@ import gtk
from chirp import platform
-RADIOS = [ "ic2820", "id800", "ic9x:A", "ic9x:B", "ic2200" ] +RADIOS = ["ic2820", "id800", "ic9x:A", "ic9x:B", "ic2200"] +
def make_choice(options, editable=True, default=None): if editable: @@ -39,12 +40,14 @@ def make_choice(options, editable=True, default=None):
return sel
+ class StdButton(gtk.Button): def __init__(self, *args): gtk.Button.__init__(self, *args)
self.set_size_request(75, 25)
+ class CsvDumpWindow(gtk.Window): def set_image_info(self, canUpload, canCsv, info): self.w_imginfo.set_text(info) @@ -66,16 +69,16 @@ class CsvDumpWindow(gtk.Window):
hbox = gtk.HBox(False, 2) hbox.set_border_width(2) - + self.w_radio = make_choice(RADIOS, False, RADIOS[0]) self.w_radio.connect("changed", self.select_radio) self.tips.set_tip(self.w_radio, "Select radio model") self.w_radio.show() - hbox.pack_start(self.w_radio, 1,1,1) + hbox.pack_start(self.w_radio, 1, , )
l = gtk.Label(" on port ") l.show() - hbox.pack_start(l, 0,0,0) + hbox.pack_start(l, 0, , )
ports = platform.get_platform().list_serial_ports() if len(ports) > 0: @@ -86,7 +89,7 @@ class CsvDumpWindow(gtk.Window): self.w_port.connect("changed", self.select_radio) self.tips.set_tip(self.w_port, "Select serial port") self.w_port.show() - hbox.pack_start(self.w_port, 1,1,1) + hbox.pack_start(self.w_port, 1, , )
f.add(hbox) hbox.show() @@ -102,7 +105,7 @@ class CsvDumpWindow(gtk.Window):
self.w_imginfo = gtk.Label("No image") self.w_imginfo.show() - vbox.pack_start(self.w_imginfo, 0,0,0) + vbox.pack_start(self.w_imginfo, 0, , )
hbox = gtk.HBox(True, 2) hbox.set_border_width(2) @@ -111,17 +114,17 @@ class CsvDumpWindow(gtk.Window): self.w_dli.connect("clicked", lambda x: self.fn_download()) self.tips.set_tip(self.w_dli, "Download image from radio") self.w_dli.show() - hbox.pack_start(self.w_dli, 0,0,0) + hbox.pack_start(self.w_dli, 0, , )
self.w_uli = StdButton("Upload") self.w_uli.set_sensitive(False) self.w_uli.connect("clicked", lambda x: self.fn_upload()) self.tips.set_tip(self.w_uli, "Upload image to radio") self.w_uli.show() - hbox.pack_start(self.w_uli, 0,0,0) + hbox.pack_start(self.w_uli, 0, , )
hbox.show() - vbox.pack_start(hbox, 0,0,0) + vbox.pack_start(hbox, 0, , )
vbox.show() self.w_imgframe.add(vbox) @@ -151,45 +154,47 @@ class CsvDumpWindow(gtk.Window):
l = gtk.Label("File") l.show() - hbox.pack_start(l, 0,0,0) + hbox.pack_start(l, 0, , )
self.w_filename = gtk.Entry() self.w_filename.connect("changed", self.file_changed) self.tips.set_tip(self.w_filename, "Path to CSV file") self.w_filename.show() - hbox.pack_start(self.w_filename, 1,1,1) - + hbox.pack_start(self.w_filename, 1, , ) + bb = StdButton("Browse") bb.connect("clicked", self.pick_file) bb.show() - hbox.pack_start(bb, 0,0,0) + hbox.pack_start(bb, 0, , )
hbox.show() - vbox.pack_start(hbox, 0,0,0) + vbox.pack_start(hbox, 0, , )
hbox = gtk.HBox(True, 2) hbox.set_border_width(2)
+ def export_handler(x): + return self.fn_eport(self.w_filename.get_text()) self.w_export = StdButton("Export") self.w_export.set_sensitive(False) - self.w_export.connect("clicked", - lambda x: self.fn_eport(self.w_filename.get_text())) + self.w_export.connect("clicked", export_handler) self.tips.set_tip(self.w_export, "Export radio memories to CSV file") self.w_export.show() - hbox.pack_start(self.w_export, 0,0,0) + hbox.pack_start(self.w_export, 0, , )
+ def import_handler(x): + return self.fn_iport(self.w_filename.get_text()) self.w_import = StdButton("Import") self.w_import.set_sensitive(False) - self.w_import.connect("clicked", - lambda x: self.fn_iport(self.w_filename.get_text())) + self.w_import.connect("clicked", import_handler) self.tips.set_tip(self.w_import, "Import radio memories from CSV file") self.w_import.show() - hbox.pack_start(self.w_import, 0,0,0) + hbox.pack_start(self.w_import, 0, , )
hbox.show() - vbox.pack_start(hbox, 0,0,0) + vbox.pack_start(hbox, 0, , )
vbox.show() self.w_fileframe.add(vbox) @@ -220,10 +225,10 @@ class CsvDumpWindow(gtk.Window):
vbox = gtk.VBox(False, 2)
- vbox.pack_start(self.make_radio_sel(), 0,0,0) - vbox.pack_start(self.make_image_ctl(), 0,0,0) - vbox.pack_start(self.make_file_ctl(), 0,0,0) - vbox.pack_start(self.make_status_bar(), 0,0,0) + vbox.pack_start(self.make_radio_sel(), 0, , ) + vbox.pack_start(self.make_image_ctl(), 0, , ) + vbox.pack_start(self.make_file_ctl(), 0, , ) + vbox.pack_start(self.make_status_bar(), 0, , )
vbox.show() self.add(vbox) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 5cf2b23..3d7e95c 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -90,8 +90,6 @@ ./chirpui/memedit.py ./chirpui/miscwidgets.py ./chirpui/reporting.py -./csvdump/csvapp.py -./csvdump/csvdump.py ./share/make_supported.py ./tools/bitdiff.py ./tools/img2thd72.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 38a9f8ff91f243e3bcad852159dd32ad6800903c
Fix style issues in make_supported.py (#2355)
Like run_tests, this script monkeys with the path to find the chirp modules, so it gets a similar exception.
diff --git a/share/make_supported.py b/share/make_supported.py index 61ddf4d..4ef7031 100755 --- a/share/make_supported.py +++ b/share/make_supported.py @@ -12,8 +12,8 @@ from chirp import * sys.stdout = tmp
RF = chirp_common.RadioFeatures() -KEYS = [x for x in sorted(RF.__dict__.keys()) \ - if "_" in x and not x.startswith("_")] +KEYS = [x for x in sorted(RF.__dict__.keys()) + if "_" in x and not x.startswith("_")]
RADIO_TYPES = { 'Clone': chirp_common.CloneModeRadio, @@ -41,13 +41,13 @@ def supported_row(radio, odd): if key == "valid_bands": value = ["%s-%s MHz" % (chirp_common.format_freq(x), chirp_common.format_freq(y)) - for x,y in value] + for x, y in value]
if key in ["valid_bands", "valid_modes", "valid_power_levels", "valid_tuning_steps"]: try: - value = ", ".join([str(x) for x in value \ - if not str(x).startswith("?")]) + value = ", ".join([str(x) for x in value + if not str(x).startswith("?")]) except Exception, e: raise
@@ -75,6 +75,7 @@ def supported_row(radio, odd): row += "</tr>\n" return row
+ def header_row(): row = "<thead><tr>" row += "<th>Radio</th>\n" @@ -85,6 +86,7 @@ def header_row(): row += "</tr></thead>\n" return row
+ print """ <style> td { @@ -114,13 +116,12 @@ span.false { <table> """
-models = { - "Icom" : [], - "Kenwood" : [], - "Yaesu" : [], - "Alinco" : [], - "z_Other" : [], -} +models = {"Icom": [], + "Kenwood": [], + "Yaesu": [], + "Alinco": [], + "z_Other": [], + }
exclude = [directory.DRV_TO_RADIO["Icom_7200"]]
diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 3d7e95c..aad6343 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -90,6 +90,5 @@ ./chirpui/memedit.py ./chirpui/miscwidgets.py ./chirpui/reporting.py -./share/make_supported.py ./tools/bitdiff.py ./tools/img2thd72.py diff --git a/tools/cpep8.exceptions b/tools/cpep8.exceptions index 3aafd1d..186c181 100644 --- a/tools/cpep8.exceptions +++ b/tools/cpep8.exceptions @@ -2,5 +2,6 @@ # Each line must contain the file name, a tab, and a comma-separated list # of style rules to ignore in that file. This mechanism should be used # sparingly and as a measure of last resort. +./share/make_supported.py E402 ./tests/run_tests E402 ./tests/unit/test_memedit_edits.py E402

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 8ca493958755d28295808b2248f29883f98c9169
Fix style issues in chirp_common.py (#2355)
diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py index 5c4e4f3..1566cc5 100644 --- a/chirp/chirp_common.py +++ b/chirp/chirp_common.py @@ -13,24 +13,21 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/.
-SEPCHAR = "," - -#print "Using separation character of '%s'" % SEPCHAR - import math - from chirp import errors, memmap
+SEPCHAR = "," + # 50 Tones -TONES = [ 67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, - 85.4, 88.5, 91.5, 94.8, 97.4, 100.0, 103.5, - 107.2, 110.9, 114.8, 118.8, 123.0, 127.3, - 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, - 159.8, 162.2, 165.5, 167.9, 171.3, 173.8, - 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, - 196.6, 199.5, 203.5, 206.5, 210.7, 218.1, - 225.7, 229.1, 233.6, 241.8, 250.3, 254.1, - ] +TONES = [67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, + 85.4, 88.5, 91.5, 94.8, 97.4, 100.0, 103.5, + 107.2, 110.9, 114.8, 118.8, 123.0, 127.3, + 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, + 159.8, 162.2, 165.5, 167.9, 171.3, 173.8, + 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, + 196.6, 199.5, 203.5, 206.5, 210.7, 218.1, + 225.7, 229.1, 233.6, 241.8, 250.3, 254.1, + ]
TONES_EXTRA = [62.5]
@@ -40,8 +37,8 @@ OLD_TONES = list(TONES)
# 104 DTCS Codes DTCS_CODES = [ - 23, 25, 26, 31, 32, 36, 43, 47, 51, 53, 54, - 65, 71, 72, 73, 74, 114, 115, 116, 122, 125, 131, + 23, 25, 26, 31, 32, 36, 43, 47, 51, 53, 54, + 65, 71, 72, 73, 74, 114, 115, 116, 122, 125, 131, 132, 134, 143, 145, 152, 155, 156, 162, 165, 172, 174, 205, 212, 223, 225, 226, 243, 244, 245, 246, 251, 252, 255, 261, 263, 265, 266, 271, 274, 306, 311, 315, 325, @@ -50,7 +47,7 @@ DTCS_CODES = [ 465, 466, 503, 506, 516, 523, 526, 532, 546, 565, 606, 612, 624, 627, 631, 632, 654, 662, 664, 703, 712, 723, 731, 732, 734, 743, 754, - ] + ]
# 512 Possible DTCS Codes ALL_DTCS_CODES = [] @@ -90,7 +87,7 @@ TUNING_STEPS = [ 9.0, 1.0, 2.5, ]
-SKIP_VALUES = [ "", "S", "P" ] +SKIP_VALUES = ["", "S", "P"]
CHARSET_UPPER_NUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890" CHARSET_ALPHANUMERIC = \ @@ -143,14 +140,17 @@ APRS_SYMBOLS = ( "TDB", "[reserved]" )
+ def watts_to_dBm(watts): """Converts @watts in watts to dBm""" return int(10 * math.log10(int(watts * 1000)))
+ def dBm_to_watts(dBm): """Converts @dBm from dBm to watts""" return int(math.pow(10, (dBm - 30) / 10))
+ class PowerLevel: """Represents a power level supported by a radio""" def __init__(self, label, watts=0, dBm=0): @@ -188,6 +188,7 @@ class PowerLevel: def __repr__(self): return "%s (%i dBm)" % (self._label, self._power)
+ def parse_freq(freqstr): """Parse a frequency string and return the value in integral Hz""" freqstr = freqstr.strip() @@ -213,14 +214,17 @@ def parse_freq(freqstr):
return mhz + khz
+ def format_freq(freq): """Format a frequency given in Hz as a string"""
return "%i.%06i" % (freq / 1000000, freq % 1000000)
+ class ImmutableValueError(ValueError): pass
+ class Memory: """Base class for a single radio memory""" freq = 0 @@ -279,18 +283,18 @@ class Memory: self.immutable = []
_valid_map = { - "rtone" : TONES + TONES_EXTRA, - "ctone" : TONES + TONES_EXTRA, - "dtcs" : ALL_DTCS_CODES, - "rx_dtcs" : ALL_DTCS_CODES, - "tmode" : TONE_MODES, - "dtcs_polarity" : ["NN", "NR", "RN", "RR"], - "cross_mode" : CROSS_MODES, - "mode" : MODES, - "duplex" : ["", "+", "-", "split", "off"], - "skip" : SKIP_VALUES, - "empty" : [True, False], - "dv_code" : [x for x in range(0, 100)], + "rtone": TONES + TONES_EXTRA, + "ctone": TONES + TONES_EXTRA, + "dtcs": ALL_DTCS_CODES, + "rx_dtcs": ALL_DTCS_CODES, + "tmode": TONE_MODES, + "dtcs_polarity": ["NN", "NR", "RN", "RR"], + "cross_mode": CROSS_MODES, + "mode": MODES, + "duplex": ["", "+", "-", "split", "off"], + "skip": SKIP_VALUES, + "empty": [True, False], + "dv_code": [x for x in range(0, 100)], }
def __repr__(self): @@ -324,10 +328,9 @@ class Memory: raise ImmutableValueError("Field %s is not " % name + "mutable on this memory")
- if self._valid_map.has_key(name) and val not in self._valid_map[name]: - raise ValueError("`%s' is not in valid list: %s" % (\ - val, - self._valid_map[name])) + if name in self._valid_map and val not in self._valid_map[name]: + raise ValueError("`%s' is not in valid list: %s" % + (val, self._valid_map[name]))
self.__dict__[name] = val
@@ -361,7 +364,7 @@ class Memory: else: dup = self.duplex
- return "Memory %i: %s%s%s %s (%s) r%.1f%s c%.1f%s d%03i%s%s [%.2f]"% \ + return "Memory %i: %s%s%s %s (%s) r%.1f%s c%.1f%s d%03i%s%s [%.2f]" % \ (self.number, format_freq(self.freq), dup, @@ -380,20 +383,20 @@ class Memory: def to_csv(self): """Return a CSV representation of this memory""" return [ - "%i" % self.number, - "%s" % self.name, + "%i" % self.number, + "%s" % self.name, format_freq(self.freq), - "%s" % self.duplex, + "%s" % self.duplex, format_freq(self.offset), - "%s" % self.tmode, + "%s" % self.tmode, "%.1f" % self.rtone, "%.1f" % self.ctone, "%03i" % self.dtcs, - "%s" % self.dtcs_polarity, - "%s" % self.mode, + "%s" % self.dtcs_polarity, + "%s" % self.mode, "%.2f" % self.tuning_step, - "%s" % self.skip, - "%s" % self.comment, + "%s" % self.skip, + "%s" % self.comment, "", "", "", ""]
@classmethod @@ -442,7 +445,8 @@ class Memory:
self.tmode = vals[5] if self.tmode not in TONE_MODES: - raise errors.InvalidDataError("Invalid tone mode `%s'" % self.tmode) + raise errors.InvalidDataError("Invalid tone mode `%s'" % + self.tmode)
try: self.rtone = float(vals[6]) @@ -494,6 +498,7 @@ class Memory:
return True
+ class DVMemory(Memory): """A Memory with D-STAR attributes""" dv_urcall = "CQCQCQ" @@ -512,24 +517,24 @@ class DVMemory(Memory):
def to_csv(self): return [ - "%i" % self.number, - "%s" % self.name, + "%i" % self.number, + "%s" % self.name, format_freq(self.freq), - "%s" % self.duplex, + "%s" % self.duplex, format_freq(self.offset), - "%s" % self.tmode, + "%s" % self.tmode, "%.1f" % self.rtone, "%.1f" % self.ctone, "%03i" % self.dtcs, - "%s" % self.dtcs_polarity, - "%s" % self.mode, + "%s" % self.dtcs_polarity, + "%s" % self.mode, "%.2f" % self.tuning_step, - "%s" % self.skip, + "%s" % self.skip, "%s" % self.comment, - "%s" % self.dv_urcall, - "%s" % self.dv_rpt1call, - "%s" % self.dv_rpt2call, - "%i" % self.dv_code] + "%s" % self.dv_urcall, + "%s" % self.dv_rpt1call, + "%s" % self.dv_rpt2call, + "%i" % self.dv_code]
def really_from_csv(self, vals): Memory.really_from_csv(self, vals) @@ -542,6 +547,7 @@ class DVMemory(Memory): except Exception: self.dv_code = 0
+ class MemoryMapping(object): """Base class for a memory mapping""" def __init__(self, model, index, name): @@ -566,6 +572,7 @@ class MemoryMapping(object): def __eq__(self, other): return self.get_index() == other.get_index()
+ class MappingModel(object): """Base class for a memory mapping model"""
@@ -602,20 +609,24 @@ class MappingModel(object): """Return a list of mappings that @memory is in""" raise NotImplementedError()
+ class Bank(MemoryMapping): """Base class for a radio's Bank"""
+ class NamedBank(Bank): """A bank that can have a name""" def set_name(self, name): """Changes the user-adjustable bank name""" self._name = name
+ class BankModel(MappingModel): """A bank model where one memory is in zero or one banks at any point""" def __init__(self, radio, name='Banks'): super(BankModel, self).__init__(radio, name)
+ class MappingModelIndexInterface: """Interface for mappings with index capabilities""" def get_index_bounds(self): @@ -635,10 +646,12 @@ class MappingModelIndexInterface: Exception if full""" raise NotImplementedError()
+ class MTOBankModel(BankModel): """A bank model where one memory can be in multiple banks at once """ pass
+ def console_status(status): """Write a status object to the console""" import sys @@ -656,76 +669,77 @@ class RadioPrompts:
BOOLEAN = [True, False]
+ class RadioFeatures: """Radio Feature Flags""" _valid_map = { # General - "has_bank_index" : BOOLEAN, - "has_dtcs" : BOOLEAN, - "has_rx_dtcs" : BOOLEAN, - "has_dtcs_polarity" : BOOLEAN, - "has_mode" : BOOLEAN, - "has_offset" : BOOLEAN, - "has_name" : BOOLEAN, - "has_bank" : BOOLEAN, - "has_bank_names" : BOOLEAN, - "has_tuning_step" : BOOLEAN, - "has_ctone" : BOOLEAN, - "has_cross" : BOOLEAN, - "has_infinite_number" : BOOLEAN, - "has_nostep_tuning" : BOOLEAN, - "has_comment" : BOOLEAN, - "has_settings" : BOOLEAN, + "has_bank_index": BOOLEAN, + "has_dtcs": BOOLEAN, + "has_rx_dtcs": BOOLEAN, + "has_dtcs_polarity": BOOLEAN, + "has_mode": BOOLEAN, + "has_offset": BOOLEAN, + "has_name": BOOLEAN, + "has_bank": BOOLEAN, + "has_bank_names": BOOLEAN, + "has_tuning_step": BOOLEAN, + "has_ctone": BOOLEAN, + "has_cross": BOOLEAN, + "has_infinite_number": BOOLEAN, + "has_nostep_tuning": BOOLEAN, + "has_comment": BOOLEAN, + "has_settings": BOOLEAN,
# Attributes - "valid_modes" : [], - "valid_tmodes" : [], - "valid_duplexes" : [], - "valid_tuning_steps" : [], - "valid_bands" : [], - "valid_skips" : [], - "valid_power_levels" : [], - "valid_characters" : "", - "valid_name_length" : 0, - "valid_cross_modes" : [], - "valid_dtcs_pols" : [], - "valid_dtcs_codes" : [], - "valid_special_chans" : [], - - "has_sub_devices" : BOOLEAN, - "memory_bounds" : (0, 0), - "can_odd_split" : BOOLEAN, + "valid_modes": [], + "valid_tmodes": [], + "valid_duplexes": [], + "valid_tuning_steps": [], + "valid_bands": [], + "valid_skips": [], + "valid_power_levels": [], + "valid_characters": "", + "valid_name_length": 0, + "valid_cross_modes": [], + "valid_dtcs_pols": [], + "valid_dtcs_codes": [], + "valid_special_chans": [], + + "has_sub_devices": BOOLEAN, + "memory_bounds": (0, 0), + "can_odd_split": BOOLEAN,
# D-STAR - "requires_call_lists" : BOOLEAN, - "has_implicit_calls" : BOOLEAN, + "requires_call_lists": BOOLEAN, + "has_implicit_calls": BOOLEAN, }
def __setattr__(self, name, val): if name.startswith("_"): self.__dict__[name] = val return - elif not name in self._valid_map.keys(): + elif name not in self._valid_map.keys(): raise ValueError("No such attribute `%s'" % name)
if type(self._valid_map[name]) == tuple: # Tuple, cardinality must match if type(val) != tuple or len(val) != len(self._valid_map[name]): - raise ValueError("Invalid value `%s' for attribute `%s'" % \ - (val, name)) + raise ValueError("Invalid value `%s' for attribute `%s'" % + (val, name)) elif type(self._valid_map[name]) == list and not self._valid_map[name]: # Empty list, must be another list if type(val) != list: - raise ValueError("Invalid value `%s' for attribute `%s'" % \ - (val, name)) + raise ValueError("Invalid value `%s' for attribute `%s'" % + (val, name)) elif type(self._valid_map[name]) == str: if type(val) != str: - raise ValueError("Invalid value `%s' for attribute `%s'" % \ - (val, name)) + raise ValueError("Invalid value `%s' for attribute `%s'" % + (val, name)) elif type(self._valid_map[name]) == int: if type(val) != int: - raise ValueError("Invalid value `%s' for attribute `%s'" % \ - (val, name)) + raise ValueError("Invalid value `%s' for attribute `%s'" % + (val, name)) elif val not in self._valid_map[name]: # Value not in the list of valid values raise ValueError("Invalid value `%s' for attribute `%s'" % (val, @@ -753,7 +767,8 @@ class RadioFeatures: self.init("has_dtcs", True, "Indicates that DTCS tone mode is available") self.init("has_rx_dtcs", False, - "Indicates that radio can use two different DTCS codes for rx and tx") + "Indicates that radio can use two different " + + "DTCS codes for rx and tx") self.init("has_dtcs_polarity", True, "Indicates that the DTCS polarity can be changed") self.init("has_mode", True, @@ -851,8 +866,8 @@ class RadioFeatures: msgs.append(msg)
if (self.valid_modes and - mem.mode not in self.valid_modes and - mem.mode != "Auto"): + mem.mode not in self.valid_modes and + mem.mode != "Auto"): msg = ValidationError("Mode %s not supported" % mem.mode) msgs.append(msg)
@@ -863,14 +878,14 @@ class RadioFeatures: if mem.tmode == "Cross": if self.valid_cross_modes and \ mem.cross_mode not in self.valid_cross_modes: - msg = ValidationError("Cross tone mode %s not supported" % \ - mem.cross_mode) + msg = ValidationError("Cross tone mode %s not supported" % + mem.cross_mode) msgs.append(msg)
if self.has_dtcs_polarity and \ mem.dtcs_polarity not in self.valid_dtcs_pols: - msg = ValidationError("DTCS Polarity %s not supported" % \ - mem.dtcs_polarity) + msg = ValidationError("DTCS Polarity %s not supported" % + mem.dtcs_polarity) msgs.append(msg)
if self.valid_dtcs_codes and \ @@ -912,8 +927,8 @@ class RadioFeatures: try: step = required_step(mem.freq) if step not in self.valid_tuning_steps: - msg = ValidationError("Frequency requires %.2fkHz step" %\ - required_step(mem.freq)) + msg = ValidationError("Frequency requires %.2fkHz step" % + required_step(mem.freq)) msgs.append(msg) except errors.InvalidDataError, e: msgs.append(str(e)) @@ -928,18 +943,22 @@ class RadioFeatures:
return msgs
+ class ValidationMessage(str): """Base class for Validation Errors and Warnings""" pass
+ class ValidationWarning(ValidationMessage): """A non-fatal warning during memory validation""" pass
+ class ValidationError(ValidationMessage): """A fatal error during memory validation""" pass
+ class Radio(object): """Base class for all Radio drivers""" BAUD_RATE = 9600 @@ -1042,6 +1061,7 @@ class Radio(object): should be True and get_settings() must be implemented as well.""" pass
+ class FileBackedRadio(Radio): """A file-backed radio stores its data in a file""" FILE_EXTENSION = "img" @@ -1086,7 +1106,6 @@ class FileBackedRadio(Radio): return self._mmap
- class CloneModeRadio(FileBackedRadio): """A clone-mode radio does a full memory dump in and out and we store an image of the radio into an image file""" @@ -1131,16 +1150,19 @@ class CloneModeRadio(FileBackedRadio): "Initiate a PC-to-radio clone operation" pass
+ class LiveRadio(Radio): """Base class for all Live-Mode radios""" pass
+ class NetworkSourceRadio(Radio): """Base class for all radios based on a network source""" def do_fetch(self): """Fetch the source data from the network""" pass
+ class IcomDstarSupport: """Base interface for radios supporting Icom's D-STAR technology""" MYCALL_LIMIT = (1, 1) @@ -1171,6 +1193,7 @@ class IcomDstarSupport: """Set the MYCALL callsign list""" pass
+ class ExperimentalRadio: """Interface for experimental radios""" @classmethod @@ -1178,6 +1201,7 @@ class ExperimentalRadio: return ("This radio's driver is marked as experimental and may " + "be unstable or unsafe to use.")
+ class Status: """Clone status object for conveying clone progress to the UI""" name = "Job" @@ -1196,26 +1220,32 @@ class Status:
return "|%-10s| %2.1f%% %s" % (ticks, pct, self.msg)
+ def is_fractional_step(freq): """Returns True if @freq requires a 12.5kHz or 6.25kHz step""" return not is_5_0(freq) and (is_12_5(freq) or is_6_25(freq))
+ def is_5_0(freq): """Returns True if @freq is reachable by a 5kHz step""" return (freq % 5000) == 0
+ def is_12_5(freq): """Returns True if @freq is reachable by a 12.5kHz step""" return (freq % 12500) == 0
+ def is_6_25(freq): """Returns True if @freq is reachable by a 6.25kHz step""" return (freq % 6250) == 0
+ def is_2_5(freq): """Returns True if @freq is reachable by a 2.5kHz step""" return (freq % 2500) == 0
+ def required_step(freq): """Returns the simplest tuning step that is required to reach @freq""" if is_5_0(freq): @@ -1228,9 +1258,9 @@ def required_step(freq): return 2.5 else: raise errors.InvalidDataError("Unable to calculate the required " + - "tuning step for %i.%5i" % \ - (freq / 1000000, - freq % 1000000)) + "tuning step for %i.%5i" % + (freq / 1000000, freq % 1000000)) +
def fix_rounded_step(freq): """Some radios imply the last bit of 12.5kHz and 6.25kHz step @@ -1259,8 +1289,9 @@ def fix_rounded_step(freq): except errors.InvalidDataError: pass
- raise errors.InvalidDataError("Unable to correct rounded frequency " + \ - format_freq(freq)) + raise errors.InvalidDataError("Unable to correct rounded frequency " + + format_freq(freq)) +
def _name(name, len, just_upper): """Justify @name to @len, optionally converting to all uppercase""" @@ -1268,42 +1299,52 @@ def _name(name, len, just_upper): name = name.upper() return name.ljust(len)[:len]
+ def name6(name, just_upper=True): """6-char name""" return _name(name, 6, just_upper)
+ def name8(name, just_upper=False): """8-char name""" return _name(name, 8, just_upper)
+ def name16(name, just_upper=False): """16-char name""" return _name(name, 16, just_upper)
+ def to_GHz(val): """Convert @val in GHz to Hz""" return val * 1000000000
+ def to_MHz(val): """Convert @val in MHz to Hz""" return val * 1000000
+ def to_kHz(val): """Convert @val in kHz to Hz""" return val * 1000
+ def from_GHz(val): """Convert @val in Hz to GHz""" return val / 100000000
+ def from_MHz(val): """Convert @val in Hz to MHz""" return val / 100000
+ def from_kHz(val): """Convert @val in Hz to kHz""" return val / 100
+ def split_tone_decode(mem, txtone, rxtone): """ Set tone mode and values on @mem based on txtone and rxtone specs like: @@ -1349,6 +1390,7 @@ def split_tone_decode(mem, txtone, rxtone): elif rxmode == "DTCS": mem.rx_dtcs = rxval
+ def split_tone_encode(mem): """ Returns TX, RX tone specs based on @mem like: diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index aad6343..5213d75 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -13,7 +13,6 @@ ./chirp/baofeng_uv3r.py ./chirp/bitwise.py ./chirp/bjuv55.py -./chirp/chirp_common.py ./chirp/elib_intl.py ./chirp/ft1802.py ./chirp/ft1d.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID ff55aeec8905dddcd546b3456362c27949720017
Fix style issues in bitwise.py (#2355)
diff --git a/chirp/bitwise.py b/chirp/bitwise.py index 6eeee26..544ac4f 100644 --- a/chirp/bitwise.py +++ b/chirp/bitwise.py @@ -36,13 +36,13 @@ # lbcd foo; /* BCD-encoded byte (LE) */ # bbcd foo; /* BCD-encoded byte (BE) */ # char foo[8]; /* 8-char array */ -# struct { -# u8 foo; -# u16 bar; +# struct { +# u8 foo; +# u16 bar; # } baz; /* Structure with u8 and u16 */ # # Example directives: -# +# # #seekto 0x1AB; /* Set the data offset to 0x1AB */ # #seek 4; /* Set the data offset += 4 */ # #printoffset "foobar" /* Echo the live data offset, @@ -51,7 +51,7 @@ # Usage: # # Create a data definition in a string, and pass it and the data -# to parse to the parse() function. The result is a structure with +# to parse to the parse() function. The result is a structure with # dict-like objects for structures, indexed by name, and lists of # objects for arrays. The actual data elements can be interpreted # as integers directly (for int types). Strings and BCD arrays @@ -63,10 +63,12 @@ import os from chirp import bitwise_grammar from chirp.memmap import MemoryMap
+ class ParseError(Exception): """Indicates an error parsing a definition""" pass
+ def format_binary(nbits, value, pad=8): s = "" for i in range(0, nbits): @@ -74,10 +76,12 @@ def format_binary(nbits, value, pad=8): value >>= 1 return "%s%s" % ((pad - len(s)) * ".", s)
+ def bits_between(start, end): - bits = (1 << (end - start )) - 1 + bits = (1 << (end - start)) - 1 return bits << start
+ def pp(structure, level=0): for i in structure: if isinstance(i, list): @@ -91,6 +95,7 @@ def pp(structure, level=0): elif isinstance(i, str): print "%s%s" % (" " * level, i)
+ def array_copy(dst, src): """Copy an array src into DataElement array dst""" if len(dst) != len(src): @@ -99,28 +104,34 @@ def array_copy(dst, src): for i in range(0, len(dst)): dst[i].set_value(src[i])
+ def bcd_to_int(bcd_array): - """Convert an array of bcdDataElement like \x12\x34 into an int like 1234""" + """Convert an array of bcdDataElement like \x12\x34 + into an int like 1234""" value = 0 for bcd in bcd_array: a, b = bcd.get_value() value = (value * 100) + (a * 10) + b return value - + + def int_to_bcd(bcd_array, value): """Convert an int like 1234 into bcdDataElements like "\x12\x34" """ for i in reversed(range(0, len(bcd_array))): bcd_array[i].set_value(value % 100) value /= 100
+ def get_string(char_array): """Convert an array of charDataElements into a string""" return "".join([x.get_value() for x in char_array])
+ def set_string(char_array, string): """Set an array of charDataElements from a string""" array_copy(char_array, list(string))
+ class DataElement: _size = 1
@@ -139,7 +150,8 @@ class DataElement: raise Exception("Not implemented")
def get_value(self): - return self._get_value(self._data[self._offset:self._offset+self._size]) + value = self._data[self._offset:self._offset + self._size] + return self._get_value(value)
def set_value(self, value): raise Exception("Not implemented for %s" % self.__class__) @@ -159,6 +171,7 @@ class DataElement: self._size, self._offset)
+ class arrayDataElement(DataElement): def __repr__(self): if isinstance(self.__items[0], bcdDataElement): @@ -252,7 +265,7 @@ class arrayDataElement(DataElement): if i.get_value() == value: return index index += 1 - raise IndexError() + raise IndexError()
def __iter__(self): return iter(self.__items) @@ -269,11 +282,12 @@ class arrayDataElement(DataElement): size += i.size() return size
+ class intDataElement(DataElement): def __repr__(self): fmt = "0x%%0%iX" % (self._size * 2) return fmt % int(self) - + def __int__(self): return self.get_value()
@@ -396,6 +410,7 @@ class intDataElement(DataElement): def __nonzero__(self): return self.get_value() != 0
+ class u8DataElement(intDataElement): _size = 1
@@ -405,6 +420,7 @@ class u8DataElement(intDataElement): def set_value(self, value): self._data[self._offset] = (int(value) & 0xFF)
+ class u16DataElement(intDataElement): _size = 2 _endianess = ">" @@ -416,9 +432,11 @@ class u16DataElement(intDataElement): self._data[self._offset] = struct.pack(self._endianess + "H", int(value) & 0xFFFF)
+ class ul16DataElement(u16DataElement): _endianess = "<" - + + class u24DataElement(intDataElement): _size = 3 _endianess = ">" @@ -435,12 +453,14 @@ class u24DataElement(intDataElement): else: start = 1 end = 4 - self._data[self._offset] = struct.pack(self._endianess + "I", - int(value) & 0xFFFFFFFF)[start:end] + packed = struct.pack(self._endianess + "I", int(value) & 0xFFFFFFFF) + self._data[self._offset] = packed[start:end] +
class ul24DataElement(u24DataElement): _endianess = "<"
+ class u32DataElement(intDataElement): _size = 4 _endianess = ">" @@ -452,9 +472,11 @@ class u32DataElement(intDataElement): self._data[self._offset] = struct.pack(self._endianess + "I", int(value) & 0xFFFFFFFF)
+ class ul32DataElement(u32DataElement): _endianess = "<"
+ class i8DataElement(u8DataElement): _size = 1
@@ -462,8 +484,9 @@ class i8DataElement(u8DataElement): return struct.unpack("b", data)[0]
def set_value(self, value): - self._data[self._offset] = struct.pack("b", int(value) ) - + self._data[self._offset] = struct.pack("b", int(value)) + + class i16DataElement(intDataElement): _size = 2 _endianess = ">" @@ -473,11 +496,13 @@ class i16DataElement(intDataElement):
def set_value(self, value): self._data[self._offset] = struct.pack(self._endianess + "h", - int(value) ) + int(value)) +
class il16DataElement(i16DataElement): _endianess = "<"
+ class i24DataElement(intDataElement): _size = 3 _endianess = ">" @@ -495,11 +520,13 @@ class i24DataElement(intDataElement): start = 1 end = 4 self._data[self._offset] = struct.pack(self._endianess + "i", - int(value) )[start:end] + int(value))[start:end] +
class il24DataElement(i24DataElement): _endianess = "<"
+ class i32DataElement(intDataElement): _size = 4 _endianess = ">" @@ -509,11 +536,13 @@ class i32DataElement(intDataElement):
def set_value(self, value): self._data[self._offset] = struct.pack(self._endianess + "i", - int(value) ) + int(value)) +
class il32DataElement(i32DataElement): _endianess = "<"
+ class charDataElement(DataElement): _size = 1
@@ -529,6 +558,7 @@ class charDataElement(DataElement): def set_value(self, value): self._data[self._offset] = str(value)
+ class bcdDataElement(DataElement): def __int__(self): tens, ones = self.get_value() @@ -560,16 +590,19 @@ class bcdDataElement(DataElement): b = ord(data) & 0x0F return (a, b)
+ class lbcdDataElement(bcdDataElement): _size = 1
+ class bbcdDataElement(bcdDataElement): _size = 1
+ class bitDataElement(intDataElement): _nbits = 0 _shift = 0 - _subgen = u8DataElement # Default to a byte + _subgen = u8DataElement # Default to a byte
def __repr__(self): fmt = "0x%%0%iX (%%sb)" % (self._size * 2) @@ -578,31 +611,23 @@ class bitDataElement(intDataElement): def get_value(self): data = self._subgen(self._data, self._offset).get_value() mask = bits_between(self._shift-self._nbits, self._shift) - val = data & mask - - #print "start: %i bits: %i" % (self._shift, self._nbits) - #print "data: %04x" % data - #print "mask: %04x" % mask - #print " val: %04x" % val - - val >>= (self._shift - self._nbits) + val = (data & mask) >> (self._shift - self._nbits) return val
def set_value(self, value): mask = bits_between(self._shift-self._nbits, self._shift) + data = self._subgen(self._data, self._offset).get_value() data &= ~mask
- #print "data: %04x" % data - #print "mask: %04x" % mask - #print "valu: %04x" % value - value = ((int(value) << (self._shift-self._nbits)) & mask) | data + self._subgen(self._data, self._offset).set_value(value) - + def size(self): return self._nbits
+ class structDataElement(DataElement): def __repr__(self): s = "struct {" + os.linesep @@ -660,7 +685,7 @@ class structDataElement(DataElement): raise AttributeError("No attribute %s in struct" % name)
def __setattr__(self, name, value): - if not self.__dict__.has_key("_structDataElement__init"): + if "_structDataElement__init" not in self.__dict__: self.__dict__[name] = value else: self.__dict__["_generators"][name].set_value(value) @@ -675,7 +700,6 @@ class structDataElement(DataElement): for el in gen: i += 1 size += el.size() - #print "Size of %s[%i] = %i" % (name, i, el.size()) return size
def get_raw(self): @@ -695,25 +719,26 @@ class structDataElement(DataElement): for key in self._keys: yield key, self._generators[key]
+ class Processor:
_types = { - "u8" : u8DataElement, - "u16" : u16DataElement, - "ul16" : ul16DataElement, - "u24" : u24DataElement, - "ul24" : ul24DataElement, - "u32" : u32DataElement, - "ul32" : ul32DataElement, - "i8" : i8DataElement, - "i16" : i16DataElement, - "il16" : il16DataElement, - "i24" : i24DataElement, - "il24" : il24DataElement, - "i32" : i32DataElement, - "char" : charDataElement, - "lbcd" : lbcdDataElement, - "bbcd" : bbcdDataElement, + "u8": u8DataElement, + "u16": u16DataElement, + "ul16": ul16DataElement, + "u24": u24DataElement, + "ul24": ul24DataElement, + "u32": u32DataElement, + "ul32": ul32DataElement, + "i8": i8DataElement, + "i16": i16DataElement, + "il16": il16DataElement, + "i24": i24DataElement, + "il24": il24DataElement, + "i32": i32DataElement, + "char": charDataElement, + "lbcd": lbcdDataElement, + "bbcd": bbcdDataElement, }
def __init__(self, data, offset): @@ -740,13 +765,13 @@ class Processor: _nbits = bits _shift = bitsleft _subgen = self._types[dtype] - + self._generators[name] = bitDE(self._data, self._offset) bitsleft -= bits
if bitsleft: - print "WARNING: %i trailing bits unaccounted for in %s" % (bitsleft, - bitfield) + print "WARNING: %i trailing bits unaccounted for in %s" % \ + (bitsleft, bitfield)
return bytes
@@ -828,7 +853,7 @@ class Processor: def parse_struct(self, struct): if struct[0][0] == "struct_defn": return self.parse_struct_defn(struct[0][1]) - elif struct [0][0] == "struct_decl": + elif struct[0][0] == "struct_decl": return self.parse_struct_decl(struct[0][1]) else: raise Exception("Internal error: What is `%s'?" % struct[0][0]) @@ -837,7 +862,6 @@ class Processor: name = directive[0][0] value = directive[0][1][0][1] if name == "seekto": - #print "NOTICE: Setting offset to %i (0x%X)" % (offset, offset) self._offset = int(value, 0) elif name == "seek": self._offset += int(value, 0) @@ -846,14 +870,12 @@ class Processor:
def parse_block(self, lang): for t, d in lang: - #print t if t == "struct": self.parse_struct(d) elif t == "definition": self.parse_defn(d) elif t == "directive": self.parse_directive(d) -
def parse(self, lang): self._generators = structDataElement(self._data, self._offset) @@ -894,7 +916,6 @@ struct { import sys sys.exit(0)
- test = """ struct { u16 bar; @@ -913,12 +934,12 @@ struct { data = "\xfe\x10\x00\x08\xFF\x23\x01\x02\x03abc\x34\x89" data = (data * 2) + "\x12" data = MemoryMap(data) - + ast = bitwise_grammar.parse(test)
# Just for testing, pretty-print the tree pp(ast) - + # Mess with it a little p = Processor(data, 0) obj = p.parse(ast) @@ -931,7 +952,7 @@ struct { obj["foo"][0]["onebit"].set_value(1) print "%i" % int(obj["foo"][0]["bar"])
- for i in obj["foo"][0]["array"]: + for i in obj["foo"][0]["array"]: print int(i) obj["foo"][0]["array"][1].set_value(255)
diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 5213d75..d33c735 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -11,7 +11,6 @@ ./chirp/bandplan_iaru_r3.py ./chirp/bandplan_na.py ./chirp/baofeng_uv3r.py -./chirp/bitwise.py ./chirp/bjuv55.py ./chirp/elib_intl.py ./chirp/ft1802.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID ec107a09aefc84b415e7e155ee52427b4920fe4d
Fix style issues in settings.py (#2355)
diff --git a/chirp/settings.py b/chirp/settings.py index c0fbe92..5d8f3ee 100644 --- a/chirp/settings.py +++ b/chirp/settings.py @@ -15,14 +15,17 @@
from chirp import chirp_common
+ class InvalidValueError(Exception): """An invalid value was specified for a given setting""" pass
+ class InternalError(Exception): """A driver provided an invalid settings object structure""" pass
+ class RadioSettingValue: """Base class for a single radio setting""" def __init__(self): @@ -49,7 +52,7 @@ class RadioSettingValue: if not self.get_mutable(): raise InvalidValueError("This value is not mutable")
- if self._current != None and value != self._current: + if self._current is not None and value != self._current: self._has_changed = True self._current = self._validate_callback(value)
@@ -63,6 +66,7 @@ class RadioSettingValue: def __str__(self): return str(self.get_value())
+ class RadioSettingValueInteger(RadioSettingValue): """An integer setting""" def __init__(self, minval, maxval, current, step=1): @@ -78,9 +82,8 @@ class RadioSettingValueInteger(RadioSettingValue): except: raise InvalidValueError("An integer is required") if value > self._max or value < self._min: - raise InvalidValueError("Value %i not in range %i-%i" % (value, - self._min, - self._max)) + raise InvalidValueError("Value %i not in range %i-%i" % + (value, self._min, self._max)) RadioSettingValue.set_value(self, value)
def get_min(self): @@ -95,6 +98,7 @@ class RadioSettingValueInteger(RadioSettingValue): """Returns the step increment""" return self._step
+ class RadioSettingValueFloat(RadioSettingValue): """A floating-point setting""" def __init__(self, minval, maxval, current, resolution=0.001, precision=4): @@ -122,7 +126,7 @@ class RadioSettingValueFloat(RadioSettingValue): raise InvalidValueError("Value %s not in range %s-%s" % ( self.format(value), self.format(self._min), self.format(self._max))) - + # FIXME: honor resolution
RadioSettingValue.set_value(self, value) @@ -134,6 +138,7 @@ class RadioSettingValueFloat(RadioSettingValue): def get_max(self): """Returns the maximum allowed value"""
+ class RadioSettingValueBoolean(RadioSettingValue): """A boolean setting""" def __init__(self, current): @@ -150,6 +155,7 @@ class RadioSettingValueBoolean(RadioSettingValue): def __str__(self): return str(bool(self.get_value()))
+ class RadioSettingValueList(RadioSettingValue): """A list-of-strings setting""" def __init__(self, options, current): @@ -158,7 +164,7 @@ class RadioSettingValueList(RadioSettingValue): self.set_value(current)
def set_value(self, value): - if not value in self._options: + if value not in self._options: raise InvalidValueError("%s is not valid for this setting" % value) RadioSettingValue.set_value(self, value)
@@ -169,6 +175,7 @@ class RadioSettingValueList(RadioSettingValue): def __trunc__(self): return self._options.index(self._current)
+ class RadioSettingValueString(RadioSettingValue): """A string setting""" def __init__(self, minlength, maxlength, current, @@ -186,8 +193,8 @@ class RadioSettingValueString(RadioSettingValue):
def set_value(self, value): if len(value) < self._minlength or len(value) > self._maxlength: - raise InvalidValueError("Value must be between %i and %i chars" % (\ - self._minlength, self._maxlength)) + raise InvalidValueError("Value must be between %i and %i chars" % + (self._minlength, self._maxlength)) if self._autopad: value = value.ljust(self._maxlength) for char in value: @@ -204,6 +211,7 @@ class RadioSettings(list): def __init__(self, *groups): list.__init__(self, groups)
+ class RadioSettingGroup(object): """A group of settings""" def _validate(self, element): @@ -212,12 +220,12 @@ class RadioSettingGroup(object): raise InternalError("Incorrect type %s" % type(element))
def __init__(self, name, shortname, *elements): - self._name = name # Setting identifier - self._shortname = shortname # Short human-readable name/description - self.__doc__ = name # Longer explanation/documentation + self._name = name # Setting identifier + self._shortname = shortname # Short human-readable name/description + self.__doc__ = name # Longer explanation/documentation self._elements = {} self._element_order = [] - + for element in elements: self._validate(element) self.append(element) @@ -250,16 +258,19 @@ class RadioSettingGroup(object): def __iter__(self): class RSGIterator: """Iterator for a RadioSettingGroup""" + def __init__(self, rsg): self.__rsg = rsg self.__i = 0 + def __iter__(self): return self + def next(self): """Next Iterator Interface""" if self.__i >= len(self.__rsg.keys()): raise StopIteration() - e = self.__rsg[self.__rsg.keys()[self.__i]] + e = self.__rsg[self.__rsg.keys()[self.__i]] self.__i += 1 return e return RSGIterator(self) @@ -290,6 +301,7 @@ class RadioSettingGroup(object): """Returns the list of elements""" return [self._elements[name] for name in self._element_order]
+ class RadioSetting(RadioSettingGroup): """A single setting, which could be an array of items like a group""" def __init__(self, *args): @@ -311,7 +323,8 @@ class RadioSetting(RadioSettingGroup): raise InternalError("Incorrect type")
def changed(self): - """Returns True if any of the elements in the group have been changed""" + """Returns True if any of the elements + in the group have been changed""" for element in self._elements.values(): if element.changed(): return True @@ -341,7 +354,7 @@ class RadioSetting(RadioSettingGroup): raise InternalError("Setting %s is not a scalar" % self._name) else: self.__dict__[name] = value - + # List interface
def append(self, value): @@ -357,8 +370,7 @@ class RadioSetting(RadioSettingGroup): def __setitem__(self, name, value): if not isinstance(name, int): raise IndexError("Index `%s' is not an integer" % name) - if self._elements.has_key(name): + if name in self._elements: self._elements[name].set_value(value) else: self._elements[name] = value - diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index d33c735..a564989 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -55,7 +55,6 @@ ./chirp/puxing.py ./chirp/pyPEG.py ./chirp/rfinder.py -./chirp/settings.py ./chirp/th9800.py ./chirp/th_uv3r.py ./chirp/th_uv3r25.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID c648abc2c5daf8dfcec838f231553fd24a013d8b
Fix style issues in elib_intl.py (#2355)
diff --git a/chirp/elib_intl.py b/chirp/elib_intl.py index 6e7cafa..76e3b9b 100644 --- a/chirp/elib_intl.py +++ b/chirp/elib_intl.py @@ -19,17 +19,18 @@
''' -The elib.intl module provides enhanced internationalization (I18N) services for -your Python modules and applications. +The elib.intl module provides enhanced internationalization (I18N) +services for your Python modules and applications.
-elib.intl wraps Python's :func:`gettext` functionality and adds the following on -Microsoft Windows systems: +elib.intl wraps Python's :func:`gettext` functionality and adds the +following on Microsoft Windows systems:
- - automatic detection of the current screen language (not necessarily the same - as the installation language) provided by MUI packs, - - makes sure internationalized C libraries which internally invoke gettext() or - dcgettext() can properly locate their message catalogs. This fixes a known - limitation in gettext's Windows support when using eg. gtk.builder or gtk.glade. + - automatic detection of the current screen language (not necessarily + the same as the installation language) provided by MUI packs, + - makes sure internationalized C libraries which internally invoke + gettext() or dcgettext() can properly locate their message catalogs. + This fixes a known limitation in gettext's Windows support when using + eg. gtk.builder or gtk.glade.
See http://www.gnu.org/software/gettext/FAQ.html#windows_setenv for more information. @@ -37,12 +38,6 @@ information. The elib.intl module defines the following functions: '''
- -__all__ = ['install', 'install_module'] -__version__ = '0.0.3' -__docformat__ = 'restructuredtext' - - import os import sys import locale @@ -50,6 +45,9 @@ import gettext
from logging import getLogger
+__all__ = ['install', 'install_module'] +__version__ = '0.0.3' +__docformat__ = 'restructuredtext'
logger = getLogger('elib.intl')
@@ -58,249 +56,254 @@ def _isofromlcid(lcid): ''' :param lcid: Microsoft Windows LCID :returns: the ISO 639-1 language code for a given lcid. If there is no - ISO 639-1 language code assigned to the language specified by lcid, - the ISO 639-2 language code is returned. If the language specified - by lcid is unknown in the ISO 639-x database, None is returned. + ISO 639-1 language code assigned to the language specified + by lcid, the ISO 639-2 language code is returned. If the + language specified by lcid is unknown in the ISO 639-x + database, None is returned.
More information can be found on the following websites: - - List of ISO 639-1 and ISO 639-2 language codes: http://www.loc.gov/standards/iso639-2/ - - List of known lcid's: http://www.microsoft.com/globaldev/reference/lcid-all.mspx - - List of known MUI packs: http://www.microsoft.com/globaldev/reference/win2k/setup/Langid.mspx + - List of ISO 639-1 and ISO 639-2 language codes: + http://www.loc.gov/standards/iso639-2/ + - List of known lcid's: + http://www.microsoft.com/globaldev/reference/lcid-all.mspx + - List of known MUI packs: + http://www.microsoft.com/globaldev/reference/win2k/setup/Langid.mspx ''' - mapping = {1078: 'af', #Afrikaans - South Africa - 1052: 'sq', #Albanian - Albania - 1118: 'am', #Amharic - Ethiopia - 1025: 'ar', #Arabic - Saudi Arabia - 5121: 'ar', #Arabic - Algeria - 15361: 'ar', #Arabic - Bahrain - 3073: 'ar', #Arabic - Egypt - 2049: 'ar', #Arabic - Iraq - 11265: 'ar', #Arabic - Jordan - 13313: 'ar', #Arabic - Kuwait - 12289: 'ar', #Arabic - Lebanon - 4097: 'ar', #Arabic - Libya - 6145: 'ar', #Arabic - Morocco - 8193: 'ar', #Arabic - Oman - 16385: 'ar', #Arabic - Qatar - 10241: 'ar', #Arabic - Syria - 7169: 'ar', #Arabic - Tunisia - 14337: 'ar', #Arabic - U.A.E. - 9217: 'ar', #Arabic - Yemen - 1067: 'hy', #Armenian - Armenia - 1101: 'as', #Assamese - 2092: 'az', #Azeri (Cyrillic) - 1068: 'az', #Azeri (Latin) - 1069: 'eu', #Basque - 1059: 'be', #Belarusian - 1093: 'bn', #Bengali (India) - 2117: 'bn', #Bengali (Bangladesh) - 5146: 'bs', #Bosnian (Bosnia/Herzegovina) - 1026: 'bg', #Bulgarian - 1109: 'my', #Burmese - 1027: 'ca', #Catalan - 1116: 'chr', #Cherokee - United States - 2052: 'zh', #Chinese - People's Republic of China - 4100: 'zh', #Chinese - Singapore - 1028: 'zh', #Chinese - Taiwan - 3076: 'zh', #Chinese - Hong Kong SAR - 5124: 'zh', #Chinese - Macao SAR - 1050: 'hr', #Croatian - 4122: 'hr', #Croatian (Bosnia/Herzegovina) - 1029: 'cs', #Czech - 1030: 'da', #Danish - 1125: 'dv', #Divehi - 1043: 'nl', #Dutch - Netherlands - 2067: 'nl', #Dutch - Belgium - 1126: 'bin', #Edo - 1033: 'en', #English - United States - 2057: 'en', #English - United Kingdom - 3081: 'en', #English - Australia - 10249: 'en', #English - Belize - 4105: 'en', #English - Canada - 9225: 'en', #English - Caribbean - 15369: 'en', #English - Hong Kong SAR - 16393: 'en', #English - India - 14345: 'en', #English - Indonesia - 6153: 'en', #English - Ireland - 8201: 'en', #English - Jamaica - 17417: 'en', #English - Malaysia - 5129: 'en', #English - New Zealand - 13321: 'en', #English - Philippines - 18441: 'en', #English - Singapore - 7177: 'en', #English - South Africa - 11273: 'en', #English - Trinidad - 12297: 'en', #English - Zimbabwe - 1061: 'et', #Estonian - 1080: 'fo', #Faroese - 1065: None, #TODO: Farsi - 1124: 'fil', #Filipino - 1035: 'fi', #Finnish - 1036: 'fr', #French - France - 2060: 'fr', #French - Belgium - 11276: 'fr', #French - Cameroon - 3084: 'fr', #French - Canada - 9228: 'fr', #French - Democratic Rep. of Congo - 12300: 'fr', #French - Cote d'Ivoire - 15372: 'fr', #French - Haiti - 5132: 'fr', #French - Luxembourg - 13324: 'fr', #French - Mali - 6156: 'fr', #French - Monaco - 14348: 'fr', #French - Morocco - 58380: 'fr', #French - North Africa - 8204: 'fr', #French - Reunion - 10252: 'fr', #French - Senegal - 4108: 'fr', #French - Switzerland - 7180: 'fr', #French - West Indies - 1122: 'fy', #Frisian - Netherlands - 1127: None, #TODO: Fulfulde - Nigeria - 1071: 'mk', #FYRO Macedonian - 2108: 'ga', #Gaelic (Ireland) - 1084: 'gd', #Gaelic (Scotland) - 1110: 'gl', #Galician - 1079: 'ka', #Georgian - 1031: 'de', #German - Germany - 3079: 'de', #German - Austria - 5127: 'de', #German - Liechtenstein - 4103: 'de', #German - Luxembourg - 2055: 'de', #German - Switzerland - 1032: 'el', #Greek - 1140: 'gn', #Guarani - Paraguay - 1095: 'gu', #Gujarati - 1128: 'ha', #Hausa - Nigeria - 1141: 'haw', #Hawaiian - United States - 1037: 'he', #Hebrew - 1081: 'hi', #Hindi - 1038: 'hu', #Hungarian - 1129: None, #TODO: Ibibio - Nigeria - 1039: 'is', #Icelandic - 1136: 'ig', #Igbo - Nigeria - 1057: 'id', #Indonesian - 1117: 'iu', #Inuktitut - 1040: 'it', #Italian - Italy - 2064: 'it', #Italian - Switzerland - 1041: 'ja', #Japanese - 1099: 'kn', #Kannada - 1137: 'kr', #Kanuri - Nigeria - 2144: 'ks', #Kashmiri - 1120: 'ks', #Kashmiri (Arabic) - 1087: 'kk', #Kazakh - 1107: 'km', #Khmer - 1111: 'kok', #Konkani - 1042: 'ko', #Korean - 1088: 'ky', #Kyrgyz (Cyrillic) - 1108: 'lo', #Lao - 1142: 'la', #Latin - 1062: 'lv', #Latvian - 1063: 'lt', #Lithuanian - 1086: 'ms', #Malay - Malaysia - 2110: 'ms', #Malay - Brunei Darussalam - 1100: 'ml', #Malayalam - 1082: 'mt', #Maltese - 1112: 'mni', #Manipuri - 1153: 'mi', #Maori - New Zealand - 1102: 'mr', #Marathi - 1104: 'mn', #Mongolian (Cyrillic) - 2128: 'mn', #Mongolian (Mongolian) - 1121: 'ne', #Nepali - 2145: 'ne', #Nepali - India - 1044: 'no', #Norwegian (Bokmᅢᆬl) - 2068: 'no', #Norwegian (Nynorsk) - 1096: 'or', #Oriya - 1138: 'om', #Oromo - 1145: 'pap', #Papiamentu - 1123: 'ps', #Pashto - 1045: 'pl', #Polish - 1046: 'pt', #Portuguese - Brazil - 2070: 'pt', #Portuguese - Portugal - 1094: 'pa', #Punjabi - 2118: 'pa', #Punjabi (Pakistan) - 1131: 'qu', #Quecha - Bolivia - 2155: 'qu', #Quecha - Ecuador - 3179: 'qu', #Quecha - Peru - 1047: 'rm', #Rhaeto-Romanic - 1048: 'ro', #Romanian - 2072: 'ro', #Romanian - Moldava - 1049: 'ru', #Russian - 2073: 'ru', #Russian - Moldava - 1083: 'se', #Sami (Lappish) - 1103: 'sa', #Sanskrit - 1132: 'nso', #Sepedi - 3098: 'sr', #Serbian (Cyrillic) - 2074: 'sr', #Serbian (Latin) - 1113: 'sd', #Sindhi - India - 2137: 'sd', #Sindhi - Pakistan - 1115: 'si', #Sinhalese - Sri Lanka - 1051: 'sk', #Slovak - 1060: 'sl', #Slovenian - 1143: 'so', #Somali - 1070: 'wen', #Sorbian - 3082: 'es', #Spanish - Spain (Modern Sort) - 1034: 'es', #Spanish - Spain (Traditional Sort) - 11274: 'es', #Spanish - Argentina - 16394: 'es', #Spanish - Bolivia - 13322: 'es', #Spanish - Chile - 9226: 'es', #Spanish - Colombia - 5130: 'es', #Spanish - Costa Rica - 7178: 'es', #Spanish - Dominican Republic - 12298: 'es', #Spanish - Ecuador - 17418: 'es', #Spanish - El Salvador - 4106: 'es', #Spanish - Guatemala - 18442: 'es', #Spanish - Honduras - 58378: 'es', #Spanish - Latin America - 2058: 'es', #Spanish - Mexico - 19466: 'es', #Spanish - Nicaragua - 6154: 'es', #Spanish - Panama - 15370: 'es', #Spanish - Paraguay - 10250: 'es', #Spanish - Peru - 20490: 'es', #Spanish - Puerto Rico - 21514: 'es', #Spanish - United States - 14346: 'es', #Spanish - Uruguay - 8202: 'es', #Spanish - Venezuela - 1072: None, #TODO: Sutu - 1089: 'sw', #Swahili - 1053: 'sv', #Swedish - 2077: 'sv', #Swedish - Finland - 1114: 'syr', #Syriac - 1064: 'tg', #Tajik - 1119: None, #TODO: Tamazight (Arabic) - 2143: None, #TODO: Tamazight (Latin) - 1097: 'ta', #Tamil - 1092: 'tt', #Tatar - 1098: 'te', #Telugu - 1054: 'th', #Thai - 2129: 'bo', #Tibetan - Bhutan - 1105: 'bo', #Tibetan - People's Republic of China - 2163: 'ti', #Tigrigna - Eritrea - 1139: 'ti', #Tigrigna - Ethiopia - 1073: 'ts', #Tsonga - 1074: 'tn', #Tswana - 1055: 'tr', #Turkish - 1090: 'tk', #Turkmen - 1152: 'ug', #Uighur - China - 1058: 'uk', #Ukrainian - 1056: 'ur', #Urdu - 2080: 'ur', #Urdu - India - 2115: 'uz', #Uzbek (Cyrillic) - 1091: 'uz', #Uzbek (Latin) - 1075: 've', #Venda - 1066: 'vi', #Vietnamese - 1106: 'cy', #Welsh - 1076: 'xh', #Xhosa - 1144: 'ii', #Yi - 1085: 'yi', #Yiddish - 1130: 'yo', #Yoruba - 1077: 'zu'} #Zulu + mapping = {1078: 'af', # frikaans - South Africa + 1052: 'sq', # lbanian - Albania + 1118: 'am', # mharic - Ethiopia + 1025: 'ar', # rabic - Saudi Arabia + 5121: 'ar', # rabic - Algeria + 15361: 'ar', # rabic - Bahrain + 3073: 'ar', # rabic - Egypt + 2049: 'ar', # rabic - Iraq + 11265: 'ar', # rabic - Jordan + 13313: 'ar', # rabic - Kuwait + 12289: 'ar', # rabic - Lebanon + 4097: 'ar', # rabic - Libya + 6145: 'ar', # rabic - Morocco + 8193: 'ar', # rabic - Oman + 16385: 'ar', # rabic - Qatar + 10241: 'ar', # rabic - Syria + 7169: 'ar', # rabic - Tunisia + 14337: 'ar', # rabic - U.A.E. + 9217: 'ar', # rabic - Yemen + 1067: 'hy', # rmenian - Armenia + 1101: 'as', # ssamese + 2092: 'az', # zeri (Cyrillic) + 1068: 'az', # zeri (Latin) + 1069: 'eu', # asque + 1059: 'be', # elarusian + 1093: 'bn', # engali (India) + 2117: 'bn', # engali (Bangladesh) + 5146: 'bs', # osnian (Bosnia/Herzegovina) + 1026: 'bg', # ulgarian + 1109: 'my', # urmese + 1027: 'ca', # atalan + 1116: 'chr', # herokee - United States + 2052: 'zh', # hinese - People's Republic of China + 4100: 'zh', # hinese - Singapore + 1028: 'zh', # hinese - Taiwan + 3076: 'zh', # hinese - Hong Kong SAR + 5124: 'zh', # hinese - Macao SAR + 1050: 'hr', # roatian + 4122: 'hr', # roatian (Bosnia/Herzegovina) + 1029: 'cs', # zech + 1030: 'da', # anish + 1125: 'dv', # ivehi + 1043: 'nl', # utch - Netherlands + 2067: 'nl', # utch - Belgium + 1126: 'bin', # do + 1033: 'en', # nglish - United States + 2057: 'en', # nglish - United Kingdom + 3081: 'en', # nglish - Australia + 10249: 'en', # nglish - Belize + 4105: 'en', # nglish - Canada + 9225: 'en', # nglish - Caribbean + 15369: 'en', # nglish - Hong Kong SAR + 16393: 'en', # nglish - India + 14345: 'en', # nglish - Indonesia + 6153: 'en', # nglish - Ireland + 8201: 'en', # nglish - Jamaica + 17417: 'en', # nglish - Malaysia + 5129: 'en', # nglish - New Zealand + 13321: 'en', # nglish - Philippines + 18441: 'en', # nglish - Singapore + 7177: 'en', # nglish - South Africa + 11273: 'en', # nglish - Trinidad + 12297: 'en', # nglish - Zimbabwe + 1061: 'et', # stonian + 1080: 'fo', # aroese + 1065: None, # ODO: Farsi + 1124: 'fil', # ilipino + 1035: 'fi', # innish + 1036: 'fr', # rench - France + 2060: 'fr', # rench - Belgium + 11276: 'fr', # rench - Cameroon + 3084: 'fr', # rench - Canada + 9228: 'fr', # rench - Democratic Rep. of Congo + 12300: 'fr', # rench - Cote d'Ivoire + 15372: 'fr', # rench - Haiti + 5132: 'fr', # rench - Luxembourg + 13324: 'fr', # rench - Mali + 6156: 'fr', # rench - Monaco + 14348: 'fr', # rench - Morocco + 58380: 'fr', # rench - North Africa + 8204: 'fr', # rench - Reunion + 10252: 'fr', # rench - Senegal + 4108: 'fr', # rench - Switzerland + 7180: 'fr', # rench - West Indies + 1122: 'fy', # risian - Netherlands + 1127: None, # ODO: Fulfulde - Nigeria + 1071: 'mk', # YRO Macedonian + 2108: 'ga', # aelic (Ireland) + 1084: 'gd', # aelic (Scotland) + 1110: 'gl', # alician + 1079: 'ka', # eorgian + 1031: 'de', # erman - Germany + 3079: 'de', # erman - Austria + 5127: 'de', # erman - Liechtenstein + 4103: 'de', # erman - Luxembourg + 2055: 'de', # erman - Switzerland + 1032: 'el', # reek + 1140: 'gn', # uarani - Paraguay + 1095: 'gu', # ujarati + 1128: 'ha', # ausa - Nigeria + 1141: 'haw', # awaiian - United States + 1037: 'he', # ebrew + 1081: 'hi', # indi + 1038: 'hu', # ungarian + 1129: None, # ODO: Ibibio - Nigeria + 1039: 'is', # celandic + 1136: 'ig', # gbo - Nigeria + 1057: 'id', # ndonesian + 1117: 'iu', # nuktitut + 1040: 'it', # talian - Italy + 2064: 'it', # talian - Switzerland + 1041: 'ja', # apanese + 1099: 'kn', # annada + 1137: 'kr', # anuri - Nigeria + 2144: 'ks', # ashmiri + 1120: 'ks', # ashmiri (Arabic) + 1087: 'kk', # azakh + 1107: 'km', # hmer + 1111: 'kok', # onkani + 1042: 'ko', # orean + 1088: 'ky', # yrgyz (Cyrillic) + 1108: 'lo', # ao + 1142: 'la', # atin + 1062: 'lv', # atvian + 1063: 'lt', # ithuanian + 1086: 'ms', # alay - Malaysia + 2110: 'ms', # alay - Brunei Darussalam + 1100: 'ml', # alayalam + 1082: 'mt', # altese + 1112: 'mni', # anipuri + 1153: 'mi', # aori - New Zealand + 1102: 'mr', # arathi + 1104: 'mn', # ongolian (Cyrillic) + 2128: 'mn', # ongolian (Mongolian) + 1121: 'ne', # epali + 2145: 'ne', # epali - India + 1044: 'no', # orwegian (Bokmᅢᆬl) + 2068: 'no', # orwegian (Nynorsk) + 1096: 'or', # riya + 1138: 'om', # romo + 1145: 'pap', # apiamentu + 1123: 'ps', # ashto + 1045: 'pl', # olish + 1046: 'pt', # ortuguese - Brazil + 2070: 'pt', # ortuguese - Portugal + 1094: 'pa', # unjabi + 2118: 'pa', # unjabi (Pakistan) + 1131: 'qu', # uecha - Bolivia + 2155: 'qu', # uecha - Ecuador + 3179: 'qu', # uecha - Peru + 1047: 'rm', # haeto-Romanic + 1048: 'ro', # omanian + 2072: 'ro', # omanian - Moldava + 1049: 'ru', # ussian + 2073: 'ru', # ussian - Moldava + 1083: 'se', # ami (Lappish) + 1103: 'sa', # anskrit + 1132: 'nso', # epedi + 3098: 'sr', # erbian (Cyrillic) + 2074: 'sr', # erbian (Latin) + 1113: 'sd', # indhi - India + 2137: 'sd', # indhi - Pakistan + 1115: 'si', # inhalese - Sri Lanka + 1051: 'sk', # lovak + 1060: 'sl', # lovenian + 1143: 'so', # omali + 1070: 'wen', # orbian + 3082: 'es', # panish - Spain (Modern Sort) + 1034: 'es', # panish - Spain (Traditional Sort) + 11274: 'es', # panish - Argentina + 16394: 'es', # panish - Bolivia + 13322: 'es', # panish - Chile + 9226: 'es', # panish - Colombia + 5130: 'es', # panish - Costa Rica + 7178: 'es', # panish - Dominican Republic + 12298: 'es', # panish - Ecuador + 17418: 'es', # panish - El Salvador + 4106: 'es', # panish - Guatemala + 18442: 'es', # panish - Honduras + 58378: 'es', # panish - Latin America + 2058: 'es', # panish - Mexico + 19466: 'es', # panish - Nicaragua + 6154: 'es', # panish - Panama + 15370: 'es', # panish - Paraguay + 10250: 'es', # panish - Peru + 20490: 'es', # panish - Puerto Rico + 21514: 'es', # panish - United States + 14346: 'es', # panish - Uruguay + 8202: 'es', # panish - Venezuela + 1072: None, # ODO: Sutu + 1089: 'sw', # wahili + 1053: 'sv', # wedish + 2077: 'sv', # wedish - Finland + 1114: 'syr', # yriac + 1064: 'tg', # ajik + 1119: None, # ODO: Tamazight (Arabic) + 2143: None, # ODO: Tamazight (Latin) + 1097: 'ta', # amil + 1092: 'tt', # atar + 1098: 'te', # elugu + 1054: 'th', # hai + 2129: 'bo', # ibetan - Bhutan + 1105: 'bo', # ibetan - People's Republic of China + 2163: 'ti', # igrigna - Eritrea + 1139: 'ti', # igrigna - Ethiopia + 1073: 'ts', # songa + 1074: 'tn', # swana + 1055: 'tr', # urkish + 1090: 'tk', # urkmen + 1152: 'ug', # ighur - China + 1058: 'uk', # krainian + 1056: 'ur', # rdu + 2080: 'ur', # rdu - India + 2115: 'uz', # zbek (Cyrillic) + 1091: 'uz', # zbek (Latin) + 1075: 've', # enda + 1066: 'vi', # ietnamese + 1106: 'cy', # elsh + 1076: 'xh', # hosa + 1144: 'ii', # i + 1085: 'yi', # iddish + 1130: 'yo', # oruba + 1077: 'zu'} # ulu
return mapping[lcid]
+ def _getscreenlanguage(): ''' :returns: the ISO 639-x language code for this session.
- If the LANGUAGE environment variable is set, it's value overrides the - screen language detection. Otherwise the screen language is determined by - the currently selected Microsoft Windows MUI language pack or the Microsoft - Windows installation language. + If the LANGUAGE environment variable is set, it's value overrides + the screen language detection. Otherwise the screen language is + determined by the currently selected Microsoft Windows MUI language + pack or the Microsoft Windows installation language.
Works on Microsoft Windows 2000 and up. ''' @@ -319,34 +322,39 @@ def _getscreenlanguage(): from ctypes import windll lcid = windll.kernel32.GetUserDefaultUILanguage() except: - logger.debug('Failed to get current screen language with 'GetUserDefaultUILanguage'') + logger.debug('Failed to get current screen language ' + 'with 'GetUserDefaultUILanguage'') finally: if lcid is None: lang = 'C' else: lang = _isofromlcid(lcid)
- logger.debug('Windows screen language is '%s' (lcid %s)' % (lang, lcid)) + logger.debug('Windows screen language is '%s' ' + '(lcid %s)' % (lang, lcid))
return lang
+ def _putenv(name, value): ''' :param name: environment variable name :param value: environment variable value
- This function ensures that changes to an environment variable are applied - to each copy of the environment variables used by a process. Starting from - Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) - and are no longer automatically applied to the other copies for the process. - - On Microsoft Windows, each process has multiple copies of the environment - variables, one managed by the OS and one managed by the C library. We also - need to take care of the fact that the C library used by Python is not - necessarily the same as the C library used by pygtk and friends. This because - the latest releases of pygtk and friends are built with mingw32 and are thus - linked against msvcrt.dll. The official gtk+ binaries have always been built - in this way. + This function ensures that changes to an environment variable are + applied to each copy of the environment variables used by a process. + Starting from Python 2.4, os.environ changes only apply to the copy + Python keeps (os.environ) and are no longer automatically applied to + the other copies for the process. + + On Microsoft Windows, each process has multiple copies of the + environment variables, one managed by the OS and one managed by the + C library. We also need to take care of the fact that the C library + used by Python is not necessarily the same as the C library used by + pygtk and friends. This because the latest releases of pygtk and + friends are built with mingw32 and are thus linked against + msvcrt.dll. The official gtk+ binaries have always been built in + this way. '''
if sys.platform == 'win32' or sys.platform == 'nt': @@ -357,34 +365,47 @@ def _putenv(name, value): # Update Python's copy of the environment variables os.environ[name] = value
- # Update the copy maintained by Windows (so SysInternals Process Explorer sees it) + # Update the copy maintained by Windows (so SysInternals + # Process Explorer sees it) try: result = windll.kernel32.SetEnvironmentVariableW(name, value) - if result == 0: raise Warning + if result == 0: + raise Warning except Exception: - logger.debug('Failed to set environment variable '%s' ('kernel32.SetEnvironmentVariableW')' % name) + logger.debug('Failed to set environment variable '%s' ' + '('kernel32.SetEnvironmentVariableW')' % name) else: - logger.debug('Set environment variable '%s' to '%s' ('kernel32.SetEnvironmentVariableW')' % (name, value)) + logger.debug('Set environment variable '%s' to '%s' ' + '('kernel32.SetEnvironmentVariableW')' % + (name, value))
# Update the copy maintained by msvcrt (used by gtk+ runtime) try: result = cdll.msvcrt._putenv('%s=%s' % (name, value)) - if result !=0: raise Warning + if result != 0: + raise Warning except Exception: - logger.debug('Failed to set environment variable '%s' ('msvcrt._putenv')' % name) + logger.debug('Failed to set environment variable '%s' ' + '('msvcrt._putenv')' % name) else: - logger.debug('Set environment variable '%s' to '%s' ('msvcrt._putenv')' % (name, value)) + logger.debug('Set environment variable '%s' to '%s' ' + '('msvcrt._putenv')' % (name, value))
# Update the copy maintained by whatever c runtime is used by Python try: msvcrt = find_msvcrt() - msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str(msvcrt) + msvcrtname = str(msvcrt).split('.')[0] \ + if '.' in msvcrt else str(msvcrt) result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value)) - if result != 0: raise Warning + if result != 0: + raise Warning except Exception: - logger.debug('Failed to set environment variable '%s' ('%s._putenv')' % (name, msvcrtname)) + logger.debug('Failed to set environment variable '%s' ' + '('%s._putenv')' % (name, msvcrtname)) else: - logger.debug('Set environment variable '%s' to '%s' ('%s._putenv')' % (name, value, msvcrtname)) + logger.debug('Set environment variable '%s' to '%s' ' + '('%s._putenv')' % (name, value, msvcrtname)) +
def _dugettext(domain, message): ''' @@ -402,11 +423,13 @@ def _dugettext(domain, message): else: return t.ugettext(message)
+ def _install(domain, localedir, asglobal=False): ''' :param domain: translation domain :param localedir: locale directory - :param asglobal: if True, installs the function _() in Python’s builtin namespace. Default is False + :param asglobal: if True, installs the function _() in Python’s + builtin namespace. Default is False
Private function doing all the work for the :func:`elib.intl.install` and :func:`elib.intl.install_module` functions. @@ -445,6 +468,7 @@ def _install(domain, localedir, asglobal=False):
del libintl
+ def install(domain, localedir): ''' :param domain: translation domain @@ -472,6 +496,7 @@ def install(domain, localedir): _install(domain, localedir, True) gettext.install(domain, localedir, unicode=True)
+ def install_module(domain, localedir): ''' :param domain: translation domain @@ -488,7 +513,7 @@ def install_module(domain, localedir): _ = elib.intl.install_module('mymodule', '/path/to/usr/share/locale') print _('This string will be translated.')
- When writing a package, you can usually do this in the package's __init__.py + When writing packages, you can usually do this in the package's __init__.py file and import the _() function from the package namespace as needed. ''' _install(domain, localedir, False) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index a564989..5a9db49 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -12,7 +12,6 @@ ./chirp/bandplan_na.py ./chirp/baofeng_uv3r.py ./chirp/bjuv55.py -./chirp/elib_intl.py ./chirp/ft1802.py ./chirp/ft1d.py ./chirp/ft2800.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID f48f4cbb644d2b90d70b0e90b5945b3bcc94373f
Fix style issues in pyPEG.py (#2355)
diff --git a/chirp/pyPEG.py b/chirp/pyPEG.py index 5faa637..68d8b74 100644 --- a/chirp/pyPEG.py +++ b/chirp/pyPEG.py @@ -3,36 +3,52 @@ # written by VB.
import re -import sys, codecs +import sys +import codecs import exceptions
-class keyword(unicode): pass -class code(unicode): pass + +class keyword(unicode): + pass + + +class code(unicode): + pass + + class ignore(object): def __init__(self, regex_text, *args): self.regex = re.compile(regex_text, *args)
+ class _and(object): def __init__(self, something): self.obj = something
-class _not(_and): pass + +class _not(_and): + pass +
class Name(unicode): def __init__(self, *args): self.line = 0 self.file = u""
+ class Symbol(list): def __init__(self, name, what): self.__name__ = name self.append(name) self.what = what self.append(what) + def __call__(self): return self.what + def __unicode__(self): return u'Symbol(' + repr(self.__name__) + ', ' + repr(self.what) + u')' + def __repr__(self): return unicode(self)
@@ -41,6 +57,7 @@ rest_regex = re.compile(ur".*")
print_trace = False
+ def u(text): if isinstance(text, exceptions.BaseException): text = text.args[0] @@ -53,6 +70,7 @@ def u(text): return codecs.decode(text, "utf-8") return unicode(text)
+ def skip(skipper, text, skipWS, skipComments): if skipWS: t = text.lstrip() @@ -64,12 +82,14 @@ def skip(skipper, text, skipWS, skipComments): skip, t = skipper.parseLine(t, skipComments, [], skipWS, None) if skipWS: t = t.lstrip() - except: pass + except: + pass return t
+ class parser(object): - def __init__(self, another = False, p = False): - self.restlen = -1 + def __init__(self, another=False, p=False): + self.restlen = -1 if not(another): self.skipper = parser(True, p) self.skipper.packrat = p @@ -86,15 +106,17 @@ class parser(object): # resultSoFar: parsing result so far (default: blank list []) # skipWS: Flag if whitespace should be skipped (default: True) # skipComments: Python functions returning pyPEG for matching comments - # + # # returns: pyAST, textrest # - # raises: SyntaxError(reason) if textline is detected not being in language - # described by pattern + # raises: SyntaxError(reason) if textline is detected not + # being in language described by pattern # - # SyntaxError(reason) if pattern is an illegal language description + # SyntaxError(reason) if pattern is an illegal + # language description
- def parseLine(self, textline, pattern, resultSoFar = [], skipWS = True, skipComments = None): + def parseLine(self, textline, pattern, resultSoFar=[], + skipWS=True, skipComments=None): name = None _textline = textline _pattern = pattern @@ -104,8 +126,10 @@ class parser(object): if print_trace: try: if _pattern.__name__ != "comment": - sys.stderr.write(u"match: " + _pattern.__name__ + u"\n") - except: pass + sys.stderr.write(u"match: " + + _pattern.__name__ + u"\n") + except: + pass
if self.restlen == -1: self.restlen = len(text) @@ -119,7 +143,7 @@ class parser(object): name.line = self.lineNo() res.append(Symbol(name, [])) elif result: - if type(result) is type([]): + if isinstance(result, list): res.extend(result) else: res.extend([result]) @@ -139,15 +163,19 @@ class parser(object): return result else: raise SyntaxError() - except: pass + except: + pass
if callable(pattern): if __debug__: if print_trace: try: if pattern.__name__ != "comment": - sys.stderr.write(u"testing with " + pattern.__name__ + u": " + textline[:40] + u"\n") - except: pass + sys.stderr.write(u"testing with " + + pattern.__name__ + u": " + + textline[:40] + u"\n") + except: + pass
if pattern.__name__[0] != "_": name = Name(pattern.__name__) @@ -162,7 +190,8 @@ class parser(object):
if pattern_type is str or pattern_type is unicode: if text[:len(pattern)] == pattern: - text = skip(self.skipper, text[len(pattern):], skipWS, skipComments) + text = skip(self.skipper, text[len(pattern):], + skipWS, skipComments) return R(None, text) else: syntaxError() @@ -171,7 +200,8 @@ class parser(object): m = word_regex.match(text) if m: if m.group(0) == pattern: - text = skip(self.skipper, text[len(pattern):], skipWS, skipComments) + text = skip(self.skipper, text[len(pattern):], + skipWS, skipComments) return R(None, text) else: syntaxError() @@ -180,7 +210,8 @@ class parser(object):
elif pattern_type is _not: try: - r, t = self.parseLine(text, pattern.obj, [], skipWS, skipComments) + r, t = self.parseLine(text, pattern.obj, [], + skipWS, skipComments) except: return resultSoFar, textline syntaxError() @@ -194,7 +225,8 @@ class parser(object): pattern = pattern.regex m = pattern.match(text) if m: - text = skip(self.skipper, text[len(m.group(0)):], skipWS, skipComments) + text = skip(self.skipper, text[len(m.group(0)):], + skipWS, skipComments) if pattern_type is ignore: return R(None, text) else: @@ -206,26 +238,29 @@ class parser(object): result = [] n = 1 for p in pattern: - if type(p) is type(0): + if isinstance(p, int): n = p else: - if n>0: + if n > 0: for i in range(n): - result, text = self.parseLine(text, p, result, skipWS, skipComments) - elif n==0: + result, text = self.parseLine( + text, p, result, skipWS, skipComments) + elif n == 0: if text == "": pass else: try: - newResult, newText = self.parseLine(text, p, result, skipWS, skipComments) + newResult, newText = self.parseLine( + text, p, result, skipWS, skipComments) result, text = newResult, newText except SyntaxError: pass - elif n<0: + elif n < 0: found = False while True: try: - newResult, newText = self.parseLine(text, p, result, skipWS, skipComments) + newResult, newText = self.parseLine( + text, p, result, skipWS, skipComments) result, text, found = newResult, newText, True except SyntaxError: break @@ -239,7 +274,8 @@ class parser(object): found = False for p in pattern: try: - result, text = self.parseLine(text, p, result, skipWS, skipComments) + result, text = self.parseLine(text, p, result, + skipWS, skipComments) found = True except SyntaxError: pass @@ -254,8 +290,10 @@ class parser(object): raise SyntaxError(u"illegal type in grammar: " + u(pattern_type))
def lineNo(self): - if not(self.lines): return u"" - if self.restlen == -1: return u"" + if not(self.lines): + return u"" + if self.restlen == -1: + return u"" parsed = self.textlen - self.restlen
left, right = 0, len(self.lines) @@ -266,14 +304,16 @@ class parser(object): try: if self.lines[mid + 1][0] >= parsed: try: - return u(self.lines[mid + 1][1]) + u":" + u(self.lines[mid + 1][2]) + return u(self.lines[mid + 1][1]) + \ + u":" + u(self.lines[mid + 1][2]) except: return u"" else: left = mid + 1 except: try: - return u(self.lines[mid + 1][1]) + u":" + u(self.lines[mid + 1][2]) + return u(self.lines[mid + 1][1]) + \ + u":" + u(self.lines[mid + 1][2]) except: return u"" else: @@ -281,9 +321,12 @@ class parser(object): if left > right: return u""
-# plain module API
-def parseLine(textline, pattern, resultSoFar = [], skipWS = True, skipComments = None, packrat = False): +# plain module APIs + + +def parseLine(textline, pattern, resultSoFar=[], skipWS=True, + skipComments=None, packrat=False): p = parser(p=packrat) text = skip(p.skipper, textline, skipWS, skipComments) ast, text = p.parseLine(text, pattern, resultSoFar, skipWS, skipComments) @@ -296,13 +339,15 @@ def parseLine(textline, pattern, resultSoFar = [], skipWS = True, skipComments = # skipComments: Python function which returns pyPEG for matching comments # packrat: use memoization # lineCount: add line number information to AST -# +# # returns: pyAST # # raises: SyntaxError(reason), if a parsed line is not in language # SyntaxError(reason), if the language description is illegal
-def parse(language, lineSource, skipWS = True, skipComments = None, packrat = False, lineCount = True): + +def parse(language, lineSource, skipWS=True, skipComments=None, + packrat=False, lineCount=True): lines, lineNo = [], 0
while callable(language): @@ -314,7 +359,8 @@ def parse(language, lineSource, skipWS = True, skipComments = None, packrat = Fa ld = 1 else: ld += 1 - lines.append((len(orig), lineSource.filename(), lineSource.lineno() - 1)) + lines.append((len(orig), lineSource.filename(), + lineSource.lineno() - 1)) orig += u(line)
textlen = len(orig) @@ -346,6 +392,7 @@ def parse(language, lineSource, skipWS = True, skipComments = None, packrat = Fa lineNo += 1 nn -= 1 lineCont = orig.splitlines()[nn] - raise SyntaxError(u"syntax error in " + u(file) + u":" + u(lineNo) + u": " + lineCont) + raise SyntaxError(u"syntax error in " + u(file) + u":" + + u(lineNo) + u": " + lineCont)
return result diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 5a9db49..a2e1803 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -52,7 +52,6 @@ ./chirp/kyd.py ./chirp/leixen.py ./chirp/puxing.py -./chirp/pyPEG.py ./chirp/rfinder.py ./chirp/th9800.py ./chirp/th_uv3r.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 7d3493b9676f5135f801077a0338d405631f01e0
Fix style issues in bandplans (#2355)
diff --git a/chirp/bandplan_au.py b/chirp/bandplan_au.py index 136ef93..9f4ba50 100644 --- a/chirp/bandplan_au.py +++ b/chirp/bandplan_au.py @@ -20,9 +20,10 @@ from chirp import bandplan, bandplan_iaru_r3 SHORTNAME = "australia"
DESC = { - "name": "Australian Amateur Band Plan", + "name": "Australian Amateur Band Plan", "updated": "April 2010", - "url": "http://www.wia.org.au/members/bandplans/data/documents/Australian%20Band%20P...", + "url": "http://www.wia.org.au/members/bandplans/data" + "/documents/Australian%20Band%20Plans%20100404.pdf", }
BANDS_10M = ( diff --git a/chirp/bandplan_iaru_r1.py b/chirp/bandplan_iaru_r1.py index f71be4a..e41b0ee 100644 --- a/chirp/bandplan_iaru_r1.py +++ b/chirp/bandplan_iaru_r1.py @@ -18,8 +18,9 @@ from chirp import bandplan SHORTNAME = "iaru_r1"
DESC = { - "name": "IARU Region 1 (Europe, Africa, Middle East and Northern Asia)", - "url": "http://iaru-r1.org/index.php?option=com_content&view=article&id=175&...", + "name": "IARU Region 1 (Europe, Africa, Middle East and Northern Asia)", + "url": "http://iaru-r1.org/index.php?option=com_content" + "&view=article&id=175&Itemid=127", "updated": "General Conference Sun City 2011", }
@@ -60,8 +61,8 @@ BANDS_40M = ( bandplan.Band((7053000, 7060000), "All modes, digimodes"), bandplan.Band((7060000, 7100000), "All modes, SSB contest preferred", mode="LSB"), - bandplan.Band((7100000, 7130000), "All modes, R1 Emergency Center Of Activity", - mode="LSB"), + bandplan.Band((7100000, 7130000), + "All modes, R1 Emergency Center Of Activity", mode="LSB"), bandplan.Band((7130000, 7200000), "All modes, SSB contest preferred", mode="LSB"), bandplan.Band((7175000, 7200000), "All modes, SSB DX preferred", mode="LSB"), @@ -82,8 +83,8 @@ BANDS_20M = ( bandplan.Band((14101000, 14112000), "All narrow band modes, digimodes"), bandplan.Band((14125000, 14350000), "All modes, SSB contest preferred", mode="USB"), - bandplan.Band((14300000, 14350000), "All modes, Global Emergency center of activity", - mode="USB"), + bandplan.Band((14300000, 14350000), + "All modes, Global Emergency center of activity", mode="USB"), )
BANDS_17M = ( @@ -99,7 +100,8 @@ BANDS_15M = ( bandplan.Band((21000000, 21450000), "15 Meter Band"), bandplan.Band((21000000, 21070000), "CW", mode="CW"), bandplan.Band((21070000, 21090000), "All narrow band modes, digimodes"), - bandplan.Band((21090000, 21110000), "All narrow band, digimodes, unattended"), + bandplan.Band((21090000, 21110000), + "All narrow band, digimodes, unattended"), bandplan.Band((21110000, 21120000), "All modes, digimodes, unattended"), bandplan.Band((21120000, 21149000), "All narrow band modes"), bandplan.Band((21149000, 21151000), "IBP, exclusively for beacons", @@ -120,7 +122,8 @@ BANDS_10M = ( bandplan.Band((28000000, 29700000), "10 Meter Band"), bandplan.Band((28000000, 28070000), "CW", mode="CW"), bandplan.Band((28070000, 28120000), "All narrow band modes, digimodes"), - bandplan.Band((28120000, 28150000), "All narrow band, digimodes, unattended"), + bandplan.Band((28120000, 28150000), + "All narrow band, digimodes, unattended"), bandplan.Band((28150000, 28190000), "All narrow band modes"), bandplan.Band((28190000, 28199000), "Beacons", mode="CW"), bandplan.Band((28199000, 28201000), "IBP, exclusively for beacons", diff --git a/chirp/bandplan_na.py b/chirp/bandplan_na.py index ba46c8c..50bbb27 100644 --- a/chirp/bandplan_na.py +++ b/chirp/bandplan_na.py @@ -20,7 +20,7 @@ SHORTNAME = "north_america"
DESC = { "name": "North American Band Plan", - "url": "http://www.arrl.org/band-plan" + "url": "http://www.arrl.org/band-plan" }
BANDS_160M = ( @@ -36,25 +36,25 @@ BANDS_80M = ( bandplan.Band((3570000, 3600000), "RTTY/Data", mode="RTTY"), bandplan.Band((3790000, 3800000), "DX window"), ) - + BANDS_40M = ( bandplan.Band((7000000, 7300000), "40 Meter Band"), bandplan.Band((7080000, 7125000), "RTTY/Data", mode="RTTY"), ) - + BANDS_30M = ( bandplan.Band((10100000, 10150000), "30 Meter Band"), bandplan.Band((10130000, 10140000), "RTTY", mode="RTTY"), bandplan.Band((10140000, 10150000), "Packet"), ) - + BANDS_20M = ( bandplan.Band((14000000, 14350000), "20 Meter Band"), bandplan.Band((14070000, 14095000), "RTTY", mode="RTTY"), bandplan.Band((14095000, 14099500), "Packet"), bandplan.Band((14100500, 14112000), "Packet"), ) - + BANDS_17M = ( bandplan.Band((18068000, 18168000), "17 Meter Band"), bandplan.Band((18100000, 18105000), "RTTY", mode="RTTY"), @@ -71,7 +71,7 @@ BANDS_12M = ( bandplan.Band((24920000, 24925000), "RTTY", mode="RTTY"), bandplan.Band((24925000, 24930000), "Packet"), ) - + BANDS_10M = ( bandplan.Band((28000000, 29700000), "10 Meter Band"), bandplan.Band((28000000, 28070000), "CW", mode="CW"), @@ -83,7 +83,7 @@ BANDS_10M = ( bandplan.Band((29300000, 29510000), "Satellite Downlinks"), bandplan.Band((29520000, 29590000), "Repeater Inputs", step_khz=10, mode="NFM"), - bandplan.Band((29610000, 29700000), "Repeater Outputs", + bandplan.Band((29610000, 29700000), "Repeater Outputs", step_khz=10, mode="NFM", input_offset=-890000), )
@@ -177,7 +177,7 @@ BANDS_70CM = ( bandplan.Band((447000000, 450000000), "Repeater inputs and outputs " "(local option)", input_offset=-5000000), ) - + BANDS_33CM = ( bandplan.Band((902000000, 928000000), "33 Centimeter Band"), bandplan.Band((902075000, 902100000), "CW/SSB, Weak signal"), @@ -206,8 +206,9 @@ BANDS_23CM = ( "with 1258.000-1260.000", mode="FM"), bandplan.Band((1248000000, 1252000000), "Digital"), bandplan.Band((1252000000, 1258000000), "ATV Channel #2"), - bandplan.Band((1258000000, 1260000000), "Point-to-point links paired " - "with 1246.000-1248.000", mode="FM"), + bandplan.Band((1258000000, 1260000000), + "Point-to-point links paired with 1246.000-1248.000", + mode="FM"), bandplan.Band((1240000000, 1260000000), "Regional option, FM ATV"), bandplan.Band((1260000000, 1270000000), "Satellite uplinks, Experimental, " "Simplex ATV"), @@ -238,8 +239,8 @@ BANDS_13CM = ( "paired with 2393 - 2393.750"), bandplan.Band((2303750000, 2304000000), "SSB, CW, digital weak-signal"), bandplan.Band((2304000000, 2304100000), "Weak Signal EME Band, <3kHz"), - bandplan.Band((2304100000, 2304300000), "SSB, CW, digital weak-signal, <3kHz" - ), + bandplan.Band((2304100000, 2304300000), + "SSB, CW, digital weak-signal, <3kHz"), bandplan.Band((2304300000, 2304400000), "Beacons, <3kHz"), bandplan.Band((2304400000, 2304750000), "SSB, CW, digital weak-signal and " "NBFM, <6kHz"), diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index a2e1803..36f1013 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -5,11 +5,6 @@ ./chirp/alinco.py ./chirp/anytone.py ./chirp/ap510.py -./chirp/bandplan_au.py -./chirp/bandplan_iaru_r1.py -./chirp/bandplan_iaru_r2.py -./chirp/bandplan_iaru_r3.py -./chirp/bandplan_na.py ./chirp/baofeng_uv3r.py ./chirp/bjuv55.py ./chirp/ft1802.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 416084d4c54526a4cc1240d1455bdd05aa77c3d3
Fix style issues in chirp module (#2355)
diff --git a/chirp/__init__.py b/chirp/__init__.py index 084af48..7b48821 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -13,12 +13,12 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/.
-CHIRP_VERSION="0.3.0dev" - import os import sys from glob import glob
+CHIRP_VERSION = "0.3.0dev" + module_dir = os.path.dirname(sys.modules["chirp"].__file__) __all__ = [] for i in glob(os.path.join(module_dir, "*.py")): diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 36f1013..35c48e4 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -1,7 +1,6 @@ # cpep8.blacklist: The list of files that do not meet PEP8 standards. # DO NOT ADD NEW FILES!! Instead, fix the code to be compliant. # Over time, this list should shrink and (eventually) be eliminated. -./chirp/__init__.py ./chirp/alinco.py ./chirp/anytone.py ./chirp/ap510.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 4f877cf677cccaee5316d1753f957240f3ac7b41
Fix style issues in common.py (#2355)
diff --git a/chirpui/common.py b/chirpui/common.py index 9fe8e23..dcbbb3f 100644 --- a/chirpui/common.py +++ b/chirpui/common.py @@ -27,11 +27,12 @@ from chirpui import reporting, config
CONF = config.get()
+ class Editor(gobject.GObject): __gsignals__ = { - 'changed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), - 'usermsg' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, - (gobject.TYPE_STRING,)), + 'changed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), + 'usermsg': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, + (gobject.TYPE_STRING,)), }
root = None @@ -74,12 +75,14 @@ class Editor(gobject.GObject):
gobject.type_register(Editor)
+ def DBG(*args): if False: print " ".join(args)
VERBOSE = False
+ class RadioJob: def __init__(self, cb, func, *args, **kwargs): self.cb = cb @@ -137,11 +140,11 @@ class RadioJob:
self._execute(self.target, func)
+ class RadioThread(threading.Thread, gobject.GObject): __gsignals__ = { - "status" : (gobject.SIGNAL_RUN_LAST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING,)), + "status": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, + (gobject.TYPE_STRING,)), }
def __init__(self, radio, parent=None): @@ -171,7 +174,7 @@ class RadioThread(threading.Thread, gobject.GObject): self.__lock.release()
def _qsubmit(self, job, priority): - if not self.__queue.has_key(priority): + if priority not in self.__queue: self.__queue[priority] = []
self.__queue[priority].append(job) @@ -179,7 +182,7 @@ class RadioThread(threading.Thread, gobject.GObject):
def _queue_clear_below(self, priority): for i in range(0, priority): - if self.__queue.has_key(i) and len(self.__queue[i]) != 0: + if i in self.__queue and len(self.__queue[i]) != 0: return False
return True @@ -221,13 +224,13 @@ class RadioThread(threading.Thread, gobject.GObject): self.flush() self.__counter.release() self.__enabled = False - + def _status(self, msg): jobs = 0 for i in dict(self.__queue): jobs += len(self.__queue[i]) gobject.idle_add(self.emit, "status", "[%i] %s" % (jobs, msg)) - + def _queue_pop(self, priority): try: return self.__queue[priority].pop(0) @@ -239,8 +242,8 @@ class RadioThread(threading.Thread, gobject.GObject): while self.__enabled: DBG("Waiting for a job") if last_job_desc: - self.status(_("Completed") + " " + last_job_desc + \ - " (" + _("idle") + ")") + self.status(_("Completed") + " " + last_job_desc + + " (" + _("idle") + ")") self.__counter.acquire()
self._qlock() @@ -260,15 +263,17 @@ class RadioThread(threading.Thread, gobject.GObject):
print "RadioThread exiting"
+ def log_exception(): - import traceback - import sys + import traceback + import sys
- reporting.report_exception(traceback.format_exc(limit=30)) + reporting.report_exception(traceback.format_exc(limit=30)) + + print "-- Exception: --" + traceback.print_exc(limit=30, file=sys.stdout) + print "------"
- print "-- Exception: --" - traceback.print_exc(limit=30, file=sys.stdout) - print "------"
def show_error(msg, parent=None): d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=parent, @@ -281,6 +286,7 @@ def show_error(msg, parent=None): d.run() d.destroy()
+ def ask_yesno_question(msg, parent=None): d = gtk.MessageDialog(buttons=gtk.BUTTONS_YES_NO, parent=parent, type=gtk.MESSAGE_QUESTION) @@ -294,6 +300,7 @@ def ask_yesno_question(msg, parent=None):
return r == gtk.RESPONSE_YES
+ def combo_select(box, value): store = box.get_model() iter = store.get_iter_first() @@ -305,6 +312,7 @@ def combo_select(box, value):
return False
+ def _add_text(d, text): v = gtk.TextView() v.get_buffer().set_text(text) @@ -314,9 +322,10 @@ def _add_text(d, text): sw = gtk.ScrolledWindow() sw.add(v) sw.show() - d.vbox.pack_start(sw, 1,1,1) + d.vbox.pack_start(sw, 1, 1, 1) return v
+ def show_error_text(msg, text, parent=None): d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=parent, type=gtk.MESSAGE_ERROR) @@ -330,6 +339,7 @@ def show_error_text(msg, text, parent=None): d.run() d.destroy()
+ def show_warning(msg, text, parent=None, buttons=None, title="Warning", can_squelch=False): @@ -363,6 +373,7 @@ def show_warning(msg, text, return r, cb.get_active() return r
+ def simple_diff(a, b, diffsonly=False): lines_a = a.split(os.linesep) lines_b = b.split(os.linesep) @@ -374,7 +385,7 @@ def simple_diff(a, b, diffsonly=False): diff += "-%s%s" % (lines_a[i], os.linesep) diff += "+%s%s" % (lines_b[i], os.linesep) blankprinted = False - elif diffsonly == True: + elif diffsonly is True: if blankprinted: continue diff += os.linesep @@ -383,6 +394,7 @@ def simple_diff(a, b, diffsonly=False): diff += " %s%s" % (lines_a[i], os.linesep) return diff
+ # A quick hacked up tool to show a blob of text in a dialog window # using fixed-width fonts. It also highlights lines that start with # a '-' in red bold font and '+' with blue bold font. @@ -430,6 +442,7 @@ def show_diff_blob(title, result): d.run() d.destroy()
+ def unpluralize(string): if string.endswith("s"): return string[:-1] diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 35c48e4..a805274 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -70,7 +70,6 @@ ./chirp/wouxun.py ./chirp/wouxun_common.py ./chirp/yaesu_clone.py -./chirpui/common.py ./chirpui/editorset.py ./chirpui/fips.py ./chirpui/importdialog.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID cb3de68bc4f6a40336e0e8624713b636298496b9
Fix style issues in editorset.py (#2355)
diff --git a/chirpui/editorset.py b/chirpui/editorset.py index 520463f..59d82ea 100644 --- a/chirpui/editorset.py +++ b/chirpui/editorset.py @@ -21,18 +21,19 @@ from chirp import chirp_common, directory, generic_csv, generic_xml from chirpui import memedit, dstaredit, bankedit, common, importdialog from chirpui import inputdialog, reporting, settingsedit, radiobrowser, config
+ class EditorSet(gtk.VBox): __gsignals__ = { - "want-close" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), - "status" : (gobject.SIGNAL_RUN_LAST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING,)), - "usermsg": (gobject.SIGNAL_RUN_LAST, + "want-close": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), + "status": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)), - "editor-selected" : (gobject.SIGNAL_RUN_LAST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING,)), + "usermsg": (gobject.SIGNAL_RUN_LAST, + gobject.TYPE_NONE, + (gobject.TYPE_STRING,)), + "editor-selected": (gobject.SIGNAL_RUN_LAST, + gobject.TYPE_NONE, + (gobject.TYPE_STRING,)), }
def _make_device_mapping_editors(self, device, devrthread, index): @@ -76,7 +77,7 @@ class EditorSet(gtk.VBox): memories.connect("changed", self.editor_changed)
if self.rf.has_sub_devices: - label = (_("Memories (%(variant)s)") % + label = (_("Memories (%(variant)s)") % dict(variant=device.VARIANT)) rf = device.get_features() else: @@ -97,7 +98,8 @@ class EditorSet(gtk.VBox): editor.connect("changed", self.editor_changed) self.editors["dstar"] = editor
- def __init__(self, source, parent_window=None, filename=None, tempname=None): + def __init__(self, source, parent_window=None, + filename=None, tempname=None): gtk.VBox.__init__(self, True, 0)
self.parent_window = parent_window @@ -146,7 +148,7 @@ class EditorSet(gtk.VBox):
conf = config.get() if (hasattr(self.rthread.radio, '_memobj') and - conf.get_bool("developer", "state")): + conf.get_bool("developer", "state")): editor = radiobrowser.RadioBrowser(self.rthread) lab = gtk.Label(_("Browser")) self.tabs.append_page(editor.root, lab) @@ -197,7 +199,7 @@ class EditorSet(gtk.VBox): if not fname: fname = self.filename if not os.path.exists(self.filename): - return # Probably before the first "Save as" + return # Probably before the first "Save as" else: self.filename = fname
@@ -240,7 +242,7 @@ class EditorSet(gtk.VBox): # interface to queue our own changes before opening it up to the # rest of the world.
- dst_rthread._qlock_when_idle(5) # Suspend job submission when idle + dst_rthread._qlock_when_idle(5) # Suspend job submission when idle
dialog = dlgclass(src_radio, dst_rthread.radio, self.parent_window) r = dialog.run() @@ -265,10 +267,9 @@ class EditorSet(gtk.VBox): choices = [x.VARIANT for x in devices]
d = inputdialog.ChoiceDialog(choices) - d.label.set_text(_("The {vendor} {model} has multiple " - "independent sub-devices").format( \ - vendor=radio.VENDOR, model=radio.MODEL) + os.linesep + \ - _("Choose one to import from:")) + text = _("The {vendor} {model} has multiple independent sub-devices") + d.label.set_text(text.format(vendor=radio.VENDOR, model=radio.MODEL) + + os.linesep + _("Choose one to import from:")) r = d.run() chosen = d.choice.get_active_text() d.destroy() @@ -297,8 +298,10 @@ class EditorSet(gtk.VBox): if isinstance(src_radio, chirp_common.NetworkSourceRadio): ww = importdialog.WaitWindow("Querying...", self.parent_window) ww.show() + def status(status): ww.set(float(status.cur) / float(status.max)) + try: src_radio.status_fn = status src_radio.do_fetch() @@ -331,7 +334,7 @@ class EditorSet(gtk.VBox): common.log_exception() common.show_error(_("There was an error during " "import: {error}").format(error=e)) - + def do_export(self, filen): try: if filen.lower().endswith(".csv"): @@ -373,7 +376,7 @@ class EditorSet(gtk.VBox): common.show_error(_("There was an error during " "export: {error}").format(error=e), self) - + def prime(self): # NOTE: this is only called to prime new CSV files, so assume # only one memory editor for now @@ -389,7 +392,7 @@ class EditorSet(gtk.VBox):
def tab_selected(self, notebook, foo, pagenum): widget = notebook.get_nth_page(pagenum) - for k,v in self.editors.items(): + for k, v in self.editors.items(): if v and v.root == widget: v.focus() self.emit("editor-selected", k) @@ -408,8 +411,9 @@ class EditorSet(gtk.VBox): editor and editor.prepare_close()
def get_current_editor(self): + tabs = self.tabs for lab, e in self.editors.items(): - if e and self.tabs.page_num(e.root) == self.tabs.get_current_page(): + if e and tabs.page_num(e.root) == tabs.get_current_page(): return e raise Exception("No editor selected?")
diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index a805274..2d58449 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -70,7 +70,6 @@ ./chirp/wouxun.py ./chirp/wouxun_common.py ./chirp/yaesu_clone.py -./chirpui/editorset.py ./chirpui/fips.py ./chirpui/importdialog.py ./chirpui/mainapp.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 75148640f8e998f673fa80c71dfc9aa9ee77e41a
Fix style issues in importdialog.py (#2355)
diff --git a/chirpui/importdialog.py b/chirpui/importdialog.py index b7417ce..dd4be6e 100644 --- a/chirpui/importdialog.py +++ b/chirpui/importdialog.py @@ -20,6 +20,7 @@ import pango from chirp import errors, chirp_common, generic_xml, import_logic from chirpui import common
+ class WaitWindow(gtk.Window): def __init__(self, msg, parent=None): gtk.Window.__init__(self) @@ -56,6 +57,7 @@ class WaitWindow(gtk.Window):
self.prog.set_fraction(fraction)
+ class ImportMemoryBankJob(common.RadioJob): def __init__(self, cb, dst_mem, src_radio, src_mem): common.RadioJob.__init__(self, cb, None) @@ -69,6 +71,7 @@ class ImportMemoryBankJob(common.RadioJob): if self.cb: gobject.idle_add(self.cb, *self.cb_args)
+ class ImportDialog(gtk.Dialog):
def _check_for_dupe(self, location): @@ -89,8 +92,7 @@ class ImportDialog(gtk.Dialog): d.set_property("text", _("Location {number} is already being imported. " "Choose another value for 'New Location' " - "before selection 'Import'").format(\ - number=nloc)) + "before selection 'Import'").format(number=nloc)) d.run() d.destroy() else: @@ -98,7 +100,7 @@ class ImportDialog(gtk.Dialog):
def _render(self, _, rend, model, iter, colnum): newloc, imp = model.get(iter, self.col_nloc, self.col_import) - lo,hi = self.dst_radio.get_features().memory_bounds + lo, hi = self.dst_radio.get_features().memory_bounds
rend.set_property("text", "%i" % newloc) if newloc in self.used_list and imp: @@ -113,7 +115,7 @@ class ImportDialog(gtk.Dialog):
def _edited(self, rend, path, new, col): iter = self.__store.get_iter(path) - + if col == self.col_nloc: nloc, = self.__store.get(iter, self.col_nloc)
@@ -149,12 +151,9 @@ class ImportDialog(gtk.Dialog): import_list = [] iter = self.__store.get_iter_first() while iter: - old, new, name, comm, enb = self.__store.get(iter, - self.col_oloc, - self.col_nloc, - self.col_name, - self.col_comm, - self.col_import) + old, new, name, comm, enb = \ + self.__store.get(iter, self.col_oloc, self.col_nloc, + self.col_name, self.col_comm, self.col_import) if enb: import_list.append((old, new, name, comm)) iter = self.__store.iter_next(iter) @@ -186,7 +185,7 @@ class ImportDialog(gtk.Dialog): print "Adding %s to rcall list" % mem.dv_rpt2call rlist.append(mem.dv_rpt2call) rlist_changed = True - + if ulist_changed: job = common.RadioJob(None, "set_urcall_list", ulist) job.set_desc(_("Updating URCALL list")) @@ -196,7 +195,7 @@ class ImportDialog(gtk.Dialog): job = common.RadioJob(None, "set_repeater_call_list", ulist) job.set_desc(_("Updating RPTCALL list")) dst_rthread._qsubmit(job, 0) - + return
def _convert_power(self, dst_levels, src_levels, mem): @@ -237,7 +236,8 @@ class ImportDialog(gtk.Dialog):
if not isinstance(self.dst_radio, generic_xml.XMLRadio) and \ len(dst_banks) != len(src_banks): - print "Source and destination radios have a different number of banks" + print "Source and destination radios have " + \ + "a different number of banks" else: self.dst_radio.set_banks(src_banks)
@@ -258,8 +258,8 @@ class ImportDialog(gtk.Dialog): mem = import_logic.import_mem(self.dst_radio, src_features, src, - {"number" : new, - "name" : name, + {"number": new, + "name": name, "comment": comm}) except import_logic.ImportError, e: print e @@ -267,7 +267,8 @@ class ImportDialog(gtk.Dialog): continue
job = common.RadioJob(None, "set_memory", mem) - job.set_desc(_("Setting memory {number}").format(number=mem.number)) + desc = _("Setting memory {number}").format(number=mem.number) + job.set_desc(desc) dst_rthread._qsubmit(job, 0)
job = ImportMemoryBankJob(None, mem, self.src_radio, src) @@ -285,12 +286,12 @@ class ImportDialog(gtk.Dialog): def make_view(self): editable = [self.col_nloc, self.col_name, self.col_comm]
- self.__store = gtk.ListStore(gobject.TYPE_BOOLEAN, # Import - gobject.TYPE_INT, # Source loc - gobject.TYPE_INT, # Destination loc - gobject.TYPE_STRING, # Name - gobject.TYPE_STRING, # Frequency - gobject.TYPE_STRING, # Comment + self.__store = gtk.ListStore(gobject.TYPE_BOOLEAN, # Import + gobject.TYPE_INT, # Source loc + gobject.TYPE_INT, # Destination loc + gobject.TYPE_STRING, # Name + gobject.TYPE_STRING, # Frequency + gobject.TYPE_STRING, # Comment gobject.TYPE_BOOLEAN, gobject.TYPE_STRING) self.__view = gtk.TreeView(self.__store) @@ -330,7 +331,7 @@ class ImportDialog(gtk.Dialog): self.__view.append_column(column)
self.__view.set_tooltip_column(self.col_tmsg) - + sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.add(self.__view) @@ -387,13 +388,13 @@ class ImportDialog(gtk.Dialog): def make_select(self): hbox = gtk.HBox(True, 2)
- all = gtk.Button(_("All")); + all = gtk.Button(_("All")) all.connect("clicked", self.__select_all, True) all.set_size_request(50, 25) all.show() hbox.pack_start(all, 0, 0, 0)
- none = gtk.Button(_("None")); + none = gtk.Button(_("None")) none.connect("clicked", self.__select_all, False) none.set_size_request(50, 25) none.show() @@ -488,10 +489,10 @@ class ImportDialog(gtk.Dialog):
def make_controls(self): hbox = gtk.HBox(False, 2) - + hbox.pack_start(self.make_select(), 0, 0, 0) hbox.pack_start(self.make_adjust(), 0, 0, 0) - #hbox.pack_start(self.make_options(), 0, 0, 0) + # hbox.pack_start(self.make_options(), 0, 0, 0) hbox.show()
return hbox @@ -548,7 +549,8 @@ class ImportDialog(gtk.Dialog): mem)) except import_logic.DestNotCompatible: msgs = self.dst_radio.validate_memory(mem) - errs = [x for x in msgs if isinstance(x, chirp_common.ValidationError)] + errs = [x for x in msgs + if isinstance(x, chirp_common.ValidationError)] if errs: msg = _("Cannot be imported because") + ":\r\n" msg += ",".join(errs) @@ -567,7 +569,6 @@ class ImportDialog(gtk.Dialog): )) self.record_use_of(mem.number)
- TITLE = _("Import From File") ACTION = _("Import")
@@ -588,28 +589,28 @@ class ImportDialog(gtk.Dialog): self.col_tmsg = 7
self.caps = { - self.col_import : self.ACTION, - self.col_nloc : _("To"), - self.col_oloc : _("From"), - self.col_name : _("Name"), - self.col_freq : _("Frequency"), - self.col_comm : _("Comment"), + self.col_import: self.ACTION, + self.col_nloc: _("To"), + self.col_oloc: _("From"), + self.col_name: _("Name"), + self.col_freq: _("Frequency"), + self.col_comm: _("Comment"), }
self.tips = { - self.col_nloc : _("Location memory will be imported into"), - self.col_oloc : _("Location of memory in the file being imported"), + self.col_nloc: _("Location memory will be imported into"), + self.col_oloc: _("Location of memory in the file being imported"), }
self.types = { - self.col_import : gobject.TYPE_BOOLEAN, - self.col_oloc : gobject.TYPE_INT, - self.col_nloc : gobject.TYPE_INT, - self.col_name : gobject.TYPE_STRING, - self.col_freq : gobject.TYPE_STRING, - self.col_comm : gobject.TYPE_STRING, - self.col_okay : gobject.TYPE_BOOLEAN, - self.col_tmsg : gobject.TYPE_STRING, + self.col_import: gobject.TYPE_BOOLEAN, + self.col_oloc: gobject.TYPE_INT, + self.col_nloc: gobject.TYPE_INT, + self.col_name: gobject.TYPE_STRING, + self.col_freq: gobject.TYPE_STRING, + self.col_comm: gobject.TYPE_STRING, + self.col_okay: gobject.TYPE_BOOLEAN, + self.col_tmsg: gobject.TYPE_STRING, }
self.src_radio = src_radio @@ -629,6 +630,7 @@ class ImportDialog(gtk.Dialog):
self.ww.hide()
+ class ExportDialog(ImportDialog): TITLE = _("Export To File") ACTION = _("Export") diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 2d58449..b0396cd 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,7 +71,6 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/importdialog.py ./chirpui/mainapp.py ./chirpui/memdetail.py ./chirpui/memedit.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID a477f261fed353484090d996ef4ec98c746f398d
Fix style issues in mainapp.py (#2355)
diff --git a/chirpui/mainapp.py b/chirpui/mainapp.py index e22196a..baff031 100644 --- a/chirpui/mainapp.py +++ b/chirpui/mainapp.py @@ -22,9 +22,17 @@ from glob import glob import shutil import time import logging - import gtk import gobject + +from chirpui import inputdialog, common +from chirp import platform, generic_xml, generic_csv, directory, util +from chirp import ic9x, kenwood_live, idrp, vx7, vx5, vx6 +from chirp import CHIRP_VERSION, chirp_common, detect, errors +from chirp import icf, ic9x_icf +from chirpui import editorset, clone, miscwidgets, config, reporting, fips +from chirpui import bandplans + gobject.threads_init()
LOG = logging.getLogger(__name__) @@ -33,34 +41,29 @@ if __name__ == "__main__": import sys sys.path.insert(0, "..")
-from chirpui import inputdialog, common try: import serial -except ImportError,e: +except ImportError, e: common.log_exception() common.show_error("\nThe Pyserial module is not installed!") -from chirp import platform, generic_xml, generic_csv, directory, util -from chirp import ic9x, kenwood_live, idrp, vx7, vx5, vx6 -from chirp import CHIRP_VERSION, chirp_common, detect, errors -from chirp import icf, ic9x_icf -from chirpui import editorset, clone, miscwidgets, config, reporting, fips -from chirpui import bandplans +
CONF = config.get()
KEEP_RECENT = 8
RB_BANDS = { - "--All--" : 0, - "10 meters (29MHz)" : 29, - "6 meters (54MHz)" : 5, - "2 meters (144MHz)" : 14, - "1.25 meters (220MHz)" : 22, - "70 centimeters (440MHz)" : 4, - "33 centimeters (900MHz)" : 9, - "23 centimeters (1.2GHz)" : 12, + "--All--": 0, + "10 meters (29MHz)": 29, + "6 meters (54MHz)": 5, + "2 meters (144MHz)": 14, + "1.25 meters (220MHz)": 22, + "70 centimeters (440MHz)": 4, + "33 centimeters (900MHz)": 9, + "23 centimeters (1.2GHz)": 12, }
+ def key_bands(band): if band.startswith("-"): return -1 @@ -70,9 +73,11 @@ def key_bands(band):
return 100000 - (float(amount) * scale)
+ class ModifiedError(Exception): pass
+ class ChirpMain(gtk.Window): def get_current_editorset(self): page = self.tabs.get_current_page() @@ -112,7 +117,7 @@ class ChirpMain(gtk.Window):
for i in ["cancelq"]: set_action_sensitive(i, eset is not None and not save_sens) - + for i in ["export", "close", "columns", "irbook", "irfinder", "move_up", "move_dn", "exchange", "iradioreference", "cut", "copy", "paste", "delete", "viewdeveloper", @@ -129,7 +134,7 @@ class ChirpMain(gtk.Window):
def ev_editor_selected(self, editorset, editortype): mappings = { - "memedit" : ["view", "edit"], + "memedit": ["view", "edit"], }
for _editortype, actions in mappings.items(): @@ -159,8 +164,9 @@ class ChirpMain(gtk.Window):
label = gtk.Label("") label.set_markup("<b>-1</b> for either Mem # does a full-file hex " + - "dump with diffs highlighted.\n" + - "<b>-2</b> for first Mem # shows <b>only</b> the diffs.") + "dump with diffs highlighted.\n" + + "<b>-2</b> for first Mem # shows " + + "<b>only</b> the diffs.") d.vbox.pack_start(label, True, True, 0) label.show()
@@ -206,9 +212,9 @@ class ChirpMain(gtk.Window):
print "Selected %s@%i and %s@%i" % (sel_a, sel_chan_a, sel_b, sel_chan_b) - name_a = os.path.basename (sel_a) + name_a = os.path.basename(sel_a) name_a = name_a[:name_a.rindex(")")] - name_b = os.path.basename (sel_b) + name_b = os.path.basename(sel_b) name_b = name_b[:name_b.rindex(")")] diffwintitle = "%s@%i diff %s@%i" % ( name_a, sel_chan_a, name_b, sel_chan_b) @@ -223,14 +229,16 @@ class ChirpMain(gtk.Window):
def _get_mem_b(mem_a): # Step 2: Get memory b - job = common.RadioJob(_show_diff, "get_raw_memory", int(sel_chan_b)) + job = common.RadioJob(_show_diff, "get_raw_memory", + int(sel_chan_b)) job.set_cb_args(mem_a) eset_b.rthread.submit(job) - + if sel_chan_a >= 0 and sel_chan_b >= 0: # Diff numbered memory # Step 1: Get memory a - job = common.RadioJob(_get_mem_b, "get_raw_memory", int(sel_chan_a)) + job = common.RadioJob(_get_mem_b, "get_raw_memory", + int(sel_chan_a)) eset_a.rthread.submit(job) elif isinstance(eset_a.rthread.radio, chirp_common.CloneModeRadio) and\ isinstance(eset_b.rthread.radio, chirp_common.CloneModeRadio): @@ -249,7 +257,7 @@ class ChirpMain(gtk.Window): else: diffsonly = False common.show_diff_blob(diffwintitle, - common.simple_diff(a, b, diffsonly)) + common.simple_diff(a, b, diffsonly)) else: common.show_error("Cannot diff whole live-mode radios!")
@@ -271,7 +279,11 @@ class ChirpMain(gtk.Window):
lab = gtk.Label("""<b><big>Unable to detect model!</big></b>
-If you think that it is valid, you can select a radio model below to force an open attempt. If selecting the model manually works, please file a bug on the website and attach your image. If selecting the model does not work, it is likely that you are trying to open some other type of file. +If you think that it is valid, you can select a radio model below to +force an open attempt. If selecting the model manually works, please +file a bug on the website and attach your image. If selecting the model +does not work, it is likely that you are trying to open some other type +of file. """)
lab.set_justify(gtk.JUSTIFY_FILL) @@ -288,7 +300,7 @@ If you think that it is valid, you can select a radio model below to force an op d.vbox.set_spacing(5) choice.show() d.set_default_size(400, 200) - #d.set_resizable(False) + # d.set_resizable(False) r = d.run() d.destroy() if r != gtk.RESPONSE_OK: @@ -318,7 +330,7 @@ If you think that it is valid, you can select a radio model below to force an op self.record_recent_file(fname)
if icf.is_icf_file(fname): - a = common.ask_yesno_question(\ + a = common.ask_yesno_question( _("ICF files cannot be edited, only displayed or imported " "into another file. Open in read-only mode?"), self) @@ -378,8 +390,8 @@ If you think that it is valid, you can select a radio model below to force an op "to the radio. Because of this, you cannot perform the " "<u>Save</u> or <u>Upload</u> operations. If you wish to " "edit the contents offline, please <u>Export</u> to a CSV " - "file, using the <b>File menu</b>.").format(vendor=radio.VENDOR, - model=radio.MODEL) + "file, using the <b>File menu</b>.") + msg = msg.format(vendor=radio.VENDOR, model=radio.MODEL) d.format_secondary_markup(msg)
again = gtk.CheckButton(_("Don't show this again")) @@ -416,10 +428,10 @@ If you think that it is valid, you can select a radio model below to force an op def do_saveas(self): eset = self.get_current_editorset()
- label = _("{vendor} {model} image file").format(\ + label = _("{vendor} {model} image file").format( vendor=eset.radio.VENDOR, model=eset.radio.MODEL) - + types = [(label + " (*.%s)" % eset.radio.FILE_EXTENSION, eset.radio.FILE_EXTENSION)]
@@ -447,7 +459,7 @@ If you think that it is valid, you can select a radio model below to force an op
try: eset.save(fname) - except Exception,e: + except Exception, e: d = inputdialog.ExceptionDialog(e) d.run() d.destroy() @@ -462,7 +474,7 @@ If you think that it is valid, you can select a radio model below to force an op d.run() d.destroy()
- def cb_cloneout(self, radio, emsg= None): + def cb_cloneout(self, radio, emsg=None): radio.pipe.close() reporting.report_model_usage(radio, "upload", True) if emsg: @@ -477,7 +489,7 @@ If you think that it is valid, you can select a radio model below to force an op if fn: recent.append(fn) return recent - + def _set_recent_list(self, recent): for fn in recent: CONF.set("recent%i" % recent.index(fn), fn, "state") @@ -493,13 +505,12 @@ If you think that it is valid, you can select a radio model below to force an op self.menu_ag.remove_action(old_action)
file_basename = os.path.basename(fname).replace("_", "__") - action = gtk.Action(action_name, - "_%i. %s" % (i+1, file_basename), - _("Open recent file {name}").format(name=fname), - "") - action.connect("activate", lambda a,f: self.do_open(f), fname) + action = gtk.Action( + action_name, "_%i. %s" % (i+1, file_basename), + _("Open recent file {name}").format(name=fname), "") + action.connect("activate", lambda a, f: self.do_open(f), fname) mid = self.menu_uim.new_merge_id() - self.menu_uim.add_ui(mid, path, + self.menu_uim.add_ui(mid, path, action_name, action_name, gtk.UI_MANAGER_MENUITEM, False) self.menu_ag.add_action(action) @@ -575,13 +586,12 @@ If you think that it is valid, you can select a radio model below to force an op _("Open stock " "configuration {name}").format(name=name), "") - action.connect("activate", lambda a,c: self.do_open(c), config) + action.connect("activate", lambda a, c: self.do_open(c), config) mid = self.menu_uim.new_merge_id() mid = self.menu_uim.add_ui(mid, path, action_name, action_name, gtk.UI_MANAGER_MENUITEM, False) self.menu_ag.add_action(action) -
configs = glob(os.path.join(stock_dir, "*.csv")) for config in configs: @@ -619,7 +629,8 @@ If you think that it is valid, you can select a radio model below to force an op msg = _("{instructions}").format(instructions=message) d.format_secondary_markup(msg)
- again = gtk.CheckButton(_("Don't show instructions for any radio again")) + again = gtk.CheckButton( + _("Don't show instructions for any radio again")) again.show() d.vbox.pack_start(again, 0, 0, 0) h_button_box = d.vbox.get_children()[2] @@ -669,7 +680,8 @@ If you think that it is valid, you can select a radio model below to force an op
fn = tempfile.mktemp() if isinstance(radio, chirp_common.CloneModeRadio): - ct = clone.CloneThread(radio, "in", cb=self.cb_clonein, parent=self) + ct = clone.CloneThread(radio, "in", cb=self.cb_clonein, + parent=self) ct.start() else: self.do_open_live(radio) @@ -688,7 +700,7 @@ If you think that it is valid, you can select a radio model below to force an op return prompts = radio.get_prompts()
- if prompts.display_pre_upload_prompt_before_opening_port == True: + if prompts.display_pre_upload_prompt_before_opening_port is True: print "Opening port after pre_upload prompt." self._show_instructions(radio, prompts.pre_upload)
@@ -709,7 +721,7 @@ If you think that it is valid, you can select a radio model below to force an op d.destroy() return
- if prompts.display_pre_upload_prompt_before_opening_port == False: + if prompts.display_pre_upload_prompt_before_opening_port is False: print "Opening port before pre_upload prompt." self._show_instructions(radio, prompts.pre_upload)
@@ -728,11 +740,11 @@ If you think that it is valid, you can select a radio model below to force an op return False
if eset.is_modified(): - dlg = miscwidgets.YesNoDialog(title=_("Save Changes?"), - parent=self, - buttons=(gtk.STOCK_YES, gtk.RESPONSE_YES, - gtk.STOCK_NO, gtk.RESPONSE_NO, - gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) + dlg = miscwidgets.YesNoDialog( + title=_("Save Changes?"), parent=self, + buttons=(gtk.STOCK_YES, gtk.RESPONSE_YES, + gtk.STOCK_NO, gtk.RESPONSE_NO, + gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) dlg.set_text(_("File is modified, save changes before closing?")) res = dlg.run() dlg.destroy() @@ -744,7 +756,7 @@ If you think that it is valid, you can select a radio model below to force an op
eset.rthread.stop() eset.rthread.join() - + eset.prepare_close()
if eset.radio.pipe: @@ -785,11 +797,11 @@ If you think that it is valid, you can select a radio model below to force an op def do_repeaterbook_prompt(self): if not CONF.get_bool("has_seen_credit", "repeaterbook"): d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) - d.set_markup("<big><big><b>RepeaterBook</b></big>\r\n" + \ - "<i>North American Repeater Directory</i></big>") - d.format_secondary_markup("For more information about this " +\ - "free service, please go to\r\n" +\ - "http://www.repeaterbook.com") + d.set_markup("<big><big><b>RepeaterBook</b></big>\r\n" + + "<i>North American Repeater Directory</i></big>") + d.format_secondary_markup("For more information about this " + + "free service, please go to\r\n" + + "http://www.repeaterbook.com") d.run() d.destroy() CONF.set_bool("has_seen_credit", True, "repeaterbook") @@ -802,19 +814,20 @@ If you think that it is valid, you can select a radio model below to force an op code = int(CONF.get("state", "repeaterbook")) except: code = CONF.get("state", "repeaterbook") - for k,v in fips.FIPS_STATES.items(): + for k, v in fips.FIPS_STATES.items(): if code == v: default_state = k break
code = CONF.get("county", "repeaterbook") - for k,v in fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].items(): + items = fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].items() + for k, v in items: if code == v: default_county = k break
code = int(CONF.get("band", "repeaterbook")) - for k,v in RB_BANDS.items(): + for k, v in RB_BANDS.items(): if code == v: default_band = k break @@ -823,18 +836,21 @@ If you think that it is valid, you can select a radio model below to force an op
state = miscwidgets.make_choice(sorted(fips.FIPS_STATES.keys()), False, default_state) - county = miscwidgets.make_choice(sorted(fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].keys()), - False, default_county) + county = miscwidgets.make_choice( + sorted(fips.FIPS_COUNTIES[fips.FIPS_STATES[default_state]].keys()), + False, default_county) band = miscwidgets.make_choice(sorted(RB_BANDS.keys(), key=key_bands), False, default_band) + def _changed(box, county): state = fips.FIPS_STATES[box.get_active_text()] county.get_model().clear() for fips_county in sorted(fips.FIPS_COUNTIES[state].keys()): county.append_text(fips_county) county.set_active(0) + state.connect("changed", _changed, county) - + d = inputdialog.FieldDialog(title=_("RepeaterBook Query"), parent=self) d.add_field("State", state) d.add_field("County", county) @@ -866,22 +882,24 @@ If you think that it is valid, you can select a radio model below to force an op try: code = CONF.get("state", "repeaterbook") except: - code = '41' # Oregon default + code = '41' # Oregon default
try: county = CONF.get("county", "repeaterbook") except: - county = '%' # --All-- default + county = '%' # --All-- default
try: band = int(CONF.get("band", "repeaterbook")) except: - band = 14 # 2m default + band = 14 # 2m default
- query = "http://www.repeaterbook.com/repeaters/downloads/chirp.php?" + \ - "func=default&state_id=%s&band=%s&freq=%%&band6=%%&loc=%%" + \ + query = "http://www.repeaterbook.com/repeaters/downloads/chirp.php" + \ + "?func=default&state_id=%s&band=%s&freq=%%&band6=%%&loc=%%" + \ "&county_id=%s&status_id=%%&features=%%&coverage=%%&use=%%" - query = query % (code, band and band or "%%", county and county or "%%") + query = query % (code, + band and band or "%%", + county and county or "%%")
# Do this in case the import process is going to take a while # to make sure we process events leading up to this @@ -1009,16 +1027,12 @@ If you think that it is valid, you can select a radio model below to force an op self.do_open_live(radio, read_only=True)
def do_rfinder_prompt(self): - fields = {"1Email" : (gtk.Entry(), - lambda x: "@" in x), - "2Password" : (gtk.Entry(), - lambda x: x), - "3Latitude" : (gtk.Entry(), - lambda x: float(x) < 90 and \ - float(x) > -90), - "4Longitude": (gtk.Entry(), - lambda x: float(x) < 180 and \ - float(x) > -180), + fields = {"1Email": (gtk.Entry(), lambda x: "@" in x), + "2Password": (gtk.Entry(), lambda x: x), + "3Latitude": (gtk.Entry(), + lambda x: float(x) < 90 and float(x) > -90), + "4Longitude": (gtk.Entry(), + lambda x: float(x) < 180 and float(x) > -180), "5Range_in_Miles": (gtk.Entry(), lambda x: int(x) > 0 and int(x) < 5000), } @@ -1070,7 +1084,9 @@ If you think that it is valid, you can select a radio model below to force an op
if do_import: eset = self.get_current_editorset() - count = eset.do_import("rfinder://%s/%s/%f/%f/%i" % (email, passwd, lat, lon, miles)) + rfstr = "rfinder://%s/%s/%f/%f/%i" % \ + (email, passwd, lat, lon, miles) + count = eset.do_import(rfstr) else: from chirp import rfinder radio = rfinder.RFinderRadio(None) @@ -1080,9 +1096,9 @@ If you think that it is valid, you can select a radio model below to force an op self.window.set_cursor(None)
def do_radioreference_prompt(self): - fields = {"1Username" : (gtk.Entry(), lambda x: x), - "2Password" : (gtk.Entry(), lambda x: x), - "3Zipcode" : (gtk.Entry(), lambda x: x), + fields = {"1Username": (gtk.Entry(), lambda x: x), + "2Password": (gtk.Entry(), lambda x: x), + "3Zipcode": (gtk.Entry(), lambda x: x), }
d = inputdialog.FieldDialog(title=_("RadioReference.com Query"), @@ -1131,7 +1147,8 @@ If you think that it is valid, you can select a radio model below to force an op
if do_import: eset = self.get_current_editorset() - count = eset.do_import("radioreference://%s/%s/%s" % (zipcode, username, passwd)) + rrstr = "radioreference://%s/%s/%s" % (zipcode, username, passwd) + count = eset.do_import(rrstr) else: try: from chirp import radioreference @@ -1178,7 +1195,7 @@ If you think that it is valid, you can select a radio model below to force an op d = gtk.AboutDialog() d.set_transient_for(self) import sys - verinfo = "GTK %s\nPyGTK %s\nPython %s\n" % ( \ + verinfo = "GTK %s\nPyGTK %s\nPython %s\n" % ( ".".join([str(x) for x in gtk.gtk_version]), ".".join([str(x) for x in gtk.pygtk_version]), sys.version.split()[0]) @@ -1210,7 +1227,7 @@ If you think that it is valid, you can select a radio model below to force an op os.linesep + "Portuguese (BR): Crezivando PP7CJ") d.set_comments(verinfo) - + d.run() d.destroy()
@@ -1238,12 +1255,13 @@ If you think that it is valid, you can select a radio model below to force an op d.set_size_request(-1, 300) d.set_resizable(False)
- label = gtk.Label(_("Visible columns for {radio}").format(radio=radio_name)) + labelstr = _("Visible columns for {radio}").format(radio=radio_name) + label = gtk.Label(labelstr) label.show() vbox.pack_start(label)
fields = [] - memedit = eset.get_current_editor() #.editors["memedit"] + memedit = eset.get_current_editor() # .editors["memedit"] unsupported = memedit.get_unsupported_columns() for colspec in memedit.cols: if colspec[0].startswith("_"): @@ -1266,7 +1284,7 @@ If you think that it is valid, you can select a radio model below to force an op memedit.set_column_visible(colnum, widget.get_active()) if widget.get_active(): selected_columns.append(widget.get_label()) - + d.destroy()
CONF.set(driver, ",".join(selected_columns), "memedit_columns") @@ -1299,18 +1317,18 @@ If you think that it is valid, you can select a radio model below to force an op
def do_toggle_report(self, action): if not action.get_active(): - d = gtk.MessageDialog(buttons=gtk.BUTTONS_YES_NO, - parent=self) - d.set_markup("<b><big>" + _("Reporting is disabled") + "</big></b>") + d = gtk.MessageDialog(buttons=gtk.BUTTONS_YES_NO, parent=self) + markup = "<b><big>" + _("Reporting is disabled") + "</big></b>" + d.set_markup(markup) msg = _("The reporting feature of CHIRP is designed to help " "<u>improve quality</u> by allowing the authors to focus " "on the radio drivers used most often and errors " "experienced by the users. The reports contain no " - "identifying information and are used only for statistical " - "purposes by the authors. Your privacy is extremely " - "important, but <u>please consider leaving this feature " - "enabled to help make CHIRP better!</u>\n\n<b>Are you " - "sure you want to disable this feature?</b>") + "identifying information and are used only for " + "statistical purposes by the authors. Your privacy is " + "extremely important, but <u>please consider leaving " + "this feature enabled to help make CHIRP better!</u>\n\n" + "<b>Are you sure you want to disable this feature?</b>") d.format_secondary_markup(msg.replace("\n", "\r\n")) r = d.run() d.destroy() @@ -1513,7 +1531,7 @@ If you think that it is valid, you can select a radio model below to force an op </menubar> </ui> """ - actions = [\ + actions = [ ('file', None, _("_File"), None, None, self.mh), ('new', gtk.STOCK_NEW, None, None, None, self.mh), ('open', gtk.STOCK_OPEN, None, None, None, self.mh), @@ -1530,36 +1548,49 @@ If you think that it is valid, you can select a radio model below to force an op ('paste', None, _("_Paste"), "<Ctrl>v", None, self.mh), ('delete', None, _("_Delete"), "Delete", None, self.mh), ('all', None, _("Select _All"), None, None, self.mh), - ('move_up', None, _("Move _Up"), "<Control>Up", None, self.mh), - ('move_dn', None, _("Move Dow_n"), "<Control>Down", None, self.mh), - ('exchange', None, _("E_xchange"), "<Control><Shift>x", None, self.mh), + ('move_up', None, _("Move _Up"), + "<Control>Up", None, self.mh), + ('move_dn', None, _("Move Dow_n"), + "<Control>Down", None, self.mh), + ('exchange', None, _("E_xchange"), + "<Control><Shift>x", None, self.mh), ('properties', None, _("P_roperties"), None, None, self.mh), ('view', None, _("_View"), None, None, self.mh), ('columns', None, _("Columns"), None, None, self.mh), ('viewdeveloper', None, _("Developer"), None, None, self.mh), - ('devshowraw', None, _('Show raw memory'), "<Control><Shift>r", None, self.mh), - ('devdiffraw', None, _("Diff raw memories"), "<Control><Shift>d", None, self.mh), - ('devdifftab', None, _("Diff tabs"), "<Control><Shift>t", None, self.mh), + ('devshowraw', None, _('Show raw memory'), + "<Control><Shift>r", None, self.mh), + ('devdiffraw', None, _("Diff raw memories"), + "<Control><Shift>d", None, self.mh), + ('devdifftab', None, _("Diff tabs"), + "<Control><Shift>t", None, self.mh), ('language', None, _("Change language"), None, None, self.mh), ('radio', None, _("_Radio"), None, None, self.mh), - ('download', None, _("Download From Radio"), "<Alt>d", None, self.mh), + ('download', None, _("Download From Radio"), + "<Alt>d", None, self.mh), ('upload', None, _("Upload To Radio"), "<Alt>u", None, self.mh), ('import', None, _("Import"), "<Alt>i", None, self.mh), ('export', None, _("Export"), "<Alt>x", None, self.mh), - ('importsrc', None, _("Import from data source"), None, None, self.mh), - ('iradioreference', None, _("RadioReference.com"), None, None, self.mh), + ('importsrc', None, _("Import from data source"), + None, None, self.mh), + ('iradioreference', None, _("RadioReference.com"), + None, None, self.mh), ('irfinder', None, _("RFinder"), None, None, self.mh), ('irbook', None, _("RepeaterBook"), None, None, self.mh), ('ipr', None, _("przemienniki.net"), None, None, self.mh), ('querysrc', None, _("Query data source"), None, None, self.mh), - ('qradioreference', None, _("RadioReference.com"), None, None, self.mh), + ('qradioreference', None, _("RadioReference.com"), + None, None, self.mh), ('qrfinder', None, _("RFinder"), None, None, self.mh), ('qpr', None, _("przemienniki.net"), None, None, self.mh), ('qrbook', None, _("RepeaterBook"), None, None, self.mh), - ('export_chirp', None, _("CHIRP Native File"), None, None, self.mh), + ('export_chirp', None, _("CHIRP Native File"), + None, None, self.mh), ('export_csv', None, _("CSV File"), None, None, self.mh), - ('stock', None, _("Import from stock config"), None, None, self.mh), - ('channel_defaults', None, _("Channel defaults"), None, None, self.mh), + ('stock', None, _("Import from stock config"), + None, None, self.mh), + ('channel_defaults', None, _("Channel defaults"), + None, None, self.mh), ('cancelq', gtk.STOCK_STOP, None, "Escape", None, self.mh), ('help', None, _('Help'), None, None, self.mh), ('about', gtk.STOCK_ABOUT, None, None, None, self.mh), @@ -1567,17 +1598,20 @@ If you think that it is valid, you can select a radio model below to force an op ]
conf = config.get() - re = not conf.get_bool("no_report"); + re = not conf.get_bool("no_report") hu = conf.get_bool("hide_unused", "memedit", default=True) dv = conf.get_bool("developer", "state") st = not conf.get_bool("no_smart_tmode", "memedit")
- toggles = [\ - ('report', None, _("Report statistics"), None, None, self.mh, re), - ('hide_unused', None, _("Hide Unused Fields"), None, None, self.mh, hu), - ('no_smart_tmode', None, _("Smart Tone Modes"), None, None, self.mh, st), - ('developer', None, _("Enable Developer Functions"), None, None, self.mh, dv), - ] + toggles = [('report', None, _("Report statistics"), + None, None, self.mh, re), + ('hide_unused', None, _("Hide Unused Fields"), + None, None, self.mh, hu), + ('no_smart_tmode', None, _("Smart Tone Modes"), + None, None, self.mh, st), + ('developer', None, _("Enable Developer Functions"), + None, None, self.mh, dv), + ]
self.menu_uim = gtk.UIManager() self.menu_ag = gtk.ActionGroup("MenuBar") @@ -1599,7 +1633,7 @@ If you think that it is valid, you can select a radio model below to force an op def make_tabs(self): self.tabs = gtk.Notebook()
- return self.tabs + return self.tabs
def close_out(self): num = self.tabs.get_n_pages() @@ -1621,28 +1655,29 @@ If you think that it is valid, you can select a radio model below to force an op self.sb_general = gtk.Statusbar() self.sb_general.set_has_resize_grip(False) self.sb_general.show() - box.pack_start(self.sb_general, 1,1,1) - + box.pack_start(self.sb_general, 1, 1, 1) + self.sb_radio = gtk.Statusbar() self.sb_radio.set_has_resize_grip(True) self.sb_radio.show() - box.pack_start(self.sb_radio, 1,1,1) + box.pack_start(self.sb_radio, 1, 1, 1)
box.show() return box
def ev_delete(self, window, event): if not self.close_out(): - return True # Don't exit + return True # Don't exit
def ev_destroy(self, window): if not self.close_out(): - return True # Don't exit + return True # Don't exit
def setup_extra_hotkeys(self): accelg = self.menu_uim.get_accel_group()
- memedit = lambda a: self.get_current_editorset().editors["memedit"].hotkey(a) + def memedit(a): + self.get_current_editorset().editors["memedit"].hotkey(a)
actions = [ # ("action_name", "key", function) @@ -1654,7 +1689,7 @@ If you think that it is valid, you can select a radio model below to force an op self.menu_ag.add_action_with_accel(a, key) a.set_accel_group(accelg) a.connect_accelerator() - + def _set_icon(self): execpath = platform.get_platform().executable_path() path = os.path.abspath(os.path.join(execpath, "share", "chirp.png")) @@ -1679,7 +1714,7 @@ If you think that it is valid, you can select a radio model below to force an op intv = 3600 * 24 * 7
if CONF.is_defined("last_update_check", "state") and \ - (time.time() - CONF.get_int("last_update_check", "state")) < intv: + (time.time() - CONF.get_int("last_update_check", "state")) < intv: return
CONF.set_int("last_update_check", int(time.time()), "state") @@ -1700,7 +1735,7 @@ If you think that it is valid, you can select a radio model below to force an op except ImportError, e: print "No MacOS support: %s" % e return - + menu_bar.hide() macapp.set_menu_bar(menu_bar)
@@ -1712,7 +1747,7 @@ If you think that it is valid, you can select a radio model below to force an op
documentationitem = self.menu_uim.get_widget("/MenuBar/help/gethelp") macapp.insert_app_menu_item(documentationitem, 0) - + macapp.set_use_quartz_accelerators(False) macapp.ready()
@@ -1746,7 +1781,7 @@ If you think that it is valid, you can select a radio model below to force an op mbar = self.make_menubar()
if os.name != "nt": - self._set_icon() # Windows gets the icon from the exe + self._set_icon() # Windows gets the icon from the exe if os.uname()[0] == "Darwin": self._init_macos(mbar)
@@ -1787,7 +1822,7 @@ If you think that it is valid, you can select a radio model below to force an op d.set_markup("<b><big>" + _("Error reporting is enabled") + "</big></b>") - d.format_secondary_markup(\ + d.format_secondary_markup( _("If you wish to disable this feature you may do so in " "the <u>Help</u> menu")) d.run() diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index b0396cd..e1d57a9 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,7 +71,6 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/mainapp.py ./chirpui/memdetail.py ./chirpui/memedit.py ./chirpui/miscwidgets.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID edddddf99ffbc05cb97da851d45cef317e45782f
Fix style issues in memdetail.py (#2355)
diff --git a/chirpui/memdetail.py b/chirpui/memdetail.py index 0f40001..120fe5b 100644 --- a/chirpui/memdetail.py +++ b/chirpui/memdetail.py @@ -21,6 +21,7 @@ from chirpui import miscwidgets, common
POL = ["NN", "NR", "RN", "RR"]
+ class ValueEditor: """Base class""" def __init__(self, features, memory, errfn, name, data=None): @@ -49,7 +50,8 @@ class ValueEditor: return getattr(self._memory, self._name)
def _get_value(self): - """Returns the value from the widget that should be set in the memory""" + """Returns the value from the widget that + should be set in the memory"""
def update(self): """Updates the memory object with self._getvalue()""" @@ -87,6 +89,7 @@ class ValueEditor: else: self._errfn(self._name, None)
+ class StringEditor(ValueEditor): def _init(self, data): self._widget = gtk.Entry(int(data)) @@ -99,6 +102,7 @@ class StringEditor(ValueEditor): def changed(self, _widget): self.update()
+ class ChoiceEditor(ValueEditor): def _init(self, data): self._widget = miscwidgets.make_choice([str(x) for x in data], @@ -112,6 +116,7 @@ class ChoiceEditor(ValueEditor): def changed(self, _widget): self.update()
+ class PowerChoiceEditor(ChoiceEditor): def _init(self, data): self._choices = data @@ -124,14 +129,17 @@ class PowerChoiceEditor(ChoiceEditor): return level raise Exception("Internal error: power level went missing")
+ class IntChoiceEditor(ChoiceEditor): def _get_value(self): return int(self._widget.get_active_text())
+ class FloatChoiceEditor(ChoiceEditor): def _get_value(self): return float(self._widget.get_active_text())
+ class FreqEditor(StringEditor): def _init(self, data): StringEditor._init(self, 0) @@ -142,6 +150,7 @@ class FreqEditor(StringEditor): def _get_value(self): return chirp_common.parse_freq(self._widget.get_text())
+ class BooleanEditor(ValueEditor): def _init(self, data): self._widget = gtk.CheckButton("Enabled") @@ -154,29 +163,31 @@ class BooleanEditor(ValueEditor): def toggled(self, _widget): self.update()
+ class OffsetEditor(FreqEditor): pass
+ class MemoryDetailEditor(gtk.Dialog): """Detail editor for a memory"""
- def _add(self, tab, row, name, editor, text, colindex = 0): + def _add(self, tab, row, name, editor, text, colindex=0): label = gtk.Label(text + ":") label.set_alignment(0.0, 0.5) label.show() - tab.attach(label, colindex, colindex + 1, row, row + 1, - xoptions=gtk.FILL, yoptions=0, xpadding=6, ypadding=3) + tab.attach(label, colindex, colindex + 1, row, row + 1, + xoptions=gtk.FILL, yoptions=0, xpadding=6, ypadding=3)
widget = editor.get_widget() widget.show() - tab.attach(widget, colindex + 1, colindex + 2, row, row + 1, - xoptions=gtk.FILL, yoptions=0, xpadding=3, ypadding=3) + tab.attach(widget, colindex + 1, colindex + 2, row, row + 1, + xoptions=gtk.FILL, yoptions=0, xpadding=3, ypadding=3)
img = gtk.Image() img.set_size_request(16, -1) img.show() - tab.attach(img, colindex + 2, colindex + 3, row, row + 1, - xoptions=gtk.FILL, yoptions=0, xpadding=3, ypadding=3) + tab.attach(img, colindex + 2, colindex + 3, row, row + 1, + xoptions=gtk.FILL, yoptions=0, xpadding=3, ypadding=3)
self._editors[name] = label, editor, img return label, editor, img @@ -186,7 +197,7 @@ class MemoryDetailEditor(gtk.Dialog): self._tips.set_tip(label, doc)
def _make_ui(self): - + box = gtk.VBox() box.show()
@@ -218,7 +229,8 @@ class MemoryDetailEditor(gtk.Dialog): _img.clear() self._tips.set_tip(_img, "") else: - _img.set_from_stock(gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_MENU) + _img.set_from_stock(gtk.STOCK_DIALOG_WARNING, + gtk.ICON_SIZE_MENU) self._tips.set_tip(_img, str(msg)) self._errors[self._order.index(name)] = msg is not None self.set_response_sensitive(gtk.RESPONSE_OK, @@ -256,20 +268,21 @@ class MemoryDetailEditor(gtk.Dialog): settings.RadioSettingValueBoolean): editor = BooleanEditor(self._features, self._memory, _err, name) - self._add(table, row, name, editor, setting.get_shortname()) + self._add(table, row, name, editor, + setting.get_shortname()) self._set_doc(name, setting.__doc__) elif isinstance(setting.value, settings.RadioSettingValueList): - editor = ChoiceEditor(self._features, self._memory, - _err, name, setting.value.get_options()) - self._add(table, row, name, editor, setting.get_shortname()) + editor = ChoiceEditor(self._features, self._memory, _err, + name, setting.value.get_options()) + self._add(table, row, name, editor, + setting.get_shortname()) self._set_doc(name, setting.__doc__) row += 1 self._order.append(name)
self.vbox.pack_start(notebook, 1, 1, 1)
- def __init__(self, features, memory, parent=None): self._memory = memory gtk.Dialog.__init__(self, @@ -282,41 +295,41 @@ class MemoryDetailEditor(gtk.Dialog): self._tips = gtk.Tooltips()
self._features = features - + self._editors = {} self._elements = { - "freq" : (_("Frequency"), - FreqEditor, None), - "name" : (_("Name"), - StringEditor, features.valid_name_length), - "tmode" : (_("Tone Mode"), - ChoiceEditor, features.valid_tmodes), - "rtone" : (_("Tone"), - FloatChoiceEditor, chirp_common.TONES), - "ctone" : (_("ToneSql"), - FloatChoiceEditor, chirp_common.TONES), - "dtcs" : (_("DTCS Code"), - IntChoiceEditor, chirp_common.DTCS_CODES), - "rx_dtcs" : (_("RX DTCS Code"), - IntChoiceEditor, chirp_common.DTCS_CODES), - "dtcs_polarity" : (_("DTCS Pol"), - ChoiceEditor, POL), - "cross_mode" : (_("Cross mode"), - ChoiceEditor, features.valid_cross_modes), - "duplex" : (_("Duplex"), - ChoiceEditor, features.valid_duplexes), - "offset" : (_("Offset"), - OffsetEditor, None), - "mode" : (_("Mode"), - ChoiceEditor, features.valid_modes), - "tuning_step" : (_("Tune Step"), - FloatChoiceEditor, features.valid_tuning_steps), - "skip" : (_("Skip"), - ChoiceEditor, features.valid_skips), - "power": (_("Power"), - PowerChoiceEditor, features.valid_power_levels), - "comment" : (_("Comment"), - StringEditor, 256), + "freq": (_("Frequency"), + FreqEditor, None), + "name": (_("Name"), + StringEditor, features.valid_name_length), + "tmode": (_("Tone Mode"), + ChoiceEditor, features.valid_tmodes), + "rtone": (_("Tone"), + FloatChoiceEditor, chirp_common.TONES), + "ctone": (_("ToneSql"), + FloatChoiceEditor, chirp_common.TONES), + "dtcs": (_("DTCS Code"), + IntChoiceEditor, chirp_common.DTCS_CODES), + "rx_dtcs": (_("RX DTCS Code"), + IntChoiceEditor, chirp_common.DTCS_CODES), + "dtcs_polarity": (_("DTCS Pol"), + ChoiceEditor, POL), + "cross_mode": (_("Cross mode"), + ChoiceEditor, features.valid_cross_modes), + "duplex": (_("Duplex"), + ChoiceEditor, features.valid_duplexes), + "offset": (_("Offset"), + OffsetEditor, None), + "mode": (_("Mode"), + ChoiceEditor, features.valid_modes), + "tuning_step": (_("Tune Step"), + FloatChoiceEditor, features.valid_tuning_steps), + "skip": (_("Skip"), + ChoiceEditor, features.valid_skips), + "power": (_("Power"), + PowerChoiceEditor, features.valid_power_levels), + "comment": (_("Comment"), + StringEditor, 256), }
self._order = [ @@ -370,6 +383,7 @@ class MemoryDetailEditor(gtk.Dialog): self._memory.empty = False return self._memory
+ class MultiMemoryDetailEditor(MemoryDetailEditor):
def __init__(self, features, memory, parent=None): @@ -381,13 +395,13 @@ class MultiMemoryDetailEditor(MemoryDetailEditor): widget.set_sensitive(selector.get_active())
def _add(self, tab, row, name, editor, text): - + label, editor, img = super(MultiMemoryDetailEditor, self)._add( tab, row, name, editor, text, 1)
selector = gtk.CheckButton() tab.attach(selector, 0, 1, row, row + 1, - xoptions=gtk.FILL, yoptions=0, xpadding=0, ypadding=3) + xoptions=gtk.FILL, yoptions=0, xpadding=0, ypadding=3) selector.show() self._toggle_selector(selector, label, editor, img) selector.connect("toggled", self._toggle_selector, label, editor, img) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index e1d57a9..03dbba8 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,7 +71,6 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/memdetail.py ./chirpui/memedit.py ./chirpui/miscwidgets.py ./chirpui/reporting.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID c1a6fcb59602346eaaf2a9e3ceef374e2567271f
Fix style issues in memedit.py (#2355)
diff --git a/chirpui/memedit.py b/chirpui/memedit.py index 5927114..89f4d4b 100644 --- a/chirpui/memedit.py +++ b/chirpui/memedit.py @@ -14,10 +14,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/.
-if __name__ == "__main__": - import sys - sys.path.insert(0, "..") - import threading
import gtk @@ -36,8 +32,15 @@ from chirpui import common, shiftdialog, miscwidgets, config, memdetail from chirpui import bandplans from chirp import chirp_common, errors, directory, import_logic
+ +if __name__ == "__main__": + import sys + sys.path.insert(0, "..") + + def handle_toggle(_, path, store, col): - store[path][col] = not store[path][col] + store[path][col] = not store[path][col] +
def handle_ed(_, iter, new, store, col): old, = store.get(iter, col) @@ -47,75 +50,78 @@ def handle_ed(_, iter, new, store, col): else: return False
+ class ValueErrorDialog(gtk.MessageDialog): def __init__(self, exception, **args): gtk.MessageDialog.__init__(self, buttons=gtk.BUTTONS_OK, **args) self.set_property("text", _("Invalid value for this field")) self.format_secondary_text(str(exception))
+ def iter_prev(store, iter): row = store.get_path(iter)[0] if row == 0: return None return store.get_iter((row - 1,))
+ class MemoryEditor(common.Editor): cols = [ - (_("Loc") , TYPE_INT, gtk.CellRendererText, ), - (_("Frequency") , TYPE_INT64, gtk.CellRendererText, ), - (_("Name") , TYPE_STRING, gtk.CellRendererText, ), - (_("Tone Mode") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Tone") , TYPE_FLOAT, gtk.CellRendererCombo, ), - (_("ToneSql") , TYPE_FLOAT, gtk.CellRendererCombo, ), - (_("DTCS Code") , TYPE_INT, gtk.CellRendererCombo, ), - (_("DTCS Rx Code") , TYPE_INT, gtk.CellRendererCombo, ), - (_("DTCS Pol") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Cross Mode") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Duplex") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Offset") , TYPE_INT64, gtk.CellRendererText, ), - (_("Mode") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Power") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Tune Step") , TYPE_FLOAT, gtk.CellRendererCombo, ), - (_("Skip") , TYPE_STRING, gtk.CellRendererCombo, ), - (_("Comment") , TYPE_STRING, gtk.CellRendererText, ), - ("_filled" , TYPE_BOOLEAN, None, ), - ("_hide_cols" , TYPE_PYOBJECT,None, ), - ("_extd" , TYPE_STRING, None, ), + (_("Loc"), TYPE_INT, gtk.CellRendererText,), + (_("Frequency"), TYPE_INT64, gtk.CellRendererText,), + (_("Name"), TYPE_STRING, gtk.CellRendererText,), + (_("Tone Mode"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Tone"), TYPE_FLOAT, gtk.CellRendererCombo,), + (_("ToneSql"), TYPE_FLOAT, gtk.CellRendererCombo,), + (_("DTCS Code"), TYPE_INT, gtk.CellRendererCombo,), + (_("DTCS Rx Code"), TYPE_INT, gtk.CellRendererCombo,), + (_("DTCS Pol"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Cross Mode"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Duplex"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Offset"), TYPE_INT64, gtk.CellRendererText,), + (_("Mode"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Power"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Tune Step"), TYPE_FLOAT, gtk.CellRendererCombo,), + (_("Skip"), TYPE_STRING, gtk.CellRendererCombo,), + (_("Comment"), TYPE_STRING, gtk.CellRendererText,), + ("_filled", TYPE_BOOLEAN, None,), + ("_hide_cols", TYPE_PYOBJECT, None,), + ("_extd", TYPE_STRING, None,), ]
defaults = { - _("Name") : "", - _("Frequency") : 146010000, - _("Tone") : 88.5, - _("ToneSql") : 88.5, - _("DTCS Code") : 23, - _("DTCS Rx Code") : 23, - _("DTCS Pol") : "NN", - _("Cross Mode") : "Tone->Tone", - _("Duplex") : "", - _("Offset") : 0, - _("Mode") : "FM", - _("Power") : "", - _("Tune Step") : 5.0, - _("Tone Mode") : "", - _("Skip") : "", - _("Comment") : "", + _("Name"): "", + _("Frequency"): 146010000, + _("Tone"): 88.5, + _("ToneSql"): 88.5, + _("DTCS Code"): 23, + _("DTCS Rx Code"): 23, + _("DTCS Pol"): "NN", + _("Cross Mode"): "Tone->Tone", + _("Duplex"): "", + _("Offset"): 0, + _("Mode"): "FM", + _("Power"): "", + _("Tune Step"): 5.0, + _("Tone Mode"): "", + _("Skip"): "", + _("Comment"): "", }
choices = { - _("Tone") : chirp_common.TONES, - _("ToneSql") : chirp_common.TONES, - _("DTCS Code") : chirp_common.ALL_DTCS_CODES, - _("DTCS Rx Code") : chirp_common.ALL_DTCS_CODES, - _("DTCS Pol") : ["NN", "NR", "RN", "RR"], - _("Mode") : chirp_common.MODES, - _("Power") : [], - _("Duplex") : ["", "-", "+", "split", "off"], - _("Tune Step") : chirp_common.TUNING_STEPS, - _("Tone Mode") : ["", "Tone", "TSQL", "DTCS"], - _("Cross Mode") : chirp_common.CROSS_MODES, + _("Tone"): chirp_common.TONES, + _("ToneSql"): chirp_common.TONES, + _("DTCS Code"): chirp_common.ALL_DTCS_CODES, + _("DTCS Rx Code"): chirp_common.ALL_DTCS_CODES, + _("DTCS Pol"): ["NN", "NR", "RN", "RR"], + _("Mode"): chirp_common.MODES, + _("Power"): [], + _("Duplex"): ["", "-", "+", "split", "off"], + _("Tune Step"): chirp_common.TUNING_STEPS, + _("Tone Mode"): ["", "Tone", "TSQL", "DTCS"], + _("Cross Mode"): chirp_common.CROSS_MODES, } - + def ed_name(self, _, __, new, ___): return self.rthread.radio.filter_name(new)
@@ -136,7 +142,7 @@ class MemoryEditor(common.Editor): dup = "-" offset *= -1
- if not dup in self.choices[_("Duplex")]: + if dup not in self.choices[_("Duplex")]: print "Duplex %s not supported by this radio" % dup return
@@ -203,7 +209,7 @@ class MemoryEditor(common.Editor):
def ed_duplex(self, _foo1, path, new, _foo2): if new == "": - return # Fast path outta here + return # Fast path outta here
iter = self.store.get_iter(path) freq, = self.store.get(iter, self.col(_("Frequency"))) @@ -234,6 +240,7 @@ class MemoryEditor(common.Editor): if modes[0] not in tmodes: modes[0] = tmodes[0] self.store.set(iter, self.col(_("Tone Mode")), modes[0]) + def _cm(*cmodes): if modes[0] == "Cross" and modes[1] not in cmodes: modes[1] = cmodes[0] @@ -314,7 +321,6 @@ class MemoryEditor(common.Editor): if duplex == "" or duplex == "(None)" or duplex == "off": hide += [self.col(_("Offset"))]
- return hide
def maybe_hide_cols(self, iter): @@ -327,19 +333,19 @@ class MemoryEditor(common.Editor): return
iter = self.store.get_iter(path) - if not self.store.get(iter, self.col("_filled"))[0] \ - and self.store.get(iter, self.col(_("Frequency")))[0] == 0: + if not self.store.get(iter, self.col("_filled"))[0] and \ + self.store.get(iter, self.col(_("Frequency")))[0] == 0: print _("Editing new item, taking defaults") self.insert_new(iter)
colnum = self.col(cap) funcs = { - _("Loc") : self.ed_loc, - _("Name") : self.ed_name, - _("Frequency") : self.ed_freq, - _("Duplex") : self.ed_duplex, - _("Offset") : self.ed_offset, - _("Tone") : self.ed_tone_field, + _("Loc"): self.ed_loc, + _("Name"): self.ed_name, + _("Frequency"): self.ed_freq, + _("Duplex"): self.ed_duplex, + _("Offset"): self.ed_offset, + _("Tone"): self.ed_tone_field, _("ToneSql"): self.ed_tone_field, _("DTCS Code"): self.ed_tone_field, _("DTCS Rx Code"): self.ed_tone_field, @@ -347,7 +353,7 @@ class MemoryEditor(common.Editor): _("Cross Mode"): self.ed_tone_field, }
- if funcs.has_key(cap): + if cap in func: new = funcs[cap](rend, path, new, colnum)
if new is None: @@ -375,8 +381,8 @@ class MemoryEditor(common.Editor):
msgs = self.rthread.radio.validate_memory(mem) if msgs: - common.show_error(_("Error setting memory") + ": " + \ - "\r\n\r\n".join(msgs)) + common.show_error(_("Error setting memory") + ": " + + "\r\n\r\n".join(msgs)) self.prefill() return
@@ -414,7 +420,6 @@ class MemoryEditor(common.Editor): if extd: val = extd
- return val
def render(self, _, rend, model, iter, colnum): @@ -427,14 +432,14 @@ class MemoryEditor(common.Editor): for key, val in self.defaults.items(): line.append(self.col(key)) line.append(val) - + if not loc: loc, = self.store.get(iter, self.col(_("Loc")))
self.store.set(iter, 0, loc, *tuple(line)) - + return self._get_memory(iter)
def insert_easy(self, store, _iter, delta): @@ -454,12 +459,12 @@ class MemoryEditor(common.Editor): self.rthread.submit(job)
def insert_hard(self, store, _iter, delta, warn=True): - if isinstance(self.rthread.radio, chirp_common.LiveRadio) and warn: + if isinstance(self.rthread.radio, chirp_common.LiveRadio) and warn: txt = _("This operation requires moving all subsequent channels " "by one spot until an empty location is reached. This " "can take a LONG time. Are you sure you want to do this?") if not common.ask_yesno_question(txt): - return False # No change + return False # No change
if delta <= 0: iter = _iter @@ -477,11 +482,12 @@ class MemoryEditor(common.Editor): else: sd.insert(pos) sd.destroy() - job = common.RadioJob(lambda x: self.prefill(), "erase_memory", pos) + job = common.RadioJob( + lambda x: self.prefill(), "erase_memory", pos) job.set_desc(_("Adding memory {number}").format(number=pos)) self.rthread.submit(job)
- return True # We changed memories + return True # We changed memories
def _delete_rows(self, paths): to_remove = [] @@ -493,16 +499,15 @@ class MemoryEditor(common.Editor): job = common.RadioJob(None, "erase_memory", cur_pos) job.set_desc(_("Erasing memory {number}").format(number=cur_pos)) self.rthread.submit(job) - + def handler(mem): if not isinstance(mem, Exception): if not mem.empty or self.show_empty: gobject.idle_add(self.set_memory, mem) - + job = common.RadioJob(handler, "get_memory", cur_pos) job.set_desc(_("Getting memory {number}").format(number=cur_pos)) self.rthread.submit(job) -
if not self.show_empty: # We need to actually remove the rows from the store @@ -518,11 +523,11 @@ class MemoryEditor(common.Editor): if pos in to_remove: to_remove.remove(pos) if not self.store.remove(iter): - break # This was the last row + break # This was the last row else: iter = self.store.iter_next(iter)
- return True # We changed memories + return True # We changed memories
def _delete_rows_and_shift(self, paths, all=False): iter = self.store.get_iter(paths[0]) @@ -533,7 +538,7 @@ class MemoryEditor(common.Editor): sd.destroy()
self.prefill() - return True # We changed memories + return True # We changed memories
def _move_up_down(self, paths, action): if action.endswith("up"): @@ -550,12 +555,12 @@ class MemoryEditor(common.Editor): if victim_path[0] < 0: raise ValueError() donor_loc = self.store.get(self.store.get_iter(donor_path), - self.col(_("Loc")))[0] + self.col(_("Loc")))[0] victim_loc = self.store.get(self.store.get_iter(victim_path), - self.col(_("Loc")))[0] + self.col(_("Loc")))[0] except ValueError: self.emit("usermsg", "No room to %s" % (action.replace("_", " "))) - return False # No change + return False # No change
class Context: pass @@ -587,7 +592,7 @@ class MemoryEditor(common.Editor): old = mem.number mem.number = dest job = common.RadioJob(None, "set_memory", mem) - job.set_desc(\ + job.set_desc( _("Moving memory from {old} to {new}").format(old=old, new=dest)) self.rthread.submit(job) @@ -598,7 +603,7 @@ class MemoryEditor(common.Editor): old = mem.number mem.number += delta job = common.RadioJob(None, "set_memory", mem) - job.set_desc(\ + job.set_desc( _("Moving memory from {old} to {new}").format(old=old, new=old+delta)) self.rthread.submit(job) @@ -631,7 +636,7 @@ class MemoryEditor(common.Editor): job.set_desc("Getting memory %i" % loc) self.rthread.submit(job)
- return True # We (scheduled some) change to the memories + return True # We (scheduled some) change to the memories
def _exchange_memories(self, paths): if len(paths) != 2: @@ -647,8 +652,9 @@ class MemoryEditor(common.Editor): src = mem.number mem.number = dst job = common.RadioJob(None, "set_memory", mem) - job.set_desc(_("Moving memory from {old} to {new}").format(old=src, - new=dst)) + job.set_desc( + _("Moving memory from {old} to {new}").format( + old=src, new=dst)) self.rthread.submit(job) if dst == loc_a: self.prefill() @@ -669,8 +675,8 @@ class MemoryEditor(common.Editor): def _show_raw(self, cur_pos): def idle_show_raw(result): gobject.idle_add(common.show_diff_blob, - _("Raw memory {number}").format(number=cur_pos), - result) + _("Raw memory {number}").format( + number=cur_pos), result)
job = common.RadioJob(idle_show_raw, "get_raw_memory", cur_pos) job.set_desc(_("Getting raw memory {number}").format(number=cur_pos)) @@ -722,8 +728,8 @@ class MemoryEditor(common.Editor): def apply_and_set(memory): for field in fields: self._copy_field(src_memory, memory, field) - cb = (memory.number == locations[-1] - and self._set_memory_cb or None) + cb = (memory.number == locations[-1] and + self._set_memory_cb or None) job = common.RadioJob(cb, "set_memory", memory) job.set_desc(_("Writing memory {number}").format( number=memory.number)) @@ -745,7 +751,7 @@ class MemoryEditor(common.Editor): if len(locations) > 1: self._apply_multiple(memory, dlg.get_fields(), locations) else: - if not "name" in mem.immutable: + if "name" not in mem.immutable: mem.name = self.rthread.radio.filter_name(mem.name) job = common.RadioJob(self._set_memory_cb, "set_memory", mem) job.set_desc(_("Writing memory {number}").format( @@ -788,7 +794,7 @@ class MemoryEditor(common.Editor): elif action == "exchange": changed = self._exchange_memories(paths) elif action in ["cut", "copy"]: - changed = self.copy_selection(action=="cut") + changed = self.copy_selection(action == "cut") elif action == "paste": changed = self.paste_selection() elif action == "all": @@ -829,7 +835,7 @@ class MemoryEditor(common.Editor):
menu_xml = """ <ui> - <popup name="Menu"> + <popup name="Menu"> <menuitem action="cut"/> <menuitem action="copy"/> <menuitem action="paste"/> @@ -853,7 +859,6 @@ class MemoryEditor(common.Editor): </ui> """ % devmenu
- (store, paths) = self.view.get_selection().get_selected_rows() issingle = len(paths) == 1 istwo = len(paths) == 2 @@ -916,7 +921,7 @@ class MemoryEditor(common.Editor): menu = self.make_context_menu() menu.popup(None, None, None, event.button, event.time) return True - + def get_column_visible(self, col): column = self.view.get_column(col) return column.get_visible() @@ -924,7 +929,7 @@ class MemoryEditor(common.Editor): def set_column_visible(self, col, visible): column = self.view.get_column(col) column.set_visible(visible) - + def cell_editing_started(self, rend, event, path): self._in_editing = True
@@ -947,10 +952,10 @@ class MemoryEditor(common.Editor):
filled = self.col("_filled")
- default_col_order = [x for x,y,z in self.cols if z] + default_col_order = [x for x, y, z in self.cols if z] try: - col_order = self._config.get("column_order_%s" % \ - self.__class__.__name__).split(",") + col_order = self._config.get("column_order_%s" % + self.__class__.__name__).split(",") if len(col_order) != len(default_col_order): raise Exception() for i in col_order: @@ -976,9 +981,10 @@ class MemoryEditor(common.Editor): rend.connect('edited', self.cell_editing_stopped)
if _type == TYPE_BOOLEAN: - #rend.set_property("activatable", True) - #rend.connect("toggled", handle_toggle, self.store, i) - col = gtk.TreeViewColumn(_cap, rend, active=i, sensitive=filled) + # rend.set_property("activatable", True) + # rend.connect("toggled", handle_toggle, self.store, i) + col = gtk.TreeViewColumn(_cap, rend, active=i, + sensitive=filled) elif _rend == gtk.CellRendererCombo: if isinstance(self.choices[_cap], gtk.ListStore): choices = self.choices[_cap] @@ -998,14 +1004,14 @@ class MemoryEditor(common.Editor): rend.connect("edited", self.edited, _cap) col = gtk.TreeViewColumn(_cap, rend, text=i, sensitive=filled) col.set_cell_data_func(rend, self.render, i) - + col.set_reorderable(True) col.set_sort_column_id(i) col.set_resizable(True) col.set_min_width(1) col.set_visible(not _cap.startswith("_") and _cap in visible_cols and - not _cap in unsupported_cols) + _cap not in unsupported_cols) cols[_cap] = col i += 1
@@ -1028,7 +1034,9 @@ class MemoryEditor(common.Editor): try: return self._cached_cols[caption] except KeyError: - raise Exception(_("Internal Error: Column {name} not found").format(name=caption)) + raise Exception( + _("Internal Error: Column {name} not found").format( + name=caption))
def prefill(self): self.store.clear() @@ -1109,13 +1117,14 @@ class MemoryEditor(common.Editor): # FIXME: Make the actual remove happen on callback self.store.remove(iter) job = common.RadioJob(None, "erase_memory", number) - job.set_desc(_("Erasing memory {number}").format(number=number)) + job.set_desc( + _("Erasing memory {number}").format(number=number)) self.rthread.submit() break iter = self.store.iter_next(iter)
def _set_mem_vals(self, mem, vals, iter): - power_levels = {"" : None} + power_levels = {"": None} for i in self._features.valid_power_levels: power_levels[str(i)] = i
@@ -1149,9 +1158,10 @@ class MemoryEditor(common.Editor):
def _limit_key(self, which): if which not in ["lo", "hi"]: - raise Exception(_("Internal Error: Invalid limit {number}").format(number=which)) - return "%s_%s" % (directory.radio_class_id(self.rthread.radio.__class__), - which) + raise Exception(_("Internal Error: Invalid limit {number}").format( + number=which)) + return "%s_%s" % \ + (directory.radio_class_id(self.rthread.radio.__class__), which)
def _store_limit(self, sb, which): self._config.set_int(self._limit_key(which), int(sb.get_value())) @@ -1200,7 +1210,7 @@ class MemoryEditor(common.Editor): hival = self.hi_limit_adj.get_value() if loval >= hival: self.hi_limit_adj.set_value(loval + 25) - + lo.connect_after("focus-out-event", set_hi) lo.connect_after("activate", activate_go) hi.connect_after("activate", activate_go) @@ -1219,7 +1229,7 @@ class MemoryEditor(common.Editor):
showempty = gtk.ToggleButton(_("Show Empty")) showempty.set_relief(gtk.RELIEF_NONE) - showempty.set_active(self.show_empty); + showempty.set_active(self.show_empty) showempty.connect("toggled", lambda x: self.set_show_empty(x.get_active())) showempty.show() @@ -1231,7 +1241,9 @@ class MemoryEditor(common.Editor):
props = gtk.Button(_("Properties")) props.set_relief(gtk.RELIEF_NONE) - props.connect("clicked", lambda x: self.hotkey(gtk.Action("properties", "", "", 0))) + props.connect("clicked", + lambda x: self.hotkey( + gtk.Action("properties", "", "", 0))) props.show() hbox.pack_start(props, 0, 0, 0)
@@ -1359,7 +1371,7 @@ class MemoryEditor(common.Editor): vbox.show()
self.prefill() - + self.root = vbox
# Run low priority jobs to get the rest of the memories @@ -1393,13 +1405,14 @@ class MemoryEditor(common.Editor): mem = self._get_memory(iter) selection.append(mem.dupe()) maybe_cut.append((iter, mem)) - + if cut: for iter, mem in maybe_cut: mem.empty = True job = common.RadioJob(self._set_memory_cb, "erase_memory", mem.number) - job.set_desc(_("Cutting memory {number}").format(number=mem.number)) + job.set_desc( + _("Cutting memory {number}").format(number=mem.number)) self.rthread.submit(job)
self._set_memory(iter, mem) @@ -1408,7 +1421,7 @@ class MemoryEditor(common.Editor): clipboard = gtk.Clipboard(selection="PRIMARY") clipboard.set_text(result)
- return cut # Only changed if we did a cut + return cut # Only changed if we did a cut
def _paste_selection(self, clipboard, text, data): if not text: @@ -1432,9 +1445,9 @@ class MemoryEditor(common.Editor): if (paths[0][0] + len(mem_list)) > self._rows_in_store: common.show_error(_("Unable to paste {src} memories into " "{dst} rows. Increase the memory bounds " - "or show empty memories.").format(\ - src=len(mem_list), - dst=(self._rows_in_store - paths[0][0]))) + "or show empty memories.").format( + src=len(mem_list), + dst=(self._rows_in_store - paths[0][0]))) return
for mem in mem_list: @@ -1449,7 +1462,8 @@ class MemoryEditor(common.Editor): gtk.STOCK_NO, 2, gtk.STOCK_CANCEL, 3, "All", 4)) - d.set_text(_("Overwrite location {number}?").format(number=loc)) + d.set_text( + _("Overwrite location {number}?").format(number=loc)) r = d.run() d.destroy() if r == 4: @@ -1464,22 +1478,23 @@ class MemoryEditor(common.Editor):
src_number = mem.number mem.number = loc - + try: mem = import_logic.import_mem(self.rthread.radio, src_features, mem) except import_logic.DestNotCompatible: msgs = self.rthread.radio.validate_memory(mem) - errs = [x for x in msgs if isinstance(x, - chirp_common.ValidationError)] + errs = [x for x in msgs + if isinstance(x, chirp_common.ValidationError)] if errs: d = miscwidgets.YesNoDialog(title=_("Incompatible Memory"), buttons=(gtk.STOCK_OK, 1, gtk.STOCK_CANCEL, 2)) - d.set_text(_("Pasted memory {number} is not compatible with " - "this radio because:").format(number=src_number) +\ - os.linesep + os.linesep.join(msgs)) + d.set_text( + _("Pasted memory {number} is not compatible with " + "this radio because:").format(number=src_number) + + os.linesep + os.linesep.join(msgs)) r = d.run() d.destroy() if r == 2: @@ -1492,7 +1507,8 @@ class MemoryEditor(common.Editor): iter = store.iter_next(iter)
job = common.RadioJob(self._set_memory_cb, "set_memory", mem) - job.set_desc(_("Writing memory {number}").format(number=mem.number)) + job.set_desc( + _("Writing memory {number}").format(number=mem.number)) self.rthread.submit(job)
def paste_selection(self): @@ -1510,6 +1526,7 @@ class MemoryEditor(common.Editor): def other_editor_changed(self, target_editor): self.need_refresh = True
+ class DstarMemoryEditor(MemoryEditor): def _get_cols_to_hide(self, iter): hide = MemoryEditor._get_cols_to_hide(self, iter) @@ -1582,12 +1599,12 @@ class DstarMemoryEditor(MemoryEditor): self.defaults["Digital Code"] = 0
MemoryEditor.__init__(self, rthread) - + def ucall_cb(calls): self.defaults["URCALL"] = calls[0] for call in calls: self.choices["URCALL"].append((call, call)) - + if self._features.requires_call_lists: ujob = common.RadioJob(ucall_cb, "get_urcall_list") ujob.set_desc(_("Downloading URCALL list")) @@ -1609,7 +1626,7 @@ class DstarMemoryEditor(MemoryEditor):
if not self._features.requires_call_lists: for i in _dv_columns: - if not self.choices.has_key(i): + if i not in self.choices: continue column = self.view.get_column(self.col(i)) rend = column.get_cell_renderers()[0] @@ -1653,5 +1670,6 @@ class DstarMemoryEditor(MemoryEditor): self.col("Digital Code"), 0, )
+ class ID800MemoryEditor(DstarMemoryEditor): pass diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 03dbba8..3899a67 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,7 +71,6 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/memedit.py ./chirpui/miscwidgets.py ./chirpui/reporting.py ./tools/bitdiff.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 430f7efb766ed3dafb338ff95134643a7a0f4be3
Fix style issues in miscwidgits.py (#2355)
diff --git a/chirpui/miscwidgets.py b/chirpui/miscwidgets.py index 6562363..723b8bf 100644 --- a/chirpui/miscwidgets.py +++ b/chirpui/miscwidgets.py @@ -21,17 +21,18 @@ import os
from chirp import platform
+ class KeyedListWidget(gtk.HBox): __gsignals__ = { - "item-selected" : (gobject.SIGNAL_RUN_LAST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING,)), - "item-toggled" : (gobject.SIGNAL_ACTION, - gobject.TYPE_BOOLEAN, - (gobject.TYPE_STRING, gobject.TYPE_BOOLEAN)), - "item-set" : (gobject.SIGNAL_ACTION, - gobject.TYPE_BOOLEAN, - (gobject.TYPE_STRING,)), + "item-selected": (gobject.SIGNAL_RUN_LAST, + gobject.TYPE_NONE, + (gobject.TYPE_STRING,)), + "item-toggled": (gobject.SIGNAL_ACTION, + gobject.TYPE_BOOLEAN, + (gobject.TYPE_STRING, gobject.TYPE_BOOLEAN)), + "item-set": (gobject.SIGNAL_ACTION, + gobject.TYPE_BOOLEAN, + (gobject.TYPE_STRING,)), }
def _toggle(self, rend, path, colnum): @@ -60,13 +61,14 @@ class KeyedListWidget(gtk.HBox):
def _make_view(self): colnum = -1 - + for typ, cap in self.columns: colnum += 1 if colnum == 0: - continue # Key column - - if typ in [gobject.TYPE_STRING, gobject.TYPE_INT, gobject.TYPE_FLOAT]: + continue # Key column + + if typ in [gobject.TYPE_STRING, gobject.TYPE_INT, + gobject.TYPE_FLOAT]: rend = gtk.CellRendererText() rend.set_property("ellipsize", pango.ELLIPSIZE_END) column = gtk.TreeViewColumn(cap, rend, text=colnum) @@ -76,10 +78,10 @@ class KeyedListWidget(gtk.HBox): column = gtk.TreeViewColumn(cap, rend, active=colnum) else: raise Exception("Unsupported type %s" % typ) - + column.set_sort_column_id(colnum) self.__view.append_column(column) - + self.__view.connect("button_press_event", self._mouse)
def set_item(self, key, *values): @@ -91,11 +93,11 @@ class KeyedListWidget(gtk.HBox): self.__store.remove(iter) return iter = self.__store.iter_next(iter) - + self.__store.append(row=(key,) + values)
self.emit("item-set", key) - + def get_item(self, key): iter = self.__store.get_iter_first() while iter: @@ -103,9 +105,9 @@ class KeyedListWidget(gtk.HBox): if vals[0] == key: return vals iter = self.__store.iter_next(iter) - + return None - + def del_item(self, key): iter = self.__store.get_iter_first() while iter: @@ -115,12 +117,12 @@ class KeyedListWidget(gtk.HBox): return True
iter = self.__store.iter_next(iter) - + return False - + def has_item(self, key): return self.get_item(key) is not None - + def get_selected(self): try: (store, iter) = self.__view.get_selection().get_selected() @@ -145,7 +147,7 @@ class KeyedListWidget(gtk.HBox): iter = self.__store.iter_next(iter)
return False - + def get_keys(self): keys = [] iter = self.__store.get_iter_first() @@ -158,16 +160,16 @@ class KeyedListWidget(gtk.HBox):
def __init__(self, columns): gtk.HBox.__init__(self, True, 0) - + self.columns = columns - - types = tuple([x for x,y in columns]) - + + types = tuple([x for x, y in columns]) + self.__store = gtk.ListStore(*types) self.__view = gtk.TreeView(self.__store) - + self.pack_start(self.__view, 1, 1, 1) - + self.__toggle_connected = False
self._make_view() @@ -176,7 +178,7 @@ class KeyedListWidget(gtk.HBox): def connect(self, signame, *args): if signame == "item-toggled": self.__toggle_connected = True - + gtk.HBox.connect(self, signame, *args)
def set_editable(self, column, is_editable): @@ -194,14 +196,15 @@ class KeyedListWidget(gtk.HBox): def get_renderer(self, colnum): return self.__view.get_column(colnum).get_cell_renderers()[0]
+ class ListWidget(gtk.HBox): __gsignals__ = { - "click-on-list" : (gobject.SIGNAL_RUN_LAST, - gobject.TYPE_NONE, - (gtk.TreeView, gtk.gdk.Event)), - "item-toggled" : (gobject.SIGNAL_RUN_LAST, + "click-on-list": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, - (gobject.TYPE_PYOBJECT,)), + (gtk.TreeView, gtk.gdk.Event)), + "item-toggled": (gobject.SIGNAL_RUN_LAST, + gobject.TYPE_NONE, + (gobject.TYPE_PYOBJECT,)), }
store_type = gtk.ListStore @@ -251,7 +254,7 @@ class ListWidget(gtk.HBox): # pylint: disable-msg=W0612 col_types = tuple([x for x, y in columns]) self._ncols = len(col_types) - + self._store = self.store_type(*col_types) self._view = None self.make_view(columns) @@ -338,6 +341,7 @@ class ListWidget(gtk.HBox): for i in lst: self.add_item(*i)
+ class TreeWidget(ListWidget): store_type = gtk.TreeStore
@@ -452,6 +456,7 @@ class TreeWidget(ListWidget): else: raise Exception("Item not found")
+ class ProgressDialog(gtk.Window): def __init__(self, title, parent=None): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) @@ -471,7 +476,7 @@ class ProgressDialog(gtk.Window):
self.pbar = gtk.ProgressBar() self.pbar.show() - + vbox.pack_start(self.label, 0, 0, 0) vbox.pack_start(self.pbar, 0, 0, 0)
@@ -493,6 +498,7 @@ class ProgressDialog(gtk.Window): while gtk.events_pending(): gtk.main_iteration_do(False)
+ class LatLonEntry(gtk.Entry): def __init__(self, *args): gtk.Entry.__init__(self, *args) @@ -526,7 +532,7 @@ class LatLonEntry(gtk.Entry): def parse_dm(self, string): string = string.strip() string = string.replace(' ', ' ') - + (_degrees, _minutes) = string.split(' ', 2)
degrees = int(_degrees) @@ -565,7 +571,7 @@ class LatLonEntry(gtk.Entry): degrees = int(deg) minutes = int(mns) seconds = float(sec) - + return degrees + (minutes / 60.0) + (seconds / 3600.0)
def value(self): @@ -591,6 +597,7 @@ class LatLonEntry(gtk.Entry): except: return False
+ class YesNoDialog(gtk.Dialog): def __init__(self, title="", parent=None, buttons=None): gtk.Dialog.__init__(self, title=title, parent=parent, buttons=buttons) @@ -604,6 +611,7 @@ class YesNoDialog(gtk.Dialog): def set_text(self, text): self._label.set_text(text)
+ def make_choice(options, editable=True, default=None): if editable: sel = gtk.combo_box_entry_new_text() @@ -622,9 +630,10 @@ def make_choice(options, editable=True, default=None):
return sel
+ class FilenameBox(gtk.HBox): __gsignals__ = { - "filename-changed" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), + "filename-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()), }
def do_browse(self, _, dir): @@ -663,7 +672,8 @@ class FilenameBox(gtk.HBox): self.filename.set_text(fn)
def get_filename(self): - return self.filename.get_text() + return self.filename.get_text() +
def make_pixbuf_choice(options, default=None): store = gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING) @@ -689,14 +699,15 @@ def make_pixbuf_choice(options, default=None):
return box
+ def test(): win = gtk.Window(gtk.WINDOW_TOPLEVEL) lst = ListWidget([(gobject.TYPE_STRING, "Foo"), - (gobject.TYPE_BOOLEAN, "Bar")]) + (gobject.TYPE_BOOLEAN, "Bar")])
lst.add_item("Test1", True) lst.set_values([("Test2", True), ("Test3", False)]) - + lst.show() win.add(lst) win.show() @@ -714,10 +725,8 @@ def test(): lst = TreeWidget([(gobject.TYPE_STRING, "Id"), (gobject.TYPE_STRING, "Value")], 1) - #l.add_item(None, "Foo", "Bar") - #l.add_item("Foo", "Bar", "Baz") - lst.set_values({"Fruit" : [("Apple", "Red"), ("Orange", "Orange")], - "Pizza" : [("Cheese", "Simple"), ("Pepperoni", "Yummy")]}) + lst.set_values({"Fruit": [("Apple", "Red"), ("Orange", "Orange")], + "Pizza": [("Cheese", "Simple"), ("Pepperoni", "Yummy")]}) lst.add_item("Fruit", "Bananna", "Yellow") lst.show() win3.add(lst) @@ -739,5 +748,6 @@ def test():
print lst.get_values()
+ if __name__ == "__main__": test() diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 3899a67..8421d48 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,7 +71,6 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/miscwidgets.py ./chirpui/reporting.py ./tools/bitdiff.py ./tools/img2thd72.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID c550f660cafcd538c3e64a4e8fc6300ed1c67e69
Fix style issues in reporting.py (#2355)
diff --git a/chirpui/reporting.py b/chirpui/reporting.py index efe18c1..0f524c5 100644 --- a/chirpui/reporting.py +++ b/chirpui/reporting.py @@ -34,7 +34,7 @@ from chirp import CHIRP_VERSION, platform
REPORT_URL = "http://chirp.danplanet.com/report/report.php?do_report" ENABLED = True -THREAD_SEM = threading.Semaphore(10) # Maximum number of outstanding threads +THREAD_SEM = threading.Semaphore(10) # Maximum number of outstanding threads LAST = 0 LAST_TYPE = None
@@ -47,6 +47,7 @@ try: except: ENABLED = False
+ def should_report(): if not ENABLED: LOG.debug("Not reporting due to recent failure") @@ -59,11 +60,13 @@ def should_report():
return True
+ def _report_model_usage(model, direction, success): global ENABLED - if direction not in ["live", "download", "upload", "import", "export", "importsrc"]: + if direction not in ["live", "download", "upload", + "import", "export", "importsrc"]: print "Invalid direction `%s'" % direction - return True # This is a bug, but not fatal + return True # This is a bug, but not fatal
model = "%s_%s" % (model.VENDOR, model.MODEL) data = "%s,%s,%s" % (model, direction, success) @@ -79,6 +82,7 @@ def _report_model_usage(model, direction, success): # If the server returns zero, it wants us to shut up return id != 0
+ def _report_exception(stack): global ENABLED
@@ -93,6 +97,7 @@ def _report_exception(stack): # If the server returns zero, it wants us to shut up return id != 0
+ def _report_misc_error(module, data): global ENABLED
@@ -106,6 +111,7 @@ def _report_misc_error(module, data): # If the server returns zero, it wants us to shut up return id != 0
+ def _check_for_updates(callback): LOG.debug("Checking for updates") proxy = xmlrpclib.ServerProxy(REPORT_URL) @@ -116,6 +122,7 @@ def _check_for_updates(callback): callback(ver) return True
+ class ReportThread(threading.Thread): def __init__(self, func, *args): threading.Thread.__init__(self) @@ -128,7 +135,7 @@ class ReportThread(threading.Thread): except Exception, e: LOG.debug("Failed to report: %s" % e) return False - + def run(self): start = time.time() result = self._run() @@ -137,12 +144,13 @@ class ReportThread(threading.Thread): ENABLED = False elif (time.time() - start) > 15: # Reporting took too long - LOG.debug("Time to report was %.2f sec -- Disabling" % \ + LOG.debug("Time to report was %.2f sec -- Disabling" % (time.time()-start)) ENABLED = False
THREAD_SEM.release()
+ def dispatch_thread(func, *args): global LAST global LAST_TYPE @@ -169,15 +177,19 @@ def dispatch_thread(func, *args): t = ReportThread(func, *args) t.start()
+ def report_model_usage(model, direction, success): dispatch_thread(_report_model_usage, model, direction, success)
+ def report_exception(stack): dispatch_thread(_report_exception, stack)
+ def report_misc_error(module, data): dispatch_thread(_report_misc_error, module, data)
+ # Calls callback with the latest version def check_for_updates(callback): dispatch_thread(_check_for_updates, callback) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 8421d48..54f568f 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -71,6 +71,5 @@ ./chirp/wouxun_common.py ./chirp/yaesu_clone.py ./chirpui/fips.py -./chirpui/reporting.py ./tools/bitdiff.py ./tools/img2thd72.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 03723ca82ed1e29d662e070e22db3601daa9e215
Fix style issues in fips.py (#2355)
diff --git a/chirpui/fips.py b/chirpui/fips.py index 0094ec1..a7089e7 100644 --- a/chirpui/fips.py +++ b/chirpui/fips.py @@ -15,77 +15,77 @@
FIPS_STATES = { - "Alaska" : 2, - "Alabama" : 1, - "Arkansas" : 5, - "Arizona" : 4, - "California" : 6, - "Colorado" : 8, - "Connecticut" : 9, - "District of Columbia" : 11, - "Delaware" : 10, - "Florida" : 12, - "Georgia" : 13, - "Guam" : 66, - "Hawaii" : 15, - "Iowa" : 19, - "Idaho" : 16, - "Illinois" : 17, - "Indiana" : 18, - "Kansas" : 20, - "Kentucky" : 21, - "Louisiana" : 22, - "Massachusetts" : 25, - "Maryland" : 24, - "Maine" : 23, - "Michigan" : 26, - "Minnesota" : 27, - "Missouri" : 29, - "Mississippi" : 28, - "Montana" : 30, - "North Carolina" : 37, - "North Dakota" : 38, - "Nebraska" : 31, - "New Hampshire" : 33, - "New Jersey" : 34, - "New Mexico" : 35, - "Nevada" : 32, - "New York" : 36, - "Ohio" : 39, - "Oklahoma" : 40, - "Oregon" : 41, - "Pennsylvania" : 42, - "Puerto Rico" : 72, - "Rhode Island" : 44, - "South Carolina" : 45, - "South Dakota" : 46, - "Tennessee" : 47, - "Texas" : 48, - "Utah" : 49, - "Virginia" : 51, - "Virgin Islands" : 78, - "Vermont" : 50, - "Washington" : 53, - "Wisconsin" : 55, - "West Virginia" : 54, - "Wyoming" : 56, - "Alberta" : "CA01", - "British Columbia" : "CA02", - "Manitoba" : "CA03", - "New Brunswick" : "CA04", + "Alaska": 2, + "Alabama": 1, + "Arkansas": 5, + "Arizona": 4, + "California": 6, + "Colorado": 8, + "Connecticut": 9, + "District of Columbia": 11, + "Delaware": 10, + "Florida": 12, + "Georgia": 13, + "Guam": 66, + "Hawaii": 15, + "Iowa": 19, + "Idaho": 16, + "Illinois": 17, + "Indiana": 18, + "Kansas": 20, + "Kentucky": 21, + "Louisiana": 22, + "Massachusetts": 25, + "Maryland": 24, + "Maine": 23, + "Michigan": 26, + "Minnesota": 27, + "Missouri": 29, + "Mississippi": 28, + "Montana": 30, + "North Carolina": 37, + "North Dakota": 38, + "Nebraska": 31, + "New Hampshire": 33, + "New Jersey": 34, + "New Mexico": 35, + "Nevada": 32, + "New York": 36, + "Ohio": 39, + "Oklahoma": 40, + "Oregon": 41, + "Pennsylvania": 42, + "Puerto Rico": 72, + "Rhode Island": 44, + "South Carolina": 45, + "South Dakota": 46, + "Tennessee": 47, + "Texas": 48, + "Utah": 49, + "Virginia": 51, + "Virgin Islands": 78, + "Vermont": 50, + "Washington": 53, + "Wisconsin": 55, + "West Virginia": 54, + "Wyoming": 56, + "Alberta": "CA01", + "British Columbia": "CA02", + "Manitoba": "CA03", + "New Brunswick": "CA04", "Newfoundland and Labrador": "CA05", - "Northwest Territories": "CA13", - "Nova Scotia" : "CA07", - "Nunavut" : "CA14", - "Ontario" : "CA08", - "Prince Edward Island" : "CA09", - "Quebec" : "CA10", - "Saskatchewan" : "CA11", - "Yukon" : "CA12", + "Northwest Territories": "CA13", + "Nova Scotia": "CA07", + "Nunavut": "CA14", + "Ontario": "CA08", + "Prince Edward Island": "CA09", + "Quebec": "CA10", + "Saskatchewan": "CA11", + "Yukon": "CA12", }
FIPS_COUNTIES = { - 1: { '--All--': '%', + 1: {'--All--': '%', 'Autauga County, AL': '001', 'Baldwin County, AL': '003', 'Barbour County, AL': '005', @@ -153,7 +153,7 @@ FIPS_COUNTIES = { 'Washington County, AL': '129', 'Wilcox County, AL': '131', 'Winston County, AL': '133'}, - 2: { '--All--': '%', + 2: {'--All--': '%', 'Aleutians East Borough, AK': '013', 'Aleutians West Census Area, AK': '016', 'Anchorage Borough/municipality, AK': '020', @@ -181,7 +181,7 @@ FIPS_COUNTIES = { 'Wrangell-Petersburg Census Area, AK': '280', 'Yakutat Borough, AK': '282', 'Yukon-Koyukuk Census Area, AK': '290'}, - 4: { '--All--': '%', + 4: {'--All--': '%', 'Apache County, AZ': '001', 'Cochise County, AZ': '003', 'Coconino County, AZ': '005', @@ -197,7 +197,7 @@ FIPS_COUNTIES = { 'Santa Cruz County, AZ': '023', 'Yavapai County, AZ': '025', 'Yuma County, AZ': '027'}, - 5: { '--All--': '%', + 5: {'--All--': '%', 'Arkansas County, AR': '001', 'Ashley County, AR': '003', 'Baxter County, AR': '005', @@ -273,7 +273,7 @@ FIPS_COUNTIES = { 'White County, AR': '145', 'Woodruff County, AR': '147', 'Yell County, AR': '149'}, - 6: { '--All--': '%', + 6: {'--All--': '%', 'Alameda County, CA': '001', 'Alpine County, CA': '003', 'Amador County, CA': '005', @@ -332,7 +332,7 @@ FIPS_COUNTIES = { 'Ventura County, CA': '111', 'Yolo County, CA': '113', 'Yuba County, CA': '115'}, - 8: { '--All--': '%', + 8: {'--All--': '%', 'Adams County, CO': '001', 'Alamosa County, CO': '003', 'Arapahoe County, CO': '005', @@ -397,7 +397,7 @@ FIPS_COUNTIES = { 'Washington County, CO': '121', 'Weld County, CO': '123', 'Yuma County, CO': '125'}, - 9: { '--All--': '%', + 9: {'--All--': '%', 'Fairfield County, CT': '001', 'Hartford County, CT': '003', 'Litchfield County, CT': '005', @@ -406,12 +406,12 @@ FIPS_COUNTIES = { 'New London County, CT': '011', 'Tolland County, CT': '013', 'Windham County, CT': '015'}, - 10: { '--All--': '%', + 10: {'--All--': '%', 'Kent County, DE': '001', 'New Castle County, DE': '003', 'Sussex County, DE': '005'}, - 11: { '--All--': '%', 'District of Columbia': '001'}, - 12: { '--All--': '%', + 11: {'--All--': '%', 'District of Columbia': '001'}, + 12: {'--All--': '%', 'Alachua County, FL': '001', 'Baker County, FL': '003', 'Bay County, FL': '005', @@ -479,7 +479,7 @@ FIPS_COUNTIES = { 'Wakulla County, FL': '129', 'Walton County, FL': '131', 'Washington County, FL': '133'}, - 13: { '--All--': '%', + 13: {'--All--': '%', 'Appling County, GA': '001', 'Atkinson County, GA': '003', 'Bacon County, GA': '005', @@ -639,12 +639,12 @@ FIPS_COUNTIES = { 'Wilkes County, GA': '317', 'Wilkinson County, GA': '319', 'Worth County, GA': '321'}, - 15: { '--All--': '%', + 15: {'--All--': '%', 'Hawaii County, HI': '001', 'Honolulu County/city, HI': '003', 'Kauai County, HI': '007', 'Maui County, HI': '009'}, - 16: { '--All--': '%', + 16: {'--All--': '%', 'Ada County, ID': '001', 'Adams County, ID': '003', 'Bannock County, ID': '005', @@ -689,7 +689,7 @@ FIPS_COUNTIES = { 'Twin Falls County, ID': '083', 'Valley County, ID': '085', 'Washington County, ID': '087'}, - 17: { '--All--': '%', + 17: {'--All--': '%', 'Adams County, IL': '001', 'Alexander County, IL': '003', 'Bond County, IL': '005', @@ -792,7 +792,7 @@ FIPS_COUNTIES = { 'Williamson County, IL': '199', 'Winnebago County, IL': '201', 'Woodford County, IL': '203'}, - 18: { '--All--': '%', + 18: {'--All--': '%', 'Adams County, IN': '001', 'Allen County, IN': '003', 'Bartholomew County, IN': '005', @@ -885,7 +885,7 @@ FIPS_COUNTIES = { 'Wells County, IN': '179', 'White County, IN': '181', 'Whitley County, IN': '183'}, - 19: { '--All--': '%', + 19: {'--All--': '%', 'Adair County, IA': '001', 'Adams County, IA': '003', 'Allamakee County, IA': '005', @@ -985,7 +985,7 @@ FIPS_COUNTIES = { 'Woodbury County, IA': '193', 'Worth County, IA': '195', 'Wright County, IA': '197'}, - 20: { '--All--': '%', + 20: {'--All--': '%', 'Allen County, KS': '001', 'Anderson County, KS': '003', 'Atchison County, KS': '005', @@ -1091,7 +1091,7 @@ FIPS_COUNTIES = { 'Wilson County, KS': '205', 'Woodson County, KS': '207', 'Wyandotte County, KS': '209'}, - 21: { '--All--': '%', + 21: {'--All--': '%', 'Adair County, KY': '001', 'Allen County, KY': '003', 'Anderson County, KY': '005', @@ -1212,7 +1212,7 @@ FIPS_COUNTIES = { 'Whitley County, KY': '235', 'Wolfe County, KY': '237', 'Woodford County, KY': '239'}, - 22: { '--All--': '%', + 22: {'--All--': '%', 'Acadia Parish, LA': '001', 'Allen Parish, LA': '003', 'Ascension Parish, LA': '005', @@ -1277,7 +1277,7 @@ FIPS_COUNTIES = { 'West Carroll Parish, LA': '123', 'West Feliciana Parish, LA': '125', 'Winn Parish, LA': '127'}, - 23: { '--All--': '%', + 23: {'--All--': '%', 'Androscoggin County, ME': '001', 'Aroostook County, ME': '003', 'Cumberland County, ME': '005', @@ -1294,7 +1294,7 @@ FIPS_COUNTIES = { 'Waldo County, ME': '027', 'Washington County, ME': '029', 'York County, ME': '031'}, - 24: { '--All--': '%', + 24: {'--All--': '%', 'Allegany County, MD': '001', 'Anne Arundel County, MD': '003', 'Baltimore County, MD': '005', @@ -1319,7 +1319,7 @@ FIPS_COUNTIES = { 'Washington County, MD': '043', 'Wicomico County, MD': '045', 'Worcester County, MD': '047'}, - 25: { '--All--': '%', + 25: {'--All--': '%', 'Barnstable County, MA': '001', 'Berkshire County, MA': '003', 'Bristol County, MA': '005', @@ -1334,7 +1334,7 @@ FIPS_COUNTIES = { 'Plymouth County, MA': '023', 'Suffolk County, MA': '025', 'Worcester County, MA': '027'}, - 26: { '--All--': '%', + 26: {'--All--': '%', 'Alcona County, MI': '001', 'Alger County, MI': '003', 'Allegan County, MI': '005', @@ -1418,7 +1418,7 @@ FIPS_COUNTIES = { 'Washtenaw County, MI': '161', 'Wayne County, MI': '163', 'Wexford County, MI': '165'}, - 27: { '--All--': '%', + 27: {'--All--': '%', 'Aitkin County, MN': '001', 'Anoka County, MN': '003', 'Becker County, MN': '005', @@ -1506,7 +1506,7 @@ FIPS_COUNTIES = { 'Winona County, MN': '169', 'Wright County, MN': '171', 'Yellow Medicine County, MN': '173'}, - 28: { '--All--': '%', + 28: {'--All--': '%', 'Adams County, MS': '001', 'Alcorn County, MS': '003', 'Amite County, MS': '005', @@ -1589,7 +1589,7 @@ FIPS_COUNTIES = { 'Winston County, MS': '159', 'Yalobusha County, MS': '161', 'Yazoo County, MS': '163'}, - 29: { '--All--': '%', + 29: {'--All--': '%', 'Adair County, MO': '001', 'Andrew County, MO': '003', 'Atchison County, MO': '005', @@ -1705,7 +1705,7 @@ FIPS_COUNTIES = { 'Webster County, MO': '225', 'Worth County, MO': '227', 'Wright County, MO': '229'}, - 30: { '--All--': '%', + 30: {'--All--': '%', 'Beaverhead County, MT': '001', 'Big Horn County, MT': '003', 'Blaine County, MT': '005', @@ -1762,7 +1762,7 @@ FIPS_COUNTIES = { 'Wheatland County, MT': '107', 'Wibaux County, MT': '109', 'Yellowstone County, MT': '111'}, - 31: { '--All--': '%', + 31: {'--All--': '%', 'Adams County, NE': '001', 'Antelope County, NE': '003', 'Arthur County, NE': '005', @@ -1856,7 +1856,7 @@ FIPS_COUNTIES = { 'Webster County, NE': '181', 'Wheeler County, NE': '183', 'York County, NE': '185'}, - 32: { '--All--': '%', + 32: {'--All--': '%', 'Carson City, NV': '510', 'Churchill County, NV': '001', 'Clark County, NV': '003', @@ -1874,7 +1874,7 @@ FIPS_COUNTIES = { 'Storey County, NV': '029', 'Washoe County, NV': '031', 'White Pine County, NV': '033'}, - 33: { '--All--': '%', + 33: {'--All--': '%', 'Belknap County, NH': '001', 'Carroll County, NH': '003', 'Cheshire County, NH': '005', @@ -1885,7 +1885,7 @@ FIPS_COUNTIES = { 'Rockingham County, NH': '015', 'Strafford County, NH': '017', 'Sullivan County, NH': '019'}, - 34: { '--All--': '%', + 34: {'--All--': '%', 'Atlantic County, NJ': '001', 'Bergen County, NJ': '003', 'Burlington County, NJ': '005', @@ -1907,7 +1907,7 @@ FIPS_COUNTIES = { 'Sussex County, NJ': '037', 'Union County, NJ': '039', 'Warren County, NJ': '041'}, - 35: { '--All--': '%', + 35: {'--All--': '%', 'Bernalillo County, NM': '001', 'Catron County, NM': '003', 'Chaves County, NM': '005', @@ -1941,7 +1941,7 @@ FIPS_COUNTIES = { 'Torrance County, NM': '057', 'Union County, NM': '059', 'Valencia County, NM': '061'}, - 36: { '--All--': '%', + 36: {'--All--': '%', 'Albany County, NY': '001', 'Allegany County, NY': '003', 'Bronx County, NY': '005', @@ -2004,7 +2004,7 @@ FIPS_COUNTIES = { 'Westchester County, NY': '119', 'Wyoming County, NY': '121', 'Yates County, NY': '123'}, - 37: { '--All--': '%', + 37: {'--All--': '%', 'Alamance County, NC': '001', 'Alexander County, NC': '003', 'Alleghany County, NC': '005', @@ -2105,7 +2105,7 @@ FIPS_COUNTIES = { 'Wilson County, NC': '195', 'Yadkin County, NC': '197', 'Yancey County, NC': '199'}, - 38: { '--All--': '%', + 38: {'--All--': '%', 'Adams County, ND': '001', 'Barnes County, ND': '003', 'Benson County, ND': '005', @@ -2159,7 +2159,7 @@ FIPS_COUNTIES = { 'Ward County, ND': '101', 'Wells County, ND': '103', 'Williams County, ND': '105'}, - 39: { '--All--': '%', + 39: {'--All--': '%', 'Adams County, OH': '001', 'Allen County, OH': '003', 'Ashland County, OH': '005', @@ -2248,7 +2248,7 @@ FIPS_COUNTIES = { 'Williams County, OH': '171', 'Wood County, OH': '173', 'Wyandot County, OH': '175'}, - 40: { '--All--': '%', + 40: {'--All--': '%', 'Adair County, OK': '001', 'Alfalfa County, OK': '003', 'Atoka County, OK': '005', @@ -2326,7 +2326,7 @@ FIPS_COUNTIES = { 'Washita County, OK': '149', 'Woods County, OK': '151', 'Woodward County, OK': '153'}, - 41: { '--All--': '%', + 41: {'--All--': '%', 'Baker County, OR': '001', 'Benton County, OR': '003', 'Clackamas County, OR': '005', @@ -2363,7 +2363,7 @@ FIPS_COUNTIES = { 'Washington County, OR': '067', 'Wheeler County, OR': '069', 'Yamhill County, OR': '071'}, - 42: { '--All--': '%', + 42: {'--All--': '%', 'Adams County, PA': '001', 'Allegheny County, PA': '003', 'Armstrong County, PA': '005', @@ -2431,13 +2431,13 @@ FIPS_COUNTIES = { 'Westmoreland County, PA': '129', 'Wyoming County, PA': '131', 'York County, PA': '133'}, - 44: { '--All--': '%', + 44: {'--All--': '%', 'Bristol County, RI': '001', 'Kent County, RI': '003', 'Newport County, RI': '005', 'Providence County, RI': '007', 'Washington County, RI': '009'}, - 45: { '--All--': '%', + 45: {'--All--': '%', 'Abbeville County, SC': '001', 'Aiken County, SC': '003', 'Allendale County, SC': '005', @@ -2484,7 +2484,7 @@ FIPS_COUNTIES = { 'Union County, SC': '087', 'Williamsburg County, SC': '089', 'York County, SC': '091'}, - 46: { '--All--': '%', + 46: {'--All--': '%', 'Aurora County, SD': '003', 'Beadle County, SD': '005', 'Bennett County, SD': '007', @@ -2551,7 +2551,7 @@ FIPS_COUNTIES = { 'Walworth County, SD': '129', 'Yankton County, SD': '135', 'Ziebach County, SD': '137'}, - 47: { '--All--': '%', + 47: {'--All--': '%', 'Anderson County, TN': '001', 'Bedford County, TN': '003', 'Benton County, TN': '005', @@ -2647,7 +2647,7 @@ FIPS_COUNTIES = { 'White County, TN': '185', 'Williamson County, TN': '187', 'Wilson County, TN': '189'}, - 48: { '--All--': '%', + 48: {'--All--': '%', 'Anderson County, TX': '001', 'Andrews County, TX': '003', 'Angelina County, TX': '005', @@ -2902,7 +2902,7 @@ FIPS_COUNTIES = { 'Young County, TX': '503', 'Zapata County, TX': '505', 'Zavala County, TX': '507'}, - 49: { '--All--': '%', + 49: {'--All--': '%', 'Beaver County, UT': '001', 'Box Elder County, UT': '003', 'Cache County, UT': '005', @@ -2932,7 +2932,7 @@ FIPS_COUNTIES = { 'Washington County, UT': '053', 'Wayne County, UT': '055', 'Weber County, UT': '057'}, - 50: { '--All--': '%', + 50: {'--All--': '%', 'Addison County, VT': '001', 'Bennington County, VT': '003', 'Caledonia County, VT': '005', @@ -2947,7 +2947,7 @@ FIPS_COUNTIES = { 'Washington County, VT': '023', 'Windham County, VT': '025', 'Windsor County, VT': '027'}, - 51: { '--All--': '%', + 51: {'--All--': '%', 'Accomack County, VA': '001', 'Albemarle County, VA': '003', 'Alexandria city, VA': '510', @@ -3082,7 +3082,7 @@ FIPS_COUNTIES = { 'Wise County, VA': '195', 'Wythe County, VA': '197', 'York County, VA': '199'}, - 53: { '--All--': '%', + 53: {'--All--': '%', 'Adams County, WA': '001', 'Asotin County, WA': '003', 'Benton County, WA': '005', @@ -3122,7 +3122,7 @@ FIPS_COUNTIES = { 'Whatcom County, WA': '073', 'Whitman County, WA': '075', 'Yakima County, WA': '077'}, - 54: { '--All--': '%', + 54: {'--All--': '%', 'Barbour County, WV': '001', 'Berkeley County, WV': '003', 'Boone County, WV': '005', @@ -3178,7 +3178,7 @@ FIPS_COUNTIES = { 'Wirt County, WV': '105', 'Wood County, WV': '107', 'Wyoming County, WV': '109'}, - 55: { '--All--': '%', + 55: {'--All--': '%', 'Adams County, WI': '001', 'Ashland County, WI': '003', 'Barron County, WI': '005', @@ -3251,7 +3251,7 @@ FIPS_COUNTIES = { 'Waushara County, WI': '137', 'Winnebago County, WI': '139', 'Wood County, WI': '141'}, - 56: { '--All--': '%', + 56: {'--All--': '%', 'Albany County, WY': '001', 'Big Horn County, WY': '003', 'Campbell County, WY': '005', @@ -3275,7 +3275,7 @@ FIPS_COUNTIES = { 'Uinta County, WY': '041', 'Washakie County, WY': '043', 'Weston County, WY': '045'}, - 72: { '--All--': '%', + 72: {'--All--': '%', 'Adjuntas Municipio, PR': '001', 'Aguada Municipio, PR': '003', 'Aguadilla Municipio, PR': '005', @@ -3354,7 +3354,7 @@ FIPS_COUNTIES = { 'Villalba Municipio, PR': '149', 'Yabucoa Municipio, PR': '151', 'Yauco Municipio, PR': '153'}, - '01': { 'Autauga County, AL': '001', + '01': {'Autauga County, AL': '001', 'Baldwin County, AL': '003', 'Barbour County, AL': '005', 'Bibb County, AL': '007', @@ -3421,7 +3421,7 @@ FIPS_COUNTIES = { 'Washington County, AL': '129', 'Wilcox County, AL': '131', 'Winston County, AL': '133'}, - '02': { 'Aleutians East Borough, AK': '013', + '02': {'Aleutians East Borough, AK': '013', 'Aleutians West Census Area, AK': '016', 'Anchorage Borough/municipality, AK': '020', 'Bethel Census Area, AK': '050', @@ -3448,7 +3448,7 @@ FIPS_COUNTIES = { 'Wrangell-Petersburg Census Area, AK': '280', 'Yakutat Borough, AK': '282', 'Yukon-Koyukuk Census Area, AK': '290'}, - '04': { 'Apache County, AZ': '001', + '04': {'Apache County, AZ': '001', 'Cochise County, AZ': '003', 'Coconino County, AZ': '005', 'Gila County, AZ': '007', @@ -3463,7 +3463,7 @@ FIPS_COUNTIES = { 'Santa Cruz County, AZ': '023', 'Yavapai County, AZ': '025', 'Yuma County, AZ': '027'}, - '05': { 'Arkansas County, AR': '001', + '05': {'Arkansas County, AR': '001', 'Ashley County, AR': '003', 'Baxter County, AR': '005', 'Benton County, AR': '007', @@ -3538,7 +3538,7 @@ FIPS_COUNTIES = { 'White County, AR': '145', 'Woodruff County, AR': '147', 'Yell County, AR': '149'}, - '06': { 'Alameda County, CA': '001', + '06': {'Alameda County, CA': '001', 'Alpine County, CA': '003', 'Amador County, CA': '005', 'Butte County, CA': '007', @@ -3596,7 +3596,7 @@ FIPS_COUNTIES = { 'Ventura County, CA': '111', 'Yolo County, CA': '113', 'Yuba County, CA': '115'}, - '08': { 'Adams County, CO': '001', + '08': {'Adams County, CO': '001', 'Alamosa County, CO': '003', 'Arapahoe County, CO': '005', 'Archuleta County, CO': '007', @@ -3660,7 +3660,7 @@ FIPS_COUNTIES = { 'Washington County, CO': '121', 'Weld County, CO': '123', 'Yuma County, CO': '125'}, - '09': { 'Fairfield County, CT': '001', + '09': {'Fairfield County, CT': '001', 'Hartford County, CT': '003', 'Litchfield County, CT': '005', 'Middlesex County, CT': '007', @@ -3668,11 +3668,11 @@ FIPS_COUNTIES = { 'New London County, CT': '011', 'Tolland County, CT': '013', 'Windham County, CT': '015'}, - '10': { 'Kent County, DE': '001', + '10': {'Kent County, DE': '001', 'New Castle County, DE': '003', 'Sussex County, DE': '005'}, - '11': { 'District of Columbia': '001'}, - '12': { 'Alachua County, FL': '001', + '11': {'District of Columbia': '001'}, + '12': {'Alachua County, FL': '001', 'Baker County, FL': '003', 'Bay County, FL': '005', 'Bradford County, FL': '007', @@ -3739,7 +3739,7 @@ FIPS_COUNTIES = { 'Wakulla County, FL': '129', 'Walton County, FL': '131', 'Washington County, FL': '133'}, - '13': { 'Appling County, GA': '001', + '13': {'Appling County, GA': '001', 'Atkinson County, GA': '003', 'Bacon County, GA': '005', 'Baker County, GA': '007', @@ -3898,11 +3898,11 @@ FIPS_COUNTIES = { 'Wilkes County, GA': '317', 'Wilkinson County, GA': '319', 'Worth County, GA': '321'}, - '15': { 'Hawaii County, HI': '001', + '15': {'Hawaii County, HI': '001', 'Honolulu County/city, HI': '003', 'Kauai County, HI': '007', 'Maui County, HI': '009'}, - '16': { 'Ada County, ID': '001', + '16': {'Ada County, ID': '001', 'Adams County, ID': '003', 'Bannock County, ID': '005', 'Bear Lake County, ID': '007', @@ -3946,7 +3946,7 @@ FIPS_COUNTIES = { 'Twin Falls County, ID': '083', 'Valley County, ID': '085', 'Washington County, ID': '087'}, - '17': { 'Adams County, IL': '001', + '17': {'Adams County, IL': '001', 'Alexander County, IL': '003', 'Bond County, IL': '005', 'Boone County, IL': '007', @@ -4048,7 +4048,7 @@ FIPS_COUNTIES = { 'Williamson County, IL': '199', 'Winnebago County, IL': '201', 'Woodford County, IL': '203'}, - '18': { 'Adams County, IN': '001', + '18': {'Adams County, IN': '001', 'Allen County, IN': '003', 'Bartholomew County, IN': '005', 'Benton County, IN': '007', @@ -4140,7 +4140,7 @@ FIPS_COUNTIES = { 'Wells County, IN': '179', 'White County, IN': '181', 'Whitley County, IN': '183'}, - '19': { 'Adair County, IA': '001', + '19': {'Adair County, IA': '001', 'Adams County, IA': '003', 'Allamakee County, IA': '005', 'Appanoose County, IA': '007', @@ -4239,7 +4239,7 @@ FIPS_COUNTIES = { 'Woodbury County, IA': '193', 'Worth County, IA': '195', 'Wright County, IA': '197'}, - '20': { 'Allen County, KS': '001', + '20': {'Allen County, KS': '001', 'Anderson County, KS': '003', 'Atchison County, KS': '005', 'Barber County, KS': '007', @@ -4344,7 +4344,7 @@ FIPS_COUNTIES = { 'Wilson County, KS': '205', 'Woodson County, KS': '207', 'Wyandotte County, KS': '209'}, - '21': { 'Adair County, KY': '001', + '21': {'Adair County, KY': '001', 'Allen County, KY': '003', 'Anderson County, KY': '005', 'Ballard County, KY': '007', @@ -4464,7 +4464,7 @@ FIPS_COUNTIES = { 'Whitley County, KY': '235', 'Wolfe County, KY': '237', 'Woodford County, KY': '239'}, - '22': { 'Acadia Parish, LA': '001', + '22': {'Acadia Parish, LA': '001', 'Allen Parish, LA': '003', 'Ascension Parish, LA': '005', 'Assumption Parish, LA': '007', @@ -4528,7 +4528,7 @@ FIPS_COUNTIES = { 'West Carroll Parish, LA': '123', 'West Feliciana Parish, LA': '125', 'Winn Parish, LA': '127'}, - '23': { 'Androscoggin County, ME': '001', + '23': {'Androscoggin County, ME': '001', 'Aroostook County, ME': '003', 'Cumberland County, ME': '005', 'Franklin County, ME': '007', @@ -4544,7 +4544,7 @@ FIPS_COUNTIES = { 'Waldo County, ME': '027', 'Washington County, ME': '029', 'York County, ME': '031'}, - '24': { 'Allegany County, MD': '001', + '24': {'Allegany County, MD': '001', 'Anne Arundel County, MD': '003', 'Baltimore County, MD': '005', 'Baltimore city, MD': '510', @@ -4568,7 +4568,7 @@ FIPS_COUNTIES = { 'Washington County, MD': '043', 'Wicomico County, MD': '045', 'Worcester County, MD': '047'}, - '25': { 'Barnstable County, MA': '001', + '25': {'Barnstable County, MA': '001', 'Berkshire County, MA': '003', 'Bristol County, MA': '005', 'Dukes County, MA': '007', @@ -4582,7 +4582,7 @@ FIPS_COUNTIES = { 'Plymouth County, MA': '023', 'Suffolk County, MA': '025', 'Worcester County, MA': '027'}, - '26': { 'Alcona County, MI': '001', + '26': {'Alcona County, MI': '001', 'Alger County, MI': '003', 'Allegan County, MI': '005', 'Alpena County, MI': '007', @@ -4665,7 +4665,7 @@ FIPS_COUNTIES = { 'Washtenaw County, MI': '161', 'Wayne County, MI': '163', 'Wexford County, MI': '165'}, - '27': { 'Aitkin County, MN': '001', + '27': {'Aitkin County, MN': '001', 'Anoka County, MN': '003', 'Becker County, MN': '005', 'Beltrami County, MN': '007', @@ -4752,7 +4752,7 @@ FIPS_COUNTIES = { 'Winona County, MN': '169', 'Wright County, MN': '171', 'Yellow Medicine County, MN': '173'}, - '28': { 'Adams County, MS': '001', + '28': {'Adams County, MS': '001', 'Alcorn County, MS': '003', 'Amite County, MS': '005', 'Attala County, MS': '007', @@ -4834,7 +4834,7 @@ FIPS_COUNTIES = { 'Winston County, MS': '159', 'Yalobusha County, MS': '161', 'Yazoo County, MS': '163'}, - '29': { 'Adair County, MO': '001', + '29': {'Adair County, MO': '001', 'Andrew County, MO': '003', 'Atchison County, MO': '005', 'Audrain County, MO': '007', @@ -4949,7 +4949,7 @@ FIPS_COUNTIES = { 'Webster County, MO': '225', 'Worth County, MO': '227', 'Wright County, MO': '229'}, - '30': { 'Beaverhead County, MT': '001', + '30': {'Beaverhead County, MT': '001', 'Big Horn County, MT': '003', 'Blaine County, MT': '005', 'Broadwater County, MT': '007', @@ -5005,7 +5005,7 @@ FIPS_COUNTIES = { 'Wheatland County, MT': '107', 'Wibaux County, MT': '109', 'Yellowstone County, MT': '111'}, - '31': { 'Adams County, NE': '001', + '31': {'Adams County, NE': '001', 'Antelope County, NE': '003', 'Arthur County, NE': '005', 'Banner County, NE': '007', @@ -5098,7 +5098,7 @@ FIPS_COUNTIES = { 'Webster County, NE': '181', 'Wheeler County, NE': '183', 'York County, NE': '185'}, - '32': { 'Carson City, NV': '510', + '32': {'Carson City, NV': '510', 'Churchill County, NV': '001', 'Clark County, NV': '003', 'Douglas County, NV': '005', @@ -5115,7 +5115,7 @@ FIPS_COUNTIES = { 'Storey County, NV': '029', 'Washoe County, NV': '031', 'White Pine County, NV': '033'}, - '33': { 'Belknap County, NH': '001', + '33': {'Belknap County, NH': '001', 'Carroll County, NH': '003', 'Cheshire County, NH': '005', 'Coos County, NH': '007', @@ -5125,7 +5125,7 @@ FIPS_COUNTIES = { 'Rockingham County, NH': '015', 'Strafford County, NH': '017', 'Sullivan County, NH': '019'}, - '34': { 'Atlantic County, NJ': '001', + '34': {'Atlantic County, NJ': '001', 'Bergen County, NJ': '003', 'Burlington County, NJ': '005', 'Camden County, NJ': '007', @@ -5146,7 +5146,7 @@ FIPS_COUNTIES = { 'Sussex County, NJ': '037', 'Union County, NJ': '039', 'Warren County, NJ': '041'}, - '35': { 'Bernalillo County, NM': '001', + '35': {'Bernalillo County, NM': '001', 'Catron County, NM': '003', 'Chaves County, NM': '005', 'Cibola County, NM': '006', @@ -5179,7 +5179,7 @@ FIPS_COUNTIES = { 'Torrance County, NM': '057', 'Union County, NM': '059', 'Valencia County, NM': '061'}, - '36': { 'Albany County, NY': '001', + '36': {'Albany County, NY': '001', 'Allegany County, NY': '003', 'Bronx County, NY': '005', 'Broome County, NY': '007', @@ -5241,7 +5241,7 @@ FIPS_COUNTIES = { 'Westchester County, NY': '119', 'Wyoming County, NY': '121', 'Yates County, NY': '123'}, - '37': { 'Alamance County, NC': '001', + '37': {'Alamance County, NC': '001', 'Alexander County, NC': '003', 'Alleghany County, NC': '005', 'Anson County, NC': '007', @@ -5341,7 +5341,7 @@ FIPS_COUNTIES = { 'Wilson County, NC': '195', 'Yadkin County, NC': '197', 'Yancey County, NC': '199'}, - '38': { 'Adams County, ND': '001', + '38': {'Adams County, ND': '001', 'Barnes County, ND': '003', 'Benson County, ND': '005', 'Billings County, ND': '007', @@ -5394,7 +5394,7 @@ FIPS_COUNTIES = { 'Ward County, ND': '101', 'Wells County, ND': '103', 'Williams County, ND': '105'}, - '39': { 'Adams County, OH': '001', + '39': {'Adams County, OH': '001', 'Allen County, OH': '003', 'Ashland County, OH': '005', 'Ashtabula County, OH': '007', @@ -5482,7 +5482,7 @@ FIPS_COUNTIES = { 'Williams County, OH': '171', 'Wood County, OH': '173', 'Wyandot County, OH': '175'}, - '40': { 'Adair County, OK': '001', + '40': {'Adair County, OK': '001', 'Alfalfa County, OK': '003', 'Atoka County, OK': '005', 'Beaver County, OK': '007', @@ -5559,7 +5559,7 @@ FIPS_COUNTIES = { 'Washita County, OK': '149', 'Woods County, OK': '151', 'Woodward County, OK': '153'}, - '41': { 'Baker County, OR': '001', + '41': {'Baker County, OR': '001', 'Benton County, OR': '003', 'Clackamas County, OR': '005', 'Clatsop County, OR': '007', @@ -5595,7 +5595,7 @@ FIPS_COUNTIES = { 'Washington County, OR': '067', 'Wheeler County, OR': '069', 'Yamhill County, OR': '071'}, - '42': { 'Adams County, PA': '001', + '42': {'Adams County, PA': '001', 'Allegheny County, PA': '003', 'Armstrong County, PA': '005', 'Beaver County, PA': '007', @@ -5662,12 +5662,12 @@ FIPS_COUNTIES = { 'Westmoreland County, PA': '129', 'Wyoming County, PA': '131', 'York County, PA': '133'}, - '44': { 'Bristol County, RI': '001', + '44': {'Bristol County, RI': '001', 'Kent County, RI': '003', 'Newport County, RI': '005', 'Providence County, RI': '007', 'Washington County, RI': '009'}, - '45': { 'Abbeville County, SC': '001', + '45': {'Abbeville County, SC': '001', 'Aiken County, SC': '003', 'Allendale County, SC': '005', 'Anderson County, SC': '007', @@ -5713,7 +5713,7 @@ FIPS_COUNTIES = { 'Union County, SC': '087', 'Williamsburg County, SC': '089', 'York County, SC': '091'}, - '46': { 'Aurora County, SD': '003', + '46': {'Aurora County, SD': '003', 'Beadle County, SD': '005', 'Bennett County, SD': '007', 'Bon Homme County, SD': '009', @@ -5779,7 +5779,7 @@ FIPS_COUNTIES = { 'Walworth County, SD': '129', 'Yankton County, SD': '135', 'Ziebach County, SD': '137'}, - '47': { 'Anderson County, TN': '001', + '47': {'Anderson County, TN': '001', 'Bedford County, TN': '003', 'Benton County, TN': '005', 'Bledsoe County, TN': '007', @@ -5874,7 +5874,7 @@ FIPS_COUNTIES = { 'White County, TN': '185', 'Williamson County, TN': '187', 'Wilson County, TN': '189'}, - '48': { 'Anderson County, TX': '001', + '48': {'Anderson County, TX': '001', 'Andrews County, TX': '003', 'Angelina County, TX': '005', 'Aransas County, TX': '007', @@ -6128,7 +6128,7 @@ FIPS_COUNTIES = { 'Young County, TX': '503', 'Zapata County, TX': '505', 'Zavala County, TX': '507'}, - '49': { 'Beaver County, UT': '001', + '49': {'Beaver County, UT': '001', 'Box Elder County, UT': '003', 'Cache County, UT': '005', 'Carbon County, UT': '007', @@ -6157,7 +6157,7 @@ FIPS_COUNTIES = { 'Washington County, UT': '053', 'Wayne County, UT': '055', 'Weber County, UT': '057'}, - '50': { 'Addison County, VT': '001', + '50': {'Addison County, VT': '001', 'Bennington County, VT': '003', 'Caledonia County, VT': '005', 'Chittenden County, VT': '007', @@ -6171,7 +6171,7 @@ FIPS_COUNTIES = { 'Washington County, VT': '023', 'Windham County, VT': '025', 'Windsor County, VT': '027'}, - '51': { 'Accomack County, VA': '001', + '51': {'Accomack County, VA': '001', 'Albemarle County, VA': '003', 'Alexandria city, VA': '510', 'Alleghany County, VA': '005', @@ -6305,7 +6305,7 @@ FIPS_COUNTIES = { 'Wise County, VA': '195', 'Wythe County, VA': '197', 'York County, VA': '199'}, - '53': { 'Adams County, WA': '001', + '53': {'Adams County, WA': '001', 'Asotin County, WA': '003', 'Benton County, WA': '005', 'Chelan County, WA': '007', @@ -6344,7 +6344,7 @@ FIPS_COUNTIES = { 'Whatcom County, WA': '073', 'Whitman County, WA': '075', 'Yakima County, WA': '077'}, - '54': { 'Barbour County, WV': '001', + '54': {'Barbour County, WV': '001', 'Berkeley County, WV': '003', 'Boone County, WV': '005', 'Braxton County, WV': '007', @@ -6399,7 +6399,7 @@ FIPS_COUNTIES = { 'Wirt County, WV': '105', 'Wood County, WV': '107', 'Wyoming County, WV': '109'}, - '55': { 'Adams County, WI': '001', + '55': {'Adams County, WI': '001', 'Ashland County, WI': '003', 'Barron County, WI': '005', 'Bayfield County, WI': '007', @@ -6471,7 +6471,7 @@ FIPS_COUNTIES = { 'Waushara County, WI': '137', 'Winnebago County, WI': '139', 'Wood County, WI': '141'}, - '56': { 'Albany County, WY': '001', + '56': {'Albany County, WY': '001', 'Big Horn County, WY': '003', 'Campbell County, WY': '005', 'Carbon County, WY': '007', @@ -6494,7 +6494,7 @@ FIPS_COUNTIES = { 'Uinta County, WY': '041', 'Washakie County, WY': '043', 'Weston County, WY': '045'}, - '72': { 'Adjuntas Municipio, PR': '001', + '72': {'Adjuntas Municipio, PR': '001', 'Aguada Municipio, PR': '003', 'Aguadilla Municipio, PR': '005', 'Aguas Buenas Municipio, PR': '007', @@ -6572,19 +6572,19 @@ FIPS_COUNTIES = { 'Villalba Municipio, PR': '149', 'Yabucoa Municipio, PR': '151', 'Yauco Municipio, PR': '153'}, - "CA01": { '--All--': '%', }, - "CA02": { '--All--': '%', }, - "CA03": { '--All--': '%', }, - "CA04": { '--All--': '%', }, - "CA05": { '--All--': '%', }, - "CA13": { '--All--': '%', }, - "CA07": { '--All--': '%', }, - "CA14": { '--All--': '%', }, - "CA08": { '--All--': '%', }, - "CA09": { '--All--': '%', }, - "CA10": { '--All--': '%', }, - "CA11": { '--All--': '%', }, - "CA12": { '--All--': '%', }, + "CA01": {'--All--': '%', }, + "CA02": {'--All--': '%', }, + "CA03": {'--All--': '%', }, + "CA04": {'--All--': '%', }, + "CA05": {'--All--': '%', }, + "CA13": {'--All--': '%', }, + "CA07": {'--All--': '%', }, + "CA14": {'--All--': '%', }, + "CA08": {'--All--': '%', }, + "CA09": {'--All--': '%', }, + "CA10": {'--All--': '%', }, + "CA11": {'--All--': '%', }, + "CA12": {'--All--': '%', }, }
@@ -6592,15 +6592,14 @@ if __name__ == "__main__": from sys import argv from pprint import PrettyPrinter pp = PrettyPrinter(indent=2) - + import csv - fipsreader = csv.reader(open(argv[1],'rb'), delimiter=',', quotechar='"') + fipsreader = csv.reader(open(argv[1], 'rb'), delimiter=',', quotechar='"') for row in fipsreader: try: FIPS_COUNTIES[int(row[1])][row[3]] = row[2] except KeyError: FIPS_COUNTIES[int(row[1])] = {'--All--': '%'} FIPS_COUNTIES[int(row[1])][row[3]] = row[2] - + pp.pprint(FIPS_COUNTIES) - \ No newline at end of file diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 54f568f..2824a96 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -70,6 +70,5 @@ ./chirp/wouxun.py ./chirp/wouxun_common.py ./chirp/yaesu_clone.py -./chirpui/fips.py ./tools/bitdiff.py ./tools/img2thd72.py

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 0bb87d9c5b84de44d96edb84f20cc47fa65a6a21
Fix style issues in tools (#2355)
diff --git a/tools/bitdiff.py b/tools/bitdiff.py index a13c63b..d06bdb2 100644 --- a/tools/bitdiff.py +++ b/tools/bitdiff.py @@ -1,81 +1,89 @@ #!/usr/bin/env python # -## Copyright 2013 Jens Jensen AF5MI kd4tjx@yahoo.com +# Copyright 2013 Jens Jensen AF5MI kd4tjx@yahoo.com + +import sys +import os +import argparse +import time
-import sys, os, argparse, time
def printDiff(pos, byte1, byte2, args): - - bits1 = '{0:08b}'.format(byte1) - bits2 = '{0:08b}'.format(byte2) - print "@%04Xh" % pos - print "1:%02Xh, %sb" % (byte1, bits1) - print "2:%02Xh, %sb" % (byte2, bits2) - if args.csv: - writeDiffCSV(pos, byte1, byte2, args) + bits1 = '{0:08b}'.format(byte1) + bits2 = '{0:08b}'.format(byte2) + print "@%04Xh" % pos + print "1:%02Xh, %sb" % (byte1, bits1) + print "2:%02Xh, %sb" % (byte2, bits2) + if args.csv: + writeDiffCSV(pos, byte1, byte2, args) +
def writeDiffCSV(pos, byte1, byte2, args): bits1 = '{0:08b}'.format(byte1) bits2 = '{0:08b}'.format(byte2) csvline = '%s, %s, %04X, %02X, %s, %02X, %s, %s, %s' % \ - (args.file1, args.file2, pos, byte1, bits1, byte2, bits2, args.setting, args.value) + (args.file1, args.file2, pos, byte1, bits1, + byte2, bits2, args.setting, args.value) if not os.path.isfile(args.csv): fh = open(args.csv, "w") - header = "filename1, filename2, byte_offset, byte1, bits1, byte2, bits2, item_msg, value_msg" + header = "filename1, filename2, byte_offset, byte1, " \ + "bits1, byte2, bits2, item_msg, value_msg" fh.write(header + os.linesep) else: fh = open(args.csv, "a") fh.write(csvline + os.linesep) fh.close() - +
def compareFiles(args): - f1 = open(args.file1, "rb") - f1.seek(args.offset) - f2 = open(args.file2, "rb") - f2.seek(args.offset) - - while True: - pos = f1.tell() - args.offset - c1 = f1.read(1) - c2 = f2.read(1) - if not (c1 and c2): - break - b1 = ord(c1) - b2 = ord(c2) - if b1 != b2: - printDiff(pos, b1, b2, args) - - pos = f1.tell() - args.offset - print "bytes read: %02d" % pos - f1.close() - f2.close() + f1 = open(args.file1, "rb") + f1.seek(args.offset) + f2 = open(args.file2, "rb") + f2.seek(args.offset) + + while True: + pos = f1.tell() - args.offset + c1 = f1.read(1) + c2 = f2.read(1) + if not (c1 and c2): + break + b1 = ord(c1) + b2 = ord(c2) + if b1 != b2: + printDiff(pos, b1, b2, args) + + pos = f1.tell() - args.offset + print "bytes read: %02d" % pos + f1.close() + f2.close() +
def compareFilesDat(args): - f1 = open(args.file1, "r") - f1contents = f1.read() - f1.close() - f2 = open(args.file2, "r") - f2contents = f2.read() - f2.close() - - f1strlist = f1contents.split() - f1intlist = map(int, f1strlist) - f2strlist = f2contents.split() - f2intlist = map(int, f2strlist) - f1bytes = bytearray(f1intlist) - f2bytes = bytearray(f2intlist) - - length = len(f1intlist) - for i in range(length): - b1 = f1bytes[i] - b2 = f2bytes[i] - pos = i - if b1 != b2: - printDiff(pos, b1, b2, args) - - pos = length - print "bytes read: %02d" % pos + f1 = open(args.file1, "r") + f1contents = f1.read() + f1.close() + f2 = open(args.file2, "r") + f2contents = f2.read() + f2.close() + + f1strlist = f1contents.split() + f1intlist = map(int, f1strlist) + f2strlist = f2contents.split() + f2intlist = map(int, f2strlist) + f1bytes = bytearray(f1intlist) + f2bytes = bytearray(f2intlist) + + length = len(f1intlist) + for i in range(length): + b1 = f1bytes[i] + b2 = f2bytes[i] + pos = i + if b1 != b2: + printDiff(pos, b1, b2, args) + + pos = length + print "bytes read: %02d" % pos +
def convertFileToBin(args): f1 = open(args.file1, "r") @@ -88,34 +96,53 @@ def convertFileToBin(args): f2.write(f1bytes) f2.close
+ def convertFileToDat(args): f1 = open(args.file1, "rb") f1contents = f1.read() f1.close() f2 = open(args.file2, "w") - for i in range(0, len(f1contents)): + for i in range(0, len(f1contents)): f2.write(" %d " % (ord(f1contents[i]), )) if i % 16 == 15: f2.write("\r\n") f2.close
-# -## main + +# main
ap = argparse.ArgumentParser(description="byte-/bit- comparison of two files") ap.add_argument("file1", help="first (reference) file to parse") ap.add_argument("file2", help="second file to parse") + mutexgrp1 = ap.add_mutually_exclusive_group() -mutexgrp1.add_argument("-o", "--offset", help="offset (hex) to start comparison", default=0) -mutexgrp1.add_argument("-d", "--dat", help="process input files from .DAT/.ADJ format (from 'jujumao' oem programming software for chinese radios)", action="store_true") -mutexgrp1.add_argument("--convert2bin", help="convert file1 from .dat/.adj to binary image file2", action="store_true") -mutexgrp1.add_argument("--convert2dat", help="convert file1 from bin to .dat/.adj file2", action="store_true") -ap.add_argument("-w", "--watch", help="'watch' changes. runs in a loop", action="store_true") +mutexgrp1.add_argument("-o", "--offset", default=0, + help="offset (hex) to start comparison") +mutexgrp1.add_argument("-d", "--dat", action="store_true", + help="process input files from .DAT/.ADJ format " + "(from 'jujumao' oem programming software " + "for chinese radios)") +mutexgrp1.add_argument("--convert2bin", action="store_true", + help="convert file1 from .dat/.adj to " + "binary image file2") +mutexgrp1.add_argument("--convert2dat", action="store_true", + help="convert file1 from bin to .dat/.adj file2") + +ap.add_argument("-w", "--watch", action="store_true", + help="'watch' changes. runs in a loop") + csvgrp = ap.add_argument_group("csv output") -csvgrp.add_argument("-c", "--csv", help="file to append csv results. format: \ - filename1, filename2, byte_offset, byte1, bits1, byte2, bits2, item_msg, value_msg") -csvgrp.add_argument("-s", "--setting", help="user-meaningful field indicating setting/item modified, e.g. 'beep' or 'txtone'") -csvgrp.add_argument("-v", "--value", help="user-meaningful field indicating values changed, e.g. 'true->false' or '110.9->100.0'") +csvgrp.add_argument("-c", "--csv", + help="file to append csv results. format: filename1, " + "filename2, byte_offset, byte1, bits1, byte2, " + "bits2, item_msg, value_msg") +csvgrp.add_argument("-s", "--setting", + help="user-meaningful field indicating setting/item " + "modified, e.g. 'beep' or 'txtone'") +csvgrp.add_argument("-v", "--value", + help="user-meaningful field indicating values " + "changed, e.g. 'true->false' or '110.9->100.0'") + args = ap.parse_args() if args.offset: args.offset = int(args.offset, 16) @@ -130,10 +157,10 @@ while True: elif (args.convert2bin): convertFileToBin(args) elif (args.convert2dat): - convertFileToDat(args) + convertFileToDat(args) else: - compareFiles(args) + compareFiles(args) if not args.watch: - break + break print "------" time.sleep(delay) diff --git a/tools/cpep8.blacklist b/tools/cpep8.blacklist index 2824a96..5d7ad07 100644 --- a/tools/cpep8.blacklist +++ b/tools/cpep8.blacklist @@ -70,5 +70,3 @@ ./chirp/wouxun.py ./chirp/wouxun_common.py ./chirp/yaesu_clone.py -./tools/bitdiff.py -./tools/img2thd72.py diff --git a/tools/img2thd72.py b/tools/img2thd72.py index a68a15c..407bdf7 100644 --- a/tools/img2thd72.py +++ b/tools/img2thd72.py @@ -18,43 +18,46 @@ # along with this software. If not, see http://www.gnu.org/licenses/.
-import sys, getopt +import sys +import getopt from PIL import Image as im
+ def die(msg): print msg sys.exit(1)
+ def thd72bitmap(fname, invert): img = im.open(ifname) - if img.size != (120,48): + if img.size != (120, 48): die("Image has wrong dimensions: must be 120x48") - + colors = img.getcolors() if len(colors) != 2: die("Image must be 1 bits per pixel (black and white)") - - if ('-i','') in opts: - c,black = colors[0] - c,white = colors[1] - else: - c,white = colors[0] - c,black = colors[1]
+ if ('-i', '') in opts: + c, black = colors[0] + c, white = colors[1] + else: + c, white = colors[0] + c, black = colors[1]
- colors = { black: 1, white: 0 } + colors = {black: 1, white: 0} data = img.getdata() buf = '' for y in range(6): for x in range(120): b = 0 for i in range(8): - b |= colors[data[x + 120*(y*8+i)]] << i + b |= colors[data[x + 120 * (y * 8 + i)]] << i buf += chr(b) return buf
+ def display_thd72(buf): - dots = { 0: '*', 1: ' '} + dots = {0: '*', 1: ' '} lines = [] for y in range(48): line = '' @@ -65,8 +68,10 @@ def display_thd72(buf): for l in lines: print l
+ def usage(): - print "\nUsage: %s <-s|-g> [-i] [-d] <image-file> <thd72-nvram-file>" % sys.argv[0] + print "\nUsage: %s <-s|-g> [-i] [-d] " \ + "<image-file> <thd72-nvram-file>" % sys.argv[0] print "\nThis program will modify whatever nvram file provided or will" print "create a new one if the file does not exist. After using this to" print "modify the image, you can use that file to upload all or part of" @@ -112,7 +117,7 @@ if __name__ == "__main__": of.seek(65536) of.close()
- if ('-d','') in opts: + if ('-d', '') in opts: display_thd72(buf)
blocks = [0, ] @@ -120,4 +125,3 @@ if __name__ == "__main__": blocks.append(1+imgpos/256) blocks.append(2+imgpos/256) print "Modified block list:", blocks -
participants (1)
-
Zach Welch