code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if status: self.logger.error(message) if self.__parser__: # pylint: disable-msg=E1101 self.__parser__.exit(status, message) # pylint: disable-msg=E1101 else: sys.exit(status)
def exit(self, status=0, message=None)
Delegates to `ArgumentParser.exit`
2.89553
2.651602
1.091992
if self.__parser__: # pylint: disable-msg=E1101 self.__parser__.error(message) # pylint: disable-msg=E1101 else: self.logger.error(message) sys.exit(2)
def error(self, message=None)
Delegates to `ArgumentParser.error`
3.304317
2.763917
1.19552
if not args: args = self.parse(sys.argv[1:]) if getattr(args, 'verbose', False): self.logger.setLevel(logging.DEBUG) try: if hasattr(args, 'run'): args.run(self, args) else: self.__main__(args) # pylint:...
def run(self, args=None)
Runs the main command or sub command based on user input
2.336459
2.358166
0.990795
if "versions" in element.attrib: result = [ int(v) for v in re.split(",\s*", element.attrib["versions"]) ] else: result = [ 1 ] return result
def _get_xml_version(element)
Extracts a list of versions that an xml element references. Returns a [ 1 ] list if there isn't a versions attribute.
4.014712
2.975388
1.349307
if self._nvalues is None: self._nvalues = 0 for val in self.values: if type(val) == type(int): self._nvalues += val else: self._nvalues = -1 break return self._nvalues
def nvalues(self)
Returns the number of values recorded on this single line. If the number is variable, it returns -1.
2.835514
2.518773
1.125752
if self.identifier in valuedict: value = valuedict[self.identifier] elif self.default is not None: value = self.default elif self.fromtag is not None and self.fromtag in valuedict: if self.operator == "count": value = len(valuedict[sel...
def write(self, valuedict)
Returns the lines that this template line should add to the input file.
4.220599
4.096836
1.030209
result = [] if element.text is not None and element.tag == self.identifier: l, k = (0, 0) raw = element.text.split() while k < len(self.values): dtype = self.dtype[k] if isinstance(self.values[k], int): for ...
def parse(self, element)
Parses the contents of the specified XML element using template info. :arg element: the XML element from the input file being converted.
5.42907
5.492238
0.988499
try: return int(value) except ValueError: msg.err("Cannot convert {} to int for line {}.".format(value, self.identifier)) exit(1)
def _cast_int(self, value)
Returns the specified value as int if possible.
6.277752
5.97418
1.050814
try: return float(value) except ValueError: msg.err("Cannot convert {} to float for line {}.".format(value, self.identifier)) exit(1)
def _cast_float(self, value)
Returns the specified value as float if possible.
6.16002
5.904043
1.043356
for child in element: if "id" in child.attrib: tline = TemplateLine(child, self, commentchar) self.order.append(tline.identifier) self.lines[tline.identifier] = tline else: msg.warn("no id element in {}....
def _load(self, element, commentchar)
Loads all the child line elements from the XML group element.
6.860616
5.687433
1.206276
#All the children of this element are what we are trying to parse. result = [] for child in element: if child.tag in self.lines: values = { child.tag: self.lines[child.tag].parse(child) } result.append(values) return result
def parse(self, element)
Extracts the values from the specified XML element that is being converted.
5.316248
4.911165
1.082482
result = [] if self.identifier in valuedict: values = valuedict[self.identifier] else: return result if self.comment != "": result.append(self.comment) if self.repeat is not None and type(values) == type([]): if self.repe...
def write(self, valuedict)
Generates the lines for the converted input file using the specified value dictionary.
4.011741
3.928377
1.021221
result = [] for key in self.order: result.append(self.lines[key].write(values)) if len(result) > 1: return result else: return result[0]
def _write_iterate(self, values)
Generates the lines for a single pass through the group.
3.650089
3.158543
1.155624
if os.path.exists(self.path): root = ET.parse(self.path).getroot() if (root.tag == "fortpy" and "mode" in root.attrib and root.attrib["mode"] == "template" and "direction" in root.attrib and root.attrib["direction"] == self.direction): ...
def _load(self)
Extracts the XML template data from the file.
4.898704
4.500932
1.088375
#Use the first element in the versions list since there should only be one. v = _get_xml_version(root)[0] result = {} for child in root: if child.tag in self.versions[v].entries: entry = self.versions[v].entries[child.tag] #E...
def parse(self, root)
Returns a dictionary of values extracted from the root of the specified XML file. It is assumed that the file is an input/output file to be converted into plaintext. As such the file should only specify a single version number.
6.220553
5.931316
1.048764
result = [] if version in self.versions: for tag in self.versions[version].order: entry = self.versions[version].entries[tag] result.extend(entry.write(valuedict)) return result
def write(self, valuedict, version)
Generates the lines for the converted input file from the valuedict. :arg valuedict: a dictionary of values where the keys are ids in the template and the values obey their template rules. :arg version: the target version of the output file.
3.846831
4.204726
0.914883
mdict = { "comments": self._comment, "line": self._line, "group": self._group } for entry in root: mdict[entry.tag](entry)
def _load_entries(self, root)
Loads all the child entries of the input template from the specified root element.
5.866498
5.557008
1.055694
for v in _get_xml_version(element): self.versions[v].comment = element.text
def _comment(self, element)
Extracts the character to use for comments in the input file.
11.180124
9.971203
1.121241
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: ...
def _line(self, element)
Parses the XML element as a single line entry in the input file.
7.550661
6.816339
1.10773
for v in _get_xml_version(element): if "name" in element.attrib: g = TemplateGroup(element, self.versions[v].comment) self.versions[v].entries[g.identifier] = g self.versions[v].order.append(g.identifier) else: msg....
def _group(self, element)
Parses the XML element as a group of [unknown] number of lines.
7.835656
7.263819
1.078724
#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: ...
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. :arg version: the new version of the file. :arg target: the optional path to save the file under. If not specified, the file is saved based on the template file name.
5.345746
5.504974
0.971076
#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)
def parse(self, path)
Extracts a dictionary of values from the XML file at the specified path.
10.580302
9.419211
1.123268
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 ...
def convert(self, path, version, target)
Converts the specified source file to a new version number.
4.902158
4.860523
1.008566
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
def cachedstr(self)
Returns the full string of the file contents from the cache for the file that we are currently providing intellisense for.
3.814622
3.484383
1.094777
#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 ...
def exact_match(self)
Returns the symbol under the cursor looking both directions as part of a definition lookup for an exact match.
3.798259
3.576088
1.062127
if self._short_symbol is None: self._short_symbol = self._symbol_extract(cache.RE_CURSOR, False) return self._short_symbol
def short_symbol(self)
Gets the symbol for the current cursor *excluding* the last character under the cursor.
8.96088
7.461207
1.200996
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
def short_full_symbol(self)
Gets the full symbol excluding the character under the cursor.
7.51372
6.070915
1.237658
if self._symbol is None: self._symbol = self._symbol_extract(cache.RE_CURSOR) return self._symbol
def symbol(self)
Gets the symbol under the current cursor.
12.346995
9.892556
1.24811
if self._full_symbol is None: self._full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR, brackets=True) return self._full_symbol
def full_symbol(self)
Returns the symbol under the cursor AND additional contextual symbols in the case of %-separated lists of type members.
9.620126
8.618626
1.116202
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,...
def _symbol_extract(self, regex, plus = True, brackets=False)
Extracts a symbol or full symbol from the current line, optionally including the character under the cursor. :arg regex: the compiled regular expression to use for extraction. :arg plus: when true, the character under the cursor *is* included. :arg brackets: when true, matching pairs o...
5.6665
5.561189
1.018937
#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 e...
def call_arg_index(self)
Determines the index of the parameter in a call list using string manipulation and context information.
9.110912
8.909601
1.022595
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
def _setup_regex(self)
Sets up the constant regex strings etc. that can be used to parse the strings for determining context.
3.637145
3.392094
1.072242
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...
def _contextualize(self)
Finds values for all the important attributes that determine the user's context.
7.77251
7.253904
1.071493
#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...
def _get_module(self, line)
Finds the name of the module and retrieves it from the parser cache.
7.83339
7.618702
1.028179
#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....
def _deep_match(self, line, column)
Checks the contents of executables, types and modules for member definitions and updates the context.
6.294716
6.144338
1.024474
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(...
def _match_exec(self, i)
Looks at line 'i' for a subroutine or function definition.
4.027009
3.257876
1.236084
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: ...
def _match_member(self, i, column)
Looks at line 'i' to see if the line matches a module member def.
5.886937
5.079061
1.15906
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
def _match_type(self, i)
Looks at line 'i' to see if the line matches a module user type def.
5.43015
4.788219
1.134065
fast = options.get('fast', False) download_dir = path('downloaded') if not download_dir.exists(): download_dir.makedirs() geoserver_dir = path('geoserver') geoserver_bin = path('geoserver_ext/target/geoserver.war') if not geoserver_bin.exists(): geoserver_bin = download_di...
def setup_geoserver(options)
Prepare a testing instance of GeoServer.
3.476152
3.442972
1.009637
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 ar...
def upgradedb(options)
Add 'fake' data migrations for existing tables from legacy GeoNode versions
5.247845
4.423661
1.186313
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 ...
def package(options)
Creates a tarball to use for building the system elsewhere
3.982131
3.920982
1.015595
from geonode.settings import OGC_SERVER GEOSERVER_BASE_URL = OGC_SERVER['default']['LOCATION'] url = "http://localhost:8080/geoserver/" if GEOSERVER_BASE_URL != url: print 'your GEOSERVER_BASE_URL does not match %s' % url sys.exit(1) download_dir = path('downloaded').abspath...
def start_geoserver(options)
Start GeoServer with GeoNode extensions
5.070084
5.044855
1.005001
import gisdata ctype = options.get('type', None) data_dir = gisdata.GOOD_DATA if ctype in ['vector', 'raster', 'time']: data_dir = os.path.join(gisdata.GOOD_DATA, ctype) sh("python manage.py importlayers %s -v2" % data_dir)
def setup_data()
Import sample data (from gisdata package) into GeoNode
7.257687
5.83585
1.243638
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 ch...
def deb(options)
Creates debian packages. Example uses: paver deb paver deb -k 12345 paver deb -k 12345 -p geonode/testing
5.938313
5.965128
0.995505
if char.isdigit(): return int(float(char)) if char.isupper(): return int(char, 36) else: return 26 + int(char, 36)
def _char2int(char)
translate characters to integer values (upper and lower case)
3.017328
2.787525
1.08244
import re test = re.match('^9[0-9]{5}$', self.targetname.strip()) is not None return test
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 at any time.
10.87898
5.031351
2.162238
# 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_c...
def iscomet(self)
`True` if `targetname` appears to be a comet.
6.609607
5.847558
1.130319
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
def isasteroid(self)
`True` if `targetname` appears to be an asteroid.
5.048578
4.854096
1.040066
self.start_epoch = start_epoch self.stop_epoch = stop_epoch self.step_size = step_size return None
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-MM-DD [HH-MM-SS]' :param stop_epoch: str; final epoch of the format 'YYYY-MM-DD [HH-MM-SS]' :param step_size: str; epoch step size, e.g., '1d' for 1 day, '10m' for 1...
2.175798
2.604079
0.835534
if not isinstance(discreteepochs, (list, np.ndarray)): discreteepochs = [discreteepochs] self.discreteepochs = list(discreteepochs)
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 1D array of floats or strings :return: None :example: >>> import callhorizons >>> ceres = callhorizons.query('Ceres') >>> ceres...
2.986676
3.763852
0.793516
try: import ephem except ImportError: raise ImportError( 'export2pyephem requires PyEphem to be installed') # obtain orbital elements self.get_elements(center) objects = [] for el in self.data: n = 0.98560766...
def export2pyephem(self, center='500@10', equinox=2000.)
Call JPL HORIZONS website to obtain orbital elements based on the provided targetname, epochs, and center code and create a PyEphem (http://rhodesmill.org/pyephem/) object. This function requires PyEphem to be installed. :param center: str; center body (default: 500@10 = Sun)...
4.634825
4.490254
1.032196
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.resour...
def prepend_urls(self)
Add the following array of urls to the resource base urls
1.446901
1.433086
1.00964
''' example use: http://.../fileservice/download/med.mp4/ or http://.../fileservice/med.mp4/download/ ''' # method check to avoid bad requests self.method_check(request, allowed=['get']) # Must be done otherwise endpoint will be wide open s...
def download(self, request, **kwargs)
example use: http://.../fileservice/download/med.mp4/ or http://.../fileservice/med.mp4/download/
4.520545
3.215358
1.405923
''' allow a file to be viewed as opposed to download. This is particularly needed when a video file is stored in the fileservice and user wants to be able to use a view the video as opposed to having to download it first. It passes the serving of the file to nginx/apache which will retur...
def view(self, request, **kwargs)
allow a file to be viewed as opposed to download. This is particularly needed when a video file is stored in the fileservice and user wants to be able to use a view the video as opposed to having to download it first. It passes the serving of the file to nginx/apache which will return all the proper hea...
8.489393
2.042559
4.156253
def inner(func): cached_name = '_' + func.__name__ @functools.wraps(func) def _decorator(self, *args, **kwargs): if getattr(self, cached_name) is None: getattr(self, func_name)() return func(self, *args, **kwargs) return _decorator return inner
def loadable(func_name)
Decorator for getters that require a load() upon first access. :type func_name: function :param func_name: class method that requires that load() be called if the class's _attribute value is None :rtype: function :return: the decorated class method.
2.212755
2.517694
0.878882
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
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:`.Base` :return: The current object.
3.244757
3.752319
0.864734
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...
def security_warnings(request, PROXY_ALLOWED_HOSTS=())
Detects insecure settings and reports them to the client-side context.
3.484992
3.123572
1.115707
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_SUFF...
def conv_units(val, meta)
Format and convert units to be more human readable @return new val with converted units
3.082843
3.060008
1.007463
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)) ...
def align(self, arr)
Align columns, including column headers
2.686319
2.558189
1.050086
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...
def wrap(self, string, width)
Wrap lines according to width Place '\n' whenever necessary
2.912767
2.950716
0.987139
if arr is None: logging.error("unable to convert data: emtpy section") return None tmp = np.copy(arr) for col in arr.dtype.names: for row in self._get_row_hdrs(): meta = self._get_meta(row, col) for mk, mv in sorted(me...
def apply_meta(self, arr, funcs)
Apply metadata to help formatting the output: - conv_funcs: convert data before column alignments - deco_funcs: decorate data after column alignments
5.44819
5.758156
0.946169
self.show_row_hdrs = show_row_hdrs self.show_col_hdrs = show_col_hdrs self.show_col_hdr_in_cell = show_col_hdr_in_cell
def config(self, show_row_hdrs=True, show_col_hdrs=True, show_col_hdr_in_cell=False, auto_resize=True)
Override the in-class params: @param show_row_hdrs : show row headers @param show_col_hdrs : show column headers @param show_col_hdr_in_cell : embed column header in each cell @param auto_resize : auto resize according to the size of terminal
1.354363
1.457847
0.929016
if self.arr is None: self.arr = np.array( [(row, val)], dtype=[ (self.name, "S50"), (col, type)]) self.meta = np.array( [(row, val)], dtype=[ (self.name, TYPE_META), (col, type)]) self.irt[row] = 0 if not row in self._get_row_...
def add_cell(self, row="unknown", col="unknown", val="unknown", type="int32", meta="")
Add/update a val on cell [row, col] Create new rows or columns accordingly @param row : row header name @param col : column header name @param meta: meta data to control data display
3.981762
4.277986
0.930756
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" %...
def _get_meta(self, row, col)
Get metadata for a particular cell
3.32102
3.259376
1.018913
#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()
def in_function_call(self)
Return either completion information or a call signature for the function definition that we are on currently.
20.068319
17.438795
1.150786
debug.speed('completions start') comps = self._evaluator.complete() debug.speed('completions end') return sorted(comps, key=lambda x: (x.name.lower()))
def completions(self)
Return :class:`classes.Completion` objects. Those objects contain information about the completions, more than just names. :return: Completion objects, sorted by name. :rtype: list of :class:`classes.Completion`
7.304748
7.435178
0.982458
element = self._evaluator.get_definition() if element is not None: return BaseDefinition(self._user_context, element) else: return None
def goto_definitions(self)
Return the definition of a the symbol under the cursor via exact match. Goes to that definition with a buffer.
8.335505
7.640711
1.090933
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, modul...
def order_module_dependencies(modules, parser)
Orders the specified list of modules based on their inter-dependencies.
5.169157
5.209692
0.992219
#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: ...
def _process_module_order(parser, module, i, result)
Adds the module and its dependencies to the result list.
6.088989
6.053656
1.005837
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]...
def list_dependencies(self, module, result)
Lists the names of all the modules that the specified module depends on.
3.926581
3.660908
1.07257
#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("."...
def _parse_dependencies(self, pmodules, dependencies, recursive, greedy)
Parses the dependencies of the modules in the list pmodules. :arg pmodules: a list of modules that were parsed from a *.f90 file. :arg dependencies: when true, the dependency's dependencies will be loaded. :arg recursive: specifies whether to continue loading dependencies to completi...
6.799482
6.906781
0.984465
xmlpath = self.get_xmldoc_path(filepath) if self.tramp.exists(xmlpath): xmlstring = self.tramp.read(xmlpath) self.modulep.docparser.parsexml(xmlstring, self.modules, xmlpath)
def _parse_docstrings(self, filepath)
Looks for additional docstring specifications in the correctly named XML files in the same directory as the module.
7.696195
6.748644
1.140406
segs = filepath.split(".") segs.pop() return ".".join(segs) + ".xml"
def get_xmldoc_path(self, filepath)
Returns the full path to a possible XML documentation file for the specified code filepath.
4.648443
4.312774
1.077831
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
def _get_mod_mtime(self, filepath)
Gets the modified time of the file or its accompanying XML file, whichever is greater.
3.29472
2.838232
1.160835
#Now that we have the file contents, we can parse them using the parsers string = self.tramp.read(filepath) pmodules = self.modulep.parse(string, self, filepath=filepath) file_mtime = self._get_mod_mtime(filepath) for module in pmodules: module.change_time =...
def _parse_from_file(self, filepath, fname, dependencies, recursive, greedy)
Parses the specified string to load the modules *from scratch* as opposed to loading pickled versions from the file cache.
4.587936
4.500835
1.019352
#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...
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 it was last loaded.
5.961415
5.73852
1.038842
#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)
def reparse(self, filepath)
Reparses the specified module file from disk, overwriting any cached representations etc. of the module.
10.374023
10.041565
1.033108
dirpath = self.tramp.dirname(path) if dirpath not in self.basepaths: self.basepaths.append(dirpath) self.rescan()
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.
5.690538
4.431227
1.28419
#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 =...
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 or not and how long it has been since we last checked the modification time of the file.
3.012382
2.682013
1.123179
#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...
def parse(self, filepath, dependencies=False, recursive=False, greedy=False)
Parses the fortran code in the specified file. :arg dependencies: if true, all folder paths will be searched for modules that have been referenced but aren't loaded in the parser. :arg greedy: if true, when a module cannot be found using a file name of module_name.f90, all modules in al...
3.755806
3.817218
0.983912
self._pathfiles = {} for path in self.basepaths: self.scan_path(path)
def rescan(self)
Rescans the base paths to find new code files.
11.983215
6.71106
1.785592
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...
def load_dependency(self, module_name, dependencies, recursive, greedy, ismapping = False)
Loads the module with the specified name if it isn't already loaded.
6.50416
6.432275
1.011176
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 ...
def _load_greedy(self, module_name, dependencies, recursive)
Keeps loading modules in the filepaths dictionary until all have been loaded or the module is found.
4.992851
4.344527
1.149228
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 ...
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. :arg result: an optional dictionary to add results to in addition to populating the private member dictionary of the parser.
3.478569
3.376858
1.03012
symbols = symbolstr.split("%") base, basemod = self.tree_find(basetype, origin, "types") #As long as we keep finding child objects, we can continue #until we run out of symbols in the list i = 1 while isinstance(base, CustomType) and i < len(symbols): ...
def type_search(self, basetype, symbolstr, origin)
Recursively traverses the module trees looking for the final code element in a sequence of %-separated symbols. :arg basetype: the type name of the first element in the symbol string. :arg symblstr: a %-separated list of symbols, e.g. this%sym%sym2%go. :arg origin: an instance of the Mo...
5.317668
5.434281
0.978541
#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. ...
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 name of the code element to find. :arg origin: an instance of a Module element who owns the text that is generate the find search. :arg attribute: one of ['depende...
6.046741
6.293439
0.960801
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
def get_executable(self, fullname)
Gets the executable corresponding to the specified full name. :arg fullname: a string with modulename.executable.
3.85764
3.642369
1.059102
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
def get_interface(self, fullname)
Gets the interface corresponding to the specified full name. :arg fullname: a string with modulename.interface.
3.324065
3.828967
0.868136
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
def get(self, name)
Gets the module with the given name if it exists in this code parser.
3.962361
3.54634
1.11731
return buckets.Bucket( key=key, rate=rate or self.rate, capacity=capacity or self.capacity, storate=self.storate, **kwargs)
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 defaults. Args: rate (float): Units regenerated by second, or None to keep Throttler defaults capacity (int): Maximum units available, or None to keep Throttler ...
3.509027
4.237638
0.828062
bucket = self.get_bucket(key, rate, capacity, **kwargs) return bucket.consume(amount)
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 Throttler defaults. Returns: bool: whether the units could be consumed
3.503678
5.357769
0.653943
if not self.consume(key, amount, rate, capacity, **kwargs): raise exc_class("Request of %d unit for %s exceeds capacity." % (amount, key))
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.
5.373909
5.269932
1.01973
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) ...
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 the bucket
3.99358
4.152028
0.961838
# First, cleanup old stock current = self.leak() if current + amount > self.capacity: return False self._incr(amount) return True
def consume(self, amount=1)
Consume one or more units from the bucket.
17.948177
17.145456
1.046818
if entry_point in self.registered_converters: raise ValueError('Already registered') self.registered_converters.insert(0, entry_point)
def register(self, entry_point)
Register a converter :param string entry_point: converter to register (entry point syntax) :raise: ValueError if already registered
4.22254
3.589857
1.176242
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_fr...
def parse()
Parses all the modules in the library specified by the script args.
6.24191
6.183032
1.009523
from fortpy.stats.bp import check_pointers check_pointers(parser, args["source"], args["filter"], args["recursive"])
def _check_pointers(parser)
Checks the pointer best-practice conditions.
22.102394
17.83396
1.239343
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)
def setup_regex(self)
Regex definitions for parsing the code elements.
5.791682
5.153804
1.123768
for iface in self.RE_INTERFACE.finditer(parent.preamble): name = iface.group("name") symbol = iface.group("symbol") contents = iface.group("contents") result = Interface(name, [], parent, symbol) self._parse_procedures(contents, result) ...
def parse(self, parent)
Parses any interfaces out of the module preamble which is the pre-contains section of the program or module. :arg parent: the ancle.elements.Module instance that will own the interfaces that get parsed from the module.
7.11944
6.547891
1.087287
#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.doce...
def update_docs(self, iface, module)
Updates the documentation for the specified interface using the module predocs.
7.425652
6.611734
1.123102