def compile_repl_group(source, pattern):
"Compiles a replacement template group reference."
source.expect("<")
name = parse_name(source, True, True)
source.expect(">")
if name.isdigit():
index = int(name)
if not 0 <= index <= pattern.groups:
raise error("invalid group reference", source.string, source.pos)
return index
try:
return pattern.groupindex[name]
except KeyError:
raise IndexError("unknown group")
# The regular expression is parsed into a syntax tree. The different types of
# node are defined below.
python类index()的实例源码
def at_end(self):
string = self.string
pos = self.pos
try:
if self.ignore_space:
while True:
if string[pos].isspace():
pos += 1
elif string[pos] == "#":
pos = string.index("\n", pos)
else:
break
return pos >= len(string)
except IndexError:
# We've reached the end of the string.
return True
except ValueError:
# The comment extended to the end of the string.
return True
def _defaultButton(self):
defaultbutton = self['defaultbutton']
if self.oldDefault == defaultbutton:
return
self.oldDefault = defaultbutton
if len(self['buttons']) > 0:
if defaultbutton is None:
self._buttonBox.setdefault(None)
else:
try:
self._buttonBox.index(defaultbutton)
except ValueError:
pass
else:
self._buttonBox.setdefault(defaultbutton)
######################################################################
### File: PmwTimeFuncs.py
# Functions for dealing with dates and times.
def _getValidatorFunc(self, validator, index):
# Search the extra and standard validator lists for the
# given 'validator'. If 'validator' is an alias, then
# continue the search using the alias. Make sure that
# self-referencial aliases do not cause infinite loops.
extraValidators = self['extravalidators']
traversedValidators = []
while 1:
traversedValidators.append(validator)
if extraValidators.has_key(validator):
validator = extraValidators[validator][index]
elif _standardValidators.has_key(validator):
validator = _standardValidators[validator][index]
else:
return validator
if validator in traversedValidators:
return validator
def realvalidator(text, separator = '.'):
if separator != '.':
if string.find(text, '.') >= 0:
return ERROR
index = string.find(text, separator)
if index >= 0:
text = text[:index] + '.' + text[index + 1:]
try:
string.atof(text)
return OK
except ValueError:
# Check if the string could be made valid by appending a digit
# eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-').
if len(text) == 0:
return PARTIAL
if text[-1] in string.digits:
return ERROR
try:
string.atof(text + '0')
return PARTIAL
except ValueError:
return ERROR
def deletemenu(self, menuName):
"""Delete should be called for cascaded menus before main menus.
"""
parentName = self._menuInfo[menuName][0]
del self._menuInfo[menuName]
if parentName is None:
parentMenu = self._menu
else:
parentMenu = self.component(parentName)
menu = self.component(menuName)
menuId = str(menu)
for item in range(parentMenu.index('end') + 1):
if parentMenu.type(item) == 'cascade':
itemMenu = str(parentMenu.entrycget(item, 'menu'))
if itemMenu == menuId:
parentMenu.delete(item)
del self._menuInfo[parentName][1][item]
break
self.destroycomponent(menuName)
def selectpage(self, page):
pageName = self._pageNames[self.index(page)]
oldTopPage = self.getcurselection()
if pageName != oldTopPage:
self._pending['topPage'] = pageName
if oldTopPage == self._topPageName:
self._hull.delete(self._topPageItem)
cmd = self['lowercommand']
if cmd is not None:
cmd(oldTopPage)
self._raiseNewTop(pageName)
self._layout()
# Set focus to the tab of new top page:
if self._withTabs and self['arrownavigation']:
self._pageAttrs[pageName]['tabbutton'].focus_set()
def index(self, index):
listLength = len(self._itemList)
if type(index) == types.IntType:
if index < listLength:
return index
else:
raise ValueError, 'index "%s" is out of range' % index
elif index is END:
if listLength > 0:
return listLength - 1
else:
raise ValueError, 'OptionMenu has no items'
else:
if index is SELECT:
if listLength > 0:
index = self.getcurselection()
else:
raise ValueError, 'OptionMenu has no items'
if index in self._itemList:
return self._itemList.index(index)
raise ValueError, \
'bad index "%s": must be a ' \
'name, a number, END or SELECT' % (index,)
def selectitem(self, index, setentry=1):
if isinstance(index, basestring):
text = index
items = self._list.get(0, 'end')
if text in items:
index = list(items).index(text)
else:
raise IndexError, 'index "%s" not found' % text
elif setentry:
text = self._list.get(0, 'end')[index]
self._list.select_clear(0, 'end')
self._list.select_set(index, index)
self._list.activate(index)
self.see(index)
if setentry:
self._entryfield.setentry(text)
# Need to explicitly forward this to override the stupid
# (grid_)size method inherited from Tkinter.Frame.Grid.
def _addHistory(self):
input = self._entryWidget.get()
if input != '':
index = None
if self['unique']:
# If item is already in list, select it and return.
items = self._list.get(0, 'end')
if input in items:
index = list(items).index(input)
if index is None:
index = self._list.index('end')
self._list.insert('end', input)
self.selectitem(index)
if self['autoclear']:
self._entryWidget.delete(0, 'end')
# Execute the selectioncommand on the new entry.
self._selectCmd()
def _next(self, event):
size = self.size()
if size <= 1:
return
cursels = self.curselection()
if len(cursels) == 0:
index = 0
else:
index = string.atoi(cursels[0])
if index == size - 1:
index = 0
else:
index = index + 1
self.selectitem(index)
def _forceCount(self, factor):
if not self.valid():
self.bell()
return
text = self._counterEntry.get()
try:
value = apply(self._counterCommand,
(text, factor, self['increment']), self._counterArgs)
except ValueError:
self.bell()
return
previousICursor = self._counterEntry.index('insert')
if self._counterEntry.setentry(value) == OK:
self._counterEntry.xview('end')
self._counterEntry.icursor(previousICursor)
def _changeDate(value, factor, increment, format = 'ymd',
separator = '/', yyyy = 0):
jdn = datestringtojdn(value, format, separator) + factor * increment
y, m, d = jdntoymd(jdn)
result = ''
for index in range(3):
if index > 0:
result = result + separator
f = format[index]
if f == 'y':
if yyyy:
result = result + '%02d' % y
else:
result = result + '%02d' % (y % 100)
elif f == 'm':
result = result + '%02d' % m
elif f == 'd':
result = result + '%02d' % d
return result
def main():
options = ''
i = 1
while i < len(sys.argv) and sys.argv[i][:1] == '-':
options = options + sys.argv[i] + ' '
i = i+1
args = sys.argv[i:]
if not args:
args = ['']
for arg in args:
if '@' in arg:
at = string.index(arg, '@')
host = arg[at+1:]
arg = arg[:at]
else:
host = ''
finger(host, options + arg)
# Call the main function.
#
def mirror_string(string):
space = ' '
previous_index = None
space_index = None
while True:
try:
space_index = string.index(space, 0 if previous_index is None else previous_index + 1)
if previous_index is None:
string = "{0} {1}".format(string[:space_index][::-1], string[space_index + 1:])
else:
string = "{0} {1} {2}".format(string[:previous_index], string[previous_index + 1: space_index][::-1], string[space_index + 1:])
previous_index = space_index
except ValueError:
break
if space_index:
string = "{0} {1}".format(string[:space_index], string[space_index + 1:][::-1])
else:
string = string[::-1]
return string
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 _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."
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 _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."
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 _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."
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 _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."
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 parseGenoFile(genoFile, names = None, includePositions = False, splitPhased=False, ploidy=None, headerLine = None):
#get file headers
headers = genoFile.readline().split()
allNames = headers[2:]
if names is None: names = allNames
if splitPhased:
if ploidy is None: ploidy = [2]*len(allNames)
ploidyDict = dict(zip(allNames, ploidy))
#if splitting phased, we need to split names too
allNames = [n + "_" + letter for n in allNames for letter in string.ascii_uppercase[:ploidyDict[n]]]
names = [n + "_" + letter for n in names for letter in string.ascii_uppercase[:ploidyDict[n]]]
#indices of samples
nameIndices = dict(zip(names, [allNames.index(name) for name in names])) # records file column for each name
#initialise an empty window
window = GenoWindow(names = names)
for line in iter(genoFile.readline,''):
site = parseGenoLine(line,splitPhased)
window.addSite(GTs=[site.GTs[nameIndices[name]] for name in names], position=site.position, ignorePosition= not includePositions)
return window
##########################################################################################################
#functions to make and parse alignment strings in fasta or phylip format
def material(self, mat, toName):
"""
Convert material to name/number
:param mat:
:param toName:
:return:
"""
lst = self.materialList(0, False, True)
if toName:
mat -= 1 # 1 based
if mat < 0 or mat >= len(lst):
if mat != -1: # Accept -1 == 0 index
raise Exception("Invalid material index requested idx=%d" % (mat + 1))
return ""
return lst[mat]
else:
try:
return lst.index(mat) + 1
except Exception:
return 0
def region(self, reg, toName):
"""
Convert region to name/number
:param reg:
:param toName:
:return:
"""
# Regions removing continuation cards
regions = [x for x in self.cardsSorted("REGION") if x.name() != "&"]
if len(regions) == 0:
return None
if toName:
if reg <= 0 or reg > len(regions):
return ""
return regions[reg - 1].sdum()
else:
try:
return [x.what(0) for x in regions].index(reg) + 1
except Exception:
return 0
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 _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."
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