Simplify looping across Gramps.

Index based loops across the Gramps project
are mapped to their Pythonic equalivant.

Many of these improves radability, and a
some of them improves performance by being
lazy evaluated.
This commit is contained in:
Baizley 2019-12-21 12:13:04 +01:00 committed by Nick Hall
parent 8777c11811
commit 7248f073f0
44 changed files with 121 additions and 172 deletions

View File

@ -255,8 +255,7 @@ class ArgParser:
# Some args can work on a list of databases:
if leftargs:
for opt_ix in range(len(options)):
option, value = options[opt_ix]
for option, value in options:
if option in ['-L', '-l', '-t']:
self.database_names = leftargs
leftargs = []
@ -269,8 +268,7 @@ class ArgParser:
) % leftargs[0],
file=sys.stderr)
#see if force open is on
for opt_ix in range(len(options)):
option, value = options[opt_ix]
for option, value in options:
if option in ('-u', '--force-unlock'):
self.force_unlock = True
break
@ -279,8 +277,7 @@ class ArgParser:
# Go over all given option and place them into appropriate lists
cleandbg = []
need_to_quit = False
for opt_ix in range(len(options)):
option, value = options[opt_ix]
for opt_ix, (option, value) in enumerate(options):
if option in ['-O', '--open']:
self.open = value
elif option in ['-C', '--create']:
@ -345,10 +342,9 @@ class ArgParser:
from gramps.gen.config import config
print(_("Gramps config settings from %s:"
) % config.filename)
for sect in config.data:
for setting in config.data[sect]:
print("%s.%s=%s" % (sect, setting,
repr(config.data[sect][setting])))
for sect, settings in config.data.items():
for setting, value in settings.items():
print("%s.%s=%s" % (sect, setting, repr(value)))
print()
sys.exit(0)
elif option in ['-c', '--config']:
@ -438,8 +434,7 @@ class ArgParser:
sys.exit(0) # Done with Default
#clean options list
cleandbg.reverse()
for ind in cleandbg:
for ind in reversed(cleandbg):
del options[ind]
if (len(options) > 0

View File

@ -94,6 +94,9 @@ class TestArgParser(unittest.TestCase):
argument_parser.errors
)
def test_option_with_multiple_arguments(self):
argument_parser = self.create_parser('-l', 'family_tree_name')
self.assertEqual(argument_parser.database_names, ['family_tree_name'])
if __name__ == "__main__":
unittest.main()

View File

@ -2008,8 +2008,7 @@ class DbWriteBase(DbReadBase):
birth_ref_index = -1
death_ref_index = -1
event_ref_list = person.get_event_ref_list()
for index in range(len(event_ref_list)):
ref = event_ref_list[index]
for index, ref in enumerate(event_ref_list):
event = self.get_event_from_handle(ref.ref)
if (event.type.is_birth()
and ref.role.is_primary()

View File

@ -53,8 +53,8 @@ class ParamFilter(GenericFilter):
# Need to change existing params one by one to keep
# the correct number of arguments
new_list = rule.list[:]
for ix in range(len(self.param_list)):
new_list[ix] = self.param_list[ix]
for index, param in enumerate(self.param_list):
new_list[index] = param
rule.set_list(new_list)
for rule in self.flist:
if rule.nrprepare > 0:

View File

@ -81,7 +81,7 @@ class Rule:
if self.nrprepare == 0:
if self.use_regex:
self.regex = [None]*len(self.labels)
for i in range(len(self.labels)):
for i in enumerate(self.labels):
if self.list[i]:
try:
self.regex[i] = re.compile(self.list[i], re.I)
@ -141,10 +141,10 @@ class Rule:
def display_values(self):
"""Return the labels and values of this rule."""
l_v = ('%s="%s"' % (_(self.labels[ix][0] if
isinstance(self.labels[ix], tuple) else
self.labels[ix]), self.list[ix])
for ix in range(len(self.list)) if self.list[ix])
l_v = ('%s="%s"' % (_(self.labels[index][0] if
isinstance(self.labels[index], tuple) else
self.labels[index]), item)
for index, item in enumerate(self.list) if item)
return ';'.join(l_v)

View File

@ -235,7 +235,7 @@ class ParserDateTest(BaseDateTest):
Date displayer and parser tests.
"""
def do_case(self, testset):
for date_format in range(len(get_date_formats())):
for date_format in enumerate(get_date_formats()):
set_format(date_format)
for dateval in date_tests[testset]:

View File

@ -300,9 +300,7 @@ def string_trim(font, text, width, ellipses = "..."):
# find the part that is < width
retval = ""
sumlen = 0
length = 0
for i in range(len(text)):
c = text[i]
for c in text:
try:
length = l[ord(c)]
except:
@ -325,9 +323,7 @@ def string_trim(font, text, width, ellipses = "..."):
# too long; try again with ellipses
retval = ""
sumlen = 0
length = 0
for i in range(len(text)):
c = text[i]
for c in text:
try:
length = l[ord(c)]
except:

View File

@ -516,10 +516,9 @@ class BookList:
'length="%d">\n' % (
escape(option_name),
len(options[option_name])))
for list_index in range(len(option_value)):
option_type = type_name(
option_value[list_index])
value = escape(str(option_value[list_index]))
for list_index, v in enumerate(option_value):
option_type = type_name(v)
value = escape(str(v))
value = value.replace('"', '&quot;')
b_f.write(' <listitem number="%d" '
'type="%s" value="%s"/>\n' % (
@ -557,7 +556,7 @@ class BookList:
b_f.write(' <size value="%f %f"/>'
'\n' % (size[0], size[1]))
if book.get_margins():
for pos in range(len(book.get_margins())):
for pos in enumerate(book.get_margins()):
b_f.write(' <margin number="%s" '
'value="%f"/>\n' % (
pos, book.get_margin(pos)))

View File

@ -497,7 +497,7 @@ class OptionListCollection(_options.OptionListCollection):
% (size[0], size[1]))
if option_list.get_margins():
margins = option_list.get_margins()
for pos in range(len(margins)):
for pos in enumerate(margins):
file.write(' <margin number="%s" value="%f"/>\n'
% (pos, margins[pos]))

View File

@ -107,10 +107,10 @@ def roman(num):
nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L',
'XL', 'X', 'IX', 'V', 'IV', 'I')
retval = ""
for i in range(len(vals)):
amount = int(num / vals[i])
for i, value in enumerate(vals):
amount = int(num / value)
retval += nums[i] * amount
num -= vals[i] * amount
num -= value * amount
return retval
#-------------------------------------------------------------------------

View File

@ -151,45 +151,25 @@ class RecentFiles:
"""
Rename a file in the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and change that item
found = True
for recent_file in self.gramps_recent_files:
if recent_file.get_name() == filename:
recent_file.set_name(new_filename)
break
if found:
self.gramps_recent_files[index].set_name(new_filename)
def remove_filename(self, filename):
"""
Remove a file from the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and pop that item
found = True
for index, recent_file in enumerate(self.gramps_recent_files):
if recent_file.get_name() == filename:
self.gramps_recent_files.pop(index)
break
if found:
self.gramps_recent_files.pop(index)
def check_if_recent(self, filename):
"""
Check if a file is present in the recent files list.
"""
# First we need to walk the existing items to see
# if our item is already there
found = False
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and pop that item
found = True
break
return found
return any(filename == recent_file.get_name() for recent_file in self.gramps_recent_files)
def save(self):
"""
@ -213,9 +193,7 @@ class RecentFiles:
fcntl.lockf(xml_file, fcntl.LOCK_EX)
xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
xml_file.write('<RecentFiles>\n')
index = 0
for item in self.gramps_recent_files:
index += 1
for index, item in enumerate(self.gramps_recent_files):
if index > MAX_GRAMPS_ITEMS:
break
xml_file.write(' <RecentItem>\n')

View File

@ -70,7 +70,7 @@ class SimpleTable:
Set the columns
"""
self._columns = [str(col) for col in cols]
self._sort_vals = [[] for i in range(len(self._columns))]
self._sort_vals = [[] for i in self._columns]
def row_sort_val(self, col, val):
"""
@ -93,8 +93,7 @@ class SimpleTable:
retval = []
row = len(self._rows)
self._raw_data.append([])
for col in range(len(data)):
item = data[col]
for col, item in enumerate(data):
self._raw_data[-1].append(item)
# FIXME: add better text representations of these objects
if item is None:

View File

@ -234,7 +234,7 @@ class GalleryTab(ButtonTab, DbGUIElement):
while node is not None:
newlist.append(self.iconmodel.get_value(node, 2))
node = self.iconmodel.iter_next(node)
for i in range(len(self.media_list)):
for i in self.media_list:
self.media_list.pop()
for i in newlist:
if i:

View File

@ -186,7 +186,7 @@ class SurnameTab(EmbeddedList):
the model
"""
new_list = []
for idx in range(len(self.model)):
for idx in enumerate(self.model):
node = self.model.get_iter(idx)
surn = self.model.get_value(node, 5)
surn.set_prefix(self.model.get_value(node, 0))
@ -318,7 +318,7 @@ class SurnameTab(EmbeddedList):
#obtain current value
node = self.model.get_iter(path)
old_val = self.model.get_value(node, colnr)
for nr in range(len(self.obj.get_surname_list())):
for nr in enumerate(self.obj.get_surname_list()):
if nr == int(path[0]):
if old_val:
#True remains True

View File

@ -141,15 +141,15 @@ class EditDate(ManagedWindow):
self.calendar_box.connect('changed', self.switch_calendar)
self.quality_box = self.top.get_object('quality_box')
for item_number in range(len(QUAL_TEXT)):
self.quality_box.append_text(QUAL_TEXT[item_number][1])
if self.date.get_quality() == QUAL_TEXT[item_number][0]:
for item_number, item in enumerate(QUAL_TEXT):
self.quality_box.append_text(item[1])
if self.date.get_quality() == item[0]:
self.quality_box.set_active(item_number)
self.type_box = self.top.get_object('type_box')
for item_number in range(len(MOD_TEXT)):
self.type_box.append_text(MOD_TEXT[item_number][1])
if self.date.get_modifier() == MOD_TEXT[item_number][0]:
for item_number, item in enumerate(MOD_TEXT):
self.type_box.append_text(item[1])
if self.date.get_modifier() == item[0]:
self.type_box.set_active(item_number)
self.type_box.connect('changed', self.switch_type)

View File

@ -988,8 +988,7 @@ class EditPerson(EditPrimary):
inorder = True
prev_date = 0
handle_list = [ref.ref for ref in child_ref_list]
for i in range(len(handle_list)):
child_handle = handle_list[i]
for child_handle in handle_list:
child = self.db.get_person_from_handle(child_handle)
if child.get_birth_ref():
event_handle = child.get_birth_ref().ref

View File

@ -547,8 +547,7 @@ class ExportAssistant(ManagedWindow, Gtk.Assistant):
selected one.
"""
for ix in range(len(self.format_buttons)):
button = self.format_buttons[ix]
for ix, button in enumerate(self.format_buttons):
if button.get_active():
return ix
return 0

View File

@ -221,8 +221,8 @@ class CommandLineTool:
vals = self.options_help[self.show][2]
if isinstance(vals, (list, tuple)):
if self.options_help[self.show][3]:
for num in range(len(vals)):
print(" %d\t%s" % (num, vals[num]))
for num, value in enumerate(vals):
print(" %d\t%s" % (num, value))
else:
for val in vals:
print(" %s" % val)

View File

@ -149,7 +149,7 @@ class BaseSelector(ManagedWindow):
parent_path = self.model.get_path(parent_iter)
if parent_path:
parent_path_list = parent_path.get_indices()
for i in range(len(parent_path_list)):
for i in enumerate(parent_path_list):
expand_path = Gtk.TreePath(
tuple([x for x in parent_path_list[:i+1]]))
self.tree.expand_row(expand_path, False)
@ -165,8 +165,7 @@ class BaseSelector(ManagedWindow):
def add_columns(self,tree):
tree.set_fixed_height_mode(True)
titles = self.get_column_titles()
for ix in range(len(titles)):
item = titles[ix]
for ix, item in enumerate(titles):
if item[2] == BaseSelector.NONE:
continue
elif item[2] == BaseSelector.TEXT:
@ -302,7 +301,7 @@ class BaseSelector(ManagedWindow):
#sorting arrow in column header (not on start, only on click)
if not self.setupcols :
for i in range(len(self.columns)):
for i in enumerate(self.columns):
enable_sort_flag = (i==self.sort_col)
self.columns[i].set_sort_indicator(enable_sort_flag)
self.columns[self.sort_col].set_sort_order(self.sortorder)

View File

@ -275,9 +275,9 @@ class UIManager():
parent = self.et_xml.find(".//*[@id='%s'].." % el_id)
if parent:
# we found it, now delete original, inset updated
for indx in range(len(parent)):
if parent[indx].get('id') == el_id:
del parent[indx]
for indx, p in enumerate(parent):
if p.get('id') == el_id:
del p
parent.insert(indx, update)
else:
# updated item not present in original, just add it
@ -314,7 +314,7 @@ class UIManager():
# find parent of id'd element
element = self.et_xml.find(".//*[@id='%s']" % el_id)
if element: # element may have already been deleted
for dummy in range(len(element)):
for dummy in element:
del element[0]
#results = ET.tostring(self.et_xml, encoding="unicode")
#LOG.info(results)

View File

@ -423,7 +423,7 @@ class ListView(NavigationView):
parent_path = self.model.get_path(parent_iter)
if parent_path:
parent_path_list = parent_path.get_indices()
for i in range(len(parent_path_list)):
for i in enumerate(parent_path_list):
expand_path = Gtk.TreePath(
tuple([x for x in parent_path_list[:i+1]]))
self.list.expand_row(expand_path, False)

View File

@ -412,8 +412,8 @@ class FlatNodeMap:
"""
#remove it from the full list first
if not self._identical:
for indx in range(len(self._fullhndl)):
if self._fullhndl[indx][1] == handle:
for indx, hndle in enumerate(self._fullhndl):
if self.hndle[1] == handle:
del self._fullhndl[indx]
break
#now remove it from the index maps

View File

@ -711,7 +711,7 @@ class TreeBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel):
does not update for every change signal.
"""
if node.children:
rows = list(range(len(node.children)-1,-1,-1))
rows = reversed(node.children)
if node.parent is None:
path = iter = None
else:

View File

@ -422,7 +422,7 @@ class FanChartBaseWidget(Gtk.DrawingArea):
divs = [x/(steps-1) for x in range(steps)]
self.gradval = ['%d' % int(x * MAX_AGE) for x in divs]
self.gradval[-1] = '%d+' % MAX_AGE
for i in range(len(self.gradval)):
for i in enumerate(self.gradval):
if i % 2 == 1:
self.gradval[i] = ''
self.gradcol = [colorsys.hsv_to_rgb(
@ -1310,7 +1310,7 @@ class FanChartWidget(FanChartBaseWidget):
angle = self.rootangle_rad[0]
portion = 1/ (2 ** i) * (self.rootangle_rad[1] -
self.rootangle_rad[0])
for dummy_count in range(len(self.data[i])):
for dummy_count in self.data[i]:
# start, stop, state
self.angle[i].append([angle, angle + portion, NORMAL])
angle += portion
@ -1397,9 +1397,7 @@ class FanChartWidget(FanChartBaseWidget):
"""
#compute the number of generations present
for generation in range(self.generations - 1, 0, -1):
for idx in range(len(self.data[generation])):
(person, dummy_parents, dummy_child,
dummy_userdata) = self.data[generation][idx]
for (person, *rest) in self.data[generation]:
if person:
return generation
return 1
@ -1423,10 +1421,8 @@ class FanChartWidget(FanChartBaseWidget):
a generator over all people outside of the core person
"""
for generation in range(self.generations):
for idx in range(len(self.data[generation])):
(person, dummy_parents, dummy_child,
userdata) = self.data[generation][idx]
yield (person, userdata)
for (person, dummy_parents, dummy_child, userdata) in self.data[generation]:
yield person, userdata
def innerpeople_generator(self):
"""
@ -1477,13 +1473,11 @@ class FanChartWidget(FanChartBaseWidget):
ctx.save()
ctx.rotate(math.radians(self.rotate_value))
for generation in range(self.generations - 1, 0, -1):
for idx in range(len(self.data[generation])):
(person, parents, child, userdata) = self.data[generation][idx]
for idx, (person, parents, child, userdata) in enumerate(self.data[generation]):
if person:
start, stop, state = self.angle[generation][idx]
if state in [NORMAL, EXPANDED]:
(radiusin,
radiusout) = self.get_radiusinout_for_gen(generation)
(radiusin, radiusout) = self.get_radiusinout_for_gen(generation)
dup = False
indicator = (generation == self.generations - 1
and parents)
@ -1689,8 +1683,7 @@ class FanChartWidget(FanChartBaseWidget):
if not (generation is None) and generation > 0:
selected = self.personpos_at_angle(generation, rads)
elif generation == -2:
for idx in range(len(self.angle[generation])):
start, stop, dummy_state = self.angle[generation][idx]
for idx, (start, stop, dummy_state) in enumerate(self.angle[generation]):
if self.radian_in_bounds(start, raw_rads, stop):
selected = idx
break
@ -1705,9 +1698,8 @@ class FanChartWidget(FanChartBaseWidget):
if generation == 0:
return 0
selected = None
for idx in range(len(self.angle[generation])):
for idx, (start, stop, state) in enumerate(self.angle[generation]):
if self.data[generation][idx][0]: # there is a person there
start, stop, state = self.angle[generation][idx]
if state == COLLAPSED:
continue
if self.radian_in_bounds(start, rads, stop):

View File

@ -195,7 +195,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
angle = self.rootangle_rad_asc[0]
portion = 1 / (2 ** i) * (self.rootangle_rad_asc[1] -
self.rootangle_rad_asc[0])
for dummy_count in range(len(self.data[i])):
for dummy_count in self.data[i]:
# start, stop, state
self.angle[i].append([angle, angle + portion, NORMAL])
angle += portion
@ -259,9 +259,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
compute the number of generations present
"""
for generation in range(self.generations_asc - 1, 0, -1):
for idx in range(len(self.data[generation])):
(person, dummy_parents, dummy_child,
dummy_userdata) = self.data[generation][idx]
for idx, (person, *rest) in enumerate(self.data[generation]):
if person:
return generation
return 1
@ -349,10 +347,8 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
for data in self.gen2fam[generation]:
yield (data[7], data[6])
for generation in range(self.generations_asc):
for idx in range(len(self.data[generation])):
(person, dummy_parents, dummy_child,
userdata) = self.data[generation][idx]
yield (person, userdata)
for (person, dummy_parents, dummy_child, userdata) in self.data[generation]:
yield person, userdata
def innerpeople_generator(self):
"""
@ -458,9 +454,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
ctx.rotate(math.radians(self.rotate_value))
# Ascendance
for generation in range(self.generations_asc - 1, 0, -1):
for idx in range(len(self.data[generation])):
(person, parents, dummy_child,
userdata) = self.data[generation][idx]
for idx, (person, parents, dummy_child, userdata) in enumerate(self.data[generation]):
if person:
start, stop, state = self.angle[generation][idx]
if state in [NORMAL, EXPANDED]:

View File

@ -555,8 +555,7 @@ class FanChartDescWidget(FanChartBaseWidget):
if not (generation is None) and generation > 0:
selected = self.personpos_at_angle(generation, rads, btype)
elif generation == -2:
for idx in range(len(self.angle[generation])):
start, stop, dummy_state = self.angle[generation][idx]
for idx, (start, stop, dummy) in enumerate(self.angle[generation]):
if self.radian_in_bounds(start, raw_rads, stop):
selected = idx
break

View File

@ -1309,7 +1309,7 @@ class GrampletPane(Gtk.ScrolledWindow):
x = sx - x
# first, find column:
col = 0
for i in range(len(self.columns)):
for i in enumerate(self.columns):
if x < (sx/len(self.columns) * (i + 1)):
col = i
break

View File

@ -114,7 +114,7 @@ class ShortlistComboEntry(ValidatedComboEntry):
# remove the existing shortlist from the model
iter = model.get_iter_first()
for n in range(len(self._shortlist)):
for n in self._shortlist:
model.remove(iter)
# update shortlist

View File

@ -184,7 +184,7 @@ class CairoDocgen(libcairodoc.CairoDoc):
body_pages = body_pages[:index_page] + index_pages + \
body_pages[index_page+1:]
self._pages = body_pages
for page_nr in range(len(self._pages)):
for page_nr in enumerate(self._pages):
cr.save()
cr.translate(left_margin, top_margin)
self.draw_page(page_nr, cr, layout,

View File

@ -475,7 +475,7 @@ def str_incr(str_counter):
raise ValueError(''.join((
'\n can\'t increment string ', ''.join(lili),
' of length ', str(len(lili)))))
for i in range(len(lili)-1, -1, -1):
for i in reversed(lili):
if lili[i] < 'z':
lili[i] = chr(ord(lili[i])+1)
break

View File

@ -1066,8 +1066,8 @@ class MakeReport:
def __reverse_family_group(self):
""" go through the n-1 to 0 cols of boxes looking for families
(parents with children) that may need to be moved. """
for x_col in range(len(self.cols)-1, -1, -1):
box = self.cols[x_col][0] #The first person in this col
for col in reversed(self.cols):
box = col[0] #The first person in this col
while box:
left_group, right_group = self.__next_family_group(box)
if not left_group:

View File

@ -1022,8 +1022,7 @@ class StatisticsChartOptions(MenuReportOptions):
sortby = EnumeratedListOption(_('Sort chart items by'),
_options.SORT_VALUE)
for item_idx in range(len(_options.opt_sorts)):
item = _options.opt_sorts[item_idx]
for item_idx, item in enumerate(_options.opt_sorts):
sortby.add_item(item_idx, item[2])
sortby.set_help(_("Select how the statistical data is sorted."))
add_option("sortby", sortby)
@ -1051,8 +1050,7 @@ class StatisticsChartOptions(MenuReportOptions):
gender = EnumeratedListOption(_('Genders included'),
Person.UNKNOWN)
for item_idx in range(len(_options.opt_genders)):
item = _options.opt_genders[item_idx]
for item in enumerate(_options.opt_genders):
gender.add_item(item[0], item[2])
gender.set_help(_("Select which genders are included into "
"statistics."))

View File

@ -144,8 +144,8 @@ class Leak(Gramplet):
try:
if referrer is not self.junk:
match = "**** "
for indx in range(len(self.junk)):
if referrer is self.junk[indx]:
for indx, junk in enumerate(self.junk):
if referrer is junk:
match = str(indx) + ": "
break
match += str(referrer) + '\n'
@ -167,8 +167,8 @@ class Leak(Gramplet):
match = ""
try:
match = "****: "
for indx in range(len(self.junk)):
if referent is self.junk[indx]:
for indx, junk in enumerate(self.junk):
if referent is junk:
match = str(indx) + ': '
break
match += str(referent) + '\n'

View File

@ -149,8 +149,8 @@ class FamilyLinesOptions(MenuReportOptions):
add_option("arrow", arrow)
color = EnumeratedListOption(_("Graph coloring"), "filled")
for i in range(len(_COLORS)):
color.add_item(_COLORS[i]["value"], _COLORS[i]["name"])
for COLOR in _COLORS:
color.add_item(COLOR["value"], COLOR["name"])
color.set_help(_("Males will be shown with blue, females "
"with red, unless otherwise set above for filled. "
"If the sex of an individual "

View File

@ -170,8 +170,8 @@ def tabstops_to_tabarray(tab_stops, dpi):
tab_array = Pango.TabArray.new(initial_size=len(tab_stops),
positions_in_pixels=False)
for index in range(len(tab_stops)):
location = tab_stops[index] * dpi * Pango.SCALE / 2.54
for index, tab_stop in enumerate(tab_stops):
location = tab_stop * dpi * Pango.SCALE / 2.54
tab_array.set_tab(index, Pango.TabAlign.LEFT, int(location))
return tab_array

View File

@ -380,17 +380,17 @@ class PG30DefTable(object):
""" Convert records to list. """
flds = []
for i in range(len(rec)):
for i, record in enumerate(rec):
typ = self.recflds[i].type_
if typ == 2 or typ == 3 or typ == 22 or typ == 23:
# Record field is record number
flds.append("%d" % rec[i])
flds.append("%d" % record)
elif typ == 46 or typ == 47:
# Record field is memory type
flds.append(self.get_mem_text(mems, rec[i]))
else:
# Not a record number, not a memory type. It must be just text.
fld = rec[i].strip()
fld = record.strip()
fld = fld.decode('cp850') # Convert to unicode
flds.append(fld)

View File

@ -114,8 +114,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string):
result = []
for ix in range(len(rel_string)):
if rel_string[ix] == 'f':
for rel in rel_string:
if rel == 'f':
result.append('far')
else:
result.append('mor')

View File

@ -102,8 +102,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string):
result = []
for ix in range(len(rel_string)):
if rel_string[ix] == 'f':
for rel in rel_string:
if rel == 'f':
result.append('faðir')
else:
result.append('móðir')

View File

@ -101,8 +101,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string):
result = []
for ix in range(len(rel_string)):
if rel_string[ix] == 'f':
for rel in rel_string:
if rel == 'f':
result.append('far')
else:
result.append('mor')

View File

@ -124,8 +124,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def _get_direct_ancestor(self, person_gender, rel_string, step, inlaw):
result = []
for ix in range(len(rel_string)):
if rel_string[ix] == 'f':
for rel in rel_string:
if rel == 'f':
result.append('far')
else:
result.append('mor')

View File

@ -120,15 +120,15 @@ class CategorySidebar(BaseSidebar):
"""
Block signals to the buttons to prevent spurious events.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_block(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self):
"""
Unblock signals to the buttons.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_unblock(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num):
"""

View File

@ -92,15 +92,15 @@ class DropdownSidebar(BaseSidebar):
"""
Block signals to the buttons to prevent spurious events.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_block(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self):
"""
Unblock signals to the buttons.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_unblock(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num):
"""

View File

@ -124,15 +124,15 @@ class ExpanderSidebar(BaseSidebar):
"""
Block signals to the buttons to prevent spurious events.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_block(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self):
"""
Unblock signals to the buttons.
"""
for idx in range(len(self.buttons)):
self.buttons[idx].handler_unblock(self.button_handlers[idx])
for idx, button in enumerate(self.buttons):
button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num):
"""

View File

@ -309,8 +309,8 @@ class DetDescendantReport(Report):
""" Entry Filter for Record-style (Modified Register) numbering """
self.apply_mod_reg_filter_aux(person_handle, 1, 1)
mod_reg_number = 1
for generation in range(len(self.gen_keys)):
for key in self.gen_keys[generation]:
for keys in self.gen_keys:
for key in keys:
person_handle = self.map[key]
if person_handle not in self.dnumber:
self.dnumber[person_handle] = mod_reg_number
@ -348,7 +348,7 @@ class DetDescendantReport(Report):
self.numbers_printed = list()
if self.structure == "by generation":
for generation in range(len(self.gen_keys)):
for generation, gen_keys in enumerate(self.gen_keys):
if self.pgbrk and generation > 0:
self.doc.page_break()
self.doc.start_paragraph("DDR-Generation")
@ -359,7 +359,7 @@ class DetDescendantReport(Report):
if self.childref:
self.prev_gen_handles = self.gen_handles.copy()
self.gen_handles.clear()
for key in self.gen_keys[generation]:
for key in gen_keys:
person_handle = self.map[key]
self.gen_handles[person_handle] = key
self.write_person(key)