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 parse_exchange_table_file(f):
"""Parse a space-separated file containing exchange compound flux limits. The first two columns contain compound IDs and compartment while the third column contains the lower flux limits. The fourth column is optional and contains the upper flux limit. """
|
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# medium compounds), or both lower and upper limit.
fields = line.split(None)
if len(fields) < 2 or len(fields) > 4:
raise ParseError('Malformed compound limit: {}'.format(fields))
# Extend to four values and unpack
fields.extend(['-']*(4-len(fields)))
compound_id, compartment, lower, upper = fields
compound = Compound(compound_id, compartment)
lower = float(lower) if lower != '-' else None
upper = float(upper) if upper != '-' else None
yield compound, None, lower, upper
|
<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_exchange_file(path, default_compartment):
"""Parse a file as a list of exchange compounds with flux limits. The file format is detected and the file is parsed accordingly. Path can be given as a string or a context. """
|
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing exchange file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for entry in parse_exchange_table_file(f):
yield entry
elif format == 'yaml':
logger.debug('Parsing exchange file {} as YAML'.format(
context.filepath))
with context.open('r') as f:
for entry in parse_exchange_yaml_file(
context, f, default_compartment):
yield entry
else:
raise ParseError('Unable to detect format of exchange file {}'.format(
context.filepath))
|
<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_limit(limit_def):
"""Parse a structured flux limit definition as obtained from a YAML file Returns a tuple of reaction, lower and upper bound. """
|
lower, upper = get_limits(limit_def)
reaction = limit_def.get('reaction')
return reaction, lower, upper
|
<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_limits_list(path, limits):
"""Parse a structured list of flux limits as obtained from a YAML file Yields tuples of reaction ID, lower and upper flux bounds. Path can be given as a string or a context. """
|
context = FilePathContext(path)
for limit_def in limits:
if 'include' in limit_def:
include_context = context.resolve(limit_def['include'])
for limit in parse_limits_file(include_context):
yield limit
else:
yield parse_limit(limit_def)
|
<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_limits_table_file(f):
"""Parse a space-separated file containing reaction flux limits The first column contains reaction IDs while the second column contains the lower flux limits. The third column is optional and contains the upper flux limit. """
|
for line in f:
line, _, comment = line.partition('#')
line = line.strip()
if line == '':
continue
# A line can specify lower limit only (useful for
# exchange reactions), or both lower and upper limit.
fields = line.split(None)
if len(fields) < 1 or len(fields) > 3:
raise ParseError('Malformed reaction limit: {}'.format(fields))
# Extend to three values and unpack
fields.extend(['-']*(3-len(fields)))
reaction_id, lower, upper = fields
lower = float(lower) if lower != '-' else None
upper = float(upper) if upper != '-' else None
yield reaction_id, lower, upper
|
<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_limits_file(path):
"""Parse a file as a list of reaction flux limits The file format is detected and the file is parsed accordingly. Path can be given as a string or a context. """
|
context = FilePathContext(path)
format = resolve_format(None, context.filepath)
if format == 'tsv':
logger.debug('Parsing limits file {} as TSV'.format(
context.filepath))
with context.open('r') as f:
for limit in parse_limits_table_file(f):
yield limit
elif format == 'yaml':
logger.debug('Parsing limits file {} as YAML'.format(
context.filepath))
with context.open('r') as f:
for limit in parse_limits_yaml_file(context, f):
yield limit
else:
raise ParseError('Unable to detect format of limits file {}'.format(
context.filepath))
|
<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_model_group(path, group):
"""Parse a structured model group as obtained from a YAML file Path can be given as a string or a context. """
|
context = FilePathContext(path)
for reaction_id in group.get('reactions', []):
yield reaction_id
# Parse subgroups
for reaction_id in parse_model_group_list(
context, group.get('groups', [])):
yield reaction_id
|
<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_model_group_list(path, groups):
"""Parse a structured list of model groups as obtained from a YAML file Yields reaction IDs. Path can be given as a string or a context. """
|
context = FilePathContext(path)
for model_group in groups:
if 'include' in model_group:
include_context = context.resolve(model_group['include'])
for reaction_id in parse_model_file(include_context):
yield reaction_id
else:
for reaction_id in parse_model_group(context, model_group):
yield reaction_id
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reaction_representer(dumper, data):
"""Generate a parsable reaction representation to the YAML parser. Check the number of compounds in the reaction, if it is larger than 10, then transform the reaction data into a list of directories with all attributes in the reaction; otherwise, just return the text_type format of the reaction data. """
|
if len(data.compounds) > _MAX_REACTION_LENGTH:
def dict_make(compounds):
for compound, value in compounds:
yield OrderedDict([
('id', text_type(compound.name)),
('compartment', compound.compartment),
('value', value)])
left = list(dict_make(data.left))
right = list(dict_make(data.right))
direction = data.direction == Direction.Both
reaction = OrderedDict()
reaction['reversible'] = direction
if data.direction == Direction.Reverse:
reaction['left'] = right
reaction['right'] = left
else:
reaction['left'] = left
reaction['right'] = right
return dumper.represent_data(reaction)
else:
return _represent_text_type(dumper, text_type(data))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reader_from_path(cls, path):
"""Create a model from specified path. Path can be a directory containing a ``model.yaml`` or ``model.yml`` file or it can be a path naming the central model file directly. """
|
context = FilePathContext(path)
try:
with open(context.filepath, 'r') as f:
return ModelReader(f, context)
except IOError:
# Try to open the default file
for filename in cls.DEFAULT_MODEL:
try:
context = FilePathContext(
os.path.join(path, filename))
with open(context.filepath, 'r') as f:
return ModelReader(f, context)
except:
logger.debug('Failed to load model file',
exc_info=True)
# No model could be loaded
raise ParseError('No model file could be found ({})'.format(
', '.join(cls.DEFAULT_MODEL)))
|
<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_compartments(self):
"""Parse compartment information from model. Return tuple of: 1) iterator of :class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs defining the compartment boundaries of the model. """
|
compartments = OrderedDict()
boundaries = set()
if 'compartments' in self._model:
boundary_map = {}
for compartment_def in self._model['compartments']:
compartment_id = compartment_def.get('id')
_check_id(compartment_id, 'Compartment')
if compartment_id in compartments:
raise ParseError('Duplicate compartment ID: {}'.format(
compartment_id))
props = dict(compartment_def)
adjacent_to = props.pop('adjacent_to', None)
if adjacent_to is not None:
if not isinstance(adjacent_to, list):
adjacent_to = [adjacent_to]
for other in adjacent_to:
boundary_map.setdefault(other, set()).add(
compartment_id)
mark = FileMark(self._context, None, None)
compartment = CompartmentEntry(props, mark)
compartments[compartment_id] = compartment
# Check boundaries from boundary_map
for source, dest_set in iteritems(boundary_map):
if source not in compartments:
raise ParseError(
'Invalid compartment {} referenced'
' by compartment {}'.format(
source, ', '.join(dest_set)))
for dest in dest_set:
boundaries.add(tuple(sorted((source, dest))))
return itervalues(compartments), frozenset(boundaries)
|
<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_reactions(self):
"""Yield tuples of reaction ID and reactions defined in the model"""
|
# Parse reactions defined in the main model file
if 'reactions' in self._model:
for reaction in parse_reaction_list(
self._context, self._model['reactions'],
self.default_compartment):
yield reaction
|
<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_model(self):
"""Yield reaction IDs of model reactions"""
|
if self.has_model_definition():
for reaction_id in parse_model_group_list(
self._context, self._model['model']):
yield reaction_id
|
<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_limits(self):
"""Yield tuples of reaction ID, lower, and upper bound flux limits"""
|
if 'limits' in self._model:
if not isinstance(self._model['limits'], list):
raise ParseError('Expected limits to be a list')
for limit in parse_limits_list(
self._context, self._model['limits']):
yield limit
|
<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_exchange(self):
"""Yield tuples of exchange compounds. Each exchange compound is a tuple of compound, reaction ID, lower and upper flux limits. """
|
if 'media' in self._model:
if 'exchange' in self._model:
raise ParseError('Both "media" and "exchange" are specified')
logger.warning(
'The "media" key is deprecated! Please use "exchange" instead:'
' https://psamm.readthedocs.io/en/stable/file_format.html')
exchange_list = self._model['media']
else:
exchange_list = self._model.get('exchange')
extracellular = self.extracellular_compartment
if exchange_list is not None:
if not isinstance(exchange_list, list):
raise ParseError('Expected "exchange" to be a list')
for exchange_compound in parse_exchange_list(
self._context, exchange_list, extracellular):
compound, reaction_id, lower, upper = exchange_compound
if compound.compartment is None:
compound = compound.in_compartment(extracellular)
yield compound, reaction_id, lower, upper
|
<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_compounds(self):
"""Yield CompoundEntries for defined compounds"""
|
if 'compounds' in self._model:
for compound in parse_compound_list(
self._context, self._model['compounds']):
yield compound
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_compartment_entry(self, compartment, adjacencies):
"""Convert compartment entry to YAML dict. Args: compartment: :class:`psamm.datasource.entry.CompartmentEntry`. adjacencies: Sequence of IDs or a single ID of adjacent compartments (or None). """
|
d = OrderedDict()
d['id'] = compartment.id
if adjacencies is not None:
d['adjacent_to'] = adjacencies
order = {key: i for i, key in enumerate(['name'])}
prop_keys = set(compartment.properties)
for prop in sorted(prop_keys,
key=lambda x: (order.get(x, 1000), x)):
if compartment.properties[prop] is not None:
d[prop] = compartment.properties[prop]
return d
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_compound_entry(self, compound):
"""Convert compound entry to YAML dict."""
|
d = OrderedDict()
d['id'] = compound.id
order = {
key: i for i, key in enumerate(
['name', 'formula', 'formula_neutral', 'charge', 'kegg',
'cas'])}
prop_keys = (
set(compound.properties) - {'boundary', 'compartment'})
for prop in sorted(prop_keys,
key=lambda x: (order.get(x, 1000), x)):
if compound.properties[prop] is not None:
d[prop] = compound.properties[prop]
return d
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_reaction_entry(self, reaction):
"""Convert reaction entry to YAML dict."""
|
d = OrderedDict()
d['id'] = reaction.id
def is_equation_valid(equation):
# If the equation is a Reaction object, it must have non-zero
# number of compounds.
return (equation is not None and (
not isinstance(equation, Reaction) or
len(equation.compounds) > 0))
order = {
key: i for i, key in enumerate(
['name', 'genes', 'equation', 'subsystem', 'ec'])}
prop_keys = (set(reaction.properties) -
{'lower_flux', 'upper_flux', 'reversible'})
for prop in sorted(prop_keys, key=lambda x: (order.get(x, 1000), x)):
if reaction.properties[prop] is None:
continue
d[prop] = reaction.properties[prop]
if prop == 'equation' and not is_equation_valid(d[prop]):
del d[prop]
return d
|
<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_entries(self, stream, entries, converter, properties=None):
"""Write iterable of entries as YAML object to stream. Args: stream: File-like object. entries: Iterable of entries. converter: Conversion function from entry to YAML object. properties: Set of compartment properties to output (or None to output all). """
|
def iter_entries():
for c in entries:
entry = converter(c)
if entry is None:
continue
if properties is not None:
entry = OrderedDict(
(key, value) for key, value in iteritems(entry)
if key == 'id' or key in properties)
yield entry
self._dump(stream, list(iter_entries()))
|
<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_compartments(self, stream, compartments, adjacencies, properties=None):
"""Write iterable of compartments as YAML object to stream. Args: stream: File-like object. compartments: Iterable of compartment entries. adjacencies: Dictionary mapping IDs to adjacent compartment IDs. properties: Set of compartment properties to output (or None to output all). """
|
def convert(entry):
return self.convert_compartment_entry(
entry, adjacencies.get(entry.id))
self._write_entries(stream, compartments, convert, properties)
|
<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_compounds(self, stream, compounds, properties=None):
"""Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds: Iterable of compound entries. properties: Set of compound properties to output (or None to output all). """
|
self._write_entries(
stream, compounds, self.convert_compound_entry, properties)
|
<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_reactions(self, stream, reactions, properties=None):
"""Write iterable of reactions as YAML object to stream. Args: stream: File-like object. compounds: Iterable of reaction entries. properties: Set of reaction properties to output (or None to output all). """
|
self._write_entries(
stream, reactions, self.convert_reaction_entry, properties)
|
<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_api_errorhandler(**kwargs):
r"""Create an API error handler. E.g. register a 404 error: .. code-block:: python app.errorhandler(404)(create_api_errorhandler( status=404, message='Not Found')) :param \*\*kwargs: It contains the ``'status'`` and the ``'message'`` to describe the error. """
|
def api_errorhandler(e):
if isinstance(e, RESTException):
return e.get_response()
elif isinstance(e, HTTPException) and e.description:
kwargs['message'] = e.description
if kwargs.get('status', 400) >= 500 and hasattr(g, 'sentry_event_id'):
kwargs['error_id'] = str(g.sentry_event_id)
return make_response(jsonify(kwargs), kwargs['status'])
return api_errorhandler
|
<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_method_serializers(self, http_method):
"""Get request method serializers + default media type. Grab serializers from ``method_serializers`` if defined, otherwise returns the default serializers. Uses GET serializers for HEAD requests if no HEAD serializers were specified. The method also determines the default media type. :param http_method: HTTP method as a string. :returns: Tuple of serializers and default media type. """
|
if http_method == 'HEAD' and 'HEAD' not in self.method_serializers:
http_method = 'GET'
return (
self.method_serializers.get(http_method, self.serializers),
self.default_method_media_type.get(
http_method, self.default_media_type)
)
|
<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_serializers_by_query_arg(self, serializers):
"""Match serializer by query arg."""
|
# if the format query argument is present, match the serializer
arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')
if arg_name:
arg_value = request.args.get(arg_name, None)
if arg_value is None:
return None
# Search for the serializer matching the format
try:
return serializers[
self.serializers_query_aliases[arg_value]]
except KeyError: # either no serializer for this format
return None
return 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 _match_serializers_by_accept_headers(self, serializers, default_media_type):
"""Match serializer by `Accept` headers."""
|
# Bail out fast if no accept headers were given.
if len(request.accept_mimetypes) == 0:
return serializers[default_media_type]
# Determine best match based on quality.
best_quality = -1
best = None
has_wildcard = False
for client_accept, quality in request.accept_mimetypes:
if quality <= best_quality:
continue
if client_accept == '*/*':
has_wildcard = True
for s in serializers:
if s in ['*/*', client_accept] and quality > 0:
best_quality = quality
best = s
# If no match found, but wildcard exists, them use default media
# type.
if best is None and has_wildcard:
best = default_media_type
if best is not None:
return serializers[best]
return 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 match_serializers(self, serializers, default_media_type):
"""Choose serializer for a given request based on query arg or headers. Checks if query arg `format` (by default) is present and tries to match the serializer based on the arg value, by resolving the mimetype mapped to the arg value. Otherwise, chooses the serializer by retrieving the best quality `Accept` headers and matching its value (mimetype). :param serializers: Dictionary of serializers. :param default_media_type: The default media type. :returns: Best matching serializer based on `format` query arg first, then client `Accept` headers or None if no matching serializer. """
|
return self._match_serializers_by_query_arg(serializers) or self.\
_match_serializers_by_accept_headers(serializers,
default_media_type)
|
<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_response(self, *args, **kwargs):
"""Create a Flask Response. Dispatch the given arguments to the serializer best matching the current request's Accept header. :return: The response created by the serializing function. :rtype: :class:`flask.Response` :raises werkzeug.exceptions.NotAcceptable: If no media type matches current Accept header. """
|
serializer = self.match_serializers(
*self.get_method_serializers(request.method))
if serializer:
return serializer(*args, **kwargs)
abort(406)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch_request(self, *args, **kwargs):
"""Dispatch current request. Dispatch the current request using :class:`flask.views.MethodView` `dispatch_request()` then, if the result is not already a :py:class:`flask.Response`, search for the serializing function which matches the best the current request's Accept header and use it to build the :py:class:`flask.Response`. :rtype: :class:`flask.Response` :raises werkzeug.exceptions.NotAcceptable: If no media type matches current Accept header. :returns: The response returned by the request handler or created by the serializing function. """
|
result = super(ContentNegotiatedMethodView, self).dispatch_request(
*args, **kwargs
)
if isinstance(result, Response):
return result
elif isinstance(result, (list, tuple)):
return self.make_response(*result)
else:
return self.make_response(result)
|
<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_etag(self, etag, weak=False):
"""Validate the given ETag with current request conditions. Compare the given ETag to the ones in the request header If-Match and If-None-Match conditions. The result is unspecified for requests having If-Match and If-None-Match being both set. :param str etag: The ETag of the current resource. For PUT and PATCH it is the one before any modification of the resource. This ETag will be tested with the Accept header conditions. The given ETag should not be quoted. :raises werkzeug.exceptions.PreconditionFailed: If the condition is not met. :raises invenio_rest.errors.SameContentException: If the the request is GET or HEAD and the If-None-Match condition is not met. """
|
# bool(:py:class:`werkzeug.datastructures.ETags`) is not consistent
# in Python 3. bool(Etags()) == True even though it is empty.
if len(request.if_match.as_set(include_weak=weak)) > 0 or \
request.if_match.star_tag:
contains_etag = (request.if_match.contains_weak(etag) if weak
else request.if_match.contains(etag))
if not contains_etag and '*' not in request.if_match:
abort(412)
if len(request.if_none_match.as_set(include_weak=weak)) > 0 or \
request.if_none_match.star_tag:
contains_etag = (request.if_none_match.contains_weak(etag) if weak
else request.if_none_match.contains(etag))
if contains_etag or '*' in request.if_none_match:
if request.method in ('GET', 'HEAD'):
raise SameContentException(etag)
else:
abort(412)
|
<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_if_modified_since(self, dt, etag=None):
"""Validate If-Modified-Since with current request conditions."""
|
dt = dt.replace(microsecond=0)
if request.if_modified_since and dt <= request.if_modified_since:
raise SameContentException(etag, last_modified=dt)
|
<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_default_compartment(model):
"""Return what the default compartment should be set to. If some compounds have no compartment, unique compartment name is returned to avoid collisions. """
|
default_compartment = 'c'
default_key = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
default_key.add(compound.compartment)
if None in default_key and default_compartment in default_key:
suffix = 1
while True:
new_key = '{}_{}'.format(default_compartment, suffix)
if new_key not in default_key:
default_compartment = new_key
break
suffix += 1
if None in default_key:
logger.warning(
'Compound(s) found without compartment, default'
' compartment is set to {}.'.format(default_compartment))
return default_compartment
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_best_flux_limit(model):
"""Detect the best default flux limit to use for model output. The default flux limit does not change the model but selecting a good value reduced the amount of output produced and reduces clutter in the output files. """
|
flux_limit_count = Counter()
for reaction in model.reactions:
if reaction.id not in model.limits:
continue
equation = reaction.properties['equation']
if equation is None:
continue
_, lower, upper = model.limits[reaction.id]
if upper is not None and upper > 0 and equation.direction.forward:
flux_limit_count[upper] += 1
if lower is not None and -lower > 0 and equation.direction.reverse:
flux_limit_count[-lower] += 1
if len(flux_limit_count) == 0:
return None
best_flux_limit, _ = flux_limit_count.most_common(1)[0]
return best_flux_limit
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files. If a subsystem has a number of reactions over the threshold, it gets its own YAML file. All other reactions, those that don't have a subsystem or are in a subsystem that falls below the threshold, get added to a common reaction file. Args: model: :class:`psamm_import.model.MetabolicModel`. dest: output path for model files. writer: :class:`psamm.datasource.native.ModelWriter`. split_subsystem: Divide reactions into multiple files by subsystem. """
|
def safe_file_name(origin_name):
safe_name = re.sub(
r'\W+', '_', origin_name, flags=re.UNICODE)
safe_name = re.sub(
r'_+', '_', safe_name.lower(), flags=re.UNICODE)
safe_name = safe_name.strip('_')
return safe_name
common_reactions = []
reaction_files = []
if not split_subsystem:
common_reactions = sorted(model.reactions, key=lambda r: r.id)
if len(common_reactions) > 0:
reaction_file = 'reactions.yaml'
with open(os.path.join(dest, reaction_file), 'w') as f:
writer.write_reactions(f, common_reactions)
reaction_files.append(reaction_file)
else:
subsystems = {}
for reaction in sorted(model.reactions, key=lambda r: r.id):
if 'subsystem' in reaction.properties:
subsystem_file = safe_file_name(
reaction.properties['subsystem'])
subsystems.setdefault(subsystem_file, []).append(reaction)
else:
common_reactions.append(reaction)
subsystem_folder = 'reactions'
sub_existance = False
for subsystem_file, reactions in iteritems(subsystems):
if len(reactions) < _MAX_REACTION_COUNT:
for reaction in reactions:
common_reactions.append(reaction)
else:
if len(reactions) > 0:
mkdir_p(os.path.join(dest, subsystem_folder))
subsystem_file = os.path.join(
subsystem_folder, '{}.yaml'.format(subsystem_file))
with open(os.path.join(dest, subsystem_file), 'w') as f:
writer.write_reactions(f, reactions)
reaction_files.append(subsystem_file)
sub_existance = True
reaction_files.sort()
if sub_existance:
reaction_file = os.path.join(
subsystem_folder, 'other_reactions.yaml')
else:
reaction_file = 'reactions.yaml'
if len(common_reactions) > 0:
with open(os.path.join(dest, reaction_file), 'w') as f:
writer.write_reactions(f, common_reactions)
reaction_files.append(reaction_file)
return reaction_files
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_limit_items(lower, upper):
"""Yield key, value pairs for limits dictionary. Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``. A key, value pair is emitted if the bounds are not None. """
|
# Use value + 0 to convert any -0.0 to 0.0 which looks better.
if lower is not None and upper is not None and lower == upper:
yield 'fixed', upper + 0
else:
if lower is not None:
yield 'lower', lower + 0
if upper is not None:
yield 'upper', upper + 0
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_exchange(model):
"""Return exchange definition as YAML dict."""
|
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
lower_default = -model.default_flux_limit
upper_default = model.default_flux_limit
compounds = []
for compound, reaction_id, lower, upper in sorted(
itervalues(model.exchange)):
d = OrderedDict([('id', compound.name)])
if reaction_id is not None:
d['reaction'] = reaction_id
lower = _get_output_limit(lower, lower_default)
upper = _get_output_limit(upper, upper_default)
d.update(_generate_limit_items(lower, upper))
compounds.append(d)
return OrderedDict([('compounds', compounds)])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_reaction_limits(model):
"""Yield model reaction limits as YAML dicts."""
|
for reaction in sorted(model.reactions, key=lambda r: r.id):
equation = reaction.properties.get('equation')
if equation is None:
continue
# Determine the default flux limits. If the value is already at the
# default it does not need to be included in the output.
lower_default, upper_default = None, None
if model.default_flux_limit is not None:
if equation.direction.reverse:
lower_default = -model.default_flux_limit
else:
lower_default = 0.0
if equation.direction.forward:
upper_default = model.default_flux_limit
else:
upper_default = 0.0
lower_flux, upper_flux = None, None
if reaction.id in model.limits:
_, lower, upper = model.limits[reaction.id]
lower_flux = _get_output_limit(lower, lower_default)
upper_flux = _get_output_limit(upper, upper_default)
if lower_flux is not None or upper_flux is not None:
d = OrderedDict([('reaction', reaction.id)])
d.update(_generate_limit_items(lower_flux, upper_flux))
yield d
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_compartment_entries(model):
"""Infer compartment entries for model based on reaction compounds."""
|
compartment_ids = set()
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
for compound, _ in equation.compounds:
compartment = compound.compartment
if compartment is None:
compartment = model.default_compartment
if compartment is not None:
compartment_ids.add(compartment)
for compartment in compartment_ids:
if compartment in model.compartments:
continue
entry = DictCompartmentEntry(dict(id=compartment))
model.compartments.add_entry(entry)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_compartment_adjacency(model):
"""Infer compartment adjacency for model based on reactions."""
|
def reaction_compartments(seq):
for compound, _ in seq:
compartment = compound.compartment
if compartment is None:
compartment = model.default_compartment
if compartment is not None:
yield compartment
for reaction in model.reactions:
equation = reaction.equation
if equation is None:
continue
left = reaction_compartments(equation.left)
right = reaction_compartments(equation.right)
for c1, c2 in product(left, right):
if c1 == c2:
continue
model.compartment_boundaries.add((c1, c2))
model.compartment_boundaries.add((c2, c1))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_genes(model):
"""Count the number of distinct genes in model reactions."""
|
genes = set()
for reaction in model.reactions:
if reaction.genes is None:
continue
if isinstance(reaction.genes, boolean.Expression):
genes.update(v.symbol for v in reaction.genes.variables)
else:
genes.update(reaction.genes)
return len(genes)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_formula(self, compound_id, s):
"""Try to parse the given compound formula string. Logs a warning if the formula could not be parsed. """
|
s = s.strip()
if s == '':
return None
try:
# Do not return the parsed formula. For now it is better to keep
# the original formula string unchanged in all cases.
formula.Formula.parse(s)
except formula.ParseError:
logger.warning('Unable to parse compound formula {}: {}'.format(
compound_id, s))
return s
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_reaction(self, reaction_id, s, parser=parse_reaction, **kwargs):
"""Try to parse the given reaction equation string. Returns the parsed Reaction object, or raises an error if the reaction could not be parsed. """
|
try:
return parser(s, **kwargs)
except ReactionParseError as e:
if e.indicator is not None:
logger.error('{}\n{}\n{}'.format(
str(e), s, e.indicator))
raise ParseError('Unable to parse reaction {}: {}'.format(
reaction_id, s))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _try_parse_gene_association(self, reaction_id, s):
"""Try to parse the given gene association rule. Logs a warning if the association rule could not be parsed and returns the original string. Otherwise, returns the boolean.Expression object. """
|
s = s.strip()
if s == '':
return None
try:
return boolean.Expression(s)
except boolean.ParseError as e:
msg = 'Failed to parse gene association for {}: {}'.format(
reaction_id, text_type(e))
if e.indicator is not None:
msg += '\n{}\n{}'.format(s, e.indicator)
logger.warning(msg)
return s
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_content_types(*allowed_content_types):
r"""Decorator to test if proper Content-Type is provided. :param \*allowed_content_types: List of allowed content types. :raises invenio_rest.errors.InvalidContentType: It's rised if a content type not allowed is required. """
|
def decorator(f):
@wraps(f)
def inner(*args, **kwargs):
if request.mimetype not in allowed_content_types:
raise InvalidContentType(allowed_content_types)
return f(*args, **kwargs)
return inner
return decorator
|
<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_connection(self, *args, **kwargs):
""" Create a new connection, or return an existing one from the cache. Uses Fabric's current ``env.host_string`` and the URL to the Docker service. :param args: Additional arguments for the client constructor, if a new client has to be instantiated. :param kwargs: Additional keyword args for the client constructor, if a new client has to be instantiated. """
|
key = env.get('host_string'), kwargs.get('base_url', env.get('docker_base_url'))
default_config = _get_default_config(None)
if default_config:
if key not in self:
self[key] = default_config
return default_config.get_client()
config = self.get_or_create_connection(key, self.configuration_class, *args, **kwargs)
return config.get_client()
|
<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_solvers(solvers, requirements):
"""Yield solvers that fullfil the requirements."""
|
for solver in solvers:
for req, value in iteritems(requirements):
if (req in ('integer', 'quadratic', 'rational', 'name') and
(req not in solver or solver[req] != value)):
break
else:
yield solver
|
<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_solver_setting(s):
"""Parse a string containing a solver setting"""
|
try:
key, value = s.split('=', 1)
except ValueError:
key, value = s, 'yes'
if key in ('rational', 'integer', 'quadratic'):
value = value.lower() in ('1', 'yes', 'true', 'on')
elif key in ('threads',):
value = int(value)
elif key in ('feasibility_tolerance', 'optimality_tolerance',
'integrality_tolerance'):
value = float(value)
return key, value
|
<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_reaction_values(self, reaction_id):
"""Return stoichiometric values of reaction as a dictionary"""
|
if reaction_id not in self._reaction_set:
raise ValueError('Unknown reaction: {}'.format(repr(reaction_id)))
return self._database.get_reaction_values(reaction_id)
|
<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_compound_reactions(self, compound_id):
"""Iterate over all reaction ids the includes the given compound"""
|
if compound_id not in self._compound_set:
raise ValueError('Compound not in model: {}'.format(compound_id))
for reaction_id in self._database.get_compound_reactions(compound_id):
if reaction_id in self._reaction_set:
yield reaction_id
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_reversible(self, reaction_id):
"""Whether the given reaction is reversible"""
|
if reaction_id not in self._reaction_set:
raise ValueError('Reaction not in model: {}'.format(reaction_id))
return self._database.is_reversible(reaction_id)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_exchange(self, reaction_id):
"""Whether the given reaction is an exchange reaction."""
|
reaction = self.get_reaction(reaction_id)
return (len(reaction.left) == 0) != (len(reaction.right) == 0)
|
<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_reaction(self, reaction_id):
"""Add reaction to model"""
|
if reaction_id in self._reaction_set:
return
reaction = self._database.get_reaction(reaction_id)
self._reaction_set.add(reaction_id)
for compound, _ in reaction.compounds:
self._compound_set.add(compound)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_reaction(self, reaction):
"""Remove reaction from model"""
|
if reaction not in self._reaction_set:
return
self._reaction_set.remove(reaction)
self._limits_lower.pop(reaction, None)
self._limits_upper.pop(reaction, None)
# Remove compound from compound_set if it is not referenced
# by any other reactions in the model.
for compound, value in self._database.get_reaction_values(reaction):
reactions = frozenset(
self._database.get_compound_reactions(compound))
if all(other_reaction not in self._reaction_set
for other_reaction in reactions):
self._compound_set.remove(compound)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Return copy of model"""
|
model = self.__class__(self._database)
model._limits_lower = dict(self._limits_lower)
model._limits_upper = dict(self._limits_upper)
model._reaction_set = set(self._reaction_set)
model._compound_set = set(self._compound_set)
return model
|
<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_model(cls, database, reaction_iter=None, exchange=None, limits=None, v_max=None):
"""Get model from reaction name iterator. The model will contain all reactions of the iterator. """
|
model_args = {}
if v_max is not None:
model_args['v_max'] = v_max
model = cls(database, **model_args)
if reaction_iter is None:
reaction_iter = iter(database.reactions)
for reaction_id in reaction_iter:
model.add_reaction(reaction_id)
# Apply reaction limits
if limits is not None:
for reaction_id, lower, upper in limits:
if lower is not None:
model.limits[reaction_id].lower = lower
if upper is not None:
model.limits[reaction_id].upper = upper
# TODO: Currently we just create a new exchange reaction in the
# database and add it to the model. Ideally, we should not modify
# the database. The exchange reaction could be created on the
# fly when required.
if exchange is not None:
for compound, reaction_id, lower, upper in exchange:
# Create exchange reaction
if reaction_id is None:
reaction_id = create_exchange_id(
model.database.reactions, compound)
model.database.set_reaction(
reaction_id, Reaction(Direction.Both, {compound: -1}))
model.add_reaction(reaction_id)
if lower is not None:
model.limits[reaction_id].lower = lower
if upper is not None:
model.limits[reaction_id].upper = upper
return model
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run flux analysis command."""
|
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Reaction genes information
def reaction_genes_string(id):
if id not in self._model.reactions:
return ''
return self._model.reactions[id].properties.get('genes', '')
reaction = self._get_objective()
if not self._mm.has_reaction(reaction):
self.fail(
'Specified reaction is not in model: {}'.format(reaction))
loop_removal = self._get_loop_removal_option()
if loop_removal == 'none':
result = self.run_fba(reaction)
elif loop_removal == 'l1min':
result = self.run_fba_minimized(reaction)
elif loop_removal == 'tfba':
result = self.run_tfba(reaction)
optimum = None
total_reactions = 0
nonzero_reactions = 0
for reaction_id, flux in sorted(result):
total_reactions += 1
if abs(flux) > self._args.epsilon:
nonzero_reactions += 1
if abs(flux) > self._args.epsilon or self._args.all_reactions:
rx = self._mm.get_reaction(reaction_id)
rx_trans = rx.translated_compounds(compound_name)
genes = reaction_genes_string(reaction_id)
print('{}\t{}\t{}\t{}'.format(
reaction_id, flux, rx_trans, genes))
# Remember flux of requested reaction
if reaction_id == reaction:
optimum = flux
logger.info('Objective flux: {}'.format(optimum))
logger.info('Reactions at zero flux: {}/{}'.format(
total_reactions - nonzero_reactions, total_reactions))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_fba_minimized(self, reaction):
"""Run normal FBA and flux minimization on model."""
|
epsilon = self._args.epsilon
solver = self._get_solver()
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
# Maximize reaction flux
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
self.report_flux_balance_error(e)
fluxes = {r: p.get_flux(r) for r in self._mm.reactions}
# Run flux minimization
flux_var = p.get_flux_var(reaction)
p.prob.add_linear_constraints(flux_var == p.get_flux(reaction))
p.minimize_l1()
logger.info('Solving took {:.2f} seconds'.format(
time.time() - start_time))
count = 0
for reaction_id in self._mm.reactions:
flux = p.get_flux(reaction_id)
if abs(flux - fluxes[reaction_id]) > epsilon:
count += 1
yield reaction_id, flux
logger.info('Minimized reactions: {}'.format(count))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_tfba(self, reaction):
"""Run FBA and tFBA on model."""
|
solver = self._get_solver(integer=True)
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
p.add_thermodynamic()
try:
p.maximize(reaction)
except fluxanalysis.FluxBalanceError as e:
self.report_flux_balance_error(e)
logger.info('Solving took {:.2f} seconds'.format(
time.time() - start_time))
for reaction_id in self._mm.reactions:
yield reaction_id, p.get_flux(reaction_id)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_consistent(database, solver, exchange=set(), zeromass=set()):
"""Try to assign a positive mass to each compound Return True if successful. The masses are simply constrained by m_i > 1 and finding a solution under these conditions proves that the database is mass consistent. """
|
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
prob.set_objective(m.sum(mass_compounds))
# Define constraints
massbalance_lhs = {reaction: 0 for reaction in database.reactions}
for (compound, reaction), value in iteritems(database.matrix):
if compound not in zeromass:
mass = m(compound.in_compartment(None))
massbalance_lhs[reaction] += mass * value
for reaction, lhs in iteritems(massbalance_lhs):
if reaction not in exchange:
prob.add_linear_constraints(lhs == 0)
result = prob.solve_unchecked(lp.ObjectiveSense.Minimize)
return result.success
|
<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_reaction_consistency(database, solver, exchange=set(), checked=set(), zeromass=set(), weights={}):
"""Check inconsistent reactions by minimizing mass residuals Return a reaction iterable, and compound iterable. The reaction iterable yields reaction ids and mass residuals. The compound iterable yields compound ids and mass assignments. Each compound is assigned a mass of at least one, and the masses are balanced using the stoichiometric matrix. In addition, each reaction has a residual mass that is included in the mass balance equations. The L1-norm of the residuals is minimized. Reactions in the checked set are assumed to have been manually checked and therefore have the residual fixed at zero. """
|
# Create Flux balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=1)
# Define residual mass variables and objective constriants
z = prob.namespace(database.reactions, lower=0)
r = prob.namespace(database.reactions)
objective = z.expr((reaction_id, weights.get(reaction_id, 1))
for reaction_id in database.reactions)
prob.set_objective(objective)
rs = r.set(database.reactions)
zs = z.set(database.reactions)
prob.add_linear_constraints(zs >= rs, rs >= -zs)
massbalance_lhs = {reaction_id: 0 for reaction_id in database.reactions}
for (compound, reaction_id), value in iteritems(database.matrix):
if compound not in zeromass:
mass_var = m(compound.in_compartment(None))
massbalance_lhs[reaction_id] += mass_var * value
for reaction_id, lhs in iteritems(massbalance_lhs):
if reaction_id not in exchange:
if reaction_id not in checked:
prob.add_linear_constraints(lhs + r(reaction_id) == 0)
else:
prob.add_linear_constraints(lhs == 0)
# Solve
try:
prob.solve(lp.ObjectiveSense.Minimize)
except lp.SolverError as e:
raise_from(
MassConsistencyError('Failed to solve mass consistency: {}'.format(
e)), e)
def iterate_reactions():
for reaction_id in database.reactions:
residual = r.value(reaction_id)
yield reaction_id, residual
def iterate_compounds():
for compound in mass_compounds:
yield compound, m.value(compound)
return iterate_reactions(), iterate_compounds()
|
<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_compound_consistency(database, solver, exchange=set(), zeromass=set()):
"""Yield each compound in the database with assigned mass Each compound will be assigned a mass and the number of compounds having a positive mass will be approximately maximized. This is an implementation of the solution originally proposed by [Gevorgyan08]_ but using the new method proposed by [Thiele14]_ to avoid MILP constraints. This is similar to the way Fastcore avoids MILP contraints. """
|
# Create mass balance problem
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
# Define mass variables
m = prob.namespace(mass_compounds, lower=0)
# Define z variables
z = prob.namespace(mass_compounds, lower=0, upper=1)
prob.set_objective(z.sum(mass_compounds))
prob.add_linear_constraints(m.set(mass_compounds) >= z.set(mass_compounds))
massbalance_lhs = {reaction_id: 0 for reaction_id in database.reactions}
for (compound, reaction_id), value in iteritems(database.matrix):
if compound not in zeromass:
mass_var = m(compound.in_compartment(None))
massbalance_lhs[reaction_id] += mass_var * value
for reaction_id, lhs in iteritems(massbalance_lhs):
if reaction_id not in exchange:
prob.add_linear_constraints(lhs == 0)
# Solve
try:
prob.solve(lp.ObjectiveSense.Maximize)
except lp.SolverError as e:
raise_from(
MassConsistencyError('Failed to solve mass consistency: {}'.format(
e)), e)
for compound in mass_compounds:
yield compound, m.value(compound)
|
<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_unique_id(prefix, existing_ids):
"""Return a unique string ID from the prefix. First check if the prefix is itself a unique ID in the set-like parameter existing_ids. If not, try integers in ascending order appended to the prefix until a unique ID is found. """
|
if prefix in existing_ids:
suffix = 1
while True:
new_id = '{}_{}'.format(prefix, suffix)
if new_id not in existing_ids:
return new_id
suffix += 1
return prefix
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def git_try_describe(repo_path):
"""Try to describe the current commit of a Git repository. Return a string containing a string with the commit ID and/or a base tag, if successful. Otherwise, return None. """
|
try:
p = subprocess.Popen(['git', 'describe', '--always', '--dirty'],
cwd=repo_path, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, _ = p.communicate()
except:
return None
else:
if p.returncode == 0:
return output.strip()
return 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 convex_cardinality_relaxed(f, epsilon=1e-5):
"""Transform L1-norm optimization function into cardinality optimization. The given function must optimize a convex problem with a weighted L1-norm as the objective. The transformed function will apply the iterated weighted L1 heuristic to approximately optimize the cardinality of the solution. This method is described by S. Boyd, "L1-norm norm methods for convex cardinality problems." Lecture Notes for EE364b, Stanford University, 2007. Available online at www.stanford.edu/class/ee364b/. The given function must take an optional keyword parameter weights (dictionary), and the weights must be set to one if not specified. The function must return the non-weighted solution as an iterator over (identifier, value)-tuples, either directly or as the first element of a tuple. """
|
def convex_cardinality_wrapper(*args, **kwargs):
def dict_result(r):
if isinstance(r, tuple):
return dict(r[0])
return dict(r)
# Initial run with default weights
full_result = f(*args, **kwargs)
result = dict_result(full_result)
def update_weight(value):
return 1/(epsilon + abs(value))
# Iterate until the difference from one iteration to
# the next is less than epsilon.
while True:
weights = {identifier: update_weight(value)
for identifier, value in iteritems(result)}
kwargs['weights'] = weights
last_result = result
full_result = f(*args, **kwargs)
result = dict_result(full_result)
delta = math.sqrt(sum(pow(value - last_result[identifier], 2)
for identifier, value in iteritems(result)))
if delta < epsilon:
break
if isinstance(full_result, tuple):
return (iteritems(result),) + full_result[1:]
return iteritems(result)
return convex_cardinality_wrapper
|
<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(self, s):
"""Write message to logger."""
|
for line in re.split(r'\n+', s):
if line != '':
self._logger.log(self._level, 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 fullname(self):
"""Returns the name of the ``Record`` class this ``Property`` is attached to, and attribute name it is attached as."""
|
if not self.bound:
if self.name is not None:
return "(unbound).%s" % self.name
else:
return "(unbound)"
elif not self.class_():
classname = "(GC'd class)"
else:
classname = self.class_().__name__
return "%s.%s" % (classname, self.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 run(self):
"""Run robustness command."""
|
reaction = self._get_objective()
if not self._mm.has_reaction(reaction):
self.fail('Specified biomass reaction is not in model: {}'.format(
reaction))
varying_reaction = self._args.varying
if not self._mm.has_reaction(varying_reaction):
self.fail('Specified varying reaction is not in model: {}'.format(
varying_reaction))
steps = self._args.steps
if steps <= 0:
self.argument_error('Invalid number of steps: {}\n'.format(steps))
loop_removal = self._get_loop_removal_option()
if loop_removal == 'tfba':
solver = self._get_solver(integer=True)
else:
solver = self._get_solver()
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
if loop_removal == 'tfba':
p.add_thermodynamic()
try:
p.check_constraints()
except fluxanalysis.FluxBalanceError as e:
self.report_flux_balance_error(e)
# Determine minimum and maximum flux for varying reaction
if self._args.maximum is None:
p.maximize(varying_reaction)
flux_max = p.get_flux(varying_reaction)
else:
flux_max = self._args.maximum
if self._args.minimum is None:
p.maximize({varying_reaction: -1})
flux_min = p.get_flux(varying_reaction)
else:
flux_min = self._args.minimum
if flux_min > flux_max:
self.argument_error('Invalid flux range: {}, {}\n'.format(
flux_min, flux_max))
logger.info('Varying {} in {} steps between {} and {}'.format(
varying_reaction, steps, flux_min, flux_max))
start_time = time.time()
handler_args = (
self._mm, solver, loop_removal, self._args.all_reaction_fluxes)
executor = self._create_executor(
RobustnessTaskHandler, handler_args, cpus_per_worker=2)
def iter_tasks():
for i in range(steps):
fixed_flux = flux_min + i*(flux_max - flux_min)/float(steps-1)
constraint = varying_reaction, fixed_flux
yield constraint, reaction
# Run FBA on model at different fixed flux values
with executor:
for task, result in executor.imap_unordered(iter_tasks(), 16):
(varying_reaction, fixed_flux), _ = task
if result is None:
logger.warning('No solution found for {} at {}'.format(
varying_reaction, fixed_flux))
elif self._args.all_reaction_fluxes:
for other_reaction in self._mm.reactions:
print('{}\t{}\t{}'.format(
other_reaction, fixed_flux,
result[other_reaction]))
else:
print('{}\t{}'.format(fixed_flux, result))
executor.join()
logger.info('Solving took {:.2f} seconds'.format(
time.time() - start_time))
|
<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_objective(self, expression):
"""Set objective of problem."""
|
if isinstance(expression, numbers.Number):
# Allow expressions with no variables as objective,
# represented as a number
expression = Expression(offset=expression)
# Clear previous objective
for i in range(swiglpk.glp_get_num_cols(self._p)):
swiglpk.glp_set_obj_coef(self._p, 1 + i, 0)
for variable, value in expression.values():
var_index = self._variables[variable]
swiglpk.glp_set_obj_coef(self._p, var_index, float(value))
swiglpk.glp_set_obj_coef(self._p, 0, float(expression.offset))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self):
"""Return string indicating the error encountered on failure."""
|
self._check_valid()
if self._ret_val == swiglpk.GLP_ENOPFS:
return 'No primal feasible solution'
elif self._ret_val == swiglpk.GLP_ENODFS:
return 'No dual feasible solution'
return str(swiglpk.glp_get_status(self._problem._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 default_weight(element):
"""Return weight of formula element. This implements the default weight proposed for MapMaker. """
|
if element in (Atom.N, Atom.O, Atom.P):
return 0.4
elif isinstance(element, Radical):
return 40.0
return 1.0
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _weighted_formula(form, weight_func):
"""Yield weight of each formula element."""
|
for e, mf in form.items():
if e == Atom.H:
continue
yield e, mf, weight_func(e)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transfers(reaction, delta, elements, result, epsilon):
"""Yield transfers obtained from result."""
|
left = set(c for c, _ in reaction.left)
right = set(c for c, _ in reaction.right)
for c1, c2 in product(left, right):
items = {}
for e in elements:
v = result.get_value(delta[c1, c2, e])
nearest_int = round(v)
if abs(v - nearest_int) < epsilon:
v = int(nearest_int)
if v >= epsilon:
items[e] = v
if len(items) > 0:
yield (c1, c2), Formula(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 _make_generic(of, coll):
"""Used to make a new Collection type, without that type having to be defined explicitly. Generates a new type name using the item type and a 'suffix' Collection class property. args: ``of=``\ *Record type* The type of values of the collection ``coll=``\ *Collection sub-class* The container class. """
|
assert(issubclass(coll, Collection))
key = (coll.__name__, "%s.%s" % (of.__module__, of.__name__))
if key in GENERIC_TYPES:
if GENERIC_TYPES[key].itemtype != of:
raise exc.PropertyNotUnique(key=key)
else:
# oh, we get to name it? Goodie!
generic_name = "%s%s" % (of.__name__, coll.suffix)
GENERIC_TYPES[key] = type(
generic_name, (coll, _Generic), dict(itemtype=of, generic_key=key)
)
mod = sys.modules[of.__module__]
if not hasattr(mod, generic_name):
setattr(mod, generic_name, GENERIC_TYPES[key])
return GENERIC_TYPES[key]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce_value(cls, v):
"""Coerce a value to the right type for the collection, or return it if it is already of the right type."""
|
if isinstance(v, cls.itemtype):
return v
else:
try:
return cls.coerceitem(v)
except Exception as e:
raise exc.CollectionItemCoerceError(
itemtype=cls.itemtype,
colltype=cls,
passed=v,
exc=e,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend(self, iterable):
"""Adds new values to the end of the collection, coercing items. """
|
# perhaps: self[len(self):len(self)] = iterable
self._values.extend(self.coerce_value(item) for item in iterable)
|
<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_response(self, connection, command_name, **options):
""" Parses a response from the ssdb server """
|
response = connection.read_response()
if command_name in self.response_callbacks and len(response):
status = nativestr(response[0])
if status == RES_STATUS.OK:
return self.response_callbacks[command_name](response[1:],
**options)
elif status == RES_STATUS.NOT_FOUND:
return None
else:
raise DataError(RES_STATUS_MSG[status]+':'.join(response))
#raise DataError('Not Found')
return response
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def incr(self, name, amount=1):
""" Increase the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` . Like **Redis.INCR** :param string name: the key name :param int amount: increments :return: the integer value at key ``name`` :rtype: int 13 14 12 42 """
|
amount = get_integer('amount', amount)
return self.execute_command('incr', name, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decr(self, name, amount=1):
""" Decrease the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` . Like **Redis.DECR** :param string name: the key name :param int amount: decrements :return: the integer value at key ``name`` :rtype: int 7 6 -42 """
|
amount = get_positive_integer('amount', amount)
return self.execute_command('decr', name, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getbit(self, name, offset):
""" Returns a boolean indicating the value of ``offset`` in ``name`` Like **Redis.GETBIT** :param string name: the key name :param int offset: the bit position :param bool val: the bit value :return: the bit at the ``offset`` , ``False`` if key doesn't exist or offset exceeds the string length. :rtype: bool True True False """
|
offset = get_positive_integer('offset', offset)
return self.execute_command('getbit', name, offset)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def countbit(self, name, start=None, size=None):
""" Returns the count of set bits in the value of ``key``. Optional ``start`` and ``size`` paramaters indicate which bytes to consider. Similiar with **Redis.BITCOUNT** :param string name: the key name :param int start: Optional, if start is negative, count from start'th character from the end of string. :param int size: Optional, if size is negative, then that many characters will be omitted from the end of string. :return: the count of the bit 1 :rtype: int True 3 True 3 16 """
|
if start is not None and size is not None:
start = get_integer('start', start)
size = get_integer('size', size)
return self.execute_command('countbit', name, start, size)
elif start is not None:
start = get_integer('start', start)
return self.execute_command('countbit', name, start)
return self.execute_command('countbit', 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 substr(self, name, start=None, size=None):
""" Return a substring of the string at key ``name``. ``start`` and ``size`` are 0-based integers specifying the portion of the string to return. Like **Redis.SUBSTR** :param string name: the key name :param int start: Optional, the offset of first byte returned. If start is negative, the returned string will start at the start'th character from the end of string. :param int size: Optional, number of bytes returned. If size is negative, then that many characters will be omitted from the end of string. :return: The extracted part of the string. :rtype: string True 'c123' '78' 'bc1234567' """
|
if start is not None and size is not None:
start = get_integer('start', start)
size = get_integer('size', size)
return self.execute_command('substr', name, start, size)
elif start is not None:
start = get_integer('start', start)
return self.execute_command('substr', name, start)
return self.execute_command('substr', 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 keys(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` Similiar with **Redis.KEYS** .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list ['set_x2', 'set_x3'] ['set_x1', 'set_x2', 'set_x3'] ['set_x1', 'set_x2', 'set_x3', 'set_x4'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('keys', name_start, name_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hincr(self, name, key, amount=1):
""" Increase the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` Like **Redis.HINCR** :param string name: the hash name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in hash ``name`` :rtype: int 49 6 101 8848 """
|
amount = get_integer('amount', amount)
return self.execute_command('hincr', name, key, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hdecr(self, name, key, amount=1):
""" Decrease the value of ``key`` in hash ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` :param string name: the hash name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in hash ``name`` :rtype: int 35 0 -101 -8848 """
|
amount = get_positive_integer('amount', amount)
return self.execute_command('hdecr', name, key, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hkeys(self, name, key_start, key_end, limit=10):
""" Return a list of the top ``limit`` keys between ``key_start`` and ``key_end`` in hash ``name`` Similiar with **Redis.HKEYS** .. note:: The range is (``key_start``, ``key_end``]. The ``key_start`` isn't in the range, but ``key_end`` is. :param string name: the hash name :param string key_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string key_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list ['b', 'c', 'd', 'e', 'f', 'g'] ['key1', 'key2', 'key3'] ['g'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('hkeys', name, key_start, key_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of hash names to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of hash names to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of hash's name :rtype: list ['hash_1', 'hash_2'] ['hash_1', 'hash_2'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('hlist', name_start, name_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hrlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` hash's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of hash names to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of hash names to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of hash's name :rtype: list ['hash_2', 'hash_1'] ['hash_2', 'hash_1'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('hrlist', name_start, name_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zset(self, name, key, score=1):
""" Set the score of ``key`` from the zset ``name`` to ``score`` Like **Redis.ZADD** :param string name: the zset name :param string key: the key name :param int score: the score for ranking :return: ``True`` if ``zset`` created a new score, otherwise ``False`` :rtype: bool True False 42 """
|
score = get_integer('score', score)
return self.execute_command('zset', name, key, score)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zincr(self, name, key, amount=1):
""" Increase the score of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as ``amount`` Like **Redis.ZINCR** :param string name: the zset name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in zset ``name`` :rtype: int 49 317 101 8848 """
|
amount = get_integer('amount', amount)
return self.execute_command('zincr', name, key, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zdecr(self, name, key, amount=1):
""" Decrease the value of ``key`` in zset ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` :param string name: the zset name :param string key: the key name :param int amount: increments :return: the integer value of ``key`` in zset ``name`` :rtype: int 36 311 -101 -8848 """
|
amount = get_positive_integer('amount', amount)
return self.execute_command('zdecr', name, key, amount)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zset names to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of zset names to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of zset's name :rtype: list ['zset_1', 'zset_2'] ['zset_1', 'zset_2'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('zlist', name_start, name_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zrlist(self, name_start, name_end, limit=10):
""" Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zset names to be returned, empty string ``''`` means +inf :param string name_end: The upper bound(included) of zset names to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a list of zset's name :rtype: list ['zset_2', 'zset_1'] ['zset_2', 'zset_1'] [] """
|
limit = get_positive_integer('limit', limit)
return self.execute_command('zrlist', name_start, name_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zkeys(self, name, key_start, score_start, score_end, limit=10):
""" Return a list of the top ``limit`` keys after ``key_start`` from zset ``name`` with scores between ``score_start`` and ``score_end`` .. note:: The range is (``key_start``+``score_start``, ``key_end``]. That means (key.score == score_start && key > key_start || key.score > score_start) :param string name: the zset name :param string key_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string key_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list ['g', 'd', 'b', 'a', 'e', 'c'] ['g', 'd', 'b'] ['a', 'e', 'c'] [] """
|
score_start = get_integer_or_emptystring('score_start', score_start)
score_end = get_integer_or_emptystring('score_end', score_end)
limit = get_positive_integer('limit', limit)
return self.execute_command('zkeys', name, key_start, score_start,
score_end, limit)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zcount(self, name, score_start, score_end):
""" Returns the number of elements in the sorted set at key ``name`` with a score between ``score_start`` and ``score_end``. Like **Redis.ZCOUNT** .. note:: The range is [``score_start``, ``score_end``] :param string name: the zset name :param int score_start: The minimum score related to keys(included), empty string ``''`` means -inf :param int score_end: The maximum score(included) related to keys, empty string ``''`` means +inf :return: the number of keys in specified range :rtype: int 3 6 0 """
|
score_start = get_integer_or_emptystring('score_start', score_start)
score_end = get_integer_or_emptystring('score_end', score_end)
return self.execute_command('zcount', name, score_start, score_end)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qget(self, name, index):
""" Get the element of ``index`` within the queue ``name`` :param string name: the queue name :param int index: the specified index, can < 0 :return: the value at ``index`` within queue ``name`` , or ``None`` if the element doesn't exist :rtype: string """
|
index = get_integer('index', index)
return self.execute_command('qget', name, index)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qset(self, name, index, value):
""" Set the list element at ``index`` to ``value``. :param string name: the queue name :param int index: the specified index, can < 0 :param string value: the element value :return: Unknown :rtype: True """
|
index = get_integer('index', index)
return self.execute_command('qset', name, index, value)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qpop_front(self, name, size=1):
""" Remove and return the first ``size`` item of the list ``name`` Like **Redis.LPOP** :param string name: the queue name :param int size: the length of result :return: the list of pop elements :rtype: list """
|
size = get_positive_integer("size", size)
return self.execute_command('qpop_front', name, size)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qpop_back(self, name, size=1):
""" Remove and return the last ``size`` item of the list ``name`` Like **Redis.RPOP** :param string name: the queue name :param int size: the length of result :return: the list of pop elements :rtype: list """
|
size = get_positive_integer("size", size)
return self.execute_command('qpop_back', name, size)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qlist(self, name_start, name_end, limit):
""" Return a list of the top ``limit`` keys between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of keys to be returned, empty string ``''`` means -inf :param string name_end: The upper bound(included) of keys to be returned, empty string ``''`` means +inf :param int limit: number of elements will be returned. :return: a list of keys :rtype: list ['queue_2'] ['queue_1', 'queue_2'] [] """
|
limit = get_positive_integer("limit", limit)
return self.execute_command('qlist', name_start, name_end, limit)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.