desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'In the usual case, use ParseResponse (or ParseFile) to create new
HTMLForm objects.
action: full (absolute URI) form action
method: "GET" or "POST"
enctype: form transfer encoding MIME type
name: name of form
attrs: dictionary mapping original HTML form attributes to their values'
| def __init__(self, action, method='GET', enctype=None, name=None, attrs=None, request_class=urllib2.Request, forms=None, labels=None, id_to_labels=None, backwards_compat=True):
| self.action = action
self.method = method
self.enctype = (enctype or 'application/x-www-form-urlencoded')
self.name = name
if (attrs is not None):
self.attrs = attrs.copy()
else:
self.attrs = {}
self.controls = []
self._request_class = request_class
self._forms = form... |
'Adds a new control to the form.
This is usually called by ParseFile and ParseResponse. Don\'t call it
youself unless you\'re building your own Control instances.
Note that controls representing lists of items are built up from
controls holding only a single list item. See ListControl.__doc__ for
further information.... | def new_control(self, type, name, attrs, ignore_unknown=False, select_default=False, index=None):
| type = type.lower()
klass = self.type2class.get(type)
if (klass is None):
if ignore_unknown:
klass = IgnoreControl
else:
klass = TextControl
a = attrs.copy()
if issubclass(klass, ListControl):
control = klass(type, name, a, select_default, index)
e... |
'Normalise form after all controls have been added.
This is usually called by ParseFile and ParseResponse. Don\'t call it
youself unless you\'re building your own Control instances.
This method should only be called once, after all controls have been
added to the form.'
| def fixup(self):
| for control in self.controls:
control.fixup()
self.backwards_compat = self._backwards_compat
|
'Return value of control.
If only name and value arguments are supplied, equivalent to
form[name]'
| def get_value(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| if by_label:
deprecation('form.get_value_by_label(...)')
c = self.find_control(name, type, kind, id, label=label, nr=nr)
if by_label:
try:
meth = c.get_value_by_label
except AttributeError:
raise NotImplementedError(("control '%s' does not yet s... |
'Set value of control.
If only name and value arguments are supplied, equivalent to
form[name] = value'
| def set_value(self, value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| if by_label:
deprecation('form.get_value_by_label(...)')
c = self.find_control(name, type, kind, id, label=label, nr=nr)
if by_label:
try:
meth = c.set_value_by_label
except AttributeError:
raise NotImplementedError(("control '%s' does not yet s... |
'All arguments should be passed by name.'
| def get_value_by_label(self, name=None, type=None, kind=None, id=None, label=None, nr=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
return c.get_value_by_label()
|
'All arguments should be passed by name.'
| def set_value_by_label(self, value, name=None, type=None, kind=None, id=None, label=None, nr=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
c.set_value_by_label(value)
|
'Clear the value attributes of all controls in the form.
See HTMLForm.clear.__doc__.'
| def clear_all(self):
| for control in self.controls:
control.clear()
|
'Clear the value attribute of a control.
As a result, the affected control will not be successful until a value
is subsequently set. AttributeError is raised on readonly controls.'
| def clear(self, name=None, type=None, kind=None, id=None, nr=None, label=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
c.clear()
|
'Return a list of all values that the specified control can take.'
| def possible_items(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| c = self._find_list_control(name, type, kind, id, label, nr)
return c.possible_items(by_label)
|
'Select / deselect named list item.
selected: boolean selected state'
| def set(self, selected, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| self._find_list_control(name, type, kind, id, label, nr).set(selected, item_name, by_label)
|
'Toggle selected state of named list item.'
| def toggle(self, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| self._find_list_control(name, type, kind, id, label, nr).toggle(item_name, by_label)
|
'Select / deselect list item in a control having only one item.
If the control has multiple list items, ItemCountError is raised.
This is just a convenience method, so you don\'t need to know the item\'s
name -- the item name in these single-item controls is usually
something meaningless like "1" or "on".
For example, ... | def set_single(self, selected, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None):
| self._find_list_control(name, type, kind, id, label, nr).set_single(selected)
|
'Toggle selected state of list item in control having only one item.
The rest is as for HTMLForm.set_single.__doc__.'
| def toggle_single(self, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None):
| self._find_list_control(name, type, kind, id, label, nr).toggle_single()
|
'Add a file to be uploaded.
file_object: file-like object (with read method) from which to read
data to upload
content_type: MIME content type of data to upload
filename: filename to pass to server
If filename is None, no filename is sent to the server.
If content_type is None, the content type is guessed based on the
... | def add_file(self, file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None):
| self.find_control(name, 'file', id=id, label=label, nr=nr).add_file(file_object, content_type, filename)
|
'Return request that would result from clicking on a control.
The request object is a urllib2.Request instance, which you can pass to
urllib2.urlopen (or ClientCookie.urlopen).
Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and
IMAGEs) can be clicked.
Will click on the first clickable control, subject to... | def click(self, name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=urllib2.Request, label=None):
| return self._click(name, type, id, label, nr, coord, 'request', self._request_class)
|
'As for click method, but return a tuple (url, data, headers).
You can use this data to send a request to the server. This is useful
if you\'re using httplib or urllib rather than urllib2. Otherwise, use
the click method.
# Untested. Have to subclass to add headers, I think -- so use urllib2
# instead!
import urllib... | def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=urllib2.Request, label=None):
| return self._click(name, type, id, label, nr, coord, 'request_data', self._request_class)
|
'As for click_request_data, but returns a list of (key, value) pairs.
You can use this list as an argument to ClientForm.urlencode. This is
usually only useful if you\'re using httplib or urllib rather than
urllib2 or ClientCookie. It may also be useful if you want to manually
tweak the keys and/or values, but this s... | def click_pairs(self, name=None, type=None, id=None, nr=0, coord=(1, 1), label=None):
| return self._click(name, type, id, label, nr, coord, 'pairs', self._request_class)
|
'Locate and return some specific control within the form.
At least one of the name, type, kind, predicate and nr arguments must
be supplied. If no matching control is found, ControlNotFoundError is
raised.
If name is specified, then the control must have the indicated name.
If type is specified then the control must h... | def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None):
| if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (predicate is None) and (nr is None)):
raise ValueError('at least one argument must be supplied to specify control')
return self._find_control(name, type, kind, id, label, predica... |
'Return sequence of (key, value) pairs suitable for urlencoding.'
| def _pairs(self):
| return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()]
|
'Return sequence of (index, key, value, control_index)
of totally ordered pairs suitable for urlencoding.
control_index is the index of the control in self.controls'
| def _pairs_and_controls(self):
| pairs = []
for control_index in xrange(len(self.controls)):
control = self.controls[control_index]
for (ii, key, val) in control._totally_ordered_pairs():
pairs.append((ii, key, val, control_index))
pairs.sort()
return pairs
|
'Return a tuple (url, data, headers).'
| def _request_data(self):
| method = self.method.upper()
parts = self._urlparse(self.action)
(rest, (query, frag)) = (parts[:(-2)], parts[(-2):])
if (method == 'GET'):
self.enctype = 'application/x-www-form-urlencoded'
parts = (rest + (urlencode(self._pairs()), None))
uri = self._urlunparse(parts)
r... |
'Aggregate two event values.'
| def aggregate(self, val1, val2):
| assert (val1 is not None)
assert (val2 is not None)
return self._aggregator(val1, val2)
|
'Format an event value.'
| def format(self, val):
| assert (val is not None)
return self._formatter(val)
|
'Validate the edges.'
| def validate(self):
| for function in self.functions.itervalues():
for callee_id in function.calls.keys():
assert (function.calls[callee_id].callee_id == callee_id)
if (callee_id not in self.functions):
sys.stderr.write(('warning: call to undefined function %s from fun... |
'Find cycles using Tarjan\'s strongly connected components algorithm.'
| def find_cycles(self):
| visited = set()
for function in self.functions.itervalues():
if (function not in visited):
self._tarjan(function, 0, [], {}, {}, visited)
cycles = []
for function in self.functions.itervalues():
if ((function.cycle is not None) and (function.cycle not in cycles)):
... |
'Tarjan\'s strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan\'s_strongly_connected_components_algorithm'
| def _tarjan(self, function, order, stack, orders, lowlinks, visited):
| visited.add(function)
orders[function] = order
lowlinks[function] = order
order += 1
pos = len(stack)
stack.append(function)
for call in function.calls.itervalues():
callee = self.functions[call.callee_id]
if (callee not in orders):
order = self._tarjan(callee, or... |
'Propagate function time ratio allong the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html'
| def integrate(self, outevent, inevent):
| assert (outevent not in self)
for function in self.functions.itervalues():
assert (outevent not in function)
assert (inevent in function)
for call in function.calls.itervalues():
assert (outevent not in call)
if (call.callee_id != function.id):
ass... |
'Aggregate an event for the whole profile.'
| def aggregate(self, event):
| total = event.null()
for function in self.functions.itervalues():
try:
total = event.aggregate(total, function[event])
except UndefinedEvent:
return
self[event] = total
|
'Prune the profile'
| def prune(self, node_thres, edge_thres):
| for function in self.functions.itervalues():
try:
function.weight = function[TOTAL_TIME_RATIO]
except UndefinedEvent:
pass
for call in function.calls.itervalues():
callee = self.functions[call.callee_id]
if (TOTAL_TIME_RATIO in call):
... |
'Extract a structure from a match object, while translating the types in the process.'
| def translate(self, mo):
| attrs = {}
groupdict = mo.groupdict()
for (name, value) in groupdict.iteritems():
if (value is None):
value = None
elif self._int_re.match(value):
value = int(value)
elif self._float_re.match(value):
value = float(value)
attrs[name] = value... |
'Parse the call graph.'
| def parse_cg(self):
| while (not self._cg_header_re.match(self.readline())):
pass
line = self.readline()
while self._cg_header_re.match(line):
line = self.readline()
entry_lines = []
while (line != '\x0c'):
if (line and (not line.isspace())):
if self._cg_sep_re.match(line):
... |
'Convert a color from HSL color-model to RGB.
See also:
- http://www.w3.org/TR/css3-color/#hsl-color'
| def hsl_to_rgb(self, h, s, l):
| h = (h % 1.0)
s = min(max(s, 0.0), 1.0)
l = min(max(l, 0.0), 1.0)
if (l <= 0.5):
m2 = (l * (s + 1.0))
else:
m2 = ((l + s) - (l * s))
m1 = ((l * 2.0) - m2)
r = self._hue_to_rgb(m1, m2, (h + (1.0 / 3.0)))
g = self._hue_to_rgb(m1, m2, h)
b = self._hue_to_rgb(m1, m2, (h -... |
'Main program.'
| def main(self):
| parser = optparse.OptionParser(usage='\n DCTB %prog [options] [file] ...', version=('%%prog %s' % __version__))
parser.add_option('-o', '--output', metavar='FILE', type='string', dest='output', help='output filename [stdout]')
parser.add_option('-n', '--node-thres', metavar='PERCENTAGE', t... |
'Remove extraneous information from C++ demangled function names.'
| def strip_function_name(self, name):
| while True:
(name, n) = self._parenthesis_re.subn('', name)
if (not n):
break
name = self._const_re.sub('', name)
while True:
(name, n) = self._angles_re.subn('', name)
if (not n):
break
return name
|
'Split the function name on multiple lines.'
| def wrap_function_name(self, name):
| if (len(name) > 32):
ratio = (2.0 / 3.0)
height = max(int(((len(name) / (1.0 - ratio)) + 0.5)), 1)
width = max((len(name) / height), 32)
name = textwrap.fill(name, width, break_long_words=False)
name = name.replace(', ', ',')
name = name.replace('> >', '>>')
name = ... |
'Compress function name according to the user preferences.'
| def compress_function_name(self, name):
| if self.options.strip:
name = self.strip_function_name(name)
if self.options.wrap:
name = self.wrap_function_name(name)
return name
|
'Register a virtual subclass of an ABC.'
| def register(cls, subclass):
| if (not isinstance(subclass, (type, types.ClassType))):
raise TypeError('Can only register classes')
if issubclass(subclass, cls):
return
if issubclass(cls, subclass):
raise RuntimeError('Refusing to create an inheritance cycle')
cls._abc_registry.add(subc... |
'Debug helper to print the ABC registry.'
| def _dump_registry(cls, file=None):
| print >>file, ('Class: %s.%s' % (cls.__module__, cls.__name__))
print >>file, ('Inv.counter: %s' % ABCMeta._abc_invalidation_counter)
for name in sorted(cls.__dict__.keys()):
if name.startswith('_abc_'):
value = getattr(cls, name)
print >>file, ('%s: %r' % (name, val... |
'Override for isinstance(instance, cls).'
| def __instancecheck__(cls, instance):
| subclass = getattr(instance, '__class__', None)
if (subclass in cls._abc_cache):
return True
subtype = type(instance)
if (subtype is _InstanceType):
subtype = subclass
if ((subtype is subclass) or (subclass is None)):
if ((cls._abc_negative_cache_version == ABCMeta._abc_inval... |
'Override for issubclass(subclass, cls).'
| def __subclasscheck__(cls, subclass):
| if (subclass in cls._abc_cache):
return True
if (cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter):
cls._abc_negative_cache = set()
cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
elif (subclass in cls._abc_negative_cache):
return False
... |
'Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.'
| @classmethod
def _from_iterable(cls, it):
| return cls(it)
|
'Compute the hash value of a set.
Note that we don\'t define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
... | def _hash(self):
| MAX = sys.maxint
MASK = ((2 * MAX) + 1)
n = len(self)
h = (1927868237 * (n + 1))
h &= MASK
for x in self:
hx = hash(x)
h ^= (((hx ^ (hx << 16)) ^ 89869747) * 3644798167)
h &= MASK
h = ((h * 69069) + 907133923)
h &= MASK
if (h > MAX):
h -= (MASK + 1)
... |
'Add an element.'
| @abstractmethod
def add(self, value):
| raise NotImplementedError
|
'Remove an element. Do not raise an exception if absent.'
| @abstractmethod
def discard(self, value):
| raise NotImplementedError
|
'Remove an element. If not a member, raise a KeyError.'
| def remove(self, value):
| if (value not in self):
raise KeyError(value)
self.discard(value)
|
'Return the popped value. Raise KeyError if empty.'
| def pop(self):
| it = iter(self)
try:
value = it.next()
except StopIteration:
raise KeyError
self.discard(value)
return value
|
'This is slow (creates N new iterators!) but effective.'
| def clear(self):
| try:
while True:
self.pop()
except KeyError:
pass
|
'return a list of connected hosts and the number of connections
to each. [(\'foo.com:80\', 2), (\'bar.org\', 1)]'
| def open_connections(self):
| return [(host, len(li)) for (host, li) in self._cm.get_all().items()]
|
'close connection(s) to <host>
host is the host:port spec, as in \'www.cnn.com:8080\' as passed in.
no error occurs if there is no connection to that host.'
| def close_connection(self, host):
| for h in self._cm.get_all(host):
self._cm.remove(h)
h.close()
|
'close all open connections'
| def close_all(self):
| for (host, conns) in self._cm.get_all().items():
for h in conns:
self._cm.remove(h)
h.close()
|
'tells us that this request is now closed and the the
connection is ready for another request'
| def _request_closed(self, request, host, connection):
| self._cm.set_ready(connection, 1)
|
'start the transaction with a re-used connection
return a response object (r) upon success or None on failure.
This DOES not close or remove bad connections in cases where
it returns. However, if an unexpected exception occurs, it
will close and remove the connection before re-raising.'
| def _reuse_connection(self, h, req, host):
| try:
self._start_transaction(h, req)
r = h.getresponse()
except (socket.error, httplib.HTTPException):
r = None
except:
if DEBUG:
DEBUG.error(('unexpected exception - closing ' + 'connection to %s (%d)'), host, id(h))
self._cm.remove(h... |
'Create a new ordered dictionary. Cannot init from a normal dict,
nor from kwargs, since items order is undefined in those cases.
If the ``strict`` keyword argument is ``True`` (``False`` is the
default) then when doing slice assignment - the ``OrderedDict`` you are
assigning from *must not* contain any keys in the rem... | def __init__(self, init_val=(), strict=False):
| self.strict = strict
dict.__init__(self)
if isinstance(init_val, OrderedDict):
self._sequence = init_val.keys()
dict.update(self, init_val)
elif isinstance(init_val, dict):
raise TypeError('undefined order, cannot get items from dict')
else:
self._se... |
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> del d[3]
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> del d[3]
Traceback (most recent call last):
KeyError: 3
>>> d[3] = 2
>>> d
OrderedDict([(1, 3), (2, 1), (3, 2)])
>>> del d[0:1]
>>> d
OrderedDict([(2, 1), (3, 2)])'
| def __delitem__(self, key):
| if isinstance(key, types.SliceType):
keys = self._sequence[key]
for entry in keys:
dict.__delitem__(self, entry)
del self._sequence[key]
else:
dict.__delitem__(self, key)
self._sequence.remove(key)
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d == OrderedDict(d)
True
>>> d == OrderedDict(((1, 3), (2, 1), (3, 2)))
False
>>> d == OrderedDict(((1, 0), (3, 2), (2, 1)))
False
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d == dict(d)
False
>>> d == False
False'
| def __eq__(self, other):
| if isinstance(other, OrderedDict):
return (self.items() == other.items())
else:
return False
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> c < d
True
>>> d < c
False
>>> d < dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts'
| def __lt__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() < other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c <= d
True
>>> d <= c
False
>>> d <= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> d <= e
True'
| def __le__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() <= other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d != OrderedDict(d)
False
>>> d != OrderedDict(((1, 3), (2, 1), (3, 2)))
True
>>> d != OrderedDict(((1, 0), (3, 2), (2, 1)))
True
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d != dict(d)
True
>>> d != False
True'
| def __ne__(self, other):
| if isinstance(other, OrderedDict):
return (not (self.items() == other.items()))
else:
return True
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> d > c
True
>>> c > d
False
>>> d > dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts'
| def __gt__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() > other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c >= d
False
>>> d >= c
True
>>> d >= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> e >= d
True'
| def __ge__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() >= other.items())
|
'Used for __repr__ and __str__
>>> r1 = repr(OrderedDict(((\'a\', \'b\'), (\'c\', \'d\'), (\'e\', \'f\'))))
>>> r1
"OrderedDict([(\'a\', \'b\'), (\'c\', \'d\'), (\'e\', \'f\')])"
>>> r2 = repr(OrderedDict(((\'a\', \'b\'), (\'e\', \'f\'), (\'c\', \'d\'))))
>>> r2
"OrderedDict([(\'a\', \'b\'), (\'e\', \'f\'), (\'c\', \'d... | def __repr__(self):
| return ('%s([%s])' % (self.__class__.__name__, ', '.join([('(%r, %r)' % (key, self[key])) for key in self._sequence])))
|
'Allows slice assignment, so long as the slice is an OrderedDict
>>> d = OrderedDict()
>>> d[\'a\'] = \'b\'
>>> d[\'b\'] = \'a\'
>>> d[3] = 12
>>> d
OrderedDict([(\'a\', \'b\'), (\'b\', \'a\'), (3, 12)])
>>> d[:] = OrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
OrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d[::2] = OrderedDic... | def __setitem__(self, key, val):
| if isinstance(key, types.SliceType):
if (not isinstance(val, OrderedDict)):
raise TypeError('slice assignment requires an OrderedDict')
keys = self._sequence[key]
indexes = range(len(self._sequence))[key]
if (key.step is None):
pos = (key.start or ... |
'Allows slicing. Returns an OrderedDict if you slice.
>>> b = OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3), (3, 4), (2, 5), (1, 6)])
>>> b[::-1]
OrderedDict([(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)])
>>> b[2:5]
OrderedDict([(5, 2), (4, 3), (3, 4)])
>>> type(b[2:4])
<class \'__main__.OrderedDict\'>'
| def __getitem__(self, key):
| if isinstance(key, types.SliceType):
keys = self._sequence[key]
return OrderedDict([(entry, self[entry]) for entry in keys])
else:
return dict.__getitem__(self, key)
|
'Implemented so that accesses to ``sequence`` raise a warning and are
diverted to the new ``setkeys`` method.'
| def __setattr__(self, name, value):
| if (name == 'sequence'):
warnings.warn('Use of the sequence attribute is deprecated. Use the keys method instead.', DeprecationWarning)
self.setkeys(value)
else:
object.__setattr__(self, name, value)
|
'Implemented so that access to ``sequence`` raises a warning.
>>> d = OrderedDict()
>>> d.sequence'
| def __getattr__(self, name):
| if (name == 'sequence'):
warnings.warn('Use of the sequence attribute is deprecated. Use the keys method instead.', DeprecationWarning)
return self._sequence
else:
raise AttributeError(("OrderedDict has no '%s' attribute" % name))
|
'To allow deepcopy to work with OrderedDict.
>>> from copy import deepcopy
>>> a = OrderedDict([(1, 1), (2, 2), (3, 3)])
>>> a[\'test\'] = {}
>>> b = deepcopy(a)
>>> b == a
True
>>> b is a
False
>>> a[\'test\'] is b[\'test\']
False'
| def __deepcopy__(self, memo):
| from copy import deepcopy
return self.__class__(deepcopy(self.items(), memo), self.strict)
|
'>>> OrderedDict(((1, 3), (3, 2), (2, 1))).copy()
OrderedDict([(1, 3), (3, 2), (2, 1)])'
| def copy(self):
| return OrderedDict(self)
|
'``items`` returns a list of tuples representing all the
``(key, value)`` pairs in the dictionary.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.items()
[(1, 3), (3, 2), (2, 1)]
>>> d.clear()
>>> d.items()'
| def items(self):
| return zip(self._sequence, self.values())
|
'Return a list of keys in the ``OrderedDict``.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]'
| def keys(self):
| return self._sequence[:]
|
'Return a list of all the values in the OrderedDict.
Optionally you can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.values()
[3, 2, 1]'
| def values(self, values=None):
| return [self[key] for key in self._sequence]
|
'>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iteritems()
>>> ii.next()
(1, 3)
>>> ii.next()
(3, 2)
>>> ii.next()
(2, 1)
>>> ii.next()
Traceback (most recent call last):
StopIteration'
| def iteritems(self):
| def make_iter(self=self):
keys = self.iterkeys()
while True:
key = keys.next()
(yield (key, self[key]))
return make_iter()
|
'>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iterkeys()
>>> ii.next()
1
>>> ii.next()
3
>>> ii.next()
2
>>> ii.next()
Traceback (most recent call last):
StopIteration'
| def iterkeys(self):
| return iter(self._sequence)
|
'>>> iv = OrderedDict(((1, 3), (3, 2), (2, 1))).itervalues()
>>> iv.next()
3
>>> iv.next()
2
>>> iv.next()
1
>>> iv.next()
Traceback (most recent call last):
StopIteration'
| def itervalues(self):
| def make_iter(self=self):
keys = self.iterkeys()
while True:
(yield self[keys.next()])
return make_iter()
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.clear()
>>> d
OrderedDict([])'
| def clear(self):
| dict.clear(self)
self._sequence = []
|
'No dict.pop in Python 2.2, gotta reimplement it
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.pop(3)
2
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> d.pop(4)
Traceback (most recent call last):
KeyError: 4
>>> d.pop(4, 0)
0
>>> d.pop(4, 0, 1)
Traceback (most recent call last):
TypeError: pop expected at most 2 argument... | def pop(self, key, *args):
| if (len(args) > 1):
raise TypeError, ('pop expected at most 2 arguments, got %s' % (len(args) + 1))
if (key in self):
val = self[key]
del self[key]
else:
try:
val = args[0]
except IndexError:
raise KeyError(key)
return ... |
'Delete and return an item specified by index, not a random one as in
dict. The index is -1 by default (the last item).
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.popitem()
(2, 1)
>>> d
OrderedDict([(1, 3), (3, 2)])
>>> d.popitem(0)
(1, 3)
>>> OrderedDict().popitem()
Traceback (most recent call last):
KeyError... | def popitem(self, i=(-1)):
| if (not self._sequence):
raise KeyError('popitem(): dictionary is empty')
try:
key = self._sequence[i]
except IndexError:
raise IndexError(('popitem(): index %s not valid' % i))
return (key, self.pop(key))
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setdefault(1)
3
>>> d.setdefault(4) is None
True
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None)])
>>> d.setdefault(5, 0)
0
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None), (5, 0)])'
| def setdefault(self, key, defval=None):
| if (key in self):
return self[key]
else:
self[key] = defval
return defval
|
'Update from another OrderedDict or sequence of (key, value) pairs
>>> d = OrderedDict(((1, 0), (0, 1)))
>>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1))))
>>> d
OrderedDict([(1, 3), (0, 1), (3, 2), (2, 1)])
>>> d.update({4: 4})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
... | def update(self, from_od):
| if isinstance(from_od, OrderedDict):
for (key, val) in from_od.items():
self[key] = val
elif isinstance(from_od, dict):
raise TypeError('undefined order, cannot get items from dict')
else:
for item in from_od:
try:
(key, val) ... |
'Rename the key for a given value, without modifying sequence order.
For the case where new_key already exists this raise an exception,
since if new_key exists, it is ambiguous as to what happens to the
associated values, and the position of new_key in the sequence.
>>> od = OrderedDict()
>>> od[\'a\'] = 1
>>> od[\'b\'... | def rename(self, old_key, new_key):
| if (new_key == old_key):
return
if (new_key in self):
raise ValueError(('New key already exists: %r' % new_key))
value = self[old_key]
old_idx = self._sequence.index(old_key)
self._sequence[old_idx] = new_key
dict.__delitem__(self, old_key)
dict.__setitem__(self, ... |
'This method allows you to set the items in the dict.
It takes a list of tuples - of the same sort returned by the ``items``
method.
>>> d = OrderedDict()
>>> d.setitems(((3, 1), (2, 3), (1, 2)))
>>> d
OrderedDict([(3, 1), (2, 3), (1, 2)])'
| def setitems(self, items):
| self.clear()
self.update(items)
|
'``setkeys`` all ows you to pass in a new list of keys which will
replace the current set. This must contain the same set of keys, but
need not be in the same order.
If you pass in new keys that don\'t match, a ``KeyError`` will be
raised.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]
>>> d.setke... | def setkeys(self, keys):
| kcopy = list(keys)
kcopy.sort()
self._sequence.sort()
if (kcopy != self._sequence):
raise KeyError('Keylist is not the same as current keylist.')
self._sequence = list(keys)
|
'You can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
(Or a ``ValueError`` is raised.)
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setvalues((1, 2, 3))
>>> d
OrderedDict([(1, 1), (3, 2), (2, 3)])
>>> d.setvalues([6])
Traceback (most recen... | def setvalues(self, values):
| if (len(values) != len(self)):
raise ValueError('Value list is not the same length as the OrderedDict.')
self.update(zip(self, values))
|
'Return the position of the specified key in the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.index(3)
1
>>> d.index(4)
Traceback (most recent call last):
ValueError: list.index(x): x not in list'
| def index(self, key):
| return self._sequence.index(key)
|
'Takes ``index``, ``key``, and ``value`` as arguments.
Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in
the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.insert(0, 4, 0)
>>> d
OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)])
>>> d.insert(0, 2, 1)
>>> d
OrderedDict([(2, 1), (4, 0), ... | def insert(self, index, key, value):
| if (key in self):
del self[key]
self._sequence.insert(index, key)
dict.__setitem__(self, key, value)
|
'Reverse the order of the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.reverse()
>>> d
OrderedDict([(2, 1), (3, 2), (1, 3)])'
| def reverse(self):
| self._sequence.reverse()
|
'Sort the key order in the OrderedDict.
This method takes the same arguments as the ``list.sort`` method on
your version of Python.
>>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4)))
>>> d.sort()
>>> d
OrderedDict([(1, 4), (2, 2), (3, 3), (4, 1)])'
| def sort(self, *args, **kwargs):
| self._sequence.sort(*args, **kwargs)
|
'Pretend to be the keys method.'
| def __call__(self):
| return self._main._keys()
|
'Fetch the key at position i.'
| def __getitem__(self, index):
| return self._main._sequence[index]
|
'You cannot assign to keys, but you can do slice assignment to re-order
them.
You can only do slice assignment if the new set of keys is a reordering
of the original set.'
| def __setitem__(self, index, name):
| if isinstance(index, types.SliceType):
indexes = range(len(self._main._sequence))[index]
if (len(indexes) != len(name)):
raise ValueError(('attempt to assign sequence of size %s to slice of size %s' % (len(name), len(indexes))))
old_keys = self._m... |
'Pretend to be the items method.'
| def __call__(self):
| return self._main._items()
|
'Fetch the item at position i.'
| def __getitem__(self, index):
| if isinstance(index, types.SliceType):
return self._main[index].items()
key = self._main._sequence[index]
return (key, self._main[key])
|
'Set item at position i to item.'
| def __setitem__(self, index, item):
| if isinstance(index, types.SliceType):
self._main[index] = OrderedDict(item)
else:
orig = self._main.keys[index]
(key, value) = item
if (self._main.strict and (key in self) and (key != orig)):
raise ValueError('slice assignment must be from unique ke... |
'Delete the item at position i.'
| def __delitem__(self, i):
| key = self._main._sequence[i]
if isinstance(i, types.SliceType):
for k in key:
del self._main[k]
else:
del self._main[key]
|
'Add an item to the end.'
| def append(self, item):
| (key, value) = item
self._main[key] = value
|
'Pretend to be the values method.'
| def __call__(self):
| return self._main._values()
|
'Fetch the value at position i.'
| def __getitem__(self, index):
| if isinstance(index, types.SliceType):
return [self._main[key] for key in self._main._sequence[index]]
else:
return self._main[self._main._sequence[index]]
|
'Set the value at position i to value.
You can only do slice assignment to values if you supply a sequence of
equal length to the slice you are replacing.'
| def __setitem__(self, index, value):
| if isinstance(index, types.SliceType):
keys = self._main._sequence[index]
if (len(keys) != len(value)):
raise ValueError(('attempt to assign sequence of size %s to slice of size %s' % (len(name), len(keys))))
for (key, val) in zip(keys, value):
... |
'Reverse the values'
| def reverse(self):
| vals = self._main.values()
vals.reverse()
self[:] = vals
|
'Sort the values.'
| def sort(self, *args, **kwds):
| vals = self._main.values()
vals.sort(*args, **kwds)
self[:] = vals
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.