text stringlengths 81 112k |
|---|
Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
this is the repository to use as the context for the rendering
:param boo... |
Find repositories via various criteria.
.. warning::
You will only be able to make 5 calls with this or other search
functions. To raise the rate-limit on this set of endpoints, create an
authenticated :class:`GitHub <github3.github.GitHub>` Session with
``login``.
The query c... |
Describe limits in effect on your AWS account. See also https://console.aws.amazon.com/ec2/v2/home#Limits:
def limits(args):
"""
Describe limits in effect on your AWS account. See also https://console.aws.amazon.com/ec2/v2/home#Limits:
"""
# https://aws.amazon.com/about-aws/whats-new/2014/06/19/amazon-... |
Add labels to this issue.
:param str args: (required), names of the labels you wish to add
:returns: list of :class:`Label`\ s
def add_labels(self, *args):
"""Add labels to this issue.
:param str args: (required), names of the labels you wish to add
:returns: list of :class:`L... |
Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:param str login: username of the person to assign this issue to
:returns: bool
def assign(self, login):
"""Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:para... |
Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int id_num: (required), comment id, see example above
:returns... |
Create a comment on this issue.
:param str body: (required), comment body
:returns: :class:`IssueComment <github3.issues.comment.IssueComment>`
def create_comment(self, body):
"""Create a comment on this issue.
:param str body: (required), comment body
:returns: :class:`IssueC... |
Edit this issue.
:param str title: Title of the issue
:param str body: markdown formatted body (description) of the issue
:param str assignee: login name of user the issue should be assigned
to
:param str state: accepted values: ('open', 'closed')
:param int mileston... |
Iterate over the comments on this issue.
:param int number: (optional), number of comments to iterate over
:returns: iterator of
:class:`IssueComment <github3.issues.comment.IssueComment>`\ s
def iter_comments(self, number=-1):
"""Iterate over the comments on this issue.
:... |
Iterate over events associated with this issue only.
:param int number: (optional), number of events to return. Default: -1
returns all events available.
:returns: generator of
:class:`IssueEvent <github3.issues.event.IssueEvent>`\ s
def iter_events(self, number=-1):
""... |
Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
def remove_label(self, name):
"""Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
"""
... |
Replace all labels on this issue with ``labels``.
:param list labels: label names
:returns: bool
def replace_labels(self, labels):
"""Replace all labels on this issue with ``labels``.
:param list labels: label names
:returns: bool
"""
url = self._build_url('lab... |
Re-open a closed issue.
:returns: bool
def reopen(self):
"""Re-open a closed issue.
:returns: bool
"""
assignee = self.assignee.login if self.assignee else ''
number = self.milestone.number if self.milestone else None
labels = [str(l) for l in self.labels]
... |
Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object.
def _strptime(self, time_str):
"""Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object."""
if time_str:
# Parse UTC string into naive datetime, then add timezone
... |
Generic iterator for this project.
:param int count: How many items to return.
:param int url: First URL to start with
:param class cls: cls to return an object of
:param params dict: (optional) Parameters for the request
:param str etag: (optional), ETag from the last call
def... |
Number of requests before GitHub imposes a ratelimit.
:returns: int
def ratelimit_remaining(self):
"""Number of requests before GitHub imposes a ratelimit.
:returns: int
"""
json = self._json(self._get(self._github_url + '/rate_limit'), 200)
core = json.get('resources'... |
Re-retrieve the information for this object and returns the
refreshed instance.
:param bool conditional: If True, then we will search for a stored
header ('Last-Modified', or 'ETag') on the object and send that
as described in the `Conditional Requests`_ section of the docs
... |
Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool
def edit(self, body):
"""Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool
"""
... |
To plot formatter
def toplot(ts,
filename=None,
grid=True,
legend=True,
pargs=(),
**kwargs):
'''To plot formatter'''
fig = plt.figure()
ax = fig.add_subplot(111)
dates = list(ts.dates())
ax.plot(dates, ts.values(), *pargs)
ax.gri... |
Ensure the table is valid for converting to grid table.
* The table must a list of lists
* Each row must contain the same number of columns
* The table must not be empty
Parameters
----------
table : list of lists of str
The list of rows of strings to convert to a grid table
Retur... |
Gets the span containing the [row, column] pair
Parameters
----------
spans : list of lists of lists
A list containing spans, which are lists of [row, column] pairs
that define where a span is inside a table.
Returns
-------
span : list of lists
A span containing the [r... |
Search through a table and return the first [row, column] pair
who's value is None.
Parameters
----------
table : list of lists of str
Returns
-------
list of int
The row column pair of the None type cell
def find_unassigned_table_cell(table):
"""
Search through a table an... |
insert *values* at date *dte*.
def insert(self, dte, values):
'''insert *values* at date *dte*.'''
if len(values):
dte = self.dateconvert(dte)
if not self:
self._date = np.array([dte])
self._data = np.array([values])
else:
... |
Convert node names into node instances...
def _translate_nodes(root, *nodes):
"""
Convert node names into node instances...
"""
#name2node = {[n, None] for n in nodes if type(n) is str}
name2node = dict([[n, None] for n in nodes if type(n) is str])
for n in root.traverse():
if n.name in... |
Add or update a node's feature.
def add_feature(self, pr_name, pr_value):
""" Add or update a node's feature. """
setattr(self, pr_name, pr_value)
self.features.add(pr_name) |
Add or update several features.
def add_features(self, **features):
""" Add or update several features. """
for fname, fvalue in six.iteritems(features):
setattr(self, fname, fvalue)
self.features.add(fname) |
Permanently deletes a node's feature.
def del_feature(self, pr_name):
""" Permanently deletes a node's feature."""
if hasattr(self, pr_name):
delattr(self, pr_name)
self.features.remove(pr_name) |
Adds a new child to this node. If child node is not suplied
as an argument, a new node instance will be created.
Parameters
----------
child:
the node instance to be added as a child.
name:
the name that will be given to the child.
dist... |
Removes a child from this node (parent and child
nodes still exit but are no longer connected).
def remove_child(self, child):
"""
Removes a child from this node (parent and child
nodes still exit but are no longer connected).
"""
try:
self.children.remove(ch... |
Adds a sister to this node. If sister node is not supplied
as an argument, a new TreeNode instance will be created and
returned.
def add_sister(self, sister=None, name=None, dist=None):
"""
Adds a sister to this node. If sister node is not supplied
as an argument, a new TreeNode... |
Removes a sister node. It has the same effect as
**`TreeNode.up.remove_child(sister)`**
If a sister node is not supplied, the first sister will be deleted
and returned.
:argument sister: A node instance
:return: The node removed
def remove_sister(self, sister=None):
"... |
Deletes node from the tree structure. Notice that this method
makes 'disappear' the node from the tree structure. This means
that children from the deleted node are transferred to the
next available parent.
Parameters:
-----------
prevent_nondicotomic:
When ... |
Detachs this node (and all its descendants) from its parent
and returns the referent to itself.
Detached node conserves all its structure of descendants, and can
be attached to another node through the 'add_child' function. This
mechanism can be seen as a cut and paste.
def detach(self... |
Prunes the topology of a node to conserve only a selected list of leaf
internal nodes. The minimum number of nodes that conserve the
topological relationships among the requested nodes will be
retained. Root node is always conserved.
Parameters:
-----------
nodes:
... |
Returns an indepent list of sister nodes.
def get_sisters(self):
""" Returns an indepent list of sister nodes."""
if self.up != None:
return [ch for ch in self.up.children if ch != self]
else:
return [] |
Returns an iterator over the leaves under this node.
def iter_leaves(self, is_leaf_fn=None):
""" Returns an iterator over the leaves under this node."""
for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn):
if not is_leaf_fn:
if n.is_leaf():
... |
Returns an iterator over the leaf names under this node.
def iter_leaf_names(self, is_leaf_fn=None):
"""Returns an iterator over the leaf names under this node."""
for n in self.iter_leaves(is_leaf_fn=is_leaf_fn):
yield n.name |
Returns an iterator over all descendant nodes.
def iter_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator over all descendant nodes."""
for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn):
if n is not self:
yield n |
Returns a list of all (leaves and internal) descendant nodes.
def get_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns a list of all (leaves and internal) descendant nodes."""
return [n for n in self.iter_descendants(
strategy=strategy, is_leaf_fn=is_leaf_fn)] |
Returns an iterator to traverse tree under this node.
Parameters:
-----------
strategy:
set the way in which tree will be traversed. Possible
values are: "preorder" (first parent and then children)
'postorder' (first children and the parent) and
... |
Iterate over all nodes in a tree yielding every node in both
pre and post order. Each iteration returns a postorder flag
(True if node is being visited in postorder) and a node
instance.
def iter_prepostorder(self, is_leaf_fn=None):
"""
Iterate over all nodes in a tree yielding ... |
Iterate over all desdecendant nodes.
def _iter_descendants_levelorder(self, is_leaf_fn=None):
""" Iterate over all desdecendant nodes."""
tovisit = deque([self])
while len(tovisit) > 0:
node = tovisit.popleft()
yield node
if not is_leaf_fn or not is_leaf_fn(n... |
Iterator over all descendant nodes.
def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_... |
Iterates over the list of all ancestor nodes from
current node to the current tree root.
def iter_ancestors(self):
"""
Iterates over the list of all ancestor nodes from
current node to the current tree root.
"""
node = self
while node.up is not None:
... |
Returns the newick representation of current node. Several
arguments control the way in which extra data is shown for
every node:
Parameters:
-----------
features:
a list of feature names to be exported using the Extended Newick
Format (i.e. features=["... |
Returns the absolute root node of current tree structure.
def get_tree_root(self):
""" Returns the absolute root node of current tree structure."""
root = self
while root.up is not None:
root = root.up
return root |
Returns the first common ancestor between this node and a given
list of 'target_nodes'.
**Examples:**
t = tree.Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=common], (D:0.00001):0.000001):2.0[&&NHX:name=root];")
A = t.get_descendants_by_name("A")[0]
C = t.get_des... |
Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees.
def iter_search_nodes(self, **conditions):
"""
Search nodes in an interative wa... |
Returns the list of nodes matching a given set of conditions.
**Example:**
tree.search_nodes(dist=0.0, name="human")
def search_nodes(self, **conditions):
"""
Returns the list of nodes matching a given set of conditions.
**Example:**
tree.search_nodes(dist=0.0, name="hum... |
Returns the distance between two nodes. If only one target is
specified, it returns the distance bewtween the target and the
current node.
Parameters:
-----------
target:
a node within the same tree structure.
target2:
a node within the sam... |
Returns the node's farthest descendant or ancestor node, and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other words, topological distance will be
used instead of branch ... |
Returns node's farthest descendant node (which is always a leaf), and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other words, topological distance will be
used instead o... |
Returns the node that divides the current tree into two
distance-balanced partitions.
def get_midpoint_outgroup(self):
"""
Returns the node that divides the current tree into two
distance-balanced partitions.
"""
# Gets the farthest node to the current root
roo... |
Generates a random topology by populating current node.
:argument None names_library: If provided, names library
(list, set, dict, etc.) will be used to name nodes.
:argument False reuse_names: If True, node names will not be
necessarily unique, which makes the process a bit more
... |
Sets a descendant node as the outgroup of a tree. This function
can be used to root a tree or even an internal node.
Parameters:
-----------
outgroup:
a node instance within the same tree structure that will be
used as a basal node.
def set_outgroup(self, out... |
Unroots current node. This function is expected to be used on
the absolute tree root node, but it can be also be applied to
any other internal node. It will convert a split into a
multifurcation.
def unroot(self):
"""
Unroots current node. This function is expected to be used on... |
Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project.
def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None):
"""
Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project.
"""
if not ... |
Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per tip.
attributes:
A list of node attributes to shown in the ASCII represe... |
Sort the branches of a given tree (swapping children nodes)
according to the size of each partition.
def ladderize(self, direction=0):
"""
Sort the branches of a given tree (swapping children nodes)
according to the size of each partition.
"""
if not self.is_leaf():
... |
This function sort the branches of a given tree by
considerening node names. After the tree is sorted, nodes are
labeled using ascendent numbers. This can be used to ensure
that nodes in a tree with the same node names are always
labeled in the same way. Note that if duplicated names ar... |
Returns a dictionary pointing to the preloaded content of each
internal node under this tree. Such a dictionary is intended
to work as a cache for operations that require many traversal
operations.
Parameters:
-----------
store_attr:
Specifies the no... |
Returns the Robinson-Foulds symmetric distance between current
tree and a different tree instance.
Parameters:
-----------
t2:
reference tree
attr_t1:
Compare trees using a custom node attribute as a node name.
attr_t2:
Compare tree... |
Iterate over the list of edges of a tree. Each egde is represented as a
tuple of two elements, each containing the list of nodes separated by
the edge.
def iter_edges(self, cached_content=None):
"""
Iterate over the list of edges of a tree. Each egde is represented as a
tuple of... |
Returns the unique ID representing the topology of the current tree.
Two trees with the same topology will produce the same id. If trees are
unrooted, make sure that the root node is not binary or use the
tree.unroot() function before generating the topology id.
This is useful to detec... |
Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
structure, a ValueError exception will be raised to warn that
strict monophyly could never be reached (this behaviour can be
... |
Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values for which monophyly is
expected.
:param target_at... |
Given a tree with one or more polytomies, this functions returns the
list of all trees (in newick format) resulting from the combination of
all possible solutions of the multifurcated nodes.
.. warning:
Please note that the number of of possible binary trees grows
exponen... |
Resolve all polytomies under current node by creating an
arbitrary dicotomic structure among the affected nodes. This
function randomly modifies current tree topology and should
only be used for compatibility reasons (i.e. programs
rejecting multifurcated node in the newick representatio... |
Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text lines without empty lines above or below
def... |
Convert a date or datetime object into a javsacript timestamp
def jstimestamp_slow(dte):
'''Convert a date or datetime object into a javsacript timestamp'''
year, month, day, hour, minute, second = dte.timetuple()[:6]
days = date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
hours = days*24 + ... |
Convert a date or datetime object into a javsacript timestamp.
def jstimestamp(dte):
'''Convert a date or datetime object into a javsacript timestamp.'''
days = date(dte.year, dte.month, 1).toordinal() - _EPOCH_ORD + dte.day - 1
hours = days*24
if isinstance(dte,datetime):
hours += d... |
Convert a string or html file to an rst table string.
Parameters
----------
html_string : str
Either the html string, or the filepath to the html
force_headers : bool
Make the first row become headers, whether or not they are
headers in the html file.
center_cells : bool
... |
Create a list of rows and columns that will make up a span
Parameters
----------
row : int
The row of the first cell in the span
column : int
The column of the first cell in the span
extra_rows : int
The number of rows that make up the span
extra_columns : int
Th... |
Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [row, column] pairs that make up a span in the table
widths : list of... |
Initialize application object.
def init_app(self, app, **kwargs):
"""Initialize application object."""
self.init_db(app, **kwargs)
app.config.setdefault('ALEMBIC', {
'script_location': pkg_resources.resource_filename(
'invenio_db', 'alembic'
),
... |
Initialize Flask-SQLAlchemy extension.
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
"""Initialize Flask-SQLAlchemy extension."""
# Setup SQLAlchemy
app.config.setdefault(
'SQLALCHEMY_DATABASE_URI',
'sqlite:///' + os.path.join(app.instance_path... |
Initialize the versioning support using SQLAlchemy-Continuum.
def init_versioning(self, app, database, versioning_manager=None):
"""Initialize the versioning support using SQLAlchemy-Continuum."""
try:
pkg_resources.get_distribution('sqlalchemy_continuum')
except pkg_resources.Distr... |
Convert an html string to data table
Parameters
----------
html_string : str
row_count : int
column_count : int
Returns
-------
data_table : list of lists of str
def extract_table(html_string, row_count, column_count):
"""
Convert an html string to data table
Parameters
... |
Ensure SQLite checks foreign key constraints.
For further details see "Foreign key support" sections on
https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support
def do_sqlite_connect(dbapi_connection, connection_record):
"""Ensure SQLite checks foreign key constraints.
For furth... |
Call before engine creation.
def apply_driver_hacks(self, app, info, options):
"""Call before engine creation."""
# Don't forget to apply hacks defined on parent object.
super(SQLAlchemy, self).apply_driver_hacks(app, info, options)
if info.drivername == 'sqlite':
connect_a... |
Create tables.
def create(verbose):
"""Create tables."""
click.secho('Creating all tables!', fg='yellow', bold=True)
with click.progressbar(_db.metadata.sorted_tables) as bar:
for table in bar:
if verbose:
click.echo(' Creating table {0}'.format(table))
table... |
Drop tables.
def drop(verbose):
"""Drop tables."""
click.secho('Dropping all tables!', fg='red', bold=True)
with click.progressbar(reversed(_db.metadata.sorted_tables)) as bar:
for table in bar:
if verbose:
click.echo(' Dropping table {0}'.format(table))
tabl... |
Create database.
def init():
"""Create database."""
click.secho('Creating database {0}'.format(_db.engine.url),
fg='green')
if not database_exists(str(_db.engine.url)):
create_database(str(_db.engine.url)) |
Drop database.
def destroy():
"""Drop database."""
click.secho('Destroying database {0}'.format(_db.engine.url),
fg='red', bold=True)
if _db.engine.name == 'sqlite':
try:
drop_database(_db.engine.url)
except FileNotFoundError as e:
click.secho('Sqlite... |
Fast rolling operation with O(log n) updates where n is the
window size
def rolling(self, op):
"""Fast rolling operation with O(log n) updates where n is the
window size
"""
missing = self.missing
ismissing = self.ismissing
window = self.window
it = ite... |
Find the length of a colspan.
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
columns : int
The number of columns included in the span
Example
-------
Consider this table::
+------+-----------... |
returns self as a dictionary with _underscore subdicts corrected.
def to_dict(self):
"returns self as a dictionary with _underscore subdicts corrected."
ndict = {}
for key, val in self.__dict__.items():
if key[0] == "_":
ndict[key[1:]] = val
else:
... |
Sum the widths of the columns that make up the span, plus the extra.
Parameters
----------
span : list of lists of int
list of [row, column] pairs that make up the span
column_widths : list of int
The widths of the columns that make up the table
Returns
-------
total_width ... |
Rebuild a model's EncryptedType properties when the SECRET_KEY is changed.
:param old_key: old SECRET_KEY.
:param model: the affected db model.
:param properties: list of properties to rebuild.
def rebuild_encrypted_properties(old_key, model, properties):
"""Rebuild a model's EncryptedType properties ... |
Create alembic_version table.
def create_alembic_version_table():
"""Create alembic_version table."""
alembic = current_app.extensions['invenio-db'].alembic
if not alembic.migration_context._has_version_table():
alembic.migration_context._ensure_version_table()
for head in alembic.script_di... |
Drop alembic_version table.
def drop_alembic_version_table():
"""Drop alembic_version table."""
if _db.engine.dialect.has_table(_db.engine, 'alembic_version'):
alembic_version = _db.Table('alembic_version', _db.metadata,
autoload_with=_db.engine)
alembic_vers... |
Get the name of the versioned model class.
def versioning_model_classname(manager, model):
"""Get the name of the versioned model class."""
if manager.options.get('use_module_name', True):
return '%s%sVersion' % (
model.__module__.title().replace('.', ''), model.__name__)
else:
... |
Return True if all versioning models have been registered.
def versioning_models_registered(manager, base):
"""Return True if all versioning models have been registered."""
declared_models = base._decl_class_registry.keys()
return all(versioning_model_classname(manager, c) in declared_models
... |
Convert an iterable into a symmetric matrix.
def vector_to_symmetric(v):
'''Convert an iterable into a symmetric matrix.'''
np = len(v)
N = (int(sqrt(1 + 8*np)) - 1)//2
if N*(N+1)//2 != np:
raise ValueError('Cannot convert vector to symmetric matrix')
sym = ndarray((N,N))
iterabl... |
The covariance matrix from the aggregate sample. It accepts an
optional parameter for the degree of freedoms.
:parameter ddof: If not ``None`` normalization is by (N - ddof), where N is
the number of observations; this overrides the value implied by bias.
The default value ... |
The correlation matrix
def corr(self):
'''The correlation matrix'''
cov = self.cov()
N = cov.shape[0]
corr = ndarray((N,N))
for r in range(N):
for c in range(r):
corr[r,c] = corr[c,r] = cov[r,c]/sqrt(cov[r,r]*cov[c,c])
corr[r,r] = ... |
Calculate the Calmar ratio for a Weiner process
@param sharpe: Annualized Sharpe ratio
@param T: Time interval in years
def calmar(sharpe, T = 1.0):
'''
Calculate the Calmar ratio for a Weiner process
@param sharpe: Annualized Sharpe ratio
@param T: Time interval... |
Multiplicator for normalizing calmar ratio to period tau
def calmarnorm(sharpe, T, tau = 1.0):
'''
Multiplicator for normalizing calmar ratio to period tau
'''
return calmar(sharpe,tau)/calmar(sharpe,T) |
Upgrade database.
def upgrade():
"""Upgrade database."""
op.execute('COMMIT') # See https://bitbucket.org/zzzeek/alembic/issue/123
ctx = op.get_context()
metadata = ctx.opts['target_metadata']
metadata.naming_convention = NAMING_CONVENTION
metadata.bind = ctx.connection.engine
insp = Inspe... |
Convert table data to a simple rst table
Parameters
----------
table : list of lists of str
A table of strings.
spans : list of lists of lists of int
A list of spans. A span is a list of [Row, Column] pairs of
table cells that are joined together.
use_headers : bool, optiona... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.