def repeat(rule, from_count, to_count=None, allow_whitespace=False):
"""Allow between from_count and to_count repetitions of a rule.
If to_count is not given, then allow as many repetitions as can be
parsed.
"""
if to_count == 0:
return null
if from_count == 0 and to_count is None:
return many(rule, allow_whitespace=allow_whitespace)
op = operator.__add__ if allow_whitespace else operator.__xor__
next_to_count = to_count - 1 if to_count is not None else None
next_from_count = from_count - 1 if from_count > 0 else 0
first_part = optional(rule) if from_count == 0 else rule
return op(first_part, repeat(rule, next_from_count, next_to_count,
allow_whitespace))
python类__add__()的实例源码
def __add__(self, other_rule):
return ConjunctionRule(self, other_rule, allow_whitespace=True)
def __add__(self, rhs):
return op_binary(self, rhs, operator.__add__)
def __radd__(self, lhs):
return op_binary(lhs, self, operator.__add__)
def __iadd__(self, v):
return self.op_binary_inplace(v, operator.__add__)
def __add__(self, rhs):
return op_binary(self, rhs, operator.__add__)
def __radd__(self, lhs):
return op_binary(lhs, self, operator.__add__)
def __init__(self, accs):
Engraver.__init__(self)
self.m_accs = accs
def f(v, w=dimentions[self.m_fontsize].accidental_widths):
x = 0
for a in v:
x += w[a]
return x
self.m_usize = reduce(operator.__add__, map(f, accs.values())) + len(accs)
def _combine_requests(self):
"""Create single request that combines keys and filters of all subscribers"""
if not self.has_subscribers:
# Don't request anything
log.debug('No subscribers - setting request to None')
self.set_request(None)
else:
kwargs = {}
all_filters = tuple(self._tfilters.values())
if not all_filters or None in all_filters:
# No subscribers or at least one subscriber wants all torrents
kwargs['torrents'] = None
else:
kwargs['torrents'] = reduce(operator.__add__, all_filters)
kwargs['keys'] = reduce(operator.__add__, self._keys.values())
# Filters also need certain keys
for f in all_filters:
if f is not None:
kwargs['keys'] += f.needed_keys
kwargs['keys'] = tuple(set(kwargs['keys']))
kwargs['autoconnect'] = self._autoconnect
log.debug('Combined filters: %s', kwargs['torrents'])
log.debug('Combined keys: %s', kwargs['keys'])
self.set_request(self._api.torrents, **kwargs)
def eval(self):
"""Evaluates the tree to get actual value.
Behavior of this function depends on an implementation class.
For example, a binary operator ``+`` calls the ``__add__`` function
with the two results of :meth:`eval` function.
"""
raise NotImplementedError()
def __init__(self, start=0.0, lock_type=Lock):
if isinstance(start, stringabc):
try:
start = ast.literal_eval(start)
except ValueError:
pass
self.__wrapped__ = start
self._lock = lock_type()
# Developer note:
# operations are implemented using operator.__add__(self._value, other)
# instead of self._value.__add__(other) as the later does *not* imply
# calling other.__radd__(self._value) on failure.
def __add__(self, other):
with self._lock:
return operator.__add__(self.__wrapped__, other)
def __radd__(self, other):
with self._lock:
return operator.__add__(other, self.__wrapped__)
def dms2decimal(degrees, minutes, seconds):
op = operator.__add__ if degrees >= 0 else operator.__sub__
return reduce(op, [degrees, float(minutes)/60, float(seconds)/3600])
def add_at_idx(t, idx, val, typ=tuple, op=operator.__add__):
"""
add_at_idx(t, idx, val, typ=tuple, op=operator.__add__) ->
t with t[idx] = op(t[idx], val)
"""
return t[:idx] + typ((op(t[idx], val),)) + t[idx+1:]
def add_at_l_idx(t, idx, val, op=operator.__add__):
"""See add_at_idx but uses typ=list"""
return add_at_idx(t, idx, val, typ=list, op=op)
def plus(typeA, typeB):
return operator.__add__(typeA.number.getNum(), typeB.number.getNum())
def write(self, fp):
options = self.__options
timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
# The time stamp in the header doesn't have the same format as that
# generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__}
# Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item.
reverse = {}
for k, v in self.__messages.items():
keys = v.keys()
keys.sort()
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = reverse.keys()
rkeys.sort()
for rkey in rkeys:
rentries = reverse[rkey]
rentries.sort()
for k, v in rentries:
isdocstring = 0
# If the entry was gleaned out of a docstring, then add a
# comment stating so. This is to aid translators who may wish
# to skip translating some unimportant docstrings.
if reduce(operator.__add__, v.values()):
isdocstring = 1
# k is the message string, v is a dictionary-set of (filename,
# lineno) tuples. We want to sort the entries in v first by
# file name and then by line number.
v = v.keys()
v.sort()
if not options.writelocations:
pass
# location comments are different b/w Solaris and GNU:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
# resulting line length doesn't exceed 'options.width'
locline = '#:'
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
s = _(' %(filename)s:%(lineno)d') % d
if len(locline) + len(s) <= options.width:
locline = locline + s
else:
print >> fp, locline
locline = "#:" + s
if len(locline) > 2:
print >> fp, locline
if isdocstring:
print >> fp, '#, docstring'
print >> fp, 'msgid', normalize(k)
print >> fp, 'msgstr ""\n'
def write(self, fp):
options = self.__options
timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
# The time stamp in the header doesn't have the same format as that
# generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__}
# Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item.
reverse = {}
for k, v in self.__messages.items():
keys = v.keys()
keys.sort()
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = reverse.keys()
rkeys.sort()
for rkey in rkeys:
rentries = reverse[rkey]
rentries.sort()
for k, v in rentries:
isdocstring = 0
# If the entry was gleaned out of a docstring, then add a
# comment stating so. This is to aid translators who may wish
# to skip translating some unimportant docstrings.
if reduce(operator.__add__, v.values()):
isdocstring = 1
# k is the message string, v is a dictionary-set of (filename,
# lineno) tuples. We want to sort the entries in v first by
# file name and then by line number.
v = v.keys()
v.sort()
if not options.writelocations:
pass
# location comments are different b/w Solaris and GNU:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
# resulting line length doesn't exceed 'options.width'
locline = '#:'
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
s = _(' %(filename)s:%(lineno)d') % d
if len(locline) + len(s) <= options.width:
locline = locline + s
else:
print >> fp, locline
locline = "#:" + s
if len(locline) > 2:
print >> fp, locline
if isdocstring:
print >> fp, '#, docstring'
print >> fp, 'msgid', normalize(k)
print >> fp, 'msgstr ""\n'
def write(self, fp):
options = self.__options
timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
# The time stamp in the header doesn't have the same format as that
# generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__}
# Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item.
reverse = {}
for k, v in self.__messages.items():
keys = v.keys()
keys.sort()
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = reverse.keys()
rkeys.sort()
for rkey in rkeys:
rentries = reverse[rkey]
rentries.sort()
for k, v in rentries:
isdocstring = 0
# If the entry was gleaned out of a docstring, then add a
# comment stating so. This is to aid translators who may wish
# to skip translating some unimportant docstrings.
if reduce(operator.__add__, v.values()):
isdocstring = 1
# k is the message string, v is a dictionary-set of (filename,
# lineno) tuples. We want to sort the entries in v first by
# file name and then by line number.
v = v.keys()
v.sort()
if not options.writelocations:
pass
# location comments are different b/w Solaris and GNU:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
# resulting line length doesn't exceeds 'options.width'
locline = '#:'
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
s = _(' %(filename)s:%(lineno)d') % d
if len(locline) + len(s) <= options.width:
locline = locline + s
else:
print >> fp, locline
locline = "#:" + s
if len(locline) > 2:
print >> fp, locline
if isdocstring:
print >> fp, '#, docstring'
print >> fp, 'msgid', normalize(k)
print >> fp, 'msgstr ""\n'
def write(self, fp):
options = self.__options
timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
# The time stamp in the header doesn't have the same format as that
# generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__}
# Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item.
reverse = {}
for k, v in self.__messages.items():
keys = v.keys()
keys.sort()
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = reverse.keys()
rkeys.sort()
for rkey in rkeys:
rentries = reverse[rkey]
rentries.sort()
for k, v in rentries:
isdocstring = 0
# If the entry was gleaned out of a docstring, then add a
# comment stating so. This is to aid translators who may wish
# to skip translating some unimportant docstrings.
if reduce(operator.__add__, v.values()):
isdocstring = 1
# k is the message string, v is a dictionary-set of (filename,
# lineno) tuples. We want to sort the entries in v first by
# file name and then by line number.
v = v.keys()
v.sort()
if not options.writelocations:
pass
# location comments are different b/w Solaris and GNU:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
# resulting line length doesn't exceeds 'options.width'
locline = '#:'
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
s = _(' %(filename)s:%(lineno)d') % d
if len(locline) + len(s) <= options.width:
locline = locline + s
else:
print >> fp, locline
locline = "#:" + s
if len(locline) > 2:
print >> fp, locline
if isdocstring:
print >> fp, '#, docstring'
print >> fp, 'msgid', normalize(k)
print >> fp, 'msgstr ""\n'