text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
yield node.up
node = node.up |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_common_ancestor(self, *target_nodes, **kargs):
""" Returns the first common ancestor between this node and a given list of 'target_nodes'. **Examples:** ... |
get_path = kargs.get("get_path", False)
if len(target_nodes) == 1 and type(target_nodes[0]) \
in set([set, tuple, list, frozenset]):
target_nodes = target_nodes[0]
# Convert node names into node instances
target_nodes = _translate_nodes(self, *target_nodes)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_search_nodes(self, **conditions):
""" Search nodes in an interative way. Matches are being yield as they are being found. This avoids to scan the full t... |
for n in self.traverse():
conditions_passed = 0
for key, value in six.iteritems(conditions):
if hasattr(n, key) and getattr(n, key) == value:
conditions_passed +=1
if conditions_passed == len(conditions):
yield n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_farthest_node(self, topology_only=False):
""" Returns the node's farthest descendant or ancestor node, and the distance to it. :argument False topology_o... |
# Init fasthest node to current farthest leaf
farthest_node, farthest_dist = self.get_farthest_leaf(
topology_only=topology_only)
prev = self
cdist = 0.0 if topology_only else prev.dist
current = prev.up
while current is not None:
for ch in curre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
root = self.get_tree_root()
nA, r2A_dist = root.get_farthest_leaf()
nB, A2B_dist = nA.get_farthest_node()
outgroup = nA
middist = A2B_dist / 2.0
cdist = 0
current = nA
while current is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate(self, size, names_library=None, reuse_names=False, random_branches=False, branch_range=(0, 1), support_range=(0, 1)):
""" Generates a random topolog... |
NewNode = self.__class__
if len(self.children) > 1:
connector = NewNode()
for ch in self.get_children():
ch.detach()
connector.add_child(child = ch)
root = NewNode()
self.add_child(child = connector)
self.add_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_outgroup(self, outgroup):
""" Sets a descendant node as the outgroup of a tree. This function can be used to root a tree or even an internal node. Parame... |
outgroup = _translate_nodes(self, outgroup)
if self == outgroup:
##return
## why raise an error for this?
raise TreeError("Cannot set myself as outgroup")
parent_outgroup = outgroup.up
# Detects (sub)tree root
n = outgroup
while n.u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unroot(self):
""" 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 inter... |
if len(self.children)==2:
if not self.children[0].is_leaf():
self.children[0].delete()
elif not self.children[1].is_leaf():
self.children[1].delete()
else:
raise TreeError("Cannot unroot a tree with only two leaves") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None):
""" Returns the ASCII representation of the tree. Code based on the PyCogent ... |
if not attributes:
attributes = ["name"]
# toytree edit:
# removed six dependency for map with comprehension
# node_name = ', '.join(map(str, [getattr(self, v) for v in attributes if hasattr(self, v)]))
_attrlist = [getattr(self, v) for v in attributes if ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_descendants(self, attr="name"):
""" This function sort the branches of a given tree by considerening node names. After the tree is sorted, nodes are lab... |
node2content = self.get_cached_content(store_attr=attr, container_type=list)
for n in self.traverse():
if not n.is_leaf():
n.children.sort(key=lambda x: str(sorted(node2content[x]))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_edges(self, cached_content=None):
""" Iterate over the list of edges of a tree. Each egde is represented as a tuple of two elements, each containing the... |
if not cached_content:
cached_content = self.get_cached_content()
all_leaves = cached_content[self]
for n, side1 in six.iteritems(cached_content):
yield (side1, all_leaves - side1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_monophyly(self, values, target_attr, ignore_missing=False, unrooted=False):
""" Returns True if a given target attribute is monophyletic under this nod... |
if type(values) != set:
values = set(values)
# This is the only time I traverse the tree, then I use cached
# leaf content
n2leaves = self.get_cached_content()
# Raise an error if requested attribute values are not even present
if ignore_missing:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_monophyletic(self, values, target_attr):
""" Returns a list of nodes matching the provided monophyly criteria. For a node to be considered a match, all `... |
if type(values) != set:
values = set(values)
n2values = self.get_cached_content(store_attr=target_attr)
is_monophyletic = lambda node: n2values[node] == values
for match in self.iter_leaves(is_leaf_fn=is_monophyletic):
if is_monophyletic(match):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate_empty_lines(lines):
""" Removes all empty lines from above and below the text. We can't just use text.strip() because that would remove the leading ... |
while lines[0].rstrip() == '':
lines.pop(0)
while lines[len(lines) - 1].rstrip() == '':
lines.pop(-1)
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 + hour
minutes = hours*60 + minute
seconds = minutes*60... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 += dte.hour
minutes = hours*60 + dte.minute
second... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def html2rst(html_string, force_headers=False, center_cells=False, center_headers=False):
""" Convert a string or html file to an rst table string. Parameters ht... |
if os.path.isfile(html_string):
file = open(html_string, 'r', encoding='utf-8')
lines = file.readlines()
file.close()
html_string = ''.join(lines)
table_data, spans, use_headers = html2data(
html_string)
if table_data == '':
return ''
if force_headers:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_span(row, column, extra_rows, extra_columns):
""" Create a list of rows and columns that will make up a span Parameters row : int The row of the first c... |
span = [[row, column]]
for r in range(row, row + extra_rows + 1):
span.append([r, column])
for c in range(column, column + extra_columns + 1):
span.append([row, c])
span.append([r, c])
return span |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_cell(table, span, widths, heights, use_headers):
""" Convert the contents of a span of the table to a grid table cell Parameters table : list of lists o... |
width = get_span_char_width(span, widths)
height = get_span_char_height(span, heights)
text_row = span[0][0]
text_column = span[0][1]
text = table[text_row][text_column]
lines = text.split("\n")
for i in range(len(lines)):
width_difference = width - len(lines[i])
lines[i] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, app.name + '.db')
)
app.config.setdefault('SQLALCHEMY_ECHO', False)
# Initialize Flask-SQLAlchemy extension.
database = kwargs.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.DistributionNotFound: # pragma: no cover
default_versioning = False
else:
default_versioning = True
app.config.setdefault('DB_VERSIONING', default_versioning)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_table(html_string, row_count, column_count):
""" Convert an html string to data table Parameters html_string : str row_count : int column_count : int... |
try:
from bs4 import BeautifulSoup
from bs4.element import Tag
except ImportError:
print("ERROR: You must have BeautifulSoup to use html2data")
return
#html_string = convertRichText(html_string)
data_table = []
for row in range(0, row_count):
data_table.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_sqlite_connect(dbapi_connection, connection_record):
"""Ensure SQLite checks foreign key constraints. For further details see "Foreign key support" sectio... |
# Enable foreign key constraint checking
cursor = dbapi_connection.cursor()
cursor.execute('PRAGMA foreign_keys=ON')
cursor.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_args = options.setdefault('connect_args', {})
if 'isolation_level' not in connect_args:
# disa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.create(bind=_db.engine, checkfirst=True)
create_alembic_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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))
table.drop(bind=_db.engine, checkfirst=True)
drop_a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 database has not been initialised',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span_column_count(span):
""" Find the length of a colspan. Parameters span : list of lists of int The [row, column] pairs that make up the span Returns -... |
columns = 1
first_column = span[0][1]
for i in range(len(span)):
if span[i][1] > first_column:
columns += 1
first_column = span[i][1]
return columns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
ndict[key] = val
return ndict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span_char_width(span, column_widths):
""" Sum the widths of the columns that make up the span, plus the extra. Parameters span : list of lists of int lis... |
start_column = span[0][1]
column_count = get_span_column_count(span)
total_width = 0
for i in range(start_column, start_column + column_count):
total_width += column_widths[i]
total_width += column_count - 1
return total_width |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild_encrypted_properties(old_key, model, properties):
"""Rebuild a model's EncryptedType properties when the SECRET_KEY is changed. :param old_key: old S... |
inspector = reflection.Inspector.from_engine(db.engine)
primary_key_names = inspector.get_primary_keys(model.__tablename__)
new_secret_key = current_app.secret_key
db.session.expunge_all()
try:
with db.session.begin_nested():
current_app.secret_key = old_key
db_colu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_directory.revision_map._real_heads:
alembic.migration_context.stamp(alembic.script_directory, he... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_version.drop(bind=_db.engine) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 '%sVersion' % (model.__name__,) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
for c in manager.pending_classes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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))
iterable = iter(v)
for r in range(N):
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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] = 1.
return corr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calmar(sharpe, T = 1.0):
'''
Calculate the Calmar ratio for a Weiner process
@param sharpe: Annualized Sharpe ratio
@param T: Time interval in years
'''
x = 0.5*T*sharpe*sharpe
return x/qp(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def calmarnorm(sharpe, T, tau = 1.0):
'''
Multiplicator for normalizing calmar ratio to period tau
'''
return calmar(sharpe,tau)/calmar(sharpe,T) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = {}
citations = {}
backrefs = {}
links = soup.find_all('a')
for link in links:
href = link.get('href')
text = pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_consensus_tree(self, cutoff=0.0, best_tree=None):
""" Returns an extended majority rule consensus tree as a Toytree object. Node labels include 'support'... |
if best_tree:
raise NotImplementedError("best_tree option not yet supported.")
cons = ConsensusTree(self.treelist, cutoff)
cons.update()
return cons.ttree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
observed[hashed] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 in self.treedict.items():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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_counts])
for idx in range(carrs.shape[0]):
conflic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 keys
countdict = defaultdict(int)
for clade, co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 distance_func(self.phonetics(word1), self.phonetics(word2))
else:
raise DistanceMetricError('Distance metric not supported! Choose from levenshtein, hamming.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_output_row_heights(table, spans):
""" Get the heights of the rows of the output table. Parameters table : list of lists of str spans : list of lists of i... |
heights = []
for row in table:
heights.append(-1)
for row in range(len(table)):
for column in range(len(table[row])):
text = table[row][column]
span = get_span(spans, row, column)
row_count = get_span_row_count(span)
height = len(text.split('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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])
return me
else:
return NaN |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 bound')
output = np.ndarray(N-window+1,dtype=input.dtype)
for val in inpu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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,0,0.,0.
N = len(input)
sqrt = np.sqrt
if window > N:
raise ValueError('Out of bound')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_span(span, table):
""" Ensure the span is valid. A span is a list of [row, column] pairs. These coordinates must form a rectangular shape. For example,... |
if not type(span) is list:
return "Spans must be a list of lists"
for pair in span:
if not type(pair) is list:
return "Spans must be a list of lists of int"
if not len(pair) == 2:
return "Spans must be a [Row, Column] pair of integers"
total_rows = get_spa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_all_cells(cells):
""" Loop through list of cells and piece them together one by one Parameters cells : list of dashtable.data2rst.Cell Returns ------- ... |
current = 0
while len(cells) > 1:
count = 0
while count < len(cells):
cell1 = cells[current]
cell2 = cells[count]
merge_direction = get_merge_direction(cell1, cell2)
if not merge_direction == "NONE":
merge_cells(cell1, cell2, me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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(";", new)
new = regex3.sub(":", new)
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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], key=lambda x: len(x.get_leaves()))[0]
else:
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.... |
# make tree height = 1 * treeheight
ctree = self._ttree.copy()
_height = ctree.treenode.height
for node in ctree.treenode.traverse():
node.dist = (node.dist / _height) * treeheight
ctree._coords.update()
return ctree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_slider(self, seed=None):
""" Returns a toytree copy with node heights modified while retaining the same topology but not necessarily node branching orde... |
# I don't think user's should need to access prop
prop = 0.999
assert isinstance(prop, float), "prop must be a float"
assert prop < 1, "prop must be a proportion >0 and < 1."
random.seed(seed)
ctree = self._ttree.copy()
for node in ctree.treenode.traverse():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = toytree.tree()
rtree.treenode.add_child(name="0")
rtree.treenode.add_child(name="1")
# add tips in a balanced... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span_char_height(span, row_heights):
""" Get the height of a span in the number of newlines it fills. Parameters span : list of list of int A list of [ro... |
start_row = span[0][0]
row_count = get_span_row_count(span)
total_height = 0
for i in range(start_row, start_row + row_count):
total_height += row_heights[i]
total_height += row_count - 1
return total_height |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def html2data(html_string):
""" Convert an html table to a data table and spans. Parameters html_string : str The string containing the html table Returns ------... |
spans = extract_spans(html_string)
column_count = get_html_column_count(html_string)
row_count = get_html_row_count(spans)
count = 0
while count < len(spans):
if len(spans[count]) == 1:
spans.pop(count)
else:
count += 1
table = extract_table(html_strin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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", "support", "height", "idx"}
testnode = self.treenode.chil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_values( self, feature=None, show_root=False, show_tips=False, ):
""" Returns node values from tree object in node plot order. To modify values you m... |
# access nodes in the order they will be plotted
ndict = self.get_node_dict(return_internal=True, return_nodes=True)
nodes = [ndict[i] for i in range(self.nnodes)[::-1]]
# get features
if feature:
vals = [i.__getattribute__(feature) if hasattr(i, feature)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tip_coordinates(self, axis=None):
""" Returns coordinates of the tip positions for a tree. If no argument for axis then a 2-d array is returned. The firs... |
# get coordinates array
coords = self.get_node_coordinates()
if axis == 'x':
return coords[:self.ntips, 0]
elif axis == 'y':
return coords[:self.ntips, 1]
return coords[:self.ntips] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate_node( self, names=None, wildcard=None, regex=None, idx=None, # modify_tree=False, ):
""" Returns a ToyTree with the selected node rotated for plotting... |
# make a copy
revd = {j: i for (i, j) in enumerate(self.get_tip_labels())}
neworder = {}
# get node to rotate
treenode = fuzzy_match_tipnames(
self, names, wildcard, regex, True, True)
children = treenode.up.children
names = [[j.name for j in i.get_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_polytomy( self, dist=1.0, support=100, recursive=True):
""" Returns a copy of the tree with all polytomies randomly resolved. Does not transform tree... |
nself = self.copy()
nself.treenode.resolve_polytomy(
default_dist=dist,
default_support=support,
recursive=recursive)
nself._coords.update()
return nself |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()
return nself |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_merge_direction(cell1, cell2):
""" Determine the side of cell1 that can be merged with cell2. This is based on the location of the two cells in the table... |
cell1_left = cell1.column
cell1_right = cell1.column + cell1.column_count
cell1_top = cell1.row
cell1_bottom = cell1.row + cell1.row_count
cell2_left = cell2.column
cell2_right = cell2.column + cell2.column_count
cell2_top = cell2.row
cell2_bottom = cell2.row + cell2.row_count
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
# enter trees block
if line.lower(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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._write_commits_to_release_notes()
## writes tag or 'devel' to
try:
self._write_new_tag_to_init()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(),
re.M).group(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.check_output(cmdlist)
## Split off just the first element, we don't need commit tag
self.commits = [x.split(" ", 1) fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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))
for commit in self.commits:
try:
msg = commit[1]
if msg != "cosmetic":
out.write("-" + msg + "\n")
exc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
dat = infile.read()
newdat = dat.format(**{'tag': self.tag, 'branch': self.branch})
with open(self.meta_yaml, 'w') as outfile:
outfile.write(newdat) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 version")
## tmp dir
bldir = "./tmp-bld"
if not os.path.exists(bldir):
os.makedirs(bldir)
## iterate over builds
for p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span_row_count(span):
""" 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... |
rows = 1
first_row = span[0][0]
for i in range(len(span)):
if span[i][0] > first_row:
rows += 1
first_row = span[i][0]
return rows |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)
if dtype == object_type:
a ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multis_2_mono(table):
""" Converts each multiline string in a table to single line. Parameters table : list of list of str A list of rows containing strings ... |
for row in range(len(table)):
for column in range(len(table[row])):
table[row][column] = table[row][column].replace('\n', ' ')
return table |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_counts[str(span[0][1])] = get_span_row_count(span)
values = list(row_counts.values(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 func:
return func(*args, **kwargs)
else:
return f(ts... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 (ts - mi)/(ma - mi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)
assert N > 20
vmin = min(data)
vmax = max(data)
DV = vmax - vmin
tol = tole*DV
vmax += t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def binOp(op, indx, amap, bmap, fill_vec):
'''
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 op_or_missing(id):
va = amap.get(id, None)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_line(space, line):
""" Add leading & trailing space to text to center it within an allowed width Parameters space : int The maximum character width al... |
line = line.strip()
left_length = math.floor((space - len(line)) / 2)
right_length = math.ceil((space - len(line)) / 2)
left_space = " " * int(left_length)
right_space = " " * int(right_length)
line = ''.join([left_space, line, right_space])
return line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, function):
"""Register a function in the function registry.
The function will be automatically instantiated if not already an
instance.
""... |
function = inspect.isclass(function) and function() or function
name = function.name
self[name] = function |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, name):
"""Unregister function by name.
""" |
try:
name = name.name
except AttributeError:
pass
return self.pop(name,None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def row_includes_spans(table, row, spans):
""" Determine if there are spans within a row Parameters table : list of lists of str row : int spans : list of lists ... |
for column in range(len(table[row])):
for span in spans:
if [row, column] in span:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(
"The 'state' attribute of a workflow should be "
"a two-tuple of strings; got %r instead." % (state_def,)
)
name, title = state_def
st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_transitions(tdef, states, prev=()):
"""Create a TransitionList object from a 'transitions' Workflow attribute. Args: tdef: list of transition definiti... |
trs = list(prev)
for transition in tdef:
if len(transition) == 3:
(name, source, target) = transition
if is_string(source) or isinstance(source, State):
source = [source]
source = [states[src] for src in source]
target = states[target]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 called as "
"@transition(['transition_name'], **kwargs)")
if check or before or after:
warnings.warn(
"The use of check=, before= and after= in @transition decorators is "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_hook_dict(fun):
"""Ensure the given function has a xworkflows_hook attribute. That attribute has the following structure: """ |
if not hasattr(fun, 'xworkflows_hook'):
fun.xworkflows_hook = {
HOOK_BEFORE: [],
HOOK_AFTER: [],
HOOK_CHECK: [],
HOOK_ON_ENTER: [],
HOOK_ON_LEAVE: [],
}
return fun.xworkflows_hook |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 available from state '%s'." %
(self.transition.name, current_state.name))
for check in self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_to(self.transition, self.current_state)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_parent_implems(self, parent_implems):
"""Import previously defined implementations. Args: parent_implems (ImplementationList):
List of implementations ... |
for trname, attr, implem in parent_implems.get_custom_implementations():
self.implementations[trname] = implem.copy()
self.transitions_at[trname] = attr
self.custom_implems.add(trname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_implem(self, transition, attribute, function, **kwargs):
"""Add an implementation. Args: transition (Transition):
the transition for which the implement... |
implem = ImplementationProperty(
field_name=self.state_field,
transition=transition,
workflow=self.workflow,
implementation=function,
**kwargs)
self.implementations[transition.name] = implem
self.transitions_at[transition.name] = attri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.