def _testKeys(self):
"""Verify that index lookup can find each word in the index file."""
print "Testing: ", self
file = open(self.indexFile.file.name, _FILE_OPEN_MODE)
counter = 0
while 1:
line = file.readline()
if line == '': break
if line[0] != ' ':
key = string.replace(line[:string.find(line, ' ')], '_', ' ')
if (counter % 1000) == 0:
print "%s..." % (key,),
import sys
sys.stdout.flush()
counter = counter + 1
self[key]
file.close()
print "done."
python类index()的实例源码
def _index(key, sequence, testfn=None, keyfn=None):
"""Return the index of key within sequence, using testfn for
comparison and transforming items of sequence by keyfn first.
>>> _index('e', 'hello')
1
>>> _index('E', 'hello', testfn=_equalsIgnoreCase)
1
>>> _index('x', 'hello')
"""
index = 0
for element in sequence:
value = element
if keyfn:
value = keyfn(value)
if (not testfn and value == key) or (testfn and testfn(value, key)):
return index
index = index + 1
return None
def _load_encoding(self):
# map character code to bitmap index
encoding = [None] * 256
fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
firstCol, lastCol = i16(fp.read(2)), i16(fp.read(2))
firstRow, lastRow = i16(fp.read(2)), i16(fp.read(2))
default = i16(fp.read(2))
nencoding = (lastCol - firstCol + 1) * (lastRow - firstRow + 1)
for i in range(nencoding):
encodingOffset = i16(fp.read(2))
if encodingOffset != 0xFFFF:
try:
encoding[i+firstCol] = encodingOffset
except IndexError:
break # only load ISO-8859-1 glyphs
return encoding
def set_positionLineOffset(self, line, offset):
text = self.get_chars(0, -1)
pos = 0
for l in xrange(line - 1):
pos = string.index(text, '\n', pos) + 1
pos = pos + offset - 1
self.set_position(pos)
def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname):
self.__ctime = ctime
self.__atime = atime
self.__mtime = mtime
self.__filesize = filesize
self.__allocsize = allocsize
self.__attribs = attribs
try:
self.__shortname = shortname[:string.index(shortname, '\0')]
except ValueError:
self.__shortname = shortname
try:
self.__longname = longname[:string.index(longname, '\0')]
except ValueError:
self.__longname = longname
def _compile(self, reverse, fuzzy):
index = self.info.named_lists_used[self.set_key]
items = self.info.kwargs[self.name]
case_flags = self.case_flags
if not items:
return []
encoding = self.info.flags & _ALL_ENCODINGS
fold_flags = encoding | case_flags
if fuzzy:
choices = [self._folded(fold_flags, i) for i in items]
# Sort from longest to shortest.
choices.sort(key=lambda s: (-len(s), s))
branches = []
for string in choices:
branches.append(Sequence([Character(c, case_flags=case_flags)
for c in string]))
if len(branches) > 1:
branch = Branch(branches)
else:
branch = branches[0]
branch = branch.optimise(self.info,
reverse).pack_characters(self.info)
return branch.compile(reverse, fuzzy)
else:
min_len = min(len(i) for i in items)
max_len = max(len(self._folded(fold_flags, i)) for i in items)
return [(self._opcode[case_flags, reverse], index, min_len,
max_len)]
def get(self):
string = self.string
pos = self.pos
try:
if self.ignore_space:
while True:
if string[pos].isspace():
# Skip over the whitespace.
pos += 1
elif string[pos] == "#":
# Skip over the comment to the end of the line.
pos = string.index("\n", pos)
else:
break
ch = string[pos]
self.pos = pos + 1
return ch
except IndexError:
# We've reached the end of the string.
self.pos = pos
return string[ : 0]
except ValueError:
# The comment extended to the end of the string.
self.pos = len(string)
return string[ : 0]
def get_many(self, count=1):
string = self.string
pos = self.pos
try:
if self.ignore_space:
substring = []
while len(substring) < count:
while True:
if string[pos].isspace():
# Skip over the whitespace.
pos += 1
elif string[pos] == "#":
# Skip over the comment to the end of the line.
pos = string.index("\n", pos)
else:
break
substring.append(string[pos])
pos += 1
substring = "".join(substring)
else:
substring = string[pos : pos + count]
pos += len(substring)
self.pos = pos
return substring
except IndexError:
# We've reached the end of the string.
self.pos = len(string)
return "".join(substring)
except ValueError:
# The comment extended to the end of the string.
self.pos = len(string)
return "".join(substring)
def match(self, substring):
string = self.string
pos = self.pos
if self.ignore_space:
try:
for c in substring:
while True:
if string[pos].isspace():
# Skip over the whitespace.
pos += 1
elif string[pos] == "#":
# Skip over the comment to the end of the line.
pos = string.index("\n", pos)
else:
break
if string[pos] != c:
return False
pos += 1
self.pos = pos
return True
except IndexError:
# We've reached the end of the string.
return False
except ValueError:
# The comment extended to the end of the string.
return False
else:
if not string.startswith(substring, pos):
return False
self.pos = pos + len(substring)
return True
def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname):
self.__ctime = ctime
self.__atime = atime
self.__mtime = mtime
self.__filesize = filesize
self.__allocsize = allocsize
self.__attribs = attribs
try:
self.__shortname = shortname[:string.index(shortname, '\0')]
except ValueError:
self.__shortname = shortname
try:
self.__longname = longname[:string.index(longname, '\0')]
except ValueError:
self.__longname = longname
def __unique():
global __counter
__counter = __counter + 1
return str(__counter)
# Function body to resolve a forwarding given the target method name and the
# index of the resolution function. The resulting lambda requires only self,
# but will forward any other parameters. The target instance is identified
# by invoking the resolution function.
def initialiseoptions(self, dummy = None):
self._initialiseoptions_counter = self._initialiseoptions_counter - 1
if self._initialiseoptions_counter == 0:
unusedOptions = []
keywords = self._constructorKeywords
for name in keywords.keys():
used = keywords[name][1]
if not used:
# This keyword argument has not been used. If it
# does not refer to a dynamic group, mark it as
# unused.
index = string.find(name, '_')
if index < 0 or name[:index] not in self._dynamicGroups:
unusedOptions.append(name)
if len(unusedOptions) > 0:
if len(unusedOptions) == 1:
text = 'Unknown option "'
else:
text = 'Unknown options "'
raise KeyError, text + string.join(unusedOptions, ', ') + \
'" for ' + self.__class__.__name__
# Call the configuration callback function for every option.
FUNCTION = _OPT_FUNCTION
for info in self._optionInfo.values():
func = info[FUNCTION]
if func is not None and func is not INITOPT:
func()
#======================================================================
# Method used to configure the megawidget.
def component(self, name):
# Return a component widget of the megawidget given the
# component's name
# This allows the user of a megawidget to access and configure
# widget components directly.
# Find the main component and any subcomponents
index = string.find(name, '_')
if index < 0:
component = name
remainingComponents = None
else:
component = name[:index]
remainingComponents = name[(index + 1):]
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
if remainingComponents is None:
remainingComponents = subComponent
else:
remainingComponents = subComponent + '_' \
+ remainingComponents
widget = self.__componentInfo[component][0]
if remainingComponents is None:
return widget
else:
return widget.component(remainingComponents)
def cget(self, option):
# Get current configuration setting.
# Return the value of an option, for example myWidget['font'].
if self._optionInfo.has_key(option):
return self._optionInfo[option][_OPT_VALUE]
else:
index = string.find(option, '_')
if index >= 0:
component = option[:index]
componentOption = option[(index + 1):]
# Expand component alias
if self.__componentAliases.has_key(component):
component, subComponent = self.__componentAliases[component]
if subComponent is not None:
componentOption = subComponent + '_' + componentOption
# Expand option string to write on error
option = component + '_' + componentOption
if self.__componentInfo.has_key(component):
# Call cget on the component.
componentCget = self.__componentInfo[component][3]
return componentCget(componentOption)
else:
# If this is a group name, call cget for one of
# the components in the group.
for info in self.__componentInfo.values():
if info[4] == component:
componentCget = info[3]
return componentCget(componentOption)
raise KeyError, 'Unknown option "' + option + \
'" for ' + self.__class__.__name__
def popgrab(window):
# Return the grab to the next window in the grab stack, if any.
# If this window is not at the top of the grab stack, then it has
# just been deleted by the window manager or deactivated by a
# timer. Call the deactivate method for the modal dialog above
# this one on the stack.
if _grabStack[-1]['grabWindow'] != window:
for index in range(len(_grabStack)):
if _grabStack[index]['grabWindow'] == window:
_grabStack[index + 1]['deactivateFunction']()
break
grabInfo = _grabStack[-1]
del _grabStack[-1]
topWidget = grabInfo['grabWindow']
prevFocus = grabInfo['previousFocus']
globalMode = grabInfo['globalMode']
if globalMode != 'nograb':
topWidget.grab_release()
if len(_grabStack) > 0:
_grabtop()
if prevFocus != '':
try:
topWidget.tk.call('focus', prevFocus)
except Tkinter.TclError:
# Previous focus widget has been deleted. Set focus
# to root window.
Tkinter._default_root.focus_set()
else:
# Make sure that focus does not remain on the released widget.
if len(_grabStack) > 0:
topWidget = _grabStack[-1]['grabWindow']
topWidget.focus_set()
else:
Tkinter._default_root.focus_set()
def invoke(self, index = DEFAULT):
return self._buttonBox.invoke(index)
def _invokeDefault(self, event):
try:
self._buttonBox.index(DEFAULT)
except ValueError:
return
self._buttonBox.invoke()
def _buttons(self):
buttons = self['buttons']
if type(buttons) != types.TupleType and type(buttons) != types.ListType:
raise ValueError, \
'bad buttons option "%s": should be a tuple' % str(buttons)
if self.oldButtons == buttons:
return
self.oldButtons = buttons
for index in range(self._buttonBox.numbuttons()):
self._buttonBox.delete(0)
for name in buttons:
self._buttonBox.add(name,
command=lambda self=self, name=name: self._doCommand(name))
if len(buttons) > 0:
defaultbutton = self['defaultbutton']
if defaultbutton is None:
self._buttonBox.setdefault(None)
else:
try:
self._buttonBox.index(defaultbutton)
except ValueError:
pass
else:
self._buttonBox.setdefault(defaultbutton)
self._buttonBox.alignbuttons()
def stringtoreal(text, separator = '.'):
if separator != '.':
if string.find(text, '.') >= 0:
raise ValueError, 'invalid value: ' + text
index = string.find(text, separator)
if index >= 0:
text = text[:index] + '.' + text[index + 1:]
return string.atof(text)
######################################################################
### File: PmwBalloon.py
def tagunbind(self, widget, tagOrItem):
if hasattr(widget, '_Pmw_BalloonBindIds'):
if widget._Pmw_BalloonBindIds.has_key(tagOrItem):
(enterId, motionId, leaveId, buttonId) = \
widget._Pmw_BalloonBindIds[tagOrItem]
widget.tag_unbind(tagOrItem, '<Enter>', enterId)
widget.tag_unbind(tagOrItem, '<Motion>', motionId)
widget.tag_unbind(tagOrItem, '<Leave>', leaveId)
widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId)
del widget._Pmw_BalloonBindIds[tagOrItem]
if self._currentTrigger is None:
# The balloon is not currently being displayed.
return
if len(self._currentTrigger) == 1:
# The current trigger is a widget.
return
if len(self._currentTrigger) == 2:
# The current trigger is a canvas item.
(triggerWidget, triggerItem) = self._currentTrigger
if triggerWidget == widget and triggerItem == tagOrItem:
if self._timer is not None:
self.after_cancel(self._timer)
self._timer = None
self.withdraw()
self.clearstatus()
self._currentTrigger = None
else: # The current trigger is a text item.
(triggerWidget, x, y) = self._currentTrigger
if triggerWidget == widget:
currentPos = widget.index('@%d,%d' % (x, y))
currentTags = widget.tag_names(currentPos)
if tagOrItem in currentTags:
if self._timer is not None:
self.after_cancel(self._timer)
self._timer = None
self.withdraw()
self.clearstatus()
self._currentTrigger = None