text
stringlengths
81
112k
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it def deduplicate(directories: L...
Command-line processor. See ``--help`` for details. def main() -> None: """ Command-line processor. See ``--help`` for details. """ parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories...
Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. ....
Returns the explanation associated with a Django choice tuple-list. def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: """ Returns the explanation associated with a Django choice tuple-list. """ for k, v in choices: if k == value: return v return ''
r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-a...
Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdo...
Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream def tee_log(tee_file: TextIO, loglevel: int) -> None: """ Context manager to add a file output stream to our l...
To act as a file. def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
To act as a file. def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
To act as a file. def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream ...
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. def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another ...
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'" def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Pyt...
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. def sql_datetime_literal(dt: DateTimeLikeType, su...
Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: ...
Reverses :func:`sql_quote_string`. def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ 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_...
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. def gen_items_from_sql_csv(s: str) -> Generator[str, No...
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). 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) t...
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. def merge_two_dicts(x...
Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
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...
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. def r...
Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. 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. """ result = {} # type: Dict[str, Any]...
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. 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``. """ if no...
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...
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 ...
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. def delete_keys(d: Dict[Any, Any], ke...
Convert things on the way from Python to the database. def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
Convert things on the way from the database to Python. def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
Convert things on the way from Python to the database. def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
Convert things on the way from the database to Python. def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
Reset the timers. def reset(self) -> None: """ Reset the timers. """ self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers? def set_timing(self, timing: bool, reset: bool = False) -> None: """ Manually set the ``timing`` parameter, and optionally reset the timer...
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increme...
Stop a named timer. Args: name: timer to stop def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check ...
Finish and report to the log. def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart ...
Plot an attitude measurement on an `mplstereonet` axes object. def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, ...
Plot the error to the pole to a plane on a `mplstereonet` axis object. def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes ...
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address ...
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL t...
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...
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...
Split string into chunks of length n def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
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. def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the key...
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 def replace_in_list(stringlist: Iterable[str]...
Mangle unicode to ASCII, losing accents etc. in the process. def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s...
Makes a string of the format ``<prefix><number><suffix>``. def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. 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 retur...
Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. 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...
Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimat...
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. def get_instance(self): """ Returns the singleton instance. Upon its first call, it c...
build local spatial index of US metro areas def mapper_init(self): """ build local spatial index of US metro areas """ self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
establish connection to MongoDB def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance ...
**uid**: :code:`division:{parentuid}_{levelcode}-{code}` def save(self, *args, **kwargs): """ **uid**: :code:`division:{parentuid}_{levelcode}-{code}` """ slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug...
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. def add_intersecting(self, division, i...
Removes paired relationships between intersecting divisions def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm...
Set intersection percentage of intersecting divisions. def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
Get intersection percentage of intersecting divisions. def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection ...
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...
Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI. def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hp...
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. def get_drug(drug_name: str, ...
Converts a drug name to the name of its generic equivalent. 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 o...
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...
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...
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...
Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`. def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, ...
Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = Fals...
Return regex text (yet to be compiled) for this drug. def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternat...
Returns a compiled regex for this drug. def regex(self) -> Pattern: """ Returns a compiled regex for this drug. """ if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
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...
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 ``%``. def sql_like_fragments(self) -> List[str]: """...
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. def name_matches(self, name: str) -> bool: """ Detects whethe...
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...
Unit quaternion for a vector and an angle def quaternion(vector, angle): """ Unit quaternion for a vector and an angle """ return N.cos(angle/2)+vector*N.sin(angle/2)
Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bu...
Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) r...
Currently assumes upper hemisphere of stereonet def normal_errors(axes, covariance_matrix, **kwargs): """ Currently assumes upper hemisphere of stereonet """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = elli...
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...
An iterative version of `pca.plane_errors`, which computes an error surface for a plane. def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level =...
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). def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ ...
Adds points and converts to topojson string. def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all...
:param element: Element to post to Netuitive :type element: object def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() ...
:param event: Event to post to Netuitive :type event: object def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' ...
:param check: Check to post to Metricly :type check: object def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' ...
Split url into scheme, host, port, path, query :param str 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 """ p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P...
Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: ...
For each state in states file build url and download file def run(self): """ For each state in states file build url and download file """ states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} ...
Dowload file to /tmp def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ 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 = ...
extract POI nodes from osm pbf extract def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ 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 d...
convert url path to filename def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
Prompts the user, with a default. Returns user input from ``stdin``. def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: ...
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. 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 f...
Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root ...
``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://...
``argparse`` argument type that checks that its value is a positive integer. def positive_int(value: str) -> int: """ ``argparse`` argument type that checks that its value is a positive integer. """ try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError...
``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). 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]). """ try: ...
Called to abort request on timeout def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
Make an HTTP request and return the body def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().reques...
Fetch a JSON result via HTTP def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Fetch a JSON result via HTTP """ if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, he...
Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Resca...