Search is not available for this dataset
text stringlengths 75 104k |
|---|
def functional(self):
"""All required enzymes for reaction are functional.
Returns
-------
bool
True if the gene-protein-reaction (GPR) rule is fulfilled for
this reaction, or if reaction is not associated to a model,
otherwise False.
"""
... |
def _update_awareness(self):
"""Make sure all metabolites and genes that are associated with
this reaction are aware of it.
"""
for x in self._metabolites:
x._reaction.add(self)
for x in self._genes:
x._reaction.add(self) |
def remove_from_model(self, remove_orphans=False):
"""Removes the reaction from a model.
This removes all associations between a reaction the associated
model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Parameters
-------... |
def delete(self, remove_orphans=False):
"""Removes the reaction from a model.
This removes all associations between a reaction the associated
model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Deprecated, use `reaction.remove_from... |
def copy(self):
"""Copy a reaction
The referenced metabolites and genes are also copied.
"""
# no references to model when copying
model = self._model
self._model = None
for i in self._metabolites:
i._model = None
for i in self._genes:
... |
def get_coefficient(self, metabolite_id):
"""
Return the stoichiometric coefficient of a metabolite.
Parameters
----------
metabolite_id : str or cobra.Metabolite
"""
if isinstance(metabolite_id, Metabolite):
return self._metabolites[metabolite_id]
... |
def add_metabolites(self, metabolites_to_add, combine=True,
reversibly=True):
"""Add metabolites and stoichiometric coefficients to the reaction.
If the final coefficient for a metabolite is 0 then it is removed
from the reaction.
The change is reverted upon exit... |
def subtract_metabolites(self, metabolites, combine=True, reversibly=True):
"""Subtract metabolites from a reaction.
That means add the metabolites with -1*coefficient. If the final
coefficient for a metabolite is 0 then the metabolite is removed from
the reaction.
Notes
... |
def build_reaction_string(self, use_metabolite_names=False):
"""Generate a human readable reaction string"""
def format(number):
return "" if number == 1 else str(number).rstrip(".") + " "
id_type = 'id'
if use_metabolite_names:
id_type = 'name'
reactant... |
def check_mass_balance(self):
"""Compute mass and charge balance for the reaction
returns a dict of {element: amount} for unbalanced elements.
"charge" is treated as an element in this dict
This should be empty for balanced reactions.
"""
reaction_element_dict = defaultd... |
def compartments(self):
"""lists compartments the metabolites are in"""
if self._compartments is None:
self._compartments = {met.compartment for met in self._metabolites
if met.compartment is not None}
return self._compartments |
def _associate_gene(self, cobra_gene):
"""Associates a cobra.Gene object with a cobra.Reaction.
Parameters
----------
cobra_gene : cobra.core.Gene.Gene
"""
self._genes.add(cobra_gene)
cobra_gene._reaction.add(self)
cobra_gene._model = self._model |
def _dissociate_gene(self, cobra_gene):
"""Dissociates a cobra.Gene object with a cobra.Reaction.
Parameters
----------
cobra_gene : cobra.core.Gene.Gene
"""
self._genes.discard(cobra_gene)
cobra_gene._reaction.discard(self) |
def build_reaction_from_string(self, reaction_str, verbose=True,
fwd_arrow=None, rev_arrow=None,
reversible_arrow=None, term_split="+"):
"""Builds reaction from reaction equation reaction_str using parser
Takes a string and using the... |
def _clip(sid, prefix):
"""Clips a prefix from the beginning of a string if it exists."""
return sid[len(prefix):] if sid.startswith(prefix) else sid |
def _f_gene(sid, prefix="G_"):
"""Clips gene prefix from id."""
sid = sid.replace(SBML_DOT, ".")
return _clip(sid, prefix) |
def read_sbml_model(filename, number=float, f_replace=F_REPLACE,
set_missing_bounds=False, **kwargs):
"""Reads SBML model from given filename.
If the given filename ends with the suffix ''.gz'' (for example,
''myfile.xml.gz'),' the file is assumed to be compressed in gzip
format and... |
def _get_doc_from_filename(filename):
"""Get SBMLDocument from given filename.
Parameters
----------
filename : path to SBML, or SBML string, or filehandle
Returns
-------
libsbml.SBMLDocument
"""
if isinstance(filename, string_types):
if ("win" in platform) and (len(filena... |
def _sbml_to_model(doc, number=float, f_replace=F_REPLACE,
set_missing_bounds=False, **kwargs):
"""Creates cobra model from SBMLDocument.
Parameters
----------
doc: libsbml.SBMLDocument
number: data type of stoichiometry: {float, int}
In which data type should the stoichi... |
def write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):
"""Writes cobra model to filename.
The created model is SBML level 3 version 1 (L1V3) with
fbc package v2 (fbc-v2).
If the given filename ends with the suffix ".gz" (for example,
"myfile.xml.gz"), libSBML assumes the calle... |
def _model_to_sbml(cobra_model, f_replace=None, units=True):
"""Convert Cobra model to SBMLDocument.
Parameters
----------
cobra_model : cobra.core.Model
Cobra model instance
f_replace : dict of replacement functions
Replacement to apply on identifiers.
units : boolean
S... |
def _create_bound(model, reaction, bound_type, f_replace, units=None,
flux_udef=None):
"""Creates bound in model for given reaction.
Adds the parameters for the bounds to the SBML model.
Parameters
----------
model : libsbml.Model
SBML model instance
reaction : cobra.... |
def _create_parameter(model, pid, value, sbo=None, constant=True, units=None,
flux_udef=None):
"""Create parameter in SBML model."""
parameter = model.createParameter() # type: libsbml.Parameter
parameter.setId(pid)
parameter.setValue(value)
parameter.setConstant(constant)
... |
def _check_required(sbase, value, attribute):
"""Get required attribute from SBase.
Parameters
----------
sbase : libsbml.SBase
value : existing value
attribute: name of attribute
Returns
-------
attribute value (or value if already set)
"""
if (value is None) or (value ==... |
def _check(value, message):
"""
Checks the libsbml return value and logs error messages.
If 'value' is None, logs an error message constructed using
'message' and then exits with status code 1. If 'value' is an integer,
it assumes it is a libSBML return status code. If the code value is
L... |
def _parse_notes_dict(sbase):
""" Creates dictionary of COBRA notes.
Parameters
----------
sbase : libsbml.SBase
Returns
-------
dict of notes
"""
notes = sbase.getNotesString()
if notes and len(notes) > 0:
pattern = r"<p>\s*(\w+\s*\w*)\s*:\s*([\w|\s]+)<"
matche... |
def _sbase_notes_dict(sbase, notes):
"""Set SBase notes based on dictionary.
Parameters
----------
sbase : libsbml.SBase
SBML object to set notes on
notes : notes object
notes information from cobra object
"""
if notes and len(notes) > 0:
tokens = ['<html xmlns = "ht... |
def _parse_annotations(sbase):
"""Parses cobra annotations from a given SBase object.
Annotations are dictionaries with the providers as keys.
Parameters
----------
sbase : libsbml.SBase
SBase from which the SBML annotations are read
Returns
-------
dict (annotation dictionary... |
def _sbase_annotations(sbase, annotation):
"""Set SBase annotations based on cobra annotations.
Parameters
----------
sbase : libsbml.SBase
SBML object to annotate
annotation : cobra annotation structure
cobra object with annotation information
FIXME: annotation format must be ... |
def validate_sbml_model(filename,
check_model=True,
internal_consistency=True,
check_units_consistency=False,
check_modeling_practice=False, **kwargs):
"""Validate SBML model and returns the model along with a list of er... |
def _error_string(error, k=None):
"""String representation of SBMLError.
Parameters
----------
error : libsbml.SBMLError
k : index of error
Returns
-------
string representation of error
"""
package = error.getPackage()
if package == '':
package = 'core'
templa... |
def production_envelope(model, reactions, objective=None, carbon_sources=None,
points=20, threshold=None):
"""Calculate the objective value conditioned on all combinations of
fluxes for a set of chosen reactions
The production envelope can be used to analyze a model's ability to
... |
def total_yield(input_fluxes, input_elements, output_flux, output_elements):
"""
Compute total output per input unit.
Units are typically mol carbon atoms or gram of source and product.
Parameters
----------
input_fluxes : list
A list of input reaction fluxes in the same order as the
... |
def reaction_elements(reaction):
"""
Split metabolites into the atoms times their stoichiometric coefficients.
Parameters
----------
reaction : Reaction
The metabolic reaction whose components are desired.
Returns
-------
list
Each of the reaction's metabolites' desired... |
def reaction_weight(reaction):
"""Return the metabolite weight times its stoichiometric coefficient."""
if len(reaction.metabolites) != 1:
raise ValueError('Reaction weight is only defined for single '
'metabolite products or educts.')
met, coeff = next(iteritems(reaction.... |
def total_components_flux(flux, components, consumption=True):
"""
Compute the total components consumption or production flux.
Parameters
----------
flux : float
The reaction flux for the components.
components : list
List of stoichiometrically weighted components.
consumpt... |
def find_carbon_sources(model):
"""
Find all active carbon source reactions.
Parameters
----------
model : Model
A genome-scale metabolic model.
Returns
-------
list
The medium reactions with carbon input flux.
"""
try:
model.slim_optimize(error_value=N... |
def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):
"""Assesses production capacity.
Assesses the capacity of the model to produce the precursors for the
reaction and absorb the production of the reaction while the reaction is
operating at, or above, the specified cutoff.
Para... |
def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses the ability of the model to provide sufficient precursors,
or absorb products, for a reaction operating at, or beyond,
the specified cutoff.
Parameters
----------
model : co... |
def assess_precursors(model, reaction, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses the ability of the model to provide sufficient precursors for
a reaction operating at, or beyond, the specified cutoff.
Deprecated: use assess_component instead
Parameters
--------... |
def assess_products(model, reaction, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses whether the model has the capacity to absorb the products of
a reaction at a given flux rate.
Useful for identifying which components might be blocking a reaction
from achieving a specific ... |
def add_loopless(model, zero_cutoff=None):
"""Modify a model so all feasible flux distributions are loopless.
In most cases you probably want to use the much faster `loopless_solution`.
May be used in cases where you want to add complex constraints and
objecives (for instance quadratic objectives) to t... |
def _add_cycle_free(model, fluxes):
"""Add constraints for CycleFreeFlux."""
model.objective = model.solver.interface.Objective(
Zero, direction="min", sloppy=True)
objective_vars = []
for rxn in model.reactions:
flux = fluxes[rxn.id]
if rxn.boundary:
rxn.bounds = (fl... |
def loopless_solution(model, fluxes=None):
"""Convert an existing solution to a loopless one.
Removes as many loops as possible (see Notes).
Uses the method from CycleFreeFlux [1]_ and is much faster than
`add_loopless` and should therefore be the preferred option to get loopless
flux distributions... |
def loopless_fva_iter(model, reaction, solution=False, zero_cutoff=None):
"""Plugin to get a loopless FVA solution from single FVA iteration.
Assumes the following about `model` and `reaction`:
1. the model objective is set to be `reaction`
2. the model has been optimized and contains the minimum/maxim... |
def create_stoichiometric_matrix(model, array_type='dense', dtype=None):
"""Return a stoichiometric array representation of the given model.
The the columns represent the reactions and rows represent
metabolites. S[i,j] therefore contains the quantity of metabolite `i`
produced (negative for consumed) ... |
def nullspace(A, atol=1e-13, rtol=0):
"""Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value
decomposition of `A`.
Parameters
----------
A : numpy.ndarray
A should be at most 2-D. A 1-D array with length k will be trea... |
def constraint_matrices(model, array_type='dense', include_vars=False,
zero_tol=1e-6):
"""Create a matrix representation of the problem.
This is used for alternative solution approaches that do not use optlang.
The function will construct the equality matrix, inequality matrix and
... |
def room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
"""
Compute a single solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active
reactions needed to accommodate a previous reference solution.
Regulatory on/off... |
def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
r"""
Add constraints and objective for ROOM.
This function adds variables and constraints for applying regulatory
on/off minimization (ROOM) to the model.
Parameters
----------
model : cobra.Model
The mode... |
def sample(model, n, method="optgp", thinning=100, processes=1, seed=None):
"""Sample valid flux distributions from a cobra model.
The function samples valid flux distributions from a cobra model.
Currently we support two methods:
1. 'optgp' (default) which uses the OptGPSampler that supports parallel... |
def fastcc(model, flux_threshold=1.0, zero_cutoff=None):
r"""
Check consistency of a metabolic network using FASTCC [1]_.
FASTCC (Fast Consistency Check) is an algorithm for rapid and
efficient consistency check in metabolic networks. FASTCC is
a pure LP implementation and is low on computation res... |
def sample(self, n, fluxes=True):
"""Generate a set of samples.
This is the basic sampling function for all hit-and-run samplers.
Parameters
----------
n : int
The number of samples that are generated at once.
fluxes : boolean
Whether to return f... |
def optimizely(parser, token):
"""
Optimizely template tag.
Renders Javascript code to set-up A/B testing. You must supply
your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError(... |
def google_analytics(parser, token):
"""
Google Analytics tracking template tag.
Renders Javascript code to track page visits. You must supply
your website property ID (as a string) in the
``GOOGLE_ANALYTICS_PROPERTY_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
... |
def google_analytics_js(parser, token):
"""
Google Analytics tracking template tag.
Renders Javascript code to track page visits. You must supply
your website property ID (as a string) in the
``GOOGLE_ANALYTICS_JS_PROPERTY_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > ... |
def rating_mailru(parser, token):
"""
[email protected] counter template tag.
Renders Javascript code to track page visits. You must supply
your website counter ID (as a string) in the
``RATING_MAILRU_COUNTER_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise T... |
def clicky(parser, token):
"""
Clicky tracking template tag.
Renders Javascript code to track page visits. You must supply
your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' ta... |
def chartbeat_top(parser, token):
"""
Top Chartbeat template tag.
Render the top Javascript code for Chartbeat.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments" % bits[0])
return ChartbeatTopNode() |
def chartbeat_bottom(parser, token):
"""
Bottom Chartbeat template tag.
Render the bottom Javascript code for Chartbeat. You must supply
your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise Template... |
def woopra(parser, token):
"""
Woopra tracking template tag.
Renders Javascript code to track page visits. You must supply
your Woopra domain in the ``WOOPRA_DOMAIN`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments" % ... |
def spring_metrics(parser, token):
"""
Spring Metrics tracking template tag.
Renders Javascript code to track page visits. You must supply
your Spring Metrics Tracking ID in the
``SPRING_METRICS_TRACKING_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise Te... |
def kiss_insights(parser, token):
"""
KISSinsights set-up template tag.
Renders Javascript code to set-up surveys. You must supply
your account number and site code in the
``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``
settings.
"""
bits = token.split_contents()
i... |
def matomo(parser, token):
"""
Matomo tracking template tag.
Renders Javascript code to track page visits. You must supply
your Matomo domain (plus optional URI path), and tracked site ID
in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.
Custom variables can be passed in the `... |
def snapengage(parser, token):
"""
SnapEngage set-up template tag.
Renders Javascript code to set-up SnapEngage chat. You must supply
your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no... |
def performable(parser, token):
"""
Performable template tag.
Renders Javascript code to set-up Performable tracking. You must
supply your Performable API key in the ``PERFORMABLE_API_KEY``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("... |
def _timestamp(when):
"""
Python 2 compatibility for `datetime.timestamp()`.
"""
return (time.mktime(when.timetuple()) if sys.version_info < (3,) else
when.timestamp()) |
def _hashable_bytes(data):
"""
Coerce strings to hashable bytes.
"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('ascii') # Fail on anything non-ASCII.
else:
raise TypeError(data) |
def intercom_user_hash(data):
"""
Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.
Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
"""
if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):
return hmac.new(
key=_hashable_bytes(s... |
def intercom(parser, token):
"""
Intercom.io template tag.
Renders Javascript code to intercom.io testing. You must supply
your APP ID account number in the ``INTERCOM_APP_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no... |
def uservoice(parser, token):
"""
UserVoice tracking template tag.
Renders Javascript code to track page visits. You must supply
your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``
setting or the ``uservoice_widget_key`` template context variable.
"""
bits = token.split_contents()
... |
def kiss_metrics(parser, token):
"""
KISSinsights tracking template tag.
Renders Javascript code to track page visits. You must supply
your KISSmetrics API key in the ``KISS_METRICS_API_KEY``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError... |
def piwik(parser, token):
"""
Piwik tracking template tag.
Renders Javascript code to track page visits. You must supply
your Piwik domain (plus optional URI path), and tracked site ID
in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.
Custom variables can be passed in the ``piwi... |
def get_required_setting(setting, value_re, invalid_msg):
"""
Return a constant from ``django.conf.settings``. The `setting`
argument is the constant name, the `value_re` argument is a regular
expression used to validate the setting value and the `invalid_msg`
argument is used as exception message ... |
def get_user_from_context(context):
"""
Get the user instance from the template context, if possible.
If the context does not contain a `request` or `user` attribute,
`None` is returned.
"""
try:
return context['user']
except KeyError:
pass
try:
request = context... |
def get_identity(context, prefix=None, identity_func=None, user=None):
"""
Get the identity of a logged in user from a template context.
The `prefix` argument is used to provide different identities to
different analytics services. The `identity_func` argument is a
function that returns the identi... |
def get_domain(context, prefix):
"""
Return the domain used for the tracking code. Each service may be
configured with its own domain (called `<name>_domain`), or a
django-analytical-wide domain may be set (using `analytical_domain`.
If no explicit domain is found in either the context or the
... |
def is_internal_ip(context, prefix=None):
"""
Return whether the visitor is coming from an internal IP address,
based on information from the template context.
The prefix is used to allow different analytics services to have
different notions of internal addresses.
"""
try:
request ... |
def mixpanel(parser, token):
"""
Mixpanel tracking template tag.
Renders Javascript code to track page visits. You must supply
your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arg... |
def gosquared(parser, token):
"""
GoSquared tracking template tag.
Renders Javascript code to track page visits. You must supply
your GoSquared site token in the ``GOSQUARED_SITE_TOKEN`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' ta... |
def olark(parser, token):
"""
Olark set-up template tag.
Renders Javascript code to set-up Olark chat. You must supply
your site ID in the ``OLARK_SITE_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments" % bits[0])
... |
def clickmap(parser, token):
"""
Clickmap tracker template tag.
Renders Javascript code to track page visits. You must supply
your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxE... |
def gauges(parser, token):
"""
Gaug.es template tag.
Renders Javascript code to gaug.es testing. You must supply
your Site ID account number in the ``GAUGES_SITE_ID``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments... |
def crazy_egg(parser, token):
"""
Crazy Egg tracking template tag.
Renders Javascript code to track page clicks. You must supply
your Crazy Egg account number (as a string) in the
``CRAZY_EGG_ACCOUNT_NUMBER`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise Te... |
def yandex_metrica(parser, token):
"""
Yandex.Metrica counter template tag.
Renders Javascript code to track page visits. You must supply
your website counter ID (as a string) in the
``YANDEX_METRICA_COUNTER_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise... |
def hubspot(parser, token):
"""
HubSpot tracking template tag.
Renders Javascript code to track page visits. You must supply
your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes ... |
def status_printer():
"""Manage the printing and in-place updating of a line of characters
.. note::
If the string is longer than a line, then in-place updating may not
work (it will print a new line at each refresh).
"""
last_len = [0]
def p(s):
s = next(spinner) + ' ' + s... |
def get_or_guess_paths_to_mutate(paths_to_mutate):
"""
:type paths_to_mutate: str or None
:rtype: str
"""
if paths_to_mutate is None:
# Guess path with code
this_dir = os.getcwd().split(os.sep)[-1]
if isdir('lib'):
return 'lib'
elif isdir('src'):
... |
def do_apply(mutation_pk, dict_synonyms, backup):
"""Apply a specified mutant to the source code
:param mutation_pk: mutmut cache primary key of the mutant to apply
:type mutation_pk: str
:param dict_synonyms: list of synonym keywords for a python dictionary
:type dict_synonyms: list[str]
:pa... |
def climain(command, argument, argument2, paths_to_mutate, backup, runner, tests_dir,
test_time_multiplier, test_time_base,
swallow_output, use_coverage, dict_synonyms, cache_only, version,
suspicious_policy, untested_policy, pre_mutation, post_mutation,
use_patch_file):
... |
def main(command, argument, argument2, paths_to_mutate, backup, runner, tests_dir,
test_time_multiplier, test_time_base,
swallow_output, use_coverage, dict_synonyms, cache_only, version,
suspicious_policy, untested_policy, pre_mutation, post_mutation,
use_patch_file):
"""return e... |
def popen_streaming_output(cmd, callback, timeout=None):
"""Open a subprocess and stream its output without hard-blocking.
:param cmd: the command to execute within the subprocess
:type cmd: str
:param callback: function that intakes the subprocess' stdout line by line.
It is called for each l... |
def run_mutation(config, filename, mutation_id):
"""
:type config: Config
:type filename: str
:type mutation_id: MutationID
:return: (computed or cached) status of the tested mutant
:rtype: str
"""
context = Context(
mutation_id=mutation_id,
filename=filename,
exc... |
def read_coverage_data():
"""
:rtype: CoverageData or None
"""
print('Using coverage data from .coverage file')
# noinspection PyPackageRequirements,PyUnresolvedReferences
from coverage import Coverage
cov = Coverage('.coverage')
cov.load()
return cov.get_data() |
def add_mutations_by_file(mutations_by_file, filename, exclude, dict_synonyms):
"""
:type mutations_by_file: dict[str, list[MutationID]]
:type filename: str
:type exclude: Callable[[Context], bool]
:type dict_synonyms: list[str]
"""
with open(filename) as f:
source = f.read()
con... |
def python_source_files(path, tests_dirs):
"""Attempt to guess where the python source files to mutate are and yield
their paths
:param path: path to a python source file or package directory
:type path: str
:param tests_dirs: list of directory paths containing test files
(we do not want t... |
def compute_exit_code(config, exception=None):
"""Compute an exit code for mutmut mutation testing
The following exit codes are available for mutmut:
* 0 if all mutants were killed (OK_KILLED)
* 1 if a fatal error occurred
* 2 if one or more mutants survived (BAD_SURVIVED)
* 4 if one or mor... |
def argument_mutation(children, context, **_):
"""
:type context: Context
"""
if len(context.stack) >= 3 and context.stack[-3].type in ('power', 'atom_expr'):
stack_pos_of_power_node = -3
elif len(context.stack) >= 4 and context.stack[-4].type in ('power', 'atom_expr'):
stack_pos_of_... |
def mutate(context):
"""
:type context: Context
:return: tuple: mutated source code, number of mutations performed
:rtype: tuple[str, int]
"""
try:
result = parse(context.source, error_recovery=False)
except Exception:
print('Failed to parse %s. Internal error from parso foll... |
def mutate_node(node, context):
"""
:type context: Context
"""
context.stack.append(node)
try:
if node.type in ('tfpdef', 'import_from', 'import_name'):
return
if node.start_pos[0] - 1 != context.current_line_index:
context.current_line_index = node.start_pos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.