code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
while True: text = compat.input('ctl > ') command, args = self.parse_input(text) if not command: continue response = self.call(command, *args) response.show()
def loop(self)
Enter loop, read user input then run command. Repeat
7.199159
6.067501
1.186511
uri = str(uri) if uri not in namespaces.values(): namespaces[AnonNS().ns] = uri return [k for k, v in namespaces.items() if uri == v][0]
def namespace_for(uri: Union[URIRef, Namespace, str]) -> str
Reverse namespace lookup. Note that returned namespace may not be unique :param uri: namespace URI :return: namespace
6.909273
6.627646
1.042493
# Cleanup text text = text.strip() text = re.sub('\s+', ' ', text) # collpse multiple spaces space, quote, parts = ' ', '"', [] part, quoted = '', False for char in text: # Encoutered beginning double quote if char is quote and quoted is False: quoted = True...
def split(text)
Split text into arguments accounting for muti-word arguments which are double quoted
3.29294
3.121193
1.055026
return sorted([name for name, kind in plugin._plugins.keys() if kind == use and (include_mime_types or '/' not in name)])
def known_formats(use: Union[Serializer, Parser]=Serializer, include_mime_types: bool = False) -> List[str]
Return a list of available formats in rdflib for the required task :param use: task (typically Serializer or Parser) :param include_mime_types: whether mime types are included in the return list :return: list of formats
9.290539
13.276413
0.699778
try: st = os.stat(file_name) except FileNotFoundError: return None return stat.S_IFMT(st.st_mode), st.st_size, st.st_mtime
def file_signature(file_name: str) -> Optional[Tuple]
Return an identity signature for file name :param file_name: name of file :return: mode, size, last modified time if file exists, otherwise none
2.373667
2.276597
1.042638
request = urllib.request.Request(url) request.get_method = lambda: 'HEAD' response = None try: response = urllib.request.urlopen(request) except urllib.error.HTTPError: return None return response.info()['Last-Modified'], response.info()['Content-Length'], response.info().ge...
def url_signature(url: str) -> Optional[Tuple]
Return an identify signature for url :param url: item to get signature for :return: tuple containing last modified, length and, if present, etag
2.317506
1.971666
1.175405
return url_signature(name) if is_url(name) else file_signature(name) if is_file(name) else None
def signature(name: str) -> Optional[Tuple]
Return the file or URL signature for name :param name: :return:
4.450778
3.589181
1.240054
try: import pypandoc except (ImportError, OSError) as e: print('No pypandoc or pandoc: %s' % (e,)) if is_py3: fh = open(readme_file, encoding='utf-8') else: fh = open(readme_file) long_description = fh.read() fh.close() return ...
def read_long_description(readme_file)
Read package long description from README file
2.292586
2.260112
1.014368
with open('./oi/version.py') as fh: for line in fh: if line.startswith('VERSION'): return line.split('=')[1].strip().strip("'")
def read_version()
Read package version
3.3702
3.483945
0.967352
return re.sub(r'^@prefix .* .\n', '', g.serialize(format="turtle").decode(), flags=re.MULTILINE).strip()
def strip_prefixes(g: Graph)
Remove the prefixes from the graph for aesthetics
5.710557
4.499437
1.269172
[self._g.bind(e[0], e[1]) for e in nsmap.items()]
def add_prefixes(self, nsmap: Dict[str, Namespace]) -> None
Add the required prefix definitions :return:
7.425866
7.025667
1.056962
self._g.add((subj, pred, obj)) return self
def add(self, subj: Node, pred: URIRef, obj: Node) -> "FHIRResource"
Shortcut to rdflib add function :param subj: :param pred: :param obj: :return: self for chaining
4.328135
5.043913
0.858091
pred_type = self._meta.predicate_type(pred) if not valuetype else valuetype # Transform generic resources into specific types if pred_type == FHIR.Resource: pred_type = FHIR[val.resourceType] val_meta = FHIRMetaVocEntry(self._vocabulary, pred_type) for k, p ...
def add_value_node(self, subj: Node, pred: URIRef, val: Union[JsonObj, str, List], valuetype: Optional[URIRef]= None) -> None
Expand val according to the range of pred and add it to the graph :param subj: graph subject :param pred: graph predicate :param val: JSON representation of target object :param valuetype: predicate type if it can't be directly determined
8.420882
8.311364
1.013177
match = FHIR_RESOURCE_RE.match(val) ref_uri_str = res_type = None if match: ref_uri_str = val if match.group(FHIR_RE_BASE) else (self._base_uri + urllib.parse.quote(val)) res_type = match.group(FHIR_RE_RESOURCE) elif '://' in val: ref_uri_str ...
def add_reference(self, subj: Node, val: str) -> None
Add a fhir:link and RDF type arc if it can be determined :param subj: reference subject :param val: reference value
2.871444
2.6356
1.089484
if json_key not in json_obj: print("Expecting to find object named '{}' in JSON:".format(json_key)) print(json_obj._as_json_dumps()) print("entry skipped") return None val = json_obj[json_key] if isinstance(val, List): list_idx...
def add_val(self, subj: Node, pred: URIRef, json_obj: JsonObj, json_key: str, valuetype: Optional[URIRef] = None) -> Optional[BNode]
Add the RDF representation of val to the graph as a target of subj, pred. Note that FHIR lists are represented as a list of BNODE objects with a fhir:index discrimanant :param subj: graph subject :param pred: predicate :param json_obj: object containing json_key :param json_key:...
3.370517
3.217635
1.047514
Union[JsonObj, List[JsonObjTypes]], key: str, pred: Optional[URIRef] = None) -> None: extendee_name = "_" + key if extendee_name in json_obj: if not isinstance(subj, BNode): raise NotImplem...
def add_extension_val(self, subj: Node, json_obj
Add any extensions for the supplied object. This can be called in following situations: 1) Single extended value "key" : (value), "_key" : { "extension": [ { "url": "http://...", "value[x]...
4.518268
4.881831
0.925527
link_node = g.value(subject, predicate) if link_node: l = g.value(link_node, FHIR.link) if l: typ = g.value(l, RDF.type) return l, typ return None, None
def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]
Return the link URI and link type for subject and predicate :param g: graph context :param subject: subject of linke :param predicate: link predicate :return: URI and optional type URI. URI is None if not a link
3.107084
2.907425
1.068672
# EXAMPLE: # fhir:Patient.maritalStatus [ # fhir:CodeableConcept.coding [ # fhir:index 0; # a sct:36629006; # fhir:Coding.system [ fhir:value "http://snomed.info/sct" ]; # fhir:Coding.code [ fhir:value "36629006" ]; # fhir:Coding.display [ fhir:value "Leg...
def codeable_concept_code(g: Graph, subject: Node, predicate: URIRef, system: Optional[str]=None) \ -> List[CodeableConcept]
Return a list of CodeableConcept entries for the supplied subject and predicate in graph g :param g: graph containing the data :param subject: subject :param predicate: predicate :param system: coding system. If present, only concepts in this system will be returned :return: system, code and option...
2.562691
2.596152
0.987111
local_name = str(uri).replace(str(FHIR), '') return local_name.rsplit('.', 1)[1] if '.' in local_name else local_name
def _to_str(uri: URIRef) -> str
Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference :param uri: URI to convert :return: tag name
5.893602
5.295153
1.113018
rval = dict() for parent in self._o.objects(self._subj, RDFS.subClassOf): if isinstance(parent, URIRef) and not str(parent).startswith(str(W5)): rval.update(**FHIRMetaVocEntry(self._o, parent).predicates()) for s in self._o.subjects(RDFS.domain, self._subj): ...
def predicates(self) -> Dict[str, URIRef]
Return the tag names and corresponding URI's for all properties that can be associated with subject :return: Map from tag name (JSON object identifier) to corresponding URI
6.083323
6.098521
0.997508
return self._o.value(pred, RDFS.range)
def predicate_type(self, pred: URIRef) -> URIRef
Return the type of pred :param pred: predicate to map :return:
23.071722
22.995872
1.003298
if not self.has_type(t): raise TypeError("Unrecognized FHIR type: {}".format(t)) return True
def is_valid(self, t: URIRef) -> bool
Raise an exception if 't' is unrecognized :param t: metadata URI
9.928436
7.842943
1.265907
return FHIR.Primitive in self._o.objects(t, RDFS.subClassOf)
def is_primitive(self, t: URIRef) -> bool
Determine whether type "t" is a FHIR primitive type :param t: type to test :return:
22.036512
17.42976
1.264304
if value_pred.startswith('value'): vp_datatype = value_pred.replace('value', '') if vp_datatype: if self.has_type(FHIR[vp_datatype]): return FHIR[vp_datatype] else: vp_datatype = vp_datatype[0].lower() + vp_...
def value_predicate_to_type(self, value_pred: str) -> URIRef
Convert a predicate in the form of "fhir:[...].value[type] to fhir:type, covering the downshift on the first character if necessary :param value_pred: Predicate associated with the value :return: corresponding type or None if not found
2.819023
2.595524
1.086109
if not self.has_type(pred): if '.value' in str(pred): # synthetic values (valueString, valueDate, ...) return False else: raise TypeError("Unrecognized FHIR predicate: {}".format(pred)) return pred == FHIR.nodeRole or OWL.Dat...
def is_atom(self, pred: URIRef) -> bool
Determine whether predicate is an 'atomic' type -- i.e it doesn't use a FHIR value representation :param pred: type to test :return:
13.306065
10.210762
1.303141
for sco in self._o.objects(t, RDFS.subClassOf): sco_type = self._o.value(sco, RDF.type) sco_prop = self._o.value(sco, OWL.onProperty) if sco_type == OWL.Restriction and sco_prop == FHIR.value: # The older versions of fhir.ttl (incorrectly) referenced ...
def primitive_datatype(self, t: URIRef) -> Optional[URIRef]
Return the data type for primitive type t, if any :param t: type :return: corresponding data type
3.740779
3.796163
0.98541
vt = self.primitive_datatype(t) if self.fhir_dates and vt == XSD.dateTime and v: return XSD.gYear if len(v) == 4 else XSD.gYearMonth if len(v) == 7 \ else XSD.date if (len(v) == 10 or (len(v) > 10 and v[10] in '+-')) else XSD.dateTime # For some reason the oi...
def primitive_datatype_nostring(self, t: URIRef, v: Optional[str] = None) -> Optional[URIRef]
Return the data type for primitive type t, if any, defaulting string to no type :param t: type :param v: value - for munging dates if we're doing FHIR official output :return: corresponding data type
4.424099
3.947698
1.120678
if self._cache_directory is not None: if name in self._cache: os.remove(os.path.join(self._cache_directory, self._cache[name].loc)) fname = os.path.join(self._cache_directory, str(uuid.uuid4())) with open(fname, 'wb') as f: pickle.dump...
def add(self, name: str, sig: Tuple, obj: object) -> None
Add a file to the cache :param name: name of the object to be pickled :param sig: signature for object :param obj: object to pickle
3.039158
2.759476
1.101353
if name not in self._cache: return None if self._cache[name].sig != sig: del self._cache[name] self._update() return None with open(self._cache[name].loc, 'rb') as f: return pickle.load(f)
def get(self, name: str, sig: Tuple) -> Optional[object]
Return the object representing name if it is cached :param name: name of object :param sig: unique signature of object :return: object if exists and signature matches
2.740979
3.036548
0.902663
if self._cache_directory is not None: # Safety - if there isn't a cache directory file, this probably isn't a valid cache assert os.path.exists(self._cache_directory_index), "Attempt to clear a non-existent cache" self._load() # Shouldn't have any impact b...
def clear(self) -> None
Clear all cache entries for directory and, if it is a 'pure' directory, remove the directory itself
6.059643
5.34553
1.133591
def check_for_continuation(data_: JsonObj) -> Optional[str]: if do_continuations and 'link' in data_ and isinstance(data_.link, list): for link_e in data_.link: if 'relation' in link_e and link_e.relation == 'next': return link_e.url return None ...
def fhir_json_to_rdf(json_fname: str, base_uri: str = "http://hl7.org/fhir/", target_graph: Optional[Graph] = None, add_ontology_header: bool = True, do_continuations: bool = True, replace_narrative_text: bool = Fal...
Convert a FHIR JSON resource image to RDF :param json_fname: Name or URI of the file to convert :param base_uri: Base URI to use for relative references. :param target_graph: If supplied, add RDF to this graph. If not, start with an empty graph. :param add_ontology_header: True means add owl:Ontology ...
2.212586
2.199627
1.005892
return URIRef(str(s) + '.' + str(p).rsplit('/', 1)[1] + ("_{}".format(idx) if idx is not None else ''))
def subj_pred_idx_to_uri(s: URIRef, p: URIRef, idx: Optional[int] = None) -> URIRef
Convert FHIR subject, predicate and entry index into a URI. The resulting element can be substituted for the name of the target BNODE :param s: Subject URI (e.g. "fhir:Patient/f201", "fhir:Patient/f201.Patient.identifier_0", ...) :param p: Predicate URI (e.g. "fhir:Patient.identifier", "fhir.Identifier.use...
3.886556
4.394118
0.884491
for p, o in gin.predicate_objects(s): if not isinstance(o, BNode): gout.add((sk_s, p, o)) else: sk_o = subj_pred_idx_to_uri(sk_s, p, gin.value(o, FHIR.index)) gout.add((sk_s, p, sk_o)) map_node(o, sk_o, gin, gout)
def map_node(s: Node, sk_s: URIRef, gin: Graph, gout: Graph) -> None
Transform the BNode whose subject is s into its equivalent, replacing s with its 'skolemized' equivalent :param s: Actual subject :param sk_s: Equivalent URI of subject in output graph :param gin: Input graph :param gout: Output graph
2.777828
2.725044
1.01937
gout = Graph() # Emit any unreferenced subject BNodes (boxes) anon_subjs = [s for s in gin.subjects() if isinstance(s, BNode) and len([gin.subject_predicates(s)]) == 0] if anon_subjs: idx = None if len(anon_subjs) == 1 else 0 for s in anon_subjs: map_node(s, FHIR['treeR...
def skolemize(gin: Graph) -> Graph
Replace all of the blank nodes in graph gin with FHIR paths :param gin: input graph :return: output graph
5.007139
5.092001
0.983334
if target_graph is None: target_graph = PrettyGraph() for p, o in source_graph.predicate_objects(subj): target_graph.add((subj, p, o)) if isinstance(o, BNode): complete_definition(o, source_graph, target_graph) return target_graph
def complete_definition(subj: Node, source_graph: Graph, target_graph: Optional[Graph]=None) -> PrettyGraph
Return the transitive closure of subject. :param subj: URI or BNode for subject :param source_graph: Graph containing defininition :param target_graph: return graph (for recursion) :return: target_graph
2.16321
1.862507
1.161451
return [l.decode('ascii') for l in sorted(g.serialize(format='nt').splitlines()) if l]
def dump_nt_sorted(g: Graph) -> List[str]
Dump graph g in a sorted n3 format :param g: graph to dump :return: stringified representation of g
5.266098
5.924399
0.888883
def graph_for_subject(g: Graph, subj: Node) -> Graph: subj_in_g = complete_definition(subj, g) if ignore_type_arcs: for ta_s, ta_o in subj_in_g.subject_objects(RDF.type): if isinstance(ta_s, BNode) and isinstance(ta_o, URIRef): subj_in_g.remove((t...
def rdf_compare(g1: Graph, g2: Graph, ignore_owl_version: bool=False, ignore_type_arcs: bool = False, compare_filter: Optional[Callable[[Graph, Graph, Graph], None]]=None) -> str
Compare graph g1 and g2 :param g1: first graph :param g2: second graph :param ignore_owl_version: :param ignore_type_arcs: :param compare_filter: Final adjustment for graph difference. Used, for example, to deal with FHIR decimal problems. :return: List of differences as printable lines or blank...
2.392908
2.386261
1.002785
g = fhir_json_to_rdf(infile, opts.uribase, opts.graph, add_ontology_header=not opts.noontology, do_continuations=not opts.nocontinuation, replace_narrative_text=bool(opts.nonarrative), metavoc=opts.fhir_metavoc) # If we aren't carrying graph in opts, we're...
def proc_file(infile: str, outfile: str, opts: Namespace) -> bool
Process infile. :param infile: input file to be processed :param outfile: target output file. :param opts: :return:
10.490333
10.63848
0.986074
# If it looks like we're processing a URL as an input file, skip the suffix check if '://' in ifn: return True if not ifn.endswith('.json'): return False if indir and (indir.startswith("_") or "/_" in indir or any(dn in indir for dn in opts.skipdirs)): return False if...
def file_filter(ifn: str, indir: str, opts: Namespace) -> bool
Determine whether to process ifn. We con't process: 1) Anything in a directory having a path element that begins with "_" 2) Really, really big files 3) Temporary lists of know errors :param ifn: input file name :param indir: input directory :param opts: argparse options :return...
4.141908
3.928823
1.054237
dlp = dirlistproc.DirectoryListProcessor(argv, description="Convert FHIR JSON into RDF", infile_suffix=".json", outfile_suffix=".ttl", ...
def fhirtordf(argv: List[str], default_exit: bool = True) -> bool
Entry point for command line utility
4.031743
3.975495
1.014149
uri_str = str(uri) m = FHIR_RESOURCE_RE.match(uri_str) if m: return FHIR_RESOURCE(URIRef(m.group(FHIR_RE_BASE)), FHIR[m.group(FHIR_RE_RESOURCE)], m.group(FHIR_RE_ID)) else: # Not in the FHIR format - we can only do namespace and name namespace, name = uri_str.rsplit('#', 1) ...
def parse_fhir_resource_uri(uri: Union[URIRef, str]) -> FHIR_RESOURCE
Use the FHIR Regular Expression for Resource URI's to determine the namespace and type of a given URI. As an example, "http://hl7.org/fhir/Patient/p123" maps to the tuple ``('Patient', 'http://hl7.org/fhir') :param uri: URI to parse :return: FHIR_RESOURCE (namespace, type, resource)
3.313136
3.211528
1.031638
from .setup_helpers import _module_state if _module_state['registered_commands'] is None: raise RuntimeError( 'astropy_helpers.setup_helpers.register_commands() must be ' 'called before using ' 'astropy_helpers.setup_helpers.get_dummy_distribution()') # Pr...
def get_dummy_distribution()
Returns a distutils Distribution object used to instrument the setup environment before calling the actual setup() function.
5.499392
5.27138
1.043255
dist = get_dummy_distribution() for cmd in commands: cmd_opts = dist.command_options.get(cmd) if cmd_opts is not None and option in cmd_opts: return cmd_opts[option][1] else: return None
def get_distutils_option(option, commands)
Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val : str or None the value of the given distutils option. If th...
3.462501
3.849166
0.899546
dist = get_dummy_distribution() cmdcls = dist.get_command_class(command) if (hasattr(cmdcls, '_astropy_helpers_options') and name in cmdcls._astropy_helpers_options): return attr = name.replace('-', '_') if hasattr(cmdcls, attr): raise RuntimeError( '...
def add_command_option(command, name, doc, is_bool=False)
Add a custom option to a setup command. Issues a warning if the option already exists on that command. Parameters ---------- command : str The name of the command as given on the command line name : str The name of the build option doc : str A short description of the...
3.610359
3.61277
0.999333
short_display_opts = set('-' + o[1] for o in Distribution.display_options if o[1]) long_display_opts = set('--' + o[0] for o in Distribution.display_options) # Include -h and --help which are not explicitly listed in # Distribution.display_options (as they are handled...
def get_distutils_display_options()
Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form display option arguments, including the - or -...
5.561899
5.882874
0.945439
# We've split out the Sphinx part of astropy-helpers into sphinx-astropy # but we want it to be auto-installed seamlessly for anyone using # build_docs. We check if it's already installed, and if not, we install # it to a local .eggs directory and add the eggs to the path (these # have to each ...
def ensure_sphinx_astropy_installed()
Make sure that sphinx-astropy is available, installing it temporarily if not. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available.
4.989729
4.946453
1.008749
plat_specifier = '.{0}-{1}'.format(cmd.plat_name, sys.version[0:3]) return os.path.join(cmd.build_base, 'lib' + plat_specifier)
def _get_platlib_dir(cmd)
Given a build command, return the name of the appropriate platform-specific build subdirectory directory (e.g. build/lib.linux-x86_64-2.7)
3.969333
3.555895
1.116268
# We need to go through this nonsense in case setuptools # downloaded and installed Numpy for us as part of the build or # install, since Numpy may still think it's in "setup mode", when # in fact we're ready to use it to build astropy now. import builtins if hasattr(builtins, '__NUMPY_SET...
def get_numpy_include_path()
Gets the path to the numpy headers.
6.635911
6.758351
0.981883
name = os.path.basename(os.path.abspath(filepath)) if isinstance(name, bytes): is_dotted = name.startswith(b'.') else: is_dotted = name.startswith('.') return is_dotted or _has_hidden_attribute(filepath)
def is_path_hidden(filepath)
Determines if a given file or directory is hidden. Parameters ---------- filepath : str The path to a file or directory Returns ------- hidden : bool Returns `True` if the file is hidden
3.568002
3.814139
0.935467
for root, dirs, files in os.walk( top, topdown=True, onerror=onerror, followlinks=followlinks): # These lists must be updated in-place so os.walk will skip # hidden directories dirs[:] = [d for d in dirs if not is_path_hidden(d)] files[:] = [f for f in f...
def walk_skip_hidden(top, onerror=None, followlinks=False)
A wrapper for `os.walk` that skips hidden files and directories. This function does not have the parameter `topdown` from `os.walk`: the directories must always be recursed top-down when using this function. See also -------- os.walk : For a description of the parameters
2.770944
3.25673
0.850836
assert isinstance(data, bytes) if os.path.exists(filename): with open(filename, 'rb') as fd: original_data = fd.read() else: original_data = None if original_data != data: with open(filename, 'wb') as fd: fd.write(data)
def write_if_different(filename, data)
Write `data` to `filename`, if the content of the file is different. Parameters ---------- filename : str The file name to be written to. data : bytes The data to be written to `filename`.
2.121141
2.038757
1.040409
# Specifying a traditional dot-separated fully qualified name here # results in a number of "Parent module 'astropy' not found while # handling absolute import" warnings. Using the same name, the # namespaces of the modules get merged together. So, this # generates an underscore-separated nam...
def import_file(filename, name=None)
Imports a module from a single file as if it doesn't belong to a particular package. The returned module will have the optional ``name`` if given, or else a name generated from the filename.
4.799503
4.993205
0.961207
parts = name.split('.') cursor = len(parts) - 1 module_name = parts[:cursor] attr_name = parts[-1] while cursor > 0: try: ret = __import__('.'.join(module_name), fromlist=[attr_name]) break except ImportError: if cursor == 0: ...
def resolve_name(name)
Resolve a name like ``module.object`` to an object and return it. Raise `ImportError` if the module or name is not found.
2.372162
2.218184
1.069416
def decorator(func): if not (extended_func.__doc__ is None or func.__doc__ is None): func.__doc__ = '\n\n'.join([extended_func.__doc__.rstrip('\n'), func.__doc__.lstrip('\n')]) return func return decorator
def extends_doc(extended_func)
A function decorator for use when wrapping an existing function but adding additional functionality. This copies the docstring from the original function, and appends to it (along with a newline) the docstring of the wrapper function. Examples -------- >>> def foo(): ... '''He...
2.82989
3.508193
0.806652
return glob.glob(os.path.join(package, pattern), recursive=True)
def find_data_files(package, pattern)
Include files matching ``pattern`` inside ``package``. Parameters ---------- package : str The package inside which to look for data files pattern : str Pattern (glob-style) to match for the data files (e.g. ``*.dat``). This supports the``**``recursive syntax. For example, ``**/...
4.495942
5.423084
0.829038
parsed_version = pkg_resources.parse_version(version) if hasattr(parsed_version, 'base_version'): # New version parsing for setuptools >= 8.0 if parsed_version.base_version: parts = [int(part) for part in parsed_version.base_version.split('.')] els...
def _version_split(version)
Split a version string into major, minor, and bugfix numbers. If any of those numbers are missing the default is zero. Any pre/post release modifiers are ignored. Examples ======== >>> _version_split('1.2.3') (1, 2, 3) >>> _version_split('1.2') (1, 2, 0) >>> _version_split('1.2rc1...
3.718184
3.965306
0.937679
loader = pkgutil.get_loader(git_helpers) source = loader.get_source(git_helpers.__name__) or '' source_lines = source.splitlines() if not source_lines: log.warn('Cannot get source code for astropy_helpers.git_helpers; ' 'git support disabled.') return '' idx =...
def _generate_git_header(packagename, version, githash)
Generates a header to the version.py module that includes utilities for probing the git repository for updates (to the current git hash, etc.) These utilities should only be available in development versions, and not in release builds. If this fails for any reason an empty string is returned.
4.075638
4.04543
1.007467
version = import_file(os.path.join(packagename, 'version.py'), name='version') if fromlist: return tuple(getattr(version, member) for member in fromlist) else: return version
def get_pkg_version_module(packagename, fromlist=None)
Returns the package's .version module generated by `astropy_helpers.version_helpers.generate_version_py`. Raises an ImportError if the version module is not found. If ``fromlist`` is an iterable, return a tuple of the members of the version module corresponding to the member names given in ``fromlist`...
3.565072
3.530395
1.009822
# DEPRECATED: store the package name in a built-in variable so it's easy # to get from other parts of the setup infrastructure. We should phase this # out in packages that use it - the cookiecutter template should now be # able to put the right package name where needed. conf = read_configurat...
def setup(**kwargs)
A wrapper around setuptools' setup() function that automatically sets up custom commands, generates a version file, and customizes the setup process via the ``setup_package.py`` files.
6.756776
6.629346
1.019222
try: current_debug = get_pkg_version_module(packagename, fromlist=['debug'])[0] except (ImportError, AttributeError): current_debug = None # Only modify the debug flag if one of the build commands was explicitly # run (i.e. not as a s...
def get_debug_option(packagename)
Determines if the build is in debug mode. Returns ------- debug : bool True if the current build was started with the debug option, False otherwise.
4.68747
4.77384
0.981908
if package is not None: warnings.warn('The package argument to generate_version_py has ' 'been deprecated and will be removed in future. Specify ' 'the package name in setup.cfg instead', AstropyDeprecationWarning) if version is not None: warnin...
def register_commands(package=None, version=None, release=None, srcdir='.')
This function generates a dictionary containing customized commands that can then be passed to the ``cmdclass`` argument in ``setup()``.
3.750112
3.773381
0.993833
hook_re = re.compile(r'^(pre|post)_(.+)_hook$') # Distutils commands have a method of the same name, but it is not a # *classmethod* (which probably didn't exist when distutils was first # written) def get_command_name(cmdcls): if hasattr(cmdcls, 'command_name'): return cm...
def add_command_hooks(commands, srcdir='.')
Look through setup_package.py modules for functions with names like ``pre_<command_name>_hook`` and ``post_<command_name>_hook`` where ``<command_name>`` is the name of a ``setup.py`` command (e.g. build_ext). If either hook is present this adds a wrapped version of that command to the passed in ``comm...
3.201168
2.900088
1.103818
def run(self, orig_run=cmd_cls.run): self.run_command_hooks('pre_hooks') orig_run(self) self.run_command_hooks('post_hooks') return type(cmd_name, (cmd_cls, object), {'run': run, 'run_command_hooks': run_command_hooks, 'pre_hooks': hooks.get('pre',...
def generate_hooked_command(cmd_name, cmd_cls, hooks)
Returns a generated subclass of ``cmd_cls`` that runs the pre- and post-command hooks for that command before and after the ``cmd_cls.run`` method.
2.868161
2.513511
1.141097
hooks = getattr(cmd_obj, hook_kind, None) if not hooks: return for modname, hook in hooks: if isinstance(hook, str): try: hook_obj = resolve_name(hook) except ImportError as exc: raise DistutilsModuleError( '...
def run_command_hooks(cmd_obj, hook_kind)
Run hooks registered for that command and phase. *cmd_obj* is a finalized command object; *hook_kind* is either 'pre_hook' or 'post_hook'.
2.6032
2.656852
0.979806
info = get_package_info(srcdir) extensions.extend(info['ext_modules']) package_data.update(info['package_data']) packagenames = list(set(packagenames + info['packages'])) package_dirs.update(info['package_dir'])
def update_package_files(srcdir, extensions, package_data, packagenames, package_dirs)
This function is deprecated and maintained for backward compatibility with affiliated packages. Affiliated packages should update their setup.py to use `get_package_info` instead.
2.488942
2.277457
1.09286
for packagename in packages: package_parts = packagename.split('.') package_path = os.path.join(srcdir, *package_parts) setup_package = os.path.relpath( os.path.join(package_path, 'setup_package.py')) if os.path.isfile(setup_package): module = import_fi...
def iter_setup_packages(srcdir, packages)
A generator that finds and imports all of the ``setup_package.py`` modules in the source packages. Returns ------- modgen : generator A generator that yields (modname, mod), where `mod` is the module and `modname` is the module name for the ``setup_package.py`` modules.
2.671473
2.760737
0.967667
for dirpath, dirnames, filenames in walk_skip_hidden(package_dir): for fn in filenames: if fn.endswith('.pyx'): fullfn = os.path.relpath(os.path.join(dirpath, fn)) # Package must match file name extmod = '.'.join([package_name, fn[:-4]]) ...
def iter_pyx_files(package_dir, package_name)
A generator that yields Cython source files (ending in '.pyx') in the source packages. Returns ------- pyxgen : generator A generator that yields (extmod, fullfn) where `extmod` is the full name of the module that the .pyx file would live in based on the source directory structu...
4.046406
3.262777
1.240173
# Vanilla setuptools and old versions of distribute include Cython files # as .c files in the sources, not .pyx, so we cannot simply look for # existing .pyx sources in the previous sources, but we should also check # for .c files with the same remaining filename. So we look for .pyx and # .c ...
def get_cython_extensions(srcdir, packages, prevextensions=tuple(), extincludedirs=None)
Looks for Cython files and generates Extensions if needed. Parameters ---------- srcdir : str Path to the root of the source directory to search. prevextensions : list of `~distutils.core.Extension` objects The extensions that are already defined. Any .pyx files already here wi...
3.689478
3.830822
0.963103
flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries', '-D': 'define_macros', '-U': 'undef_macros'} command = "{0} --libs --cflags {1}".format(executable, ' '.join(packages)), result = DistutilsExtensionArgs() try: pipe = subprocess.Popen(command, shel...
def pkg_config(packages, default_libraries, executable='pkg-config')
Uses pkg-config to update a set of distutils Extension arguments to include the flags necessary to link against the given packages. If the pkg-config lookup fails, default_libraries is applied to libraries. Parameters ---------- packages : list of str A list of pkg-config packages to l...
3.28361
3.169997
1.03584
for command in ['build', 'build_ext', 'install']: add_command_option(command, str('use-system-' + library), 'Use the system {0} library'.format(library), is_bool=True)
def add_external_library(library)
Add a build option for selecting the internal or system copy of a library. Parameters ---------- library : str The name of the library. If the library is `foo`, the build option will be called `--use-system-foo`.
7.33002
6.104935
1.200671
if exclude: warnings.warn( "Use of the exclude parameter is no longer supported since it does " "not work as expected. Use add_exclude_packages instead. Note that " "it must be called prior to any other calls from setup helpers.", AstropyDeprecationWarni...
def find_packages(where='.', exclude=(), invalidate_cache=False)
This version of ``find_packages`` caches previous results to speed up subsequent calls. Use ``invalide_cache=True`` to ignore cached results from previous ``find_packages`` calls, and repeat the package search.
5.08936
5.359656
0.949568
# Only build with Cython if, of course, Cython is installed, we're in a # development version (i.e. not release) or the Cython-generated source # files haven't been created yet (cython_version == 'unknown'). The latter # case can happen even when release is True if checking out a release tag #...
def should_build_with_cython(previous_cython_version, is_release)
Returns the previously used Cython version (or 'unknown' if not previously built) if Cython should be used to build extension modules from pyx files.
4.924437
4.549611
1.082386
# Determine the compiler we'll be using if self.compiler is None: compiler = get_default_compiler() else: compiler = self.compiler # Replace .pyx with C-equivalents, unless c files are missing for jdx, src in enumerate(extension.sources): ...
def _check_cython_sources(self, extension)
Where relevant, make sure that the .c files associated with .pyx modules are present (if building without Cython installed).
4.066736
3.984286
1.020694
if sys.platform.startswith('win'): return None # Simple input validation if not var or not flag: return None flag_length = len(flag) if not flag_length: return None # Look for var in os.eviron then in get_config_var if var in os.environ: flags = os.env...
def _get_flag_value_from_var(flag, var, delim=' ')
Extract flags from an environment variable. Parameters ---------- flag : str The flag to extract, for example '-I' or '-L' var : str The environment variable to extract the flag from, e.g. CFLAGS or LDFLAGS. delim : str, optional The delimiter separating flags inside the env...
4.220159
3.355831
1.25756
compile_flags = [] link_flags = [] if get_compiler_option() == 'msvc': compile_flags.append('-openmp') else: include_path = _get_flag_value_from_var('-I', 'CFLAGS') if include_path: compile_flags.append('-I' + include_path) lib_path = _get_flag_value_...
def get_openmp_flags()
Utility for returning compiler and linker flags possibly needed for OpenMP support. Returns ------- result : `{'compiler_flags':<flags>, 'linker_flags':<flags>}` Notes ----- The flags returned are not tested for validity, use `check_openmp_support(openmp_flags=get_openmp_flags())` to d...
2.227362
2.199712
1.01257
ccompiler = new_compiler() customize_compiler(ccompiler) if not openmp_flags: # customize_compiler() extracts info from os.environ. If certain keys # exist it uses these plus those from sysconfig.get_config_vars(). # If the key is missing in os.environ it is not extracted from...
def check_openmp_support(openmp_flags=None)
Check whether OpenMP test code can be compiled and run. Parameters ---------- openmp_flags : dict, optional This should be a dictionary with keys ``compiler_flags`` and ``linker_flags`` giving the compiliation and linking flags respectively. These are passed as `extra_postargs` to `...
3.155651
3.109008
1.015003
log_threshold = log.set_threshold(log.FATAL) ret = check_openmp_support() log.set_threshold(log_threshold) return ret
def is_openmp_supported()
Determine whether the build compiler has OpenMP support.
5.693113
5.550714
1.025654
if _ASTROPY_DISABLE_SETUP_WITH_OPENMP_: log.info("OpenMP support has been explicitly disabled.") return False openmp_flags = get_openmp_flags() using_openmp = check_openmp_support(openmp_flags=openmp_flags) if using_openmp: compile_flags = openmp_flags.get('compiler_flags...
def add_openmp_flags_if_available(extension)
Add OpenMP compilation flags, if supported (if not a warning will be printed to the console and no flags will be added.) Returns `True` if the flags were added, `False` otherwise.
3.150286
3.10684
1.013984
if packagename.lower() == 'astropy': packagetitle = 'Astropy' else: packagetitle = packagename epoch = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) timestamp = datetime.datetime.utcfromtimestamp(epoch) if disable_openmp is not None: import builtins bu...
def generate_openmp_enabled_py(packagename, srcdir='.', disable_openmp=None)
Generate ``package.openmp_enabled.is_openmp_enabled``, which can then be used to determine, post build, whether the package was built with or without OpenMP support.
2.99156
2.78132
1.07559
if len(self.dataframe): return str(self.dataframe.iloc[row, col]) return ''
def GetValue(self, row, col)
Find the matching value from pandas DataFrame, return it.
6.054592
5.014929
1.207314
self.dataframe.iloc[row, col] = value
def SetValue(self, row, col, value)
Set value in the pandas DataFrame
8.806677
5.237105
1.681593
try: self.dataframe.iloc[:, col] = value except ValueError: self.dataframe.loc[:, col] = value
def SetColumnValues(self, col, value)
Custom method to efficiently set all values in a column. Parameters ---------- col : str or int name or index position of column value : list-like values to assign to all cells in the column
4.124986
4.076813
1.011816
if len(self.dataframe): return self.dataframe.columns[col] return ''
def GetColLabelValue(self, col)
Get col label from dataframe
7.57479
5.366812
1.411413
if len(self.dataframe): col_name = str(self.dataframe.columns[col]) self.dataframe.rename(columns={col_name: str(value)}, inplace=True) return None
def SetColLabelValue(self, col, value)
Set col label value in dataframe
4.15359
3.543851
1.172056
try: if len(self.row_labels) < 5: show_horizontal = wx.SHOW_SB_NEVER else: show_horizontal = wx.SHOW_SB_DEFAULT self.ShowScrollbars(show_horizontal, wx.SHOW_SB_DEFAULT) except AttributeError: pass
def set_scrollbars(self)
Set to always have vertical scrollbar. Have horizontal scrollbar unless grid has very few rows. Older versions of wxPython will choke on this, in which case nothing happens.
4.038778
3.186968
1.267279
# replace "None" values with "" dataframe = dataframe.fillna("") # remove any columns that shouldn't be shown for col in hide_cols: if col in dataframe.columns: del dataframe[col] # add more rows self.AppendRows(len(dataframe)) ...
def add_items(self, dataframe, hide_cols=())
Add items and/or update existing items in grid
3.15247
3.108701
1.014079
if rows: rows = rows else: rows = list(range(self.GetNumberRows())) cols = list(range(self.GetNumberCols())) data = {} for row in rows: data[row] = {} for col in cols: col_name = self.GetColLabelValue(col) ...
def save_items(self, rows=None, verbose=False)
Return a dictionary of row data for selected rows: {1: {col1: val1, col2: val2}, ...} If a list of row numbers isn't provided, get data for all.
2.070246
1.845438
1.121818
if not self.changes: self.changes = {event.Row} else: self.changes.add(event.Row) #self.changes = True try: editor = event.GetControl() editor.Bind(wx.EVT_KEY_DOWN, self.onEditorKey) except AttributeError: # if ...
def on_edit_grid(self, event)
sets self.changes to true when user edits the grid. provides down and up key functionality for exiting the editor
4.614754
4.2147
1.094919
# find where the user has clicked col_ind = self.GetGridCursorCol() row_ind = self.GetGridCursorRow() # read in clipboard text text_df = pd.read_clipboard(header=None, sep='\t').fillna('') # add extra rows if need to accomadate clipboard text row_length_d...
def do_paste(self, event)
Read clipboard into dataframe Paste data into grid, adding extra rows if needed and ignoring extra columns.
3.298962
3.059175
1.078383
if row_num in self.changes.copy(): self.changes.remove(row_num) updated_rows = [] for changed_row in self.changes: if changed_row == -1: updated_rows.append(-1) if changed_row > row_num: updated_rows.append(changed_row ...
def update_changes_after_row_delete(self, row_num)
Update self.changes so that row numbers for edited rows are still correct. I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3. This function updates self.changes to reflect that.
2.076848
2.040482
1.017822
self.SetColLabelRenderer(col, MyColLabelRenderer('#1101e0')) # SetCellRenderer doesn't work with table-based grid (HugeGrid class) if not skip_cell: self.SetCellRenderer(row, col, MyCustomRenderer(color))
def paint_invalid_cell(self, row, col, color='MEDIUM VIOLET RED', skip_cell=False)
Take row, column, and turn it color
12.033475
11.888107
1.012228
self.table.dataframe[label] = '' self.AppendCols(1, updateLabels=False) last_col = self.table.GetNumberCols() - 1 self.SetColLabelValue(last_col, label) self.col_labels.append(label) self.size_grid() return last_col
def add_col(self, label)
Update table dataframe, and append a new column Parameters ---------- label : str Returns --------- last_col: int index column number of added col
4.750505
5.511971
0.861852
label_value = self.GetColLabelValue(col_num).strip('**').strip('^^') self.col_labels.remove(label_value) del self.table.dataframe[label_value] result = self.DeleteCols(pos=col_num, numCols=1, updateLabels=True) self.size_grid() return result
def remove_col(self, col_num)
update table dataframe, and remove a column. resize grid to display correctly
6.487873
5.779639
1.122539
fmt,plot='svg',0 if len(sys.argv) > 0: if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-fmt' in sys.argv: ind=sys.argv.index('-fmt') fmt=sys.argv[ind+1] if '-sav' in sys.argv:plot=1 ...
def main()
NAME plotdi_a.py DESCRIPTION plots equal area projection from dec inc data and fisher mean, cone of confidence INPUT FORMAT takes dec, inc, alpha95 as first three columns in space delimited file SYNTAX plotdi_a.py [-i][-f FILE] OPTIONS -f FILE to read file name f...
3.247371
3.054229
1.063238
D,I=0.,90. outfile="" infile="" if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-f' in sys.argv: ind=sys.argv.index('-f') infile=sys.argv[ind+1] data=numpy.loadtxt(infile) else: data=numpy.loadtxt(sys.stdin,dtype=numpy.float) if '-...
def main()
NAME di_rot.py DESCRIPTION rotates set of directions to new coordinate system SYNTAX di_rot.py [command line options] OPTIONS -h prints help message and quits -f specify input file, default is standard input -F specify output file, default is standard outpu...
2.418819
2.339293
1.033996
ofile="" if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-F' in sys.argv: ind=sys.argv.index('-F') ofile=sys.argv[ind+1] out=open(ofile,'w') if '-flt' in sys.argv: ind=sys.argv.index('-flt') flt=float(sys.argv[ind+1]) else: ...
def main()
NAME unsquish.py DESCRIPTION takes dec/inc data and "unsquishes" with specified flattening factor, flt using formula tan(If)=(1/flt)*tan(Io) INPUT declination inclination OUTPUT "unsquished" declincation inclination SYNTAX unsquish.py [c...
2.637123
2.307892
1.142654
# does not exclude ptrm checks that are less than tmin ptrm_checks_included_temps= [] for num, check in enumerate(ptrm_temps): if check > tmax: pass elif ptrm_starting_temps[num] > tmax: # or ptrm_starting_temps[num] < tmin: pass else: ptrm_ch...
def get_n_ptrm(tmin, tmax, ptrm_temps, ptrm_starting_temps)
input: tmin, tmax, ptrm_temps, ptrm_starting_temps returns number of ptrm_checks included in best fit segment. excludes checks if temp exceeds tmax OR if starting temp exceeds tmax. output: n_ptrm, ptrm_checks_included_temperatures
3.078552
2.417177
1.273614
if not ptrm_checks_included_temps: return [], float('nan'), float('nan'), float('nan'), float('nan') diffs = [] abs_diffs = [] x_Arai_compare = [] ptrm_compare = [] check_percents = [] ptrm_checks_all_temps = list(ptrm_checks_all_temps) for check in ptrm_checks_included_temp...
def get_max_ptrm_check(ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai)
input: ptrm_checks_included_temps, ptrm_checks_all_temps, ptrm_x, t_Arai, x_Arai. sorts through included ptrm_checks and finds the largest ptrm check diff, the sum of the total diffs, and the percentage of the largest check / original measurement at that temperature step output: max_diff, sum_diffs, che...
2.25573
2.01227
1.120988
L = numpy.sqrt(delta_x_prime**2 + delta_y_prime**2) DRAT = (old_div(max_ptrm_check, L)) * 100 return DRAT, L
def get_DRAT(delta_x_prime, delta_y_prime, max_ptrm_check)
Input: TRM length of best fit line (delta_x_prime), NRM length of best fit line, max_ptrm_check Output: DRAT (maximum difference produced by a ptrm check normed by best fit line), length best fit line
3.518556
3.39182
1.037365
CDRAT = (old_div(sum_ptrm_checks, L)) * 100. CDRAT_prime = (old_div(sum_abs_ptrm_checks, L)) * 100. return CDRAT, CDRAT_prime
def get_CDRAT(L, sum_ptrm_checks, sum_abs_ptrm_checks)
input: best_fit line length, sum of ptrm check diffs, sum of absolute value of ptrm check diffs output: CDRAT (uses sum of diffs), CDRAT_prime (uses sum of absolute diffs)
2.117175
2.261714
0.936093