_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q37700
matchToString
train
def matchToString(aaMatch, read1, read2, indent='', offsets=None): """ Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of ...
python
{ "resource": "" }
q37701
compareAaReads
train
def compareAaReads(read1, read2, gapChars='-', offsets=None): """ Compare two amino acid sequences. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param gapChars: An object supporting __contains__ ...
python
{ "resource": "" }
q37702
parseColors
train
def parseColors(colors, args): """ Parse read id color specification. @param colors: A C{list} of C{str}s. Each item is of the form, e.g., 'green X Y Z...', where each of X, Y, Z, ... etc. is either a read id or the name of a FASTA or FASTQ file containing reads whose ids should be ...
python
{ "resource": "" }
q37703
download_release
train
def download_release(download_file, release=None): """Downloads the "go-basic.obo" file for the specified release.""" if release is None: release = get_latest_release() url = 'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo' % release #download_file = 'go-basic_%s....
python
{ "resource": "" }
q37704
get_current_ontology_date
train
def get_current_ontology_date(): """Get the release date of the current Gene Ontolgo release.""" with closing(requests.get( 'http://geneontology.org/ontology/go-basic.obo', stream=True)) as r: for i, l in enumerate(r.iter_lines(decode_unicode=True)): if i == 1: ...
python
{ "resource": "" }
q37705
execute
train
def execute(function, name): """ Execute a task, returning a TaskResult """ try: return TaskResult(name, True, None, function()) except Exception as exc: return TaskResult(name, False, exc, None)
python
{ "resource": "" }
q37706
truncatechars
train
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: return...
python
{ "resource": "" }
q37707
get_gtf_argument_parser
train
def get_gtf_argument_parser(desc, default_field_name='gene'): """Return an argument parser with basic options for reading GTF files. Parameters ---------- desc: str Description of the ArgumentParser default_field_name: str, optional Name of field in GTF file to look for. Return...
python
{ "resource": "" }
q37708
jsonresolver_loader
train
def jsonresolver_loader(url_map): """JSON resolver plugin that loads the schema endpoint. Injected into Invenio-Records JSON resolver. """ from flask import current_app from . import current_jsonschemas url_map.add(Rule( "{0}/<path:path>".format(current_app.config['JSONSCHEMAS_ENDPOINT'...
python
{ "resource": "" }
q37709
merge_layouts
train
def merge_layouts(layouts): ''' Utility function for merging multiple layouts. Args: layouts (list): A list of BIDSLayout instances to merge. Returns: A BIDSLayout containing merged files and entities. Notes: Layouts will be merged in the order of the elements in the list. I.e.,...
python
{ "resource": "" }
q37710
File.copy
train
def copy(self, path_patterns, symbolic_link=False, root=None, conflicts='fail'): ''' Copy the contents of a file to a new location, with target filename defined by the current File's entities and the specified path_patterns. ''' new_filename = build_path(self.entities, path_...
python
{ "resource": "" }
q37711
Entity.match_file
train
def match_file(self, f, update_file=False): """ Determine whether the passed file matches the Entity. Args: f (File): The File instance to match against. Returns: the matched value if a match was found, otherwise None. """ if self.map_func is not None: ...
python
{ "resource": "" }
q37712
Layout._get_or_load_domain
train
def _get_or_load_domain(self, domain): ''' Return a domain if one already exists, or create a new one if not. Args: domain (str, dict): Can be one of: - The name of the Domain to return (fails if none exists) - A path to the Domain configuration file ...
python
{ "resource": "" }
q37713
Layout._check_inclusions
train
def _check_inclusions(self, f, domains=None): ''' Check file or directory against regexes in config to determine if it should be included in the index ''' filename = f if isinstance(f, six.string_types) else f.path if domains is None: domains = list(self.domains.values(...
python
{ "resource": "" }
q37714
Layout._find_entity
train
def _find_entity(self, entity): ''' Find an Entity instance by name. Checks both name and id fields.''' if entity in self.entities: return self.entities[entity] _ent = [e for e in self.entities.values() if e.name == entity] if len(_ent) > 1: raise ValueError("Enti...
python
{ "resource": "" }
q37715
Layout.save_index
train
def save_index(self, filename): ''' Save the current Layout's index to a .json file. Args: filename (str): Filename to write to. Note: At the moment, this won't serialize directory-specific config files. This means reconstructed indexes will only work properly in ca...
python
{ "resource": "" }
q37716
Layout.load_index
train
def load_index(self, filename, reindex=False): ''' Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every fil...
python
{ "resource": "" }
q37717
Layout.add_entity
train
def add_entity(self, domain, **kwargs): ''' Add a new Entity to tracking. ''' # Set the entity's mapping func if one was specified map_func = kwargs.get('map_func', None) if map_func is not None and not callable(kwargs['map_func']): if self.entity_mapper is None: ...
python
{ "resource": "" }
q37718
Layout.count
train
def count(self, entity, files=False): """ Return the count of unique values or files for the named entity. Args: entity (str): The name of the entity. files (bool): If True, counts the number of filenames that contain at least one value of the entity, rat...
python
{ "resource": "" }
q37719
Layout.as_data_frame
train
def as_data_frame(self, **kwargs): """ Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Retur...
python
{ "resource": "" }
q37720
configure_logger
train
def configure_logger(name, log_stream=sys.stdout, log_file=None, log_level=logging.INFO, keep_old_handlers=False, propagate=False): """Configures and returns a logger. This function serves to simplify the configuration of a logger that writes to a file and/or to a ...
python
{ "resource": "" }
q37721
get_logger
train
def get_logger(name='', log_stream=None, log_file=None, quiet=False, verbose=False): """Convenience function for getting a logger.""" # configure root logger log_level = logging.INFO if quiet: log_level = logging.WARNING elif verbose: log_level = logging.DEBUG if...
python
{ "resource": "" }
q37722
start
train
def start(milliseconds, func, *args, **kwargs): """ Call function every interval. Starts the timer at call time. Although this could also be a decorator, that would not initiate the time at the same time, so would require additional work. Arguments following function will be sent to function. Not...
python
{ "resource": "" }
q37723
example_async_client
train
def example_async_client(api_client): """Example async client. """ try: pprint((yield from api_client.echo())) except errors.RequestError as exc: log.exception('Exception occurred: %s', exc) yield gen.Task(lambda *args, **kwargs: ioloop.IOLoop.current().stop())
python
{ "resource": "" }
q37724
example_sync_client
train
def example_sync_client(api_client): """Example sync client use with. """ try: pprint(api_client.echo()) except errors.RequestError as exc: log.exception('Exception occurred: %s', exc)
python
{ "resource": "" }
q37725
main
train
def main(): """Run the examples. """ logging.basicConfig(level=logging.INFO) example_sync_client(SyncAPIClient()) example_async_client(AsyncAPIClient()) io_loop = ioloop.IOLoop.current() io_loop.start()
python
{ "resource": "" }
q37726
main
train
def main(args=None): """Extract protein-coding genes and store in tab-delimited text file. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module...
python
{ "resource": "" }
q37727
IxePortsStats.read_stats
train
def read_stats(self, *stats): """ Read port statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ self.statistics = OrderedDict() for port in self.ports: port_stats = IxeStatTotal(port).get_attributes(FLAG_R...
python
{ "resource": "" }
q37728
IxeStreamsStats.read_stats
train
def read_stats(self, *stats): """ Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ from ixexplorer.ixe_stream import IxePacketGroupStream sleep_time = 0.1 # in cases we only want few counters but very f...
python
{ "resource": "" }
q37729
arbiter
train
def arbiter(rst, clk, req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None, gnt_rdy=None, ARBITER_TYPE="priority"): ''' Wrapper that provides common interface to all arbiters ''' if ARBITER_TYPE == "priority": _arb = arbiter_priority(req_vec, gnt_vec, gnt_idx, gnt_vld) elif (ARBITER_TYPE == "roundrobin...
python
{ "resource": "" }
q37730
seq_seqhash
train
def seq_seqhash(seq, normalize=True): """returns 24-byte Truncated Digest sequence `seq` >>> seq_seqhash("") 'z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXc' >>> seq_seqhash("ACGT") 'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2' >>> seq_seqhash("acgt") 'aKF498dAxcJAqme6QYQ7EZ07-fiw8Kw2' >>> seq_seqhash("acgt"...
python
{ "resource": "" }
q37731
seq_seguid
train
def seq_seguid(seq, normalize=True): """returns seguid for sequence `seq` This seguid is compatible with BioPython's seguid. >>> seq_seguid('') '2jmj7l5rSw0yVb/vlWAYkK/YBwk' >>> seq_seguid('ACGT') 'IQiZThf2zKn/I1KtqStlEdsHYDQ' >>> seq_seguid('acgt') 'IQiZThf2zKn/I1KtqStlEdsHYDQ' ...
python
{ "resource": "" }
q37732
seq_md5
train
def seq_md5(seq, normalize=True): """returns unicode md5 as hex digest for sequence `seq`. >>> seq_md5('') 'd41d8cd98f00b204e9800998ecf8427e' >>> seq_md5('ACGT') 'f1f8f4bf413b16ad135722aa4591043e' >>> seq_md5('ACGT*') 'f1f8f4bf413b16ad135722aa4591043e' >>> seq_md5(' A C G T ') 'f...
python
{ "resource": "" }
q37733
seq_sha1
train
def seq_sha1(seq, normalize=True): """returns unicode sha1 hexdigest for sequence `seq`. >>> seq_sha1('') 'da39a3ee5e6b4b0d3255bfef95601890afd80709' >>> seq_sha1('ACGT') '2108994e17f6cca9ff2352ada92b6511db076034' >>> seq_sha1('acgt') '2108994e17f6cca9ff2352ada92b6511db076034' >>> seq...
python
{ "resource": "" }
q37734
seq_sha512
train
def seq_sha512(seq, normalize=True): """returns unicode sequence sha512 hexdigest for sequence `seq`. >>> seq_sha512('') 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e' >>> seq_sha512('ACGT') '68a178f7c740c5c240aa67...
python
{ "resource": "" }
q37735
map_single_end
train
def map_single_end(credentials, instance_config, instance_name, script_dir, index_dir, fastq_file, output_dir, num_threads=None, seed_start_lmax=None, mismatch_nmax=None, multimap_nmax=None, splice_min_overhang=None, out_mult...
python
{ "resource": "" }
q37736
generate_index
train
def generate_index(credentials, instance_config, instance_name, script_dir, genome_file, output_dir, annotation_file=None, splice_overhang=100, num_threads=8, chromosome_bin_bits=18, genome_memory_limit=31000000000, self_dest...
python
{ "resource": "" }
q37737
get_file_checksums
train
def get_file_checksums(url, ftp=None): """Download and parse an Ensembl CHECKSUMS file and obtain checksums. Parameters ---------- url : str The URL of the CHECKSUM file. ftp : `ftplib.FTP` or `None`, optional An FTP connection. Returns ------- `collections.OrderedD...
python
{ "resource": "" }
q37738
listify
train
def listify(obj, ignore=(list, tuple, type(None))): ''' Wraps all non-list or tuple objects in a list; provides a simple way to accept flexible arguments. ''' return obj if isinstance(obj, ignore) else [obj]
python
{ "resource": "" }
q37739
_get_divisions
train
def _get_divisions(taxdump_file): """Returns a dictionary mapping division names to division IDs.""" with tarfile.open(taxdump_file) as tf: with tf.extractfile('division.dmp') as fh: df = pd.read_csv(fh, header=None, sep='|', encoding='ascii') # only keep division ids and names...
python
{ "resource": "" }
q37740
get_species
train
def get_species(taxdump_file, select_divisions=None, exclude_divisions=None, nrows=None): """Get a dataframe with species information.""" if select_divisions and exclude_divisions: raise ValueError('Cannot specify "select_divisions" and ' '"exclude_divisions...
python
{ "resource": "" }
q37741
IxeObject.set_attributes
train
def set_attributes(self, **attributes): """ Set group of attributes without calling set between attributes regardless of global auto_set. Set will be called only after all attributes are set based on global auto_set. :param attributes: dictionary of <attribute, value> to set. """ ...
python
{ "resource": "" }
q37742
Correios.consulta_faixa
train
def consulta_faixa(self, localidade, uf): """Consulta site e retorna faixa para localidade""" url = 'consultaFaixaCepAction.do' data = { 'UF': uf, 'Localidade': localidade.encode('cp1252'), 'cfm': '1', 'Metodo': 'listaFaixaCEP', 'TipoCo...
python
{ "resource": "" }
q37743
Correios.consulta
train
def consulta(self, endereco, primeiro=False, uf=None, localidade=None, tipo=None, numero=None): """Consulta site e retorna lista de resultados""" if uf is None: url = 'consultaEnderecoAction.do' data = { 'relaxation': endereco.encode('ISO-8859-1'...
python
{ "resource": "" }
q37744
SyncRequestEngine._request
train
def _request(self, url, *, method='GET', headers=None, data=None, result_callback=None): """Perform synchronous request. :param str url: request URL. :param str method: request method. :param object data: JSON-encodable object. :param object -> object result_cal...
python
{ "resource": "" }
q37745
SyncRequestEngine._make_session
train
def _make_session(): """Create session object. :rtype: requests.Session """ sess = requests.Session() sess.mount('http://', requests.adapters.HTTPAdapter(max_retries=False)) sess.mount('https://', requests.adapters.HTTPAdapter(max_retries=False)) return sess
python
{ "resource": "" }
q37746
fastaSubtract
train
def fastaSubtract(fastaFiles): """ Given a list of open file descriptors, each with FASTA content, remove the reads found in the 2nd, 3rd, etc files from the first file in the list. @param fastaFiles: a C{list} of FASTA filenames. @raises IndexError: if passed an empty list. @return: An ite...
python
{ "resource": "" }
q37747
SqliteIndex._addFilename
train
def _addFilename(self, filename): """ Add a new file name. @param filename: A C{str} file name. @raise ValueError: If a file with this name has already been added. @return: The C{int} id of the newly added file. """ cur = self._connection.cursor() try: ...
python
{ "resource": "" }
q37748
SqliteIndex.addFile
train
def addFile(self, filename): """ Add a new FASTA file of sequences. @param filename: A C{str} file name, with the file in FASTA format. This file must (obviously) exist at indexing time. When __getitem__ is used to access sequences, it is possible to provide a ...
python
{ "resource": "" }
q37749
SqliteIndex._find
train
def _find(self, id_): """ Find the filename and offset of a sequence, given its id. @param id_: A C{str} sequence id. @return: A 2-tuple, containing the C{str} file name and C{int} offset within that file of the sequence. """ cur = self._connection.cursor() ...
python
{ "resource": "" }
q37750
PathogenSampleFiles.writeSampleIndex
train
def writeSampleIndex(self, fp): """ Write a file of sample indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) in s...
python
{ "resource": "" }
q37751
PathogenSampleFiles.writePathogenIndex
train
def writePathogenIndex(self, fp): """ Write a file of pathogen indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) ...
python
{ "resource": "" }
q37752
ProteinGrouper._title
train
def _title(self): """ Create a title summarizing the pathogens and samples. @return: A C{str} title. """ return ( 'Overall, proteins from %d pathogen%s were found in %d sample%s.' % (len(self.pathogenNames), '' if len(self.pathogenNames) == 1...
python
{ "resource": "" }
q37753
ProteinGrouper.addFile
train
def addFile(self, filename, fp): """ Read and record protein information for a sample. @param filename: A C{str} file name. @param fp: An open file pointer to read the file's data from. @raise ValueError: If information for a pathogen/protein/sample combination is gi...
python
{ "resource": "" }
q37754
ProteinGrouper.toStr
train
def toStr(self): """ Produce a string representation of the pathogen summary. @return: A C{str} suitable for printing. """ # Note that the string representation contains much less # information than the HTML summary. E.g., it does not contain the # unique (de-dup...
python
{ "resource": "" }
q37755
SSFastaReads.iter
train
def iter(self): """ Iterate over the sequences in self.file_, yielding each as an instance of the desired read class. @raise ValueError: If the input file has an odd number of records or if any sequence has a different length than its predicted secondary structur...
python
{ "resource": "" }
q37756
npartial
train
def npartial(func, *args, **kwargs): """ Returns a partial node visitor function """ def wrapped(self, node): func(self, *args, **kwargs) return wrapped
python
{ "resource": "" }
q37757
aa3_to_aa1
train
def aa3_to_aa1(seq): """convert string of 3-letter amino acids to 1-letter amino acids >>> aa3_to_aa1("CysAlaThrSerAlaArgGluLeuAlaMetGlu") 'CATSARELAME' >>> aa3_to_aa1(None) """ if seq is None: return None return "".join(aa3_to_aa1_lut[aa3] for aa3 in [seq[i:i +...
python
{ "resource": "" }
q37758
elide_sequence
train
def elide_sequence(s, flank=5, elision="..."): """trim a sequence to include the left and right flanking sequences of size `flank`, with the intervening sequence elided by `elision`. >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 'ABCDE...VWXYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", f...
python
{ "resource": "" }
q37759
normalize_sequence
train
def normalize_sequence(seq): """return normalized representation of sequence for hashing This really means ensuring that the sequence is represented as a binary blob and removing whitespace and asterisks and uppercasing. >>> normalize_sequence("ACGT") 'ACGT' >>> normalize_sequence(" A C G T ...
python
{ "resource": "" }
q37760
translate_cds
train
def translate_cds(seq, full_codons=True, ter_symbol="*"): """translate a DNA or RNA sequence into a single-letter amino acid sequence using the standard translation table If full_codons is True, a sequence whose length isn't a multiple of three generates a ValueError; else an 'X' will be added as the l...
python
{ "resource": "" }
q37761
BaseRequestEngine.request
train
def request(self, url, *, method='GET', headers=None, data=None, result_callback=None): """Perform request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: request data. :param obje...
python
{ "resource": "" }
q37762
BaseRequestEngine._make_full_url
train
def _make_full_url(self, url): """Given base and relative URL, construct the full URL. :param str url: relative URL. :return: full URL. :rtype: str """ return SLASH.join([self._api_base_url, url.lstrip(SLASH)])
python
{ "resource": "" }
q37763
merge_dictionaries
train
def merge_dictionaries(current, new, only_defaults=False, template_special_case=False): ''' Merge two settings dictionaries, recording how many changes were needed. ''' changes = 0 for key, value in new.items(): if key not in current: if hasattr(global_settings, key): ...
python
{ "resource": "" }
q37764
configure_settings
train
def configure_settings(settings, environment_settings=True): ''' Given a settings object, run automatic configuration of all the apps in INSTALLED_APPS. ''' changes = 1 iterations = 0 while changes: changes = 0 app_names = ['django_autoconfig'] + list(settings['INSTALLED_APP...
python
{ "resource": "" }
q37765
configure_urls
train
def configure_urls(apps, index_view=None, prefixes=None): ''' Configure urls from a list of apps. ''' prefixes = prefixes or {} urlpatterns = patterns('') if index_view: from django.views.generic.base import RedirectView urlpatterns += patterns('', url(r'^$', Redirec...
python
{ "resource": "" }
q37766
check_images
train
def check_images(data): """ Check and reformat input images if needed """ if isinstance(data, ndarray): data = fromarray(data) if not isinstance(data, Images): data = fromarray(asarray(data)) if len(data.shape) not in set([3, 4]): raise Exception('Number of image di...
python
{ "resource": "" }
q37767
check_reference
train
def check_reference(images, reference): """ Ensure the reference matches image dimensions """ if not images.shape[1:] == reference.shape: raise Exception('Image shape %s and reference shape %s must match' % (images.shape[1:], reference.shape)) return reference
python
{ "resource": "" }
q37768
ExpGene.from_dict
train
def from_dict(cls, data: Dict[str, Union[str, int]]): """Generate an `ExpGene` object from a dictionary. Parameters ---------- data : dict A dictionary with keys corresponding to attribute names. Attributes with missing keys will be assigned `None`. Retu...
python
{ "resource": "" }
q37769
ReadIntervals.add
train
def add(self, start, end): """ Add the start and end offsets of a matching read. @param start: The C{int} start offset of the read match in the subject. @param end: The C{int} end offset of the read match in the subject. This is Python-style: the end offset is not included i...
python
{ "resource": "" }
q37770
ReadIntervals.walk
train
def walk(self): """ Get the non-overlapping read intervals that match the subject. @return: A generator that produces (TYPE, (START, END)) tuples, where where TYPE is either self.EMPTY or self.FULL and (START, STOP) is the interval. The endpoint (STOP) of the interval is...
python
{ "resource": "" }
q37771
ReadIntervals.coverage
train
def coverage(self): """ Get the fraction of a subject is matched by its set of reads. @return: The C{float} fraction of a subject matched by its reads. """ if self._targetLength == 0: return 0.0 coverage = 0 for (intervalType, (start, end)) in self.w...
python
{ "resource": "" }
q37772
ReadIntervals.coverageCounts
train
def coverageCounts(self): """ For each location in the subject, return a count of how many times that location is covered by a read. @return: a C{Counter} where the keys are the C{int} locations on the subject and the value is the number of times the location is ...
python
{ "resource": "" }
q37773
OffsetAdjuster._reductionForOffset
train
def _reductionForOffset(self, offset): """ Calculate the total reduction for a given X axis offset. @param offset: The C{int} offset. @return: The total C{float} reduction that should be made for this offset. """ reduction = 0 for (thisOffset, thisRed...
python
{ "resource": "" }
q37774
OffsetAdjuster.adjustHSP
train
def adjustHSP(self, hsp): """ Adjust the read and subject start and end offsets in an HSP. @param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance. """ reduction = self._reductionForOffset( min(hsp.readStartInSubject, hsp.subjectStart)) hsp.readEndInSubjec...
python
{ "resource": "" }
q37775
GeneSetCollection.get_by_index
train
def get_by_index(self, i): """Look up a gene set by its index. Parameters ---------- i: int The index of the gene set. Returns ------- GeneSet The gene set. Raises ------ ValueError If the given index ...
python
{ "resource": "" }
q37776
GeneSetCollection.read_tsv
train
def read_tsv(cls, path, encoding='utf-8'): """Read a gene set database from a tab-delimited text file. Parameters ---------- path: str The path name of the the file. encoding: str The encoding of the text file. Returns ------- Non...
python
{ "resource": "" }
q37777
GeneSetCollection.write_tsv
train
def write_tsv(self, path): """Write the database to a tab-delimited text file. Parameters ---------- path: str The path name of the file. Returns ------- None """ with open(path, 'wb') as ofh: writer = csv.writer( ...
python
{ "resource": "" }
q37778
GeneSetCollection.read_msigdb_xml
train
def read_msigdb_xml(cls, path, entrez2gene, species=None): # pragma: no cover """Read the complete MSigDB database from an XML file. The XML file can be downloaded from here: http://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/5.0/msigdb_v5.0.xml ...
python
{ "resource": "" }
q37779
Feature.legendLabel
train
def legendLabel(self): """ Provide a textual description of the feature and its qualifiers to be used as a label in a plot legend. @return: A C{str} description of the feature. """ excludedQualifiers = set(( 'codon_start', 'db_xref', 'protein_id', 'region_nam...
python
{ "resource": "" }
q37780
recent_articles
train
def recent_articles(limit=10, exclude=None): """Returns list of latest article""" queryset = Article.objects.filter(published=True).order_by('-modified') if exclude: if hasattr(exclude, '__iter__'): queryset = queryset.exclude(pk__in=exclude) else: queryset = queryset...
python
{ "resource": "" }
q37781
_flatten
train
def _flatten(n): """Recursively flatten a mixed sequence of sub-sequences and items""" if isinstance(n, collections.Sequence): for x in n: for y in _flatten(x): yield y else: yield n
python
{ "resource": "" }
q37782
wrap
train
def wrap(stream, unicode=False, window=1024, echo=False, close_stream=True): """Wrap a stream to implement expect functionality. This function provides a convenient way to wrap any Python stream (a file-like object) or socket with an appropriate :class:`Expecter` class for the stream type. The returned...
python
{ "resource": "" }
q37783
BytesSearcher.search
train
def search(self, buf): """Search the provided buffer for matching bytes. Search the provided buffer for matching bytes. If the *match* is found, returns a :class:`SequenceMatch` object, otherwise returns ``None``. :param buf: Buffer to search for a match. :return: :class:`Seque...
python
{ "resource": "" }
q37784
TextSearcher.search
train
def search(self, buf): """Search the provided buffer for matching text. Search the provided buffer for matching text. If the *match* is found, returns a :class:`SequenceMatch` object, otherwise returns ``None``. :param buf: Buffer to search for a match. :return: :class:`Sequenc...
python
{ "resource": "" }
q37785
RegexSearcher.search
train
def search(self, buf): """Search the provided buffer for a match to the object's regex. Search the provided buffer for a match to the object's regex. If the *match* is found, returns a :class:`RegexMatch` object, otherwise returns ``None``. :param buf: Buffer to search for a ma...
python
{ "resource": "" }
q37786
SearcherCollection.search
train
def search(self, buf): """Search the provided buffer for a match to any sub-searchers. Search the provided buffer for a match to any of this collection's sub-searchers. If a single matching sub-searcher is found, returns that sub-searcher's *match* object. If multiple matches are found,...
python
{ "resource": "" }
q37787
LoadFixtureRunner.init_graph
train
def init_graph(self): """ Initialize graph Load all nodes and set dependencies. To avoid errors about missing nodes all nodes get loaded first before setting the dependencies. """ self._graph = Graph() # First add all nodes for key in self.loader...
python
{ "resource": "" }
q37788
LoadFixtureRunner.load_fixtures
train
def load_fixtures(self, nodes=None, progress_callback=None, dry_run=False): """Load all fixtures for given nodes. If no nodes are given all fixtures will be loaded. :param list nodes: list of nodes to be loaded. :param callable progress_callback: Callback which will be called while ...
python
{ "resource": "" }
q37789
getAPOBECFrequencies
train
def getAPOBECFrequencies(dotAlignment, orig, new, pattern): """ Gets mutation frequencies if they are in a certain pattern. @param dotAlignment: result from calling basePlotter @param orig: A C{str}, naming the original base @param new: A C{str}, what orig was mutated to @param pattern: A C{str...
python
{ "resource": "" }
q37790
getCompleteFreqs
train
def getCompleteFreqs(blastHits): """ Make a dictionary which collects all mutation frequencies from all reads. Calls basePlotter to get dotAlignment, which is passed to getAPOBECFrequencies with the respective parameter, to collect the frequencies. @param blastHits: A L{dark.blast.BlastHits...
python
{ "resource": "" }
q37791
writeDetails
train
def writeDetails(accept, readId, taxonomy, fp): """ Write read and taxonomy details. @param accept: A C{bool} indicating whether the read was accepted, according to its taxonomy. @param readId: The C{str} id of the read. @taxonomy: A C{list} of taxonomy C{str} levels. @fp: An open file ...
python
{ "resource": "" }
q37792
Graph.add
train
def add(self, name, parents=None): """ add a node to the graph. Raises an exception if the node cannot be added (i.e., if a node that name already exists, or if it would create a cycle. NOTE: A node can be added before its parents are added. name: The name of the node ...
python
{ "resource": "" }
q37793
Graph.remove
train
def remove(self, name, strategy=Strategy.promote): """ Remove a node from the graph. Returns the set of nodes that were removed. If the node doesn't exist, an exception will be raised. name: The name of the node to remove. strategy: (Optional, Strategy.promote) What to ...
python
{ "resource": "" }
q37794
Graph.ancestor_of
train
def ancestor_of(self, name, ancestor, visited=None): """ Check whether a node has another node as an ancestor. name: The name of the node being checked. ancestor: The name of the (possible) ancestor node. visited: (optional, None) If given, a set of nodes that have a...
python
{ "resource": "" }
q37795
respond
train
def respond(template, context={}, request=None, **kwargs): "Calls render_to_response with a RequestConext" from django.http import HttpResponse from django.template import RequestContext from django.template.loader import render_to_string if request: default = context_processors.default...
python
{ "resource": "" }
q37796
update_subscription
train
def update_subscription(request, ident): "Shows subscriptions options for a verified subscriber." try: subscription = Subscription.objects.get(ident=ident) except Subscription.DoesNotExist: return respond('overseer/invalid_subscription_token.html', {}, request) if request.POST: ...
python
{ "resource": "" }
q37797
verify_subscription
train
def verify_subscription(request, ident): """ Verifies an unverified subscription and create or appends to an existing subscription. """ try: unverified = UnverifiedSubscription.objects.get(ident=ident) except UnverifiedSubscription.DoesNotExist: return respond('overseer/inva...
python
{ "resource": "" }
q37798
ReadsAlignments.hsps
train
def hsps(self): """ Provide access to all HSPs for all alignments of all reads. @return: A generator that yields HSPs (or LSPs). """ for readAlignments in self: for alignment in readAlignments: for hsp in alignment.hsps: yield hsp
python
{ "resource": "" }
q37799
getSequence
train
def getSequence(title, db='nucleotide'): """ Get information about a sequence from Genbank. @param title: A C{str} sequence title from a BLAST hit. Of the form 'gi|63148399|gb|DQ011818.1| Description...'. @param db: The C{str} name of the Entrez database to consult. NOTE: this uses the net...
python
{ "resource": "" }