code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
reg_func = lambda a: N.linalg.svd(a,full_matrices=False)[2][2] beta_boots = bootstrap(array, func=reg_func) return yhat, yhat_boots
def bootstrap(array)
Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method.
8.439309
8.945992
0.943362
# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <character string literal> return SQUOTE + text.replace(SQUOTE, DOUBLE_SQUOTE) + SQUOTE
def sql_string_literal(text: str) -> str
Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'"
7.588947
9.502045
0.798665
# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <timestamp string> # ... the subsecond part is non-ANSI fmt = "'%Y-%m-%d %H:%M:%S{}'".format(".%f" if subsecond else "") return dt.strftime(fmt)
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str
Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar.
6.895512
6.505994
1.059871
if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
def sql_comment(comment: str) -> str
Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``.
5.474626
4.450027
1.230246
if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
def sql_dequote_string(s: str) -> str
Reverses :func:`sql_quote_string`.
3.364935
3.026746
1.111734
# csv.reader will not both process the quotes and return the quotes; # we need them to distinguish e.g. NULL from 'NULL'. # log.warning('gen_items_from_sql_csv: s = {0!r}', s) if not s: return n = len(s) startpos = 0 pos = 0 in_quotes = False while pos < n: if no...
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed.
3.408654
3.327008
1.024541
for key in d.keys(): if k.lower() == key.lower(): return key return None
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]
Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one).
2.61224
2.869693
0.910285
z = x.copy() z.update(y) return z
def merge_two_dicts(x: Dict, y: Dict) -> Dict
Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987.
5.298754
5.770356
0.918272
d[new] = d.pop(old)
def rename_key(d: Dict[str, Any], old: str, new: str) -> None
Rename a key in dictionary ``d`` from ``old`` to ``new``, in place.
8.083658
3.883051
2.08178
result = {} # type: Dict[str, Any] for k, v in d.items(): if k in mapping: k = mapping[k] result[k] = v return result
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]
Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The i...
1.883029
2.412431
0.780553
# noqa for old_key, new_key in renames.items(): if new_key == old_key: continue if old_key in d: if new_key in d: raise ValueError( "rename_keys_in_dict: renaming {} -> {} but new key " "already exists".format(repr...
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
2.148642
2.432884
0.883167
result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]
Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys.
2.267635
2.326377
0.974749
return {v: k for k, v in d.items()}
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping.
2.855049
3.068341
0.930486
if not null_literals: return # DO NOT add/delete values to/from a dictionary during iteration, but it # is OK to modify existing keys: # https://stackoverflow.com/questions/6777485 # https://stackoverflow.com/questions/2315520 # https://docs.python.org/3/library/st...
def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None
Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``.
4.395238
4.361968
1.007627
result = [] for k in l: if raise_if_missing and k not in d: raise ValueError("Missing key: " + repr(k)) if omit_if_missing and k not in d: continue result.append(d.get(k, default)) return result
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]
The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` i...
2.061898
2.259258
0.912644
changes = {k: v for k, v in d2.items() if k not in d1 or d2[k] != d1[k]} for k in d1.keys(): if k not in d2: changes[k] = deleted_value return changes
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]
Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs ...
1.972218
2.287261
0.862262
for k in keys_to_delete: if k in d and k not in keys_to_keep: del d[k]
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
3.102592
3.469028
0.894369
retval = self._strlist_to_dbstr(value) return retval
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str
Convert things on the way from Python to the database.
21.357609
12.294552
1.73716
retval = self._dbstr_to_strlist(value) return retval
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]
Convert things on the way from the database to Python.
21.01334
15.500705
1.355638
retval = self._intlist_to_dbstr(value) return retval
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str
Convert things on the way from Python to the database.
24.475483
12.667548
1.932141
retval = self._dbstr_to_intlist(value) return retval
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]
Convert things on the way from the database to Python.
17.95203
13.046253
1.37603
self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
def reset(self) -> None
Reset the timers.
10.368984
8.652594
1.198367
self._timing = timing if reset: self.reset()
def set_timing(self, timing: bool, reset: bool = False) -> None
Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers?
6.697366
6.102568
1.097467
if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: last = self._stack[-1] self._totaldurations[last] += now - self._starttimes[last] # Start timing our new...
def start(self, name: str, increment_count: bool = True) -> None
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer
4.000484
3.979338
1.005314
if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.stop() when nothing running") if self._stack[-1] != name: raise AssertionError( "MultiTimer...
def stop(self, name: str) -> None
Stop a named timer. Args: name: timer to stop
6.164092
6.253004
0.985781
while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self._totaldurations.items(): grand_total += duration log.info...
def report(self) -> None
Finish and report to the log.
3.11259
3.035246
1.025482
vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonlat *= -1 n = len(lonlat) if sheet == 'lower': lonlat = lonlat[::-1] vertices +=...
def girdle_error(ax, fit, **kwargs)
Plot an attitude measurement on an `mplstereonet` axes object.
4.951186
4.954129
0.999406
ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat) plot_patch(ax, vertices, codes, **kwargs)
def pole_error(ax, fit, **kwargs)
Plot the error to the pole to a plane on a `mplstereonet` axis object.
7.406419
7.4286
0.997014
if sys.platform == "win32": timeout_ms = timeout_s * 1000 args = [ "ping", hostname, "-n", "1", # ping count "-w", str(timeout_ms), # timeout ] elif sys.platform.startswith('linux'): args = [ "ping", h...
def ping(hostname: str, timeout_s: int = 5) -> bool
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful?
2.189099
2.173485
1.007184
log.info("Downloading from {} to {}", url, filename) # urllib.request.urlretrieve(url, filename) # ... sometimes fails (e.g. downloading # https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with: # ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl....
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check?
4.61217
4.436889
1.039506
for url in urls: if on_disk: # Necessary for e.g. zip processing (random access) with tempfile.TemporaryDirectory() as tmpdir: filename = os.path.join(tmpdir, "tempfile") download(url=url, filename=filename) with open(filename, 'rb...
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress...
2.953383
2.945069
1.002823
# noqa length_of_fragment = 1 if overlap else len(x) i = -length_of_fragment for _ in range(n + 1): i = s.find(x, i + length_of_fragment) if i < 0: break return i
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int
Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to overlap. If not, they must be distinct. As per https://stackove...
3.080889
3.098132
0.994434
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
def split_string(x: str, n: int) -> List[str]
Split string into chunks of length n
2.751735
2.788754
0.986726
rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
def multiple_replace(text: str, rep: Dict[str, str]) -> str
Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings.
1.687576
1.766556
0.955292
newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]
Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings
4.971415
4.286078
1.159898
# http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) .encode('ascii', 'ignore') # gets rid of accents .decode('ascii') # back to a string ...
def mangle_unicode_to_ascii(s: Any) -> str
Mangle unicode to ASCII, losing accents etc. in the process.
3.506061
3.093325
1.133428
return "{}{}{}".format(prefix, num, suffix)
def strnum(prefix: str, num: int, suffix: str = "") -> str
Makes a string of the format ``<prefix><number><suffix>``.
8.847393
4.926079
1.796031
return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]
Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list.
3.667969
4.864317
0.754056
return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]
Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list.
3.938694
4.20083
0.937599
A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjust(hspace=0, wspace=0.1) kw = dict(c="#555555", s=40, alpha=0.5) #lengths = attitude.pca.singular_values[::-1] lengths = (A[:,i].max()-A[:,i].min() for i in range(3)) titles = ( ...
def aligned_residuals(pca)
Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset.
4.476766
4.567373
0.980162
try: return self._instance except AttributeError: self._instance = self._decorated() return self._instance
def get_instance(self)
Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned.
3.700553
2.884726
1.282809
self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
def mapper_init(self)
build local spatial index of US metro areas
39.40966
24.391924
1.615685
try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
def reducer_init_output(self)
establish connection to MongoDB
10.473696
8.050426
1.301011
slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.slug = uuslug( self.name, instance=self, max_length=100, separator="-", start_no=2 ) s...
def save(self, *args, **kwargs)
**uid**: :code:`division:{parentuid}_{levelcode}-{code}`
3.503063
2.859648
1.224998
relationship, created = IntersectRelationship.objects.update_or_create( from_division=self, to_division=division, defaults={"intersection": intersection}, ) if symm: division.add_intersecting(self, None, False) return relationship
def add_intersecting(self, division, intersection=None, symm=True)
Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on one side of the relationship when adding a peer.
3.6095
3.76249
0.959338
IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
def remove_intersecting(self, division, symm=True)
Removes paired relationships between intersecting divisions
5.35134
4.733406
1.130547
IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
def set_intersection(self, division, intersection)
Set intersection percentage of intersecting divisions.
6.881542
6.66243
1.032888
try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception("No intersecting relationship with that division.")
def get_intersection(self, division)
Get intersection percentage of intersecting divisions.
5.91644
5.357217
1.104387
if partition: partition_cmd = "#SBATCH -p {}".format(partition) else: partition_cmd = "" if modules is None: modules = ["default-wbic"] log.info("Launching SLURM job: {}", jobname) script = .format( # noqa cmd=cmd, cpus_per_task=cpus_per_task, d...
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: s...
Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum durati...
2.931262
3.000194
0.977024
if modules is None: modules = ["default-wbic"] launch_slurm( cmd=cmd, cpus_per_task=cpus_per_task, directory=directory, duration=duration, email=email, encoding=encoding, jobname=jobname, memory_mb=memory_mb, modules=modules, ...
def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str = "wbic-cs", # 2018-02: was "wbic", now "wbic-...
Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI.
2.103306
1.871216
1.124032
drug_name = drug_name.strip().lower() if name_is_generic: drug = DRUGS_BY_GENERIC_NAME.get(drug_name) # type: Optional[Drug] if drug is not None and drug.category_not_drug and not include_categories: # noqa return None return drug else: for d in DRUGS: ...
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]
Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs.
2.69302
3.08358
0.873342
drug = get_drug(drug_name, include_categories=include_categories) if drug is not None: return drug.generic_name return default if unknown_to_default else drug_name
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str
Converts a drug name to the name of its generic equivalent.
3.034594
2.56785
1.181764
return [ drug_name_to_generic(drug, unknown_to_default=unknown_to_default, default=default, include_categories=include_categories) for drug in drugs ]
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]
Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. t...
1.960129
2.833157
0.691853
for attribute, value in criteria.items(): if getattr(drug, attribute) != value: return False return True
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool
Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword argum...
3.514419
4.457637
0.788404
matching_drugs = [] # type: List[Drug] for drug in DRUGS: if drug.category_not_drug and not include_categories: continue if drug_matches_criteria(drug, **criteria): matching_drugs.append(drug) if sort: matching_drugs.sort(key=lambda d: d.generic_name) ...
def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]
Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatr...
2.761605
2.624561
1.052216
drug = get_drug(drug_name, name_is_generic) if drug is None: return False if drug.category_not_drug and not include_categories: return False return drug_matches_criteria(drug, **criteria)
def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool
Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`.
3.755039
3.297311
1.138819
return [ drug_name_matches_criteria( dn, name_is_generic=names_are_generic, include_categories=include_categories, **criteria) for dn in drug_names ]
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]
Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`.
2.62895
3.023508
0.869503
if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boundary and not p.startswith(WB): p = WB + p if self.add_preceding_wildca...
def regex_text(self) -> str
Return regex text (yet to be compiled) for this drug.
2.892672
2.742408
1.054793
if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
def regex(self) -> Pattern
Returns a compiled regex for this drug.
3.046835
2.377861
1.281334
def append_to_all(new_content: str) -> None: nonlocal results results = [r + new_content for r in results] def split_and_append(new_options: List[str]) -> None: nonlocal results newresults = [] # type: List[str] for option in new_opt...
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]
Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an unde...
3.452179
3.555757
0.97087
if self._sql_like_fragments is None: self._sql_like_fragments = [] for p in list(set(self.all_generics + self.alternatives)): self._sql_like_fragments.extend(self.regex_to_sql_like(p)) return self._sql_like_fragments
def sql_like_fragments(self) -> List[str]
Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``.
3.511734
3.749115
0.936683
return bool(self.regex.match(name))
def name_matches(self, name: str) -> bool
Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace.
13.226983
11.902878
1.111242
clauses = [ "{col} LIKE {fragment}".format( col=column_name, fragment=sql_string_literal(f)) for f in self.sql_like_fragments ] return "({})".format(" OR ".join(clauses))
def sql_column_like_drug(self, column_name: str) -> str
Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragme...
5.749141
5.684898
1.011301
return N.cos(angle/2)+vector*N.sin(angle/2)
def quaternion(vector, angle)
Unit quaternion for a vector and an angle
5.468664
5.352729
1.021659
u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([N.cos(u),N.sin(u)]).T
def ellipse(n=1000, adaptive=False)
Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given.
7.615678
7.888971
0.965358
dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
def scale_errors(cov_axes, confidence_level=0.95)
Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic
5.446911
5.04999
1.078598
level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes *= -1 # Not sure where this factor comes from but it # seems to make things work better c1 = 2 axis...
def normal_errors(axes, covariance_matrix, **kwargs)
Currently assumes upper hemisphere of stereonet
6.367432
6.01611
1.058397
level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.sqrt(covariance_matrix) ell = ellipse(**kwargs) bundle = dot(ell, d[:2]) res = d[2]*level # Switch hemispheres if PCA is upside-down # Normal vector is always correctly fit #if tra...
def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs)
kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the compass points of strike around the equator. Thus, longitude at the equat...
5.837768
5.474831
1.066292
sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_matrix)) u = N.linspace(0, 2*N.pi, n) scales = dict(upper=1,lower=-1,nominal=0) c1 = scales[sheet] c1 *= -1 # We assume upper hemisphere if axes[2,2] < ...
def iterative_plane_errors(axes,covariance_matrix, **kwargs)
An iterative version of `pca.plane_errors`, which computes an error surface for a plane.
4.083219
4.158557
0.981884
if debug_force_quote: return cls.quote_identifier(identifier) if cls.is_quoted(identifier): return identifier if cls.requires_quoting(identifier): return cls.quote_identifier(identifier) return identifier
def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str
Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless).
2.729841
2.470024
1.105188
topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topojson)
def to_topojson(self)
Adds points and converts to topojson string.
3.10373
2.708162
1.146065
try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) if element.id is None: raise Exce...
def post(self, element)
:param element: Element to post to Netuitive :type element: object
2.872169
2.788677
1.029939
if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) payload = json.dumps( [event], default=lambda o: o.__dict__, sort_keys=True) logging.debug(payload) ...
def post_event(self, event)
:param event: Event to post to Netuitive :type event: object
2.844239
2.779305
1.023363
if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) url = self.checkurl + '/' \ + check.name + '/' \ + check.elementId + '/' \ + str(check....
def post_check(self, check)
:param check: Check to post to Metricly :type check: object
4.550417
4.409215
1.032024
p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m.group('port') _scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url)) return scheme, host, port, path, query
def urlsplit(url)
Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query
3.401814
3.889139
0.874696
url = "" if scheme is not None: url += "%s://" % scheme if host is not None: url += host if port is not None: url += ":%s" % str(port) if path is not None: url += ensure_url_path_starts_with_slash(path) if query is not None: url += "?%s" % (urlencode(...
def generate_url(scheme=None, host=None, port=None, path=None, query=None)
Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return:
1.865174
1.981247
0.941414
states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} > from < {1} >" logging.info(log.format(state, url)) tmp = self.download(self.output, url, self.overwrite) ...
def run(self)
For each state in states file build url and download file
6.311085
5.024128
1.256155
tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') logging.info("Downloading {0}".format(url)) res = requests.get(url...
def download(self, output_dir, url, overwrite)
Dowload file to /tmp
2.446179
2.404959
1.01714
logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): for node in nodes: node_id, tags, coordinates = node ...
def extract(self, pbf, output)
extract POI nodes from osm pbf extract
4.021692
3.739771
1.075385
filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
def url2tmp(self, root, url)
convert url path to filename
3.059945
2.468653
1.23952
if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else default
def ask_user(prompt: str, default: str = None) -> Optional[str]
Prompts the user, with a default. Returns user input from ``stdin``.
2.430526
2.288932
1.061861
root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.asksaveasfilename( ...
def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename.
5.159103
5.009816
1.029799
root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.askopenfilename( ...
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str
Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename.
5.40815
5.082765
1.064017
# noqa lv = v.lower() if lv in ('yes', 'true', 't', 'y', '1'): return True elif lv in ('no', 'false', 'f', 'n', '0'): return False else: raise ArgumentTypeError('Boolean value expected.')
def str2bool(v: str) -> bool
``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n', '0' False From https://...
1.958103
2.65189
0.73838
try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid positive int".format(value)) return ivalue
def positive_int(value: str) -> int
``argparse`` argument type that checks that its value is a positive integer.
3.330525
3.354889
0.992738
try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid percentage value".format(value)) return fvalue
def percentage(value: str) -> float
``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]).
3.410729
3.097121
1.101258
self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
def abort_request(self, request)
Called to abort request on timeout
9.265107
7.729397
1.198684
if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, timeout)
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120)
Make an HTTP request and return the body
7.800386
8.26755
0.943494
if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) defer.returnValue(json.loads(body))
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120)
Fetch a JSON result via HTTP
3.766846
3.775784
0.997633
cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
def aligned_covariance(fit, type='noise')
Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space
9.23319
7.471536
1.235782
return N.degrees(angle(fit1.normal,fit2.normal))
def fit_angle(fit1, fit2, degrees=True)
Finds the angle between the nominal vectors
12.358267
12.255874
1.008355
cov1 = aligned_covariance(fit1) cov2 = aligned_covariance(fit2) if fit2.axes[2,2] < 0: cov2 *= -1 v0 = fit1.normal-fit2.normal cov0 = cov1+cov2 # Axes are aligned, so no covariances # Find distance of point from center # Decompose covariance matrix U,s,V = N.linalg.svd(cov...
def fit_similarity(fit1, fit2)
Distance apart for vectors, given in standard deviations
7.398742
7.158973
1.033492
I = N.eye(3) xy = I[:2] xz = N.vstack((I[0],I[2])) yz = I[1:] return xy,xz,yz
def axis_aligned_transforms()
Generates three transformation matrices to map three-dimensional data down to slices on the xy, xz and yz planes, respectively. The typical use case for this is to iterate over the results of this method to provide arguments to e.g. the `HyperbolicErrors` function.
4.514829
4.595745
0.982393
if fig is None: return "" # Make a file-like object memfile = io.BytesIO() # In general, can do # fig.savefig(filename/file-like-object/backend, format=...) # or # backend.savefig(fig): # see e.g. http://matplotlib.org/api/backend_pdf_api.html fig.savefig(memfile, fo...
def png_img_html_from_pyplot_figure(fig: "Figure", dpi: int = 100, extra_html_class: str = None) -> str
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
4.961887
4.720068
1.051232
if fig is None: return "" memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode fig.savefig(memfile, format="svg") return memfile.getvalue().decode("utf-8")
def svg_html_from_pyplot_figure(fig: "Figure") -> str
Converts a ``pyplot`` figure to an SVG tag.
4.404652
3.909207
1.126738
font = { # http://stackoverflow.com/questions/3899980 # http://matplotlib.org/users/customizing.html 'family': 'sans-serif', # ... serif, sans-serif, cursive, fantasy, monospace 'style': 'normal', # normal (roman), italic, oblique 'variant': 'normal', # normal,...
def set_matplotlib_fontsize(matplotlib: ModuleType, fontsize: Union[int, float] = 12) -> None
Sets the current font size within the ``matplotlib`` library. **WARNING:** not an appropriate method for multithreaded environments, as it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for alternative methods.
3.395958
3.251785
1.044337
m_keys = [] for key in keys: if key.startswith('keybase:'): m_keys.append(cryptorito.key_from_keybase(key[8:])['fingerprint']) else: m_keys.append(key) return m_keys
def massage_keys(keys)
Goes through list of GPG/Keybase keys. For the keybase keys it will attempt to look up the GPG key
4.868616
4.388221
1.109474
keys = massage_keys(csv_keys.split(',')) cryptorito.encrypt(src, dest, keys)
def encrypt_file(src, dest, csv_keys)
Encrypt a file with the specific GPG keys and write out to the specified path
9.939693
11.559588
0.859866
keys = massage_keys(csv_keys.split(',')) data = sys.stdin.read() encrypted = cryptorito.encrypt_var(data, keys) print(cryptorito.portable_b64encode(encrypted))
def encrypt_var(csv_keys)
Encrypt what comes in from stdin and return base64 encrypted against the specified keys, returning on stdout
6.48186
5.522192
1.173784
encrypted = cryptorito.portable_b64decode(sys.stdin.read()) print(cryptorito.decrypt_var(encrypted, passphrase))
def decrypt_var(passphrase=None)
Decrypt what comes in from stdin (base64'd) and write it out to stdout
9.470278
8.611513
1.099723