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 split_by_connected_component(self, idents):
'''Split idents into equivalence classes based on connected
components.
'''
idents_remaining = set(idents)
connected_components = []
for ident in idents:
if ident not in idents_remaining:
continue... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def connected_component(self, ident):
'''Return a connected component generator for ``ident``.
``ident`` may be a ``content_id`` or a ``(content_id,
subtopic_id)``.
Given an ``ident``, return the corresponding connected
component by following all positive transitivity relations... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def expand(self, ident):
'''Return expanded set of labels from a connected component.
The connected component is derived from ``ident``. ``ident``
may be a ``content_id`` or a ``(content_id, subtopic_id)``.
If ``ident`` identifies a subtopic, then expansion is done
on a subtopic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def negative_inference(self, content_id):
'''Return a generator of inferred negative label relationships
centered on ``content_id``.
Negative labels are inferred by getting all other content ids
connected to ``content_id`` through a negative label, then
running :meth:`LabelStore... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def negative_label_inference(self, label):
'''Return a generator of inferred negative label relationships.
Construct ad-hoc negative labels between ``label.content_id1``
and the positive connected component of ``label.content_id2``,
and ``label.content_id2`` to the connected component o... |
<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_keys(self, content_id=None, prefix=None, subtopic_id=None):
'''Filter out-of-order labels by key tuple.
:class:`Label` always sorts by `(cid1,cid2,sid1,sid2)`, but
for efficient lookups on `cid2` this class also stores in
order `(cid2,cid1,sid2,sid1)`. Filter out things tha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def apply_diff(self, diff):
'''Applies a diff to the label table.
A ``diff`` is a dictionary with three keys: ``add``, ``delete``
and ``change``. Each key should map to a list of labels.
``add`` corresponds to the labels that are in ``new`` but not in
``old``.
``delete... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_exists(original_file):
""" Check to make sure the original file exists """ |
if original_file.startswith("s3://"):
from filesystem import s3
return s3.file_exists(original_file)
else:
if not os.path.exists(original_file):
return False
if not os.path.isfile(original_file):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_task(self, task):
"""Complete logging of a task Returns the time lapsed since `start_task` was called Parameters task : str Name of the task to be s... |
try:
runtime = self.timer() - self.tasks[task]
del self.tasks[task]
if runtime >= self.min_runtime:
self.info("Calculated {} in {:.2f} seconds.".format(
task, runtime))
return runtime
except KeyError:
self.i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_miz( # noqa: C901 infile: str, outfile: str = None, metar: typing.Union[str, Metar] = None, time: str = None, min_wind: int = 0, max_wind: int = 40 ) -> ... |
if outfile is None:
LOGGER.debug('editing in place: %s', infile)
outfile = infile
else:
LOGGER.debug('editing miz file: %s -> %s', infile, outfile)
mission_weather = mission_time = None
if metar:
error, metar = emiz.weather.custom_metar.CustomMetar.get_metar(metar)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(self, loader, filename, encoding='utf-8', silent=False):
""" Updates recursively the value in the the config from some file. :param loader: (functi... |
conf = {}
try:
with open(filename, encoding=encoding) as f:
conf = loader(f)
except Exception:
if not silent:
raise
self.update(conf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(self, filename, encoding='utf-8', silent=False):
""" Updates recursively the value in the the config from a JSON file. :param filename: (str) a fil... |
self.from_file(json.load, filename, encoding, silent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_yaml(self, filename, encoding='utf-8', silent=False):
""" Updates recursively the value in the the config from a YAML file. The method requires the PyYA... |
if not yaml:
raise AttributeError(
'You need to install PyYAML before using this method!')
self.from_file(yaml.load, filename, encoding, silent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, iterable={}, **kwargs):
""" Updates recursively a self with a given iterable. TODO: rewrite this ugly stuff """ |
def _merge(a, *args):
for key, value in itertools.chain(*args):
if key in a and isinstance(value, (dict, Conf)):
value = _merge(a[key], value.items())
a[key] = value
return a
# adopt iterable sequence to unified interface: (ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def baseline(dataset, column=1, fn=None, fail_silently=True):
""" Substract baseline from the dataset Parameters dataset : list of numpy array list A list of num... |
try:
if fn is None:
fn = lambda columns, column: columns[column][0]
for i, data in enumerate(dataset):
_baseline = fn(data, column=column)
dataset[i][column] -= _baseline
return dataset
except IndexError, e:
if fail_silently:
# fai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dataset_info(dataset):
"""Return information about dataset as a dict.""" |
info = {}
info["uri"] = dataset.uri
info["uuid"] = dataset.uuid
# Computer and human readable size of dataset.
tot_size = sum([dataset.item_properties(i)["size_in_bytes"]
for i in dataset.identifiers])
info["size_int"] = tot_size
info["size_str"] = sizeof_fmt(tot_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 inventory(uri, format):
"""Generate an inventory of datasets in a base URI.""" |
base_uri = dtoolcore.utils.sanitise_uri(uri)
info = _base_uri_info(base_uri)
if format is None:
_cmd_line_report(info)
elif format == "csv":
_csv_tsv_report(info, ",")
elif format == "tsv":
_csv_tsv_report(info, "\t")
elif format == "html":
_html_report(info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def custom_prompt(msg, delims="", completer=lambda: None):
"""Start up a prompt that with particular delims and completer""" |
try:
orig_delims = readline.get_completer_delims()
orig_completer = readline.get_completer()
readline.set_completer_delims(delims)
readline.set_completer(completer)
try:
ret = input(msg)
finally:
readline.set_completer_delims(orig_delims)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def primitive_form(obj, **kwargs):
'''Return obj, if possible, in a form composed of primitive or builtin objects.'''
if isinstance(obj, type):
return obj
return Type.dispatch(obj).primitive_form(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evalPDF(self, u_values):
'''Returns the PDF of the uncertain parameter evaluated at the values
provided in u_values.
:param iterable u_values: values of the uncertain parameter at which to
evaluate the PDF
*Example Usage* ::
>>> u = UniformParameter()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def term_regex(term):
""" Returns a case-insensitive regex for searching terms """ |
return re.compile(r'^{0}$'.format(re.escape(term)), re.IGNORECASE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_fact(term):
""" Shows a fact stored for a given term, using a case-insensitive search. If a fact has an author, it will be shown. If it has a timestamp,... |
logger.info('Showing fact %s', term)
record = db.facts.find_one({'term': term_regex(term)})
if record is None:
return None
# Fix double spacing in older facts
if record['fact']:
record['fact'] = record['fact'].replace(' ', ' ')
# If it isn't authored
if not record.get('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 add_fact(term, fact, author=''):
""" Records a new fact with a given term. Optionally can set an author """ |
logger.info('Adding new fact %s: %s', term, fact)
if not db.facts.find({'term': term_regex(term)}).count():
db.facts.insert({
'term': term,
'fact': fact,
'set_by': author,
'set_date': time.time()
})
db.facts.ensure_index('term') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forget_fact(term):
""" Forgets a fact by removing it from the database """ |
logger.info('Removing fact %s', term)
db.facts.remove({'term': term_regex(term)})
return random.choice(ACKS) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_fact(term, fact, author=''):
""" Replaces an existing fact by removing it, then adding the new definition """ |
forget_fact(term)
add_fact(term, fact, author)
return random.choice(ACKS) |
<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_module_docstring(app, what, name, obj, options, lines):
""" Ignore the docstring of the ``clusterpolate`` module. """ |
if what == "module" and name == "clusterpolate":
del lines[:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wind(direction: Number, speed: Number, gust: Number, vardir: typing.List[Number] = None, # type: ignore unit: str = 'kt', cardinals: bool = True, spoken: bool... |
ret = ''
target = 'spoken' if spoken else 'repr'
# Wind direction
if direction:
if direction.repr in WIND_DIR_REPR:
ret += WIND_DIR_REPR[direction.repr]
elif direction.value is None:
ret += direction.repr
else:
if cardinals:
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visibility(vis: Number, unit: str = 'm') -> str: """ Formats a visibility element into a string with both km and sm values Ex: 8km ( 5sm ) """ |
if not (vis and unit in ('m', 'sm')):
return ''
if vis.repr in VIS_REPR:
return VIS_REPR[vis.repr]
if unit == 'm':
converted = vis.value * 0.000621371
converted = str(round(converted, 1)).replace('.0', '') + 'sm' # type: ignore
value = str(round(vis.value / 1000, 1)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temperature(temp: Number, unit: str = 'C') -> str: """ Formats a temperature element into a string with both C and F values Used for both Temp and Dew Ex: 34°... |
unit = unit.upper()
if not (temp and unit in ('C', 'F')):
return ''
if unit == 'C':
converted = temp.value * 1.8 + 32
converted = str(int(round(converted))) + '°F' # type: ignore
elif unit == 'F':
converted = (temp.value - 32) / 1.8
converted = str(int(round(con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def altimeter(alt: Number, unit: str = 'hPa') -> str: """ Formats the altimter element into a string with hPa and inHg values Ex: 30.11 inHg (10.20 hPa) """ |
if not (alt and unit in ('hPa', 'inHg')):
return ''
if unit == 'hPa':
value = alt.repr
converted = alt.value / 33.8638866667
converted = str(round(converted, 2)) + ' inHg' # type: ignore
elif unit == 'inHg':
value = alt.repr[:2] + '.' + alt.repr[2:]
converte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clouds(clds: [Cloud], unit: str = 'ft') -> str: # type: ignore """ Format cloud list into a readable sentence Returns the translation string Ex: Broken layer ... |
if clds is None:
return ''
ret = []
for cloud in clds:
if cloud.altitude is None:
continue
cloud_str = CLOUD_TRANSLATIONS[cloud.type]
if cloud.modifier:
cloud_str += f' ({CLOUD_TRANSLATIONS[cloud.modifier]})'
ret.append(cloud_str.format(cloud.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wxcode(code: str) -> str: """ Translates weather codes into readable strings Returns translated string of variable length """ |
if not code:
return ''
ret = ''
if code[0] == '+':
ret = 'Heavy '
code = code[1:]
elif code[0] == '-':
ret = 'Light '
code = code[1:]
# Return code if code is not a code, ex R03/03002V03
if len(code) not in [2, 4, 6]:
return code
for _ in rang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt', spoken: bool = False) -> str: """ Translate wind shear into a readable string Ex: Wind she... |
if not shear or 'WS' not in shear or '/' not in shear:
return ''
shear = shear[2:].rstrip(unit_wind.upper()).split('/') # type: ignore
wdir = core.spoken_number(shear[1][:3]) if spoken else shear[1][:3]
return f'Wind shear {int(shear[0])*100}{unit_alt} from {wdir} at {shear[1][3:]}{unit_wind}' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def turb_ice(turbice: [str], unit: str = 'ft') -> str: # type: ignore """ Translate the list of turbulance or icing into a readable sentence Ex: Occasional modera... |
if not turbice:
return ''
# Determine turbulance or icing
if turbice[0][0] == '5':
conditions = TURBULANCE_CONDITIONS
elif turbice[0][0] == '6':
conditions = ICING_CONDITIONS
else:
return ''
# Create list of split items (type, floor, height)
split = []
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def min_max_temp(temp: str, unit: str = 'C') -> str: """ Format the Min and Max temp elemets into a readable string Ex: Maximum temperature of 23°C (73°F) at 18-1... |
if not temp or len(temp) < 7:
return ''
if temp[:2] == 'TX':
temp_type = 'Maximum'
elif temp[:2] == 'TN':
temp_type = 'Minimum'
else:
return ''
temp = temp[2:].replace('M', '-').replace('Z', '').split('/') # type: ignore
if len(temp[1]) > 2:
temp[1] = te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shared(wxdata: ReportData, units: Units) -> typing.Dict[str, str]: """ Translate Visibility, Altimeter, Clouds, and Other """ |
translations = {}
translations['visibility'] = visibility(wxdata.visibility, units.visibility) # type: ignore
translations['altimeter'] = altimeter(wxdata.altimeter, units.altimeter) # type: ignore
translations['clouds'] = clouds(wxdata.clouds, units.altitude) # type: ignore
translations['other'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metar(wxdata: MetarData, units: Units) -> MetarTrans: """ Translate the results of metar.parse Keys: Wind, Visibility, Clouds, Temperature, Dewpoint, Altimete... |
translations = shared(wxdata, units)
translations['wind'] = wind(wxdata.wind_direction, wxdata.wind_speed,
wxdata.wind_gust, wxdata.wind_variable_direction,
units.wind_speed)
translations['temperature'] = temperature(wxdata.temperature, units.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def taf(wxdata: TafData, units: Units) -> TafTrans: """ Translate the results of taf.parse Keys: Forecast, Min-Temp, Max-Temp Forecast keys: Wind, Visibility, Clo... |
translations = {'forecast': []} # type: ignore
for line in wxdata.forecast:
trans = shared(line, units) # type: ignore
trans['wind'] = wind(line.wind_direction, line.wind_speed,
line.wind_gust, unit=units.wind_speed)
trans['wind_shear'] = wind_shear(line.w... |
<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_substitute_element(head, elt, ps):
'''if elt matches a member of the head substitutionGroup, return
the GED typecode.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap Instance
'''
if not isinstance(head, ElementDeclaration):
return... |
<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_substitute_element(head, sub):
'''if head and sub are both GEDs, and sub declares
head as its substitutionGroup then return True.
head -- Typecode instance
sub -- Typecode instance
'''
if not isinstance(head, ElementDeclaration) or not isinstance(sub, ElementDeclaration):
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False):
'''Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def checkSubstitute(self, typecode):
'''If this is True, allow typecode to be substituted
for "self" typecode.
'''
if not isinstance(typecode, ElementDeclaration):
return False
try:
nsuri,ncname = typecode.substitutionGroup
except (AttributeError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getSubstitutionElement(self, elt, ps):
'''if elt matches a member of the head substitutionGroup, return
the GED typecode representation of the member.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap instance
'''
nsu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def RegisterBuiltin(cls, arg):
'''register a builtin, create a new wrapper.
'''
if arg in cls.types_dict:
raise RuntimeError, '%s already registered' %arg
class _Wrapper(arg):
'Wrapper for builtin %s\n%s' %(arg, cls.__doc__)
_Wrapper.__name__ = '_%sWrapper... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def RegisterAnyElement(cls):
'''If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper.
'''
for k,v in cls.types_dict.items():
what = Any.serialmap.get(k)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def render_doc(self):
'''Override this method to customize the documentation page'''
if self._doc_view:
return self._doc_view()
elif not self._doc:
self.abort(self.bc_HTTPStatus_NOT_FOUND)
res = render_template('swagger-ui.html', title=self.title, specs_url=self.specs_url)
res = res.repl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __createLayout(self):
"""Creates the dialog layout""" |
self.resize(450, 150)
self.setSizeGripEnabled(True)
verticalLayout = QVBoxLayout(self)
whereGroupbox = QGroupBox(self)
whereGroupbox.setTitle("Garbage collector message destination")
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
sizePol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCheckedOption(self):
"""Returns what destination is selected""" |
if self.__silentRButton.isChecked():
return GCPluginConfigDialog.SILENT
if self.__statusbarRButton.isChecked():
return GCPluginConfigDialog.STATUS_BAR
return GCPluginConfigDialog.LOG |
<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_seq(seq_record, codon_positions, aminoacids=False, degenerate=None):
""" required sequence as string. Parameters: seq_record (SeqRecordExpanded object):
... |
Sequence = namedtuple('Sequence', ['seq', 'warning'])
if codon_positions not in [None, '1st', '2nd', '3rd', '1st-2nd', 'ALL']:
raise WrongParameterFormat("`codon_positions` argument should be any of the following"
": 1st, 2nd, 3rd, 1st-2nd or ALL")
if aminoacids:... |
<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_nexus_to_format(dataset_as_nexus, dataset_format):
""" Converts nexus format to Phylip and Fasta using Biopython tools. :param dataset_as_nexus: :par... |
fake_handle = StringIO(dataset_as_nexus)
nexus_al = AlignIO.parse(fake_handle, 'nexus')
tmp_file = make_random_filename()
AlignIO.write(nexus_al, tmp_file, dataset_format)
dataset_as_fasta = read_and_delete_tmp_file(tmp_file)
return dataset_as_fasta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate_sentence(text, max_chars, break_words=False, padding=0):
"""Truncates a sentence. :param max_chars: The maximum characters of truncated sentence. :p... |
if break_words:
return text[:-abs(max_chars - len(text)) - padding]
words = []
for word in text.split():
predicted_len = (
sum(map(len, words)) + # length of words
len(word) + # length of next word
len(words) - 1 + # length of spaces
paddi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def always_win(cls, request) -> [(200, 'Ok', String)]:
'''Perform an always succeeding task.'''
task_id = uuid4().hex.upper()[:5]
log.info('Starting always OK task {}'.format(task_id))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
log.info('Finished always OK t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def always_fail(cls, request) -> [
(200, 'Ok', String),
(406, 'Not Acceptable', Void)]:
'''Perform an always failing task.'''
task_id = uuid4().hex.upper()[:5]
log.info('Starting always FAILING task {}'.format(task_id))
for i in range(randint(0, MAX_LOOP_DURATION)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fibonacci(cls, request,
limit: (Ptypes.path,
Integer('Upper limit of the series'))) -> [
(200, 'Ok', FibonacciFragment)]:
'''Return Fibonacci sequence whose last number is <= limit.'''
def fibonacci_generator():
last_two = (0, 1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def query_echo(cls, request,
foo: (Ptypes.query, String('A query parameter'))) -> [
(200, 'Ok', String)]:
'''Echo the query parameter.'''
log.info('Echoing query param, value is: {}'.format(foo))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def body_echo(cls, request,
foo: (Ptypes.body, String('A body parameter'))) -> [
(200, 'Ok', String)]:
'''Echo the body parameter.'''
log.info('Echoing body param, value is: {}'.format(foo))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
ms... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def header_echo(cls, request,
api_key: (Ptypes.header, String('API key'))) -> [
(200, 'Ok', String)]:
'''Echo the header parameter.'''
log.info('Echoing header param, value is: {}'.format(api_key))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def form_echo(cls, request,
foo: (Ptypes.form, String('A form parameter'))) -> [
(200, 'Ok', String)]:
'''Echo the form parameter.'''
log.info('Echoing form param, value is: {}'.format(foo))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
ms... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(data_type, name=None, listify_default=False):
"""Retrieve the properties for a given data type. This is the main routine where most of the work is do... |
data_type = _consolidate(data_type)
return Nani(
dtype=numpy.dtype(_resolve_dtype(data_type)),
default=_resolve_default(data_type, listify=listify_default),
view=_resolve_view(Array(element_type=data_type, shape=-1, name=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 _consolidate(data_type):
"""Enforce the structure of the data type. Specifically, ensure that if a field is defined as a generic tuple, then it will be conve... |
if isinstance(data_type, _ATOMIC):
out = data_type
elif isinstance(data_type, Array):
element_type = _consolidate(data_type.element_type)
out = data_type._replace(element_type=element_type)
elif isinstance(data_type, Structure):
fields = tuple(
Field(*(_consolida... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_dtype(data_type):
"""Retrieve the corresponding NumPy's `dtype` for a given data type.""" |
if isinstance(data_type, _FIXED_ATOMIC):
out = _get_atomic_dtype(data_type)
elif isinstance(data_type, _FLEXIBLE_ATOMIC):
out = (_get_atomic_dtype(data_type), data_type.length)
elif isinstance(data_type, Array):
shape = data_type.shape
if isinstance(shape, _SEQUENCE_TYPES) a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_default(data_type, listify=False):
"""Retrieve the default value for a given data type.""" |
if isinstance(data_type, _ATOMIC):
# A Python's object type needs to be left as is instead of being
# wrapped into a NumPy type.
out = (data_type.default if isinstance(data_type, Object)
else _get_atomic_dtype(data_type)(data_type.default))
elif isinstance(data_type, Arra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_view(data_type):
"""Retrieve the view for a given data type. Only one view class is returned, that is the one representing the root data type, but m... |
view = getattr(data_type, 'view', None)
if view is not None:
return view
if isinstance(data_type, _ATOMIC):
out = None
elif isinstance(data_type, Array):
out = _define_array_view(data_type)
elif isinstance(data_type, Structure):
out = _define_structure_view(data_typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _define_array_view(data_type):
"""Define a new view object for a `Array` type.""" |
element_type = data_type.element_type
element_view = _resolve_view(element_type)
if element_view is None:
mixins = (_DirectArrayViewMixin,)
attributes = _get_mixin_attributes(mixins)
elif isinstance(element_type, _ATOMIC):
mixins = (_IndirectAtomicArrayViewMixin,)
attrib... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _define_structure_view(data_type):
"""Define a new view object for a `Structure` type.""" |
def define_getter(field_index, field_type, field_view):
if field_view is None:
def getter(self):
return self._data[field_index]
elif isinstance(field_type, _ATOMIC):
def getter(self):
return field_view(self._data, field_index)
else:
... |
<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_mixin_attributes(mixins):
"""Retrieve the attributes for a given set of mixin classes. The attributes of each mixin class are being merged into a single... |
return {attribute: mixin.__dict__[attribute]
for mixin in mixins
for attribute in _MIXIN_ATTRIBUTES[mixin]} |
<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_atomic_dtype(data_type):
"""Retrieve the NumPy's `dtype` for a given atomic data type.""" |
atomic_type = getattr(data_type, 'type', None)
if atomic_type is not None:
return atomic_type
return _PREDEFINED_ATOMIC_NUMPY_TYPES[_find_base_type(data_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 _find_base_type(data_type):
"""Find the Nani's base type for a given data type. This is useful when Nani's data types were subclassed and the original type i... |
bases = type(data_type).__mro__
for base in bases:
if base in _ALL:
return base
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 _find_duplicates(seq):
"""Find the duplicate elements from a sequence.""" |
seen = set()
return [element for element in seq
if seq.count(element) > 1
and element not in seen and seen.add(element) is 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 _format_type(cls):
"""Format a type name for printing.""" |
if cls.__module__ == _BUILTIN_MODULE:
return cls.__name__
else:
return '%s.%s' % (cls.__module__, cls.__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 _format_element(element, count, index, last_separator):
"""Format an element from a sequence. This only prepends a separator for the last element and wraps e... |
return ("%s'%s'" % (last_separator, element)
if count > 1 and index == count - 1
else "'%s'" % (element,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join_sequence(seq, last_separator=''):
"""Join a sequence into a string.""" |
count = len(seq)
return ', '.join(_format_element(element, count, i, last_separator)
for i, element in enumerate(seq)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join_types(seq, last_separator=''):
"""Join class object names into a string.""" |
class_names = [_format_type(cls) for cls in seq]
return _join_sequence(class_names, last_separator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice_columns(x, using=None):
""" Slice a numpy array to make columns Parameters x : ndarray A numpy array instance using : list of integer or slice instance... |
if using is None:
using = range(0, len(x[0]))
return [x[:,s] for s in using] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unite_dataset(dataset, basecolumn=0):
""" Unite dataset into a single data Parameters dataset : list of ndarray A data list of a column list of a numpy array... |
ndata = [None] * len(dataset[0])
for pdata in dataset:
# select basecolumn
bnx = ndata[basecolumn]
bpx = pdata[basecolumn]
if bnx is not None and bnx.ndim >= 2:
bnx = bnx[:,-1]
if bpx is not None and bpx.ndim >= 2:
bpx = bpx[:,-1]
# calcul... |
<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(self, filename, using=None, parser=None, **kwargs):
""" Load data from file using a specified parser. Return value will be separated or sliced into a co... |
using = using or self.using
parser = parser or self.parser
if parser is None:
raise AttributeError("A parser instance must be specified")
# parse iterator with the specified parser
data = parser.load(filename, **kwargs)
# slice column by using
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_filenames(self, normalized_url, request):
""" Prepare template filename list based on the user authenticated state If user is authenticated user, it ... |
filenames = [normalized_url]
if request.user.is_authenticated():
filenames.insert(0, normalized_url + ".authenticated")
else:
filenames.insert(0, normalized_url + ".anonymous")
return filenames |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadFromStream(self, stream, name=None):
"""Return a WSDL instance loaded from a stream object.""" |
document = DOM.loadDocument(stream)
wsdl = WSDL()
if name:
wsdl.location = name
elif hasattr(stream, 'name'):
wsdl.location = stream.name
wsdl.load(document)
return wsdl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadFromURL(self, url):
"""Return a WSDL instance loaded from the given url.""" |
document = DOM.loadFromURL(url)
wsdl = WSDL()
wsdl.location = url
wsdl.load(document)
return wsdl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadFromFile(self, filename):
"""Return a WSDL instance loaded from the given file.""" |
file = open(filename, 'rb')
try:
wsdl = self.loadFromStream(file)
finally:
file.close()
return wsdl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toDom(self):
""" Generate a DOM representation of the WSDL instance. Not dealing with generating XML Schema, thus the targetNamespace of all XML Schema eleme... |
namespaceURI = DOM.GetWSDLUri(self.version)
self.document = DOM.createDocument(namespaceURI ,'wsdl:definitions')
# Set up a couple prefixes for easy reading.
child = DOM.getElement(self.document, None)
child.setAttributeNS(None, 'targetNamespace', self.targetNamespace)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getWSDL(self):
"""Return the WSDL object that contains this information item.""" |
parent = self
while 1:
# skip any collections
if isinstance(parent, WSDL):
return parent
try: parent = parent.parent()
except: break
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 getBinding(self):
"""Return the Binding object that is referenced by this port.""" |
wsdl = self.getService().getWSDL()
return wsdl.bindings[self.binding] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPortType(self):
"""Return the PortType object that is referenced by this port.""" |
wsdl = self.getService().getWSDL()
binding = wsdl.bindings[self.binding]
return wsdl.portTypes[binding.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 getAddressBinding(self):
"""A convenience method to obtain the extension element used as the address binding for the port.""" |
for item in self.extensions:
if isinstance(item, SoapAddressBinding) or \
isinstance(item, HttpAddressBinding):
return item
raise WSDLError(
'No address binding found in port.'
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addInParameter(self, name, type, namespace=None, element_type=0):
"""Add an input parameter description to the call info.""" |
parameter = ParameterInfo(name, type, namespace, element_type)
self.inparams.append(parameter)
return parameter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addOutParameter(self, name, type, namespace=None, element_type=0):
"""Add an output parameter description to the call info.""" |
parameter = ParameterInfo(name, type, namespace, element_type)
self.outparams.append(parameter)
return parameter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setReturnParameter(self, name, type, namespace=None, element_type=0):
"""Set the return parameter description for the call info.""" |
parameter = ParameterInfo(name, type, namespace, element_type)
self.retval = parameter
return parameter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addInHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0):
"""Add an input SOAP header description to the call info.""" |
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.inheaders.append(headerinfo)
return headerinfo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addOutHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0):
"""Add an output SOAP header description to the call info.""" |
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
self.outheaders.append(headerinfo)
return headerinfo |
<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_requirements(dist, attr, value):
"""Verify that install_requires is a valid requirements list""" |
try:
list(pkg_resources.parse_requirements(value))
except (TypeError,ValueError):
raise DistutilsSetupError(
"%r must be a string or list of strings "
"containing valid project/version requirement specifiers" % (attr,)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def store(self):
""" Create a context manager to store records in the cleaned table. """ |
output = tempfile.NamedTemporaryFile(suffix='.json')
try:
def write(o):
line = json.dumps(o, default=json_default)
return output.write(line + '\n')
yield write
output.seek(0)
log.info("Uploading generated table (%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 records(self):
""" Get each record that has been stored in the table. """ |
output = tempfile.NamedTemporaryFile(suffix='.json')
try:
log.info("Loading table from (%s)...", self._obj)
shutil.copyfileobj(self.fh(), output)
output.seek(0)
for line in output.file:
yield json.loads(line, object_hook=json_hook)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cleanRecursive(self, subSelf):
""" Delete all NestedOrderedDict that haven't any entries. """ |
for key, item in list(subSelf.items()):
if self.isNestedDict(item):
if not item:
subSelf.pop(key)
else:
self._cleanRecursive(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def belongsToModule(obj, module):
"""Returns True is an object belongs to a module.""" |
return obj.__module__ == module.__name__ or obj.__module__.startswith(
module.__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 create_table(self):
"""Create the DynamoDB table used by this ObjectStore, only if it does not already exists. """ |
all_tables = self.aws_conn.list_tables()['TableNames']
if self.table_name in all_tables:
log.info("Table %s already exists" % self.table_name)
else:
log.info("Table %s does not exist: creating it" % self.table_name)
self.table = Table.create(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, key, value, overwrite=True):
"""Marshall the python object given as 'value' into a string, using the to_string marshalling method passed in the con... |
self._get_table()
s = self.to_string(value)
log.debug("Storing in key '%s' the object: '%s'" % (key, s))
self.table.put_item(
data={
'key': key,
'value': s,
},
overwrite=overwrite
) |
<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(self, key):
"""Get the string representation of the object stored in DynamoDB under this key, convert it back to an object using the 'from_string' unmars... |
self._get_table()
s = self.table.get_item(key=key)
log.debug("Retrieved from key '%s' the object: '%s'" % (key, s['value']))
return self.from_string(s['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 delete(self, key):
"""If this key exists, delete it""" |
self._get_table()
self.table.delete_item(key=key)
log.debug("Deleted item at key '%s'" % (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 _get_env(key, default=None, coerce=lambda x: x, required=False):
""" Return env var coerced into a type other than string. This function extends the standard... |
try:
value = os.environ[key]
except KeyError:
if required is True:
raise RequiredSettingMissing(key)
else:
return default
try:
return coerce(value)
except Exception:
raise CoercianError(key, value, coerce) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.