text stringlengths 81 112k |
|---|
Add the links to the bottom of the text
def add_links(converted_text, html):
"""
Add the links to the bottom of the text
"""
soup = BeautifulSoup(html, 'html.parser')
link_exceptions = [
'footnote-reference',
'fn-backref',
'citation-reference'
]
footnotes = {}
... |
Load symbols data.
:keyword providers: Dictionary of registered data providers.
:keyword symbols: list of symbols to load.
:keyword start: start date.
:keyword end: end date.
:keyword logger: instance of :class:`logging.Logger` or ``None``.
:keyword backend: :clas... |
Internal function which perform pre-conditioning on dates:
:keyword start: start date.
:keyword end: end date.
This function makes sure the *start* and *end* date are consistent.
It *never fails* and always return a two-element tuple
containing *start*, *end* with *start* less or equal *end*
and *end* never a... |
Parse a symbol to obtain information regarding ticker,
field and provider. Must return an instance of :attr:`symboldata`.
:keyword symbol: string associated with market data to load.
:keyword providers: dictionary of :class:`dynts.data.DataProvider`
instances av... |
Return an instance of *symboldata* containing
information about the data provider, the data provider ticker name
and the data provider field.
def symbol_for_ticker(self, ticker, field, provider, providers):
'''Return an instance of *symboldata* containing
information about the data provider, the data provi... |
Preprocess **hook**. This is first loading hook and it is
**called before requesting data** from a dataprovider.
It must return an instance of :attr:`TimeSerieLoader.preprocessdata`.
By default it returns::
self.preprocessdata(intervals = ((start,end),))
It could be overritten to modify the intervals.
If ... |
Register a new data provider. *provider* must be an instance of
DataProvider. If provider name is already available, it will be replaced.
def register(self, provider):
'''Register a new data provider. *provider* must be an instance of
DataProvider. If provider name is already available, it will be r... |
Unregister an existing data provider.
*provider* must be an instance of DataProvider.
If provider name is already available, it will be replaced.
def unregister(self, provider):
'''Unregister an existing data provider.
*provider* must be an instance of DataProvider.
If ... |
Function for parsing :ref:`timeseries expressions <dsl-script>`.
If succesful, it returns an instance of :class:`dynts.dsl.Expr` which
can be used to to populate timeseries or scatters once data is available.
Parsing is implemented using the ply_ module,
an implementation of lex and yacc parsing t... |
Evaluate a timeseries ``expression`` into
an instance of :class:`dynts.dsl.dslresult` which can be used
to obtain timeseries and/or scatters.
This is probably the most used function of the library.
:parameter expression: A timeseries expression string or an instance
of :class:`dynts.dsl.E... |
Convert Grid table to data (the kind used by Dashtable)
Parameters
----------
text : str
The text must be a valid rst table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row, column] pairs that define a group of
... |
Returns an extended majority rule consensus tree as a Toytree object.
Node labels include 'support' values showing the occurrence of clades
in the consensus tree across trees in the input treelist.
Clades with support below 'cutoff' are collapsed into polytomies.
If you enter an option... |
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
Number of grid cells in x dimension. Default=automatically set.
y (int):
Number of grid cells in y dimension. Default=automatically set.
start (int):
... |
Draw a series of trees overlapping each other in coordinate space.
The order of tip_labels is fixed in cloud trees so that trees with
discordant relationships can be seen in conflict. To change the tip
order use the 'fixed_order' argument in toytree.mtree() when creating
the MultiTree o... |
hash ladderized tree topologies
def hash_trees(self):
"hash ladderized tree topologies"
observed = {}
for idx, tree in enumerate(self.treelist):
nwk = tree.write(tree_format=9)
hashed = md5(nwk.encode("utf-8")).hexdigest()
if hashed not in observed:
... |
Count clade occurrences.
def find_clades(self):
"Count clade occurrences."
# index names from the first tree
ndict = {j: i for i, j in enumerate(self.names)}
namedict = {i: j for i, j in enumerate(self.names)}
# store counts
clade_counts = {}
for tidx, ncopies i... |
Remove conflicting clades and those < cutoff to get majority rule
def filter_clades(self):
"Remove conflicting clades and those < cutoff to get majority rule"
passed = []
carrs = np.array([list(i[0]) for i in self.clade_counts], dtype=int)
freqs = np.array([i[1] for i in self.clade_coun... |
Build an unrooted consensus tree from filtered clade counts.
def build_trees(self):
"Build an unrooted consensus tree from filtered clade counts."
# storage
nodes = {}
idxarr = np.arange(len(self.fclade_counts[0][0]))
queue = []
## create dict of clade counts and set k... |
Compare the phonetic representations of 2 words, and return a boolean value.
def sounds_like(self, word1, word2):
"""Compare the phonetic representations of 2 words, and return a boolean value."""
return self.phonetics(word1) == self.phonetics(word2) |
Get the similarity of the words, using the supported distance metrics.
def distance(self, word1, word2, metric='levenshtein'):
"""Get the similarity of the words, using the supported distance metrics."""
if metric in self.distances:
distance_func = self.distances[metric]
return ... |
Get the heights of the rows of the output table.
Parameters
----------
table : list of lists of str
spans : list of lists of int
Returns
-------
heights : list of int
The heights of each row in the output table
def get_output_row_heights(table, spans):
"""
Get the heights ... |
Generalised media for odd and even number of samples
def smedian(olist,nobs):
'''Generalised media for odd and even number of samples'''
if nobs:
rem = nobs % 2
midpoint = nobs // 2
me = olist[midpoint]
if not rem:
me = 0.5 * (me + olist[midpoint-1])
... |
Apply a rolling mean function to an array.
This is a simple rolling aggregation.
def roll_mean(input, window):
'''Apply a rolling mean function to an array.
This is a simple rolling aggregation.'''
nobs, i, j, sum_x = 0,0,0,0.
N = len(input)
if window > N:
raise ValueError('Out of boun... |
Apply a rolling standard deviation function
to an array. This is a simple rolling aggregation of squared
sums.
def roll_sd(input, window, scale = 1.0, ddof = 0):
'''Apply a rolling standard deviation function
to an array. This is a simple rolling aggregation of squared
sums.'''
nobs, i, j, sx, sxx = 0,0,... |
Ensure the span is valid.
A span is a list of [row, column] pairs. These coordinates
must form a rectangular shape. For example, this span will cause an
error because it is not rectangular in shape.::
span = [[0, 1], [0, 2], [1, 0]]
Spans must be
* Rectanglular
* A list of li... |
Loop through list of cells and piece them together one by one
Parameters
----------
cells : list of dashtable.data2rst.Cell
Returns
-------
grid_table : str
The final grid table
def merge_all_cells(cells):
"""
Loop through list of cells and piece them together one by one
... |
converts bpp newick format to normal newick
def bpp2newick(bppnewick):
"converts bpp newick format to normal newick"
regex1 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[:]")
regex2 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[;]")
regex3 = re.compile(r": ")
new = regex1.sub(":", bppnewick)
new = regex2.sub("... |
used to produce balanced trees, returns a tip node from the smaller clade
def return_small_clade(treenode):
"used to produce balanced trees, returns a tip node from the smaller clade"
node = treenode
while 1:
if node.children:
c1, c2 = node.children
node = sorted([c1, c2], k... |
Used in multiple internal functions (e.g., .root()) and .drop_tips())
to select an internal mrca node, or multiple tipnames, using fuzzy matching
so that every name does not need to be written out by hand.
name: verbose list
wildcard: matching unique string
regex: regex expression
mrca: return ... |
Returns a toytree copy with all nodes scaled so that the root
height equals the value entered for treeheight.
def node_scale_root_height(self, treeheight=1):
"""
Returns a toytree copy with all nodes scaled so that the root
height equals the value entered for treeheight.
"""
... |
Returns a toytree copy with node heights modified while retaining
the same topology but not necessarily node branching order.
Node heights are moved up or down uniformly between their parent
and highest child node heights in 'levelorder' from root to tips.
The total tree height is ret... |
Returns a toytree copy with all nodes multiplied by a constant
sampled uniformly between (multiplier, 1/multiplier).
def node_multiplier(self, multiplier=0.5, seed=None):
"""
Returns a toytree copy with all nodes multiplied by a constant
sampled uniformly between (multiplier, 1/multip... |
Returns a tree with branch lengths transformed so that the tree is
ultrametric. Strategies include (1) tip-align: extend tips to the length
of the fartest tip from the root; (2) non-parametric rate-smoothing:
minimize ancestor-descendant local rates on branches to align tips (
not yet ... |
Returns a coalescent tree with ntips samples and waiting times
between coalescent events drawn from the kingman coalescent:
(4N)/(k*(k-1)), where N is population size and k is sample size.
Edge lengths on the tree are in generations.
If no Ne argument is entered then edge lengths are r... |
Returns a random tree topology w/ N tips and a root height set to
1 or a user-entered treeheight value. Descendant nodes are evenly
spaced between the root and time 0.
Parameters
-----------
ntips (int):
The number of tips in the randomly generated tree
tre... |
Return an imbalanced (comb-like) tree topology.
def imbtree(ntips, treeheight=1.0):
"""
Return an imbalanced (comb-like) tree topology.
"""
rtree = toytree.tree()
rtree.treenode.add_child(name="0")
rtree.treenode.add_child(name="1")
for i in range(2, ntips):
... |
Returns a balanced tree topology.
def baltree(ntips, treeheight=1.0):
"""
Returns a balanced tree topology.
"""
# require even number of tips
if ntips % 2:
raise ToytreeError("balanced trees must have even number of tips.")
# make first cherry
rtree ... |
Get the height of a span in the number of newlines it fills.
Parameters
----------
span : list of list of int
A list of [row, column] pairs that make up the span
row_heights : list of int
A list of the number of newlines for each row in the table
Returns
-------
total_heigh... |
Convert an html table to a data table and spans.
Parameters
----------
html_string : str
The string containing the html table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row, column] pairs that define what cells
... |
Returns newick represenation of the tree in its current state.
def newick(self, tree_format=0):
"Returns newick represenation of the tree in its current state."
# checks one of root's children for features and extra feats.
if self.treenode.children:
features = {"name", "dist", "supp... |
Returns edge values in the order they are plotted (see .get_edges())
def get_edge_values(self, feature='idx'):
"""
Returns edge values in the order they are plotted (see .get_edges())
"""
elist = []
for cidx in self._coords.edges[:, 1]:
node = self.treenode.search_no... |
Enter a dictionary mapping node 'idx' or tuple of tipnames to values
that you want mapped to the stem and descendant edges that node.
Edge values are returned in proper plot order to be entered to the
edge_colors or edge_widths arguments to draw(). To see node idx values
use node_lab... |
Returns the node idx label of the most recent common ancestor node
for the clade that includes the selected tips. Arguments can use fuzzy
name matching: a list of tip names, wildcard selector, or regex string.
def get_mrca_idx_from_tip_labels(self, names=None, wildcard=None, regex=None):
"""
... |
Returns node values from tree object in node plot order. To modify
values you must modify the .treenode object directly by setting new
'features'. For example
for node in ttree.treenode.traverse():
node.add_feature("PP", 100)
By default node and tip values are hidden (set t... |
Return node labels as a dictionary mapping {idx: name} where idx is
the order of nodes in 'preorder' traversal. Used internally by the
func .get_node_values() to return values in proper order.
return_internal: if True all nodes are returned, if False only tips.
return_nodes: if True r... |
Returns coordinates of the tip positions for a tree. If no argument
for axis then a 2-d array is returned. The first column is the x
coordinates the second column is the y-coordinates. If you enter an
argument for axis then a 1-d array will be returned of just that axis.
def get_tip_coordinat... |
Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip labels descended from that node will be
returned,... |
Returns False if there is a polytomy in the tree, including if the tree
is unrooted (basal polytomy), unless you use the include_root=False
argument.
def is_bifurcating(self, include_root=True):
"""
Returns False if there is a polytomy in the tree, including if the tree
is unroo... |
Ladderize tree (order descendants) so that top child has fewer
descendants than the bottom child in a left to right tree plot.
To reverse this pattern use direction=1.
def ladderize(self, direction=0):
"""
Ladderize tree (order descendants) so that top child has fewer
descend... |
Returns a copy of the tree where internal nodes with dist <= min_dist
are deleted, resulting in a collapsed tree. e.g.:
newtre = tre.collapse_nodes(min_dist=0.001)
newtre = tre.collapse_nodes(min_support=50)
def collapse_nodes(self, min_dist=1e-6, min_support=0):
"""
Returns a ... |
Returns a copy of the tree with the selected tips removed. The entered
value can be a name or list of names. To prune on an internal node to
create a subtree see the .prune() function instead.
Parameters:
tips: list of tip names.
# example:
ptre = tre.drop_tips(['a', 'b... |
Returns a ToyTree with the selected node rotated for plotting.
tip colors do not align correct currently if nodes are rotated...
def rotate_node(
self,
names=None,
wildcard=None,
regex=None,
idx=None,
# modify_tree=False,
):
"""
Retur... |
Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place.
def resolve_polytomy(
self,
dist=1.0,
support=100,
recursive=True):
"""
Returns a copy of the tree with all polytomies randomly resolved.
Does not transfor... |
Returns a copy of the tree unrooted. Does not transform tree in-place.
def unroot(self):
"""
Returns a copy of the tree unrooted. Does not transform tree in-place.
"""
nself = self.copy()
nself.treenode.unroot()
nself.treenode.ladderize()
nself._coords.update()
... |
(Re-)root a tree by creating selecting a existing split in the tree,
or creating a new node to split an edge in the tree. Rooting location
is selected by entering the tips descendant from one child of the root
split (e.g., names='a' or names=['a', 'b']). You can alternatively
select a li... |
Plot a Toytree tree, returns a tuple of Toyplot (Canvas, Axes) objects.
Parameters:
-----------
tree_style: str
One of several preset styles for tree plotting. The default is 'n'
(normal). Other options inlude 'c' (coalescent), 'd' (dark), and
'm' (multitree)... |
Determine the side of cell1 that can be merged with cell2.
This is based on the location of the two cells in the table as well
as the compatability of their height and width.
For example these cells can merge::
cell1 cell2 merge "RIGHT"
+-----+ +------+ +-----+------+
... |
NHX format: [&&NHX:prop1=value1:prop2=value2]
MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ...
def parse_nhx(NHX_string):
"""
NHX format: [&&NHX:prop1=value1:prop2=value2]
MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ...
"""
# store features
ndict = {}
# parse NH... |
Load *data* from a file or string and return as a list of strings.
The data contents could be one newick string; a multiline NEXUS format
for one tree; multiple newick strings on multiple lines; or multiple
newick strings in a multiline NEXUS format. In any case, we will read
in the data... |
get newick data from NEXUS
def parse_nexus(self):
"get newick data from NEXUS"
if self.data[0].strip().upper() == "#NEXUS":
nex = NexusParser(self.data)
self.data = nex.newicks
self.tdict = nex.tdict |
test format of intree nex/nwk, extra features
def get_treenodes(self):
"test format of intree nex/nwk, extra features"
if not self.multitree:
# get TreeNodes from Newick
extractor = Newick2TreeNode(self.data[0].strip(), fmt=self.fmt)
# extract one tree
... |
Reads a newick string in the New Hampshire format.
def newick_from_string(self):
"Reads a newick string in the New Hampshire format."
# split on parentheses to traverse hierarchical tree structure
for chunk in self.data.split("(")[1:]:
# add child to make this node a parent.
... |
iterate through data file to extract trees
def extract_tree_block(self):
"iterate through data file to extract trees"
lines = iter(self.data)
while 1:
try:
line = next(lines).strip()
except StopIteration:
break
# ... |
Parse CLI args.
def parse_command_line():
""" Parse CLI args."""
## create the parser
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
* Example command-line usage:
## push test branch to conda --label=conda-test for travis CI
./ver... |
Gets git and init versions and commits since the init version
def get_git_status(self):
"""
Gets git and init versions and commits since the init version
"""
## get git branch
self._get_git_branch()
## get tag in the init file
self._get_init_release_tag()
... |
if no conflicts then write new tag to
def push_git_package(self):
"""
if no conflicts then write new tag to
"""
## check for conflicts, then write to local files
self._pull_branch_from_origin()
## log commits to releasenotes
if self.deploy:
self._wr... |
Pulls from origin/master, if you have unmerged conflicts
it will raise an exception. You will need to resolve these.
def _pull_branch_from_origin(self):
"""
Pulls from origin/master, if you have unmerged conflicts
it will raise an exception. You will need to resolve these.
"""
... |
parses init.py to get previous version
def _get_init_release_tag(self):
"""
parses init.py to get previous version
"""
self.init_version = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
open(self.init_file, "r").read(),
... |
calls git log to complile a change list
def _get_log_commits(self):
"""
calls git log to complile a change list
"""
## check if update is necessary
cmd = "git log --pretty=oneline {}..".format(self.init_version)
cmdlist = shlex.split(cmd)
commits = subprocess.che... |
writes commits to the releasenotes file by appending to the end
def _write_commits_to_release_notes(self):
"""
writes commits to the releasenotes file by appending to the end
"""
with open(self.release_file, 'a') as out:
out.write("==========\n{}\n".format(self.tag))
... |
Write version to __init__.py by editing in place
def _write_new_tag_to_init(self):
"""
Write version to __init__.py by editing in place
"""
for line in fileinput.input(self.init_file, inplace=1):
if line.strip().startswith("__version__"):
line = "__version__ ... |
Write branch and tag to meta.yaml by editing in place
def _write_branch_and_tag_to_meta_yaml(self):
"""
Write branch and tag to meta.yaml by editing in place
"""
## set the branch to pull source from
with open(self.meta_yaml.replace("meta", "template"), 'r') as infile:
... |
Write version to __init__.py by editing in place
def _revert_tag_in_init(self):
"""
Write version to __init__.py by editing in place
"""
for line in fileinput.input(self.init_file, inplace=1):
if line.strip().startswith("__version__"):
line = "__version__ = \... |
tags a new release and pushes to origin/master
def _push_new_tag_to_git(self):
"""
tags a new release and pushes to origin/master
"""
print("Pushing new version to git")
## stage the releasefile and initfileb
subprocess.call(["git", "add", self.release_file]... |
Run the Linux build and use converter to build OSX
def build_conda_packages(self):
"""
Run the Linux build and use converter to build OSX
"""
## check if update is necessary
#if self.nversion == self.pversion:
# raise SystemExit("Exited: new version == existing versio... |
Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
Consider this table::
+--------+--... |
Convert ``x`` into a ``numpy.ndarray``.
def asarray(x, dtype=None):
'''Convert ``x`` into a ``numpy.ndarray``.'''
iterable = scalarasiter(x)
if isinstance(iterable, ndarray):
return iterable
else:
if not hasattr(iterable, '__len__'):
iterable = list(iterable)
... |
Convert ``x`` into a ``column``-type ``numpy.ndarray``.
def ascolumn(x, dtype = None):
'''Convert ``x`` into a ``column``-type ``numpy.ndarray``.'''
x = asarray(x, dtype)
return x if len(x.shape) >= 2 else x.reshape(len(x),1) |
Converts each multiline string in a table to single line.
Parameters
----------
table : list of list of str
A list of rows containing strings
Returns
-------
table : list of lists of str
def multis_2_mono(table):
"""
Converts each multiline string in a table to single line.
... |
Get the number of rows
def get_html_row_count(spans):
"""Get the number of rows"""
if spans == []:
return 0
row_counts = {}
for span in spans:
span = sorted(span)
try:
row_counts[str(span[0][1])] += get_span_row_count(span)
except KeyError:
row_c... |
Computes the Levenshtein distance.
[Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance
[Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions,
insertions,and reversals". Soviet Physics Doklady 10 (8): 707–710.
[Implementation]: https://en.wiki... |
Decorator which check if timeseries has a better
implementation of the function.
def better_ts_function(f):
'''Decorator which check if timeseries has a better
implementation of the function.'''
fname = f.__name__
def _(ts, *args, **kwargs):
func = getattr(ts, fname, None)
if fun... |
Rolling Z-Score statistics.
The Z-score is more formally known as ``standardised residuals``.
To calculate the standardised residuals of a data set,
the average value and the standard deviation of the data value
have to be estimated.
.. math::
z = \frac{x - \mu(x)}{\sigma(x)}
def ... |
Rolling Percentage range.
Value between 0 and 1 indicating the position in the rolling range.
def prange(ts, **kwargs):
'''Rolling Percentage range.
Value between 0 and 1 indicating the position in the rolling range.
'''
mi = ts.rollmin(**kwargs)
ma = ts.rollmax(**kwargs)
return ... |
data must be numeric list with a len above 20
This function counts the number of data points in a reduced array
def bindata(data, maxbins = 30, reduction = 0.1):
'''
data must be numeric list with a len above 20
This function counts the number of data points in a reduced array
'''
tole = 0.01
N = len(data)... |
Combines the values from two map objects using the indx values
using the op operator. In situations where there is a missing value
it will use the callable function handle_missing
def binOp(op, indx, amap, bmap, fill_vec):
'''
Combines the values from two map objects using the indx values
usin... |
takes a single value and creates a vecotor / matrix with that value filled
in it
def _toVec(shape, val):
'''
takes a single value and creates a vecotor / matrix with that value filled
in it
'''
mat = np.empty(shape)
mat.fill(val)
return mat |
Add leading & trailing space to text to center it within an allowed
width
Parameters
----------
space : int
The maximum character width allowed for the text. If the length
of text is more than this value, no space will be added.\
line : str
The text that will be centered.
... |
Register a function in the function registry.
The function will be automatically instantiated if not already an
instance.
def register(self, function):
"""Register a function in the function registry.
The function will be automatically instantiated if not already an
instanc... |
Unregister function by name.
def unregister(self, name):
"""Unregister function by name.
"""
try:
name = name.name
except AttributeError:
pass
return self.pop(name,None) |
Determine if there are spans within a row
Parameters
----------
table : list of lists of str
row : int
spans : list of lists of lists of int
Returns
-------
bool
Whether or not a table's row includes spans
def row_includes_spans(table, row, spans):
"""
Determine if the... |
Create a StateList object from a 'states' Workflow attribute.
def _setup_states(state_definitions, prev=()):
"""Create a StateList object from a 'states' Workflow attribute."""
states = list(prev)
for state_def in state_definitions:
if len(state_def) != 2:
raise TypeError(
... |
Create a TransitionList object from a 'transitions' Workflow attribute.
Args:
tdef: list of transition definitions
states (StateList): already parsed state definitions.
prev (TransitionList): transition definitions from a parent.
Returns:
TransitionList: the list of transitions... |
Decorator to declare a function as a transition implementation.
def transition(trname='', field='', check=None, before=None, after=None):
"""Decorator to declare a function as a transition implementation."""
if is_callable(trname):
raise ValueError(
"The @transition decorator should be call... |
Ensure the given function has a xworkflows_hook attribute.
That attribute has the following structure:
>>> {
... 'before': [('state', <TransitionHook>), ...],
... }
def _make_hook_dict(fun):
"""Ensure the given function has a xworkflows_hook attribute.
That attribute has the following str... |
Checks whether a given State matches self.names.
def _match_state(self, state):
"""Checks whether a given State matches self.names."""
return (self.names == '*'
or state in self.names
or state.name in self.names) |
Checks whether a given Transition matches self.names.
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names) |
Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source ... |
Run the pre-transition checks.
def _pre_transition_checks(self):
"""Run the pre-transition checks."""
current_state = getattr(self.instance, self.field_name)
if current_state not in self.transition.source:
raise InvalidTransitionError(
"Transition '%s' isn't availabl... |
Filter a list of hooks, keeping only applicable ones.
def _filter_hooks(self, *hook_kinds):
"""Filter a list of hooks, keeping only applicable ones."""
hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), [])
return sorted(hook for hook in hooks
if hook.applies_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.