text stringlengths 81 112k |
|---|
Sends a pre-built e-mail message.
Args:
from_addr: e-mail address for 'From:' field
to_addrs: address or list of addresses to transmit to
host: mail server host
user: username on mail server
password: password for username on mail server
port: port to use, or ``None... |
Sends an e-mail in text/html format using SMTP via TLS.
Args:
host: mail server host
user: username on mail server
password: password for username on mail server
port: port to use, or ``None`` for protocol default
use_tls: use TLS, rather than plain SMTP?
da... |
Command-line processor. See ``--help`` for details.
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_arg... |
Parse a string of C/C++ code
def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) |
Parse a C/C++ file
def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) |
Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDED_FOR``) header
Returns:
a list of IP address as st... |
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
... |
Queue a job in Rhumba
def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid... |
Retrieve the result of a job from its ID
def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = yield self.client.get('rhumba.q.... |
Returns a dict of cluster nodes and their status information
def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
servers = yield self.client.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in s... |
Queue a job in Rhumba
def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid... |
Retrieve the result of a job from its ID
def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = self._get_client().get('rhumba.q... |
Returns a dict of cluster nodes and their status information
def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
c = self._get_client()
servers = c.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
... |
Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1.
def toposimplify(geojson, p):
"""
Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification ... |
Gets SQL Server version information.
Attempted to use ``dialect.server_version_info``:
.. code-block:: python
from sqlalchemy import create_engine
url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME"
engine = create_engine(url)
dialect = engine.dialect
vi = dialect.server_v... |
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later?
def is_sqlserver_2008_or_later(engine: "Engine") -> bool:
"""
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later?
"""
if not is_sqlserver(engine):
retu... |
Adds a column of 1s at the end of the array
def add_ones(a):
"""Adds a column of 1s at the end of the array"""
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr |
uninstall the hook if installed
def _uninstall(cls):
"""
uninstall the hook if installed
"""
if cls._hook:
sys.meta_path.remove(cls._hook)
cls._hook = None |
add a couple of fsts to be superimposed on the module given
by module_name as soon as it is imported.
internal - use featuremonkey.compose_later
def add(cls, module_name, fsts, composer):
'''
add a couple of fsts to be superimposed on the module given
by module_name as soon as ... |
Until the guard is dropped again,
disallow imports of the module given by ``module_name``.
If the module is imported while the guard is in place
an ``ImportGuard`` is raised. An additional message on why
the module cannot be imported can optionally be specified
using the paramet... |
drop a previously created guard on ``module_name``
if the module is not guarded, then this is a no-op.
def remove(cls, module_name):
"""
drop a previously created guard on ``module_name``
if the module is not guarded, then this is a no-op.
"""
module_guards = cls._guards... |
Random selection from itertools.product(*args, **kwds)
def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools) |
Use self as a template to build a new feature, replacing
values in kwargs
def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a templ... |
Return true if this feature stored, or is unstored, but can be computed
from stored dependencies
def _can_compute(self, _id, persistence):
"""
Return true if this feature stored, or is unstored, but can be computed
from stored dependencies
"""
if self.store and self._sto... |
TODO: _partial is a shit name for this, kind of. I'm building a graph
such that I can only do work necessary to compute self, and no more
def _partial(self, _id, features=None, persistence=None):
"""
TODO: _partial is a shit name for this, kind of. I'm building a graph
such that I can... |
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row
def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args... |
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the firs... |
Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row, as an :class:`OrderedDict` whose key are column names
and whose values are the row values
def gendicts(cursor: ... |
Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the row values
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:... |
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not... |
Used when building Colander nodes.
Args:
values: an iterable of tuples like ``(value, description)`` used in
HTML forms
add_none: add a tuple ``(None, none_description)`` at the start of
``values`` in the result?
none_description: the description used for ``None`` ... |
Serializes Python object to string representation.
def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to strin... |
Deserializes string representation to Python object.
def deserialize(self,
node: SchemaNode,
cstruct: Union[str, ColanderNullType]) \
-> Optional[Pendulum]:
"""
Deserializes string representation to Python object.
"""
if not cstruct:
... |
Serializes Python object to string representation.
def serialize(self, node: SchemaNode,
value: Any) -> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if value is None:
retval = ''
else:
# noinsp... |
returns list of feature names read from equation file given
by ``filename``.
format: one feature per line; comments start with ``#``
Example::
#this is a comment
basefeature
#empty lines are ignored
myfeature
anotherfeature
:param filename:
:return:
def g... |
applies refinement ``transformation`` to ``baseattr`` attribute of ``base``.
``baseattr`` can be any type of callable (function, method, functor)
this method handles the differences.
docstrings are also rescued from the original if the refinement
has no docstring set.
def _create_refine... |
composes onto base by applying the role
def _compose_pair(self, role, base):
'''
composes onto base by applying the role
'''
# apply transformations in role to base
for attrname in dir(role):
transformation = getattr(role, attrname)
self._apply_transforma... |
compose applies multiple fsts onto a base implementation.
Pass the base implementation as last parameter.
fsts are merged from RIGHT TO LEFT (like function application)
e.g.:
class MyFST(object):
#place introductions and refinements here
introduce_foo = 'bar'
... |
register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code
def compose_later(self, *things):
"""
regi... |
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module.
def select(self, *features):
"""
se... |
Plots the residuals of a principal component
analysis of attiude data.
def plot_aligned(pca, sparse=True, **kwargs):
""" Plots the residuals of a principal component
analysis of attiude data.
"""
colormap = kwargs.pop('colormap',None)
A = pca.rotated()
# Flip the result if upside d... |
map each osm POI and geotweets based on spatial lookup of metro area
def mapper_metro(self, _, data):
""" map each osm POI and geotweets based on spatial lookup of metro area """
# OSM POI record
if 'tags' in data:
type_tag = 1
lonlat = data['coordinates']
pa... |
Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet lookup nearby POI, and emit tag values for predefined tags.... |
count occurences for each (metro, POI) record
def reducer_count(self, key, values):
""" count occurences for each (metro, POI) record """
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) |
store each record in MongoDB and output tab delimited lines
def reducer_output(self, metro, values):
""" store each record in MongoDB and output tab delimited lines """
records = []
# build up list of data for each metro area and submit as one network
# call instead of individually
... |
Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been implemented (with a helpful error message).
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None:
"""
Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been imp... |
Takes a clause element that must have a single clause, and converts it
to raw SQL text.
def fetch_processed_single_clause(element: "ClauseElement",
compiler: "SQLCompiler") -> str:
"""
Takes a clause element that must have a single clause, and converts it
to raw SQL te... |
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"... |
Returns its parameter as a valid integer NHS number, or raises
``django.forms.ValidationError``.
def clean_nhs_number(x) -> int:
"""
Returns its parameter as a valid integer NHS number, or raises
``django.forms.ValidationError``.
"""
try:
x = int(x)
if not is_valid_nhs_number(x)... |
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as such instances, or as the
class type. This function ensures that such classes are converted to
instances.
To explain: you can specify columns like
.. code-block:: python
... |
Starting with a SQLAlchemy ORM object, this function walks a
relationship tree, yielding each of the objects once.
To skip attributes by name, put the attribute name(s) in
``skip_attrs_always``. To skip by table name, pass
``skip_attrs_by_tablename`` as e.g.
.. code-block:: python
{'somet... |
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies
across all attributes, omitting PKs (by default), FKs (by default), and
relationship attributes (always omitted).
Args:
obj: the object to copy
... |
A utility function only.
Used in copying objects between SQLAlchemy sessions.
Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance
``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its
relationships, according to the map ``objmap``, which maps old to new
objects.
... |
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a
new session.
This function operates in several passes:
1. Walk the ORM tree through all objects and their relationships, copying
every object thus found (via :func:`copy_sqla_object`, without their
relationships), an... |
Makes a copy of the object, inserting it into ``session``.
Uses :func:`deepcopy_sqla_objects` (q.v.).
A problem is the creation of duplicate dependency objects if you call it
repeatedly.
Optionally, if you pass the objmap in (which maps old to new objects), you
can call this function repeatedly t... |
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?"
Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object
instance. Also works with the corresponding SQLAlchemy ORM class. Examples:
.. code-block:: python
from sqlalchemy.ext.declarative import declarative_base
... |
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns
def get_pk_attrnames(obj) -> List[str]:
"""
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQ... |
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e.
one that does not inherit from ``declarative_base()``. Use this for mixins
of that kind.
SUBOPTIMAL. May produce warnings like:
.. code-block:: none
SAWarning: Unmanaged access of declarative attribute id from ... |
Asks an SQLAlchemy class how its attribute names correspond to database
column names.
Args:
cls: SQLAlchemy ORM class
Returns:
a dictionary mapping attribute names to database column names
def attrname_to_colname_dict(cls) -> Dict[str, str]:
"""
Asks an SQLAlchemy class how its at... |
Yields tuples of ``(attrname, RelationshipProperty, related_class)``
for all relationships of an ORM object.
The object 'obj' can be EITHER an instance OR a class.
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],
None, None]:
"""
Yi... |
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
def get_orm_columns(cls: Type) -> List[Column]:
"""
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
"""
mapper = inspect(cls) # type: Mapper
... |
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
... |
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values(... |
From an SQLAlchemy ORM base class, yield all the subclasses (except those
that are abstract).
If you begin with the proper :class`Base` class, then this should give all
ORM classes in use.
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
"""
From an SQLAlchemy ORM base cla... |
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are
table names and whose values are ORM classes.
If you begin with the proper :class`Base` class, then this should give all
tables and ORM classes in use.
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
""... |
Returns what looks like a plain object with the values of the
SQLAlchemy ORM object.
def get_attrdict(self) -> OrderedNamespace:
"""
Returns what looks like a plain object with the values of the
SQLAlchemy ORM object.
"""
# noinspection PyUnresolvedReferences
col... |
Builds a new instance of the ORM object from values in an attrdict.
def from_attrdict(cls, attrdict: OrderedNamespace) -> object:
"""
Builds a new instance of the ORM object from values in an attrdict.
"""
dictionary = attrdict.__dict__
# noinspection PyArgumentList
retu... |
Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
base: a base class
method_name: the name of a method
Returns:
whether the derived class method is (a) present, and (b) different to
the base class's... |
Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]:
"""
Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses
"""
for s1 in cls.__s... |
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices.
def augment_tensor(matrix, ndim=None):
"""
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension.... |
Find the angle between two vectors.
:param cos: If True, the cosine of the
angle will be returned. False by default.
def angle(v1,v2, cos=False):
"""
Find the angle between two vectors.
:param cos: If True, the cosine of the
angle will be returned. False by default.
"""
n = (norm(v1)*... |
Get a random vector perpendicular
to the given vector
def perpendicular_vector(n):
"""
Get a random vector perpendicular
to the given vector
"""
dim = len(n)
if dim == 2:
return n[::-1]
# More complex in 3d
for ix in range(dim):
_ = N.zeros(dim)
# Try to keep... |
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx
Un... |
Determines whether an OpenXML file appears to be good (not corrupted).
def is_openxml_good(filename: str) -> bool:
"""
Determines whether an OpenXML file appears to be good (not corrupted).
"""
try:
log.debug("Trying: {}", filename)
with ZipFile(filename, 'r') as zip_ref:
na... |
Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if ``True``, then prints the filename if the file
appears good.
delete_if_bad: if ``True``, then deletes the file if the file
... |
Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help.
def main() -> None:
"""
Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
... |
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
def open(self) -> bool:
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
... |
A measure of the distance between two probability distributions
def bhattacharyya_distance(pca1,pca2):
"""
A measure of the distance between two probability distributions
"""
u1 = pca1.coefficients
s1 = pca1.covariance_matrix
u2 = pca2.coefficients
s2 = pca2.covariance_matrix
sigma = (... |
Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- ... eh? What was I talking about?
- POOR; DEPRECATED.
Args:
filehandle: file to write to
fields: field names
values: values
def produce_csv_output(filehandle: TextIO,
... |
Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
filehandle: file to write to
values: values
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
"""
Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
fileha... |
Find the part of ``s`` that is after ``prefix``.
Args:
s: string to analyse
prefix: prefix to find
onlyatstart: only accept the prefix if it is right at the start of
``s``
stripwhitespace: remove whitespace from the result
Returns:
tuple: ``(found, result)``... |
Find a string in ``strings`` that begins with ``prefix``; return the part
that's after ``prefix``. Optionally, require that the preceding string
(line) is ``precedingline``.
Args:
strings: strings to analyse
prefix: prefix to find
onlyatstart: only accept the prefix if it is right a... |
Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get_what_follows`
ignoreleadingcolon: if ``True``, restrict the result to what comes
after its first colon (and whitespace-strip that)
precedingline: see :func:`... |
Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves
``delta`` lines (strings) further. Returns the end of the line that
begins with ``prefix2``, if found.
Args:
strings: as above
prefix1: as above
delta: as above
prefix2: as above
ignoreleadingcolo... |
Fetches an integer parameter via :func:`get_string`.
def get_int(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[int]:
"""
Fetches an integer parameter via :func:`get_string`.
"""
return get_int_raw(get_stri... |
Fetches a float parameter via :func:`get_string`.
def get_float(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string`.
"""
return get_float_raw(ge... |
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
def get_bool_raw(s: str) -> Optional[bool]:
"""
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
"""
if s == "Y" or s == "y":
return True
elif s == "N" or s == "n":
return False
return None |
Fetches a boolean parameter via :func:`get_string`.
def get_bool(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string`.
"""
return get_bool_raw(get_... |
Fetches a boolean parameter via :func:`get_string_relative`.
def get_bool_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[bool]:
"""
Fetches a boolean p... |
Fetches a float parameter via :func:`get_string_relative`.
def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float... |
Fetches an int parameter via :func:`get_string_relative`.
def get_int_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[int]:
"""
Fetches an int parameter via... |
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
def get_datetime(strings: Sequence[str],
prefix: str,
datetime_format_string: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[datetime.datetime]:
"""
... |
Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line.
def find_line_beginning(strings: Sequence[str],
linestart: Optional[str]) -> int:
"""
Finds the index of the line in ``strings``... |
Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found.
def find_line_containing(strings: Sequence[str], contents: str) -> int:
"""
Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found.
"""
for i in range(le... |
Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts``
(exclusive).
To search to the end of the list, use ``list_of_lastline_starts = []``.
To search to a blank line, use ``list_of_lastline_starts = [None]``
def get_lines... |
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for processing e.g. MonkeyCantab rescue text output.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parame... |
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parameter passed to :func:`csv.reader`
Returns:
list of dict... |
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``.
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries.... |
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, using
``datetime_format_string`` as the format parameter to
:func:`datetime.datetime.strptime`.
def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
... |
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to an integer. If that fails, convert it to ``None``.
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.