diff --git a/analemma.py b/analemma.py index 1e438fe2..8ed276e5 100755 --- a/analemma.py +++ b/analemma.py @@ -40,19 +40,13 @@ def __init__(self, observer, year, lunar=False, background=None): self.width = 0 self.height = 0 # Even if we're actually showing the moon, call the object self.sun. - if self.lunar: - self.sun = ephem.Moon() - else: - self.sun = ephem.Sun() + self.sun = ephem.Moon() if self.lunar else ephem.Sun() self.sinusoidal = False self.sun_color = (1, 1, 0) self.backside_color = (1, .7, 0) self.text_color = (1, 1, 0) - if background: - self.background_color = background - else: - self.background_color = (0, 0, .6, 1) + self.background_color = background if background else (0, 0, .6, 1) self.special_dot_size = 5 def draw_sun_position(self, date): @@ -398,7 +392,7 @@ def draw(self, widget, ctx, background=None, labels=True): ctx.set_source_rgba(*background) if self.sinusoidal: self.draw_rectangle(0, 0, self.width, self.height) - for f in range(0, int(math.pi * 100)): + for f in range(int(math.pi * 100)): theta = f/200. (x, y) = self.project_sinusoidal(math.pi/2, theta) self.draw_rectangle(x, y, self.width - 2*x, 4) @@ -431,7 +425,7 @@ def draw(self, widget, ctx, background=None, labels=True): # For testing, try replacing 30 with, say, 5000 to see the # motion of the moon over many years. - for i in range(0, 30): + for _ in range(30): self.draw_sun_position(transit) # Also draw lunar analemmas 4 hours earlier and later: diff --git a/androidfiles.py b/androidfiles.py index 5800bb09..e1a4c919 100755 --- a/androidfiles.py +++ b/androidfiles.py @@ -148,9 +148,9 @@ def list_local_dir(path, sorted=True, sizes=False, recursive=False): like foo/bar/baz.jpg. """ path = os.path.normpath(path) - lenpath = len(path) if recursive: file_list = [] + lenpath = len(path) for root, dirs, files in os.walk(path): root = os.path.normpath(root) for f in files: @@ -244,7 +244,7 @@ def copyfile(src, dst, move=False): doesn't create directories first. If move=True, use move rather than copy (remove the src). """ - if not is_android(src) and not is_android(dst): + if not (is_android(src) or is_android(dst)): if move: shutil.move(src, dst) else: @@ -299,10 +299,9 @@ def find_basename_size_match(pair, pairlist): match = None num_matches = 0 for i, p in enumerate(pairlist): - if os.path.basename(p[0]) == base: - if p[1] == pair[1]: - match = i - num_matches += 1 + if os.path.basename(p[0]) == base and p[1] == pair[1]: + match = i + num_matches += 1 if num_matches == 1: return match elif num_matches > 1: @@ -464,11 +463,7 @@ def find_dir_in(thedir, whichlist): # match books whose titles start with the same name as the dir. if not thedir.endswith('/'): thedir += '/' - for pair in whichlist: - if pair[0].startswith(thedir): - return True - - return False + return any(pair[0].startswith(thedir) for pair in whichlist) def remember_needed_dirs(f): """Check full pathname f (from src_ls) to see if its dirname diff --git a/bdump b/bdump index fe55c6a7..349945e9 100755 --- a/bdump +++ b/bdump @@ -22,26 +22,26 @@ def Usage() : print("Usage: %s [-cxd] file ..." % os.path.basename(sys.argv[0])) exit(1) -def parse_opts() : +def parse_opts(): global do_char, do_hex, do_dec, file_list, multi_format num_formats = 0 - for i in range(1, len(sys.argv)) : + for i in range(1, len(sys.argv)): if sys.argv[i][0] != '-' : file_list = sys.argv[i:] break - for c in sys.argv[i][1:] : - if c == 'c' : + for c in sys.argv[i][1:]: + if c == 'c': do_char = True - num_formats = num_formats + 1 - elif c == 'x' : - do_hex = True - num_formats = num_formats + 1 - elif c == 'd' : + num_formats += 1 + elif c == 'd': do_dec = True - num_formats = num_formats + 1 - elif c == 'h' : + num_formats += 1 + elif c == 'h': Usage() + elif c == 'x': + do_hex = True + num_formats += 1 if num_formats == 0 : do_char = True do_hex = True diff --git a/birdcodes.py b/birdcodes.py index 35f5e0f7..6b7b6471 100755 --- a/birdcodes.py +++ b/birdcodes.py @@ -32,11 +32,7 @@ def __init__(self): fields = next(reader) code4 = fields.index('4code') name = fields.index('name') - if 'sci_name' in fields: - sciname = fields.index('sci_name') - else: - sciname = None - + sciname = fields.index('sci_name') if 'sci_name' in fields else None for fields in reader: if sciname: self.allbirds[fields[code4]] = (fields[name], fields[sciname]) @@ -53,11 +49,7 @@ def __init__(self): fields = next(reader) code4 = fields.index('4code') name = fields.index('name') - if 'sci_name' in fields: - sciname = fields.index('sci_name') - else: - sciname = None - + sciname = fields.index('sci_name') if 'sci_name' in fields else None for fields in reader: if fields[code4] in self.allbirds: continue @@ -83,10 +75,7 @@ def match_code(self, matchcode): return None def match_codes(self, matchcodes): - matches = [] - for code in matchcode: - matches.append(self.match_code(code)) - return matches + return [self.match_code(code) for code in matchcode] def match_name(self, matchname, fuzzy=True): matchname = matchname.upper() diff --git a/cachefile.py b/cachefile.py index 790789e2..5d3e2ee9 100755 --- a/cachefile.py +++ b/cachefile.py @@ -218,7 +218,7 @@ def time_bounds(self, starttime=None, endtime=None, day=None, now=None): starttime = self.day_start(day) endtime = self.day_end(day) - elif not starttime and not endtime: + elif not (starttime or endtime): # Set back to the beginning of the day: starttime = self.day_start(now) # and end now. @@ -235,9 +235,11 @@ def time_bounds(self, starttime=None, endtime=None, day=None, now=None): # Else end at the end of the day we started: else: endtime = self.day_end(starttime) - elif starttime.year != endtime.year \ - or starttime.month != endtime.month \ - or starttime.day != endtime.day: + elif not ( + starttime.year == endtime.year + and starttime.month == endtime.month + and starttime.day == endtime.day + ): raise ValueError("time_bounds: %s and %s must start and end on the same day" % (endtime, starttime)) if starttime > endtime: @@ -260,10 +262,7 @@ def get_data(self, starttime=None, endtime=None): data = [] if not endtime: - if starttime: - endtime = self.day_start(starttime) - else: - endtime = datetime.datetime.now() + endtime = self.day_start(starttime) if starttime else datetime.datetime.now() if not starttime: starttime = self.day_start(endtime) diff --git a/cellaut.py b/cellaut.py index 0fbbf22a..4fa924c1 100755 --- a/cellaut.py +++ b/cellaut.py @@ -74,10 +74,7 @@ def __repr__(self): out = '' for row in self.grid: for cell in row: - if self.characters: - out += self.characters[cell] - else: - out += '%3d' % cell + out += self.characters[cell] if self.characters else '%3d' % cell out += '\n' return out @@ -126,18 +123,14 @@ def idle_handler(self, widget): if self.running: return True - def key_press_event(self, widget, event) : - if event.string == "q" : - self.cellgrid.quit() - return True - - if event.string == " " : + def key_press_event(self, widget, event): + if event.string == " ": self.cellgrid.update(self.rule) self.draw() self.running = False return True - if event.string == "c" : + elif event.string == "c": if self.running: return True self.running = True @@ -145,6 +138,10 @@ def key_press_event(self, widget, event) : self.drawing_area) return True + elif event.string == "q": + self.cellgrid.quit() + return True + return False def expose_handler(self, widget, event): diff --git a/cleanhtml.py b/cleanhtml.py index e5d6d8cb..b70a4b39 100755 --- a/cleanhtml.py +++ b/cleanhtml.py @@ -11,7 +11,7 @@ def remove_empty_tags(soup): innerhtml = t.text # print "tag", t # print "innerHTML", innerhtml - if not innerhtml or not innerhtml.strip(): + if not (innerhtml and innerhtml.strip()): t.extract() def prettyprint(soup): diff --git a/conjunctions.py b/conjunctions.py index 3066926d..e9453c97 100755 --- a/conjunctions.py +++ b/conjunctions.py @@ -56,10 +56,7 @@ planets_by_name = ["Moon", "Mercury", "Venus", "Mars", "Jupiter", "Saturn"] -planets_up = {} -for planet in planets: - planets_up[planet.name] = None - +planets_up = {planet.name: None for planet in planets} saw_conjunction = False visible_planets = [] @@ -223,11 +220,7 @@ def conjstr(b1, b2, sepdate, minsep): if hour > sepdate_tuple[3]: sepdate_tuple[2] -= 1 sepdate_tuple[3] = hour - if hour > 12: - hourstr = str(hour-12) + " pm" - else: - hourstr = str(hour) + " am" - + hourstr = str(hour-12) + " pm" if hour > 12 else str(hour) + " am" seps = "POSSIBLE OCCULTATION around " + hourstr else: seps = sepstr(minsep) @@ -350,12 +343,8 @@ def finish_planet(p, d, observer, output_format): observer.date = d transit = observer.previous_transit(body) - ephem.hour * timezone transit = list(ephem.Date(transit).tuple()) - if transit[3] < 3 or transit[3] > 12: - when = "evening" - else: - when = "morning" - - if p == "Venus" or p == "Mercury": + when = "evening" if transit[3] < 3 or transit[3] > 12 else "morning" + if p in ["Venus", "Mercury"]: if when == "evening": isvis = p + " is visible in the early evening sky." else: @@ -386,28 +375,33 @@ def finish_planet(p, d, observer, output_format): isvis += '.' crescents[p] = [ None, None ] - if output_format == "csv" or output_format == "sql": - if p != 'Moon': - if web_image[p]: - img = web_image[p][0] - cred = web_image[p][1] - w = web_image[p][2] - h = web_image[p][3] - else: - img = "" - cred = "" - w = "" - h = "" - - if output_format == "csv": - print("%s,%s,%s,,%s,,%s,%s,%s,%s" % \ - (p, datestr(planets_up[p]), datestr(d), isvis, - img, w, h, cred)) - else: - print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', '%s', %s, %s, '%s' )," % \ - (p, datestr(planets_up[p]), datestr(d), isvis, - img, w, h, cred)) - else: + if ( + output_format == "csv" + and p != 'Moon' + or output_format != "csv" + and output_format == "sql" + and p != 'Moon' + ): + if web_image[p]: + img = web_image[p][0] + cred = web_image[p][1] + w = web_image[p][2] + h = web_image[p][3] + else: + img = "" + cred = "" + w = "" + h = "" + + if output_format == "csv": + print("%s,%s,%s,,%s,,%s,%s,%s,%s" % \ + (p, datestr(planets_up[p]), datestr(d), isvis, + img, w, h, cred)) + else: + print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', '%s', %s, %s, '%s' )," % \ + (p, datestr(planets_up[p]), datestr(d), isvis, + img, w, h, cred)) + elif output_format not in ["csv", "sql"]: print(datestr(planets_up[p]), "to", datestr(d), ":", isvis) planets_up[p] = None diff --git a/countsyl b/countsyl index 1f09f4a1..93d5fc00 100755 --- a/countsyl +++ b/countsyl @@ -47,7 +47,7 @@ def count_syllables(word): if verbose: print("new syllable") minsyl += 1 maxsyl += 1 - elif on_vowel and not in_diphthong and c != lastchar: + elif not in_diphthong and c != lastchar: # We were already in a vowel. # Don't increment anything except the max count, # and only do that once per diphthong. diff --git a/decodemail.py b/decodemail.py index fb5be50d..1b7d1fb4 100755 --- a/decodemail.py +++ b/decodemail.py @@ -39,11 +39,7 @@ def decode_piece(piece): # anything about whether part[0] is str or bytes. # So you have to check the type. for part in decode_header(piece): - if type(part[0]) is bytes: - ret += part[0].decode(errors='replace') - else: - ret += part[0] - + ret += part[0].decode(errors='replace') if type(part[0]) is bytes else part[0] # Special case: the header itself comes out with charset None # and decode doesn't add a space between it and the next part, # even though there was a space in the original. So add one @@ -159,7 +155,7 @@ def decode_file(filename, header_wanted, all=False, casematch=False): all = False if len(sys.argv) > 2: - if sys.argv[1] == '-h' or sys.argv[1] == '--help': + if sys.argv[1] in ['-h', '--help']: print(Usage) sys.exit(1) diff --git a/domaincheck.py b/domaincheck.py index 06e8bd38..d2fff1f5 100755 --- a/domaincheck.py +++ b/domaincheck.py @@ -21,10 +21,9 @@ RETRIES = 1 def get_domain(domainname): - for i in range(RETRIES): + for _ in range(RETRIES): try: - domain = whois.whois(name) - return domain + return whois.whois(name) except socket.timeout: print("%s timed out; retrying" % domainname) except whois.parser.PywhoisError: @@ -63,8 +62,5 @@ def get_domain(domainname): two_months_from_now = two_months_from_now.date() print(format % ("Domain", "Expires", "", "Registrar")) for d in domainlist: - if d[1] < two_months_from_now: - alert = "***" - else: - alert = "" + alert = "***" if d[1] < two_months_from_now else "" print(format % (d[0], d[1].strftime('%Y-%m-%d'), alert, d[2])) diff --git a/eggtimer b/eggtimer index ed3777d3..10856123 100755 --- a/eggtimer +++ b/eggtimer @@ -65,11 +65,7 @@ if __name__ == '__main__': except ValueError: Usage() - if len(sys.argv) > 2: - message = ' '.join(sys.argv[2:]) - else: - message = "Wake up!" - + message = ' '.join(sys.argv[2:]) if len(sys.argv) > 2 else "Wake up!" print("Sleeping for", sleeptime, "seconds with message:", message) # Return control to the shell before sleeping: diff --git a/epubtag.py b/epubtag.py index e0d07aac..4a5b3021 100755 --- a/epubtag.py +++ b/epubtag.py @@ -56,8 +56,6 @@ def parse_contents(self): break if not content: raise RuntimeError('No .opf file in %s' % self.filename) - return - # Now content is a file handle on the content.opf XML file try: self.dom = xml.dom.minidom.parse(content) @@ -180,10 +178,7 @@ def info_string(self, brief=False): if brief: outstr += ', '.join(authors) + ' | ' else: - if len(authors) > 1: - outstr += "Authors: " - else: - outstr += "Author: " + outstr += "Authors: " if len(authors) > 1 else "Author: " outstr += ', '.join(authors) + "\n" tags = self.get_tags() @@ -215,17 +210,13 @@ def add_tags(self, new_tag_list): print("Warning: didn't see any subject tags previously") parent = self.dom.getElementsByTagName("metadata")[0] - # If there's no metadata tag, maybe we should add one, - # but it might be better to throw an error. - if not parent: - raise RuntimeError("No metadata tag! Bailing.") + # If there's no metadata tag, maybe we should add one, + # but it might be better to throw an error. + if not parent: + raise RuntimeError("No metadata tag! Bailing.") # Add the new subject tags after the last one. - if elements: - last_tag_el = elements[-1] - else: - last_tag_el = None - + last_tag_el = elements[-1] if elements else None for new_tag in new_tag_list: # Don't add duplicate tags (case-insensitive). new_tag_lower = new_tag.lower() diff --git a/fincompare.py b/fincompare.py index 08dcb335..2036c26e 100755 --- a/fincompare.py +++ b/fincompare.py @@ -109,7 +109,7 @@ def read_finance_data_alphavantage(ticker, start_date, end_date): print("Hit the API frequency limit. Try again in 1 minute...", end='') sys.stdout.flush() - for i in range(60): + for _ in range(60): print(".", end='') sys.stdout.flush() time.sleep(1) diff --git a/fixbookcover b/fixbookcover index d18347b1..319c1e57 100755 --- a/fixbookcover +++ b/fixbookcover @@ -78,18 +78,6 @@ class BookCoverFixer: print("WARNING: Adding new covers doesn't work yet") return None - self.newcoverfile = "/tmp/cover.jpg" - width, height = (480, 640) - subprocess.call(["convert", - "-size", "%dx%d" % (width, height), - "-background", "white", - "-fill", "black", "-gravity", "center", - "-font", "Times-New-Roman-Bold", - "caption:%s" % ', '.join(self.book.get_titles()), - "-flatten", self.newcoverfile]) - - return self.newcoverfile - def save_changes(self): print("Saving changes, supposedly") print("Replacing %s with %s" % (self.coverzipname, self.newcoverfile)) @@ -191,12 +179,12 @@ class BookCoverFixerWindow(imageviewer.ImageViewerWindow): if event.string == "n": self.next_book(); return - if event.string == "y": - self.do_fix() - return - if event.string == "q": + elif event.string == "q": self.quit() return + elif event.string == "y": + self.do_fix() + return if __name__ == "__main__": fixer = BookCoverFixer() diff --git a/fontasia b/fontasia index 4676d236..c9a0f08a 100755 --- a/fontasia +++ b/fontasia @@ -318,7 +318,7 @@ class FontApp(gtk.Window): treeView.append_column(column) def is_font_in_category(self, fontname, catname): - for i in range(0, len(self.category_buttons)): + for i in range(len(self.category_buttons)): if self.category_buttons[i].get_name() == catname: return ( fontname in self.category_fontlists[i] ) return False @@ -328,7 +328,7 @@ class FontApp(gtk.Window): # else add it. # def toggle_font_in_category(self, fontname, catname): - for i in range(0, len(self.category_buttons)): + for i in range(len(self.category_buttons)): if self.category_buttons[i].get_name() == catname: if fontname in self.category_fontlists[i]: self.category_fontlists[i].remove(fontname) @@ -562,7 +562,7 @@ class FontApp(gtk.Window): if not self.fancy_list: print("set fancy_list=False", file=catfp) - for i in range(0, len(self.category_buttons)): + for i in range(len(self.category_buttons)): catname = self.category_buttons[i].get_name() print(catname + ":", ', '.join(self.category_fontlists[i]), file=catfp) @@ -573,10 +573,7 @@ class FontApp(gtk.Window): btn.set_sensitive(entry.get_text_length() > 0) def category_exists(self, catname): - for btn in self.category_buttons: - if btn.get_name() == catname: - return True - return False + return any(btn.get_name() == catname for btn in self.category_buttons) def add_category(self, newcat, entry=None): if entry: @@ -616,7 +613,7 @@ class FontApp(gtk.Window): btn.get_style_context().remove_class("highlightbtn") def update_category_buttons(self, fontname): - for i in range(0, len(self.category_buttons)): + for i in range(len(self.category_buttons)): if fontname in self.category_fontlists[i]: self.change_button_color(self.category_buttons[i], True) # Can't call set_active because that invokes the diff --git a/fotogr b/fotogr index d94c840f..74f6b3a0 100755 --- a/fotogr +++ b/fotogr @@ -14,7 +14,7 @@ from __future__ import print_function import glob import sys, os -def search_for_keywords(grepdirs, orpats, andpats, notpats, separate) : +def search_for_keywords(grepdirs, orpats, andpats, notpats, separate): """Inside grepdirs, open files named Tags or Keywords. Search those lines looking for matches in the keywords for pats. Each item in grepdirs may be a shell-style pattery, like 20?? @@ -26,11 +26,11 @@ def search_for_keywords(grepdirs, orpats, andpats, notpats, separate) : results = [] for pat in grepdirs: for d in glob.glob(os.path.expanduser(pat)): - for root, dirs, files in os.walk(d) : + for root, dirs, files in os.walk(d): if not files : continue - for f in files : - if f == "Tags" or f == "Keywords": + for f in files: + if f in ["Tags", "Keywords"]: search_for_keywords_in(root, f, orpats, andpats, notpats, separate, results) @@ -98,10 +98,7 @@ def has_match(tags, orpats, andpats, notpats): return False if not orpats: return True - for pat in orpats: - if pat in tags: - return True - return False + return any(pat in tags for pat in orpats) if __name__ == "__main__": # Sadly, we can't use argparse if we want to be able to use -term diff --git a/geojsonmap.py b/geojsonmap.py index ed03d7e0..07601f62 100755 --- a/geojsonmap.py +++ b/geojsonmap.py @@ -50,9 +50,7 @@ ax.add_patch(PolygonPatch(poly, fc=color, ec=BLACK, alpha=0.5, zorder=2 )) # create legend -legend_patches = [] -for c in colormap: - legend_patches.append(mpatches.Patch(color=colormap[c], label=c)) +legend_patches = [mpatches.Patch(color=colormap[c], label=c) for c in colormap] plt.legend(handles=legend_patches, title='Ownership') plt.tight_layout(pad=0, w_pad=0, h_pad=0) diff --git a/gitbranchsync.py b/gitbranchsync.py index c2c36d38..f4adff5d 100755 --- a/gitbranchsync.py +++ b/gitbranchsync.py @@ -177,8 +177,7 @@ def list_branches(repo, add_tracking=False): local_only = [] # local, no remote of same name remote_only = [] # remote, no local of same name - for branch in localbranches: - lb = localbranches[branch] + for branch, lb in localbranches.items(): if lb.tracking_branch(): tracking_branches.append(lb.name) elif lb.name in remotebranches: @@ -280,7 +279,7 @@ def main(): args = parser.parse_args() # By default (no arguments specified), do -cl, i.e. check and list. - if not args.list and not args.check and not args.track: + if not (args.list or args.check or args.track): args.list = True args.check = True diff --git a/gquickbrowse b/gquickbrowse index 9b37ec57..a5d482a1 100755 --- a/gquickbrowse +++ b/gquickbrowse @@ -421,7 +421,7 @@ class WebToolbar(gtk.Toolbar): def zoom_hundred_cb(self, menu_item, web_view): """Zoom 100%""" - if not (web_view.get_zoom_level() == 1.0): + if web_view.get_zoom_level() != 1.0: web_view.set_zoom_level(1.0) def print_cb(self, menu_item, web_view): diff --git a/hotdog.py b/hotdog.py index 0a283b88..07ceafd1 100755 --- a/hotdog.py +++ b/hotdog.py @@ -20,7 +20,7 @@ def fetch_temps(): tmax = piece.high tcrit = piece.critical - if not tcurrent or (not tmax and not tcrit): + if not (tcurrent and (tmax or tcrit)): continue if not tmax: tmax = tcrit @@ -38,10 +38,7 @@ def overtemp(temps): # if random.randint(0, 5) == 0: # return True - for quad in temps: - if quad[1] > quad[2]: - return True - return False + return any(quad[1] > quad[2] for quad in temps) def hoglist(delay=3): """Return a list of processes using a nonzero CPU percentage diff --git a/htmlmail.py b/htmlmail.py index c0790234..87c73b7f 100755 --- a/htmlmail.py +++ b/htmlmail.py @@ -161,7 +161,7 @@ def compose_email_msg(recipients, sender, html, text=None, return msg def contains_non_ascii_characters(s): - return not all(ord(c) < 128 for c in s) + return any(ord(c) >= 128 for c in s) def encode_header(header_txt): if contains_non_ascii_characters(header_txt): diff --git a/imageviewer.py b/imageviewer.py index 1ec3b413..b429b772 100755 --- a/imageviewer.py +++ b/imageviewer.py @@ -279,7 +279,7 @@ def key_press_event(widget, event, imagewin): if event.string == " ": imagewin.next_image() return - if event.string == "q": + elif event.string == "q": gtk.main_quit() return diff --git a/imageviewer3.py b/imageviewer3.py index 3b9aeae8..779d410e 100755 --- a/imageviewer3.py +++ b/imageviewer3.py @@ -38,23 +38,22 @@ def draw(self, widget, cr): # self.xgc_fg = widget.window.new_gc() # self.xgc_fg.set_rgb_fg_color(Gdk.color_parse("yellow")) - if True: - rect = self.get_allocation() - w = rect.width - h = rect.height - if w != self.width or h != self.height: - # get_allocation() gives a number that's too large, - # and if we later try to draw_rectangle() with these - # dimensions, we'll only get half the rectangle horizontally. - # I have no idea why this is happening, but subtracting a - # few pixels from allocation width is a temporary workaround. - self.width = w # -5 - self.height = h - - # Have we had load_image called, but we weren't ready for it? - # Now, theoretically, we are ... so call it again. - if w and h and self.cur_img and not self.pixbuf: - self.prepare_image() + rect = self.get_allocation() + w = rect.width + h = rect.height + if w != self.width or h != self.height: + # get_allocation() gives a number that's too large, + # and if we later try to draw_rectangle() with these + # dimensions, we'll only get half the rectangle horizontally. + # I have no idea why this is happening, but subtracting a + # few pixels from allocation width is a temporary workaround. + self.width = w # -5 + self.height = h + + # Have we had load_image called, but we weren't ready for it? + # Now, theoretically, we are ... so call it again. + if w and h and self.cur_img and not self.pixbuf: + self.prepare_image() self.cr = cr self.show_image() @@ -185,12 +184,6 @@ def show_image(self): def clear(self): return - if not self.xgc_bg: - return - - self.window.draw_rectangle(self.xgc_bg, True, - 0, 0, self.width, self.height) - def draw_text(self, label): ###### NOT YET UPDATED FOR CAIRO AND GTK3 ############ if not self.xgc_fg: @@ -279,7 +272,7 @@ def key_press_event(widget, event, imagewin): if event.string == " ": imagewin.next_image() return - if event.string == "q": + elif event.string == "q": Gtk.main_quit() return diff --git a/imgcpy.py b/imgcpy.py index 69dd065e..fee8e325 100755 --- a/imgcpy.py +++ b/imgcpy.py @@ -52,11 +52,7 @@ def copy_to_clip(imgfile, maxwidth): img = sys.argv[1] - if len(sys.argv) > 2: - width = int(sys.argv[2]) - else: - width = 600 - + width = int(sys.argv[2]) if len(sys.argv) > 2 else 600 copy_to_clip(img, width) diff --git a/ipsearch b/ipsearch index 96ed6495..f5a832af 100755 --- a/ipsearch +++ b/ipsearch @@ -40,9 +40,7 @@ def ping(host): rv = subprocess.call(["ping", "-q", "-c", "1", "-W", "1", host], stdout = subprocess.PIPE, stderr = subprocess.PIPE) - if rv == 0: - return True - return False + return rv == 0 def fping(network): """Ping all hosts on the given network. @@ -158,9 +156,8 @@ def scan(iface, port=None): print(hostip, end='\r') sys.stdout.flush() - if port: - if not check_port(hostip, port): - continue + if port and not check_port(hostip, port): + continue if ping_separately: pingout = ping(hostip) @@ -171,11 +168,7 @@ def scan(iface, port=None): if not mac: continue - if match_mac: - oui = match_mac(mac) - else: - oui = '' - + oui = match_mac(mac) if match_mac else '' try: hostname, blah1, blah2 = socket.gethostbyaddr(hostip) except: diff --git a/kobo/kobo_utils.py b/kobo/kobo_utils.py index 79bb0cb7..27211408 100755 --- a/kobo/kobo_utils.py +++ b/kobo/kobo_utils.py @@ -152,9 +152,9 @@ def list_shelves(self, names=None): else: allshelves[item["ShelfName"]].append(item["ContentId"]) - for shelf in allshelves: + for shelf, value in allshelves.items(): print("\n===", shelf, "===") - for id in allshelves[shelf]: + for id in value: book = self.get_book_by_id(id) if not book: print("Eek, book", id, "doesn't exist") diff --git a/kobo/koboize.py b/kobo/koboize.py index 1133fead..f154cd2a 100755 --- a/kobo/koboize.py +++ b/kobo/koboize.py @@ -48,11 +48,11 @@ def convert_file(filename, destdir): def altertags(soup): counter = 1 for tag in soup.body.find_all(re.compile("^(p|h[1-6])")): - new_tag = soup.new_tag("span", id="kobo.%d.1" % counter) - counter = counter + 1 - tag.wrap(new_tag) - tag.unwrap() - new_tag.wrap(tag) + new_tag = soup.new_tag("span", id="kobo.%d.1" % counter) + counter += 1 + tag.wrap(new_tag) + tag.unwrap() + new_tag.wrap(tag) if __name__ == '__main__': if len(sys.argv) <= 1: diff --git a/langgrep b/langgrep index cf54a77b..a5035d74 100755 --- a/langgrep +++ b/langgrep @@ -146,10 +146,7 @@ def find_files_in_dir(lang, direc): def langgrep(lang, pattern, grepargs, fil, flags): - arglist = ['grep', '-H'] - arglist.extend(grepargs) - arglist.append(pattern) - arglist.append(fil) + arglist = ['grep', '-H', *grepargs, pattern, fil] proc = subprocess.Popen(arglist, shell=False, stdout=subprocess.PIPE) pout = proc.communicate()[0] diff --git a/linkedinify b/linkedinify index 5ce38a62..2d38983c 100755 --- a/linkedinify +++ b/linkedinify @@ -17,7 +17,7 @@ link = primary.wait_for_text() link = link.replace("\n", "").replace("&", "&") + \ "&count=1000&paginationToken=" -if len(sys.argv) > 1 and (sys.argv[1] == '-s' or sys.argv[1] == '--same-tab'): +if len(sys.argv) > 1 and sys.argv[1] in ['-s', '--same-tab']: subprocess.call(["firefox", link]) else: subprocess.call(["firefox", "-new-tab", link]) diff --git a/losalamosmtgs.py b/losalamosmtgs.py index a2685deb..f391543e 100755 --- a/losalamosmtgs.py +++ b/losalamosmtgs.py @@ -75,10 +75,7 @@ def parse_meeting_list(only_past=False): # If there's an Agenda URL, make it absolute. a = field.find("a") href = a.get("href") - if href: - dic[fieldnames[i]] = urljoin(MEETING_LIST_URL, href) - else: - dic[fieldnames[i]] = None + dic[fieldnames[i]] = urljoin(MEETING_LIST_URL, href) if href else None else: dic[fieldnames[i]] = field.text.strip() @@ -338,10 +335,7 @@ def write_rss20_file(mtglist): and not f.endswith('.html'): continue def is_active(f): - for act in active_meetings: - if f.startswith(act): - return True - return False + return any(f.startswith(act) for act in active_meetings) if not is_active(f): print("removing", f) os.unlink(f) diff --git a/mac_lookup.py b/mac_lookup.py index e9f00cdd..771a03f2 100755 --- a/mac_lookup.py +++ b/mac_lookup.py @@ -24197,7 +24197,7 @@ def find_mac_in(instr): if match: fullmac = '%-16s %-17s' % (match.group(), fullmac) - elif len(instr) == 8 or len(instr) == 17: # nn-nn-nn, nn:nn:nn:nn:nn:nn + elif len(instr) in [8, 17]: # nn-nn-nn, nn:nn:nn:nn:nn:nn fullmac = instr mac = "%2s%2s%2s" % (instr[0:2], instr[3:5], instr[6:8]) diff --git a/mapping/election2016/bluered-opendatasoft.py b/mapping/election2016/bluered-opendatasoft.py index f32cf685..7480349a 100755 --- a/mapping/election2016/bluered-opendatasoft.py +++ b/mapping/election2016/bluered-opendatasoft.py @@ -133,9 +133,7 @@ def init_map(): ''' bbox = { 'lllon': -119, 'urlon': -64, 'lllat': 22.0, 'urlat': 50. } - m = map_from_bounding_box(bbox) - - return m + return map_from_bounding_box(bbox) def show_map(): # This gets rid of most of the extra horizontal whitespace, diff --git a/mnist.py b/mnist.py index 8fed49cc..44dd6095 100755 --- a/mnist.py +++ b/mnist.py @@ -112,7 +112,7 @@ def key_press(e): """Exit on ctrl-q. Any other key dismisses this plot and shows the next one. """ - if e.key == 'ctrl+q' or e.key == 'q': + if e.key in ['ctrl+q', 'q']: sys.exit(0) # Matplotlib has no way to distinguish printable keys diff --git a/monmon.py b/monmon.py index d46c658b..c57ea832 100755 --- a/monmon.py +++ b/monmon.py @@ -113,20 +113,12 @@ def find_monitors(self): def active_monitors(self): """List monitors xrandr is actually using""" - active = [] - for mname in self.monitors: - if mname in self.mon_geom: - active.append(mname) - return active + return [mname for mname in self.monitors if mname in self.mon_geom] def inactive_monitors(self): """List monitors that are connected but not being used""" - inactive = [] - for mname in self.monitors: - if mname not in self.mon_geom: - inactive.append(mname) - return inactive + return [mname for mname in self.monitors if mname not in self.mon_geom] def connected_monitors(self): @@ -141,10 +133,7 @@ def print_monitor(self, mon, show_all_modes): try: geom = self.mon_geom[mon['name']] - if self.laptop_screen == mon['name']: - islaptop = " **laptop" - else: - islaptop = "" + islaptop = " **laptop" if self.laptop_screen == mon['name'] else "" print("%s: %4dx%4d Position: (%4d, %4d) mm: %d x %d%s" % (mon['name'], geom['width'], geom['height'], geom['x'], geom['y'], diff --git a/moonpos b/moonpos index c839b805..a8f543fe 100755 --- a/moonpos +++ b/moonpos @@ -32,7 +32,7 @@ def discont_range(start, end, max): end = end%max if start <= end: return list(range(start, end)) - return list(range(start, max)) + list(range(0, end)) + return list(range(start, max)) + list(range(end)) def time_zone_offset(ephemdate): """Get the timezone offset at a given ephem.date @@ -250,10 +250,13 @@ def when_rise_set_at_position(body, observer, targetaz, rise_set, body.compute(observer) az = body.az * DEGREES - if az >= targetaz - slop and az <= targetaz + slop: - if (body.phase > minphase and body.phase < maxphase): - results.append([observer.date, observer.horizon*DEGREES, az, - body.phase]) + if ( + az >= targetaz - slop + and az <= targetaz + slop + and (body.phase > minphase and body.phase < maxphase) + ): + results.append([observer.date, observer.horizon*DEGREES, az, + body.phase]) # Push the date forward a little bit to make sure we get the # next rise/set, not this one again. @@ -335,7 +338,7 @@ if __name__ == '__main__': # # Predict rise/set times: # - if args[0] == "rise" or args[0] == "set": + if args[0] in ["rise", "set"]: try: az = float(args[1]) except ValueError: @@ -397,21 +400,14 @@ if __name__ == '__main__': alt, az, start_hour, end_hour, startdate, days, 5, minphase, maxphase) - if days: - timerange = "%d days" % days - else: - timerange = "year" + timerange = "%d days" % days if days else "year" print("""The %s will be near %.1f, %.1f between %dh and %dh during the next %s at these times: """ % (phasestr, alt, az, start_hour, end_hour, timerange)) print("%26s %5s %5s %s" % ("Date/time range", "Alt", "Az", "Phase")) for r in results: - if len(r) > 4 and r[4]: - phase = "%2d%% illuminated" % r[4] - else: - phase = 'x' - + phase = "%2d%% illuminated" % r[4] if len(r) > 4 and r[4] else 'x' # pargs = tuple(r[0:3] + [phase]) print("%26s %5.1f %5.1f %s" % (timerange_str(r[0], r[1]), r[2], r[3], phase)) diff --git a/motioncam/gmotion_detect.py b/motioncam/gmotion_detect.py index a39796d0..5e093542 100755 --- a/motioncam/gmotion_detect.py +++ b/motioncam/gmotion_detect.py @@ -355,11 +355,7 @@ def red_frame(): #full_res = [3648, 2736] full_res = [1024, 768] - if have_rangefinder: - rangefinder = ME007.ME007(trigger=23, echo=24) - else: - rangefinder = None - + rangefinder = ME007.ME007(trigger=23, echo=24) if have_rangefinder else None md = MotionDetectorViewer(test_res=res, test_borders=test_borders, full_res=full_res, localdir=localdir, remotedir=remotedir, diff --git a/motioncam/motion_detect.py b/motioncam/motion_detect.py index f160afb9..e2c59e6e 100755 --- a/motioncam/motion_detect.py +++ b/motioncam/motion_detect.py @@ -94,11 +94,7 @@ def __init__(self, if sensitivity: self.test_res = test_res - if threshold: - self.threshold = threshold - else: - self.threshold = 20 - + self.threshold = threshold if threshold else 20 self.sensitivity = sensitivity # Should we save debug images, so the user can tell where @@ -425,10 +421,9 @@ def compare_images(self, new_image): for x in range(piece[0][0]-1, piece[0][1]): debug_buf[x, piece[1][0]-1] = (0, 0, 255) debug_buf[x, piece[1][1]-1] = (0, 0, 255) - if changed: - if piece[1][0] > 1: - debug_buf[x, piece[1][0]-2] = (255, 255, 255) - debug_buf[x, piece[1][1]] = (255, 255, 255) + if changed and piece[1][0] > 1: + debug_buf[x, piece[1][0]-2] = (255, 255, 255) + debug_buf[x, piece[1][1]] = (255, 255, 255) for y in range(piece[1][0]-1, piece[1][1]): debug_buf[piece[0][0]-1, y] = (0, 0, 255) debug_buf[piece[0][1]-1, y] = (0, 0, 255) diff --git a/musicplayer.py b/musicplayer.py index 429a9203..2cdb54e6 100755 --- a/musicplayer.py +++ b/musicplayer.py @@ -36,7 +36,6 @@ from mutagen.mp3 import MP3 except: print("No mutagen, won't be able to check song length or adjust speeds") - pass class MusicWin(Gtk.Window): LEFT_KEY = Gdk.KEY_Left @@ -329,8 +328,7 @@ def pause(self, w=None): # else must be MusicWin.STOPPED. Nothing to do. def stop(self, w=None): - if self.play_state == MusicWin.PLAYING \ - or self.play_state == MusicWin.PAUSED: + if self.play_state in [MusicWin.PLAYING, MusicWin.PAUSED]: mixer.music.stop() self.stop_btn.set_label(u"\u25B6") # black right-pointing triangle self.stop_btn.set_tooltip_text("Play") @@ -602,13 +600,13 @@ def timer_func(self): rand = None backward = False if args: - if args[0] == '-r' or args[0] == '--random': + if args[0] in ['-r', '--random']: rand = True args = args[1:] - elif args[0] == '-s' or args[0] == '--sequential': + elif args[0] in ['-s', '--sequential']: rand = False args = args[1:] - elif args[0] == '-b' or args[0] == '--backward': + elif args[0] in ['-b', '--backward']: backward = True rand = False args = args[1:] diff --git a/oppretro/oppretro_ephem.py b/oppretro/oppretro_ephem.py index 307447ec..e64b481e 100755 --- a/oppretro/oppretro_ephem.py +++ b/oppretro/oppretro_ephem.py @@ -65,10 +65,7 @@ def __init__(self, observer): self.planettrack = None def set_time(self, d): - if type(d) is ephem.Date: - self.observer.date = d - else: - self.observer.date = ephem.date(d) + self.observer.date = d if type(d) is ephem.Date else ephem.date(d) def find_opp_and_retro(self, start_date): self.observer.date = start_date @@ -195,7 +192,7 @@ def find_opp_and_retro(self, start_date): print("Difference between opposition and midpoint of retrograde:") if (degdiff > 2): print(degdiff, "degrees") - elif (degdiff * 60. > 2): + elif degdiff > 2 / 60.0: print(degdiff * 60., "arcmin") elif (degdiff > 5): print(degdiff * 3600., "arcsec") diff --git a/oppretro/oppretro_gtk.py b/oppretro/oppretro_gtk.py index bf3a2148..cd2de718 100755 --- a/oppretro/oppretro_gtk.py +++ b/oppretro/oppretro_gtk.py @@ -33,11 +33,7 @@ def __init__(self, location, background=None): oppretro.OppRetro.__init__(self, location) Gtk.Window.__init__(self) - if background: - self.background_color = background - else: - self.background_color = (0, 0, .3, 1) - + self.background_color = background if background else (0, 0, .3, 1) self.planet_color = (1, 1, .5, 1) self.save_all_points = True diff --git a/pathmatch b/pathmatch index d59b1263..f8526014 100755 --- a/pathmatch +++ b/pathmatch @@ -11,14 +11,14 @@ import sys, string, os, types -def getMatchingFiles(pat, files) : +def getMatchingFiles(pat, files): matches = [] lc = pat.lower() - for fil in range(0, len(files)) : + for file in files: #print "Looking for", lc, "in", files[fil] - callfile = files[fil].lower() - if (callfile.find(lc) >= 0) : - matches.append(files[fil]) + callfile = file.lower() + if (callfile.find(lc) >= 0): + matches.append(file) return matches def findPatInPath(pat, pathdirs) : diff --git a/play_chord.py b/play_chord.py index 3b66492a..7ea6d578 100755 --- a/play_chord.py +++ b/play_chord.py @@ -235,7 +235,7 @@ def parse_chord(ns, default_duration=300): chord = None for ns in indnotes: if ns[0] in Notes: - if len(ns) > 1 and (ns[1] == 'b' or ns[1] == '#'): + if len(ns) > 1 and ns[1] in ['b', '#']: # It's a sharp or flat freqlist.append(Notes[ns[:2]]) ns = ns[2:] @@ -306,7 +306,7 @@ def main(): if len(sys.argv) <= 1: return play_some_chords() - if sys.argv[1].lower() == "-h" or sys.argv[1].lower() == "--help": + if sys.argv[1].lower() in ["-h", "--help"]: print("Usage: %s [scale|imperial|cmajor|other note string]") % os.path.basename(sys.argv[0]) return @@ -314,7 +314,7 @@ def main(): # Play a scale return play_notes("C D E F G A2 B2 C2") - if sys.argv[1].lower() == "imperial" or sys.argv[1].lower() == "empire": + if sys.argv[1].lower() in ["imperial", "empire"]: # Play the first line of the Imperial March return play_notes("G G G Eb:.75 Bb2:.25 G Eb:.75 Bb2:.25 G") diff --git a/podcopy b/podcopy index f5a5c29a..3d36da41 100755 --- a/podcopy +++ b/podcopy @@ -33,19 +33,18 @@ def copy_pods(indir, outdir, playlist=None): print("No m3u files in %s" % indir) return + existing_sizes = [] # Get a list of the files already in the output dir. # We'll compare names and sizes to try to avoid duplicate copies. if is_android: ls_out = androidfiles.listdir(outdir, sizes=True) existing_files = [] - existing_sizes = [] for e in ls_out: existing_files.append(e[0]) existing_sizes.append(e[1]) else: existing_files = os.listdir(outdir) - existing_sizes = [] for f in existing_files: statbuf = os.stat(os.path.join(outdir, f)) existing_sizes.append(statbuf.st_size) @@ -120,10 +119,6 @@ def copy_pods(indir, outdir, playlist=None): shutil.copyfile(f, os.path.join(outdir, base + ext)) if __name__ == '__main__': - if len(sys.argv) > 3: - playlist = sys.argv[3] - else: - playlist = None - + playlist = sys.argv[3] if len(sys.argv) > 3 else None copy_pods(sys.argv[1], sys.argv[2], playlist) diff --git a/pulsehelper.py b/pulsehelper.py index fdc6aa92..7055f348 100755 --- a/pulsehelper.py +++ b/pulsehelper.py @@ -93,8 +93,7 @@ def parse_sources_sinks(whichtype): if words[0] == b'index:': # start a new sink if curdict: devs.append(curdict) - curdict = { 'fallback': fallback } - curdict['index'] = words[1].decode() + curdict = {'fallback': fallback, 'index': words[1].decode()} by_index[whichtype][curdict['index']] = curdict elif words[0] == b'name:': diff --git a/pycamera/gphoto.py b/pycamera/gphoto.py index cc979d1c..c4707388 100755 --- a/pycamera/gphoto.py +++ b/pycamera/gphoto.py @@ -86,13 +86,15 @@ def take_still(self, outfile=None, res=None, zoom=None): if outfile and outfile != '-': if outfile[0] == '/': outdir = os.path.split(outfile)[0] - if os.stat(outdir).st_dev != os.stat(os.getcwd()).st_dev: - if self.verbose: - print(outfile, "is not on the same filesystem as", \ - os.getcwd()) - print("Changing directory to", outdir) - os.chdir(outdir) - # XXX should we change back afterward? + if ( + os.stat(outdir).st_dev != os.stat(os.getcwd()).st_dev + and self.verbose + ): + print(outfile, "is not on the same filesystem as", \ + os.getcwd()) + print("Changing directory to", outdir) + os.chdir(outdir) + # XXX should we change back afterward? # gphoto2 will also prompt if the target file already exists, # so we have to rename or remove it. diff --git a/pycamera/piphoto.py b/pycamera/piphoto.py index b97d4cfb..b84f352c 100755 --- a/pycamera/piphoto.py +++ b/pycamera/piphoto.py @@ -58,9 +58,7 @@ def camera_present(self): camdet = subprocess.check_output(["vcgencmd","get_camera"]) # Returns something like: supported=0 detected=0 # Strip the newline and check only the last character: - if int(camdet.strip()[-1]): - return True - return False + return bool(int(camdet.strip()[-1])) def take_still(self, outfile='/tmp/still.jpg', res=[640, 480], format=None): @@ -123,10 +121,7 @@ def take_still_picamera(self, outfile='/tmp/still.jpg', ''' if self.verbose: print("Res:", res) - if res: - res_str = "%dx%d" % tuple(res) - else: - res_str = "(unknown res)" + res_str = "%dx%d" % tuple(res) if res else "(unknown res)" print("Taking %s photo with picamera module" % res_str) with picamera.PiCamera(resolution=res) as camera: diff --git a/pyclip b/pyclip index 4cbccb13..c34a0cf5 100755 --- a/pyclip +++ b/pyclip @@ -93,7 +93,7 @@ def get_selection(): if selection_string != None: break - if selection_string == None: + if selection_string is None: print("Nothing worked, sorry") sys.exit(1) else: diff --git a/qpdf.py b/qpdf.py index 9e31f779..56daeaf4 100755 --- a/qpdf.py +++ b/qpdf.py @@ -258,11 +258,7 @@ def resize_to_fit_content(self): """ if not self.vscrollbar: self.vscrollbar = self.verticalScrollBar() - if self.vscrollbar: - vscrollbarwidth = self.vscrollbar.width() - else: - vscrollbarwidth = 14 - + vscrollbarwidth = self.vscrollbar.width() if self.vscrollbar else 14 # Getting the size of a widget is tricky. # self.widget().width(), for some reason, gives the width minus 12 # pixels, while self.widget().sizeHint().width() gives the diff --git a/qpreso.py b/qpreso.py index e8d72378..f83635ae 100755 --- a/qpreso.py +++ b/qpreso.py @@ -29,10 +29,7 @@ def __init__(self, url=None, curviews=None, fullscreen=False, monitor=-1, super().__init__() - if not curviews: - self._windows = [] - else: - self._windows = curviews + self._windows = [] if not curviews else curviews self._windows.append(self) # Are we making screenshots? TODO: make this a command-line param. @@ -47,10 +44,7 @@ def __init__(self, url=None, curviews=None, fullscreen=False, monitor=-1, # Size of the window we'll actually display. # XXX Currently assumes a projector at 1024x768 # and should be made more general. - if show_notes: - self.fullwidth = 1366 - else: - self.fullwidth = 1024 + self.fullwidth = 1366 if show_notes else 1024 self.fullheight = 768 if zoom != 1.0 : @@ -109,8 +103,7 @@ def createWindow(self, wintype): # WebDialog: A JavaScript-created window # WebBrowserBackgroundTab: A new tab that isn't immediately active - if wintype == QWebEnginePage.WebBrowserWindow or \ - wintype == QWebEnginePage.WebDialog: + if wintype in [QWebEnginePage.WebBrowserWindow, QWebEnginePage.WebDialog]: v = PresoView('about:blank', curviews=self._windows) # v.resize(640, 480) v.show() diff --git a/quickbrowse.py b/quickbrowse.py index bb523633..2e3c08cc 100755 --- a/quickbrowse.py +++ b/quickbrowse.py @@ -76,11 +76,7 @@ def keyPressEvent(self, event): if handle_pdf: class PDFBrowserView(qpdf.PDFScrolledWidget): def __init__(self, browserwin, url, parent=None): - if url.startswith('file://'): - self.theurl = url[7:] - else: - self.theurl = url - + self.theurl = url[7:] if url.startswith('file://') else url super().__init__(self.theurl, parent=parent) def url(self): @@ -538,11 +534,7 @@ def eventFilter(self, object, event): return super().eventFilter(object, event) def new_tab(self, url=None): - if url: - init_name = url[:self.init_tab_name_len] - else: - init_name = "New tab" - + init_name = url[:self.init_tab_name_len] if url else "New tab" if is_pdf(url): webview = PDFBrowserView(self, url) self.browserviews.append(webview) @@ -776,7 +768,6 @@ def find_proc_by_name(name): return int(proc) except Exception as e: print("Exception", e) - pass return None args = parse_args() diff --git a/quotekiosk.py b/quotekiosk.py index 54197376..f6f36033 100755 --- a/quotekiosk.py +++ b/quotekiosk.py @@ -307,10 +307,7 @@ def fade_cb(self): self.content_area.queue_draw() - if self.d_alpha: - return True - - return False + return bool(self.d_alpha) def key_press(self, widget, event): """Handle a key press event anywhere in the window""" diff --git a/randombg b/randombg index 4ae195aa..b2f24b5a 100755 --- a/randombg +++ b/randombg @@ -42,7 +42,7 @@ while True: height = int(parts[1]) break fp.close() -if not width or not height: +if not (width and height): print("Couldn't find screen dimensions!") sys.exit(1) diff --git a/randomline b/randomline index 125494c5..c8819de4 100755 --- a/randomline +++ b/randomline @@ -29,11 +29,7 @@ def randomline(fp): if __name__ == '__main__': random.seed() - if len(sys.argv) > 1: - fp = open(sys.argv[1]) - else: - fp = sys.stdin - + fp = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin print(randomline(fp)) diff --git a/rise_set_az.py b/rise_set_az.py index 2783630f..3c2bd4a9 100755 --- a/rise_set_az.py +++ b/rise_set_az.py @@ -26,9 +26,8 @@ def find_rise_set(observer, body, rise, start, end, targetaz, phase, slop): observer.date = observer.next_setting(body) body.compute(observer) - if phase > 0: - if abs(body.phase - phase) > PHASESLOP: - continue + if phase > 0 and abs(body.phase - phase) > PHASESLOP: + continue if abs(body.az - targetaz) < slop: print("%s: %.1f at %d%% illuminated" % (observer.date, @@ -132,11 +131,7 @@ def observer_for_city(city): ele = re.findall(floatexp, obsparts[2])[0].strip() else: ele = '0' - if len(obsparts) > 3: - obsname = ','.join(obsparts[3:]).strip() - else: - obsname = 'Custom' - + obsname = ','.join(obsparts[3:]).strip() if len(obsparts) > 3 else 'Custom' print("lat", lat, "lon", lon, "ele", ele, "obsname", obsname) observer = ephem.Observer() @@ -159,11 +154,7 @@ def observer_for_city(city): print("Observer:", observer) - if args.sun: - body = ephem.Sun() - else: - body = ephem.Moon() - + body = ephem.Sun() if args.sun else ephem.Moon() rise = not args.set if rise: print("Finding %srises" % body.name) diff --git a/rpi/HC_SR04.py b/rpi/HC_SR04.py index 896a13d7..757d5db8 100755 --- a/rpi/HC_SR04.py +++ b/rpi/HC_SR04.py @@ -73,7 +73,7 @@ def measure_distance_in(self, verbose=False): def average_distance_in(self, samples=3, verbose=False): tot = 0.0 - for i in xrange(samples): + for _ in xrange(samples): tot += self.measure_distance_in(verbose) time.sleep(0.1) return tot / samples diff --git a/rpi/pisoothe b/rpi/pisoothe index 191bc319..4b7a9c43 100755 --- a/rpi/pisoothe +++ b/rpi/pisoothe @@ -151,18 +151,16 @@ class SoundPlayer : self.curpath = None return poll - def is_done(self) : + def is_done(self): '''Simpler version of retcode: returns True if the process is finished, False otherwise. ''' if not self.current : return True - if self.poll() != None : - return True - return False + return self.poll() != None - def wait(self) : - if self.current and self.current.poll() == None : + def wait(self): + if self.current and self.current.poll() is None: self.current.wait() class KeyReader : diff --git a/skyalignments.py b/skyalignments.py index 4b3c6825..848808f4 100755 --- a/skyalignments.py +++ b/skyalignments.py @@ -171,10 +171,7 @@ def read_waypoint_file_CSV(filename): for row in reader: # Each row is an OrderedDict try: - if 'elevation' in row: - ele = float(row['elevation']) - else: - ele = 0 + ele = float(row['elevation']) if 'elevation' in row else 0 point = [ row['name'], float(row['latitude']), float(row['latitude']), ele ] diff --git a/tee.py b/tee.py index 37e49ed4..123684a7 100755 --- a/tee.py +++ b/tee.py @@ -15,9 +15,9 @@ def __init__(self, _fd1, _fd2): self.fd2 = _fd2 def __del__(self): - if self.fd1 != sys.stdout and self.fd1 != sys.stderr: + if self.fd1 not in [sys.stdout, sys.stderr]: self.fd1.close() - if self.fd2 != sys.stdout and self.fd2 != sys.stderr: + if self.fd2 not in [sys.stdout, sys.stderr]: self.fd2.close() def write(self, text): diff --git a/test/test_cachefile.py b/test/test_cachefile.py index af11d18c..86c722ee 100755 --- a/test/test_cachefile.py +++ b/test/test_cachefile.py @@ -37,13 +37,10 @@ def fetch_one_day_data(self, day): 'int': 99, 'str': "Goodbye", 'float': 1000. } ] elif day.year == 2018 and day.month == 2: - data = [] - for hour in range(24): - data.append( { 'time': datetime.datetime(2018, 2, day.day, + return [{ 'time': datetime.datetime(2018, 2, day.day, hour, 0, 0), 'int': hour, 'str': "Hello, world", - 'float': day.day + hour/100. }) - return data + 'float': day.day + hour/100. } for hour in range(24)] else: morning = self.day_start(day) return [ { 'time': morning + datetime.timedelta(hours=2), @@ -72,12 +69,10 @@ def __init__(self, *args, **kwargs): # executed prior to each test def setUp(self): self.cache.clean_cachedir() - pass # executed after each test def tearDown(self): self.cache.clean_cachedir() - pass def test_cache_just_starttime(self): diff --git a/transimageviewer.py b/transimageviewer.py index 84780f57..76e96de9 100755 --- a/transimageviewer.py +++ b/transimageviewer.py @@ -37,7 +37,7 @@ def key_press_event(self, widget, event): if event.string == " ": imagewin.next_image() return - if event.string == "q": + elif event.string == "q": gtk.main_quit() return diff --git a/tweet b/tweet index aa64172e..d1c8d42c 100755 --- a/tweet +++ b/tweet @@ -72,9 +72,9 @@ def playList(lis) : def tweet(args): matches = getMatchingFiles(args) # If we have more than one, prompt the user: - while len(matches) > 1 : + while len(matches) > 1: # Prettyprint the list of matches so the user can choose. - for m in range(0, len(matches)) : + for m in range(len(matches)): dot = matches[m].rfind(".") if dot < 0 : continue diff --git a/vol b/vol index aa04b6ff..5bf99392 100755 --- a/vol +++ b/vol @@ -72,8 +72,8 @@ def create_window(vol, verticalP) : # main vertical = 0 -if len(sys.argv) > 1 : - if sys.argv[1] == "-v" or sys.argv[1] == "-V" : +if len(sys.argv) > 1: + if sys.argv[1] in ["-v", "-V"]: vertical = 1 elif sys.argv[1] != "-h" : Usage() diff --git a/vote411export.py b/vote411export.py index ce332c2d..caddc623 100755 --- a/vote411export.py +++ b/vote411export.py @@ -48,7 +48,7 @@ def __init__(self, name, lastname, office, party, questions, answers): self.party = 'Democrat' elif party == 'Rep': self.party = 'Republican' - elif party == 'Lib' or party == 'L': + elif party in ['Lib', 'L']: self.party = 'Libertarian' else: self.party = party diff --git a/waymaker b/waymaker index 93e78be8..23ee3337 100755 --- a/waymaker +++ b/waymaker @@ -51,10 +51,7 @@ xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/ for ent in entries: print('' % (ent[0], ent[1]), file=fp) - if omit_address: - addy = '\n'.join(ent[2].split('\n')[2:]) - else: - addy = ent[2] + addy = '\n'.join(ent[2].split('\n')[2:]) if omit_address else ent[2] print('%s' % addy, file=fp) print('', file=fp) @@ -208,11 +205,7 @@ def read_description_file(filename): if re.search('\S{27,}', line): print("Skipping long line: '%s'" % line) continue - if cur_ent[2]: - cur_ent[2] += '\n' + cgi.escape(line) - else: - cur_ent[2] += cgi.escape(line) - + cur_ent[2] += '\n' + cgi.escape(line) if cur_ent[2] else cgi.escape(line) if cur_ent: entries.append(cur_ent) diff --git a/weather/noaatemps.py b/weather/noaatemps.py index 9e58a01a..be5255b9 100755 --- a/weather/noaatemps.py +++ b/weather/noaatemps.py @@ -101,7 +101,7 @@ def add_obs(self, line) : self.tots[field][month] += val self.num_obs[field][month] += 1 -def findstations(stationnames) : +def findstations(stationnames): '''Search through ish-history.txt for given station names. stationnames is a list of strings like 'KSJC' and we return a dictionary of lists of the first two numbers from the @@ -115,12 +115,11 @@ def findstations(stationnames) : ''' result = {} ish = open('ish-history.txt') - for line in ish : - for station in stationnames : - if station not in result.keys() : - if station == line[52:56] : - result[station] = [ line[0:6], line[7:12], - line[13:43].strip() ] + for line in ish: + for station in stationnames: + if station not in result.keys() and station == line[52:56]: + result[station] = [ line[0:6], line[7:12], + line[13:43].strip() ] ish.close() return result diff --git a/weather/wunderwx.py b/weather/wunderwx.py index 569d7c84..0777194e 100755 --- a/weather/wunderwx.py +++ b/weather/wunderwx.py @@ -82,9 +82,8 @@ def print_conditions(conditions): def conditions_at_station(stationid): r = requests.get('http://api.wunderground.com/api/%s/conditions/q/pws:%s.json' % (wunderkey, stationid)) - conditions = json.loads(r.text) # pprint(conditions) - return conditions + return json.loads(r.text) if __name__ == '__main__': init_key() diff --git a/wikitable.py b/wikitable.py index 08667a14..044f59fc 100755 --- a/wikitable.py +++ b/wikitable.py @@ -28,7 +28,7 @@ def parse_table(inurl, outfile): if i == 0: if cells != last_headers: last_headers = cells - writer.writerow(cells) + writer.writerow(last_headers) continue # print '\t'.join(cells) diff --git a/wpnet.py b/wpnet.py index 01fa6cea..b9fbe56e 100755 --- a/wpnet.py +++ b/wpnet.py @@ -142,11 +142,7 @@ def get_available_accesspoints(iface): words = line.strip().split(maxsplit=4) # Get the ssid if it's not hidden, else use the MAC - if len(words) == 4: - ssid = '[%s]' % words[0] - else: - ssid = words[4] - + ssid = '[%s]' % words[0] if len(words) == 4 else words[4] aps[ssid] = { 'MAC': words[0], 'flags': words[3], 'signal': int(words[2]),