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 load_clubs(self):
"""Fetches the MAL character clubs page and sets the current character's clubs attributes. :rtype: :class:`.Character` :return: Current cha... |
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(character)))
return 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 generate(self, minlen, maxlen):
""" Generates words of different length without storing them into memory, enforced by itertools.product """ |
if minlen < 1 or maxlen < minlen:
raise ValueError()
for cur in range(minlen, maxlen + 1):
# string product generator
str_generator = product(self.charset, repeat=cur)
for each in str_generator:
# yield the produced word
y... |
<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_username_from_user_id(session, user_id):
"""Look up a MAL username's user ID. :type session: :class:`myanimelist.session.Session` :param session: A vali... |
comments_page = session.session.get(u'http://myanimelist.net/comments.php?' + urllib.urlencode({'id': int(user_id)})).text
comments_page = bs4.BeautifulSoup(comments_page)
username_elt = comments_page.find('h1')
if "'s Comments" not in username_elt.text:
raise InvalidUserError(user_id, message="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 parse_reviews(self, reviews_page):
"""Parses the DOM and returns user reviews attributes. :type reviews_page: :class:`bs4.BeautifulSoup` :param reviews_page:... |
user_info = self.parse_sidebar(reviews_page)
second_col = reviews_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'reviews'] = {}
reviews = second_col.find_all(u'div', {u'class': u'borderDark'}, recursive=False)
if rev... |
<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_recommendations(self, recommendations_page):
"""Parses the DOM and returns user recommendations attributes. :type recommendations_page: :class:`bs4.Bea... |
user_info = self.parse_sidebar(recommendations_page)
second_col = recommendations_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
recommendations = second_col.find_all(u"div", {u"class": u"spaceit borderClass"})
if recommendations:
... |
<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_clubs(self, clubs_page):
"""Parses the DOM and returns user clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL user ... |
user_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'clubs'] = []
club_list = second_col.find(u'ol')
if club_list:
clubs = club_list.find_all(u'li')
... |
<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_friends(self, friends_page):
"""Parses the DOM and returns user friends attributes. :type friends_page: :class:`bs4.BeautifulSoup` :param friends_page:... |
user_info = self.parse_sidebar(friends_page)
second_col = friends_page.find(u'div', {u'id': u'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
user_info[u'friends'] = {}
friends = second_col.find_all(u'div', {u'class': u'friendHolder'})
if friends:
... |
<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(self):
"""Fetches the MAL user page and sets the current user's attributes. :rtype: :class:`.User` :return: Current user object. """ |
user_profile = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username)).text
self.set(self.parse(utilities.get_clean_dom(user_profile)))
return 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 load_reviews(self):
"""Fetches the MAL user reviews page and sets the current user's reviews attributes. :rtype: :class:`.User` :return: Current user object.... |
page = 0
# collect all reviews over all pages.
review_collection = []
while True:
user_reviews = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/reviews&' + urllib.urlencode({u'p': page})).text
parse_result = self.parse_reviews(utilities... |
<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_recommendations(self):
"""Fetches the MAL user recommendations page and sets the current user's recommendations attributes. :rtype: :class:`.User` :retu... |
user_recommendations = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/recommendations').text
self.set(self.parse_recommendations(utilities.get_clean_dom(user_recommendations)))
return 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 load_clubs(self):
"""Fetches the MAL user clubs page and sets the current user's clubs attributes. :rtype: :class:`.User` :return: Current user object. """ |
user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text
self.set(self.parse_clubs(utilities.get_clean_dom(user_clubs)))
return 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 load_friends(self):
"""Fetches the MAL user friends page and sets the current user's friends attributes. :rtype: :class:`.User` :return: Current user object.... |
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text
self.set(self.parse_friends(utilities.get_clean_dom(user_friends)))
return 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 arb(text, cols, split):
"""Prints a line of text in arbitrary colors specified by the numeric values contained in msg.cenum dictionary. """ |
stext = text if text[-1] != split else text[0:-1]
words = stext.split(split)
for i, word in enumerate(words):
col = icols[cols[i]]
printer(word, col, end="")
if i < len(words)-1:
printer(split, end="")
else:
printer(split) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def will_print(level=1):
"""Returns True if the current global status of messaging would print a message using any of the printing functions in this module. """ |
if level == 1:
#We only affect printability using the quiet setting.
return quiet is None or quiet == False
else:
return ((isinstance(verbosity, int) and level <= verbosity) or
(isinstance(verbosity, bool) and verbosity == 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 warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to the message, so that can be left off. """ |
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def err(msg, level=-1, prefix=True):
"""Prints the specified message as an error; prepends "ERROR" to the message, so that can be left off. """ |
if will_print(level) or verbosity is None:
printer(("ERROR: " if prefix else "") + msg, "red") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getenvar(self, envar):
from os import getenv """Retrieves the value of an environment variable if it exists.""" |
if getenv(envar) is not None:
self._vardict[envar] = getenv(envar) |
<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_isense(self, tag):
"""Loads isense configuration as a dict of dicts into vardict.""" |
isense = {}
for child in tag:
if child.tag in isense:
isense[child.tag].update(child.attrib)
else:
isense[child.tag] = child.attrib
self._vardict["isense"] = isense |
<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_ssh(self, tag):
"""Loads the SSH configuration into the vardict.""" |
for child in tag:
if child.tag == "server":
self._vardict["server"] = child.attrib
elif child.tag == "codes":
self._load_codes(child, True)
elif child.tag == "mappings":
self._load_mapping(child, True)
elif child.ta... |
<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_includes(self, tag, ssh=False):
"""Extracts all additional libraries that should be included when linking the unit testing executables. """ |
import re
includes = []
for child in tag:
if child.tag == "include" and "path" in child.attrib:
incl = { "path": child.attrib["path"] }
if "modules" in child.attrib:
incl["modules"] = re.split(",\s*", child.attrib["modules"].lower(... |
<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_codes(self, tag, ssh=False):
"""Extracts all the paths to additional code directories to be considered. :arg tag: the ET tag for the <codes> element.""... |
codes = []
for code in tag:
if code.tag == "trunk":
codes.append(code.attrib["value"])
if ssh == False:
self._vardict["codes"] = codes
else:
self._vardict["ssh.codes"] = codes |
<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_mapping(self, tag, ssh=False):
"""Extracts all the alternate module name mappings to be considered. :arg tag: the ET tag for the <mappings> element.""" |
mappings = {}
for mapping in tag:
if mapping.tag == "map":
mappings[mapping.attrib["module"]] = mapping.attrib["file"]
if ssh == False:
self._vardict["mappings"] = mappings
else:
self._vardict["ssh.mappings"] = mappings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copytree(src, dst):
"""Recursively copies the source directory to the destination only if the files are newer or modified by using rsync. """ |
from os import path, waitpid
from subprocess import Popen, PIPE
#Append any trailing / that we need to get rsync to work correctly.
source = path.join(src, "")
desti = path.join(dst, "")
if not path.isdir(desti):
from os import mkdir
mkdir(desti)
prsync = Popen("rsync ... |
<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_fortpy_templates_dir():
"""Gets the templates directory from the fortpy package.""" |
import fortpy
from os import path
fortdir = path.dirname(fortpy.__file__)
return path.join(fortdir, "templates") |
<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_fortpy_templates(obj, fortpy_templates=None):
"""Sets the directory path for the fortpy templates. If no directory is specified, use the default one that... |
#If they didn't specify a custom templates directory, use the default
#one that shipped with the package.
from os import path
if fortpy_templates is not None:
obj.fortpy_templates = path.abspath(path.expanduser(fortpy_templates))
else:
from fortpy.utility import get_fortpy_templates... |
<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_dir_relpath(base, relpath):
"""Returns the absolute path to the 'relpath' taken relative to the base directory. :arg base: the base directory to take the... |
from os import path
xbase = path.abspath(path.expanduser(base))
if not path.isdir(xbase):
return path.join(xbase, relpath)
if relpath[0:2] == "./":
return path.join(xbase, relpath[2::])
else:
from os import chdir, getcwd
cd = getcwd()
chdir(xbase)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_line(line, limit=None, chars=80):
"""Wraps the specified line of text on whitespace to make sure that none of the lines' lengths exceeds 'chars' charact... |
result = []
builder = []
length = 0
if limit is not None:
sline = line[0:limit]
else:
sline = line
for word in sline.split():
if length <= chars:
builder.append(word)
length += len(word) + 1
else:
result.append(' '.joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def x_parse_error(err, content, source):
"""Explains the specified ParseError instance to show the user where the error happened in their XML. """ |
lineno, column = err.position
if "<doc>" in content:
#Adjust the position since we are taking the <doc> part out of the tags
#since we may have put that in ourselves.
column -= 5
start = lineno - (1 if lineno == 1 else 2)
lines = []
tcontent = content.replace("<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 XML(content, source=None):
"""Parses the XML text using the ET.XML function, but handling the ParseError in a user-friendly way. """ |
try:
tree = ET.XML(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree |
<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_fromstring(content, source=None):
"""Parses the XML string into a node tree. If an ParseError exception is raised, the error message is formatted nicely ... |
try:
tree = ET.fromstring(content)
except ET.ParseError as err:
x_parse_error(err, content, source)
return tree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(element):
"""Formats all of the docstrings in the specified element and its children into a user-friendly paragraph format for printing. :arg element:... |
result = []
if type(element).__name__ in ["Subroutine", "Function"]:
_format_executable(result, element)
elif type(element).__name__ == "CustomType":
_format_type(result, element)
elif isinstance(element, ValueElement):
_format_value_element(result, element)
return '\n'.joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_executable(lines, element, spacer=""):
"""Performs formatting specific to a Subroutine or Function code element for relevant docstrings. """ |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
rlines.append("PARAMETERS")
for p in element.ordered_parameters:
_format_value_element(rlines, p)
rlines.append("")
_format_generic(rlines, element, ["summary"])
#Subroutines c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_type(lines, element, spacer=""):
"""Formats a derived type for full documentation output.""" |
rlines = []
rlines.append(element.signature)
_format_summary(rlines, element)
rlines.append("")
_format_generic(rlines, element, ["summary"])
if len(element.executables) > 0:
rlines.append("\nEMBEDDED PROCEDURES")
for key, value in list(element.executables.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 _format_value_element(lines, element, spacer=""):
"""Formats a member or parameter for full documentation output.""" |
lines.append(spacer + element.definition())
_format_summary(lines, element)
_format_generic(lines, element, ["summary"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_summary(lines, element, spacer=" "):
"""Adds the element's summary tag to the lines if it exists.""" |
summary = spacer + element.summary
if element.summary == "":
summary = spacer + "No description given in XML documentation for this element."
lines.append(summary) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_generic(lines, element, printed, spacer=""):
"""Generically formats all remaining docstrings and custom XML tags that don't appear in the list of alr... |
for doc in element.docstring:
if doc.doctype.lower() not in printed:
lines.append(spacer + doc.__str__()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_ex_argtype(executable):
"""Returns the code to create the argtype to assign to the methods argtypes attribute. """ |
result = []
for p in executable.ordered_parameters:
atypes = p.argtypes
if atypes is not None:
result.extend(p.argtypes)
else:
print(("No argtypes for: {}".format(p.definition())))
if type(executable).__name__ == "Function":
result.extend(executable.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_ctype(parameter):
"""Returns the ctypes type name for the specified fortran parameter. """ |
ctype = parameter.ctype
if ctype is None:
raise ValueError("Can't bind ctypes py_parameter for parameter"
" {}".format(parameter.definition()))
return ctype.lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_code_clean(lines, tab, executable):
"""Appends all the code lines needed to create the result class instance and populate its keys with all output variab... |
count = 0
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
value = _py_clean(p, tab)
if value is not None:
count += 1
lines.append(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 _py_ftype(parameter, tab):
"""Returns the code to declare an Ftype object that handles memory deallocation for Fortran return arrays that were allocated by t... |
splice = ', '.join(["{0}_{1:d}".format(parameter.lname, i)
for i in range(parameter.D)])
return "{2}{0}_ft = Ftype({0}_o, [{1}], libpath)".format(parameter.lname, splice, tab) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_clean(parameter, tab):
"""Returns the code line to clean the output value of the specified parameter. """ |
if "out" in parameter.direction:
if parameter.D > 0:
if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
if parameter.D == 1:
clarray = "as_array({0}_o, (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_code_variables(lines, executable, lparams, tab):
"""Adds the variable code lines for all the parameters in the executable. :arg lparams: a list of the lo... |
allparams = executable.ordered_parameters
if type(executable).__name__ == "Function":
allparams = allparams + [executable]
for p in allparams:
_py_code_parameter(lines, p, "invar", lparams, tab)
if p.direction == "(out)":
#We need to reverse the order of the indices to ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_code_parameter(lines, parameter, position, lparams, tab):
"""Appends the code to produce the parameter at the specified position in the executable. :arg ... |
mdict = {
"invar": _py_invar,
"outvar": _py_outvar,
"indices": _py_indices
}
line = mdict[position](parameter, lparams, tab)
if line is not None:
value, blank = line
lines.append(tab + value)
if blank:
lines.append("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_invar(parameter, lparams, tab):
"""Returns the code to create the local input parameter that is coerced to have the correct type for ctypes interaction. ... |
if ("in" in parameter.direction and parameter.D > 0):
if parameter.direction == "(inout)" and ":" not in parameter.dimension:
wstr = ", writeable"
else:
wstr = ""
pytype = _py_pytype(parameter)
lparams.append("{}_a".format(parameter.lname))
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 _py_outvar(parameter, lparams, tab):
"""Returns the code to produce a ctypes output variable for interacting with fortran. """ |
if ("out" in parameter.direction and parameter.D > 0 and ":" in parameter.dimension and
("allocatable" in parameter.modifiers or "pointer" in parameter.modifiers)):
lparams.append("byref({}_o)".format(parameter.lname))
blank = True if parameter.direction == "(inout)" else False
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _py_indices(parameter, lparams, tab):
"""Returns the code to produce py ctypes for the indices of the specified parameter that has D > 0. """ |
if parameter.D > 0 and ":" in parameter.dimension:
if "in" in parameter.direction:
indexstr = "{0}_{1:d} = c_int({0}_a.shape[{1:d}])"
else:
indexstr = "{0}_{1:d} = c_int(0)"
lparams.extend(["byref({}_{})".format(parameter.lname, i) for i in range(parameter.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 _ctypes_code_parameter(lines, parameter, position):
"""Returns the code for the specified parameter being written into a subroutine wrapper. :arg position: o... |
mdict = {
'indices': _ctypes_indices,
'variable': _ctypes_variables,
'out': _ctypes_out,
'regular': _ctypes_regular,
'saved': _ctypes_saved,
'assign': _ctypes_assign,
'clean': _ctypes_clean
}
line = mdict[position](parameter)
if line is not 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 _ctypes_dtype(parameter):
"""Determines the ISO_C data type to use for describing the specified parameter. """ |
ctype = parameter.ctype
if ctype is None:
if parameter.kind is not None:
return "{}({})".format(parameter.dtype, parameter.kind)
else:
return parameter.dtype
else:
return"{}({})".format(parameter.dtype, ctype) |
<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_splice(parameter):
"""Returns a list of variable names that define the size of each dimension. """ |
params = parameter.ctypes_parameter()
if parameter.direction == "(inout)" and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers):
return ', '.join(params[1:-1])
else:
return ', '.join(params[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 _ctypes_indices(parameter):
"""Returns code for parameter variable declarations specifying the size of each dimension in the specified parameter. """ |
if (parameter.dimension is not None and ":" in parameter.dimension):
splice = _ctypes_splice(parameter)
if "out" in parameter.direction:
#Even for pure out variables, the ctypes pointer is passed in and will
#have a value already.
return ("integer, intent(inout) ... |
<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_variables(parameter):
"""Returns the local parameter definition for implementing a Fortran wrapper subroutine for this parameter's parent executable.... |
if parameter.dimension is not None and ":" in parameter.dimension:
#For arrays that provide input (including 'inout'), we pass the output separately
#through a c-pointer. They will always be input arrays. For pure (out) parameters
#we use *only* a c-ptr, but it needs intent (inout) since it... |
<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_out(parameter):
"""Returns a parameter variable declaration for an output variable for the specified parameter. """ |
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
if parameter.direction == "(inout)":
return ("type(C_PTR), 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 _ctypes_saved(parameter):
"""Returns local variable declarations that create allocatable variables that can persist long enough to return their value through... |
if ("out" in parameter.direction and parameter.dimension is not None and
":" in parameter.dimension and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
stype = _ctypes_dtype(parameter)
name = "{}_t({})".format(parameter.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 _ctypes_clean(parameter):
"""Returns the lines of code required to assign the correct values to the integers representing the indices of the output arrays in... |
if ("out" in parameter.direction and parameter.dimension is not None
and ":" in parameter.dimension and ("pointer" in parameter.modifiers or
"allocatable" in parameter.modifiers)):
params = parameter.ctypes_parameter()
result = []
spacer =... |
<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_ex_parameters(executable):
"""Returns a list of the parameters to form the wrapper executable to interact with ctypes. """ |
result = []
for p in executable.ordered_parameters:
result.extend(p.ctypes_parameter())
if type(executable).__name__ == "Function":
result.extend(executable.ctypes_parameter()) #This method inherits from ValueElement.
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 _ctypes_ex_variables(executable):
"""Returns a list of the local variable definitions required to construct the ctypes interop wrapper. """ |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "indices")
_ctypes_code_parameter(result, p, "variable")
_ctypes_code_parameter(result, p, "out")
if type(executable).__name__ == "Function":
#For functions, we still create a subroutine-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 _ctypes_ex_compatvars(executable):
"""Returns a list of code lines for signature matching variables, and pointer saving variables. """ |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "regular")
_ctypes_code_parameter(result, p, "saved")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "regular")
_ctypes_code_parameter(result, execu... |
<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_ex_assign(executable):
"""Return a list of code lines to allocate and assign the local parameter definitions that match those in the signature of the... |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "assign")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "assign")
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 _ctypes_ex_clean(executable):
"""Return a list of code lines to take care of assigning pointers for output variables interacting with ctypes. """ |
result = []
for p in executable.ordered_parameters:
_ctypes_code_parameter(result, p, "clean")
if type(executable).__name__ == "Function":
_ctypes_code_parameter(result, executable, "clean")
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 libname(self):
"""Returns the name of the shared library file compiled for the wrapper subroutines coded in fortran. """ |
if self.library is not None:
return "ftypes.{}.so".format(self.library)
else:
return "{}.so".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 _check_lib(self, remake, compiler, debug, profile):
"""Makes sure that the linked library with the original code exists. If it doesn't the library is compile... |
from os import path
if self.link is None or not path.isfile(self.link):
self.makelib(remake, True, compiler, debug, profile) |
<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(self, dirpath, makename, compiler, debug, profile):
"""Compiles the makefile at the specified location with 'compiler'. :arg dirpath: the full path ... |
from os import path
options = ""
if debug:
options += " DEBUG=true"
if profile:
options += " GPROF=true"
from os import system
codestr = "cd {}; make -f '{}' F90={} FAM={}" + options
code = system(codestr.format(dirpath, makename, compile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makelib(self, remake=False, full=True, compiler="gfortran", debug=False, profile=False):
"""Generates a makefile for the code files that reside in the same d... |
if self.link is None or remake:
from os import path
if self.library is not None:
outpath = path.join(self.dirpath, "{}.a".format(self.library))
else:
outpath = path.join(self.dirpath, "{}.a".format(self.name))
if not remake and pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_so(self, outpath):
"""Copies the shared library in self.so into the working directory for the wrapper module if it doesn't already exist. """ |
from os import path
if not path.isfile(outpath) and path.isfile(self.link):
from shutil import copy
copy(self.link, outpath) |
<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_modules(self, full):
"""Returns a list of the modules in the same folder as the one being wrapped for compilation as a linked library. :arg full: wh... |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
result = []
if full:
found = {}
... |
<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_dependencies(self):
"""Gets a list of the module names that should be included in the shared lib compile as dependencies for the current wrapper module.... |
#The only complication with the whole process is that we need to get the list of
#dependencies for the current module. For full lib, we compile *all* the files in
#the directory, otherwise only those that are explicitly required.
from os import path
modules = self.module.search_... |
<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_executables(self):
"""Finds the list of executables that pass the requirements necessary to have a wrapper created for them. """ |
if len(self.needs) > 0:
return
for execname, executable in list(self.module.executables.items()):
skip = False
#At the moment we can't handle executables that use special derived types.
if not execname in self.module.publics or not executable.pri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_dir(self):
"""Makes sure that the working directory for the wrapper modules exists. """ |
from os import path, mkdir
if not path.isdir(self.dirpath):
mkdir(self.dirpath)
#Copy the ftypes.py module shipped with fortpy to the local directory.
ftypes = path.join(get_fortpy_templates(), "ftypes.py")
from shutil import copy
copy(ftypes,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_py(self):
"""Writes a python module file to the current working directory for the library. """ |
self._check_dir()
#We make it so that the write py method can be called independently (as opposed
#to first needing the F90 write method to be called).
self._find_executables()
lines = []
lines.append('"""Auto-generated python module for interaction with Fortran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_f90(self):
"""Writes the F90 module file to the specified directory. """ |
from os import path
self._check_dir()
#Find the list of executables that we actually need to write wrappers for.
self._find_executables()
lines = []
lines.append("!!<summary>Auto-generated Fortran module for interaction with ctypes\n"
"!!thr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_executable_f90(self, execname, lines):
"""Appends the Fortran code to write the wrapper executable to the specified 'lines' list. :arg execname: the n... |
executable = self.module.executables[execname]
#The 14 in the formatting indent comes from 4 spaces, 2 from "_c", 1 from the spacing
#between 'subroutine' and name of the executable, 10 from subroutine, 1 from the ("
cparams = present_params(_ctypes_ex_parameters(executable... |
<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_module_needs(self, modules):
"""Adds the module and its dependencies to the result list in dependency order.""" |
result = list(modules)
for i, module in enumerate(modules):
#It is possible that the parser couldn't find it, if so
#we can't create the executable!
if module in self.module.parent.modules:
modneeds = self.module.parent.modules[module].needs
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coderelpath(coderoot, relpath):
"""Returns the absolute path of the 'relpath' relative to the specified code directory.""" |
from os import chdir, getcwd, path
cd = getcwd()
chdir(coderoot)
result = path.abspath(relpath)
chdir(cd)
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 _setup_ssh(self):
"""Initializes the connection to the server via SSH.""" |
global paramiko
if paramiko is none:
import paramiko
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.server, username=self.user, pkey=self.pkey) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abspath(self, path):
"""Returns the absolute path to the specified relative or user-relative path. For ssh paths, just return the full ssh path.""" |
if self.is_ssh(path):
return path
else:
return os.path.abspath(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirname(self, path):
"""Returns the full path to the parent directory of the specified file path.""" |
if self.is_ssh(path):
remotepath = self._get_remote(path)
remotedir = os.path.dirname(remotepath)
return self._get_tramp_path(remotedir)
else:
return os.path.dirname(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def touch(self, filepath):
"""Touches the specified file so that its modified time changes.""" |
if self.is_ssh(filepath):
self._check_ssh()
remotepath = self._get_remote(filepath)
stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath))
stdin.close()
else:
os.system("touch {}".format(filepath)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expanduser(self, filepath, ssh=False):
"""Replaces the user root ~ with the full path on the file system. Works for local disks and remote servers. For remot... |
if ssh:
self._check_ssh()
stdin, stdout, stderr = self.ssh.exec_command("cd; pwd")
stdin.close()
remotepath = filepath.replace("~", stdout.read().split()[0])
return self._get_tramp_path(remotepath)
else:
return os.path.expanduser(f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getmtime(self, filepath):
"""Gets the last time that the file was modified.""" |
if self.is_ssh(filepath):
self._check_ftp()
source = self._get_remote(filepath)
mtime = self.ftp.stat(source).st_mtime
else:
mtime = os.path.getmtime(filepath)
return mtime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, filepath):
"""Returns the entire file as a string even if it is on a remote server.""" |
target = self._read_check(filepath)
if os.path.isfile(target):
with open(target) as f:
string = f.read()
#If we got this file via SSH, delete it from the temp folder
if self.is_ssh(filepath):
os.remove(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 walk(self, dirpath):
"""Performs an os.walk on a local or SSH filepath.""" |
if self.is_ssh(dirpath):
self._check_ftp()
remotepath = self._get_remote(dirpath)
return self._sftp_walk(remotepath)
else:
return os.walk(dirpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sftp_walk(self, remotepath):
"""Performs the same function as os.walk but over the SSH channel.""" |
#Get all the files and folders in the current directory over SFTP.
path = remotepath # We need this instance of path for the yield to work.
files=[]
folders=[]
for f in self.ftp.listdir_attr(remotepath):
if S_ISDIR(f.st_mode):
folders.append(self._get... |
<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_hashed_path(self, path):
"""Returns an md5 hash for the specified file path.""" |
return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pkey(self):
"""Returns the private key for quick authentication on the SSH server.""" |
if self._pkey is None:
self._pkey = self._get_pkey()
return self._pkey |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metarate(self, func, name='values'):
""" Set the values object to the function object's namespace """ |
setattr(func, name, self.values)
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exit(self, status=0, message=None):
""" Delegates to `ArgumentParser.exit` """ |
if status:
self.logger.error(message)
if self.__parser__: # pylint: disable-msg=E1101
self.__parser__.exit(status, message) # pylint: disable-msg=E1101
else:
sys.exit(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, message=None):
""" Delegates to `ArgumentParser.error` """ |
if self.__parser__: # pylint: disable-msg=E1101
self.__parser__.error(message) # pylint: disable-msg=E1101
else:
self.logger.error(message)
sys.exit(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 run(self, args=None):
""" Runs the main command or sub command based on user input """ |
if not args:
args = self.parse(sys.argv[1:])
if getattr(args, 'verbose', False):
self.logger.setLevel(logging.DEBUG)
try:
if hasattr(args, 'run'):
args.run(self, args)
else:
self.__main__(args) # pylint: disable... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nvalues(self):
"""Returns the number of values recorded on this single line. If the number is variable, it returns -1.""" |
if self._nvalues is None:
self._nvalues = 0
for val in self.values:
if type(val) == type(int):
self._nvalues += val
else:
self._nvalues = -1
break
return self._nvalues |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, valuedict):
"""Returns the lines that this template line should add to the input file.""" |
if self.identifier in valuedict:
value = valuedict[self.identifier]
elif self.default is not None:
value = self.default
elif self.fromtag is not None and self.fromtag in valuedict:
if self.operator == "count":
value = len(valuedict[self.fromta... |
<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, element):
"""Parses the contents of the specified XML element using template info. :arg element: the XML element from the input file being conver... |
result = []
if element.text is not None and element.tag == self.identifier:
l, k = (0, 0)
raw = element.text.split()
while k < len(self.values):
dtype = self.dtype[k]
if isinstance(self.values[k], int):
for i in ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_int(self, value):
"""Returns the specified value as int if possible.""" |
try:
return int(value)
except ValueError:
msg.err("Cannot convert {} to int for line {}.".format(value, self.identifier))
exit(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 _cast_float(self, value):
"""Returns the specified value as float if possible.""" |
try:
return float(value)
except ValueError:
msg.err("Cannot convert {} to float for line {}.".format(value, self.identifier))
exit(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 _load(self, element, commentchar):
"""Loads all the child line elements from the XML group element.""" |
for child in element:
if "id" in child.attrib:
tline = TemplateLine(child, self, commentchar)
self.order.append(tline.identifier)
self.lines[tline.identifier] = tline
else:
msg.warn("no id element in {}. Ignored... |
<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, element):
"""Extracts the values from the specified XML element that is being converted.""" |
#All the children of this element are what we are trying to parse.
result = []
for child in element:
if child.tag in self.lines:
values = { child.tag: self.lines[child.tag].parse(child) }
result.append(values)
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 write(self, valuedict):
"""Generates the lines for the converted input file using the specified value dictionary.""" |
result = []
if self.identifier in valuedict:
values = valuedict[self.identifier]
else:
return result
if self.comment != "":
result.append(self.comment)
if self.repeat is not None and type(values) == type([]):
if self.repeat.isdig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_iterate(self, values):
"""Generates the lines for a single pass through the group.""" |
result = []
for key in self.order:
result.append(self.lines[key].write(values))
if len(result) > 1:
return result
else:
return result[0] |
<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(self):
"""Extracts the XML template data from the file.""" |
if os.path.exists(self.path):
root = ET.parse(self.path).getroot()
if (root.tag == "fortpy" and "mode" in root.attrib and
root.attrib["mode"] == "template" and "direction" in root.attrib and
root.attrib["direction"] == self.direction):
#Fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, valuedict, version):
"""Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the key... |
result = []
if version in self.versions:
for tag in self.versions[version].order:
entry = self.versions[version].entries[tag]
result.extend(entry.write(valuedict))
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 _load_entries(self, root):
"""Loads all the child entries of the input template from the specified root element.""" |
mdict = {
"comments": self._comment,
"line": self._line,
"group": self._group
}
for entry in root:
mdict[entry.tag](entry) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.