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 _findSubsetProteins(proteins, protToPeps, pepToProts):
"""Find proteins which peptides are a sub-set, but not a same-set to other proteins. :param proteins: iterable, proteins that are tested for being a subset :param pepToProts: dict, for each peptide (=key) contains a set of parent :param protToPeps: dict, for each protein (=key) contains a set of :returns: a list of pairs of protein and their superset proteins. """ |
proteinsEqual = lambda prot1, prot2: protToPeps[prot1] == protToPeps[prot2]
subGroups = list()
for protein in proteins:
peptideCounts = Counter()
for peptide in protToPeps[protein]:
proteins = pepToProts[peptide]
peptideCounts.update(proteins)
peptideCount = peptideCounts.pop(protein)
superGroups = set()
for sharingProtein, sharedPeptides in peptideCounts.most_common():
if peptideCount == sharedPeptides:
if not proteinsEqual(protein, sharingProtein):
superGroups.add(sharingProtein)
else:
break
if superGroups:
subGroups.append((protein, superGroups))
return subGroups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _findRedundantProteins(protToPeps, pepToProts, proteins=None):
"""Returns a set of proteins with redundant peptide evidence. After removing the redundant proteins from the "protToPeps" and "pepToProts" mapping, all remaining proteins have at least one unique peptide. The remaining proteins are a "minimal" set of proteins that are able to explain all peptides. However, this is not guaranteed to be the optimal solution with the least number of proteins. In addition it is possible that multiple solutions with the same number of "minimal" proteins exist. Procedure for finding the redundant proteins: 1. Generate a list of proteins that do not contain any unique peptides, a unique peptide has exactly one protein entry in "pepToProts". 2. Proteins are first sorted in ascending order of the number of peptides. Proteins with an equal number of peptides are sorted in descending order of their sorted peptide frequencies (= proteins per peptide). If two proteins are still equal, they are sorted alpha numerical in descending order according to their protein names. For example in the case of a tie between proteins "A" and "B", protein "B" would be removed. 3. Parse this list of sorted non unique proteins; If all its peptides have a frequency value of greater 1; mark the protein as redundant; remove its peptides from the peptide frequency count, continue with the next entry. 4. Return the set of proteins marked as redundant. :param pepToProts: dict, for each peptide (=key) contains a set of parent :param protToPeps: dict, for each protein (=key) contains a set of :param proteins: iterable, proteins that are tested for being redundant. If None all proteins in "protToPeps" are parsed. :returns: a set of redundant proteins, i.e. proteins that are not necessary to explain all peptides """ |
if proteins is None:
proteins = viewkeys(protToPeps)
pepFrequency = _getValueCounts(pepToProts)
protPepCounts = _getValueCounts(protToPeps)
getCount = operator.itemgetter(1)
getProt = operator.itemgetter(0)
#TODO: quick and dirty solution
#NOTE: add a test for merged proteins
proteinTuples = list()
for protein in proteins:
if isinstance(protein, tuple):
proteinTuples.append(protein)
else:
proteinTuples.append(tuple([protein]))
sort = list()
for protein in sorted(proteinTuples, reverse=True):
if len(protein) == 1:
protein = protein[0]
protPepFreq = [pepFrequency[pep] for pep in protToPeps[protein]]
if min(protPepFreq) > 1:
sortValue = (len(protPepFreq)*-1, sorted(protPepFreq, reverse=True))
sort.append((protein, sortValue))
sortedProteins = map(getProt, sorted(sort, key=getCount, reverse=True))
redundantProteins = set()
for protein in sortedProteins:
for pep in protToPeps[protein]:
if pepFrequency[pep] <= 1:
break
else:
protPepFrequency = Counter(protToPeps[protein])
pepFrequency.subtract(protPepFrequency)
redundantProteins.add(protein)
return redundantProteins |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mergeProteinEntries(proteinLists, protToPeps):
"""Returns a new "protToPeps" dictionary with entries merged that are present in proteinLists. NOTE: The key of the merged entry is a tuple of the sorted protein keys. This behaviour might change in the future; the tuple might be replaced by simply one of the protein entries which is then representative for all. :param proteinLists: a list of protein groups that will be merged :param protToPeps: dict, for each protein (=key) contains a set of """ |
mergedProtToPeps = dict(protToPeps)
for proteins in proteinLists:
for protein in proteins:
peptides = mergedProtToPeps.pop(protein)
mergedProtein = tuple(sorted(proteins))
mergedProtToPeps[mergedProtein] = peptides
return mergedProtToPeps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reducedProtToPeps(protToPeps, proteins):
"""Returns a new, reduced "protToPeps" dictionary that does not contain entries present in "proteins". :param protToPeps: dict, for each protein (=key) contains a set of :param proteins: a list of proteinSet :returns: dict, protToPeps not containing entries from "proteins" """ |
return {k: v for k, v in viewitems(protToPeps) if k not in proteins} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _findUniqueMappingKeys(mapping):
"""Find mapping keys that only have one entry (value length of 1. :param mapping: dict, for each key contains a set of entries :returns: a set of unique mapping keys """ |
uniqueMappingKeys = set()
for key, entries in viewitems(mapping):
if len(entries) == 1:
uniqueMappingKeys.add(key)
return uniqueMappingKeys |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _invertMapping(mapping):
"""Converts a protein to peptide or peptide to protein mapping. :param mapping: dict, for each key contains a set of entries :returns: an inverted mapping that each entry of the values points to a set of initial keys. """ |
invertedMapping = ddict(set)
for key, values in viewitems(mapping):
for value in values:
invertedMapping[value].add(key)
return invertedMapping |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mappingGetValueSet(mapping, keys):
"""Return a combined set of values from the mapping. :param mapping: dict, for each key contains a set of entries returns a set of combined entries """ |
setUnion = set()
for k in keys:
setUnion = setUnion.union(mapping[k])
return setUnion |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _flattenMergedProteins(proteins):
"""Return a set where merged protein entries in proteins are flattened. :param proteins: an iterable of proteins, can contain merged protein entries in the form of tuple([protein1, protein2]). returns a set of protein entries, where all entries are strings """ |
proteinSet = set()
for protein in proteins:
if isinstance(protein, tuple):
proteinSet.update(protein)
else:
proteinSet.add(protein)
return proteinSet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getGroups(self, proteinId):
"""Return a list of protein groups a protein is associated with.""" |
return [self.groups[gId] for gId in self._proteinToGroupIds[proteinId]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addProteinGroup(self, groupRepresentative):
"""Adds a new protein group and returns the groupId. The groupId is defined using an internal counter, which is incremented every time a protein group is added. The groupRepresentative is added as a leading protein. :param groupRepresentative: the protein group representing protein :returns: the protein groups groupId """ |
groupId = self._getNextGroupId()
self.groups[groupId] = ProteinGroup(groupId, groupRepresentative)
self.addLeadingToGroups(groupRepresentative, groupId)
return groupId |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addLeadingToGroups(self, proteinIds, groupIds):
"""Add one or multiple leading proteins to one or multiple protein groups. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupIds: a groupId or a list of groupIds, a groupId must be a string. """ |
for groupId in AUX.toList(groupIds):
self.groups[groupId].addLeadingProteins(proteinIds)
self._addProteinIdsToGroupMapping(proteinIds, groupId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addSubsetToGroups(self, proteinIds, groupIds):
"""Add one or multiple subset proteins to one or multiple protein groups. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupIds: a groupId or a list of groupIds, a groupId must be a string. """ |
for groupId in AUX.toList(groupIds):
self.groups[groupId].addSubsetProteins(proteinIds)
self._addProteinIdsToGroupMapping(proteinIds, groupId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addSubsumableToGroups(self, proteinIds, groupIds):
"""Add one or multiple subsumable proteins to one or multiple protein groups. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupIds: a groupId or a list of groupIds, a groupId must be a string. """ |
for groupId in AUX.toList(groupIds):
self.groups[groupId].addSubsumableProteins(proteinIds)
self._addProteinIdsToGroupMapping(proteinIds, groupId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _addProteinIdsToGroupMapping(self, proteinIds, groupId):
"""Add a groupId to one or multiple entries of the internal proteinToGroupId mapping. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupId: str, a groupId """ |
for proteinId in AUX.toList(proteinIds):
self._proteinToGroupIds[proteinId].add(groupId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _addProteins(self, proteinIds, containerNames):
"""Add one or multiple proteinIds to the respective container. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param containerNames: list, entries must be one or multiple of 'leading', 'subset', 'subsumableProteins' or 'proteins' :param addToProteins: bool, if True the proteinIds are added to the """ |
proteinIds = AUX.toList(proteinIds)
for containerName in containerNames:
proteinContainer = getattr(self, containerName)
proteinContainer.update(proteinIds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def satisfies(self, other):
"""Check if the capabilities of a primitive are enough to satisfy a requirement. Should be called on a Requirement that is acting as a capability of a primitive. This method returning true means that the capability advertised here is enough to handle representing the data described by the Requirement passed in as 'other'. Here is a chart showing what satisfies what. other A C 0 1 |Y N N N N s A|Y Y Y Y Y e C|Y - Y Y Y l 0|Y * * Y N f 1|Y * * N Y ' ' = No Care A = arbitrary C = Constant 0 = ZERO 1 = ONE Y = YES N = NO - = Could satisfy with multiple instances * = Not yet determined behavior. Used for bitbanging controllers. """ |
if other.isnocare:
return True
if self.isnocare:
return False
if self.arbitrary:
return True
if self.constant and not other.arbitrary:
return True
if self.value is other.value and not other.arbitrary\
and not other.constant:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _list(self, foldername="INBOX", reverse=False, since=None):
"""Do structured list output. Sorts the list by date, possibly reversed, filtered from 'since'. The returned list is: foldername, message key, message object """ |
folder = self.folder \
if foldername == "INBOX" \
else self._getfolder(foldername)
def sortcmp(d):
try:
return d[1].date
except:
return -1
lst = folder.items() if not since else folder.items_since(since)
sorted_lst = sorted(lst, key=sortcmp, reverse=1 if reverse else 0)
itemlist = [(folder, key, msg) for key,msg in sorted_lst]
return itemlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls(self, foldername="INBOX", reverse=False, since=None, grep=None, field=None, stream=sys.stdout):
"""Do standard text list of the folder to the stream. 'foldername' is the folder to list.. INBOX by default. 'since' allows the listing to be date filtered since that date. It should be a float, a time since epoch. 'grep' allows text matching on the whole record 'field' allows only 1 field to be output """ |
if foldername == "":
foldername = "INBOX"
msg_list = self._list(foldername, reverse, since)
for folder, mk, m in msg_list:
try:
# I am very unsure about this defaulting of foldername
output_items = (
"%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
m.date,
m.get_from()[0:50] if m.get_from() else "",
m.get_flags(),
re.sub("\n", "", m.get_subject() or "")
)
output_string = "% -20s % 20s % 50s [%s] %s" % output_items
if not grep or (grep and grep in output_string):
if field:
print(output_items[int(field)], file=stream)
else:
print(output_string, file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout):
"""Do JSON list of the folder to the stream. 'since' allows the listing to be date filtered since that date. It should be a float, a time since epoch. """ |
def fromval(hdr):
if hdr:
return parseaddr(hdr)
for folder, mk, m in self._list(foldername, reverse, since):
try:
print(json.dumps({
'folder': folder.folder or foldername or "INBOX",
'key': "%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
'date': str(m.date),
"flags": m.get_flags(),
'from': fromval(m.get_from()),
'subject': re.sub("\n|\'|\"", _escape, m.get_subject() or "")
}), file=stream)
except IOError as e:
if e.errno == errno.EPIPE:
# Broken pipe we can ignore
return
self.logger.exception("whoops!")
except Exception as e:
self.logger.exception("whoops!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lsfolders(self, stream=sys.stdout):
"""List the subfolders""" |
for f in self.folder.folders():
print(f.folder.strip("."), file=stream) |
<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, msgid):
"""Yields the message header against each part from the message.""" |
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
# Now look up the message
msg = folder[msgkey]
msg.is_seen = True
hdr = list(msg.items())
for p in msg.walk():
yield hdr,p
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 gettext(self, msgid, stream=sys.stdout, splitter="--text follows this line--\n"):
"""Get the first text part we can find and print it as a message. This is a simple cowpath, most of the time you want the first plain part. 'msgid' is the message to be used 'stream' is printed to with the header, splitter, first-textpart 'splitter' is text used to split the header from the body, Emacs uses this """ |
for hdr,part in self._get(msgid):
if part.get_content_type() == "text/plain":
for name,val in hdr:
# Use the subtype, since we're printing just that - tidy it up first
if name.lower() == "content-type":
val = part["content-type"]
val = " ".join([l.strip() for l in val.split("\n")])
print("%s: %s" % (name,val), file=stream)
print(splitter, file=stream)
payload = part.get_payload(decode=True)
# There seems to be a problem with the parser not doing charsets for parts
chartype = part.get_charset() \
or _get_charset(part.get("Content-Type", "")) \
or "us-ascii"
print(payload.decode(chartype), file=stream)
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrawpart(self, msgid, stream=sys.stdout):
"""Get the first part from the message and print it raw. """ |
for hdr, part in self._get(msgid):
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream)
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrawpartid(self, msgid, partid, stream=sys.stdout):
"""Get a specific part from the message and print it raw. """ |
parts = [part for hdr,part in self._get(msgid)]
part = parts[int(partid)]
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getraw(self, msgid, stream=sys.stdout):
"""Get the whole message and print it. """ |
foldername, msgkey = msgid.split(SEPERATOR)
folder = self.folder if foldername == "INBOX" else self._getfolder(foldername)
msg = folder[msgkey]
print(msg.content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getstruct(self, msgid, as_json=False, stream=sys.stdout):
"""Get and print the whole message. as_json indicates whether to print the part list as JSON or not. """ |
parts = [part.get_content_type() for hdr, part in self._get(msgid)]
if as_json:
print(json.dumps(parts), file=stream)
else:
for c in parts:
print(c, file=stream) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_alphabet(self, grammar):
""" Extract an alphabet from the given grammar. """ |
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal])
self.alphabet = list(alphabet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def action(self, column=None, value=None, **kwargs):
""" The underlying GICS table provides codes and descriptions identifying the current status or disposition of a grant project. """ |
return self._resolve_call('GIC_ACTION', column, value, **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 applicant(self, column=None, value=None, **kwargs):
""" Find the applicant information for a grant. """ |
return self._resolve_call('GIC_APPLICANT', column, value, **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 authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes.""" |
return self._resolve_call('GIC_AUTHORITY', column, value, **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 construction(self, column=None, value=None, **kwargs):
""" Identifies monetary, descriptive, and milestone information for Wastewater Treatment construction grants. """ |
return self._resolve_call('GIC_CONSTRUCTION', column, value, **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 eligible_cost(self, column=None, value=None, **kwargs):
""" The assistance dollar amounts by eligible cost category. """ |
return self._resolve_call('GIC_ELIGIBLE_COST', column, value, **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 grant(self, column=None, value=None, **kwargs):
""" Provides various award, project, and grant personnel information. """ |
return self._resolve_call('GIC_GRANT', column, value, **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 grant_assistance(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and assistance.""" |
return self._resolve_call('GIC_GRANT_ASST_PGM', column, value, **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 grant_authority(self, column=None, value=None, **kwargs):
"""Many-to-many table connecting grants and authority.""" |
return self._resolve_call('GIC_GRANT_AUTH', column, value, **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 lab_office(self, column=None, value=None, **kwargs):
"""Abbreviations, names, and locations of labratories and offices.""" |
return self._resolve_call('GIC_LAB_OFFICE', column, value, **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 milestone(self, column=None, value=None, **kwargs):
""" Status codes and related dates of certain grants, """ |
return self._resolve_call('GIC_MILESTONE', column, value, **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 record_type(self, column=None, value=None, **kwargs):
""" Codes and descriptions indicating whether an award is for a new project or for the continuation of a currently funded one. """ |
return self._resolve_call('GIC_RECORD_TYPE', column, value, **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 srf_cap(self, column=None, value=None, **kwargs):
""" Fiscal dollar amounts for State Revolving Fund Capitalization Grants. """ |
return self._resolve_call('GIC_SRF_CAP', column, value, **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 status(self, column=None, value=None, **kwargs):
""" Provides codes and descriptions of project milestones. """ |
return self._resolve_call('GIC_STATUS', column, value, **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 recRemoveTreeFormating(element):
"""Removes whitespace characters, which are leftovers from previous xml formatting. :param element: an instance of lxml.etree._Element str.strip() is applied to the "text" and the "tail" attribute of the element and recursively to all child elements. """ |
children = element.getchildren()
if len(children) > 0:
for child in children:
recRemoveTreeFormating(child)
if element.text is not None:
if len(element.text.strip()) == 0:
element.text = None
else:
element.text = element.text.strip()
if element.tail is not None:
if len(element.tail.strip()) == 0:
element.tail = None
else:
element.tail = element.tail.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all child elements. :param oldelement: an instance of lxml.etree._Element :returns: a copy of the "oldelement" .. warning:: doesn't copy ``.text`` or ``.tail`` of xml elements """ |
newelement = ETREE.Element(oldelement.tag, oldelement.attrib)
if len(oldelement.getchildren()) > 0:
for childelement in oldelement.getchildren():
newelement.append(recCopyElement(childelement))
return newelement |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getParam(xmlelement):
"""Converts an mzML xml element to a param tuple. :param xmlelement: #TODO docstring :returns: a param tuple or False if the xmlelement is not a parameter ('userParam', 'cvParam' or 'referenceableParamGroupRef') """ |
elementTag = clearTag(xmlelement.tag)
if elementTag in ['userParam', 'cvParam', 'referenceableParamGroupRef']:
if elementTag == 'cvParam':
param = cvParamFromDict(xmlelement.attrib)
elif elementTag == 'userParam':
param = userParamFromDict(xmlelement.attrib)
else:
param = refParamGroupFromDict(xmlelement.attrib)
else:
param = False
return param |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xmlAddParams(parentelement, params):
"""Generates new mzML parameter xml elements and adds them to the 'parentelement' as xml children elements. :param parentelement: :class:`xml.etree.Element`, an mzML element :param params: a list of mzML parameter tuples ('cvParam', 'userParam' or 'referencableParamGroup') """ |
if not params:
return None
for param in params:
if len(param) == 3:
cvAttrib = {'cvRef': param[0].split(':')[0], 'accession': param[0],
'name':oboTranslator.getNameWithId(param[0])
}
if param[1]:
cvAttrib.update({'value': param[1]})
else:
cvAttrib.update({'value': ''})
if param[2]:
unitName = oboTranslator.getNameWithId(param[2])
cvAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0],
'unitName': unitName
})
paramElement = ETREE.Element('cvParam', **cvAttrib)
elif len(param) == 4:
userAttrib = {'name': param[0]}
if param[1]:
userAttrib.update({'value': param[1]})
else:
userAttrib.update({'value': ''})
if param[2]:
userAttrib.update({'unitAccession': param[2],
'unitCvRef': param[2].split(':')[0]
})
if param[3]:
userAttrib.update({'type': param[3]})
paramElement = ETREE.Element('userParam', **userAttrib)
elif param[0] == 'ref':
refAttrib = {'ref': param[1]}
paramElement = ETREE.Element('referenceableParamGroupRef',
**refAttrib
)
parentelement.append(paramElement) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpretBitEncoding(bitEncoding):
"""Returns a floattype string and a numpy array type. :param bitEncoding: Must be either '64' or '32' :returns: (floattype, numpyType) """ |
if bitEncoding == '64':
floattype = 'd' # 64-bit
numpyType = numpy.float64
elif bitEncoding == '32':
floattype = 'f' # 32-bit
numpyType = numpy.float32
else:
errorText = ''.join(['bitEncoding \'', bitEncoding, '\' not defined. ',
'Must be \'64\' or \'32\''
])
raise TypeError(errorText)
return (floattype, numpyType) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_partition_function(mass, omega_array, temperature_array):
""" Calculates the partition function of your system at each point in time. Parameters mass : float The mass of the particle in kg omega_array : array array which represents omega at every point in your time trace and should therefore have the same length as the Hamiltonian temperature_array : array array which represents the temperature at every point in your time trace and should therefore have the same length as the Hamiltonian Returns: ------- Partition function : array The Partition Function at every point in time over a given trap-frequency and temperature change. """ |
Kappa_t= mass*omega_array**2
return _np.sqrt(4*_np.pi**2*_scipy.constants.Boltzmann**2*temperature_array**2/(mass*Kappa_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 calc_mean_and_variance_of_variances(self, NumberOfOscillations):
""" Calculates the mean and variance of a set of varainces. This set is obtained by splitting the timetrace into chunks of points with a length of NumberOfOscillations oscillations. Parameters NumberOfOscillations : int The number of oscillations each chunk of the timetrace used to calculate the variance should contain. Returns ------- Mean : float Variance : float """ |
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1)
return _np.mean(SnippetsVariances), _np.var(SnippetsVariances) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_template_directory(kb_app: kb, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames=List[str], ):
""" Add this resource's templates dir to template paths """ |
template_bridge = sphinx_app.builder.templates
actions = ResourceAction.get_callbacks(kb_app)
for action in actions:
f = os.path.dirname(inspect.getfile(action))
template_bridge.loaders.append(SphinxFileSystemLoader(f)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_directives(kb_app: kb, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames=List[str], ):
""" For each resource type, register a new Sphinx directive """ |
for k, v in list(kb_app.config.resources.items()):
sphinx_app.add_directive(k, ResourceDirective) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stamp_title(kb_app: kb, sphinx_app: Sphinx, doctree: doctree):
""" Walk the tree and extra RST title into resource.title """ |
# First, find out which resource this is. Won't be easy.
resources = sphinx_app.env.resources
confdir = sphinx_app.confdir
source = PurePath(doctree.attributes['source'])
# Get the relative path inside the docs dir, without .rst, then
# get the resource
docname = str(source.relative_to(confdir)).split('.rst')[0]
resource = resources.get(docname)
if resource:
# Stamp the title on the resource
title = get_rst_title(doctree)
resource.title = title |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exception(error):
"""Simple method for handling exceptions raised by `PyBankID`. :param flask_pybankid.FlaskPyBankIDError error: The exception to handle. :return: The exception represented as a dictionary. :rtype: dict """ |
response = jsonify(error.to_dict())
response.status_code = error.status_code
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 create_from_pybankid_exception(cls, exception):
"""Class method for initiating from a `PyBankID` exception. :param bankid.exceptions.BankIDError exception: :return: The wrapped exception. :rtype: :py:class:`~FlaskPyBankIDError` """ |
return cls(
"{0}: {1}".format(exception.__class__.__name__, str(exception)),
_exception_class_to_status_code.get(exception.__class__),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
"""Create a dict representation of this exception. :return: The dictionary representation. :rtype: dict """ |
rv = dict(self.payload or ())
rv["message"] = self.message
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def integers(num, minimum, maximum, base=10):
# TODO: Ensure numbers within bounds """Random integers within specified interval. The integer generator generates truly random integers in the specified interval. Parameters num : int, bounds=[1, 1E4] Total number of integers in returned array. minimum : int, bounds=[-1E9, 1E9] Minimum value (inclusive) of returned integers. maximum : int, bounds=[-1E9, 1E9] Maximum value (inclusive) of returned integers. base: int, values=[2, 8, 10, 16], default=10 Base used to print numbers in array, the default is decimal representation (base=10). Returns ------- integers : array A 1D numpy array containing integers between the specified bounds. Examples -------- Generate an array of 10 integers with values between -100 and 100, inclusive: A coin toss, where heads=1 and tails=0, with multiple flips (flips should be an odd number):
""" |
function = 'integers'
num, minimum, maximum = list(map(int, [num, minimum, maximum]))
# INPUT ERROR CHECKING
# Check input values are within range
if (1 <= num <= 10 ** 4) is False:
print('ERROR: %s is out of range' % num)
return
if (-10 ** 9 <= minimum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % minimum)
return
if (-10 ** 9 <= maximum <= 10 ** 9) is False:
print('ERROR: %s is out of range' % maximum)
return
if maximum < minimum:
print('ERROR: %s is less than %s' % (maximum, minimum))
return
base = int(base)
if base not in [2, 8, 10, 16]:
raise Exception('Base not in range!')
opts = {'num': num,
'min': minimum,
'max': maximum,
'col': 1,
'base': base,
'format': 'plain',
'rnd': 'new'}
integers = get_http(RANDOM_URL, function, opts)
integers_arr = str_to_arr(integers)
return integers_arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sequence(minimum, maximum):
"""Randomize a sequence of integers.""" |
function = 'sequences'
opts = {'min': minimum,
'max': maximum,
'col': 1,
'format': 'plain',
'rnd': 'new'}
deal = get_http(RANDOM_URL, function, opts)
deal_arr = str_to_arr(deal)
return deal_arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string(num, length, digits=False, upper=True, lower=True, unique=False):
"""Random strings.""" |
function = 'strings'
# Convert arguments to random.org style
# for a discussion on the method see: http://bit.ly/TKGkOF
digits = convert(digits)
upper = convert(upper)
lower = convert(lower)
unique = convert(unique)
opts = {'num': num,
'len': length,
'digits': digits,
'upperalpha': upper,
'loweralpha': lower,
'format': 'plain',
'rnd': 'new'}
seq = get_http(RANDOM_URL, function, opts)
seq = seq.strip().split('\n') # convert to list
# seq_arr = str_to_arr(seq)
return 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 quota(ip=None):
"""Check your quota.""" |
# TODO: Add arbitrary user defined IP check
url = 'http://www.random.org/quota/?format=plain'
data = urlopen(url)
credit = int(data.read().strip())
if data.code == 200:
return credit
else:
return "ERROR: Server responded with code %s" % data.code |
<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_http(base_url, function, opts):
"""HTTP request generator.""" |
url = (os.path.join(base_url, function) + '/?' + urlencode(opts))
data = urlopen(url)
if data.code != 200:
raise ValueError("Random.rg returned server code: " + str(data.code))
return data.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(*p):
"""Build a file path from paths and return the contents.""" |
with open(os.path.join(*p), 'r') as fi:
return fi.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, processProtocol, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Form a command and start a process in the desired environment. """ |
raise NotImplementedError() |
<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, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and return the results of the completed run. """ |
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
d = defer.maybeDeferred(self.execute, processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
d.addErrback(deferred.errback)
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getOutput(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and get the output of the finished process. """ |
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env,
path, uid, gid, usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
stdout, _stderr, _returnCode = tuple_
return stdout
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getExitCode(self, command, env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None):
"""Execute a command and get the return code of the finished process. """ |
deferred = defer.Deferred()
processProtocol = _SummaryProcessProtocol(deferred)
self.execute(processProtocol, command, env, path, uid, gid,
usePTY, childFDs)
@deferred.addCallback
def getStdOut(tuple_):
_stdout, _stderr, exitCode = tuple_
return exitCode
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_task(original_task):
""" Validates task and adds default values for missing options using the following steps. 1. If there is no input list specified or if it is None, the input spec is assumed to be ['*']. 2. If there are not outputs specified, or if the output spec is None or an empty list, the output spec is assumed to be ['*']. 3. If the input or output spec is not iterable, they are converted into single element tuples. If they are any iterable, they are converted into tuples. 4. The task['fn'] option must be callable. 5. If number of outputs is more than one, task['fn'] must be a generator function. 6. Generator functions are not supported for output spec of '*'. Returns new task with updated options """ |
task = original_task._asdict()
# Default values for inputs and outputs
if 'inputs' not in task or task['inputs'] is None:
task['inputs'] = ['*']
# Outputs list cannot be empty
if ('outputs' not in task or
task['outputs'] is None or
len(task['outputs']) == 0):
task['outputs'] = ['*']
# Convert to tuples (even for single values)
if not hasattr(task['inputs'], '__iter__') or isinstance(task['inputs'], str):
task['inputs'] = (task['inputs'],)
else:
task['inputs'] = tuple(task['inputs'])
if not hasattr(task['outputs'], '__iter__') or isinstance(task['outputs'], str):
task['outputs'] = (task['outputs'],)
else:
task['outputs'] = tuple(task['outputs'])
if not callable(task['fn']):
raise TypeError('Task function must be a callable object')
if (len(task['outputs']) > 1 and
not inspect.isgeneratorfunction(task['fn'])):
raise TypeError('Multiple outputs are only supported with \
generator functions')
if inspect.isgeneratorfunction(task['fn']):
if task['outputs'][0] == '*':
raise TypeError('Generator functions cannot be used for tasks with \
output specification "*"')
return Task(**task) |
<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_task(task, workspace):
""" Runs the task and updates the workspace with results. Parameters task - dict Task Description Examples: {'task': task_func, 'inputs': ['a', 'b'], 'outputs': 'c'} {'task': task_func, 'inputs': '*', 'outputs': '*'} {'task': task_func, 'inputs': ['*','a'], 'outputs': 'b'} Returns a new workspace with results """ |
data = copy.copy(workspace)
task = validate_task(task)
# Prepare input to task
inputs = [input_parser(key, data) for key in task.inputs]
if inspect.isgeneratorfunction(task.fn):
# Multiple output task
# Assuming number of outputs are equal to number of return values
data.update(zip(task.outputs, task.fn(*inputs)))
else:
# Single output task
results = task.fn(*inputs)
if task.outputs[0] != '*':
results = {task.outputs[0]: results}
elif not isinstance(results, dict):
raise TypeError('Result should be a dict for output type *')
data.update(results)
return 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 run_hook(name, workspace, hooks):
"""Runs all hooks added under the give name. Parameters name - str Name of the hook to invoke workspace - dict Workspace that the hook functions operate on hooks - dict of lists Mapping with hook names and callback functions """ |
data = copy.copy(workspace)
for hook_listener in hooks.get(name, []):
# Hook functions may mutate the data and returns nothing
hook_listener(data)
return 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 add_task(self, fn, inputs=None, outputs=None):
""" Adds a task to the workflow. Returns self to facilitate chaining method calls """ |
# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs})
self.tasks.append(Task(fn, inputs, outputs))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_hook(self, name, function):
""" Adds a function to be called for hook of a given name. The function gets entire workspace as input and does not return anything. Example: def hook_fcn(workspace):
pass """ |
if not callable(function):
return ValueError('Hook function should be callable')
if name not in self.hooks:
self.hooks[name] = []
self.hooks[name].append(function)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dns(self):
"""DNS details.""" |
dns = {
'elb': self.dns_elb(),
'elb_region': self.dns_elb_region(),
'global': self.dns_global(),
'region': self.dns_region(),
'instance': self.dns_instance(),
}
return dns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def s3_app_bucket(self, include_region=False):
"""Generate s3 application bucket name. Args: include_region (bool):
Include region in the name generation. """ |
if include_region:
s3_app_bucket = self.format['s3_app_region_bucket'].format(**self.data)
else:
s3_app_bucket = self.format['s3_app_bucket'].format(**self.data)
return s3_app_bucket |
<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_s3_app_bucket(self, include_region=False):
"""Generate shared s3 application bucket name. Args: include_region (bool):
Include region in the name generation. """ |
if include_region:
shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].format(**self.data)
else:
shared_s3_app_bucket = self.format['shared_s3_app_bucket'].format(**self.data)
return shared_s3_app_bucket |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iam(self):
"""Generate iam details.""" |
iam = {
'group': self.format['iam_group'].format(**self.data),
'lambda_role': self.format['iam_lambda_role'].format(**self.data),
'policy': self.format['iam_policy'].format(**self.data),
'profile': self.format['iam_profile'].format(**self.data),
'role': self.format['iam_role'].format(**self.data),
'user': self.format['iam_user'].format(**self.data),
'base': self.format['iam_base'].format(**self.data),
}
return iam |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def archaius(self):
"""Generate archaius bucket path.""" |
bucket = self.format['s3_bucket'].format(**self.data)
path = self.format['s3_bucket_path'].format(**self.data)
archaius_name = self.format['s3_archaius_name'].format(**self.data)
archaius = {'s3': archaius_name, 'bucket': bucket, 'path': path}
return archaius |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jenkins(self):
"""Generate jenkins job details.""" |
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gitlab(self):
"""Generate gitlab details.""" |
main_name = self.format['git_repo'].format(**self.data)
qe_name = self.format['git_repo_qe'].format(**self.data)
config_name = self.format['git_repo_configs'].format(**self.data)
git = {
'config': config_name,
'main': main_name,
'qe': qe_name,
}
return git |
<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_value_matched_by_regex(field_name, regex_matches, string):
"""Ensure value stored in regex group exists.""" |
try:
value = regex_matches.group(field_name)
if value is not None:
return value
except IndexError:
pass
raise MissingFieldError(string, field_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 positive_int(val):
"""Parse `val` into a positive integer.""" |
if isinstance(val, float):
raise ValueError('"{}" must not be a float'.format(val))
val = int(val)
if val >= 0:
return val
raise ValueError('"{}" must be positive'.format(val)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strictly_positive_int_or_none(val):
"""Parse `val` into either `None` or a strictly positive integer.""" |
val = positive_int_or_none(val)
if val is None or val > 0:
return val
raise ValueError('"{}" must be strictly positive'.format(val)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary. :param attributeLines: a list of obo 'Term' lines. Each line contains a key and a value part which are separated by a ':'. :return: a dictionary containing the attributes of an obo 'Term' entry. NOTE: Some attributes can occur multiple times in one single term, for example 'is_a' or 'relationship'. However, currently only the last occurence is stored. """ |
attributes = dict()
for line in attributeLines:
attributeId, attributeValue = line.split(':', 1)
attributes[attributeId.strip()] = attributeValue.strip()
return attributes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _termIsObsolete(oboTerm):
"""Determine wheter an obo 'Term' entry is marked as obsolete. :param oboTerm: a dictionary as return by :func:`maspy.ontology._attributeLinesToDict()` :return: bool """ |
isObsolete = False
if u'is_obsolete' in oboTerm:
if oboTerm[u'is_obsolete'].lower() == u'true':
isObsolete = True
return isObsolete |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discover_handler_classes(handlers_package):
""" Looks for handler classes within handler path module. Currently it's not looking deep into nested module. :param handlers_package: module path to handlers :type handlers_package: string :return: list of handler classes """ |
if handlers_package is None:
return
# Add working directory into PYTHONPATH to import developer packages
sys.path.insert(0, os.getcwd())
package = import_module(handlers_package)
# Continue searching for module if package is not a module
if hasattr(package, '__path__'):
for _, modname, _ in pkgutil.iter_modules(package.__path__):
import_module('{package}.{module}'.format(package=package.__name__, module=modname))
return registered_handlers |
<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_multi_word_keywords(features):
"""This returns an OrderedDict containing the multi word keywords in order of length. This is so the tokenizer will match the longer matches before the shorter matches """ |
keys = {
'is not': Token(TokenTypes.NOT_EQUAL, 'is not'),
}
return OrderedDict(sorted(list(keys.items()), key=lambda t: len(t[0]), reverse=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 inside_try(func, options={}):
""" decorator to silence exceptions, for logging we want a "safe" fail of the functions """ |
if six.PY2:
name = func.func_name
else:
name = func.__name__
@wraps(func)
def silenceit(*args, **kwargs):
""" the function func to be silenced is wrapped inside a
try catch and returned, exceptions are logged
exceptions are returned in an error dict
takes all kinds of arguments and passes to the original func
"""
excpt = None
try:
return func(*args, **kwargs)
# pylint: disable=W0703
# inside_try.silenceit: Catching too general exception Exception
# that's the idea!
except Exception as excpt:
# first tell the object in charge
if 'ctx' in kwargs:
ctx = kwargs['ctx']
else:
# otherwise tell object defined in options
# if we can be sure there is a context
ctx = get_try_option(None, 'ctx')
if not ctx:
# tell a new object
ctx = Bubble('Inside Try')
# ctx.set_verbose(100); #todo: move to magic
head = name + ': silenced function inside_try:Error:'
if get_try_option(ctx, 'count_it'):
ctx.gbc.cry(head + 'counting')
if get_try_option(ctx, 'print_it'):
ctx.gbc.cry(head + 'printing:' + str(excpt))
if get_try_option(ctx, 'print_args'):
ctx.gbc.cry(head + 'printing ak:' + str(excpt))
ctx.gbc.cry('args', stuff=args)
ctx.gbc.cry('kwargs', stuff=kwargs)
if get_try_option(ctx, 'inspect_it'):
ctx.gbc.cry(head + 'inspecting:', stuff=excpt)
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'log_it'):
ctx.gbc.cry(head + 'logging')
for s in inspect.stack():
ctx.gbc.cry(head + ':stack:', stuff=s)
if get_try_option(ctx, 'reraise_it'):
ctx.gbc.cry(head + 'reraising')
raise excpt
# always return error
return {'error': str(excpt),
'silenced': name,
'args': args,
'kwargs': kwargs}
return silenceit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start the server and run forever. """ |
Server().start(self.options,self.handler_function, self.__class__.component_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 sort_entries(self):
"""Get whether reverse is True or False. Return the sorted data.""" |
return sorted(self.data, key=self.sort_func, reverse=self.get_reverse()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visible_fields(self):
""" Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fieldset, all visible fields minus the excluded fields will be returned. :return: List of bound field instances or empty tuple. """ |
form_visible_fields = self.form.visible_fields()
if self.render_fields:
fields = self.render_fields
else:
fields = [field.name for field in form_visible_fields]
filtered_fields = [field for field in fields if field not in self.exclude_fields]
return [field for field in form_visible_fields if field.name in filtered_fields] |
<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_fieldsets(self, fieldsets=None):
""" This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to generate fieldsets for. If no fieldsets argument is passed, the class property ``fieldsets`` is used. When generating the fieldsets, the method ensures that at least one fielset will be the primary fieldset which is responsible for rendering the non field errors and hidden fields. :param fieldsets: Alternative set of fieldset kwargs. If passed this set is prevered of the ``fieldsets`` property of the form. :return: generator which yields fieldset instances. """ |
fieldsets = fieldsets or self.fieldsets
if not fieldsets:
raise StopIteration
# Search for primary marker in at least one of the fieldset kwargs.
has_primary = any(fieldset.get('primary') for fieldset in fieldsets)
for fieldset_kwargs in fieldsets:
fieldset_kwargs = copy.deepcopy(fieldset_kwargs)
fieldset_kwargs['form'] = self
if not has_primary:
fieldset_kwargs['primary'] = True
has_primary = True
yield self.get_fieldset(**fieldset_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 get_chunks(Array, Chunksize):
"""Generator that yields chunks of size ChunkSize""" |
for i in range(0, len(Array), Chunksize):
yield Array[i:i + Chunksize] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_data_from_bin_file(fileName):
""" Loads the binary data stored in the a binary file and extracts the data for each channel that was saved, along with the sample rate and length of the data array. Parameters fileContent : bytes bytes object containing the data from a .bin file exported from the saleae data logger. Returns ------- ChannelData : list List containing a list which contains the data from each channel LenOf1Channel : int The length of the data in each channel NumOfChannels : int The number of channels saved SampleTime : float The time between samples (in seconds) SampleRate : float The sample rate (in Hz) """ |
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
(ChannelData, LenOf1Channel,
NumOfChannels, SampleTime) = read_data_from_bytes(fileContent)
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_data_from_bytes(fileContent):
""" Takes the binary data stored in the binary string provided and extracts the data for each channel that was saved, along with the sample rate and length of the data array. Parameters fileContent : bytes bytes object containing the data from a .bin file exported from the saleae data logger. Returns ------- ChannelData : list List containing a list which contains the data from each channel LenOf1Channel : int The length of the data in each channel NumOfChannels : int The number of channels saved SampleTime : float The time between samples (in seconds) SampleRate : float The sample rate (in Hz) """ |
TotalDataLen = struct.unpack('Q', fileContent[:8])[0] # Unsigned long long
NumOfChannels = struct.unpack('I', fileContent[8:12])[0] # unsigned Long
SampleTime = struct.unpack('d', fileContent[12:20])[0]
AllChannelData = struct.unpack("f" * ((len(fileContent) -20) // 4), fileContent[20:])
# ignore the heading bytes (= 20)
# The remaining part forms the body, to know the number of bytes in the body do an integer division by 4 (since 4 bytes = 32 bits = sizeof(float)
LenOf1Channel = int(TotalDataLen/NumOfChannels)
ChannelData = list(get_chunks(AllChannelData, LenOf1Channel))
return ChannelData, LenOf1Channel, NumOfChannels, SampleTime |
<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_coord_box(centre_x, centre_y, distance):
"""Get the square boundary coordinates for a given centre and distance""" |
"""Todo: return coordinates inside a circle, rather than a square"""
return {
'top_left': (centre_x - distance, centre_y + distance),
'top_right': (centre_x + distance, centre_y + distance),
'bottom_left': (centre_x - distance, centre_y - distance),
'bottom_right': (centre_x + distance, centre_y - distance),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False):
""" Calculate the time taken to construct a given fleet """ |
unit_weights = {
UNIT_SCOUT: 1,
UNIT_DESTROYER: 13,
UNIT_BOMBER: 10,
UNIT_CRUISER: 85,
UNIT_STARBASE: 1,
}
govt_weight = 80 if is_dict else 100
prod_weight = 85 if is_techno else 100
weighted_qty = unit_weights[unit_type] * quantity
ttb = (weighted_qty * govt_weight * prod_weight) * (2 * factories)
# TTB is 66% longer with stasis enabled
return ttb + (ttb * 0.66) if stasis_enabled else ttb |
<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_fasta(data):
# pragma: no cover """ Load sequences in Fasta format. This generator function yields a Sequence object for each sequence record in a GFF3 file. Implementation stolen shamelessly from http://stackoverflow.com/a/7655072/459780. """ |
name, seq = None, []
for line in data:
line = line.rstrip()
if line.startswith('>'):
if name:
yield Sequence(name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name:
yield Sequence(name, ''.join(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 _reset(self):
"""Clear internal data structure.""" |
self.records = list()
self.featsbyid = dict()
self.featsbyparent = dict()
self.countsbytype = dict() |
<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_by_label(self, label):
""" Return the first item with a specific label, or None. """ |
return next((x for x in self if x.label == label), 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 getGenericAnswers(self, name, instruction, prompts):
"""Called when the server requests keyboard interactive authentication """ |
responses = []
for prompt, _echo in prompts:
password = self.getPassword(prompt)
responses.append(password)
return defer.succeed(responses) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pairwise(iterable):
""" Generate consecutive pairs of elements from the given iterable. """ |
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return
for element in iterator:
yield first, element
first = 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 https_policy_from_config(config):
""" Create an ``IPolicyForHTTPS`` which can authenticate a Kubernetes API server. :param KubeConfig config: A Kubernetes configuration containing an active context identifying a cluster. The resulting ``IPolicyForHTTPS`` will authenticate the API server for that cluster. :return IPolicyForHTTPS: A TLS context which requires server certificates signed by the certificate authority certificate associated with the active context's cluster. """ |
server = config.cluster["server"]
base_url = URL.fromText(native_string_to_unicode(server))
ca_certs = pem.parse(config.cluster["certificate-authority"].bytes())
if not ca_certs:
raise ValueError("No certificate authority certificate found.")
ca_cert = ca_certs[0]
try:
# Validate the certificate so we have early failures for garbage data.
ssl.Certificate.load(ca_cert.as_bytes(), FILETYPE_PEM)
except OpenSSLError as e:
raise ValueError(
"Invalid certificate authority certificate found.",
str(e),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={},
trust_roots={
netloc: ca_cert,
},
)
return policy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate_with_certificate_chain(reactor, base_url, client_chain, client_key, ca_cert):
""" Create an ``IAgent`` which can issue authenticated requests to a particular Kubernetes server using a client certificate. :param reactor: The reactor with which to configure the resulting agent. :param twisted.python.url.URL base_url: The base location of the Kubernetes API. :param list[pem.Certificate] client_chain: The client certificate (and chain, if applicable) to use. :param pem.Key client_key: The private key to use with the client certificate. :param pem.Certificate ca_cert: The certificate authority to respect when verifying the Kubernetes server certificate. :return IAgent: An agent which will authenticate itself to a particular Kubernetes server and which will verify that server or refuse to interact with it. """ |
if base_url.scheme != u"https":
raise ValueError(
"authenticate_with_certificate() makes sense for HTTPS, not {!r}".format(
base_url.scheme
),
)
netloc = NetLocation(host=base_url.host, port=base_url.port)
policy = ClientCertificatePolicyForHTTPS(
credentials={
netloc: TLSCredentials(
chain=Chain(certificates=Certificates(client_chain)),
key=client_key,
),
},
trust_roots={
netloc: ca_cert,
},
)
return Agent(reactor, contextFactory=policy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
""" See ``authenticate_with_certificate_chain``. :param pem.Certificate client_cert: The client certificate to use. """ |
return authenticate_with_certificate_chain(
reactor, base_url, [client_cert], client_key, ca_cert,
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.