text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_definition(self):
"""Checks variable and executable code elements based on the current context for a code element whose name matches context.exact_match ... |
#Check the variables first, then the functions.
match = self._bracket_exact_var(self.context.exact_match)
if match is None:
match = self._bracket_exact_exec(self.context.exact_match)
return match |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bracket_exact_var(self, symbol):
"""Checks local first and then module global variables for an exact match to the specified symbol name.""" |
if isinstance(self.element, Executable):
if symbol in self.element.parameters:
return self.element.parameters[symbol]
if symbol in self.element.members:
return self.element.members[symbol]
if symbol in self.element.module.members:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bracket_exact_exec(self, symbol):
"""Checks builtin, local and global executable collections for the specified symbol and returns it as soon as it is found.... |
if symbol in self.context.module.executables:
return self.context.module.executables[symbol]
if symbol in self.context.module.interfaces:
return self.context.module.interfaces[symbol]
if symbol in cache.builtin:
return cache.builtin[symbol]
#Loop t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_signature(self, iexec, call_name):
"""Compiles the signature for the specified executable and returns as a dictionary.""" |
if iexec is not None:
summary = iexec.summary
if isinstance(iexec, Function):
summary = iexec.returns + "| " + iexec.summary
elif isinstance(iexec, Subroutine) and len(iexec.modifiers) > 0:
summary = ", ".join(iexec.modifiers) + " | " + iexec.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature(self):
"""Gets completion or call signature information for the current cursor.""" |
#We can't really do anything sensible without the name of the function
#whose signature we are completing.
iexec, execmod = self.context.parser.tree_find(self.context.el_name,
self.context.module, "executables")
if iexec is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _signature_index(self, iexec):
"""Determines where in the call signature the cursor is to decide which parameter needs to have its information returned for t... |
#Find out where in the signature the cursor is at the moment.
call_index = self.context.call_arg_index
if call_index is not None:
#We found the index of the parameter whose docstring we want
#to return.
param = iexec.get_parameter(call_index)
para... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete(self):
"""Gets a list of completion objects for the symbol under the cursor.""" |
if self._possible is None:
self._possible = []
for possible in self.names:
c = Completion(self.context, self.names[possible], len(self.context.symbol))
self._possible.append(c)
return self._possible |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _symbol_in(self, symbol, name):
"""Checks whether the specified symbol is part of the name for completion.""" |
lsymbol = symbol.lower()
lname = name.lower()
return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_chain_parent_symbol(self, symbol, fullsymbol):
"""Gets the code element object for the parent of the specified symbol in the fullsymbol chain.""" |
#We are only interested in the type of the variable immediately preceding our symbol
#in the chain so we can list its members.
chain = fullsymbol.split("%")
#We assume that if symbol != fullsymbol, we have at least a % at the end that
#tricked the symbol regex.
if len(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _complete_type_chain(self, symbol, fullsymbol):
"""Suggests completion for the end of a type chain.""" |
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
if target is None:
return {}
result = {}
#We might know what kind of symbol to limit the completion by depending on whether
#it was preceded by a "call " for example. Check the context's el_call
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _complete_sig(self, symbol, attribute):
"""Suggests completion for calling a function or subroutine.""" |
#Return a list of valid parameters for the function being called
fncall = self.context.el_name
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables")
if iexec is None:
#Try the interfaces as a possible executable to complete.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _complete_word(self, symbol, attribute):
"""Suggests context completions based exclusively on the word preceding the cursor.""" |
#The cursor is after a %(,\s and the user is looking for a list
#of possibilities that is a bit smarter that regular AC.
if self.context.el_call in ["sub", "fun", "assign", "arith"]:
if symbol == "":
#The only possibilities are local vars, global vars or functions
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _complete_values(self, symbol = ""):
"""Compiles a list of possible symbols that can hold a value in place. These consist of local vars, global vars, and fun... |
result = {}
#Also add the subroutines from the module and its dependencies.
moddict = self._generic_filter_execs(self.context.module)
self._cond_update(result, moddict, symbol)
self._cond_update(result, self.context.module.interfaces, symbol)
for depend in self.context.m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cond_update(self, first, second, symbol, maxadd = -1):
"""Overwrites the keys and values in the first dictionary with those of the second as long as the sym... |
if symbol != "":
added = 0
for key in second:
if self._symbol_in(symbol, key) and (maxadd == -1 or added <= maxadd):
first[key] = second[key]
added += 1
else:
first.update(second) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_attribute(self):
"""Gets the appropriate module attribute name for a collection corresponding to the context's element type.""" |
attributes = ['dependencies', 'publics', 'members',
'types', 'executables']
#Find the correct attribute based on the type of the context
if self.context.el_type in [Function, Subroutine]:
attribute = attributes[4]
elif self.context.el_type == Custo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, parser, xml):
"""Parses the rawtext to extract contents and references.""" |
#We can only process references if the XML tag has inner-XML
if xml.text is not None:
matches = parser.RE_REFS.finditer(xml.text)
if matches:
for match in matches:
#Handle "special" references to this.name and param.name here.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exhandler(function, parser):
"""If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function... |
args = vars(bparser.parse_known_args()[0])
if args["examples"]:
function()
exit(0)
if args["verbose"]:
from msg import set_verbosity
set_verbosity(args["verbose"])
args.update(vars(parser.parse_known_args()[0]))
return args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _common_parser():
"""Returns a parser with common command-line options for all the scripts in the fortpy suite. """ |
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-examples", action="store_true",
help="See detailed help and examples for this script.")
parser.add_argument("-verbose", action="store_true",
help="See verbose output as... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getHeaders(self, updateParams=None):
""" create headers list for flask wrapper """ |
if not updateParams:
updateParams = {}
policies = self.defaultPolicies
if len(updateParams) > 0:
for k,v in updateParams.items():
k = k.replace('-','_')
c = globals()[k](v)
try:
policies[k] = c.update_policy(self.defaultPolicies[k])
except Exception, e:
raise
return [globals()[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def policyChange(self, updateParams, func):
""" update defaultPolicy dict """ |
for k,v in updateParams.items():
k = k.replace('-','_')
c = globals()[k](v)
try:
self.defaultPolicies[k] = getattr(c,func)(self.defaultPolicies[k])
except Exception, e:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrapper(self, updateParams=None):
""" create wrapper for flask app route """ |
def decorator(f):
_headers = self._getHeaders(updateParams)
""" flask decorator to include headers """
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
self._setRespHeader(resp, _headers)
resp.has_secure_headers = True
return resp
return decor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_module(self, path, changed_time, parser=None):
"""Attempts to load the specified module from a serialized, cached version. If that fails, the method ret... |
if settings.use_filesystem_cache == False:
return None
try:
pickle_changed_time = self._index[path]
except KeyError:
return None
if (changed_time is not None and
pickle_changed_time < changed_time):
# the pickle file ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_module(self, path, module, change_time=None):
"""Saves the specified module and its contents to the file system so that it doesn't have to be parsed aga... |
#First, get a list of the module paths that have already been
#pickled. We will add to that list of pickling this module.
if settings.use_filesystem_cache == False:
return
self.__index = None
try:
files = self._index
except KeyError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _index(self):
"""Keys a list of file paths that have been pickled in this directory. The index is stored in a json file in the same directory as the pickled ... |
if self.__index is None:
try:
with open(self._get_path('index.json')) as f:
data = json.load(f)
except (IOError, ValueError):
self.__index = {}
else:
# 0 means version is not defined (= always delete cache):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cache_directory(self):
"""Returns the full path to the cache directory as specified in settings. """ |
if settings.unit_testing_mode or settings.use_test_cache:
return os.path.join(settings.cache_directory.replace("Fortpy", "Fortpy_Testing"), self.py_tag)
else:
return os.path.join(settings.cache_directory, self.py_tag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_lib_and_tag_name(tag):
""" Takes a tag string and returns the tag library and tag name. For example, "app_tags.tag_name" is returned as "app_tags", "tag_... |
if '.' not in tag:
raise ValueError('Tag string must be in the format "tag_lib.tag_name"')
lib = tag.rpartition('.')[0]
tag_name = tag.rpartition('.')[-1]
return lib, tag_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tag_html(tag_id):
""" Returns the Django HTML to load the tag library and render the tag. Args: tag_id (str):
The tag id for the to return the HTML for.... |
tag_data = get_lazy_tag_data(tag_id)
tag = tag_data['tag']
args = tag_data['args']
kwargs = tag_data['kwargs']
lib, tag_name = get_lib_and_tag_name(tag)
args_str = ''
if args:
for arg in args:
if isinstance(arg, six.string_types):
args_str += "'{0}' ".fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expand_autotag(atag, container):
"""Expands the contents of the specified auto tag within its parent container. """ |
if atag.tag != "auto":
return
if "names" in atag.attrib:
i = -1
for name in re.split("[\s,]+", atag.attrib["names"]):
if name[0] == '^':
name = name[1::]
insert = True
i += 1
else:
insert = False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_regex(self):
"""Sets up the patterns and regex objects for parsing the docstrings.""" |
#Regex for grabbing out valid XML tags that represent known docstrings that we can work with.
self.keywords = [ "summary", "usage", "errors", "member", "group", "local",
"comments", "parameter" ]
#Regex for extracting the contents of docstrings minus the !! and any le... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_docs(self, string, container = None):
"""Parses the docstrings from the specified string that is the contents of container. Returns a dictionary with k... |
from fortpy.utility import XML
result = {}
if container is None:
#We are working with the code file at the module level. Extract the module
#docstrings and XML and return the dictionary with module names as keys.
for module in self.RE_MODDOCS.finditer(string)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_docgroup(self, group, code_el, add=True):
"""Explodes the group members into a list; adds the group to the specified code element and updates the gr... |
if group.name in code_el.groups and add:
msg.warn("duplicate group names in code element {}".format(code_el.name))
else:
code_el.groups[group.name] = group
kids = self.to_doc(list(group.xml), group.decorates)
for child in kids:
child.group = group.na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_execdocs(self, docs, anexec, key, add=True):
"""Associates parameter documentation with parameters for the executable and any remaining docs with the... |
#Paramdocs has a list of docstrings for summary, usage, parameters, etc.
#check which belong to parameters and associate them, otherwise append
#them to the executable.
for doc in docs:
if doc.doctype == "parameter":
if doc.pointsto is not None and doc.points... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_memberdocs(self, docs, codeEl, add=True):
"""Associates member type DocElements with their corresponding members in the specified code element. The e... |
#Now we need to associate the members with their docstrings
#Some of the members may be buried inside a group tag and
#need to be handled separately.
remainingdocs = []
expandeddocs = []
#Process any groups that are in the doc list.
for doc in docs:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_docstrings(self, doc, members, add=True):
"""Adds the docstrings from the list of DocElements to their respective members. Returns true if the doc e... |
if ((doc.doctype == "member" or doc.doctype == "local") and
doc.pointsto is not None and
doc.pointsto in members):
if add:
members[doc.pointsto].docstring.append(doc)
else:
members[doc.pointsto].overwrite_docs(doc)
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_doc(self, xmllist, decorates):
"""Converts the specified xml list to a list of docstring elements.""" |
result = []
for xitem in xmllist:
if xitem.tag != "group":
#The docstring allows a single string to point to multiple
#names in a comma-separated list in the names attribute.
if "name" in list(xitem.keys()):
names = re.spli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_docblocks(self, string, container):
"""Parses all the docstrings out of the specified string. Returns a dictionary of docstrings with the key as paren... |
#The easiest way to do this is to look at one line at a time and see if it is a docstring
#When we find a group of docstrings that suddenly ends, the next item is the code element
#that they were decorating (which may or may not be pertinent).
from fortpy.utility import XML
curr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_docline(self, line, container):
"""Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so... |
match = self.RE_DECOR.match(line)
if match is not None:
return "{}.{}".format(container.name, match.group("name"))
else:
return container.name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsexml(self, xmlstring, modules, source=None):
"""Parses the docstrings out of the specified xml file. :arg source: the path to the file from which the XML... |
result = {}
from fortpy.utility import XML_fromstring
xmlroot = XML_fromstring(xmlstring, source)
if xmlroot.tag == "fortpy" and "mode" in xmlroot.attrib and \
xmlroot.attrib["mode"] == "docstring":
#First, cycle through the kids to find the <global> tag (if any
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _xml_update_modules(self, xmldict, modules):
"""Updates the docstrings in the specified modules by looking for docstrings in the xmldict.""" |
for kdecor in xmldict:
modname, memname = kdecor.split(".")
if modname in modules:
module = modules[modname]
#We only need to check the members, types and executables
memname = memname.lower()
if memname in module.members:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rt_update_module(self, xmldict, module):
"""Updates the members, executables and types in the specified module to have the latest docstring information from ... |
#This keeps track of how many character were added/removed by
#updating the docstrings in xmldict.
delta = 0
for kdecor in xmldict:
if "." in kdecor:
modname, memname = kdecor.split(".")
else:
modname, memname = module.name, None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rt_update_docindices(self, element, docstart, docend):
"""Updates the docstart, docend, start and end attributes for the specified element using the new lim... |
#see how many characters have to be added/removed from the end
#of the current doc limits.
delta = element.docend - docend
element.docstart = docstart
element.docend = docend
element.start += delta
element.end += delta
return delta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paint(self, tbl):
""" Paint the table on terminal Currently only print out basic string format """ |
if not isinstance(tbl, Table):
logging.error("unable to paint table: invalid object")
return False
self.term.stream.write(self.term.clear)
self.term.stream.write(str(tbl))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_caches(delete_all=False):
"""Fortpy caches many things, that should be completed after each completion finishes. :param delete_all: Deletes also the ca... |
global _time_caches
if delete_all:
_time_caches = []
_parser = { "default": CodeParser() }
else:
# normally just kill the expired entries, not all
for tc in _time_caches:
# check time_cache for expired entries
for key, (t, value) in list(tc.items()):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_call_signatures(source, user_pos, stmt):
"""This function calculates the cache key.""" |
index = user_pos[0] - 1
lines = source.splitlines() or ['']
if source and source[-1] == '\n':
lines.append('')
before_cursor = lines[index][:user_pos[1]]
other_lines = lines[stmt.start_pos[0]:index]
whole = '\n'.join(other_lines + [before_cursor])
before_bracket = re.match(r'.*\(',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_new_node(self, distance, angle):
"""Make a new node from an existing one. This method creates a new node with a distance and angle given. The position o... |
return Node((cos(-angle)*distance+self.pos[0],
sin(-angle)*distance+self.pos[1])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_angle(self, node):
"""Get the angle beetween 2 nodes relative to the horizont. Args: node (object):
The other node. Returns: rad: The angle """ |
return atan2(self.pos[0]-node.pos[0], self.pos[1]-node.pos[1]) - pi / 2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_distance(self, node):
"""Get the distance beetween 2 nodes Args: node (object):
The other node. """ |
delta = (node.pos[0]-self.pos[0], node.pos[1]-self.pos[1])
return sqrt(delta[0]**2+delta[1]**2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move(self, delta):
"""Move the node. Args: delta (tupel):
A tupel, holding the adjustment of the position. """ |
self.pos = (self.pos[0]+delta[0], self.pos[1]+delta[1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exec_check_pointers(executable):
"""Checks the specified executable for the pointer condition that not all members of the derived type have had their values... |
oparams = []
pmembers = {}
xassigns = map(lambda x: x.lower().strip(), executable.external_assignments())
def add_offense(pname, member):
"""Adds the specified member as an offender under the specified parameter."""
if pname not in oparams:
oparams.append(pname)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _type_check_pointers(utype):
"""Checks the user-derived type for non-nullified pointer array declarations in its base definition. Returns (list of offending ... |
result = []
for mname, member in utype.members.items():
if ("pointer" in member.modifiers and member.D > 0 and
(member.default is None or "null" not in member.default)):
result.append(member)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status_schedule(token):
""" Returns the json string from the Hydrawise server after calling statusschedule.php. :param token: The users API token. :type toke... |
url = 'https://app.hydrawise.com/api/v1/statusschedule.php'
payload = {
'api_key': token,
'hours': 168}
get_response = requests.get(url, params=payload, timeout=REQUESTS_TIMEOUT)
if get_response.status_code == 200 and \
'error_msg' not in get_response.json():
return g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_zones(token, action, relay=None, time=None):
""" Controls the zone relays to turn sprinklers on and off. :param token: The users API token. :type token: ... |
# Actions must be one from this list.
action_list = [
'run', # Run a zone for an amount of time.
'runall', # Run all zones for an amount of time.
'stop', # Stop a zone.
'stopall', # stop all zones.
'suspend', # Suspend a zone for an amount of time.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_status(modeladmin, request, queryset, status):
"""The workhorse function for the admin action functions that follow.""" |
# We loop over the objects here rather than use queryset.update() for
# two reasons:
#
# 1. No one should ever be updating zillions of Topics or Questions, so
# performance is not an issue.
# 2. To be tidy, we want to log what the user has done.
#
for obj in queryset:
obj.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exec_callers(xinst, result):
"""Adds the dependency calls from the specified executable instance to the results dictionary. """ |
for depkey, depval in xinst.dependencies.items():
if depval.target is not None:
if depval.target.name in result:
if xinst not in result[depval.target.name]:
result[depval.target.name].append(xinst)
else:
result[depval.target.name] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _module_callers(parser, modname, result):
"""Adds any calls to executables contained in the specified module. """ |
if modname in result:
#We have already processed this module.
return
module = parser.get(modname)
mresult = {}
if module is not None:
for xname, xinst in module.executables():
_exec_callers(xinst, mresult)
result[modname] = mresult
for d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call_fan(branch, calls, executable):
"""Appends a list of callees to the branch for each parent in the call list that calls this executable. """ |
#Since we don't keep track of the specific logic in the executables
#it is possible that we could get a infinite recursion of executables
#that keep calling each other.
if executable in branch:
return
branch.append(executable)
if executable.name in calls:
for caller in call... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def topic_detail(request, slug):
""" A detail view of a Topic Templates: :template:`faq/topic_detail.html` Context: topic An :model:`faq.Topic` object. question_... |
extra_context = {
'question_list': Question.objects.published().filter(topic__slug=slug),
}
return object_detail(request, queryset=Topic.objects.published(),
extra_context=extra_context, template_object_name='topic', slug=slug) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(self):
"""Returns the full docstring information for the element suggested as a completion.""" |
result = ""
if isinstance(self._element, ValueElement):
if self._element.kind is not None:
result = "{}({}) | {}".format(self._element.dtype, self._element.kind,
self._element.summary)
else:
result = "{} |... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def params(self):
""" Raises an ``AttributeError``if the definition is not callable. Otherwise returns a list of `ValueElement` that represents the params. """ |
if self.context.el_type in [Function, Subroutine]:
return self.evaluator.element.parameters |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _type_description(self):
"""Gets the completion description for a TypeExecutable.""" |
#This is a little tricker because the docstring is housed
#inside of the module that contains the actual executable.
#These TypeExecutables are just pointers.
iexec = self._element.target
if iexec is not None:
result = "method() | " + iexec.summary
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overwrite_docs(self, doc):
"""Adds the specified DocElement to the docstring list. However, if an element with the same xml tag and pointsto value already ex... |
for i in range(len(self.docstring)):
if (self.docstring[i].doctype == doc.doctype and
self.docstring[i].pointsto == doc.pointsto):
del self.docstring[i]
break
self.docstring.append(doc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpickle_docs(self):
"""Sets the pointers for the docstrings that have groups.""" |
for doc in self.docstring:
if (doc.parent_name is not None and
doc.parent_name in self.groups):
doc.group = self.groups[doc.parent_name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absstart(self):
"""Returns the absolute start of the element by including docstrings outside of the element definition if applicable.""" |
if hasattr(self, "docstart") and self.docstart > 0:
return self.docstart
else:
return self.start |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module(self):
"""Returns the module that this code element belongs to.""" |
if self._module is None:
root = self
while self._module is None and root is not None:
if isinstance(root, Module):
self._module = root
else:
root = root.parent
return self._module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary(self):
"""Returns the docstring summary for the code element if it exists.""" |
if self._summary is None:
self._summary = "No summary for element."
for doc in self.docstring:
if doc.doctype == "summary":
self._summary = doc.contents
break
#If a parameter, member or local tag has dimensions or othe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_name(self):
"""Returns the full name of this element by visiting every non-None parent in its ancestor chain.""" |
if self._full_name is None:
ancestors = [ self.name ]
current = self.parent
while current is not None and type(current).__name__ != "CodeParser":
ancestors.append(current.name)
current = current.parent
self._full_name = ".".join(r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_children(self, doctype, limiters=[]):
"""Finds all grand-children of this element's docstrings that match the specified doctype. If 'limiters' is specifi... |
result = []
for doc in self.docstring:
if len(limiters) == 0 or doc.doctype in limiters:
result.extend(doc.children(doctype))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def warn(self, collection):
"""Checks this code element for documentation related problems.""" |
if not self.has_docstring():
collection.append("WARNING: no docstring on code element {}".format(self.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matched(self, other):
"""Returns True if the two ValueElement instances differ only by name, default value or some other inconsequential modifier. """ |
mods = ["allocatable", "pointer"]
return (self.kind.lower() == other.kind.lower() and
self.dtype.lower() == other.dtype.lower() and
self.D == other.D and
all([m in other.modifiers for m in self.modifiers if m in mods])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strtype(self):
"""Returns a string representing the type and kind of this value element.""" |
if self.kind is not None:
return "{}({})".format(self.dtype, self.kind)
else:
return self.dtype |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_ctypes_name(self, index=None):
"""Returns a formatted name for the ctypes Fortran wrapper module. :arg index: the index of the array to return a name fo... |
if index is None:
if ("allocatable" not in self.modifiers and "pointer" not in self.modifiers
and self.dtype != "logical"):
#The fortan logical has type 4 by default, whereas c_bool only has 1
return self.name
else:
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ctypes_parameter(self):
"""Returns the parameter list for this ValueElement adjusted for interoperability with the ctypes module. """ |
if self._ctypes_parameter is None:
#Essentially, we just need to check if we are an array that doesn't have explicitly
#defined bounds. Assumed-shape arrays have to be 'pointer' or 'allocatable'. However,
#the deffered/assumed shape arrays always use ':' as the array dimensi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def definition(self, suffix = "", local=False, ctype=None, optionals=True, customdim=None, modifiers=None):
"""Returns the fortran code string that would define ... |
kind = "({})".format(self.kind) if self.kind is not None else ""
cleanmods = [m for m in self.modifiers if m != "" and m != " "
and not (local and ("intent" in m or m == "optional"))
and not (not optionals and m == "optional")]
if modifiers is not No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def argtypes(self):
"""Returns the ctypes argtypes for use with the method.argtypes assignment for an executable loaded from a shared library. """ |
if self.dimension is not None:
result = []
if "in" in self.direction:
#The only complication here is that the 'known' dimensionality could actually
#be a function like "size" that needs information about other variables.
#If we choose to i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ctype(self):
"""Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. """ |
if self.dtype == "logical":
return "C_BOOL"
elif self.dtype == "complex":
#We don't actually know what the precision of the complex numbers is because
#it is defined by the developer when they construct the number with CMPLX()
#We just return double to be... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def customtype(self):
"""If this variable is a user-derivedy type, return the CustomType instance that is its kind. """ |
result = None
if self.is_custom:
#Look for the module that declares this variable's kind in its public list.
self.dependency()
if self._kind_module is not None:
if self.kind.lower() in self._kind_module.types:
result = self._kind_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def external_name(self):
"""Returns the modulename.executable string that uniquely identifies the executable that this dependency points to.""" |
target = self.target
if target is not None:
return "{}.{}".format(target.name.lower(), self.name)
else:
return "{}.{}".format(self.module.name.lower(), self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target(self):
"""Returns the executable code element that this dependency points to if it can be found. """ |
if self._target is None:
if '%' in self.name:
parts = self.name.split('%')
base = self.module.parent.type_search(parts[0], self.name, self.module)
if base is not None:
self._target = base.target
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self, argslist):
"""Cleans the argslist.""" |
result = []
for arg in argslist:
if type(arg) == type([]):
if len(result) > 0:
result[-1] = result[-1] + "(*{})".format(len(self.clean(arg)))
elif "/" not in arg[0]:
msg.warn("argument to function call unrecognized. {}"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_section(self, charindex):
"""Returns a value indicating whether the specified character index is owned by the current object.""" |
#All objects instances of decorable also inherit from CodeElement,
#so we should have no problem accessing the start and end attributes.
result = None
if hasattr(self, "start") and hasattr(self, "end"):
#The 8 seems arbitrary, but it is the length of type::b\n for a
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_dependencies(self):
"""Returns a list of modules that this executable needs in order to run properly. This includes special kind declarations for prec... |
#It is understood that this executable's module is obviously required. Just
#add any additional modules from the parameters.
result = [p.dependency() for p in self.ordered_parameters]
result.extend([v.dependency() for k, v in list(self.members.items())])
for ekey, anexec in list... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unpickle_collection(self, collection):
"""Unpickles all members of the specified dictionary.""" |
for mkey in collection:
if isinstance(collection[mkey], list):
for item in collection[mkey]:
item.unpickle(self)
else:
collection[mkey].unpickle(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rt_update(self, statement, linenum, mode, xparser):
"""Uses the specified line parser to parse the given line. :arg statement: a string of lines that are par... |
section = self.find_section(self.module.charindex(linenum, 1))
if section == "body":
xparser.parse_line(statement, self, mode)
elif section == "signature":
if mode == "insert":
xparser.parse_signature(statement, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_name(self, name):
"""Changes the name of this executable and the reference to it in the parent module.""" |
if name != self.name:
self.parent.executables[name] = self
del self.parent.executables[self.name]
self.name = name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_type_target(self):
"""Returns the CustomType instance if this executable is an embedded procedure in a custom type declaration; else False. """ |
if self._is_type_target is None:
#All we need to do is search through the custom types in the parent
#module and see if any of their executables points to this method.
self._is_type_target = False
for tkey in self.module.types:
custype = self.modu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_assignments_in(self, filterlist, symbol = ""):
"""Returns a list of code elements whose names are in the specified object. :arg filterlist: the list of ... |
if symbol != "":
lsymbol = symbol
for assign in self._assignments:
target = assign.split("%")[0].lower()
if target == lsymbol:
return True
else:
result = []
for assign in self._assignments:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parameter(self, index):
"""Returns the ValueElement corresponding to the parameter at the specified index.""" |
result = None
if index < len(self.paramorder):
key = self.paramorder[index]
if key in self._parameters:
result = self._parameters[key]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_parameter(self, parameter):
"""Adds the specified parameter value to the list.""" |
if parameter.name.lower() not in self.paramorder:
self.paramorder.append(parameter.name.lower())
self._parameters[parameter.name.lower()] = parameter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_parameter(self, parameter_name):
"""Removes the specified parameter from the list.""" |
if parameter_name in self.paramorder:
index = self.paramorder.index(parameter_name)
del self.paramorder[index]
if parameter_name in self._parameters:
del self._parameters[parameter_name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameters_as_string(self):
"""Returns a comma-separated list of the parameters in the executable definition.""" |
params = ", ".join([ p.name for p in self.ordered_parameters ])
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_dependency(self, value):
"""Adds the specified executable dependency to the list for this executable.""" |
if value.name in self.dependencies:
self.dependencies[value.name.lower()].append(value)
else:
self.dependencies[value.name.lower()] = [ value ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, name, modifiers, dtype, kind):
"""Updates the attributes for the function instance, handles name changes in the parent module as well.""" |
self.update_name(name)
self.modifiers = modifiers
self.dtype = dtype
self.kind = kind
self.update_dtype() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def returns(self):
"""Gets a string showing the return type and modifiers for the function in a nice display format.""" |
kind = "({}) ".format(self.kind) if self.kind is not None else ""
mods = ", ".join(self.modifiers) + " "
dtype = self.dtype if self.dtype is not None else ""
return "{}{}{}".format(dtype, kind, mods) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature(self):
"""Returns the signature definition for the subroutine.""" |
mods = ", ".join(self.modifiers)
return "{} SUBROUTINE {}({})".format(mods, self.name,
self.parameters_as_string()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, name, modifiers):
"""Updates the attributes for the subroutine instance, handles name changes in the parent module as well.""" |
self.update_name(name)
self.modifiers = modifiers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target(self):
"""Returns the code element that is the actual executable that this type executable points to.""" |
if self.pointsto is not None:
#It is in the format of module.executable.
xinst = self.module.parent.get_executable(self.pointsto.lower())
return xinst
else:
#The executable it points to is the same as its name.
fullname = "{}.{}".format(self.m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fixedvar(self):
"""Returns the name of a member in this type that is non-custom so that it would terminate the auto-class variable context chain. """ |
possible = [m for m in self.members.values() if not m.is_custom]
#If any of the possible variables is not allocatable or pointer, it will always
#have a value and we can just use that.
sufficient = [m for m in possible if "allocatable" not in m.modifiers
and "point... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recursive(self):
"""When True, this CustomType has at least one member that is of the same type as itself. """ |
for m in self.members.values():
if m.kind is not None and m.kind.lower() == self.name.lower():
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_name(self, name):
"""Updates the name of the custom type in this instance and its parent reference.""" |
if name != self.name:
self.parent.types[name] = self
del self.parent.types[self.name]
self.name = name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parameter(self, index):
"""Gets the list of parameters at the specified index in the calling argument list for each of the module procedures in the inter... |
result = []
for target in self.targets:
if target is not None:
result.append(target.get_parameter(index))
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.