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 _comment(self, element): """Extracts the character to use for comments in the input file."""
for v in _get_xml_version(element): self.versions[v].comment = element.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 _line(self, element): """Parses the XML element as a single line entry in the input file."""
for v in _get_xml_version(element): if "id" in element.attrib: tline = TemplateLine(element, None, self.versions[v].comment) self.versions[v].entries[tline.identifier] = tline self.versions[v].order.append(tline.identifier) 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 convert(self, path, version, target = None): """Converts the specified file using the relevant template. :arg path: the full path to the file to convert. :ar...
#Get the template and values out of the XML input file and #write them in the format of the keywordless file. values, template = self.parse(path) lines = template.write(values, version) #Finally, write the lines to the correct path. if target is None: target...
<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, path): """Extracts a dictionary of values from the XML file at the specified path."""
#Load the template that will be used for parsing the values. expath, template, root = self._load_template(path) if expath is not None: values = template.parse(root) return (values, template)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(self, path, version, target): """Converts the specified source file to a new version number."""
source = self.comparer.get_representation(path) lines = [ '# <fortpy version="{}"></fortpy>\n'.format(version) ] for line in self.comparer.template.contents[version].preamble: lines.append(line.write(source.preamble, source.version, source.stored) + "\n") for line in 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 cachedstr(self): """Returns the full string of the file contents from the cache for the file that we are currently providing intellisense for."""
if self._cachedstr is None: if self.module is not None: refstring = self.module.refstring self._cachedstr = refstring.splitlines() else: self._cachedstr = [] return self._cachedstr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exact_match(self): """Returns the symbol under the cursor looking both directions as part of a definition lookup for an exact match. """
#We don't have to worry about grouping or anything else fancy. Just #loop through forward and back until we hit a character that can't be #part of a variable or function name. if self._exact_match is None: i = self.pos[1] - 1 start = None end = 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 short_full_symbol(self): """Gets the full symbol excluding the character under the cursor."""
if self._short_full_symbol is None: self._short_full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR, False, True) return self._short_full_symbol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbol(self): """Gets the symbol under the current cursor."""
if self._symbol is None: self._symbol = self._symbol_extract(cache.RE_CURSOR) return self._symbol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_symbol(self): """Returns the symbol under the cursor AND additional contextual symbols in the case of %-separated lists of type members."""
if self._full_symbol is None: self._full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR, brackets=True) return self._full_symbol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _symbol_extract(self, regex, plus = True, brackets=False): """Extracts a symbol or full symbol from the current line, optionally including the character unde...
charplus = self.pos[1] + (1 if plus else -1) consider = self.current_line[:charplus][::-1] #We want to remove matching pairs of brackets so that derived types #that have arrays still get intellisense. if brackets==True: #The string has already been reversed, just ru...
<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_arg_index(self): """Determines the index of the parameter in a call list using string manipulation and context information."""
#The function name we are calling should be in el_name by now if self._call_index is None: if (self.el_section == "body" and self.el_call in [ "sub", "fun" ]): #Get hold of the element instance of the function being called so #we can examine 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 _setup_regex(self): """Sets up the constant regex strings etc. that can be used to parse the strings for determining context."""
self.RE_COMMENTS = cache.RE_COMMENTS self.RE_MODULE = cache.RE_MODULE self.RE_TYPE = cache.RE_TYPE self.RE_EXEC = cache.RE_EXEC self.RE_MEMBERS = cache.RE_MEMBERS self.RE_DEPEND = cache.RE_DEPEND
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _contextualize(self): """Finds values for all the important attributes that determine the user's context."""
line, column = self.pos #Get the module top-level information self._get_module(line) if self.module is None: return #Use the position of the cursor in the file to decide which #element we are working on. self.element = self.module.get_element...
<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_module(self, line): """Finds the name of the module and retrieves it from the parser cache."""
#Finding the module name is trivial; start at the beginning of #the module and iterate lines until we find the module. for sline in self._source: if len(sline) > 0 and sline[0] != "!": rmatch = self.RE_MODULE.match(sline) if rmatch 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 _deep_match(self, line, column): """Checks the contents of executables, types and modules for member definitions and updates the context."""
#Now we just try each of the possibilities for the current line if self._match_member(line, column): self.el_section = "vars" self.el_type = ValueElement self.el_name = self.col_match.group("names") return if isinstance(self.element,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_exec(self, i): """Looks at line 'i' for a subroutine or function definition."""
self.col_match = self.RE_EXEC.match(self._source[i]) if self.col_match is not None: if self.col_match.group("codetype") == "function": self.el_type = Function else: self.el_type = Subroutine self.el_name = self.col_match.group("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 _match_member(self, i, column): """Looks at line 'i' to see if the line matches a module member def."""
self.col_match = self.RE_MEMBERS.match(self._source[i]) if self.col_match is not None: if column < self._source[i].index(":"): self.el_call = "name" else: self.el_call = "assign" return True else: 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 _match_type(self, i): """Looks at line 'i' to see if the line matches a module user type def."""
self.col_match = self.RE_TYPE.match(self._source[i]) if self.col_match is not None: self.section = "types" self.el_type = CustomType self.el_name = self.col_match.group("name") return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradedb(options): """ Add 'fake' data migrations for existing tables from legacy GeoNode versions """
version = options.get('version') if version in ['1.1', '1.2']: sh("python manage.py migrate maps 0001 --fake") sh("python manage.py migrate avatar 0001 --fake") elif version is None: print "Please specify your GeoNode version" else: print "Upgrades from version %s are 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 package(options): """ Creates a tarball to use for building the system elsewhere """
import pkg_resources import tarfile import geonode version = geonode.get_version() # Use GeoNode's version for the package name. pkgname = 'GeoNode-%s-all' % version # Create the output directory. out_pkg = path(pkgname) out_pkg_tar = path("%s.tar.gz" % pkgname) # Create a di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deb(options): """ Creates debian packages. Example uses: paver deb paver deb -k 12345 paver deb -k 12345 -p geonode/testing """
key = options.get('key', None) ppa = options.get('ppa', None) version, simple_version = versions() info('Creating package for GeoNode version %s' % version) with pushd('package'): # Get rid of any uncommitted changes to debian/changelog info('Getting rid of any uncommitted change...
<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_comet(self): """Parse `targetname` as if it were a comet. :return: (string or None, int or None, string or None); The designation, number and prefix, a...
import re pat = ('^(([1-9]+[PDCXAI](-[A-Z]{1,2})?)|[PDCXAI]/)' + # prefix [0,1,2] '|([-]?[0-9]{3,4}[ _][A-Z]{1,2}([0-9]{1,3})?(-[1-9A-Z]{0,2})?)' + # designation [3,4] ('|(([A-Z][a-z]?[A-Z]*[a-z]*[ -]?[A-Z]?[1-9]*[a-z]*)' + '( [1-9A-Z]{1,2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isorbit_record(self): """`True` if `targetname` appears to be a comet orbit record number. NAIF record numbers are 6 digits, begin with a '9' and can change ...
import re test = re.match('^9[0-9]{5}$', self.targetname.strip()) is not None return test
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iscomet(self): """`True` if `targetname` appears to be a comet. """
# treat this object as comet if there is a prefix/number if self.comet is not None: return self.comet elif self.asteroid is not None: return not self.asteroid else: return (self.parse_comet()[0] is not None or self.parse_comet()[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 isasteroid(self): """`True` if `targetname` appears to be an asteroid."""
if self.asteroid is not None: return self.asteroid elif self.comet is not None: return not self.comet else: return any(self.parse_asteroid()) 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 set_epochrange(self, start_epoch, stop_epoch, step_size): """Set a range of epochs, all times are UT :param start_epoch: str; start epoch of the format 'YYYY...
self.start_epoch = start_epoch self.stop_epoch = stop_epoch self.step_size = step_size return 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 set_discreteepochs(self, discreteepochs): """Set a list of discrete epochs, epochs have to be given as Julian Dates :param discreteepochs: array_like list or...
if not isinstance(discreteepochs, (list, np.ndarray)): discreteepochs = [discreteepochs] self.discreteepochs = list(discreteepochs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_urls(self): """ Add the following array of urls to the resource base urls """
return [ url(r"^(?P<resource_name>%s)/view/(?P<name>[\w\d_.-]+)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('view'), name="api_fileitem_view"), url(r"^(?P<resource_name>%s)/download/(?P<name>[\w\d_.-]+)%s$" % ( self._meta.resource_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 set(self, attr_dict): """Sets attributes of this user object. :type attr_dict: dict :param attr_dict: Parameters to set, with attribute keys. :rtype: :class:...
for key in attr_dict: if key == self._id_attribute: setattr(self, self._id_attribute, attr_dict[key]) else: setattr(self, u"_" + key, attr_dict[key]) 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 security_warnings(request, PROXY_ALLOWED_HOSTS=()): """ Detects insecure settings and reports them to the client-side context. """
warnings = [] PROXY_ALLOWED_HOSTS = PROXY_ALLOWED_HOSTS or getattr(settings, 'PROXY_ALLOWED_HOSTS', ()) if PROXY_ALLOWED_HOSTS and '*' in PROXY_ALLOWED_HOSTS: warnings.append(dict(title=_('Insecure setting detected.'), description=_('A wildcard is included in the PRO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conv_units(val, meta): """ Format and convert units to be more human readable @return new val with converted units """
if not val or not meta: return val try: val = float(val) except ValueError: logging.error("unable to apply convert units for %s" % val) return val suf = 0 while val > 1024 and suf < 4: val /= 1024 suf += 1 return "%.2f%s" % (val, UNITS_SUFFIX[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 align(self, arr): """ Align columns, including column headers """
if arr is None: return arr c_hdrs = self._get_col_hdrs() if self.show_col_hdr_in_cell: for hdr in c_hdrs: arr[hdr] = map(lambda col: ":".join([hdr, str(col)]), arr[hdr]) if self.show_col_hdrs: widths = [max(len(str(col)) ...
<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(self, string, width): """ Wrap lines according to width Place '\n' whenever necessary """
if not string or width <= 0: logging.error("invalid string: %s or width: %s" % (string, width)) return False tmp = "" for line in string.splitlines(): if len(line) <= width: tmp += line + "\n" continue cur = 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_meta(self, row, col): """ Get metadata for a particular cell """
if self.meta is None: logging.error("unable to get meta: empty section") return {} if not row in self._get_row_hdrs() or\ not col in self._get_col_hdrs(): logging.error("unable to get meta: cell [%s,%s] does not exist" % (row, 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 in_function_call(self): """Return either completion information or a call signature for the function definition that we are on currently."""
#The last thing to do before we can form completions etc. is perform #a real-time update of the in-memory versions of the modules. if settings.real_time_update: cache.rt.update(self._user_context) return self._evaluator.in_function_call()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def goto_definitions(self): """ Return the definition of a the symbol under the cursor via exact match. Goes to that definition with a buffer. """
element = self._evaluator.get_definition() if element is not None: return BaseDefinition(self._user_context, element) else: return 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 order_module_dependencies(modules, parser): """Orders the specified list of modules based on their inter-dependencies."""
result = [] for modk in modules: if modk not in result: result.append(modk) #We also need to look up the dependencies of each of these modules recursed = list(result) for i in range(len(result)): module = result[i] _process_module_order(parser, module, 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 _process_module_order(parser, module, i, result): """Adds the module and its dependencies to the result list."""
#Some code might decide to use the fortpy module methods for general #development, ignore it since we know it will be present in the end. if module == "fortpy" or module == "fpy_auxiliary": return #See if the parser has alread loaded this module. if module not in parser.modules: 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 list_dependencies(self, module, result): """Lists the names of all the modules that the specified module depends on."""
if result is None: result = {} #We will try at least once to load each module that we don't have if module not in self.modules: self.load_dependency(module, True, True, False) if module in self.modules and module not in result: result[module] = 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 _parse_dependencies(self, pmodules, dependencies, recursive, greedy): """Parses the dependencies of the modules in the list pmodules. :arg pmodules: a list o...
#See if we need to also load dependencies for the modules if dependencies: allkeys = [ module.name.lower() for module in pmodules ] for key in allkeys: for depend in self.modules[key].collection("dependencies"): base = depend.split(".")[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 _parse_docstrings(self, filepath): """Looks for additional docstring specifications in the correctly named XML files in the same directory as the module."""
xmlpath = self.get_xmldoc_path(filepath) if self.tramp.exists(xmlpath): xmlstring = self.tramp.read(xmlpath) self.modulep.docparser.parsexml(xmlstring, self.modules, xmlpath)
<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_xmldoc_path(self, filepath): """Returns the full path to a possible XML documentation file for the specified code filepath."""
segs = filepath.split(".") segs.pop() return ".".join(segs) + ".xml"
<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_mod_mtime(self, filepath): """Gets the modified time of the file or its accompanying XML file, whichever is greater. """
file_mtime = self.tramp.getmtime(filepath) xmlpath = self.get_xmldoc_path(filepath) if self.tramp.exists(xmlpath): xml_mtime = self.tramp.getmtime(xmlpath) if xml_mtime > file_mtime: file_mtime = xml_mtime return file_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 _check_parse_modtime(self, filepath, fname): """Checks whether the modules in the specified file path need to be reparsed because the file was changed since ...
#We also want to perform a reparse if the XML documentation file for the #module changed, since the docs are also cached. file_mtime = self._get_mod_mtime(filepath) #If we have parsed this file and have its modules in memory, its #filepath will be in self._parsed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reparse(self, filepath): """Reparses the specified module file from disk, overwriting any cached representations etc. of the module."""
#The easiest way to do this is to touch the file and then call #the regular parse method so that the cache becomes invalidated. self.tramp.touch(filepath) self.parse(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 _add_current_codedir(self, path): """Adds the directory of the file at the specified path as a base path to find other files in. """
dirpath = self.tramp.dirname(path) if dirpath not in self.basepaths: self.basepaths.append(dirpath) self.rescan()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isense_parse(self, filepath, modulename): """Parses the specified file from either memory, cached disk or full disk depending on whether the fetch is via SSH...
#We only want to check whether the file has been modified for reload from datetime import datetime if modulename not in self._last_isense_check: self._last_isense_check[modulename] = datetime.utcnow() self.parse(filepath, True) else: elapsed = (dateti...
<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, filepath, dependencies=False, recursive=False, greedy=False): """Parses the fortran code in the specified file. :arg dependencies: if true, all f...
#If we have already parsed this file path, we should check to see if the #module file has changed and needs to be reparsed. abspath = self.tramp.abspath(filepath) self._add_current_codedir(abspath) fname = filepath.split("/")[-1].lower() mtime_check = self._check_parse_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rescan(self): """Rescans the base paths to find new code files."""
self._pathfiles = {} for path in self.basepaths: self.scan_path(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 load_dependency(self, module_name, dependencies, recursive, greedy, ismapping = False): """Loads the module with the specified name if it isn't already loade...
key = module_name.lower() if key not in self.modules: if key == "fortpy": #Manually specify the correct path to the fortpy.f90 that shipped with #the distribution from fortpy.utility import get_fortpy_templates_dir from os impo...
<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_greedy(self, module_name, dependencies, recursive): """Keeps loading modules in the filepaths dictionary until all have been loaded or the module is fo...
found = module_name in self.modules allmodules = list(self._pathfiles.keys()) i = 0 while not found and i < len(allmodules): current = allmodules[i] if not current in self._modulefiles: #We haven't tried to parse this file yet 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 scan_path(self, path, result = None): """Determines which valid fortran files reside in the base path. :arg path: the path to the folder to list f90 files in...
files = [] #Find all the files in the directory for (dirpath, dirnames, filenames) in self.tramp.walk(path): files.extend(filenames) break #Check if the .fpyignore file exists in the folder. patterns = [".#*"] if ".fpyignore" in files: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree_find(self, symbol, origin, attribute): """Finds the code element corresponding to specified symbol by searching all modules in the parser. :arg symbol: ...
#The symbol must be accessible to the origin module, otherwise #it wouldn't compile. Start there, first looking at the origin #itself and then the other modules that it depends on. #Since we will be referring to this multiple times, might as #well get a pointer to 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 get_executable(self, fullname): """Gets the executable corresponding to the specified full name. :arg fullname: a string with modulename.executable. """
result = None modname, exname = fullname.split(".") module = self.get(modname) if module is not None: if exname in module.executables: result = module.executables[exname] 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 get_interface(self, fullname): """Gets the interface corresponding to the specified full name. :arg fullname: a string with modulename.interface. """
result = None [modname, iname] = fullname.split(".") module = self.get(modname) if module is not None: if iname in module.interfaces: result = module.interfaces[iname] 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 get(self, name): """Gets the module with the given name if it exists in this code parser."""
if name not in self.modules: self.load_dependency(name, False, False, False) if name in self.modules: return self.modules[name] else: return 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 get_bucket(self, key, rate=None, capacity=None, **kwargs): """Fetch a Bucket for the given key. rate and capacity might be overridden from the Throttler defa...
return buckets.Bucket( key=key, rate=rate or self.rate, capacity=capacity or self.capacity, storate=self.storate, **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 consume(self, key, amount=1, rate=None, capacity=None, **kwargs): """Consume an amount for a given key. Non-default rate/capacity can be given to override Th...
bucket = self.get_bucket(key, rate, capacity, **kwargs) return bucket.consume(amount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def throttle(self, key, amount=1, rate=None, capacity=None, exc_class=Throttled, **kwargs): """Consume an amount for a given key, or raise a Throttled exception....
if not self.consume(key, amount, rate, capacity, **kwargs): raise exc_class("Request of %d unit for %s exceeds capacity." % (amount, key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def leak(self): """Leak the adequate amount of data from the bucket. This should be called before any consumption takes place. Returns: int: the new capacity of ...
capacity, last_leak = self.storage.mget(self.key_amount, self.key_last_leak, coherent=True) now = time.time() if last_leak: elapsed = now - last_leak decrement = elapsed * self.rate new_capacity = max(int(capacity - decrement), 0) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self, amount=1): """Consume one or more units from the bucket."""
# First, cleanup old stock current = self.leak() if current + amount > self.capacity: return False self._incr(amount) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, entry_point): """Register a converter :param string entry_point: converter to register (entry point syntax) :raise: ValueError if already regi...
if entry_point in self.registered_converters: raise ValueError('Already registered') self.registered_converters.insert(0, entry_point)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(): """Parses all the modules in the library specified by the script args. """
from fortpy.code import CodeParser c = CodeParser() if args["verbose"]: c.verbose = True f90files = {} c.scan_path(args["source"], f90files) for fname, fpath in f90files.items(): if fname not in c._modulefiles: c._modulefiles[fname] = [] c._parse_from_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 _check_pointers(parser): """Checks the pointer best-practice conditions."""
from fortpy.stats.bp import check_pointers check_pointers(parser, args["source"], args["filter"], args["recursive"])
<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): """Regex definitions for parsing the code elements."""
self._RX_INTERFACE = (r"\n\s*interface\s+(?P<name>[a-z0-9_]+)(\s\((?P<symbol>[.\w+*=/-]+)\))?" r"(?P<contents>.+?)" r"end\s*interface\s+(?P=name)?") self.RE_INTERFACE = re.compile(self._RX_INTERFACE, re.I | re.DOTALL)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_docs(self, iface, module): """Updates the documentation for the specified interface using the module predocs."""
#We need to look in the parent module docstrings for this types decorating tags. key = "{}.{}".format(module.name, iface.name) if key in module.predocs: iface.docstring = self.docparser.to_doc(module.predocs[key][0], iface.name) iface.docstart, iface.docend = (mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makefile(identifier, dependencies, makepath, compileid, precompile=False, inclfortpy=True, parser=None, executable=True, extralinks=None, inclfpyaux=False, ma...
lines = [] #Append the general variables lines.append("EXENAME\t\t= {}.x".format(identifier)) lines.append("SHELL\t\t= /bin/bash") lines.append("UNAME\t\t= $(shell uname)") lines.append("HOSTNAME\t= $(shell hostname)") lines.append("LOG\t\t= compile.{}.log".format(identifier if identifier ...
<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_explicit_includes(lines, dependencies=None, extralinks=None): """Adds any relevant libraries that need to be explicitly included according to the fortpy...
from fortpy import config import sys from os import path includes = sys.modules["config"].includes linklibs = False if extralinks is not None and len(extralinks) > 0: for i, link in enumerate(extralinks): lines.append("LBD{0:d} = {1}".format(i, link)) 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 _get_mapping(parser, mapped): """Gets the original file name for a module that was mapped when the module name does not coincide with the file name that the ...
if mapped in parser.mappings: return parser.mappings[mapped] else: return mapped + ".f90"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(self, overrides): """ Patches the config with the given overrides. Example: If the current dictionary looks like this: a: 1, b: { c: 3, d: 4 } and `pat...
overrides = overrides or {} for key, value in iteritems(overrides): current = self.get(key) if isinstance(value, dict) and isinstance(current, dict): current.patch(value) else: self[key] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_controller_info(self): """ Pulls controller information. :returns: True if successfull, otherwise False. :rtype: boolean """
# Read the controller information. self.controller_info = customer_details(self._user_token) self.controller_status = status_schedule(self._user_token) if self.controller_info is None or self.controller_status is None: return False # Only supports one controller r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def controller(self): """ Check if multiple controllers are connected. :returns: Return the controller_id of the active controller. :rtype: string """
if hasattr(self, 'controller_id'): if len(self.controller_info['controllers']) > 1: raise TypeError( 'Only one controller per account is supported.' ) return self.controller_id raise AttributeError('No controllers assigned 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 relay_info(self, relay, attribute=None): """ Return information about a relay. :param relay: The relay being queried. :type relay: int :param attribute: The ...
# Check if the relay number is valid. if (relay < 0) or (relay > (self.num_relays - 1)): # Invalid relay index specified. return None else: if attribute is None: # Return all the relay attributes. return self.relays[relay] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suspend_zone(self, days, zone=None): """ Suspend or unsuspend a zone or all zones for an amount of time. :param days: Number of days to suspend the zone(s) :...
if zone is None: zone_cmd = 'suspendall' relay_id = None else: if zone < 0 or zone > (len(self.relays) - 1): return None else: zone_cmd = 'suspend' relay_id = self.relays[zone]['relay_id'] # If days...
<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_zone(self, minutes, zone=None): """ Run or stop a zone or all zones for an amount of time. :param minutes: The number of minutes to run. :type minutes: i...
if zone is None: zone_cmd = 'runall' relay_id = None else: if zone < 0 or zone > (len(self.relays) - 1): return None else: zone_cmd = 'run' relay_id = self.relays[zone]['relay_id'] if minutes <= 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 list_running_zones(self): """ Returns the currently active relay. :returns: Returns the running relay number or None if no relays are active. :rtype: string ...
self.update_controller_info() if self.running is None or not self.running: return None return int(self.running[0]['relay'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_zone_running(self, zone): """ Returns the state of the specified zone. :param zone: The zone to check. :type zone: int :returns: Returns True if the zone ...
self.update_controller_info() if self.running is None or not self.running: return False if int(self.running[0]['relay']) == zone: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_remaining(self, zone): """ Returns the amount of watering time left in seconds. :param zone: The zone to check. :type zone: int :returns: If the zone is...
self.update_controller_info() if zone < 0 or zone > (self.num_relays-1): return None if self.is_zone_running(zone): return int(self.running[0]['time_left']) return 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 cache(self): """Memoize access to the cache backend."""
if self._cache is None: self._cache = django_cache.get_cache(self.cache_name) return self._cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element(self): """Returns the instance of the element who owns the first line number for the operation in the cached source code."""
#We assume here that the entire operation is associated with a single #code element. Since the sequence matcher groups operations by contiguous #lines of code to change, this is a safe assumption. if self._element is None: line = self.icached[0] #If we are insert...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def docelement(self): """Returns the instance of the element whose body owns the docstring in the current operation. """
#This is needed since the decorating documentation #for types and executables is in the body of the module, but when they #get edited, the edit belongs to the type/executable because the character #falls within the absstart and end attributes. if self._docelement is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self): """Handles the real time update of some code from the cached representation of the module. """
#If we have more statements in the buffer than the cached, it doesn't matter, #we just run the first few replacements of the cache concurrently and do #what's left over from the buffer. #REVIEW if self.mode == "insert": #then self.icached[0] == self.icached[1]: #We...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_docstrings(self): """Searches through the lines affected by this operation to find blocks of adjacent docstrings to parse for the current element. ""...
#Docstrings have to be continuous sets of lines that start with !! #When they change in any way (i.e. any of the three modes), we #have to reparse the entire block because it has XML dependencies #Because of that, the cached version of the docstrings is actually #pointless and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _docstring_parse(self, blocks): """Parses the XML from the specified blocks of docstrings."""
result = {} for block, docline, doclength, key in blocks: doctext = "<doc>{}</doc>".format(" ".join(block)) try: docs = ET.XML(doctext) docstart = self.parser.charindex(docline, 0, self.context) if not key in 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 _docstring_getblocks(self): """Gets the longest continuous block of docstrings from the buffer code string if any of those lines are docstring lines. """
#If there are no lines to look at, we have nothing to do here. if self.ibuffer[0] == self.ibuffer[1]: return [] lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]] docblock = [] result = [] self._doclines = [] #We need to keep track of 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 _docstring_key(self, line): """Returns the key to use for the docblock immediately preceding the specified line."""
decormatch = self.docparser.RE_DECOR.match(line) if decormatch is not None: key = "{}.{}".format(self.docelement.name, decormatch.group("name")) else: key = self.element.name return key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_extent(self): """Updates the extent of the element being altered by this operation to include the code that has changed."""
#For new instances, their length is being updated by the module #updater and will include *all* statements, so we don't want to #keep changing the endpoints. if self.bar_extent: return original = self.element.end if self.mode == "insert": ...
<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_buffered(self): """Gets a list of the statements that are new for the real time update."""
lines = self.context.bufferstr[self.ibuffer[0]:self.ibuffer[1]] return self._get_statements(lines, self.ibuffer[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_cached(self): """Gets a list of statements that the operation will affect during the real time update."""
lines = self.context.cachedstr[self.icached[0]:self.icached[1]] return self._get_statements(lines, self.icached[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 update(self, context): """Updates all references in the cached representation of the module with their latest code from the specified source code string that...
#Get a list of all the operations that need to be performed and then #execute them. self._operations = self._get_operations(context) for i in range(len(self._operations)): self._operations[i].handle() self.update_extent(self._operations[i]) #Last of all...
<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_operations(self, context): """Returns a list of operations that need to be performed to turn the cached source code into the one in the buffer."""
#Most of the time, the real-time update is going to fire with #incomplete statements that don't result in any changes being made #to the module instances. The SequenceMatches caches hashes for the #second argument. Logically, we want to turn the cached version into #the buffer 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 update_instance_extent(self, instance, module, operation): """Updates a new instance that was added to a module to be complete if the end token is present in...
#Essentially, we want to look in the rest of the statements that are #part of the current operation to see how many more of them pertain #to the new instance that was added. #New signatures only result in instances being added if mode is "insert" #or "replace". In both cases, ...
<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_end_token(self, end_token, operation): """Looks for a statement in the operation's list that matches the specified end token. Returns the index of the ...
ibuffer, icache = operation.state length = operation.buffered[ibuffer][2] result = None for i in range(len(operation.buffered) - ibuffer - 1): linenum, statement, charlength = operation.buffered[i + ibuffer + 1] length += charlength if e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mget(self, *keys, **kwargs): """Retrieve values for a set of keys. Args: keys (str list): the list of keys whose value should be retrieved Keyword arguement...
default = kwargs.get('default') coherent = kwargs.get('coherent', False) for key in keys: yield self.get(key, default=default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mset(self, values): """Set the value of several keys at once. Args: values (dict): maps a key to its value. """
for key, value in values.items(): self.set(key, 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 names(self): """Returns a list of possible completions for the symbol under the cursor in the current user context."""
#This is where the context information is extremely useful in #limiting the extent of the search space we need to examine. if self._names is None: attribute = self.get_attribute() if self.context.module is not None: symbol = self.context.symbol ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bracket_complete(self): """Returns a function call signature for completion whenever a bracket '(' is pressed."""
#The important thing to keep track of here is that '(' can be #pushed in the following places: # - in a subroutine/function definition # - when calling a function or subroutine, this includes calls within # the argument list of a function, e.g. function(a, fnb(c,d), e) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bracket_complete_sig(self, symbol, fullsymbol): """Returns the call signature and docstring for the executable immediately preceding a bracket '(' that was ...
if symbol != fullsymbol: #We have a sym%sym%... chain and the completion just needs to #be the signature of the member method. target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol) if symbol in target.executables: child = target.exe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bracket_dim_suggest(self, variable): """Returns a dictionary of documentation for helping complete the dimensions of a variable."""
if variable is not None: #Look for <dimension> descriptors that are children of the variable #in its docstrings. dims = variable.doc_children("dimension", ["member", "parameter", "local"]) descript = str(variable) if len(dims) > 0: des...