_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6000 | screen._print | train | def _print(self, char):
"""
Print a character at the current cursor position and advance the
cursor.
"""
# Don't make bugs where we try to print a screen.
assert len(char) == 1
try:
try:
# Python 3
char = self.decoder... | python | {
"resource": ""
} |
q6001 | screen._index | train | def _index(self):
"""
Move the cursor down one row in the same column. If the cursor is at
the last row, create a new row at the bottom.
"""
if self.y + 1 >= self.size[0]:
# If the cursor is currently on the last row, then spawn another
# and scroll down... | python | {
"resource": ""
} |
q6002 | screen._reverse_index | train | def _reverse_index(self):
"""
Move the cursor up one row in the same column. If the cursor is at the
first row, create a new row at the top.
"""
if self.y == 0:
# If the cursor is currently at the first row, then scroll the
# screen up.
self.di... | python | {
"resource": ""
} |
q6003 | screen._next_tab_stop | train | def _next_tab_stop(self):
"""
Return the x value of the next available tabstop or the x value of the
margin if there are no more tabstops.
"""
for stop in sorted(self.tabstops):
if self.x < stop:
return stop
return self.size[1] - 1 | python | {
"resource": ""
} |
q6004 | screen._insert_line | train | def _insert_line(self, count=1):
"""
Inserts lines at line with cursor. Lines displayed below cursor move
down. Lines moved past the bottom margin are lost.
"""
trimmed = self.display[:self.y+1] + \
[u" " * self.size[1]] * count + \
self.disp... | python | {
"resource": ""
} |
q6005 | screen._delete_line | train | def _delete_line(self, count=1):
"""
Deletes count lines, starting at line with cursor. As lines are
deleted, lines displayed below cursor move up. Lines added to bottom of
screen have spaces with same character attributes as last line moved
up.
"""
self.display... | python | {
"resource": ""
} |
q6006 | screen._delete_character | train | def _delete_character(self, count=1):
"""
Deletes count characters, starting with the character at cursor
position. When a character is deleted, all characters to the right
of cursor move left.
"""
# First resize the text display
row = self.display[self.y]
... | python | {
"resource": ""
} |
q6007 | screen._erase_in_line | train | def _erase_in_line(self, type_of=0):
"""
Erases the row in a specific way, depending on the type_of.
"""
row = self.display[self.y]
attrs = self.attributes[self.y]
if type_of == 0:
# Erase from the cursor to the end of line, including the cursor
r... | python | {
"resource": ""
} |
q6008 | screen._cursor_down | train | def _cursor_down(self, count=1):
"""
Moves cursor down count lines in same column. Cursor stops at bottom
margin.
"""
self.y = min(self.size[0] - 1, self.y + count) | python | {
"resource": ""
} |
q6009 | screen._cursor_forward | train | def _cursor_forward(self, count=1):
"""
Moves cursor right count columns. Cursor stops at right margin.
"""
self.x = min(self.size[1] - 1, self.x + count) | python | {
"resource": ""
} |
q6010 | screen._cursor_position | train | def _cursor_position(self, row=0, column=0):
"""
Set the cursor to a specific row and column.
Obnoxiously row/column is 1 based, instead of zero based, so we need
to compensate. I know I've created bugs in here somehow.
Confoundingly, inputs of 0 are still acceptable, and shou... | python | {
"resource": ""
} |
q6011 | screen._text_attr | train | def _text_attr(self, attr):
"""
Given a text attribute, set the current cursor appropriately.
"""
attr = text[attr]
if attr == "reset":
self.cursor_attributes = self.default_attributes
elif attr == "underline-off":
self.cursor_attributes = self._re... | python | {
"resource": ""
} |
q6012 | screen._color_attr | train | def _color_attr(self, ground, attr):
"""
Given a color attribute, set the current cursor appropriately.
"""
attr = colors[ground][attr]
attrs = self.cursor_attributes
if ground == "foreground":
self.cursor_attributes = (attrs[0], attr, attrs[2])
elif ... | python | {
"resource": ""
} |
q6013 | screen._set_attr | train | def _set_attr(self, attr):
"""
Given some text attribute, set the current cursor attributes
appropriately.
"""
if attr in text:
self._text_attr(attr)
elif attr in colors["foreground"]:
self._color_attr("foreground", attr)
elif attr in colo... | python | {
"resource": ""
} |
q6014 | screen._select_graphic_rendition | train | def _select_graphic_rendition(self, *attrs):
"""
Set the current text attribute.
"""
if len(attrs) == 0:
# No arguments means that we're really trying to do a reset.
attrs = [0]
for attr in attrs:
self._set_attr(attr) | python | {
"resource": ""
} |
q6015 | FlatDict.setdefault | train | def setdefault(self, key, default):
"""If key is in the flat dictionary, return its value. If not,
insert key with a value of default and return default.
default defaults to ``None``.
:param mixed key: The key name
:param mixed default: The default value
:rtype: mixed
... | python | {
"resource": ""
} |
q6016 | FlatterDict._child_as_list | train | def _child_as_list(self, pk, ck):
"""Returns a list of values from the child FlatterDict instance
with string based integer keys.
:param str pk: The parent key
:param str ck: The child key
:rtype: list
"""
return [self._values[pk][ck][k]
for k in... | python | {
"resource": ""
} |
q6017 | V.gen_query | train | def gen_query(self):
"""
Generate an SQL query for the edge object.
"""
return (
SQL.forwards_relation(self.src, self.rel) if self.dst is None else
SQL.inverse_relation(self.dst, self.rel)
) | python | {
"resource": ""
} |
q6018 | Query.traverse | train | def traverse(self, edge):
"""
Traverse the graph, and selecting the destination
nodes for a particular relation that the selected
nodes are a source of, i.e. select the friends of
my friends. You can traverse indefinitely.
:param edge: The edge query. If the edge's
... | python | {
"resource": ""
} |
q6019 | Graph.setup_sql | train | def setup_sql(self, graphs):
"""
Sets up the SQL tables for the graph object,
and creates indexes as well.
:param graphs: The graphs to create.
"""
with closing(self.db.cursor()) as cursor:
for table in graphs:
cursor.execute(SQL.CREATE_TABLE ... | python | {
"resource": ""
} |
q6020 | remove | train | def remove(src, rel, dst):
"""
Returns an SQL statement that removes edges from
the SQL backing store. Either `src` or `dst` may
be specified, even both.
:param src: The source node.
:param rel: The relation.
:param dst: The destination node.
"""
smt = 'DELETE FROM %s' % rel
que... | python | {
"resource": ""
} |
q6021 | Transaction.perform_ops | train | def perform_ops(self):
"""
Performs the stored operations on the database
connection.
"""
with self.db:
with closing(self.db.cursor()) as cursor:
cursor.execute('BEGIN TRANSACTION')
self._perform_ops(cursor) | python | {
"resource": ""
} |
q6022 | HTTPClient.from_url | train | def from_url(cls, url, **kwargs):
"""Create a client from a url."""
url = urllib3.util.parse_url(url)
if url.host:
kwargs.setdefault('host', url.host)
if url.port:
kwargs.setdefault('port', url.port)
if url.scheme == 'https':
kwargs.setdefaul... | python | {
"resource": ""
} |
q6023 | NsqdTCPClient.connect | train | def connect(self):
"""Initialize connection to the nsqd."""
if self.state == DISCONNECTED:
raise errors.NSQException('connection already closed')
if self.is_connected:
return
stream = Stream(self.address, self.port, self.timeout)
stream.connect()
... | python | {
"resource": ""
} |
q6024 | NsqdTCPClient.close_stream | train | def close_stream(self):
"""Close the underlying socket."""
if not self.is_connected:
return
self.stream.close()
self.state = DISCONNECTED
self.on_close.send(self) | python | {
"resource": ""
} |
q6025 | NsqdTCPClient.read_response | train | def read_response(self):
"""Read an individual response from nsqd.
:returns: tuple of the frame type and the processed data.
"""
response = self._read_response()
frame, data = nsq.unpack_response(response)
self.last_response = time.time()
if frame not in self._f... | python | {
"resource": ""
} |
q6026 | NsqdTCPClient.identify | train | def identify(self):
"""Update client metadata on the server and negotiate features.
:returns: nsqd response data if there was feature negotiation,
otherwise ``None``
"""
self.send(nsq.identify({
# nsqd 0.2.28+
'client_id': self.client_id,
... | python | {
"resource": ""
} |
q6027 | NsqdTCPClient.auth | train | def auth(self):
"""Send authorization secret to nsqd."""
self.send(nsq.auth(self.auth_secret))
frame, data = self.read_response()
if frame == nsq.FRAME_TYPE_ERROR:
raise data
try:
response = json.loads(data.decode('utf-8'))
except ValueError:
... | python | {
"resource": ""
} |
q6028 | NsqdTCPClient.subscribe | train | def subscribe(self, topic, channel):
"""Subscribe to a nsq `topic` and `channel`."""
self.send(nsq.subscribe(topic, channel)) | python | {
"resource": ""
} |
q6029 | NsqdTCPClient.publish | train | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over tcp.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publishing
(requires nsq 0.3.6)
"""
... | python | {
"resource": ""
} |
q6030 | NsqdTCPClient.ready | train | def ready(self, count):
"""Indicate you are ready to receive ``count`` messages."""
self.ready_count = count
self.send(nsq.ready(count)) | python | {
"resource": ""
} |
q6031 | NsqdHTTPClient.publish | train | def publish(self, topic, data, defer=None):
"""Publish a message to the given topic over http.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in millisconds to defer before publishing
(requires nsq 0.3.6)
"""
... | python | {
"resource": ""
} |
q6032 | NsqdHTTPClient.create_topic | train | def create_topic(self, topic):
"""Create a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/create', fields={'topic': topic}) | python | {
"resource": ""
} |
q6033 | NsqdHTTPClient.delete_topic | train | def delete_topic(self, topic):
"""Delete a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/delete', fields={'topic': topic}) | python | {
"resource": ""
} |
q6034 | NsqdHTTPClient.empty_topic | train | def empty_topic(self, topic):
"""Empty all the queued messages for an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/empty', fields={'topic': topic}) | python | {
"resource": ""
} |
q6035 | NsqdHTTPClient.empty_channel | train | def empty_channel(self, topic, channel):
"""Empty all the queued messages for an existing channel."""
nsq.assert_valid_topic_name(topic)
nsq.assert_valid_channel_name(channel)
return self._request('POST', '/channel/empty',
fields={'topic': topic, 'channel': c... | python | {
"resource": ""
} |
q6036 | NsqdHTTPClient.pause_topic | train | def pause_topic(self, topic):
"""Pause message flow to all channels on an existing topic.
Messages will queue at topic.
"""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/pause', fields={'topic': topic}) | python | {
"resource": ""
} |
q6037 | NsqdHTTPClient.unpause_topic | train | def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/unpause', fields={'topic': topic}) | python | {
"resource": ""
} |
q6038 | NsqdHTTPClient.stats | train | def stats(self, topic=None, channel=None, text=False):
"""Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
"""
if text:
... | python | {
"resource": ""
} |
q6039 | Producer.join | train | def join(self, timeout=None, raise_error=False):
"""Block until all connections have closed and workers stopped."""
self._workers.join(timeout, raise_error) | python | {
"resource": ""
} |
q6040 | Producer.publish | train | def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publish... | python | {
"resource": ""
} |
q6041 | Producer.multipublish | train | def multipublish(self, topic, messages, block=True, timeout=None,
raise_error=True):
"""Publish an iterable of messages to the given topic.
:param topic: the topic to publish to
:param messages: iterable of bytestrings to publish
:param block: wait for a connectio... | python | {
"resource": ""
} |
q6042 | LookupdClient.lookup | train | def lookup(self, topic):
"""Returns producers for a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/lookup', fields={'topic': topic}) | python | {
"resource": ""
} |
q6043 | LookupdClient.channels | train | def channels(self, topic):
"""Returns all known channels of a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/channels', fields={'topic': topic}) | python | {
"resource": ""
} |
q6044 | LookupdClient.tombstone_topic | train | def tombstone_topic(self, topic, node):
"""Tombstones a specific producer of an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/tombstone',
fields={'topic': topic, 'node': node}) | python | {
"resource": ""
} |
q6045 | deprecated | train | def deprecated(fn):
"""Mark a function as deprecated and warn the user on use."""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn(fn.__doc__.split('\n')[0],
category=DeprecationWarning, stacklevel=2)
return fn(*args, **kwargs)
return wrapper | python | {
"resource": ""
} |
q6046 | _new_lnotab | train | def _new_lnotab(instrs, lnotab):
"""The updated lnotab after the instructions have been transformed.
Parameters
----------
instrs : iterable[Instruction]
The new instructions.
lnotab : dict[Instruction -> int]
The lnotab for the old code object.
Returns
-------
new_lnot... | python | {
"resource": ""
} |
q6047 | CodeTransformer.transform_consts | train | def transform_consts(self, consts):
"""transformer for the co_consts field.
Override this method to transform the `co_consts` of the code object.
Parameters
----------
consts : tuple
The co_consts
Returns
-------
new_consts : tuple
... | python | {
"resource": ""
} |
q6048 | CodeTransformer.transform | train | def transform(self, code, *, name=None, filename=None):
"""Transform a codetransformer.Code object applying the transforms.
Parameters
----------
code : Code
The code object to transform.
name : str, optional
The new name for this code object.
fil... | python | {
"resource": ""
} |
q6049 | pformat_ast | train | def pformat_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT):
"""
Pretty-format an AST tree element
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whether to include... | python | {
"resource": ""
} |
q6050 | pprint_ast | train | def pprint_ast(node,
include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
indent=INDENT_DEFAULT,
file=None):
"""
Pretty-print an AST tree.
Parameters
----------
node : ast.AST
Top-level node to render.
include_attributes : bool, optional
Whe... | python | {
"resource": ""
} |
q6051 | walk_code | train | def walk_code(co, _prefix=''):
"""
Traverse a code object, finding all consts which are also code objects.
Yields pairs of (name, code object).
"""
name = _prefix + co.co_name
yield name, co
yield from chain.from_iterable(
walk_code(c, _prefix=_extend_name(name, co))
for c i... | python | {
"resource": ""
} |
q6052 | a | train | def a(text, mode='exec', indent=' ', file=None):
"""
Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode... | python | {
"resource": ""
} |
q6053 | d | train | def d(obj, mode='exec', file=None):
"""
Interactive convenience for displaying the disassembly of a function,
module, or code string.
Compiles `text` and recursively traverses the result looking for `code`
objects to render with `dis.dis`.
Parameters
----------
obj : str, CodeType, or ... | python | {
"resource": ""
} |
q6054 | extract_code | train | def extract_code(obj, compile_mode):
"""
Generic function for converting objects into instances of `CodeType`.
"""
try:
code = obj.__code__
if isinstance(code, CodeType):
return code
raise ValueError(
"{obj} has a `__code__` attribute, "
"but i... | python | {
"resource": ""
} |
q6055 | display | train | def display(text, mode='exec', file=None):
"""
Show `text`, rendered as AST and as Bytecode.
Parameters
----------
text : str
Text of Python code to render.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse` and `compile`. Default is 'exec'.
file : None or file-like obj... | python | {
"resource": ""
} |
q6056 | match | train | def match(match_expr, exc_type, exc_value, exc_traceback):
"""
Called to determine whether or not an except block should be matched.
True -> enter except block
False -> don't enter except block
"""
# Emulate standard behavior when match_expr is an exception subclass.
if isinstance(match_exp... | python | {
"resource": ""
} |
q6057 | decompile | train | def decompile(f):
"""
Decompile a function.
Parameters
----------
f : function
The function to decompile.
Returns
-------
ast : ast.FunctionDef
A FunctionDef node that compiles to f.
"""
co = f.__code__
args, kwonly, varargs, varkwargs = paramnames(co)
a... | python | {
"resource": ""
} |
q6058 | pycode_to_body | train | def pycode_to_body(co, context):
"""
Convert a Python code object to a list of AST body elements.
"""
code = Code.from_pycode(co)
# On each instruction, temporarily store all the jumps to the **next**
# instruction. This is used in _make_expr to determine when an expression
# is part of a ... | python | {
"resource": ""
} |
q6059 | instrs_to_body | train | def instrs_to_body(instrs, context):
"""
Convert a list of Instruction objects to a list of AST body nodes.
"""
stack = []
body = []
process_instrs(instrs, stack, body, context)
if stack:
raise DecompilationError(
"Non-empty stack at the end of instrs_to_body(): %s." % s... | python | {
"resource": ""
} |
q6060 | process_instrs | train | def process_instrs(queue, stack, body, context):
"""
Process instructions from the instruction queue.
"""
next_instr = queue.popleft
while queue:
newcontext = _process_instr(next_instr(), queue, stack, body, context)
if newcontext is not None:
context = newcontext | python | {
"resource": ""
} |
q6061 | make_if_statement | train | def make_if_statement(instr, queue, stack, context):
"""
Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
"""
test_expr = make_expr(stack)
if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)
first_block = popwhile(op.... | python | {
"resource": ""
} |
q6062 | _process_instr_import_name | train | def _process_instr_import_name(instr, queue, stack, body, context):
"""
Process an IMPORT_NAME instruction.
Side Effects
------------
Pops two instuctions from `stack`
Consumes instructions from `queue` to the end of the import statement.
Appends an ast.Import or ast.ImportFrom node to `bod... | python | {
"resource": ""
} |
q6063 | make_importfrom_alias | train | def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of t... | python | {
"resource": ""
} |
q6064 | _make_function | train | def _make_function(instr, queue, stack, body, context):
"""
Set a make_function_context, then push onto the stack.
"""
assert stack, "Empty stack before MAKE_FUNCTION."
prev = stack[-1]
expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION")
stack.append(instr)
if is_lambda_name(prev.a... | python | {
"resource": ""
} |
q6065 | make_assignment | train | def make_assignment(instr, queue, stack):
"""
Make an ast.Assign node.
"""
value = make_expr(stack)
# Make assignment targets.
# If there are multiple assignments (e.g. 'a = b = c'),
# each LHS expression except the last is preceded by a DUP_TOP instruction.
# Thus, we make targets unti... | python | {
"resource": ""
} |
q6066 | pop_with_body_instrs | train | def pop_with_body_instrs(setup_with_instr, queue):
"""
Pop instructions from `queue` that form the body of a with block.
"""
body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')
# Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
# These don't correspond... | python | {
"resource": ""
} |
q6067 | make_withitem | train | def make_withitem(queue, stack):
"""
Make an ast.withitem node.
"""
context_expr = make_expr(stack)
# This is a POP_TOP for just "with <expr>:".
# This is a STORE_NAME(name) for "with <expr> as <name>:".
as_instr = queue.popleft()
if isinstance(as_instr, (instrs.STORE_FAST,
... | python | {
"resource": ""
} |
q6068 | make_for_loop | train | def make_for_loop(loop_body_instrs, else_body_instrs, context):
"""
Make an ast.For node.
"""
# Instructions from start until GET_ITER are the builders for the iterator
# expression.
iterator_expr = make_expr(
popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left')
)
# N... | python | {
"resource": ""
} |
q6069 | make_while_loop | train | def make_while_loop(test_and_body_instrs, else_body_instrs, context):
"""
Make an ast.While node.
Parameters
----------
test_and_body_instrs : deque
Queue of instructions forming the loop test expression and body.
else_body_instrs : deque
Queue of instructions forming the else b... | python | {
"resource": ""
} |
q6070 | pop_loop_instrs | train | def pop_loop_instrs(setup_loop_instr, queue):
"""
Determine whether setup_loop_instr is setting up a for-loop or a
while-loop. Then pop the loop instructions from queue.
The easiest way to tell the difference is to look at the target of the
JUMP_ABSOLUTE instruction at the end of the loop. If it ... | python | {
"resource": ""
} |
q6071 | _make_expr | train | def _make_expr(toplevel, stack_builders):
"""
Override the single-dispatched make_expr with wrapper logic for handling
short-circuiting expressions.
"""
base_expr = _make_expr_internal(toplevel, stack_builders)
if not toplevel._next_target_of:
return base_expr
subexprs = deque([base... | python | {
"resource": ""
} |
q6072 | make_call_keywords | train | def make_call_keywords(stack_builders, count):
"""
Make the keywords entry for an ast.Call node.
"""
out = []
for _ in range(count):
value = make_expr(stack_builders)
load_kwname = stack_builders.pop()
if not isinstance(load_kwname, instrs.LOAD_CONST):
raise Decom... | python | {
"resource": ""
} |
q6073 | make_call_positionals | train | def make_call_positionals(stack_builders, count):
"""
Make the args entry for an ast.Call node.
"""
out = [make_expr(stack_builders) for _ in range(count)]
out.reverse()
return out | python | {
"resource": ""
} |
q6074 | _make_expr_empty_dict | train | def _make_expr_empty_dict(toplevel, stack_builders):
"""
This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead.
"""
if toplevel.arg:
raise DecompilationError(
"make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
)
... | python | {
"resource": ""
} |
q6075 | find_build_map | train | def find_build_map(stack_builders):
"""
Find the BUILD_MAP instruction for which the last element of
``stack_builders`` is a store.
"""
assert isinstance(stack_builders[-1], instrs.STORE_MAP)
to_consume = 0
for instr in reversed(stack_builders):
if isinstance(instr, instrs.STORE_MAP... | python | {
"resource": ""
} |
q6076 | _make_dict_elems | train | def _make_dict_elems(build_instr, builders):
"""
Return a list of keys and a list of values for the dictionary literal
generated by ``build_instr``.
"""
keys = []
values = []
for _ in range(build_instr.arg):
popped = builders.pop()
if not isinstance(popped, instrs.STORE_MAP):... | python | {
"resource": ""
} |
q6077 | normalize_tuple_slice | train | def normalize_tuple_slice(node):
"""
Normalize an ast.Tuple node representing the internals of a slice.
Returns the node wrapped in an ast.Index.
Returns an ExtSlice node built from the tuple elements if there are any
slices.
"""
if not any(isinstance(elt, ast.Slice) for elt in node.elts):
... | python | {
"resource": ""
} |
q6078 | _binop_handler | train | def _binop_handler(nodetype):
"""
Factory function for binary operator handlers.
"""
def _handler(toplevel, stack_builders):
right = make_expr(stack_builders)
left = make_expr(stack_builders)
return ast.BinOp(left=left, op=nodetype(), right=right)
return _handler | python | {
"resource": ""
} |
q6079 | make_function_arguments | train | def make_function_arguments(args,
kwonly,
varargs,
varkwargs,
defaults,
kw_defaults,
annotations):
"""
Make an ast.arguments from the args parse... | python | {
"resource": ""
} |
q6080 | make_global_and_nonlocal_decls | train | def make_global_and_nonlocal_decls(code_instrs):
"""
Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations.
"""
globals_ = sorted(set(
i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOB... | python | {
"resource": ""
} |
q6081 | make_defaults_and_annotations | train | def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_... | python | {
"resource": ""
} |
q6082 | _check_make_function_instrs | train | def _check_make_function_instrs(load_code_instr,
load_name_instr,
make_function_instr,
*,
expect_lambda=False):
"""
Validate the instructions passed to a make_function call.
"""
... | python | {
"resource": ""
} |
q6083 | pop_arguments | train | def pop_arguments(instr, stack):
"""
Pop instructions off `stack` until we pop all instructions that will
produce values popped by `instr`.
"""
needed = instr.stack_effect
if needed >= 0:
raise DecompilationError(
"%s is does not have a negative stack effect" % instr
... | python | {
"resource": ""
} |
q6084 | _check_stack_for_module_return | train | def _check_stack_for_module_return(stack):
"""
Verify that the stack is in the expected state before the dummy
RETURN_VALUE instruction of a module or class.
"""
fail = (
len(stack) != 1
or not isinstance(stack[0], instrs.LOAD_CONST)
or stack[0].arg is not None
)
if ... | python | {
"resource": ""
} |
q6085 | expect | train | def expect(instr, expected, context):
"""
Check that an instruction is of the expected type.
"""
if not isinstance(instr, expected):
raise DecompilationError(
"Expected a {expected} instruction {context}. Got {instr}.".format(
instr=instr, expected=expected, context=c... | python | {
"resource": ""
} |
q6086 | overloaded_constants | train | def overloaded_constants(type_, __doc__=None):
"""A factory for transformers that apply functions to literals.
Parameters
----------
type_ : type
The type to overload.
__doc__ : str, optional
Docstring for the generated transformer.
Returns
-------
transformer : subclas... | python | {
"resource": ""
} |
q6087 | paramnames | train | def paramnames(co):
"""
Get the parameter names from a pycode object.
Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs).
varargs and varkwargs will be None if the function doesn't take *args or
**kwargs, respectively.
"""
flags = co.co_flags
varnames = co.co_varnames
argc... | python | {
"resource": ""
} |
q6088 | _freevar_argname | train | def _freevar_argname(arg, cellvars, freevars):
"""
Get the name of the variable manipulated by a 'uses_free' instruction.
Parameters
----------
arg : int
The raw argument to a uses_free instruction that we want to resolve to
a name.
cellvars : list[str]
The co_cellvars o... | python | {
"resource": ""
} |
q6089 | pycode | train | def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars=(),
cellvars=())... | python | {
"resource": ""
} |
q6090 | Code.from_pycode | train | def from_pycode(cls, co):
"""Create a Code object from a python code object.
Parameters
----------
co : CodeType
The python code object.
Returns
-------
code : Code
The codetransformer Code object.
"""
# Make it sparse to ... | python | {
"resource": ""
} |
q6091 | Code.to_pycode | train | def to_pycode(self):
"""Create a python code object from the more abstract
codetransfomer.Code object.
Returns
-------
co : CodeType
The python code object.
"""
consts = self.consts
names = self.names
varnames = self.varnames
f... | python | {
"resource": ""
} |
q6092 | Code.consts | train | def consts(self):
"""The constants referenced in this code object.
"""
# We cannot use a set comprehension because consts do not need
# to be hashable.
consts = []
append_const = consts.append
for instr in self.instrs:
if isinstance(instr, LOAD_CONST) ... | python | {
"resource": ""
} |
q6093 | Code.names | train | def names(self):
"""The names referenced in this code object.
Names come from instructions like LOAD_GLOBAL or STORE_ATTR
where the name of the global or attribute is needed at runtime.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to... | python | {
"resource": ""
} |
q6094 | Code.varnames | train | def varnames(self):
"""The names of all of the local variables in this code object.
"""
# We must sort to preserve the order between calls.
# The set comprehension is to drop the duplicates.
return self._argnames + tuple(sorted({
instr.arg
for instr in sel... | python | {
"resource": ""
} |
q6095 | Code.py_lnotab | train | def py_lnotab(self):
"""The encoded lnotab that python uses to compute when lines start.
Note
----
See Objects/lnotab_notes.txt in the cpython source for more details.
"""
reverse_lnotab = reverse_dict(self.lnotab)
py_lnotab = []
prev_instr = 0
pr... | python | {
"resource": ""
} |
q6096 | Code.stacksize | train | def stacksize(self):
"""The maximum amount of stack space used by this code object.
"""
return max(scanl(
op.add,
0,
map(op.attrgetter('stack_effect'), self.instrs),
)) | python | {
"resource": ""
} |
q6097 | initialize_slot | train | def initialize_slot(obj, name, value):
"""Initalize an unitialized slot to a value.
If there is already a value for this slot, this is a nop.
Parameters
----------
obj : immutable
An immutable object.
name : str
The name of the slot to initialize.
value : any
The va... | python | {
"resource": ""
} |
q6098 | scanl | train | def scanl(f, n, ns):
"""Reduce ns by f starting with n yielding each intermediate value.
tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n)
Parameters
----------
f : callable
A binary function.
n : any
The starting value.
ns : iterable of any
The iterable to scan over.
... | python | {
"resource": ""
} |
q6099 | ffill | train | def ffill(iterable):
"""Forward fill non None values in some iterable.
Parameters
----------
iterable : iterable
The iterable to forward fill.
Yields
------
e : any
The last non None value or None if there has not been a non None value.
"""
it = iter(iterable)
p... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.