repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit
python
def visit(self, node, **kwargs): containingNodes = kwargs.get('containingNodes', []) method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node, containingNodes=containingNodes)
Visit a node and extract useful information from it. This is virtually identical to the standard version contained in NodeVisitor. It is only overridden because we're tracking extra information (the hierarchy of containing nodes) not preserved in the original.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L570-L582
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker._getFullPathName
python
def _getFullPathName(self, containingNodes): assert isinstance(containingNodes, list) return [(self.options.fullPathNamespace, 'module')] + containingNodes
Returns the full node hierarchy rooted at module name. The list representing the full path through containing nodes (starting with the module itself) is returned.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L584-L592
null
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit_Module
python
def visit_Module(self, node, **kwargs): containingNodes=kwargs.get('containingNodes', []) if self.options.debug: stderr.write("# Module {0}{1}".format(self.options.fullPathNamespace, linesep)) if get_docstring(node): if se...
Handles the module-level docstring. Process the module-level docstring and create appropriate Doxygen tags if autobrief option is set.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L594-L614
[ "def _processDocstring(self, node, tail='', **kwargs):\n \"\"\"\n Handles a docstring for functions, classes, and modules.\n\n Basically just figures out the bounds of the docstring and sends it\n off to the parser to do the actual work.\n \"\"\"\n typeName = type(node).__name__\n # Modules don...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit_Assign
python
def visit_Assign(self, node, **kwargs): lineNum = node.lineno - 1 # Assignments have one Doxygen-significant special case: # interface attributes. match = AstWalker.__attributeRE.match(self.lines[lineNum]) if match: self.lines[lineNum] = '{0}## @property {1}{2}{0}# {3...
Handles assignments within code. Variable assignments in Python are used to represent interface attributes in addition to basic variables. If an assignment appears to be an attribute, it gets labeled as such for Doxygen. If a variable name uses Python mangling or is just a bed lump, i...
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L616-L656
[ "def _checkMemberName(name):\n \"\"\"\n See if a member name indicates that it should be private.\n\n Private variables in Python (starting with a double underscore but\n not ending in a double underscore) and bed lumps (variables that\n are not really private but are by common convention treated as\...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit_Call
python
def visit_Call(self, node, **kwargs): lineNum = node.lineno - 1 # Function calls have one Doxygen-significant special case: interface # implementations. match = AstWalker.__implementsRE.match(self.lines[lineNum]) if match: self.lines[lineNum] = '{0}## @implements {1}...
Handles function calls within code. Function calls in Python are used to represent interface implementations in addition to their normal use. If a call appears to mark an implementation, it gets labeled as such for Doxygen.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L658-L678
[ "def generic_visit(self, node, **kwargs):\n \"\"\"\n Extract useful information from relevant nodes including docstrings.\n\n This is virtually identical to the standard version contained in\n NodeVisitor. It is only overridden because we're tracking extra\n information (the hierarchy of containing ...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit_FunctionDef
python
def visit_FunctionDef(self, node, **kwargs): if self.options.debug: stderr.write("# Function {0.name}{1}".format(node, linesep)) # Push either 'interface' or 'class' onto our containing nodes # hierarchy so we can keep track of context. This will let us tell # if a function ...
Handles function definitions within code. Process a function's docstring, keeping well aware of the function's context and whether or not it's part of an interface definition.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L680-L708
[ "def _processDocstring(self, node, tail='', **kwargs):\n \"\"\"\n Handles a docstring for functions, classes, and modules.\n\n Basically just figures out the bounds of the docstring and sends it\n off to the parser to do the actual work.\n \"\"\"\n typeName = type(node).__name__\n # Modules don...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.visit_ClassDef
python
def visit_ClassDef(self, node, **kwargs): lineNum = node.lineno - 1 # Push either 'interface' or 'class' onto our containing nodes # hierarchy so we can keep track of context. This will let us tell # if a function is a method or an interface method definition or if # a class is ...
Handles class definitions within code. Process the docstring. Note though that in Python Class definitions are used to define interfaces in addition to classes. If a class definition appears to be an interface definition tag it as an interface definition for Doxygen. Otherwise tag it ...
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L710-L766
[ "def _processDocstring(self, node, tail='', **kwargs):\n \"\"\"\n Handles a docstring for functions, classes, and modules.\n\n Basically just figures out the bounds of the docstring and sends it\n off to the parser to do the actual work.\n \"\"\"\n typeName = type(node).__name__\n # Modules don...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
Feneric/doxypypy
doxypypy/doxypypy.py
AstWalker.parseLines
python
def parseLines(self): inAst = parse(''.join(self.lines), self.inFilename) # Visit all the nodes in our tree and apply Doxygen tags to the source. self.visit(inAst)
Form an AST for the code and produce a new version of the source.
train
https://github.com/Feneric/doxypypy/blob/a8555b15fa2a758ea8392372de31c0f635cc0d93/doxypypy/doxypypy.py#L768-L772
[ "def visit(self, node, **kwargs):\n \"\"\"\n Visit a node and extract useful information from it.\n\n This is virtually identical to the standard version contained in\n NodeVisitor. It is only overridden because we're tracking extra\n information (the hierarchy of containing nodes) not preserved in\...
class AstWalker(NodeVisitor): """ A walker that'll recursively progress through an AST. Given an abstract syntax tree for Python code, walk through all the nodes looking for significant types (for our purposes we only care about module starts, class definitions, function definitions, variable a...
pepkit/peppy
peppy/sample.py
merge_sample
python
def merge_sample(sample, sample_subann, data_sources=None, derived_attributes=None): merged_attrs = {} if sample_subann is None: _LOGGER.log(5, "No data for sample merge, skipping") return merged_attrs if SAMPLE_NAME_COLNAME not in sample_subann.columns: raise Key...
Use merge table (subannotation) data to augment/modify Sample. :param Sample sample: sample to modify via merge table data :param sample_subann: data with which to alter Sample :param Mapping data_sources: collection of named paths to data locations, optional :param Iterable[str] derived_attrib...
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/sample.py#L913-L1048
null
""" Modeling individual samples to process or otherwise use. """ from collections import OrderedDict import glob import logging from operator import itemgetter import os import sys if sys.version_info < (3, 3): from collections import Mapping else: from collections.abc import Mapping import warnings from pand...
pepkit/peppy
peppy/project.py
suggest_implied_attributes
python
def suggest_implied_attributes(prj): def suggest(key): return "To declare {}, consider using {}".format( key, IMPLICATIONS_DECLARATION) return [suggest(k) for k in prj if k in IDEALLY_IMPLIED]
If given project contains what could be implied attributes, suggest that. :param Iterable prj: Intent is a Project, but this could be any iterable of strings to check for suitability of declaration as implied attr :return list[str]: (likely empty) list of warning messages about project config k...
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/project.py#L1068-L1080
null
""" Model a project with individual samples and associated data. Project Models ======================= Workflow explained: - Create a Project object - Samples are created and added to project (automatically) In the process, Models will check: - Project structure (created if not existing) - Exist...
pepkit/peppy
peppy/utils.py
alpha_cased
python
def alpha_cased(text, lower=False): text = "".join(filter( lambda c: c.isalpha() or c == GENERIC_PROTOCOL_KEY, text)) return text.lower() if lower else text.upper()
Filter text to just letters and homogenize case. :param str text: what to filter and homogenize. :param bool lower: whether to convert to lowercase; default uppercase. :return str: input filtered to just letters, with homogenized case.
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L34-L44
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
check_bam
python
def check_bam(bam, o): try: p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE) # Count paired alignments paired = 0 read_lengths = defaultdict(int) while o > 0: # Count down number of lines line = p.stdout.readline().decode().split("\t") flag = i...
Check reads in BAM file for read type and lengths. :param str bam: BAM file path. :param int o: Number of reads to look at for estimation.
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L62-L91
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
expandpath
python
def expandpath(path): return os.path.expandvars(os.path.expanduser(path)).replace("//", "/")
Expand a filesystem path that may or may not contain user/env vars. :param str path: path to expand :return str: expanded version of input path
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L121-L128
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
get_file_size
python
def get_file_size(filename): if filename is None: return float(0) if type(filename) is list: return float(sum([get_file_size(x) for x in filename])) try: total_bytes = sum([float(os.stat(f).st_size) for f in filename.split(" ") if f is not '']) except O...
Get size of all files in gigabytes (Gb). :param str | collections.Iterable[str] filename: A space-separated string or list of space-separated strings of absolute file paths. :return float: size of file(s), in gigabytes.
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L131-L150
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
fetch_samples
python
def fetch_samples(proj, selector_attribute=None, selector_include=None, selector_exclude=None): if selector_attribute is None or (not selector_include and not selector_exclude): # Simple; keep all samples. In this case, this function simply # offers a list rather than an iterator. return li...
Collect samples of particular protocol(s). Protocols can't be both positively selected for and negatively selected against. That is, it makes no sense and is not allowed to specify both selector_include and selector_exclude protocols. On the other hand, if neither is provided, all of the Project's Samp...
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L153-L211
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
grab_project_data
python
def grab_project_data(prj): if not prj: return {} data = {} for section in SAMPLE_INDEPENDENT_PROJECT_SECTIONS: try: data[section] = getattr(prj, section) except AttributeError: _LOGGER.debug("Project lacks section '%s', skipping", section) return data
From the given Project, grab Sample-independent data. There are some aspects of a Project of which it's beneficial for a Sample to be aware, particularly for post-hoc analysis. Since Sample objects within a Project are mutually independent, though, each doesn't need to know about any of the others. A P...
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L214-L236
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
import_from_source
python
def import_from_source(module_filepath): import sys if not os.path.exists(module_filepath): raise ValueError("Path to alleged module file doesn't point to an " "extant file: '{}'".format(module_filepath)) # Randomly generate module name. fname_chars = string.ascii_lett...
Import a module from a particular filesystem location. :param str module_filepath: path to the file that constitutes the module to import :return module: module imported from the given location, named as indicated :raises ValueError: if path provided does not point to an extant file
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L250-L285
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
infer_delimiter
python
def infer_delimiter(filepath): ext = os.path.splitext(filepath)[1][1:].lower() return {"txt": "\t", "tsv": "\t", "csv": ","}.get(ext)
From extension infer delimiter used in a separated values file. :param str filepath: path to file about which to make inference :return str | NoneType: extension if inference succeeded; else null
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L288-L296
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
is_null_like
python
def is_null_like(x): return x in [None, ""] or \ (coll_like(x) and isinstance(x, Sized) and 0 == len(x))
Determine whether an object is effectively null. :param object x: Object for which null likeness is to be determined. :return bool: Whether given object is effectively "null."
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L299-L307
[ "def coll_like(c):\n \"\"\"\n Determine whether an object is collection-like.\n\n :param object c: Object to test as collection\n :return bool: Whether the argument is a (non-string) collection\n \"\"\"\n return isinstance(c, Iterable) and not isinstance(c, str)\n" ]
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
parse_ftype
python
def parse_ftype(input_file): if input_file.endswith(".bam"): return "bam" elif input_file.endswith(".fastq") or \ input_file.endswith(".fq") or \ input_file.endswith(".fq.gz") or \ input_file.endswith(".fastq.gz"): return "fastq" else: raise TypeEr...
Checks determine filetype from extension. :param str input_file: String to check. :return str: filetype (extension without dot prefix) :raises TypeError: if file does not appear of a supported type
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L331-L348
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
parse_text_data
python
def parse_text_data(lines_or_path, delimiter=os.linesep): if os.path.isfile(lines_or_path): with open(lines_or_path, 'r') as f: return f.readlines() else: _LOGGER.debug("Not a file: '{}'".format(lines_or_path)) if isinstance(lines_or_path, str): return lines_or_path.spl...
Interpret input argument as lines of data. This is intended to support multiple input argument types to core model constructors. :param str | collections.Iterable lines_or_path: :param str delimiter: line separator used when parsing a raw string that's not a file :return collections.Iterable: l...
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L351-L376
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
sample_folder
python
def sample_folder(prj, sample): return os.path.join(prj.metadata.results_subdir, sample["sample_name"])
Get the path to this Project's root folder for the given Sample. :param attmap.PathExAttMap | Project prj: project with which sample is associated :param Mapping sample: Sample or sample data for which to get root output folder path. :return str: this Project's root folder for the given Sample
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L379-L389
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
standard_stream_redirector
python
def standard_stream_redirector(stream): import sys genuine_stdout, genuine_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = stream, stream try: yield finally: sys.stdout, sys.stderr = genuine_stdout, genuine_stderr
Temporarily redirect stdout and stderr to another stream. This can be useful for capturing messages for easier inspection, or for rerouting and essentially ignoring them, with the destination as something like an opened os.devnull. :param FileIO[str] stream: temporary proxy for standard streams
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L393-L409
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
is_command_callable
python
def is_command_callable(command, name=""): # Use `command` to see if command is callable, store exit code code = os.system( "command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command)) if code != 0: alias_value = " ('{}') ".format(name) if name else " " _LOGGER.debug("Command...
Check if command can be called. :param str command: actual command to call :param str name: nickname/alias by which to reference the command, optional :return bool: whether given command's call succeeded
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L540-L557
null
""" Helpers without an obvious logical home. """ from collections import defaultdict, Iterable import contextlib import logging import os import random import string import subprocess as sp import sys if sys.version_info < (3, 0): from urlparse import urlparse else: from urllib.parse import urlparse if sys.ver...
pepkit/peppy
peppy/utils.py
CommandChecker._store_status
python
def _store_status(self, section, command, name): succeeded = is_command_callable(command, name) # Store status regardless of its value in the instance's largest DS. self.section_to_status_by_command[section][command] = succeeded if not succeeded: # Only update the failure-spe...
Based on new command execution attempt, update instance's data structures with information about the success/fail status. Return the result of the execution test.
train
https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L508-L521
[ "def is_command_callable(command, name=\"\"):\n \"\"\"\n Check if command can be called.\n\n :param str command: actual command to call\n :param str name: nickname/alias by which to reference the command, optional\n :return bool: whether given command's call succeeded\n \"\"\"\n\n # Use `comman...
class CommandChecker(object): """ Validate PATH availability of executables referenced by a config file. :param str path_conf_file: path to configuration file with sections detailing executable tools to validate :param Iterable[str] sections_to_check: names of sections of the given conf...
BrewBlox/brewblox-service
brewblox_service/scheduler.py
create_task
python
async def create_task(app: web.Application, coro: Coroutine, *args, **kwargs ) -> asyncio.Task: return await get_scheduler(app).create(coro, *args, **kwargs)
Convenience function for calling `TaskScheduler.create(coro)` This will use the default `TaskScheduler` to create a new background task. Example: import asyncio from datetime import datetime from brewblox_service import scheduler, service async def current_time(interval): ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L24-L58
[ "def get_scheduler(app: web.Application) -> 'TaskScheduler':\n return features.get(app, TaskScheduler)\n" ]
""" Background task scheduling. """ import asyncio from contextlib import suppress from typing import Any, Coroutine, Set from aiohttp import web from brewblox_service import features CLEANUP_INTERVAL_S = 300 def setup(app: web.Application): features.add(app, TaskScheduler(app)) def get_scheduler(app: web.A...
BrewBlox/brewblox-service
brewblox_service/scheduler.py
cancel_task
python
async def cancel_task(app: web.Application, task: asyncio.Task, *args, **kwargs ) -> Any: return await get_scheduler(app).cancel(task, *args, **kwargs)
Convenience function for calling `TaskScheduler.cancel(task)` This will use the default `TaskScheduler` to cancel the given task. Example: import asyncio from datetime import datetime from brewblox_service import scheduler, service async def current_time(interval): ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L61-L104
[ "def get_scheduler(app: web.Application) -> 'TaskScheduler':\n return features.get(app, TaskScheduler)\n" ]
""" Background task scheduling. """ import asyncio from contextlib import suppress from typing import Any, Coroutine, Set from aiohttp import web from brewblox_service import features CLEANUP_INTERVAL_S = 300 def setup(app: web.Application): features.add(app, TaskScheduler(app)) def get_scheduler(app: web.A...
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler._cleanup
python
async def _cleanup(self): while True: await asyncio.sleep(CLEANUP_INTERVAL_S) self._tasks = {t for t in self._tasks if not t.done()}
Periodically removes completed tasks from the collection, allowing fire-and-forget tasks to be garbage collected. This does not delete the task object, it merely removes the reference in the scheduler.
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L121-L130
null
class TaskScheduler(features.ServiceFeature): def __init__(self, app: web.Application): super().__init__(app) self._tasks: Set[asyncio.Task] = set() async def startup(self, *_): await self.create(self._cleanup()) async def shutdown(self, *_): [task.cancel() for task in sel...
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler.create
python
async def create(self, coro: Coroutine) -> asyncio.Task: task = asyncio.get_event_loop().create_task(coro) self._tasks.add(task) return task
Starts execution of a coroutine. The created asyncio.Task is returned, and added to managed tasks. The scheduler guarantees that it is cancelled during application shutdown, regardless of whether it was already cancelled manually. Args: coro (Coroutine): The...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L132-L151
null
class TaskScheduler(features.ServiceFeature): def __init__(self, app: web.Application): super().__init__(app) self._tasks: Set[asyncio.Task] = set() async def startup(self, *_): await self.create(self._cleanup()) async def shutdown(self, *_): [task.cancel() for task in sel...
BrewBlox/brewblox-service
brewblox_service/scheduler.py
TaskScheduler.cancel
python
async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any: if task is None: return task.cancel() with suppress(KeyError): self._tasks.remove(task) with suppress(Exception): return (await task) if wait_for else None
Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/scheduler.py#L153-L180
null
class TaskScheduler(features.ServiceFeature): def __init__(self, app: web.Application): super().__init__(app) self._tasks: Set[asyncio.Task] = set() async def startup(self, *_): await self.create(self._cleanup()) async def shutdown(self, *_): [task.cancel() for task in sel...
BrewBlox/brewblox-service
brewblox_service/service.py
create_parser
python
def create_parser(default_name: str) -> argparse.ArgumentParser: argparser = argparse.ArgumentParser(fromfile_prefix_chars='@') argparser.add_argument('-H', '--host', help='Host to which the app binds. [%(default)s]', default='0.0.0.0') argparser.add_arg...
Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argpa...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L68-L106
null
""" Generic startup functions for a brewblox application. Responsible for parsing user configuration, and creating top-level objects. This module provides the framework to which service implementations can attach their features. Example: # Uses the default argument parser # To add new commandline arguments, u...
BrewBlox/brewblox-service
brewblox_service/service.py
create_app
python
def create_app( default_name: str = None, parser: argparse.ArgumentParser = None, raw_args: List[str] = None ) -> web.Application: if parser is None: assert default_name, 'Default service name is required' parser = create_parser(default_name) args = parser.parse_args(ra...
Creates and configures an Aiohttp application. Args: default_name (str, optional): Default value for the --name commandline argument. This value is required if `parser` is not provided. This value will be ignored if `parser` is provided. parser (argparse.Argumen...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L109-L147
[ "def _init_logging(args: argparse.Namespace):\n level = logging.DEBUG if args.debug else logging.INFO\n format = '%(asctime)s %(levelname)-8s %(name)-30s %(message)s'\n datefmt = '%Y/%m/%d %H:%M:%S'\n\n logging.basicConfig(level=level, format=format, datefmt=datefmt)\n\n if args.output:\n han...
""" Generic startup functions for a brewblox application. Responsible for parsing user configuration, and creating top-level objects. This module provides the framework to which service implementations can attach their features. Example: # Uses the default argument parser # To add new commandline arguments, u...
BrewBlox/brewblox-service
brewblox_service/service.py
furnish
python
def furnish(app: web.Application): app_name = app['config']['name'] prefix = '/' + app_name.lstrip('/') app.router.add_routes(routes) cors_middleware.enable_cors(app) # Configure CORS and prefixes on all endpoints. known_resources = set() for route in list(app.router.routes()): if r...
Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L150-L189
[ "def enable_cors(app: web.Application):\n app.middlewares.append(cors_middleware)\n" ]
""" Generic startup functions for a brewblox application. Responsible for parsing user configuration, and creating top-level objects. This module provides the framework to which service implementations can attach their features. Example: # Uses the default argument parser # To add new commandline arguments, u...
BrewBlox/brewblox-service
brewblox_service/service.py
run
python
def run(app: web.Application): host = app['config']['host'] port = app['config']['port'] # starts app. run_app() will automatically start the async context. web.run_app(app, host=host, port=port)
Runs the application in an async context. This function will block indefinitely until the application is shut down. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/service.py#L192-L205
null
""" Generic startup functions for a brewblox application. Responsible for parsing user configuration, and creating top-level objects. This module provides the framework to which service implementations can attach their features. Example: # Uses the default argument parser # To add new commandline arguments, u...
BrewBlox/brewblox-service
brewblox_service/features.py
add
python
def add(app: web.Application, feature: Any, key: Hashable = None, exist_ok: bool = False ): if FEATURES_KEY not in app: app[FEATURES_KEY] = dict() key = key or type(feature) if key in app[FEATURES_KEY]: if exist_ok: return else: ...
Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): The current Aiohttp application. feature (Any): The new feature that should be registered. ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/features.py#L14-L53
null
""" Registers and gets features added to Aiohttp by brewblox services. """ from abc import ABC, abstractmethod from enum import Enum, auto from typing import Any, Hashable, Type from aiohttp import web FEATURES_KEY = '#features' def get(app: web.Application, feature_type: Type[Any] = None, key: Ha...
BrewBlox/brewblox-service
brewblox_service/features.py
get
python
def get(app: web.Application, feature_type: Type[Any] = None, key: Hashable = None ) -> Any: key = key or feature_type if not key: raise AssertionError('No feature identifier provided') try: found = app[FEATURES_KEY][key] except KeyError: raise KeyError(...
Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type (Type[Any]): The Python type of the desired feature. If specified, it will be checked against the found f...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/features.py#L56-L92
null
""" Registers and gets features added to Aiohttp by brewblox services. """ from abc import ABC, abstractmethod from enum import Enum, auto from typing import Any, Hashable, Type from aiohttp import web FEATURES_KEY = '#features' def add(app: web.Application, feature: Any, key: Hashable = None, ...
BrewBlox/brewblox-service
brewblox_service/events.py
post_publish
python
async def post_publish(request): args = await request.json() try: await get_publisher(request.app).publish( args['exchange'], args['routing'], args['message'] ) return web.Response() except Exception as ex: warnings.warn(f'Unable to publis...
--- tags: - Events summary: Publish event. description: Publish a new event message to the event bus. operationId: events.publish produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L462-L499
[ "def get_publisher(app: web.Application) -> 'EventPublisher':\n return features.get(app, EventPublisher)\n" ]
""" Offers event publishing and subscription for service implementations. Example use: from brewblox_service import scheduler, events scheduler.setup(app) events.setup(app) async def on_message(subscription, key, message): print(f'Message from {subscription}: {key} = {message} ({type(message...
BrewBlox/brewblox-service
brewblox_service/events.py
post_subscribe
python
async def post_subscribe(request): args = await request.json() get_listener(request.app).subscribe( args['exchange'], args['routing'] ) return web.Response()
--- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L503-L531
[ "def get_listener(app: web.Application) -> 'EventListener':\n return features.get(app, EventListener)\n" ]
""" Offers event publishing and subscription for service implementations. Example use: from brewblox_service import scheduler, events scheduler.setup(app) events.setup(app) async def on_message(subscription, key, message): print(f'Message from {subscription}: {key} = {message} ({type(message...
BrewBlox/brewblox-service
brewblox_service/events.py
EventSubscription._relay
python
async def _relay(self, channel: aioamqp.channel.Channel, body: str, envelope: aioamqp.envelope.Envelope, properties: aioamqp.properties.Properties): try: await channel.basic_client_ack(envelope.delivery_tag) ...
Relays incoming messages between the queue and the user callback
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L122-L132
null
class EventSubscription(): """ Subscription class for receiving AMQP messages. This class should not be instantiated directly. To subscribe to AMQP messages, use `EventListener.subscribe()` The `on_message` property can safely be changed while the subscription is active. It will be used for th...
BrewBlox/brewblox-service
brewblox_service/events.py
EventListener._lazy_listen
python
def _lazy_listen(self): if all([ self._loop, not self.running, self._subscriptions or (self._pending and not self._pending.empty()), ]): self._task = self._loop.create_task(self._listen())
Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or act...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L169-L184
null
class EventListener(features.ServiceFeature): """ Allows subscribing to AMQP messages published to a central event bus. `EventListener` will maintain a persistent connection to the AMQP host, and ensures that all subscriptions remain valid if the connection is lost and reestablished. """ def _...
BrewBlox/brewblox-service
brewblox_service/events.py
EventListener.subscribe
python
def subscribe(self, exchange_name: str, routing: str, exchange_type: ExchangeType_ = 'topic', on_message: EVENT_CALLBACK_ = None ) -> EventSubscription: sub = EventSubscription( exchange_name, routi...
Adds a new event subscription to the listener. Actual queue declaration to the remote message server is done when connected. If the listener is not currently connected, it defers declaration. All existing subscriptions are redeclared on the remote if `EventListener` loses and recreates...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L275-L324
[ "def _lazy_listen(self):\n \"\"\"\n Ensures that the listener task only runs when actually needed.\n This function is a no-op if any of the preconditions is not met.\n\n Preconditions are:\n * The application is running (self._loop is set)\n * The task is not already running\n * There are subsc...
class EventListener(features.ServiceFeature): """ Allows subscribing to AMQP messages published to a central event bus. `EventListener` will maintain a persistent connection to the AMQP host, and ensures that all subscriptions remain valid if the connection is lost and reestablished. """ def _...
BrewBlox/brewblox-service
brewblox_service/events.py
EventPublisher.publish
python
async def publish(self, exchange: str, routing: str, message: Union[str, dict], exchange_type: ExchangeType_ = 'topic'): try: await self._ensure_channel() except Exception: # If server has res...
Publish a new event message. Connections are created automatically when calling `publish()`, and will attempt to reconnect if connection was lost. For more information on publishing AMQP messages, see https://www.rabbitmq.com/tutorials/tutorial-three-python.html Args: ...
train
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L396-L454
[ "async def _ensure_channel(self):\n if not self.connected:\n self._transport, self._protocol = await aioamqp.connect(\n host=self._host,\n port=self._port,\n loop=self.app.loop\n )\n self._channel = await self._protocol.channel()\n\n try:\n await se...
class EventPublisher(features.ServiceFeature): """ Allows publishing AMQP messages to a central eventbus. `EventPublisher` is associated with a single eventbus address, but will only create a connection when attempting to publish. Connections are re-used for subsequent `publish()` calls. """ ...
aloetesting/aloe_django
aloe_django/management/commands/harvest.py
Command.run_from_argv
python
def run_from_argv(self, argv): self.test_runner = test_runner_class super(Command, self).run_from_argv(argv)
Set the default Gherkin test runner for its options to be parsed.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/management/commands/harvest.py#L25-L31
null
class Command(TestCommand): """Django command: harvest""" help = "Run Gherkin tests" requires_system_checks = False def handle(self, *test_labels, **options): """ Set the default Gherkin test runner. """ if not options.get('testrunner', None): options['tes...
aloetesting/aloe_django
aloe_django/management/commands/harvest.py
Command.handle
python
def handle(self, *test_labels, **options): if not options.get('testrunner', None): options['testrunner'] = test_runner_class return super(Command, self).handle(*test_labels, **options)
Set the default Gherkin test runner.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/management/commands/harvest.py#L33-L40
null
class Command(TestCommand): """Django command: harvest""" help = "Run Gherkin tests" requires_system_checks = False def run_from_argv(self, argv): """ Set the default Gherkin test runner for its options to be parsed. """ self.test_runner = test_runner_class su...
aloetesting/aloe_django
aloe_django/__init__.py
django_url
python
def django_url(step, url=None): base_url = step.test.live_server_url if url: return urljoin(base_url, url) else: return base_url
The URL for a page from the test server. :param step: A Gherkin step :param url: If specified, the relative URL to append.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/__init__.py#L38-L51
null
# -*- coding: utf-8 -*- """ Django integration for Aloe """ try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin # pylint:disable=import-error from django.core.exceptions import ImproperlyConfigured try: from django.contrib.staticfiles.testing import ( StaticL...
aloetesting/aloe_django
aloe_django/steps/models.py
_models_generator
python
def _models_generator(): for app in apps.get_app_configs(): for model in app.get_models(): yield (str(model._meta.verbose_name).lower(), model) yield (str(model._meta.verbose_name_plural).lower(), model)
Build a hash of model verbose names to models
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L29-L37
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
get_model
python
def get_model(name): model = MODELS.get(name.lower(), None) assert model, "Could not locate model by name '%s'" % name return model
Convert a model's verbose name to the model class. This allows us to use the models verbose name in steps.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L166-L176
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
reset_sequence
python
def reset_sequence(model): sql = connection.ops.sequence_reset_sql(no_style(), [model]) for cmd in sql: connection.cursor().execute(cmd)
Reset the ID sequence for a model.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L179-L185
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_dump_model
python
def _dump_model(model, attrs=None): fields = [] for field in model._meta.fields: fields.append((field.name, str(getattr(model, field.name)))) if attrs is not None: for attr in attrs: fields.append((attr, str(getattr(model, attr)))) for field in model._meta.many_to_many: ...
Dump the model fields for debugging.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L188-L212
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_model_exists_step
python
def _model_exists_step(self, model, should_exist): model = get_model(model) data = guess_types(self.hashes) queryset = model.objects try: existence_check = _TEST_MODEL[model] except KeyError: existence_check = test_existence failed = 0 try: for hash_ in data: ...
Test for the existence of a model matching the given data.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L247-L289
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
write_models
python
def write_models(model, data, field): written = [] for hash_ in data: if field: if field not in hash_: raise KeyError(("The \"%s\" field is required for all update " "operations") % field) model_kwargs = {field: hash_[field]} ...
:param model: a Django model class :param data: a list of hashes to build models from :param field: a field name to match models on, or None :returns: a list of models written Create or update models for each data hash. `field` is the field that is used to get the existing models out of the da...
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L338-L375
[ "def reset_sequence(model):\n \"\"\"\n Reset the ID sequence for a model.\n \"\"\"\n sql = connection.ops.sequence_reset_sql(no_style(), [model])\n for cmd in sql:\n connection.cursor().execute(cmd)\n" ]
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_write_models_step
python
def _write_models_step(self, model, field=None): model = get_model(model) data = guess_types(self.hashes) try: func = _WRITE_MODEL[model] except KeyError: func = partial(write_models, model) func(data, field)
Write or update a model.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L378-L391
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_create_models_for_relation_step
python
def _create_models_for_relation_step(self, rel_model_name, rel_key, rel_value, model): model = get_model(model) lookup = {rel_key: rel_value} rel_model = get_model(rel_model_name).objects.get(**lookup) data = guess_types(self.hashes) for hash_ in data: ...
Create a new model linked to the given model. Syntax: And `model` with `field` "`value`" has `new model` in the database: Example: .. code-block:: gherkin And project with name "Ball Project" has goals in the database: | description | ...
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L441-L473
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_create_m2m_links_step
python
def _create_m2m_links_step(self, rel_model_name, rel_key, rel_value, relation_name): lookup = {rel_key: rel_value} rel_model = get_model(rel_model_name).objects.get(**lookup) relation = None for m2m in rel_model._meta.many_to_many: if relation_name in (m2m.name, m2m.v...
Link many-to-many models together. Syntax: And `model` with `field` "`value`" is linked to `other model` in the database: Example: .. code-block:: gherkin And article with name "Guidelines" is linked to tags in the database: | name | | coding | ...
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L478-L518
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/models.py
_model_count_step
python
def _model_count_step(self, count, model): model = get_model(model) expected = int(count) found = model.objects.count() assert found == expected, "Expected %d %s, found %d." % \ (expected, model._meta.verbose_name_plural, found)
Count the number of models in the database. Example: .. code-block:: gherkin Then there should be 0 goals in the database
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L522-L538
null
""" Step definitions and utilities for working with Django models. """ from __future__ import print_function from __future__ import unicode_literals # pylint:disable=redefined-builtin from builtins import str # pylint:disable=redefined-builtin import warnings from functools import partial from django.apps import app...
aloetesting/aloe_django
aloe_django/steps/mail.py
mail_sent_count
python
def mail_sent_count(self, count): expected = int(count) actual = len(mail.outbox) assert expected == actual, \ "Expected to send {0} email(s), got {1}.".format(expected, actual)
Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L25-L42
null
""" Step definitions for working with Django email. """ from __future__ import print_function from smtplib import SMTPException from django.core import mail from django.test.html import parse_html from nose.tools import assert_in # pylint:disable=no-name-in-module from aloe import step __all__ = () STEP_PREFIX ...
aloetesting/aloe_django
aloe_django/steps/mail.py
mail_sent_content
python
def mail_sent_content(self, text, part): if not any(text in getattr(email, part) for email in mail.outbox): dump_emails(part) raise AssertionError( "No email contained expected text in the {0}.".format(part))
Test an email contains (assert text in) the given text in the relevant message part (accessible as an attribute on the email object). This step strictly applies whitespace. Syntax: I have sent an email with "`text`" in the `part` Example: .. code-block:: gherkin Then I have sen...
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L61-L81
[ "def dump_emails(part):\n \"\"\"Show the sent emails' tested parts, to aid in debugging.\"\"\"\n\n print(\"Sent emails:\")\n for email in mail.outbox:\n print(getattr(email, part))\n" ]
""" Step definitions for working with Django email. """ from __future__ import print_function from smtplib import SMTPException from django.core import mail from django.test.html import parse_html from nose.tools import assert_in # pylint:disable=no-name-in-module from aloe import step __all__ = () STEP_PREFIX ...
aloetesting/aloe_django
aloe_django/steps/mail.py
mail_sent_contains_html
python
def mail_sent_contains_html(self): for email in mail.outbox: try: html = next(content for content, mime in email.alternatives if mime == 'text/html') dom1 = parse_html(html) dom2 = parse_html(self.multiline) assert_in(dom1, dom2) ...
Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent an email with the following HTML alternative: ...
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L131-L167
null
""" Step definitions for working with Django email. """ from __future__ import print_function from smtplib import SMTPException from django.core import mail from django.test.html import parse_html from nose.tools import assert_in # pylint:disable=no-name-in-module from aloe import step __all__ = () STEP_PREFIX ...
aloetesting/aloe_django
aloe_django/steps/mail.py
dump_emails
python
def dump_emails(part): print("Sent emails:") for email in mail.outbox: print(getattr(email, part))
Show the sent emails' tested parts, to aid in debugging.
train
https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L208-L213
null
""" Step definitions for working with Django email. """ from __future__ import print_function from smtplib import SMTPException from django.core import mail from django.test.html import parse_html from nose.tools import assert_in # pylint:disable=no-name-in-module from aloe import step __all__ = () STEP_PREFIX ...
sci-bots/serial-device
serial_device/__init__.py
_comports
python
def _comports(): ''' Returns ------- pandas.DataFrame Table containing descriptor, and hardware ID of each available COM port, indexed by port (e.g., "COM4"). ''' return (pd.DataFrame(list(map(list, serial.tools.list_ports.comports())), columns=['port', '...
Returns ------- pandas.DataFrame Table containing descriptor, and hardware ID of each available COM port, indexed by port (e.g., "COM4").
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/__init__.py#L34-L44
null
''' Copyright 2014 Christian Fobel Copyright 2011 Ryan Fobel This file is part of serial_device. serial_device is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)...
sci-bots/serial-device
serial_device/__init__.py
comports
python
def comports(vid_pid=None, include_all=False, check_available=True, only_available=False): ''' .. versionchanged:: 0.9 Add :data:`check_available` keyword argument to optionally check if each port is actually available by attempting to open a temporary connection. A...
.. versionchanged:: 0.9 Add :data:`check_available` keyword argument to optionally check if each port is actually available by attempting to open a temporary connection. Add :data:`only_available` keyword argument to only include ports that are actually available for connection....
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/__init__.py#L47-L143
[ "def _comports():\n '''\n Returns\n -------\n pandas.DataFrame\n Table containing descriptor, and hardware ID of each available COM\n port, indexed by port (e.g., \"COM4\").\n '''\n return (pd.DataFrame(list(map(list, serial.tools.list_ports.comports())),\n co...
''' Copyright 2014 Christian Fobel Copyright 2011 Ryan Fobel This file is part of serial_device. serial_device is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)...
sci-bots/serial-device
serial_device/__init__.py
_get_serial_ports_windows
python
def _get_serial_ports_windows(): ''' Uses the Win32 registry to return a iterator of serial (COM) ports existing on this computer. See http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows ''' import six.moves.winreg as winreg reg_path = 'HARDWARE\\DEVICEMAP\\SERIA...
Uses the Win32 registry to return a iterator of serial (COM) ports existing on this computer. See http://stackoverflow.com/questions/1205383/listing-serial-com-ports-on-windows
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/__init__.py#L160-L181
null
''' Copyright 2014 Christian Fobel Copyright 2011 Ryan Fobel This file is part of serial_device. serial_device is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)...
sci-bots/serial-device
serial_device/__init__.py
SerialDevice.get_port
python
def get_port(self, baud_rate): ''' Using the specified baud-rate, attempt to connect to each available serial port. If the `test_connection()` method returns `True` for a port, update the `port` attribute and return the port. In the case where the `test_connection()` does not r...
Using the specified baud-rate, attempt to connect to each available serial port. If the `test_connection()` method returns `True` for a port, update the `port` attribute and return the port. In the case where the `test_connection()` does not return `True` for any of the evaluated ports...
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/__init__.py#L206-L226
[ "def get_serial_ports():\n if os.name == 'nt':\n ports = _get_serial_ports_windows()\n else:\n ports = itertools.chain(ph.path('/dev').walk('ttyUSB*'),\n ph.path('/dev').walk('ttyACM*'),\n ph.path('/dev').walk('tty.usb*'))\n # sort...
class SerialDevice(object): ''' This class provides a base interface for encapsulating interaction with a device connected through a serial-port. It provides methods to automatically resolve a port based on an implementation-defined connection-test, which is applied to all available serial-port...
sci-bots/serial-device
serial_device/or_event.py
orify
python
def orify(event, changed_callback): ''' Override ``set`` and ``clear`` methods on event to call specified callback function after performing default behaviour. Parameters ---------- ''' event.changed = changed_callback if not hasattr(event, '_set'): # `set`/`clear` methods have...
Override ``set`` and ``clear`` methods on event to call specified callback function after performing default behaviour. Parameters ----------
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/or_event.py#L19-L36
null
''' Wait on multiple :class:`threading.Event` instances. Based on code from: https://stackoverflow.com/questions/12317940/python-threading-can-i-sleep-on-two-threading-events-simultaneously/12320352#12320352 ''' import threading def or_set(self): self._set() self.changed() def or_clear(self): self._cle...
sci-bots/serial-device
serial_device/or_event.py
OrEvent
python
def OrEvent(*events): ''' Parameters ---------- events : list(threading.Event) List of events. Returns ------- threading.Event Event that is set when **at least one** of the events in :data:`events` is set. ''' or_event = threading.Event() def changed():...
Parameters ---------- events : list(threading.Event) List of events. Returns ------- threading.Event Event that is set when **at least one** of the events in :data:`events` is set.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/or_event.py#L39-L70
[ "def orify(event, changed_callback):\n '''\n Override ``set`` and ``clear`` methods on event to call specified callback\n function after performing default behaviour.\n\n Parameters\n ----------\n\n '''\n event.changed = changed_callback\n if not hasattr(event, '_set'):\n # `set`/`cle...
''' Wait on multiple :class:`threading.Event` instances. Based on code from: https://stackoverflow.com/questions/12317940/python-threading-can-i-sleep-on-two-threading-events-simultaneously/12320352#12320352 ''' import threading def or_set(self): self._set() self.changed() def or_clear(self): self._cle...
sci-bots/serial-device
serial_device/threaded.py
request
python
def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send payload to serial device and wait for response. Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or...
Send payload to serial device and wait for response. Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait...
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/threaded.py#L237-L272
[ "def write(self, data, timeout_s=None):\n '''\n Write to serial port.\n\n Waits for serial connection to be established before writing.\n\n Parameters\n ----------\n data : str or bytes\n Data to write to serial port.\n timeout_s : float, optional\n Maximum number of seconds to wa...
import queue import logging import platform import threading import datetime as dt import serial import serial.threaded import serial_device from .or_event import OrEvent logger = logging.getLogger(__name__) # Flag to indicate whether queues should be polled. # XXX Note that polling performance may vary by platfor...
sci-bots/serial-device
serial_device/threaded.py
EventProtocol.connection_made
python
def connection_made(self, transport): self.port = transport.serial.port logger.debug('connection_made: `%s` `%s`', self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear()
Called when reader thread is started
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/threaded.py#L28-L34
null
class EventProtocol(serial.threaded.Protocol): def __init__(self): self.transport = None self.connected = threading.Event() self.disconnected = threading.Event() self.port = None def data_received(self, data): """Called with snippets received from the serial port""" ...
sci-bots/serial-device
serial_device/threaded.py
EventProtocol.connection_lost
python
def connection_lost(self, exception): if isinstance(exception, Exception): logger.debug('Connection to port `%s` lost: %s', self.port, exception) else: logger.debug('Connection to port `%s` closed', self.port) self.connected.clear() self.d...
\ Called when the serial port is closed or the reader loop terminated otherwise.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/threaded.py#L40-L51
null
class EventProtocol(serial.threaded.Protocol): def __init__(self): self.transport = None self.connected = threading.Event() self.disconnected = threading.Event() self.port = None def connection_made(self, transport): """Called when reader thread is started""" sel...
sci-bots/serial-device
serial_device/threaded.py
KeepAliveReader.write
python
def write(self, data, timeout_s=None): ''' Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum num...
Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be ...
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/threaded.py#L167-L184
null
class KeepAliveReader(threading.Thread): ''' Keep a serial connection alive (as much as possible). Parameters ---------- state : dict State dictionary to share ``protocol`` object reference. comport : str Name of com port to connect to. default_timeout_s : float, optional ...
sci-bots/serial-device
serial_device/threaded.py
KeepAliveReader.request
python
def request(self, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str ...
Send Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in sec...
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/threaded.py#L186-L213
[ "def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES):\n '''\n Send payload to serial device and wait for response.\n\n Parameters\n ----------\n device : serial.Serial\n Serial instance.\n response_queue : Queue.Queue\n Queue to wait for response on.\n p...
class KeepAliveReader(threading.Thread): ''' Keep a serial connection alive (as much as possible). Parameters ---------- state : dict State dictionary to share ``protocol`` object reference. comport : str Name of com port to connect to. default_timeout_s : float, optional ...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager.on_connect
python
def on_connect(self, client, userdata, flags, rc): ''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object ...
Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` ...
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L57-L106
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager.on_message
python
def on_message(self, client, userdata, msg): ''' Callback for when a ``PUBLISH`` message is received from the broker. ''' if msg.topic == 'serial_device/refresh_comports': self.refresh_comports() return match = CRE_MANAGER.match(msg.topic) if matc...
Callback for when a ``PUBLISH`` message is received from the broker.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L108-L138
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._publish_status
python
def _publish_status(self, port): ''' Publish status for specified port. Parameters ---------- port : str Device name/port. ''' if port not in self.open_devices: status = {} else: device = self.open_devices[port].serial ...
Publish status for specified port. Parameters ---------- port : str Device name/port.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L142-L160
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._serial_close
python
def _serial_close(self, port): ''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: ...
Handle close request. Parameters ---------- port : str Device name/port.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L162-L180
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._serial_connect
python
def _serial_connect(self, port, request): ''' Handle connection request. Parameters ---------- port : str Device name/port. request : dict ''' # baudrate : int # Baud rate such as 9600 or 115200 etc. # bytesize ...
Handle connection request. Parameters ---------- port : str Device name/port. request : dict
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L182-L324
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
sci-bots/serial-device
serial_device/mqtt.py
SerialDeviceManager._serial_send
python
def _serial_send(self, port, payload): ''' Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device. ''' if port not in self.open_devices: # Not connect...
Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device.
train
https://github.com/sci-bots/serial-device/blob/5de1c3fc447ae829b57d80073ec6ac4fba3283c6/serial_device/mqtt.py#L326-L347
null
class SerialDeviceManager(pmh.BaseMqttReactor): def __init__(self, *args, **kwargs): super(SerialDeviceManager, self).__init__(*args, **kwargs) # Open devices. self.open_devices = {} def refresh_comports(self): # Query list of available serial ports comports = _comports(...
matthewgilbert/mapping
mapping/plot.py
plot_composition
python
def plot_composition(df, intervals, axes=None): generics = df.columns if (axes is not None) and (len(axes) != len(generics)): raise ValueError("If 'axes' is not None then it must be the same " "length as 'df.columns'") if axes is None: _, axes = plt.subplots(nrows=...
Plot time series of generics and label underlying instruments which these series are composed of. Parameters: ----------- df: pd.DataFrame DataFrame of time series to be plotted. Each column is a generic time series. intervals: pd.DataFrame A DataFrame including information ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/plot.py#L5-L76
null
import matplotlib.pyplot as plt import pandas as pd def intervals(weights): """ Extract intervals where generics are composed of different tradeable instruments. Parameters ---------- weights: DataFrame or dict A DataFrame or dictionary of DataFrames with columns representing ...
matthewgilbert/mapping
mapping/plot.py
intervals
python
def intervals(weights): intrvls = [] if isinstance(weights, dict): for root in weights: wts = weights[root] intrvls.append(_intervals(wts)) intrvls = pd.concat(intrvls, axis=0) else: intrvls = _intervals(weights) intrvls = intrvls.reset_index(drop=True) ...
Extract intervals where generics are composed of different tradeable instruments. Parameters ---------- weights: DataFrame or dict A DataFrame or dictionary of DataFrames with columns representing generics and a MultiIndex of date and contract. Values represent weights on tradea...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/plot.py#L79-L106
[ "def _intervals(weights):\n # since weights denote weightings for returns, not holdings. To determine\n # the previous day we look at the index since lagging would depend on the\n # calendar. As a kludge we omit the first date since impossible to\n # know\n dates = weights.index.get_level_values(0)\n...
import matplotlib.pyplot as plt import pandas as pd def plot_composition(df, intervals, axes=None): """ Plot time series of generics and label underlying instruments which these series are composed of. Parameters: ----------- df: pd.DataFrame DataFrame of time series to be plotted. Ea...
matthewgilbert/mapping
mapping/util.py
read_price_data
python
def read_price_data(files, name_func=None): if name_func is None: def name_func(x): return os.path.split(x)[1].split(".")[0] dfs = [] for f in files: name = name_func(f) df = pd.read_csv(f, index_col=0, parse_dates=True) df.sort_index(inplace=True) df.ind...
Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dates name_func: func A function to apply to the file strings to infer the instrument name, ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L6-L40
[ "def name_func(fstr):\n file_name = os.path.split(fstr)[-1]\n name = file_name.split('-')[1].split('.')[0]\n return name[-4:] + name[:3]\n", "def name_func(x):\n return os.path.split(x)[1].split(\".\")[0]\n" ]
import pandas as pd import numpy as np import os def flatten(weights): """ Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the se...
matthewgilbert/mapping
mapping/util.py
flatten
python
def flatten(weights): """ Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the second level is instrument names. The columns ...
Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the second level is instrument names. The columns consist of generic names. If dict ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L43-L89
null
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
unflatten
python
def unflatten(flat_weights): """ Pivot weights from long DataFrame into weighting matrix. Parameters ---------- flat_weights: pandas.DataFrame A long DataFrame of weights, where columns are "date", "contract", "generic", "weight" and optionally "key". If "key" column is pres...
Pivot weights from long DataFrame into weighting matrix. Parameters ---------- flat_weights: pandas.DataFrame A long DataFrame of weights, where columns are "date", "contract", "generic", "weight" and optionally "key". If "key" column is present a dictionary of unflattened DataFrame...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L92-L143
null
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
calc_rets
python
def calc_rets(returns, weights): """ Calculate continuous return series for futures instruments. These consist of weighted underlying instrument returns, who's weights can vary over time. Parameters ---------- returns: pandas.Series or dict A Series of instrument returns with a Mult...
Calculate continuous return series for futures instruments. These consist of weighted underlying instrument returns, who's weights can vary over time. Parameters ---------- returns: pandas.Series or dict A Series of instrument returns with a MultiIndex where the top level is pandas....
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L146-L225
[ "def _check_indices(returns, weights):\n # dictionaries of returns and weights\n\n # check 1: ensure that all non zero instrument weights have associated\n # returns, see https://github.com/matthewgilbert/mapping/issues/3\n\n # check 2: ensure that returns are not dropped if reindexed from weights,\n ...
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
reindex
python
def reindex(prices, index, limit): if not index.is_unique: raise ValueError("'index' must be unique") index = index.sort_values() index.names = ["date", "instrument"] price_dts = prices.sort_index().index.unique(level=0) index_dts = index.unique(level=0) mask = price_dts < index_dts[0]...
Reindex a pd.Series of prices such that when instrument level returns are calculated they are compatible with a pd.MultiIndex of instrument weights in calc_rets(). This amount to reindexing the series by an augmented version of index which includes the preceding date for the first appearance of each ins...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L282-L362
null
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
calc_trades
python
def calc_trades(current_contracts, desired_holdings, trade_weights, prices, multipliers, **kwargs): if not isinstance(trade_weights, dict): trade_weights = {"": trade_weights} generics = [] for key in trade_weights: generics.extend(trade_weights[key].columns) if not set...
Calculate the number of tradeable contracts for rebalancing from a set of current contract holdings to a set of desired generic notional holdings based on prevailing prices and mapping from generics to tradeable instruments. Differences between current holdings and desired holdings are treated as 0. Zer...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L365-L458
[ "def to_contracts(instruments, prices, multipliers, desired_ccy=None,\n instr_fx=None, fx_rates=None, rounder=None):\n \"\"\"\n Convert notional amount of tradeable instruments to number of instrument\n contracts, rounding to nearest integer number of contracts.\n\n Parameters\n -----...
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
to_notional
python
def to_notional(instruments, prices, multipliers, desired_ccy=None, instr_fx=None, fx_rates=None): notionals = _instr_conv(instruments, prices, multipliers, True, desired_ccy, instr_fx, fx_rates) return notionals
Convert number of contracts of tradeable instruments to notional value of tradeable instruments in a desired currency. Parameters ---------- instruments: pandas.Series Series of instrument holdings. Index is instrument name and values are number of contracts. prices: pandas.Series ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L461-L508
[ "def _instr_conv(instruments, prices, multipliers, to_notional, desired_ccy,\n instr_fx, fx_rates):\n\n if not instruments.index.is_unique:\n raise ValueError(\"'instruments' must have unique index\")\n if not prices.index.is_unique:\n raise ValueError(\"'prices' must have unique ...
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
to_contracts
python
def to_contracts(instruments, prices, multipliers, desired_ccy=None, instr_fx=None, fx_rates=None, rounder=None): contracts = _instr_conv(instruments, prices, multipliers, False, desired_ccy, instr_fx, fx_rates) if rounder is None: rounder = pd.Series.round ...
Convert notional amount of tradeable instruments to number of instrument contracts, rounding to nearest integer number of contracts. Parameters ---------- instruments: pandas.Series Series of instrument holdings. Index is instrument name and values are notional amount on instrument. ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L511-L557
[ "def _instr_conv(instruments, prices, multipliers, to_notional, desired_ccy,\n instr_fx, fx_rates):\n\n if not instruments.index.is_unique:\n raise ValueError(\"'instruments' must have unique index\")\n if not prices.index.is_unique:\n raise ValueError(\"'prices' must have unique ...
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
get_multiplier
python
def get_multiplier(weights, root_generic_multiplier): if len(root_generic_multiplier) > 1 and not isinstance(weights, dict): raise ValueError("For multiple generic instruments weights must be a " "dictionary") mults = [] intrs = [] for ast, multiplier in root_generic_mu...
Determine tradeable instrument multiplier based on generic asset multipliers and weights mapping from generics to tradeables. Parameters ---------- weights: pandas.DataFrame or dict A pandas.DataFrame of loadings of generic contracts on tradeable instruments **for a given date**. The co...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L593-L643
null
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/util.py
weighted_expiration
python
def weighted_expiration(weights, contract_dates): """ Calculate the days to expiration for generic futures, weighted by the composition of the underlying tradeable instruments. Parameters: ----------- weights: pandas.DataFrame A DataFrame of instrument weights with a MultiIndex where th...
Calculate the days to expiration for generic futures, weighted by the composition of the underlying tradeable instruments. Parameters: ----------- weights: pandas.DataFrame A DataFrame of instrument weights with a MultiIndex where the top level contains pandas.Timestamps and the second ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/util.py#L646-L694
null
import pandas as pd import numpy as np import os def read_price_data(files, name_func=None): """ Convenience function for reading in pricing data from csv files Parameters ---------- files: list List of strings refering to csv files to read data in from, first column should be dat...
matthewgilbert/mapping
mapping/mappings.py
bdom_roll_date
python
def bdom_roll_date(sd, ed, bdom, months, holidays=[]): if not isinstance(bdom, int): raise ValueError("'bdom' must be integer") sd = pd.Timestamp(sd) ed = pd.Timestamp(ed) t1 = sd if not t1.is_month_start: t1 = t1 - pd.offsets.MonthBegin(1) t2 = ed if not t2.is_month_end: ...
Convenience function for getting business day data associated with contracts. Usefully for generating business day derived 'contract_dates' which can be used as input to roller(). Returns dates for a business day of the month for months in months.keys() between the start date and end date. Parameters ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L18-L78
null
import pandas as pd import numpy as np import cvxpy import sys # deal with API change from cvxpy version 0.4 to 1.0 if hasattr(cvxpy, "sum_entries"): CVX_SUM = getattr(cvxpy, "sum_entries") else: CVX_SUM = getattr(cvxpy, "sum") TO_MONTH_CODE = dict(zip(range(1, 13), "FGHJKMNQUVXZ")) FROM_MONTH_CODE = dict(z...
matthewgilbert/mapping
mapping/mappings.py
roller
python
def roller(timestamps, contract_dates, get_weights, **kwargs): timestamps = sorted(timestamps) contract_dates = contract_dates.sort_values() _check_contract_dates(contract_dates) weights = [] # for loop speedup only validate inputs the first function call to # get_weights() validate_inputs =...
Calculate weight allocations to tradeable instruments for generic futures at a set of timestamps for a given root generic. Paramters --------- timestamps: iterable Sorted iterable of of pandas.Timestamps to calculate weights for contract_dates: pandas.Series Series with index of tra...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L81-L141
[ "def _check_contract_dates(contract_dates):\n if not contract_dates.index.is_unique:\n raise ValueError(\"'contract_dates.index' must be unique\")\n if not contract_dates.is_unique:\n raise ValueError(\"'contract_dates' must be unique\")\n # since from above we know this is unique if not mono...
import pandas as pd import numpy as np import cvxpy import sys # deal with API change from cvxpy version 0.4 to 1.0 if hasattr(cvxpy, "sum_entries"): CVX_SUM = getattr(cvxpy, "sum_entries") else: CVX_SUM = getattr(cvxpy, "sum") TO_MONTH_CODE = dict(zip(range(1, 13), "FGHJKMNQUVXZ")) FROM_MONTH_CODE = dict(z...
matthewgilbert/mapping
mapping/mappings.py
aggregate_weights
python
def aggregate_weights(weights, drop_date=False): dwts = pd.DataFrame(weights, columns=["generic", "contract", "weight", "date"]) dwts = dwts.pivot_table(index=['date', 'contract'], columns=['generic'], values='weight', fill_value=0) dwts = dwts.astype(floa...
Transforms list of tuples of weights into pandas.DataFrame of weights. Parameters: ----------- weights: list A list of tuples consisting of the generic instrument name, the tradeable contract as a string, the weight on this contract as a float and the date as a pandas.Timestamp. ...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L144-L171
null
import pandas as pd import numpy as np import cvxpy import sys # deal with API change from cvxpy version 0.4 to 1.0 if hasattr(cvxpy, "sum_entries"): CVX_SUM = getattr(cvxpy, "sum_entries") else: CVX_SUM = getattr(cvxpy, "sum") TO_MONTH_CODE = dict(zip(range(1, 13), "FGHJKMNQUVXZ")) FROM_MONTH_CODE = dict(z...
matthewgilbert/mapping
mapping/mappings.py
static_transition
python
def static_transition(timestamp, contract_dates, transition, holidays=None, validate_inputs=True): if validate_inputs: # required for MultiIndex slicing _check_static(transition.sort_index(axis=1)) # the algorithm below will return invalid results if contract_dates is ...
An implementation of *get_weights* parameter in roller(). Return weights to tradeable instruments for a given date based on a transition DataFrame which indicates how to roll through the roll period. Parameters ---------- timestamp: pandas.Timestamp The timestamp to return instrument weight...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L174-L282
[ "def _check_contract_dates(contract_dates):\n if not contract_dates.index.is_unique:\n raise ValueError(\"'contract_dates.index' must be unique\")\n if not contract_dates.is_unique:\n raise ValueError(\"'contract_dates' must be unique\")\n # since from above we know this is unique if not mono...
import pandas as pd import numpy as np import cvxpy import sys # deal with API change from cvxpy version 0.4 to 1.0 if hasattr(cvxpy, "sum_entries"): CVX_SUM = getattr(cvxpy, "sum_entries") else: CVX_SUM = getattr(cvxpy, "sum") TO_MONTH_CODE = dict(zip(range(1, 13), "FGHJKMNQUVXZ")) FROM_MONTH_CODE = dict(z...
matthewgilbert/mapping
mapping/mappings.py
to_generics
python
def to_generics(instruments, weights): if not isinstance(weights, dict): weights = {"": weights} allocations = [] unmapped_instr = instruments.index for key in weights: w = weights[key] # may not always have instrument holdings for a set of weights so allow # weights to ...
Map tradeable instruments to generics given weights and tradeable instrument holdings. This is solving the equation Ax = b where A is the weights, and b is the instrument holdings. When Ax = b has no solution we solve for x' such that Ax' is closest to b in the least squares sense with the additional co...
train
https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L315-L407
null
import pandas as pd import numpy as np import cvxpy import sys # deal with API change from cvxpy version 0.4 to 1.0 if hasattr(cvxpy, "sum_entries"): CVX_SUM = getattr(cvxpy, "sum_entries") else: CVX_SUM = getattr(cvxpy, "sum") TO_MONTH_CODE = dict(zip(range(1, 13), "FGHJKMNQUVXZ")) FROM_MONTH_CODE = dict(z...
inveniosoftware/invenio-records-files
invenio_records_files/alembic/1ba76da94103_create_records_files_tables.py
upgrade
python
def upgrade(): op.create_table( 'records_buckets', sa.Column( 'record_id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), sa.Column( 'bucket_id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), ...
Upgrade database.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/alembic/1ba76da94103_create_records_files_tables.py#L25-L40
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create records files tables.""" import sqlalchemy as sa import sqlalchemy_utils f...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
_writable
python
def _writable(method): @wraps(method) def wrapper(self, *args, **kwargs): """Send record for indexing. :returns: Execution result of the decorated method. :raises InvalidOperationError: It occurs when the bucket is locked or deleted. """ if self.bucket.locke...
Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L80-L98
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """API for manipulating files associated to a record.""" from collections import Ord...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FileObject.get_version
python
def get_version(self, version_id=None): return ObjectVersion.get(bucket=self.obj.bucket, key=self.obj.key, version_id=version_id)
Return specific version ``ObjectVersion`` instance or HEAD. :param version_id: Version ID of the object. :returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or HEAD of the stored object.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L32-L40
null
class FileObject(object): """Wrapper for files.""" def __init__(self, obj, data): """Bind to current bucket.""" self.obj = obj self.data = data def get(self, key, default=None): """Proxy to ``obj``. :param key: Metadata key which holds the value. :returns:...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FileObject.get
python
def get(self, key, default=None): if hasattr(self.obj, key): return getattr(self.obj, key) return self.data.get(key, default)
Proxy to ``obj``. :param key: Metadata key which holds the value. :returns: Metadata value of the specified key or default.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L42-L50
null
class FileObject(object): """Wrapper for files.""" def __init__(self, obj, data): """Bind to current bucket.""" self.obj = obj self.data = data def get_version(self, version_id=None): """Return specific version ``ObjectVersion`` instance or HEAD. :param version_id:...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FileObject.dumps
python
def dumps(self): self.data.update({ 'bucket': str(self.obj.bucket_id), 'checksum': self.obj.file.checksum, 'key': self.obj.key, # IMPORTANT it must stay here! 'size': self.obj.file.size, 'version_id': str(self.obj.version_id), }) retur...
Create a dump of the metadata associated to the record.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L68-L77
null
class FileObject(object): """Wrapper for files.""" def __init__(self, obj, data): """Bind to current bucket.""" self.obj = obj self.data = data def get_version(self, version_id=None): """Return specific version ``ObjectVersion`` instance or HEAD. :param version_id:...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.flush
python
def flush(self): files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files attached. if files or '_files' in self.record: self.record['_files'] = files
Flush changes to record.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L150-L156
[ "def dumps(self, bucket=None):\n \"\"\"Serialize files from a bucket.\n\n :param bucket: Instance of files\n :class:`invenio_files_rest.models.Bucket`. (Default:\n ``self.bucket``)\n :returns: List of serialized files.\n \"\"\"\n return [\n self.file_cls(o, self.filesmap.get(o.ke...
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket ...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.sort_by
python
def sort_by(self, *ids): # Support sorting by file_ids or keys. files = {str(f_.file_id): f_.key for f_ in self} # self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids] self.filesmap = OrderedDict([ (files.get(id_, id_), self[files.get(id_, id_)].dumps()) ...
Update files order. :param ids: List of ids specifying the final status of the list.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L180-L192
[ "def flush(self):\n \"\"\"Flush changes to record.\"\"\"\n files = self.dumps()\n # Do not create `_files` when there has not been `_files` field before\n # and the record still has no files attached.\n if files or '_files' in self.record:\n self.record['_files'] = files\n" ]
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket ...