Search is not available for this dataset
text stringlengths 75 104k |
|---|
def log_entity_deletion(entity, params=None):
"""Logs an entity creation
"""
p = {'entity': entity}
if params:
p['params'] = params
_log(TYPE_CODES.DELETE, p) |
def log_operation(entities, operation_name, params=None):
"""Logs an operation done on an entity, possibly with other arguments
"""
if isinstance(entities, (list, tuple)):
entities = list(entities)
else:
entities = [entities]
p = {'name': operation_name, 'on': entities}
if param... |
def log_state(entity, state):
"""Logs a new state of an entity
"""
p = {'on': entity, 'state': state}
_log(TYPE_CODES.STATE, p) |
def log_update(entity, update):
"""Logs an update done on an entity
"""
p = {'on': entity, 'update': update}
_log(TYPE_CODES.UPDATE, p) |
def log_error(error, result):
"""Logs an error
"""
p = {'error': error, 'result':result}
_log(TYPE_CODES.ERROR, p) |
def dict_cursor(func):
"""
Decorator that provides a dictionary cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorTyp... |
def cursor(func):
"""
Decorator that provides a cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor() coroutine or provides such an objec... |
def nt_cursor(func):
"""
Decorator that provides a namedtuple cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.... |
def transaction(func):
"""
Provides a transacted cursor which will run in autocommit=false mode
For any exception the transaction will be rolled back.
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTU... |
def connect(cls, database: str, user: str, password: str, host: str, port: int, *, use_pool: bool=True,
enable_ssl: bool=False, minsize=1, maxsize=50, keepalives_idle=5, keepalives_interval=4, echo=False,
**kwargs):
"""
Sets connection parameters
For more informat... |
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method')
if not cls._pool:
cls._pool = yield from create_pool(**c... |
def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor:
"""
Yields:
new client-side cursor from existing db connection pool
"""
_cur = None
if cls._use_pool:
_connection_source = yield from cls.get_pool()
else:
_connection_source ... |
def count(cls, cur, table:str, where_keys: list=None):
"""
gives the number of records in the table
Args:
table: a string indicating the name of the table
Returns:
an integer indicating the number of records in the table
"""
if where_keys:
... |
def insert(cls, cur, table: str, values: dict):
"""
Creates an insert statement with only chosen fields
Args:
table: a string indicating the name of the table
values: a dict of fields and values to be inserted
Returns:
A 'Record' object with table co... |
def update(cls, cur, table: str, values: dict, where_keys: list) -> tuple:
"""
Creates an update query with only chosen fields
Supports only a single field where clause
Args:
table: a string indicating the name of the table
values: a dict of fields and values to ... |
def delete(cls, cur, table: str, where_keys: list):
"""
Creates a delete query with where keys
Supports multiple where clause with and or or both
Args:
table: a string indicating the name of the table
where_keys: list of dictionary
example of where ke... |
def select(cls, cur, table: str, order_by: str, columns: list=None, where_keys: list=None, limit=100,
offset=0):
"""
Creates a select query for selective columns with where keys
Supports multiple where claus with and or or both
Args:
table: a string indicating... |
def raw_sql(cls, cur, query: str, values: tuple):
"""
Run a raw sql query
Args:
query : query string to execute
values : tuple of values to be used with the query
Returns:
result of query as list of named tuple
"""
yield from cur.exe... |
def serialize_text(out, text):
"""This method is used to append content of the `text`
argument to the `out` argument.
Depending on how many lines in the text, a
padding can be added to all lines except the first
one.
Concatenation result is appended to the `out` argument.
"""
padding =... |
def serialize_list(out, lst, delimiter=u'', max_length=20):
"""This method is used to serialize list of text
pieces like ["some=u'Another'", "blah=124"]
Depending on how many lines are in these items,
they are concatenated in row or as a column.
Concatenation result is appended to the `out` argum... |
def format_value(value):
"""This function should return unicode representation of the value
"""
value_id = id(value)
if value_id in recursion_breaker.processed:
return u'<recursion>'
recursion_breaker.processed.add(value_id)
try:
if isinstance(value, six.binary_type):
... |
def make_repr(*args, **kwargs):
"""Returns __repr__ method which returns ASCII
representaion of the object with given fields.
Without arguments, ``make_repr`` generates a method
which outputs all object's non-protected (non-undercored)
arguments which are not callables.
Accepts ``*args``, whic... |
def connect(self, host, port, minsize=5, maxsize=10, loop=asyncio.get_event_loop()):
"""
Setup a connection pool
:param host: Redis host
:param port: Redis port
:param loop: Event loop
"""
self._pool = yield from aioredis.create_pool((host, port), minsize=minsize,... |
def set_key(self, key, value, namespace=None, expire=0):
"""
Set a key in a cache.
:param key: Key name
:param value: Value
:param namespace : Namespace to associate the key with
:param expire: expiration
:return:
"""
with (yield from self._pool) a... |
def traverse(element, query, deep=False):
"""
Helper function to traverse an element tree rooted at element, yielding nodes matching the query.
"""
# Grab the next part of the query (it will be chopped from the front each iteration).
part = query[0]
if not part:
# If the part is blank, w... |
def parse_query(query):
"""
Given a simplified XPath query string, returns an array of normalized query parts.
"""
parts = query.split('/')
norm = []
for p in parts:
p = p.strip()
if p:
norm.append(p)
elif '' not in norm:
norm.append('')
return... |
def parse(url_or_path, encoding=None, handler_class=DrillHandler):
"""
:param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement`
"""
handler = handler_class()
parser = expat.ParserCreate(encoding)
parser.buffer_text = 1
parse... |
def iterparse(filelike, encoding=None, handler_class=DrillHandler, xpath=None):
"""
:param filelike: A file-like object with a ``read`` method
:returns: An iterator yielding :class:`XmlElement` objects
"""
parser = expat.ParserCreate(encoding)
elem_iter = DrillElementIterator(filelike, parser)
... |
def write(self, writer):
"""
Writes an XML representation of this node (including descendants) to the specified file-like object.
:param writer: An :class:`XmlWriter` instance to write this node to
"""
multiline = bool(self._children)
newline_start = multiline and not bo... |
def xml(self, **kwargs):
"""
Returns an XML representation of this node (including descendants). This method automatically creates an
:class:`XmlWriter` instance internally to handle the writing.
:param **kwargs: Any named arguments are passed along to the :class:`XmlWriter` constructor... |
def append(self, name, attrs=None, data=None):
"""
Called when the parser detects a start tag (child element) while in this node. Internally creates an
:class:`XmlElement` and adds it to the end of this node's children.
:param name: The tag name to add
:param attrs: Attributes f... |
def insert(self, before, name, attrs=None, data=None):
"""
Inserts a new element as a child of this element, before the specified index or sibling.
:param before: An :class:`XmlElement` or a numeric index to insert the new node before
:param name: The tag name to add
:param attr... |
def items(self):
"""
A generator yielding ``(key, value)`` attribute pairs, sorted by key name.
"""
for key in sorted(self.attrs):
yield key, self.attrs[key] |
def children(self, name=None, reverse=False):
"""
A generator yielding children of this node.
:param name: If specified, only consider elements with this tag name
:param reverse: If ``True``, children will be yielded in reverse declaration order
"""
elems = self._childre... |
def _match(self, pred):
"""
Helper function to determine if this node matches the given predicate.
"""
if not pred:
return True
# Strip off the [ and ]
pred = pred[1:-1]
if pred.startswith('@'):
# An attribute predicate checks the existence... |
def path(self, include_root=False):
"""
Returns a canonical path to this element, relative to the root node.
:param include_root: If ``True``, include the root node in the path. Defaults to ``False``.
"""
path = '%s[%d]' % (self.tagname, self.index or 0)
p = self.parent
... |
def iter(self, name=None):
"""
Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will
yield every descendant node.
:param name: If specified, only consider elements with this tag name
:returns: A generator yielding descendants ... |
def last(self, name=None):
"""
Returns the last child of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
for c in self.children(name, reverse=True):
return c |
def parents(self, name=None):
"""
Yields all parents of this element, back to the root element.
:param name: If specified, only consider elements with this tag name
"""
p = self.parent
while p is not None:
if name is None or p.tagname == name:
... |
def siblings(self, name=None):
"""
Yields all siblings of this node (not including the node itself).
:param name: If specified, only consider elements with this tag name
"""
if self.parent and self.index:
for c in self.parent._children:
if c.index != ... |
def next(self, name=None):
"""
Returns the next sibling of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
if self.parent is None or self.index is None:
return None
for idx in xrange(self... |
def prev(self, name=None):
"""
Returns the previous sibling of this node.
:param name: If specified, only consider elements with this tag name
:rtype: :class:`XmlElement`
"""
if self.parent is None or self.index is None:
return None
for idx in xrange(... |
def get_observations(self):
"""
Parses the HTML table into a list of dictionaries, each of which
represents a single observation.
"""
if self.empty:
return []
rows = list(self.tbody)
observations = []
for row_observation, row_details in zip(row... |
def get_cache_key(prefix, *args, **kwargs):
"""
Calculates cache key based on `args` and `kwargs`.
`args` and `kwargs` must be instances of hashable types.
"""
hash_args_kwargs = hash(tuple(kwargs.iteritems()) + args)
return '{}_{}'.format(prefix, hash_args_kwargs) |
def cache_method(func=None, prefix=''):
"""
Cache result of function execution into the `self` object (mostly useful in models).
Calculate cache key based on `args` and `kwargs` of the function (except `self`).
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):... |
def cache_func(prefix, method=False):
"""
Cache result of function execution into the django cache backend.
Calculate cache key based on `prefix`, `args` and `kwargs` of the function.
For using like object method set `method=True`.
"""
def decorator(func):
@wraps(func)
def wrappe... |
def get_or_default(func=None, default=None):
"""
Wrapper around Django's ORM `get` functionality.
Wrap anything that raises ObjectDoesNotExist exception
and provide the default value if necessary.
`default` by default is None. `default` can be any callable,
if it is callable it will be called wh... |
def _get_column_nums_from_args(columns):
"""Turn column inputs from user into list of simple numbers.
Inputs can be:
- individual number: 1
- range: 1-3
- comma separated list: 1,2,3,4-6
"""
nums = []
for c in columns:
for p in c.split(','):
p = p.strip()
... |
def _get_printable_columns(columns, row):
"""Return only the part of the row which should be printed.
"""
if not columns:
return row
# Extract the column values, in the order specified.
return tuple(row[c] for c in columns) |
def writerow(self, observation_data):
"""
Writes a single observation to the output file.
If the ``observation_data`` parameter is a dictionary, it is
converted to a list to keep a consisted field order (as described
in format specification). Otherwise it is assumed that the dat... |
def dict_to_row(cls, observation_data):
"""
Takes a dictionary of observation data and converts it to a list
of fields according to AAVSO visual format specification.
:param cls: current class
:param observation_data: a single observation as a dictionary
"""
row ... |
def row_to_dict(cls, row):
"""
Converts a raw input record to a dictionary of observation data.
:param cls: current class
:param row: a single observation as a list or tuple
"""
comment_code = row[3]
if comment_code.lower() == 'na':
comment_code = ''
... |
def get_default_tag(app):
'''Get the name of the view function used to prevent having to set the tag
manually for every endpoint'''
view_func = get_view_function(app, request.path, request.method)
if view_func:
return view_func.__name__ |
def get_view_function(app, url, method):
"""Match a url and return the view and arguments
it will be called with, or None if there is no view.
Creds: http://stackoverflow.com/a/38488506
"""
# pylint: disable=too-many-return-statements
adapter = app.create_url_adapter(request)
try:
... |
def download_observations(observer_code):
"""
Downloads all variable star observations by a given observer.
Performs a series of HTTP requests to AAVSO's WebObs search and
downloads the results page by page. Each page is then passed to
:py:class:`~pyaavso.parsers.webobs.WebObsResultsParser` and par... |
def get_random_filename(instance, filename):
"""
Generates random filename for uploading file using uuid4 hashes
You need to define UPLOADS_ROOT in your django settings
something like this
UPLOADS_ROOT = rel(MEDIA_ROOT, 'uploads')
"""
folder = settings.UPLOADS_ROOT
ext = filename.split(... |
def image_path(instance, filename):
"""Generates likely unique image path using md5 hashes"""
filename, ext = os.path.splitext(filename.lower())
instance_id_hash = hashlib.md5(str(instance.id)).hexdigest()
filename_hash = ''.join(random.sample(hashlib.md5(filename.encode('utf-8')).hexdigest(), 8))
r... |
async def get_ltd_product_urls(session):
"""Get URLs for LSST the Docs (LTD) products from the LTD Keeper API.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
Returns
---... |
async def get_ltd_product(session, slug=None, url=None):
"""Get the product resource (JSON document) from the LSST the Docs API.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
... |
async def process_lander_page(session, github_api_token, ltd_product_data,
mongo_collection=None):
"""Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session... |
async def _upload_to_mongodb(collection, jsonld):
"""Upsert the technote resource into the projectmeta MongoDB collection.
Parameters
----------
collection : `motor.motor_asyncio.AsyncIOMotorCollection`
The MongoDB collection.
jsonld : `dict`
The JSON-LD document that represents the... |
def json_doc_to_xml(json_obj, lang='en', custom_namespace=None):
"""Converts a Open511 JSON document to XML.
lang: the appropriate language code
Takes a dict deserialized from JSON, returns an lxml Element.
Accepts only the full root-level JSON object from an Open511 response."""
if 'meta' not in... |
def json_struct_to_xml(json_obj, root, custom_namespace=None):
"""Converts a Open511 JSON fragment to XML.
Takes a dict deserialized from JSON, returns an lxml Element.
This won't provide a conforming document if you pass in a full JSON document;
it's for translating little fragments, and is mostly us... |
def geojson_to_gml(gj, set_srs=True):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
tag = G(gj['type'])
if set_srs:
tag.set('srsName', 'urn:ogc:def:crs:EPSG::4326')
if gj['type'] == 'Point':
tag.append(G.pos(_revers... |
def geom_to_xml_element(geom):
"""Transform a GEOS or OGR geometry object into an lxml Element
for the GML geometry."""
if geom.srs.srid != 4326:
raise NotImplementedError("Only WGS 84 lat/long geometries (SRID 4326) are supported.")
# GeoJSON output is far more standard than GML, so go through ... |
def remove_comments(tex_source):
"""Delete latex comments from TeX source.
Parameters
----------
tex_source : str
TeX source content.
Returns
-------
tex_source : str
TeX source without comments.
"""
# Expression via http://stackoverflow.com/a/13365453
return re... |
def read_tex_file(root_filepath, root_dir=None):
r"""Read a TeX file, automatically processing and normalizing it
(including other input files, removing comments, and deleting trailing
whitespace).
Parameters
----------
root_filepath : `str`
Filepath to a TeX file.
root_dir : `str`
... |
def process_inputs(tex_source, root_dir=None):
r"""Insert referenced TeX file contents (from ``\input`` and ``\include``
commands) into the source.
Parameters
----------
tex_source : `str`
TeX source where referenced source files will be found and inserted.
root_dir : `str`, optional
... |
def replace_macros(tex_source, macros):
r"""Replace macros in the TeX source with their content.
Parameters
----------
tex_source : `str`
TeX source content.
macros : `dict`
Keys are macro names (including leading ``\``) and values are the
content (as `str`) of the macros. S... |
def ensure_format(doc, format):
"""
Ensures that the provided document is an lxml Element or json dict.
"""
assert format in ('xml', 'json')
if getattr(doc, 'tag', None) == 'open511':
if format == 'json':
return xml_to_json(doc)
elif isinstance(doc, dict) and 'meta' in doc:
... |
def open511_convert(input_doc, output_format, serialize=True, **kwargs):
"""
Convert an Open511 document between formats.
input_doc - either an lxml open511 Element or a deserialized JSON dict
output_format - short string name of a valid output format, as listed above
"""
try:
output_fo... |
def read(cls, root_tex_path):
"""Construct an `LsstLatexDoc` instance by reading and parsing the
LaTeX source.
Parameters
----------
root_tex_path : `str`
Path to the LaTeX source on the filesystem. For multi-file LaTeX
projects this should be the path to... |
def html_title(self):
"""HTML5-formatted document title (`str`)."""
return self.format_title(format='html5', deparagraph=True,
mathjax=False, smart=True) |
def html_short_title(self):
"""HTML5-formatted document short title (`str`)."""
return self.format_short_title(format='html5', deparagraph=True,
mathjax=False, smart=True) |
def html_authors(self):
"""HTML5-formatted authors (`list` of `str`)."""
return self.format_authors(format='html5', deparagraph=True,
mathjax=False, smart=True) |
def html_abstract(self):
"""HTML5-formatted document abstract (`str`)."""
return self.format_abstract(format='html5', deparagraph=False,
mathjax=False, smart=True) |
def is_draft(self):
"""Document is a draft if ``'lsstdoc'`` is included in the
documentclass options (`bool`).
"""
if not hasattr(self, '_document_options'):
self._parse_documentclass()
if 'lsstdraft' in self._document_options:
return True
else:
... |
def format_content(self, format='plain', mathjax=False,
smart=True, extra_args=None):
"""Get the document content in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'plain'``).
... |
def format_title(self, format='html5', deparagraph=True, mathjax=False,
smart=True, extra_args=None):
"""Get the document title in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'plain'... |
def format_short_title(self, format='html5', deparagraph=True,
mathjax=False, smart=True, extra_args=None):
"""Get the document short title in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'htm... |
def format_abstract(self, format='html5', deparagraph=False, mathjax=False,
smart=True, extra_args=None):
"""Get the document abstract in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or... |
def format_authors(self, format='html5', deparagraph=True, mathjax=False,
smart=True, extra_args=None):
"""Get the document authors in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'... |
def _parse_documentclass(self):
"""Parse documentclass options.
Sets the the ``_document_options`` attribute.
"""
command = LatexCommand(
'documentclass',
{'name': 'options', 'required': False, 'bracket': '['},
{'name': 'class_name', 'required': True,... |
def _parse_title(self):
"""Parse the title from TeX source.
Sets these attributes:
- ``_title``
- ``_short_title``
"""
command = LatexCommand(
'title',
{'name': 'short_title', 'required': False, 'bracket': '['},
{'name': 'long_title',... |
def _parse_doc_ref(self):
"""Parse the document handle.
Sets the ``_series``, ``_serial``, and ``_handle`` attributes.
"""
command = LatexCommand(
'setDocRef',
{'name': 'handle', 'required': True, 'bracket': '{'})
try:
parsed = next(command.pa... |
def _parse_author(self):
r"""Parse the author from TeX source.
Sets the ``_authors`` attribute.
Goal is to parse::
\author{
A.~Author,
B.~Author,
and
C.~Author}
Into::
['A. Author', 'B. Author', 'C. Author']
"... |
def _parse_abstract(self):
"""Parse the abstract from the TeX source.
Sets the ``_abstract`` attribute.
"""
command = LatexCommand(
'setDocAbstract',
{'name': 'abstract', 'required': True, 'bracket': '{'})
try:
parsed = next(command.parse(self... |
def _prep_snippet_for_pandoc(self, latex_text):
"""Process a LaTeX snippet of content for better transformation
with pandoc.
Currently runs the CitationLinker to convert BibTeX citations to
href links.
"""
replace_cite = CitationLinker(self.bib_db)
latex_text = r... |
def _load_bib_db(self):
r"""Load the BibTeX bibliography referenced by the document.
This method triggered by the `bib_db` attribute and populates the
`_bib_db` private attribute.
The ``\bibliography`` command is parsed to identify the bibliographies
referenced by the document.... |
def _parse_revision_date(self):
r"""Parse the ``\date`` command, falling back to getting the
most recent Git commit date and the current datetime.
Result is available from the `revision_datetime` attribute.
"""
doc_datetime = None
# First try to parse the \date command ... |
def build_jsonld(self, url=None, code_url=None, ci_url=None,
readme_url=None, license_id=None):
"""Create a JSON-LD representation of this LSST LaTeX document.
Parameters
----------
url : `str`, optional
URL where this document is published to the web. P... |
def rename(self, from_name, to_name):
"""Renames an existing database."""
log.info('renaming database from %s to %s' % (from_name, to_name))
self._run_stmt('alter database %s rename to %s' % (from_name, to_name)) |
def connections(self, name):
"""Returns a list of existing connections to the named database."""
stmt = """
select {fields} from pg_stat_activity
where datname = {datname!r} and pid <> pg_backend_pid()
""".format(fields=', '.join(CONNECTION_FIELDS), datname=name)
... |
def available(self, timeout=5):
"""Returns True if database server is running, False otherwise."""
host = self._connect_args['host']
port = self._connect_args['port']
try:
sock = socket.create_connection((host, port), timeout=timeout)
sock.close()
retu... |
def dump(self, name, filename):
"""
Saves the state of a database to a file.
Parameters
----------
name: str
the database to be backed up.
filename: str
path to a file where database backup will be written.
"""
if not self.exists(n... |
def restore(self, name, filename):
"""
Loads state of a backup file to a database.
Note
----
If database name does not exist, it will be created.
Parameters
----------
name: str
the database to which backup will be restored.
filename:... |
def connection_dsn(self, name=None):
"""
Provides a connection string for database.
Parameters
----------
name: str, optional
an override database name for the connection string.
Returns
-------
str: the connection string (e.g. 'dbname=db1 us... |
def connection_url(self, name=None):
"""
Provides a connection string for database as a sqlalchemy compatible URL.
NB - this doesn't include special arguments related to SSL connectivity (which are outside the scope
of the connection URL format).
Parameters
----------
... |
def shell(self, expect=pexpect):
"""
Connects the database client shell to the database.
Parameters
----------
expect_module: str
the database to which backup will be restored.
"""
dsn = self.connection_dsn()
log.debug('connection string: %s' ... |
def settings(self):
"""Returns settings from the server."""
stmt = "select {fields} from pg_settings".format(fields=', '.join(SETTINGS_FIELDS))
settings = []
for row in self._iter_results(stmt):
row['setting'] = self._vartype_map[row['vartype']](row['setting'])
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.