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 _collapse_default(self, entry): """Collapses the list structure in entry to a single string representing the default value assigned to a variable or its dime...
if isinstance(entry, tuple) or isinstance(entry, list): sets = [] i = 0 while i < len(entry): if isinstance(entry[i], str) and i+1 < len(entry) and isinstance(entry[i+1], list): sets.append((entry[i], entry[i+1])) 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 _clean_multiple_def(self, ready): """Cleans the list of variable definitions extracted from the definition text to get hold of the dimensions and default val...
result = [] for entry in ready: if isinstance(entry, list): #This variable declaration has a default value specified, which is in the #second slot of the list. default = self._collapse_default(entry[1]) #For hard-coded array de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def char_range(starting_char, ending_char): """ Create a range generator for chars """
assert isinstance(starting_char, str), 'char_range: Wrong argument/s type' assert isinstance(ending_char, str), 'char_range: Wrong argument/s type' for char in range(ord(starting_char), ord(ending_char) + 1): yield chr(char)
<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_charset(charset): """ Finds out whether there are intervals to expand and creates the charset """
import re regex = r'(\w-\w)' pat = re.compile(regex) found = pat.findall(charset) result = '' if found: for element in found: for char in char_range(element[0], element[-1]): result += char return result return charset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """Return the viewable size of the Table as @tuple (x,y)"""
width = max( map(lambda x: x.size()[0], self.sections.itervalues())) height = sum( map(lambda x: x.size()[1], self.sections.itervalues())) return width, height
<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_ftr(self): """ Process footer and return the processed string """
if not self.ftr: return self.ftr width = self.size()[0] return re.sub( "%time", "%s\n" % time.strftime("%H:%M:%S"), self.ftr).rjust(width)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_help(self, arg): """Sets up the header for the help command that explains the background on how to use the script generally. Help for each command then st...
if arg == "": lines = [("The fortpy unit testing analysis shell makes it easy to analyze the results " "of multiple test cases, make plots of trends and tabulate values for use in " "other applications. This documentation will provide an overview of the b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fixed_width_info(self, lines): """Prints the specified string as information with fixed width of 80 chars."""
for string in lines: for line in [string[i:i+80] for i in range(0, len(string), 80)]: msg.info(line) msg.blank()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _redirect_output(self, value, filename=None, append=None, printfun=None): """Outputs the specified value to the console or a file depending on the redirect b...
if filename is None: if printfun is None: print(value) else: printfun(value) else: if append: mode = 'a' else: mode = 'w' from os import path fullpath = path.abspath(...
<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_cases(self, text, line, istart, iend): """Returns the completion list of possible test cases for the active unit test."""
if text == "": return list(self.live.keys()) else: return [c for c in self.live if c.startswith(text)]
<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_arg_generic(self, argid, arg, cast=str): """Sets the value of the argument with the specified id using the argument passed in from the shell session. ""...
usable, filename, append = self._redirect_split(arg) if usable != "": self.curargs[argid] = cast(usable) if argid in self.curargs: result = "{}: '{}'".format(argid.upper(), self.curargs[argid]) self._redirect_output(result, filename, append, msg.info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_map_dict(self, argkey, filename, append): """Prints a dictionary that has variable => value mappings."""
result = [] skeys = list(sorted(self.curargs[argkey].keys())) for key in skeys: result.append("'{}' => {}".format(key, self.curargs[argkey][key])) self._redirect_output('\n'.join(result), filename, append, msg.info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_postfix(self, arg): """Sets the function to apply to the values of a specific variable before plotting or tabulating values. """
usable, filename, append = self._redirect_split(arg) sargs = usable.split() if len(sargs) == 1 and sargs[0] == "list": self._print_map_dict("functions", filename, append) elif len(sargs) >= 2: defvars = self._postfix_varlist("postfix " + arg) for var ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_rmpostfix(self, arg): """Removes a postfix function from a variable. See 'postfix'."""
altered = False if arg in self.curargs["functions"]: del self.curargs["functions"][arg] altered = True elif arg == "*": for varname in list(self.curargs["functions"].keys()): del self.curargs["functions"][varname] altered = 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 do_rmfit(self, arg): """Removes a fit function from a variable. See 'fit'."""
if arg in self.curargs["fits"]: del self.curargs["fits"][arg] #We also need to remove the variable entry if it exists. if "timing" in arg: fitvar = "{}|fit".format(arg) else: fitvar = "{}.fit".format(arg) if fitvar in self.curargs["dep...
<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_matplot_dict(self, option, prop, defdict): """Returns a copy of the settings dictionary for the specified option in curargs with update values where the...
cargs = self.curargs[option] result = cargs.copy() for varname in cargs: if prop in cargs[varname]: name = cargs[varname][prop] for key, val in list(defdict.items()): if val == name: cargs[varname][prop] = k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _plot_generic(self, filename=None): """Plots the current state of the shell, saving the value to the specified file if specified. """
#Since the filename is being passed directly from the argument, check its validity. if filename == "": filename = None if "x" not in self.curargs["labels"]: #Set a default x-label since we know what variable is being plotted. self.curargs["labels"]["x"] = "V...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_plot(self, arg): """Plots the current state of the shell's independent vs. dependent variables on the same set of axes. Give filename to save to as argume...
usable, filename, append = self._redirect_split(arg) self.curargs["xscale"] = None self.curargs["yscale"] = None self._plot_generic(filename)
<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_def_prompt(self): """Sets the default prompt to match the currently active unit test."""
if len(self.active) > 15: ids = self.active.split(".") if len(ids) > 2: module, executable, compiler = ids else: module, executable = ids compiler = "g" self.prompt = "({}*.{}*.{}:{})".format(module[0:6], 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 do_set(self, arg): """Sets the specified 'module.executable' to be the active test result to interact with. """
if arg in self.tests: self.active = arg #Create a default argument set and analysis group for the current plotting if arg not in self.args: self.args[arg] = {"default": dict(self._template_args)} self.group = "default" 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 do_load(self, arg): """Loads a saved session variables, settings and test results to the shell."""
from os import path import json fullpath = path.expanduser(arg) if path.isfile(fullpath): with open(fullpath) as f: data = json.load(f) #Now, reparse the staging directories that were present in the saved session. for stagepath in dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_reparse(self, arg): """Reparses the currently active unit test to get the latest test results loaded to the console. """
#We just get the full path of the currently active test and hit reparse. full = arg == "full" from os import path fullpath = path.abspath(self.tests[self.active].stagedir) self.tests[self.active] = Analysis(fullpath, full)
<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_fits(self): """Generates the data fits for any variables set for fitting in the shell."""
a = self.tests[self.active] args = self.curargs #We need to generate a fit for the data if there are any fits specified. if len(args["fits"]) > 0: for fit in list(args["fits"].keys()): a.fit(args["independent"], fit, args["fits"][fit], args["threshold"], 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 do_table(self, arg): """Prints the set of values for the independent vs. dependent variables in the active unit test and analysis group as a table. """
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs self._make_fits() result = a.table(args["independent"], args["dependents"], args["threshold"], args["headings"], args["functions"]) if result is ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_failures(self, arg): """Prints a list of test cases that failed for the current unit test and analysis group settings. To only check failure on specific o...
usable, filename, append = self._redirect_split(arg) a = self.tests[self.active] args = self.curargs splitargs = usable.split() if len(splitargs) > 0: tfilter = splitargs[0] else: tfilter = "*" outfiles = None if len(splitargs) > ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def histpath(self): """Returns the full path to the console history file."""
from os import path from fortpy import settings return path.join(settings.cache_directory, "history")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _store_lasterr(self): """Stores the information about the last unhandled exception."""
from sys import exc_info from traceback import format_exception e = exc_info() self.lasterr = '\n'.join(format_exception(e[0], e[1], e[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 precmd(self, line): """Makes sure that the command specified in the line is valid given the current status of loaded unit tests and analysis group. """
if line == "": return "" command = line.split()[0] if "!" in command: value = command.split("!")[1] try: ihist = int(value) import readline if ihist <= readline.get_current_history_length(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_cd(self, arg): """Imitates the bash shell 'cd' command."""
from os import chdir, path fullpath = path.abspath(path.expanduser(arg)) if path.isdir(fullpath): chdir(fullpath) else: msg.err("'{}' is not a valid directory.".format(arg))
<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_branches(scales=None, angles=None, shift_angle=0): """Generates branches with alternative system. Args: scales (tuple/array): Indicating how the br...
branches = [] for pos, scale in enumerate(scales): angle = -sum(angles)/2 + sum(angles[:pos]) + shift_angle branches.append([scale, angle]) return branches
<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_rectangle(self): """Gets the coordinates of the rectangle, in which the tree can be put. Returns: tupel: (x1, y1, x2, y2) """
rec = [self.pos[0], self.pos[1]]*2 for age in self.nodes: for node in age: # Check max/min for x/y coords for i in range(2): if rec[0+i] > node.pos[i]: rec[0+i] = node.pos[i] elif rec[2+i] < node...
<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_size(self): """Get the size of the tree. Returns: tupel: (width, height) """
rec = self.get_rectangle() return (int(rec[2]-rec[0]), int(rec[3]-rec[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_branch_length(self, age=None, pos=0): """Get the length of a branch. This method calculates the length of a branch in specific age. The used formula: len...
if age is None: age = self.age return self.length * pow(self.branches[pos][0], age)
<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_steps_branch_len(self, length): """Get, how much steps will needed for a given branch length. Returns: float: The age the tree must achieve to reach the ...
return log(length/self.length, min(self.branches[0][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 get_node_sum(self, age=None): """Get sum of all branches in the tree. Returns: int: The sum of all nodes grown until the age. """
if age is None: age = self.age return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 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_age_sum(self, age=None): """Get the sum of branches grown in an specific age. Returns: int: The sum of all nodes grown in an age. """
if age is None: age = self.age return pow(self.comp, age)
<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_nodes(self): """Get the tree nodes as list. Returns: list: A 2d-list holding the grown nodes coordinates as tupel for every age. Example: [ [(10, 40)], [...
nodes = [] for age, level in enumerate(self.nodes): nodes.append([]) for node in level: nodes[age].append(node.get_tuple()) return nodes
<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_branches(self): """Get the tree branches as list. Returns: list: A 2d-list holding the grown branches coordinates as tupel for every age. Example: [ [(10...
branches = [] for age, level in enumerate(self.nodes): branches.append([]) for n, node in enumerate(level): if age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(age-1, n) ...
<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 tree. Args: delta (tupel): The adjustment of the position. """
pos = self.pos self.pos = (pos[0]+delta[0], pos[1]+delta[1], pos[2]+delta[0], pos[3]+delta[1]) # Move all nodes for age in self.nodes: for node in age: node.move(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 grow(self, times=1): """Let the tree grow. Args: times (integer): Indicate how many times the tree will grow. """
self.nodes.append([]) for n, node in enumerate(self.nodes[self.age]): if self.age == 0: p_node = Node(self.pos[:2]) else: p_node = self._get_node_parent(self.age-1, n) angle = node.get_node_angle(p_node) for i in range(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_on(self, canvas, stem_color, leaf_color, thickness, ages=None): """Draw the tree on a canvas. Args: canvas (object): The canvas, you want to draw the t...
if canvas.__module__ in SUPPORTED_CANVAS: drawer = SUPPORTED_CANVAS[canvas.__module__] drawer(self, canvas, stem_color, leaf_color, thickness, ages).draw()
<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_total_angle(self, angle, pos): """Get the total angle."""
tot_angle = angle - self.branches[pos][1] if self.sigma[1] != 0: tot_angle += gauss(0, self.sigma[1]) * pi return tot_angle
<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_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """
return self.nodes[age][int(pos / self.comp)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _field_lookups(model, status=None): """ Abstraction of field lookups for managers. Returns a dictionary of field lookups for a queryset. The lookups will alw...
# Import models here to avoid circular import fail. from faq.models import Topic, Question field_lookups = {} if model == Topic: field_lookups['sites__pk'] = settings.SITE_ID if model == Question: field_lookups['topic__sites__pk'] = settings.SITE_ID if 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 detect_compiler(libpath): """Determines the compiler used to compile the specified shared library by using the system utilities. :arg libpath: the full path ...
from os import waitpid, path from subprocess import Popen, PIPE command = "nm {0}".format(path.abspath(libpath)) child = Popen(command, shell=True, executable="/bin/bash", stdout=PIPE) # Need to do this so that we are sure the process is done before moving on waitpid(child.pid, 0) contents ...
<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): """Deallocates the fortran-managed memory that this ctype references. """
if not self.deallocated: #Release/deallocate the pointer in fortran. method = self._deallocator() if method is not None: dealloc = static_symbol("ftypes_dealloc", method, self.libpath, True) if dealloc is None: 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 _deallocator(self): """Returns the name of the subroutine in ftypes_dealloc.f90 that can deallocate the array for this Ftype's pointer. :arg ctype: the strin...
lookup = { "c_bool": "logical", "c_double": "double", "c_double_complex": "complex", "c_char": "char", "c_int": "int", "c_float": "float", "c_short": "short", "c_long": "long" } ctype = 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 add(self, varname, result, pointer=None): """Adds the specified python-typed result and an optional Ftype pointer to use when cleaning up this object. :arg r...
self.result[varname] = result setattr(self, varname, result) if pointer is not None: self._finalizers[varname] = pointer
<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_python_object(name): """ Loads a python module from string """
logger = getLoggerWithNullHandler('commando.load_python_object') (module_name, _, object_name) = name.rpartition(".") if module_name == '': (module_name, object_name) = (object_name, module_name) try: logger.debug('Loading module [%s]' % module_name) module = __import__(module_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLoggerWithConsoleHandler(logger_name=None): """ Gets a logger object with a pre-initialized console handler. """
logger = logging.getLogger(logger_name) logger.setLevel(logging.INFO) if not logger.handlers: handler = logging.StreamHandler(sys.stdout) if sys.platform == 'win32': formatter = logging.Formatter( fmt="%(asctime)s %(name)s %(message)s", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLoggerWithNullHandler(logger_name): """ Gets the logger initialized with the `logger_name` and a NullHandler. """
logger = logging.getLogger(logger_name) if not logger.handlers: logger.addHandler(NullHandler()) return logger
<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(self, *args, **kwargs): """ Delegates to `subprocess.check_call`. """
args, kwargs = self.__process__(*args, **kwargs) return check_call(args, **kwargs)
<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(self, *args, **kwargs): """ Delegates to `subprocess.check_output`. """
args, kwargs = self.__process__(*args, **kwargs) return check_output(args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, *args, **kwargs): """ Delegates to `subprocess.Popen`. """
args, kwargs = self.__process__(*args, **kwargs) return Popen(args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tag(request, tag_id=None): """ The view used to render a tag after the page has loaded. """
html = get_tag_html(tag_id) t = template.Template(html) c = template.RequestContext(request) return HttpResponse(t.render(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 _get_color(self, age): """Get the fill color depending on age. Args: age (int): The age of the branch/es Returns: tuple: (r, g, b) """
if age == self.tree.age: return self.leaf_color color = self.stem_color tree = self.tree if len(color) == 3: return color diff = [color[i+3]-color[i] for i in range(3)] per_age = [diff[i]/(tree.age-1) for i in range(3)] return tuple([in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws the tree. Args: ages (array): Contains the ages you want to draw. """
for age, level in enumerate(self.tree.get_branches()): if age in self.ages: thickness = self._get_thickness(age) color = self._get_color(age) for branch in level: self._draw_branch(branch, color, thickness, age)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cmd_create(self): """Create a migration in the current or new revision folder """
assert self._message, "need to supply a message for the \"create\" command" if not self._revisions: self._revisions.append("1") # get the migration folder rev_folder = self._revisions[-1] full_rev_path = os.path.join(self._migration_path, rev_folder) if not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cmd_up(self): """Upgrade to a revision"""
revision = self._get_revision() if not self._rev: self._log(0, "upgrading current revision") else: self._log(0, "upgrading from revision %s" % revision) for rev in self._revisions[int(revision) - 1:]: sql_files = glob.glob(os.path.join(self._migration...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cmd_down(self): """Downgrade to a revision"""
revision = self._get_revision() if not self._rev: self._log(0, "downgrading current revision") else: self._log(0, "downgrading to revision %s" % revision) # execute from latest to oldest revision for rev in reversed(self._revisions[int(revision) - 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_revision(self): """Validate and return the revision to use for current command """
assert self._revisions, "no migration revision exist" revision = self._rev or self._revisions[-1] # revision count must be less or equal since revisions are ordered assert revision in self._revisions, "invalid revision specified" return revision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newest(cls, session): """Fetches the latest media added to MAL. :type session: :class:`myanimelist.session.Session` :param session: A valid MAL session :rtyp...
media_type = cls.__name__.lower() p = session.session.get(u'http://myanimelist.net/' + media_type + '.php?o=9&c[]=a&c[]=d&cv=2&w=1').text soup = utilities.get_clean_dom(p) latest_entry = soup.find(u"div", {u"class": u"hoverinfo"}) if not latest_entry: raise MalformedMediaPageError(0, p, u"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 parse(self, media_page): """Parses the DOM and returns media attributes in the main-content area. :type media_page: :class:`bs4.BeautifulSoup` :param media_p...
media_info = self.parse_sidebar(media_page) try: synopsis_elt = media_page.find(u'h2', text=u'Synopsis').parent utilities.extract_tags(synopsis_elt.find_all(u'h2')) media_info[u'synopsis'] = synopsis_elt.text.strip() except: if not self.session.suppress_parse_exceptions: ra...
<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_characters(self, character_page): """Parses the DOM and returns media character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulS...
media_info = self.parse_sidebar(character_page) try: character_title = filter(lambda x: u'Characters' in x.text, character_page.find_all(u'h2')) media_info[u'characters'] = {} if character_title: character_title = character_title[0] curr_elt = character_title.find_next_siblin...
<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 media page and sets the current media's attributes. :rtype: :class:`.Media` :return: current media object. """
media_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id)).text self.set(self.parse(utilities.get_clean_dom(media_page))) 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_stats(self): """Fetches the MAL media statistics page and sets the current media's statistics attributes. :rtype: :class:`.Media` :return: current media...
stats_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/stats').text self.set(self.parse_stats(utilities.get_clean_dom(stats_page))) 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_characters(self): """Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current m...
characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(self.id) + u'/' + utilities.urlencode(self.title) + u'/characters').text self.set(self.parse_characters(utilities.get_clean_dom(characters_page))) 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(parser, serializer): """Returns a dictionary of builtin functions for Fortran. Checks the cache first to see if we have a serialized version. If we don'...
fortdir = os.path.dirname(fortpy.__file__) xmlpath = os.path.join(fortdir, "isense", "builtin.xml") if not os.path.isfile(xmlpath): return {} changed_time = os.path.getmtime(xmlpath) cached = serializer.load_module("builtin.xml", changed_time) if cached is None: result = _load_...
<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_builtin_xml(xmlpath, parser): """Loads the builtin function specifications from the builtin.xml file. :arg parser: the DocParser instance for parsing t...
#First we need to get hold of the fortpy directory so we can locate #the isense/builtin.xml file. result = {} el = ET.parse(xmlpath).getroot() if el.tag == "builtin": for child in el: anexec = _parse_xml(child, parser) result[anexec.name.lower()] = anexec retur...
<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_xml(child, parser): """Parses the specified child XML tag and creates a Subroutine or Function object out of it."""
name, modifiers, dtype, kind = _parse_common(child) #Handle the symbol modification according to the isense settings. name = _isense_builtin_symbol(name) if child.tag == "subroutine": parent = Subroutine(name, modifiers, None) elif child.tag == "function": parent = Function(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 make_request(self, url, params, auth=None): """ Prepares a request from a url, params, and optionally authentication. """
req = urllib2.Request(url + urllib.urlencode(params)) if auth: req.add_header('AUTHORIZATION', 'Basic ' + auth) return urllib2.urlopen(req)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fpy_interface(fpy, static, interface, typedict): """Splices the full list of subroutines and the module procedure list into the static.f90 file. :arg static:...
modprocs = [] subtext = [] for dtype, combos in list(typedict.items()): for tcombo in combos: kind, suffix = tcombo xnames, sub = fpy_interface_sub(fpy, dtype, kind, suffix) modprocs.extend(xnames) subtext.append(sub) subtext.append("\n") ...
<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(): """Parses the specified Fortran source file from which the wrappers will be constructed for ctypes. """
if not args["reparse"]: settings.use_filesystem_cache = False c = CodeParser() if args["verbose"]: c.verbose = True if args["reparse"]: c.reparse(args["source"]) else: c.parse(args["source"]) return 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 setup_regex(self): """Sets up compiled regex objects for parsing code elements."""
#Regex for extracting modules from the code self._RX_MODULE = r"(\n|^)\s*module\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*module" self.RE_MODULE = re.compile(self._RX_MODULE, re.I | re.DOTALL) self._RX_PROGRAM = r"(\n|^)\s*program\s+(?P<name>[a-z0-9_]+)(?P<contents>.+?)end\s*program"...
<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_programs(self, string, parent, filepath=None): """Extracts a PROGRAM from the specified fortran code file."""
#First, get hold of the docstrings for all the modules so that we can #attach them as we parse them. moddocs = self.docparser.parse_docs(string) #Now look for modules in the file and then match them to their decorators. matches = self.RE_PROGRAM.finditer(string) 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 _process_publics(self, contents): """Extracts a list of public members, types and executables that were declared using the public keyword instead of a decora...
matches = self.RE_PUBLIC.finditer(contents) result = {} start = 0 for public in matches: methods = public.group("methods") #We need to keep track of where the public declarations start so that the unit #testing framework can insert public statements 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 _process_module(self, name, contents, parent, match, filepath=None): """Processes a regex match for a module to create a CodeElement."""
#First, get hold of the name and contents of the module so that we can process the other #parts of the module. modifiers = [] #We need to check for the private keyword before any type or contains declarations if self.RE_PRIV.search(contents): modifiers.append("priva...
<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_use(self, string): """Extracts use dependencies from the innertext of a module."""
result = {} for ruse in self.RE_USE.finditer(string): #We also handle comments for individual use cases, the "only" section #won't pick up any comments. name = ruse.group("name").split("!")[0].strip() if name.lower() == "mpi": continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dict_increment(self, dictionary, key): """Increments the value of the dictionary at the specified key."""
if key in dictionary: dictionary[key] += 1 else: dictionary[key] = 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 _parse_members(self, contents, module): """Extracts any module-level members from the code. They must appear before any type declalations."""
#We need to get hold of the text before the module's main CONTAINS keyword #so that we don't find variables from executables and claim them as #belonging to the module. icontains = module.contains_index ichar = module.charindex(icontains, 0) module.preamble = module.refs...
<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 compiled regex objects for parsing the executables from a module."""
self._RX_CONTAINS = r"^\s*contains[^\n]*?$" self.RE_CONTAINS = re.compile(self._RX_CONTAINS, re.M | re.I) #Setup a regex that can extract information about both functions and subroutines self._RX_EXEC = r"\n[ \t]*((?P<type>character|real|type|logical|integer|complex)?" + \ ...
<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, module): """Extracts all the subroutine and function definitions from the specified module."""
#Because of embedded types, we have to examine the entire module for #executable definitions. self.parse_block(module.refstring, module, module, 0) #Now we can set the value of module.contains as the text after the start of #the *first* non-embedded executable. min_star...
<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_block(self, contents, parent, module, depth): """Extracts all executable definitions from the specified string and adds them to the specified parent.""...
for anexec in self.RE_EXEC.finditer(contents): x = self._process_execs(anexec, parent, module) parent.executables[x.name.lower()] = x if isinstance(parent, Module) and "public" in x.modifiers: parent.publics[x.name.lower()] = 1 #To h...
<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_execs(self, execmatch, parent, module): """Processes the regex match of an executable from the match object."""
#Get the matches that must be present for every executable. name = execmatch.group("name").strip() modifiers = execmatch.group("modifiers") if modifiers is None: modifiers = [] else: modifiers = re.split(",[ \t]*", modifiers) codetype = execmatch....
<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_assignments(self, anexec, contents, mode="insert"): """Extracts all variable assignments from the body of the executable. :arg mode: for real-time u...
for assign in self.RE_ASSIGN.finditer(contents): assignee = assign.group("assignee").strip() target = re.split(r"[(%\s]", assignee)[0].lower() #We only want to include variables that we know are in the scope of the #current executable. This excludes function cal...
<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_dependencies(self, anexec, contents, mode="insert"): """Extracts a list of subroutines and functions that are called from within this executable. :a...
#At this point we don't necessarily know which module the executables are #in, so we just extract the names. Once all the modules in the library #have been parsed, we can do the associations at that level for linking. for dmatch in self.RE_DEPEND.finditer(contents): isSubrou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _depend_exec_clean(self, text): """Cleans any string constants in the specified dependency text to remove embedded ! etc. that break the parsing. """
#First remove the escaped quotes, we will add them back at the end. unquoted = text.replace('""', "_FORTPYDQ_").replace("''", "_FORTPYSQ_") for cmatch in self.RE_CONST.finditer(unquoted): string = cmatch.string[cmatch.start():cmatch.end()] newstr = string.replace("!", "_...
<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_dependlist(self, dependlist, anexec, isSubroutine, mode="insert"): """Processes a list of nested dependencies recursively."""
for i in range(len(dependlist)): #Since we are looping over all the elements and some will #be lists of parameters, we need to skip any items that are lists. if isinstance(dependlist[i], list): continue key = dependlist[i].lower() 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 _remove_dependency(self, dependlist, i, isSubroutine, anexec): """Removes the specified dependency from the executable if it exists and matches the call sign...
if dependlist[i] in anexec.dependencies: all_depends = anexec.dependencies[dependlist[i]] if len(all_depends) > 0: clean_args = all_depends[0].clean(dependlist[i + 1]) for idepend in range(len(all_depends)): #Make sure we match across ...
<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, key, dependlist, i, isSubroutine, anexec): """Determines whether the item in the dependency list is a valid function call by excluding ...
#First determine if the reference is to a derived type variable lkey = key.lower() if "%" in key: #Find the type of the base variable and then perform a tree #search at the module level to determine if the final reference #is a valid executable ba...
<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_docs(self, anexec, docblocks, parent, module, docsearch): """Associates the docstrings from the docblocks with their parameters."""
#The documentation for the parameters is stored outside of the executable #We need to get hold of them from docblocks from the parent text key = "{}.{}".format(parent.name, anexec.name) if key in docblocks: docs = self.docparser.to_doc(docblocks[key][0], anexec.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 _parse_members(self, contents, anexec, params, mode="insert"): """Parses the local variables for the contents of the specified executable."""
#First get the variables declared in the body of the executable, these can #be either locals or parameter declarations. members = self.vparser.parse(contents, anexec) #If the name matches one in the parameter list, we can connect them for param in list(params): lpar...
<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_sidebar(self, character_page): """Parses the DOM and returns character attributes in the sidebar. :type character_page: :class:`bs4.BeautifulSoup` :par...
character_info = {} error_tag = character_page.find(u'div', {'class': 'badresult'}) if error_tag: # MAL says the character does not exist. raise InvalidCharacterError(self.id) try: full_name_tag = character_page.find(u'div', {'id': 'contentWrapper'}).find(u'h1') if not full_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 parse(self, character_page): """Parses the DOM and returns character attributes in the main-content area. :type character_page: :class:`bs4.BeautifulSoup` :p...
character_info = self.parse_sidebar(character_page) second_col = character_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] name_elt = second_col.find(u'div', {'class': 'normal_header'}) try: name_jpn_node = name_elt.find(u'small') if nam...
<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_favorites(self, favorites_page): """Parses the DOM and returns character favorites attributes. :type favorites_page: :class:`bs4.BeautifulSoup` :param ...
character_info = self.parse_sidebar(favorites_page) second_col = favorites_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: character_info[u'favorites'] = [] favorite_links = second_col.find_all('a', recursive=False) for link in fav...
<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_pictures(self, picture_page): """Parses the DOM and returns character pictures attributes. :type picture_page: :class:`bs4.BeautifulSoup` :param pictur...
character_info = self.parse_sidebar(picture_page) second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: picture_table = second_col.find(u'table', recursive=False) character_info[u'pictures'] = [] if picture_table: ...
<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 character clubs attributes. :type clubs_page: :class:`bs4.BeautifulSoup` :param clubs_page: MAL ...
character_info = self.parse_sidebar(clubs_page) second_col = clubs_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: clubs_header = second_col.find(u'div', text=u'Related Clubs') character_info[u'clubs'] = [] if clubs_header: ...
<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 character page and sets the current character's attributes. :rtype: :class:`.Character` :return: Current character object. """
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id)).text self.set(self.parse(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 load_favorites(self): """Fetches the MAL character favorites page and sets the current character's favorites attributes. :rtype: :class:`.Character` :return:...
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/favorites').text self.set(self.parse_favorites(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 load_pictures(self): """Fetches the MAL character pictures page and sets the current character's pictures attributes. :rtype: :class:`.Character` :return: Cu...
character = self.session.session.get(u'http://myanimelist.net/character/' + str(self.id) + u'/' + utilities.urlencode(self.name) + u'/pictures').text self.set(self.parse_pictures(utilities.get_clean_dom(character))) return self