text
stringlengths
81
112k
Performs post-transition actions. def _post_transition(self, result, *args, **kwargs): """Performs post-transition actions.""" for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER): hook(self.instance, result, *args, **kwargs)
Import previously defined implementations. Args: parent_implems (ImplementationList): List of implementations defined in a parent class. def load_parent_implems(self, parent_implems): """Import previously defined implementations. Args: parent_implems (I...
Add an implementation. Args: transition (Transition): the transition for which the implementation is added attribute (str): the name of the attribute where the implementation will be available function (callable): the actual implementation fun...
Decide whether a given value should be collected. def should_collect(self, value): """Decide whether a given value should be collected.""" return ( # decorated with @transition isinstance(value, TransitionWrapper) # Relates to a compatible transition and ...
Collect the implementations from a given attributes dict. def collect(self, attrs): """Collect the implementations from a given attributes dict.""" for name, value in attrs.items(): if self.should_collect(value): transition = self.workflow.transitions[value.trname] ...
Retrieve a list of cutom implementations. Yields: (str, str, ImplementationProperty) tuples: The name of the attribute an implementation lives at, the name of the related transition, and the related implementation. def get_custom_implementations(self): """Re...
Looks at an object method and registers it for relevent transitions. def register_function_hooks(self, func): """Looks at an object method and registers it for relevent transitions.""" for hook_kind, hooks in func.xworkflows_hook.items(): for field_name, hook in hooks: if fi...
Checks whether an ImplementationProperty may override an attribute. def _may_override(self, implem, other): """Checks whether an ImplementationProperty may override an attribute.""" if isinstance(other, ImplementationProperty): # Overriding another custom implementation for the same transit...
Update the 'attrs' dict with generated ImplementationProperty. def fill_attrs(self, attrs): """Update the 'attrs' dict with generated ImplementationProperty.""" for trname, attrname in self.transitions_at.items(): implem = self.implementations[trname] if attrname in attrs: ...
Perform all actions on a given attribute dict. def transform(self, attrs): """Perform all actions on a given attribute dict.""" self.collect(attrs) self.add_missing_implementations() self.fill_attrs(attrs)
Log a transition. Args: transition (Transition): the name of the performed transition from_state (State): the source state instance (object): the modified object Kwargs: Any passed when calling the transition def log_transition(self, transition, from_st...
Attach a workflow to the attribute list (create a StateProperty). def _add_workflow(mcs, field_name, state_field, attrs): """Attach a workflow to the attribute list (create a StateProperty).""" attrs[field_name] = StateProperty(state_field.workflow, field_name)
Finds all occurrences of a workflow in the attributes definitions. Returns: dict(str => StateField): maps an attribute name to a StateField describing the related Workflow. def _find_workflows(mcs, attrs): """Finds all occurrences of a workflow in the attributes definitions...
Collect and enhance transition definitions to a workflow. Modifies the 'attrs' dict in-place. Args: field_name (str): name of the field transitions should update workflow (Workflow): workflow we're working on attrs (dict): dictionary of attributes to be updated. ...
Updates cartesian coordinates for drawing tree graph def update(self): "Updates cartesian coordinates for drawing tree graph" # get new shape and clear for attrs self.edges = np.zeros((self.ttree.nnodes - 1, 2), dtype=int) self.verts = np.zeros((self.ttree.nnodes, 2), dtyp...
set root idx highest, tip idxs lowest ordered as ladderized def update_idxs(self): "set root idx highest, tip idxs lowest ordered as ladderized" # internal nodes: root is highest idx idx = self.ttree.nnodes - 1 for node in self.ttree.treenode.traverse("levelorder"): if not n...
after pruning fixed order needs update to match new nnodes/ntips. def update_fixed_order(self): "after pruning fixed order needs update to match new nnodes/ntips." # set tips order if fixing for multi-tree plotting (default None) fixed_order = self.ttree._fixed_order self.ttree_fixed_or...
Sets .edges, .verts for node positions. X and Y positions here refer to base assumption that tree is right facing, reorient_coordinates() will handle re-translating this. def assign_vertices(self): """ Sets .edges, .verts for node positions. X and Y positions here refer to bas...
Returns a modified .verts array with new coordinates for nodes. This does not need to modify .edges. The order of nodes, and therefore of verts rows is still the same because it is still based on the tree branching order (ladderized usually). def reorient_coordinates(self): """ ...
An iterator of timeseries as tuples. def tsiterator(ts, dateconverter=None, desc=None, clean=False, start_value=None, **kwargs): '''An iterator of timeseries as tuples.''' dateconverter = dateconverter or default_converter yield ['Date'] + ts.names() if clean == 'full': for dt, v...
Modify coords to shift tree position for x,y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots, but still sharing a common cartesian axes coordinates. def set_baselines(self): """ Modify coords to shift tree position for x,y baseline arguments. This...
Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. def add_tip_labels_to_axes(self): """ Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree p...
add lines to connect tips to zero axis for tip_labels_align=True def add_tip_lines_to_axes(self): "add lines to connect tips to zero axis for tip_labels_align=True" # get tip-coords and align-coords from verts xpos, ypos, aedges, averts = self.get_tip_label_coords() if self.style.tip_...
Modifies display range to ensure tip labels fit. This is a bit hackish still. The problem is that the 'extents' range of the rendered text is totally correct. So we add a little buffer here. Should add for user to be able to modify this if needed. If not using edge lengths then need to ...
Resolve conflict of 'node_color' and 'node_style['fill'] args which are redundant. Default is node_style.fill unless user entered node_color. To enter multiple colors user must use node_color not style fill. Either way, we build a list of colors to pass to Drawing.node_colors which is ...
assign features of nodes to be plotted based on user kwargs def assign_node_labels_and_sizes(self): "assign features of nodes to be plotted based on user kwargs" # shorthand nvals = self.ttree.get_node_values() # False == Hide nodes and labels unless user entered size if self...
assign tip labels based on user provided kwargs def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" # COLOR # tip color overrides tipstyle.fill if self.style.tip_labels_colors: #if self.style.tip_labels_style.fill: # self....
Resolve conflict of 'node_color' and 'node_style['fill'] args which are redundant. Default is node_style.fill unless user entered node_color. To enter multiple colors user must use node_color not style fill. Either way, we build a list of colors to pass to Drawing.node_colors which is ...
Creates a new marker for every node from idx indexes and lists of node_values, node_colors, node_sizes, node_style, node_labels_style. Pulls from node_color and adds to a copy of the style dict for each node to create marker. Node_colors has priority to overwrite node_style['fill'] d...
Get starting position of tip labels text based on locations of the leaf nodes on the tree and style offset and align options. Node positions are found using the .verts attribute of coords and is already oriented for the tree face direction. def get_tip_label_coords(self): """ ...
Calculate reasonable canvas height and width for tree given N tips def get_dims_from_tree_size(self): "Calculate reasonable canvas height and width for tree given N tips" ntips = len(self.ttree) if self.style.orient in ("right", "left"): # height is long tip-wise dimension ...
Get the length longest line in a paragraph def get_longest_line_length(text): """Get the length longest line in a paragraph""" lines = text.split("\n") length = 0 for i in range(len(lines)): if len(lines[i]) > length: length = len(lines[i]) return length
Return true if obj is a numeric value def isnumeric(obj): ''' Return true if obj is a numeric value ''' from decimal import Decimal if type(obj) == Decimal: return True else: try: float(obj) except: return False return True
Format a number according to a given number of significant figures. def significant_format(number, decimal_sep='.', thousand_sep=',', n=3): """Format a number according to a given number of significant figures. """ str_number = significant(number, n) # sign if float(number) < 0: sig...
Convert `obj` to (unicode) text string def to_text_string(obj, encoding=None): """Convert `obj` to (unicode) text string""" if PY2: # Python 2 if encoding is None: return unicode(obj) else: return unicode(obj, encoding) else: # Python 3 if enc...
Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() if not is_string(text): # testing for QStr...
Create a QFont from tuple: (family [string], size [int], italic [bool], bold [bool]) def tuple_to_qfont(tup): """ Create a QFont from tuple: (family [string], size [int], italic [bool], bold [bool]) """ if not isinstance(tup, tuple) or len(tup) != 4 \ or not is_text_string(tup[0]...
Create form dialog and return result (if Cancel button is pressed, return None) :param tuple data: datalist, datagroup (see below) :param str title: form title :param str comment: header comment :param QIcon icon: dialog box icon :param QWidget parent: parent widget :param str ok: customize...
Return FormDialog instance def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog
Return form result def get(self): """Return form result""" # It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute if self.outfile: if self.result in ['list', 'dict', 'OrderedDict']: ...
Merge timeseries into a new :class:`~.TimeSeries` instance. :parameter series: an iterable over :class:`~.TimeSeries`. def ts_merge(series): '''Merge timeseries into a new :class:`~.TimeSeries` instance. :parameter series: an iterable over :class:`~.TimeSeries`. ''' series = iter(series) ...
Entry point for any arithmetic type function performed on a timeseries and/or a scalar. op_name - name of the function to be performed ts1, ts2 - timeseries or scalars that the function is to performed over all - whether all dates should be included in the result fill - the value that should be...
Return the algorithm for *operation* named *name* def getalgo(self, operation, name): '''Return the algorithm for *operation* named *name*''' if operation not in self._algorithms: raise NotAvailable('{0} not registered.'.format(operation)) oper = self._algorithms[operation] ...
Returns an iterable over ``datetime.date`` instances in the timeseries. def dates(self, desc=None): '''Returns an iterable over ``datetime.date`` instances in the timeseries.''' c = self.dateinverse for key in self.keys(desc=desc): yield c(key)
Returns a python ``generator`` which can be used to iterate over :func:`dynts.TimeSeries.dates` and :func:`dynts.TimeSeries.values` returning a two dimensional tuple ``(date,value)`` in each iteration. Similar to the python dictionary items function. :parameter de...
Generator of single series data (no dates are included). def series(self): '''Generator of single series data (no dates are included).''' data = self.values() if len(data): for c in range(self.count()): yield data[:, c] else: raise StopIter...
Generator of tuples with name and serie data. def named_series(self, ordering=None): '''Generator of tuples with name and serie data.''' series = self.series() if ordering: series = list(series) todo = dict(((n, idx) for idx, n in enumerate(self.names()))) ...
Create a clone of timeseries def clone(self, date=None, data=None, name=None): '''Create a clone of timeseries''' name = name or self.name data = data if data is not None else self.values() ts = self.__class__(name) ts._dtype = self._dtype if date is None: ...
Trim :class:`Timeseries` to a new *size* using the algorithm *method*. If *size* is greater or equal than len(self) it does nothing. def reduce(self, size, method='simple', **kwargs): '''Trim :class:`Timeseries` to a new *size* using the algorithm *method*. If *size* is greater or equal than len(self) it do...
Create a new :class:`TimeSeries` with missing data removed or replaced by the *algorithm* provided def clean(self, algorithm=None): '''Create a new :class:`TimeSeries` with missing data removed or replaced by the *algorithm* provided''' # all dates original_dates = list(self.dates()) ...
Check if the timeseries is consistent def isconsistent(self): '''Check if the timeseries is consistent''' for dt1, dt0 in laggeddates(self): if dt1 <= dt0: return False return True
Calculate variance of timeseries. Return a vector containing the variances of each series in the timeseries. :parameter ddof: delta degree of freedom, the divisor used in the calculation is given by ``N - ddof`` where ``N`` represents the length of timeseries. Default ``0``. ....
Calculate standard deviation of timeseries def sd(self): '''Calculate standard deviation of timeseries''' v = self.var() if len(v): return np.sqrt(v) else: return None
Apply function ``func`` to the timeseries. :keyword func: string indicating function to apply :keyword window: Rolling window, If not defined ``func`` is applied on the whole dataset. Default ``None``. :keyword bycolumn: If ``True``, function ``func`` is applied on ...
A generic :ref:`rolling function <rolling-function>` for function *func*. Same construct as :meth:`dynts.TimeSeries.apply` but with default ``window`` set to ``20``. def rollapply(self, func, window=20, **kwargs): '''A generic :ref:`rolling function <rolling-function>` for ...
A :ref:`rolling function <rolling-function>` for stadard-deviation values: Same as:: self.rollapply('sd', **kwargs) def rollsd(self, scale=1, **kwargs): '''A :ref:`rolling function <rolling-function>` for stadard-deviation values: Same as:: sel...
Unwind expression by applying *values* to the abstract nodes. The ``kwargs`` dictionary can contain data which can be used to override values def unwind(self, values, backend, **kwargs): '''Unwind expression by applying *values* to the abstract nodes. The ``kwargs`` dictionary c...
Loop over children a remove duplicate entries. @return - a list of removed entries def removeduplicates(self, entries = None): ''' Loop over children a remove duplicate entries. @return - a list of removed entries ''' removed = [] if entries == None: ...
Convert a string or html file to a markdown table string. Parameters ---------- html_string : str Either the html string, or the filepath to the html Returns ------- str The html table converted to a Markdown table Notes ----- This function requires BeautifulSoup_ ...
Converts the table to a list of spans, for consistency. This method combines the table data with the span data into a single, more consistent type. Any normal cell will become a span of just 1 column and 1 row. Parameters ---------- table : list of lists of str spans : list of lists of int...
numpy asarray does not copy data def keys(self, desc = None): '''numpy asarray does not copy data''' res = asarray(self.rc('index')) if desc == True: return reversed(res) else: return res
numpy asarray does not copy data def values(self, desc = None): '''numpy asarray does not copy data''' if self._ts: res = asarray(self._ts) if desc == True: return reversed(res) else: return res else: retur...
General function for applying a rolling R function to a timeserie def rcts(self, command, *args, **kwargs): '''General function for applying a rolling R function to a timeserie''' cls = self.__class__ name = kwargs.pop('name','') date = kwargs.pop('date',None) data = kwargs...
Gets the number of columns in an html table. Paramters --------- html_string : str Returns ------- int The number of columns in the table def get_html_column_count(html_string): """ Gets the number of columns in an html table. Paramters --------- html_string : str...
Add space to start and end of each string in a list of lists Parameters ---------- table : list of lists of str A table of rows of strings. For example:: [ ['dog', 'cat', 'bicycle'], ['mouse', trumpet', ''] ] Returns ------- tabl...
Efficient rolling window calculation for min, max type functions def rollsingle(self, func, window=20, name=None, fallback=False, align='right', **kwargs): '''Efficient rolling window calculation for min, max type functions ''' rname = 'roll_{0}'.format(func) if fallback: rfunc =...
Building block of all searches. Find the index corresponding to the leftmost value greater or equal to *dt*. If *dt* is greater than the :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.RightOutOfBound` exception will raise. *dt* must be a python datetime.date instance. def find_ge(self, dt): ''...
Find the index corresponding to the rightmost value less than or equal to *dt*. If *dt* is less than :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.LeftOutOfBound` exception will raise. *dt* must be a python datetime.date instance. def find_le(self, dt): '''Find the index corresponding to the ...
Update database. def upgrade(): """Update database.""" op.create_table( 'transaction', sa.Column('issued_at', sa.DateTime(), nullable=True), sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('remote_addr', sa.String(length=50), nullable=True), ) op.create_prima...
Downgrade database. def downgrade(): """Downgrade database.""" op.drop_table('transaction') if op._proxy.migration_context.dialect.supports_sequences: op.execute(DropSequence(Sequence('transaction_id_seq')))
r'([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)? def t_NUMBER(self, t): r'([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?' try: sv = t.value v = float(sv) iv = int(v) t.value = (iv if iv == v else v, sv) except ValueError: print...
r'`[^`]*`|[a-zA-Z_][a-zA-Z_0-9:@]* def t_ID(self, t): r'`[^`]*`|[a-zA-Z_][a-zA-Z_0-9:@]*' res = self.oper.get(t.value, None) # Check for reserved words if res is None: res = t.value.upper() if res == 'FALSE': t.type = 'BOOL' t.valu...
Reads a newick tree from either a string or a file, and returns an ETE tree structure. A previously existent node object can be passed as the root of the tree, which means that all its new children will belong to the same class as the root (This allows to work with custom TreeNode objects). You ca...
Reads a newick string in the New Hampshire format. def _read_newick_from_string(nw, root_node, matcher, formatcode): """ Reads a newick string in the New Hampshire format. """ if nw.count('(') != nw.count(')'): raise NewickError('Parentheses do not match. Broken tree structure?') # white spaces an...
Reads node's extra data form its NHX string. NHX uses this format: [&&NHX:prop1=value1:prop2=value2] def _parse_extra_features(node, NHX_string): """ Reads node's extra data form its NHX string. NHX uses this format: [&&NHX:prop1=value1:prop2=value2] """ NHX_string = NHX_string.replace("[&&...
Tests newick string against format types? and makes a re.compile def compile_matchers(formatcode): """ Tests newick string against format types? and makes a re.compile """ matchers = {} for node_type in ["leaf", "single", "internal"]: if node_type == "leaf" or node_type == "single": ...
Reads a leaf node from a subpart of the original newicktree def _read_node_data(subnw, current_node, node_type, matcher, formatcode): """ Reads a leaf node from a subpart of the original newicktree """ if node_type == "leaf" or node_type == "single": if node_type == "leaf": node =...
Iteratively export a tree structure and returns its NHX representation. def write_newick(rootnode, features=None, format=1, format_root_node=True, is_leaf_fn=None, dist_formatter=None, support_formatter=None, name_formatter=None): """ Iteratively export a tree structure and returns ...
Generates the extended newick string NHX with extra data about a node. def _get_features_string(self, features=None): """ Generates the extended newick string NHX with extra data about a node.""" string = "" if features is None: features = [] elif features == []: features = self.feature...
Get the character width of a column in a table Parameters ---------- column : int The column index analyze table : list of lists of str The table of rows of strings. For this to be accurate, each string must only be 1 line long. Returns ------- width : int def ...
makes a simple Text Mark object def get_text_mark(ttree): """ makes a simple Text Mark object""" if ttree._orient in ["right"]: angle = 0. ypos = ttree.verts[-1*len(ttree.tree):, 1] if ttree._kwargs["tip_labels_align"]: xpos = [ttree.verts[:, 0].max()] * len(ttree.tree)...
makes a simple Graph Mark object def get_edge_mark(ttree): """ makes a simple Graph Mark object""" ## tree style if ttree._kwargs["tree_style"] in ["c", "cladogram"]: a=ttree.edges vcoordinates=ttree.verts else: a=ttree._lines vcoordinates=ttree._coor...
get shared styles def split_styles(mark): """ get shared styles """ markers = [mark._table[key] for key in mark._marker][0] nstyles = [] for m in markers: ## fill and stroke are already rgb() since already in markers msty = toyplot.style.combine({ "fill": m.mstyle['fill...
Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters ---------- cell : dashtable.data2rst.Cell Returns ------- cell : dashtable.data2rst.Cell def center_cell_t...
Computes the Hamming distance. [Reference]: https://en.wikipedia.org/wiki/Hamming_distance [Article]: Hamming, Richard W. (1950), "Error detecting and error correcting codes", Bell System Technical Journal 29 (2): 147–160 def hamming_distance(word1, word2): """ Computes the Hamming distance. ...
Polynomial generating function def polygen(*coefficients): '''Polynomial generating function''' if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] def _(i): v = c0 for c in coefficients: ...
Create a new :class:`dynts.TimeSeries` instance using a ``backend`` and populating it with provided the data. :parameter name: optional timeseries name. For multivarate timeseries the :func:`dynts.tsname` utility function can be used to build it. :parameter b...
Force each cell in the table to be a string Parameters ---------- table : list of lists Returns ------- table : list of lists of str def ensure_table_strings(table): """ Force each cell in the table to be a string Parameters ---------- table : list of lists Returns ...
The number of sections that touch the left side. During merging, the cell's text will grow to include other cells. This property keeps track of the number of sections that are touching the left side. For example:: +-----+-----+ section --> | foo | dog | <-- ...
The number of sections that touch the right side. Returns ------- sections : int The number of sections on the right def right_sections(self): """ The number of sections that touch the right side. Returns ------- sections : int T...
The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top def top_sections(self): """ The number of sections that touch the top side. Returns ------- sections : int The numbe...
The number of cells that touch the bottom side. Returns ------- sections : int The number of sections on the top def bottom_sections(self): """ The number of cells that touch the bottom side. Returns ------- sections : int The nu...
Whether or not the cell is a header Any header cell will have "=" instead of "-" on its border. For example, this is a header cell:: +-----+ | foo | +=====+ while this cell is not:: +-----+ | foo | +-----+ Retu...
Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. def get_git_changeset(file...
Checks if the html table contains headers and returns True/False Parameters ---------- html_string : str Returns ------- bool def headers_present(html_string): """ Checks if the html table contains headers and returns True/False Parameters ---------- html_string : str ...
Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- html_string : str Returns ------- list of lists of lists of int def extract_spans(html_string): """ Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- ...
Create an index of mapped letters (zip to dict). def translation(first, second): """Create an index of mapped letters (zip to dict).""" if len(first) != len(second): raise WrongLengthException('The lists are not of the same length!') return dict(zip(first, second))
Recursively go through a tag's children, converting them, then convert the tag itself. def process_tag(node): """ Recursively go through a tag's children, converting them, then convert the tag itself. """ text = '' exceptions = ['table'] for element in node.children: if isins...
Lagged iterator over dates def laggeddates(ts, step=1): '''Lagged iterator over dates''' if step == 1: dates = ts.dates() if not hasattr(dates, 'next'): dates = dates.__iter__() dt0 = next(dates) for dt1 in dates: yield dt1, dt0 dt0 =...
Create a new skiplist def make_skiplist(*args, use_fallback=False): '''Create a new skiplist''' sl = fallback.Skiplist if use_fallback else Skiplist return sl(*args)