_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37600 | IdentifierSQLiteIndex.list_documents | train | def list_documents(self, limit=None):
""" Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
"""
limit_str = ''
if limit:
... | python | {
"resource": ""
} |
q37601 | IdentifierSQLiteIndex.reset | train | def reset(self):
""" Drops index table. """
query = """
DROP TABLE identifier_index;
"""
self.backend.library.database.connection.execute(query) | python | {
"resource": ""
} |
q37602 | timezone | train | def timezone(utcoffset):
'''
Return a string representing the timezone offset.
Remaining seconds are rounded to the nearest minute.
>>> timezone(3600)
'+01:00'
>>> timezone(5400)
'+01:30'
>>> timezone(-28800)
'-08:00'
'''
hours, seconds = divmod(abs(utcoffset), 3600)
m... | python | {
"resource": ""
} |
q37603 | BuildConfigGroupAccessor.build_duration | train | def build_duration(self):
"""Return the difference between build and build_done states"""
return int(self.state.build_done) - int(self.state.build) | python | {
"resource": ""
} |
q37604 | BuildConfigGroupAccessor.build_duration_pretty | train | def build_duration_pretty(self):
"""Return the difference between build and build_done states, in a human readable format"""
from ambry.util import pretty_time
from time import time
if not self.state.building:
return None
built = self.state.built or time()
... | python | {
"resource": ""
} |
q37605 | BuildConfigGroupAccessor.built_datetime | train | def built_datetime(self):
"""Return the built time as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.build_done)
except TypeError:
# build_done is null
return None | python | {
"resource": ""
} |
q37606 | BuildConfigGroupAccessor.new_datetime | train | def new_datetime(self):
"""Return the time the bundle was created as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.new)
except TypeError:
return None | python | {
"resource": ""
} |
q37607 | BuildConfigGroupAccessor.last_datetime | train | def last_datetime(self):
"""Return the time of the last operation on the bundle as a datetime object"""
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | python | {
"resource": ""
} |
q37608 | list_product_versions | train | def list_product_versions(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions
"""
content = list_product_versions_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | {
"resource": ""
} |
q37609 | create_product_version | train | def create_product_version(product_id, version, **kwargs):
"""
Create a new ProductVersion.
Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product.
Follows the Red Hat product support c... | python | {
"resource": ""
} |
q37610 | update_product_version | train | def update_product_version(id, **kwargs):
"""
Update the ProductVersion with ID id with new values.
"""
content = update_product_version_raw(id, **kwargs)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37611 | Widget.prepare_data | train | def prepare_data(self):
'''
Method returning data passed to template.
Subclasses can override it.
'''
value = self.get_raw_value()
return dict(widget=self,
field=self.field,
value=value,
readonly=not self.field.w... | python | {
"resource": ""
} |
q37612 | Widget.render | train | def render(self):
'''
Renders widget to template
'''
data = self.prepare_data()
if self.field.readable:
return self.env.template.render(self.template, **data)
return '' | python | {
"resource": ""
} |
q37613 | AsyncRequestEngine._request | train | def _request(self, url, *,
method='GET', headers=None, data=None, result_callback=None):
"""Perform asynchronous request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable obj... | python | {
"resource": ""
} |
q37614 | BlastReadsAlignments.adjustHspsForPlotting | train | def adjustHspsForPlotting(self, titleAlignments):
"""
Our HSPs are about to be plotted. If we are using e-values, these need
to be adjusted.
@param titleAlignments: An instance of L{TitleAlignment}.
"""
# If we're using bit scores, there's nothing to do.
if self.... | python | {
"resource": ""
} |
q37615 | BlastReadsAlignments.adjustPlot | train | def adjustPlot(self, readsAx):
"""
Add a horizontal line to the plotted reads if we're plotting e-values
and a zero e-value was found.
@param readsAx: A Matplotlib sub-plot instance, as returned by
matplotlib.pyplot.subplot.
"""
# If we're using bit scores, t... | python | {
"resource": ""
} |
q37616 | ExpMatrix.get_figure | train | def get_figure(self, heatmap_kw=None, **kwargs):
"""Generate a plotly figure showing the matrix as a heatmap.
This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``.
See :func:`ExpHeatmap.get_figure` for keyword arguments.
Parameters
----------
heatmap_k... | python | {
"resource": ""
} |
q37617 | ExpMatrix.sort_genes | train | def sort_genes(self, stable=True, inplace=False, ascending=True):
"""Sort the rows of the matrix alphabetically by gene name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whether to... | python | {
"resource": ""
} |
q37618 | ExpMatrix.sort_samples | train | def sort_samples(self, stable=True, inplace=False, ascending=True):
"""Sort the columns of the matrix alphabetically by sample name.
Parameters
----------
stable: bool, optional
Whether to use a stable sorting algorithm. [True]
inplace: bool, optional
Whe... | python | {
"resource": ""
} |
q37619 | ExpMatrix.sample_correlations | train | def sample_correlations(self):
"""Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix.
"""
C = np.corrcoef(self.X.T)
corr_matrix = ExpMatrix(genes=self.samples, samples=self.sa... | python | {
"resource": ""
} |
q37620 | ExpMatrix.read_tsv | train | def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None,
encoding: str = 'UTF-8', sep: str = '\t'):
"""Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGe... | python | {
"resource": ""
} |
q37621 | check_chain | train | def check_chain(chain):
"""Verify a merkle chain to see if the Merkle root can be reproduced.
"""
link = chain[0][0]
for i in range(1, len(chain) - 1):
if chain[i][1] == 'R':
link = hash_function(link + chain[i][0]).digest()
elif chain[i][1] == 'L':
link = hash_fu... | python | {
"resource": ""
} |
q37622 | check_hex_chain | train | def check_hex_chain(chain):
"""Verify a merkle chain, with hashes hex encoded, to see if the Merkle root can be reproduced.
"""
return codecs.encode(check_chain([(codecs.decode(i[0], 'hex_codec'), i[1]) for i in chain]), 'hex_codec') | python | {
"resource": ""
} |
q37623 | MerkleTree.add_hash | train | def add_hash(self, value):
"""Add a Node based on a precomputed, hex encoded, hash value.
"""
self.leaves.append(Node(codecs.decode(value, 'hex_codec'), prehashed=True)) | python | {
"resource": ""
} |
q37624 | MerkleTree.clear | train | def clear(self):
"""Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest
should be garbage collected. This may be useful for situations where you want to take an existing
tree, make changes to the leaves, but leave it uncalculated for some time, without node
... | python | {
"resource": ""
} |
q37625 | MerkleTree.build_fun | train | def build_fun(self, layer=None):
"""Calculate the merkle root and make references between nodes in the tree.
Written in functional style purely for fun.
"""
if not layer:
if not self.leaves:
raise MerkleError('The tree has no leaves and cannot be calculated.')... | python | {
"resource": ""
} |
q37626 | MerkleTree._build | train | def _build(self, leaves):
"""Private helper function to create the next aggregation level and put all references in place.
"""
new, odd = [], None
# check if even number of leaves, promote odd leaf to next level, if not
if len(leaves) % 2 == 1:
odd = leaves.pop(-1)
... | python | {
"resource": ""
} |
q37627 | MerkleTree.get_chain | train | def get_chain(self, index):
"""Assemble and return the chain leading from a given node to the merkle root of this tree.
"""
chain = []
this = self.leaves[index]
chain.append((this.val, 'SELF'))
while this.p:
chain.append((this.sib.val, this.sib.side))
... | python | {
"resource": ""
} |
q37628 | MerkleTree.get_all_chains | train | def get_all_chains(self):
"""Assemble and return a list of all chains for all leaf nodes to the merkle root.
"""
return [self.get_chain(i) for i in range(len(self.leaves))] | python | {
"resource": ""
} |
q37629 | MerkleTree.get_hex_chain | train | def get_hex_chain(self, index):
"""Assemble and return the chain leading from a given node to the merkle root of this tree
with hash values in hex form
"""
return [(codecs.encode(i[0], 'hex_codec'), i[1]) for i in self.get_chain(index)] | python | {
"resource": ""
} |
q37630 | MerkleTree.get_all_hex_chains | train | def get_all_hex_chains(self):
"""Assemble and return a list of all chains for all nodes to the merkle root, hex encoded.
"""
return [[(codecs.encode(i[0], 'hex_codec'), i[1]) for i in j] for j in self.get_all_chains()] | python | {
"resource": ""
} |
q37631 | MerkleTree._get_whole_subtrees | train | def _get_whole_subtrees(self):
"""Returns an array of nodes in the tree that have balanced subtrees beneath them,
moving from left to right.
"""
subtrees = []
loose_leaves = len(self.leaves) - 2**int(log(len(self.leaves), 2))
the_node = self.root
while loose_leave... | python | {
"resource": ""
} |
q37632 | MerkleTree.add_adjust | train | def add_adjust(self, data, prehashed=False):
"""Add a new leaf, and adjust the tree, without rebuilding the whole thing.
"""
subtrees = self._get_whole_subtrees()
new_node = Node(data, prehashed=prehashed)
self.leaves.append(new_node)
for node in reversed(subtrees):
... | python | {
"resource": ""
} |
q37633 | StaticGSEResult.fold_enrichment | train | def fold_enrichment(self):
"""Returns the fold enrichment of the gene set.
Fold enrichment is defined as ratio between the observed and the
expected number of gene set genes present.
"""
expected = self.K * (self.n/float(self.N))
return self.k / expected | python | {
"resource": ""
} |
q37634 | StaticGSEResult.get_pretty_format | train | def get_pretty_format(self, max_name_length=0):
"""Returns a nicely formatted string describing the result.
Parameters
----------
max_name_length: int [0]
The maximum length of the gene set name (in characters). If the
gene set name is longer than this number, it... | python | {
"resource": ""
} |
q37635 | main | train | def main(recordFilenames, fastaFilename, title, xRange, bitRange):
"""
Print reads that match in a specified X-axis and bit score range.
@param recordFilenames: A C{list} of C{str} file names contain results of a
BLAST run, in JSON format.
@param fastaFilename: The C{str} name of the FASTA file... | python | {
"resource": ""
} |
q37636 | fetch_seq | train | def fetch_seq(ac, start_i=None, end_i=None):
"""Fetches sequences and subsequences from NCBI eutils and Ensembl
REST interfaces.
:param string ac: accession of sequence to fetch
:param int start_i: start position of *interbase* interval
:param int end_i: end position of *interbase* interval
*... | python | {
"resource": ""
} |
q37637 | _fetch_seq_ensembl | train | def _fetch_seq_ensembl(ac, start_i=None, end_i=None):
"""Fetch the specified sequence slice from Ensembl using the public
REST interface.
An interbase interval may be optionally provided with start_i and
end_i. However, the Ensembl REST interface does not currently
accept intervals, so the entire s... | python | {
"resource": ""
} |
q37638 | _fetch_seq_ncbi | train | def _fetch_seq_ncbi(ac, start_i=None, end_i=None):
"""Fetch sequences from NCBI using the eutils interface.
An interbase interval may be optionally provided with start_i and
end_i. NCBI eutils will return just the requested subsequence,
which might greatly reduce payload sizes (especially with
chro... | python | {
"resource": ""
} |
q37639 | _add_eutils_api_key | train | def _add_eutils_api_key(url):
"""Adds eutils api key to the query
:param url: eutils url with a query string
:return: url with api_key parameter set to the value of environment
variable 'NCBI_API_KEY' if available
"""
apikey = os.environ.get("NCBI_API_KEY")
if apikey:
url += "&api_k... | python | {
"resource": ""
} |
q37640 | rom | train | def rom(addr, dout, CONTENT):
''' CONTENT == tuple of non-sparse values '''
@always_comb
def read():
dout.next = CONTENT[int(addr)]
return read | python | {
"resource": ""
} |
q37641 | Event.post_to_twitter | train | def post_to_twitter(self, message=None):
"""Update twitter status, i.e., post a tweet"""
consumer = oauth2.Consumer(key=conf.TWITTER_CONSUMER_KEY,
secret=conf.TWITTER_CONSUMER_SECRET)
token = oauth2.Token(key=conf.TWITTER_ACCESS_TOKEN, secret=conf.TWITTER_ACCES... | python | {
"resource": ""
} |
q37642 | get_gaf_gene_ontology_file | train | def get_gaf_gene_ontology_file(path):
"""Extract the gene ontology file associated with a GO annotation file.
Parameters
----------
path: str
The path name of the GO annotation file.
Returns
-------
str
The URL of the associated gene ontology file.
"""
assert isinst... | python | {
"resource": ""
} |
q37643 | Displacement.apply | train | def apply(self, im):
"""
Apply an n-dimensional displacement by shifting an image or volume.
Parameters
----------
im : ndarray
The image or volume to shift
"""
from scipy.ndimage.interpolation import shift
return shift(im, map(lambda x: -x, s... | python | {
"resource": ""
} |
q37644 | Displacement.compute | train | def compute(a, b):
"""
Compute an optimal displacement between two ndarrays.
Finds the displacement between two ndimensional arrays. Arrays must be
of the same size. Algorithm uses a cross correlation, computed efficiently
through an n-dimensional fft.
Parameters
... | python | {
"resource": ""
} |
q37645 | LocalDisplacement.compute | train | def compute(a, b, axis):
"""
Finds optimal displacements localized along an axis
"""
delta = []
for aa, bb in zip(rollaxis(a, axis, 0), rollaxis(b, axis, 0)):
delta.append(Displacement.compute(aa, bb).delta)
return LocalDisplacement(delta, axis=axis) | python | {
"resource": ""
} |
q37646 | LocalDisplacement.apply | train | def apply(self, im):
"""
Apply axis-localized displacements.
Parameters
----------
im : ndarray
The image or volume to shift
"""
from scipy.ndimage.interpolation import shift
im = rollaxis(im, self.axis)
im.setflags(write=True)
... | python | {
"resource": ""
} |
q37647 | write_sample_sheet | train | def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None):
"""Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
----------
output_file: str... | python | {
"resource": ""
} |
q37648 | NCBISequenceLinkURL | train | def NCBISequenceLinkURL(title, default=None):
"""
Given a sequence title, like "gi|42768646|gb|AY516849.1| Homo sapiens",
return the URL of a link to the info page at NCBI.
title: the sequence title to produce a link URL for.
default: the value to return if the title cannot be parsed.
"""
t... | python | {
"resource": ""
} |
q37649 | NCBISequenceLink | train | def NCBISequenceLink(title, default=None):
"""
Given a sequence title, like "gi|42768646|gb|AY516849.1| Homo sapiens",
return an HTML A tag dispalying a link to the info page at NCBI.
title: the sequence title to produce an HTML link for.
default: the value to return if the title cannot be parsed.
... | python | {
"resource": ""
} |
q37650 | AlignmentPanelHTMLWriter._writeFASTA | train | def _writeFASTA(self, i, image):
"""
Write a FASTA file containing the set of reads that hit a sequence.
@param i: The number of the image in self._images.
@param image: A member of self._images.
@return: A C{str}, either 'fasta' or 'fastq' indicating the format
of t... | python | {
"resource": ""
} |
q37651 | AlignmentPanelHTMLWriter._writeFeatures | train | def _writeFeatures(self, i, image):
"""
Write a text file containing the features as a table.
@param i: The number of the image in self._images.
@param image: A member of self._images.
@return: The C{str} features file name - just the base name, not
including the pat... | python | {
"resource": ""
} |
q37652 | DosDateTimeToTimeTuple | train | def DosDateTimeToTimeTuple(dosDateTime):
"""Convert an MS-DOS format date time to a Python time tuple.
"""
dos_date = dosDateTime >> 16
dos_time = dosDateTime & 0xffff
day = dos_date & 0x1f
month = (dos_date >> 5) & 0xf
year = 1980 + (dos_date >> 9)
second = 2 * (dos_time & 0x1f)
min... | python | {
"resource": ""
} |
q37653 | bitScoreToEValue | train | def bitScoreToEValue(bitScore, dbSize, dbSequenceCount, queryLength,
lengthAdjustment):
"""
Convert a bit score to an e-value.
@param bitScore: The C{float} bit score to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all seque... | python | {
"resource": ""
} |
q37654 | eValueToBitScore | train | def eValueToBitScore(eValue, dbSize, dbSequenceCount, queryLength,
lengthAdjustment):
"""
Convert an e-value to a bit score.
@param eValue: The C{float} e-value to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences i... | python | {
"resource": ""
} |
q37655 | parseBtop | train | def parseBtop(btopString):
"""
Parse a BTOP string.
The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If C{btopString} is not valid BTOP.
@return: A generator that yields a series of integers and 2-tuples of
... | python | {
"resource": ""
} |
q37656 | countGaps | train | def countGaps(btopString):
"""
Count the query and subject gaps in a BTOP string.
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If L{parseBtop} finds an error in the BTOP string
C{btopString}.
@return: A 2-tuple of C{int}s, with the (query, subject) gaps counts as
fo... | python | {
"resource": ""
} |
q37657 | btop2cigar | train | def btop2cigar(btopString, concise=False, aa=False):
"""
Convert a BTOP string to a CIGAR string.
@param btopString: A C{str} BTOP sequence.
@param concise: If C{True}, use 'M' for matches and mismatches instead
of the more specific 'X' and '='.
@param aa: If C{True}, C{btopString} will be ... | python | {
"resource": ""
} |
q37658 | Command.progress_callback | train | def progress_callback(self, action, node, elapsed_time=None):
"""
Callback to report progress
:param str action:
:param list node: app, module
:param int | None elapsed_time:
"""
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.... | python | {
"resource": ""
} |
q37659 | GOTerm.get_pretty_format | train | def get_pretty_format(self, include_id=True, max_name_length=0,
abbreviate=True):
"""Returns a nicely formatted string with the GO term information.
Parameters
----------
include_id: bool, optional
Include the GO term ID.
max_name_length: in... | python | {
"resource": ""
} |
q37660 | HSP.toDict | train | def toDict(self):
"""
Get information about the HSP as a dictionary.
@return: A C{dict} representation of the HSP.
"""
result = _Base.toDict(self)
result['score'] = self.score.score
return result | python | {
"resource": ""
} |
q37661 | get_argument_parser | train | def get_argument_parser():
"""Returns an argument parser object for the script."""
desc = 'Filter FASTA file by chromosome names.'
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-f', '--fasta-file', default='-', type=str, help=textwrap.dedent("""\
Path of the... | python | {
"resource": ""
} |
q37662 | main | train | def main(args=None):
"""Script body."""
if args is None:
# parse command-line arguments
parser = get_argument_parser()
args = parser.parse_args()
fasta_file = args.fasta_file
species = args.species
chrom_pat = args.chromosome_pattern
output_file = args.output_file
... | python | {
"resource": ""
} |
q37663 | make_app | train | def make_app(global_conf, **app_conf):
"""Create a WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``app_conf``
The application's local configuration. Normally specified in
... | python | {
"resource": ""
} |
q37664 | dimensionalIterator | train | def dimensionalIterator(dimensions, maxItems=-1):
"""
Given a list of n positive integers, return a generator that yields
n-tuples of coordinates to 'fill' the dimensions. This is like an
odometer in a car, but the dimensions do not each have to be 10.
For example: dimensionalIterator((2, 3)) will ... | python | {
"resource": ""
} |
q37665 | matchToString | train | def matchToString(dnaMatch, read1, read2, matchAmbiguous=True, indent='',
offsets=None):
"""
Format a DNA match as a string.
@param dnaMatch: A C{dict} returned by C{compareDNAReads}.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read}... | python | {
"resource": ""
} |
q37666 | compareDNAReads | train | def compareDNAReads(read1, read2, matchAmbiguous=True, gapChars='-',
offsets=None):
"""
Compare two DNA 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 matchAmbi... | python | {
"resource": ""
} |
q37667 | check | train | def check(fastaFile, jsonFiles):
"""
Check for simple consistency between the FASTA file and the JSON files.
Note that some checking is already performed by the BlastReadsAlignments
class. That includes checking the number of reads matches the number of
BLAST records and that read ids and BLAST rec... | python | {
"resource": ""
} |
q37668 | thresholdForIdentity | train | def thresholdForIdentity(identity, colors):
"""
Get the best identity threshold for a specific identity value.
@param identity: A C{float} nucleotide identity.
@param colors: A C{list} of (threshold, color) tuples, where threshold is a
C{float} and color is a C{str} to be used as a cell backgro... | python | {
"resource": ""
} |
q37669 | parseColors | train | def parseColors(colors, defaultColor):
"""
Parse command line color information.
@param colors: A C{list} of space separated "value color" strings, such as
["0.9 red", "0.75 rgb(23, 190, 207)", "0.1 #CF3CF3"].
@param defaultColor: The C{str} color to use for cells that do not reach
the ... | python | {
"resource": ""
} |
q37670 | getReadLengths | train | def getReadLengths(reads, gapChars):
"""
Get all read lengths, excluding gap characters.
@param reads: A C{Reads} instance.
@param gapChars: A C{str} of sequence characters considered to be gaps.
@return: A C{dict} keyed by read id, with C{int} length values.
"""
gapChars = set(gapChars)
... | python | {
"resource": ""
} |
q37671 | explanation | train | def explanation(matchAmbiguous, concise, showLengths, showGaps, showNs):
"""
Make an explanation of the output HTML table.
@param matchAmbiguous: If C{True}, count ambiguous nucleotides that are
possibly correct as actually being correct. Otherwise, we are strict
and insist that only non-am... | python | {
"resource": ""
} |
q37672 | collectData | train | def collectData(reads1, reads2, square, matchAmbiguous):
"""
Get pairwise matching statistics for two sets of reads.
@param reads1: An C{OrderedDict} of C{str} read ids whose values are
C{Read} instances. These will be the rows of the table.
@param reads2: An C{OrderedDict} of C{str} read ids w... | python | {
"resource": ""
} |
q37673 | simpleTable | train | def simpleTable(tableData, reads1, reads2, square, matchAmbiguous, gapChars):
"""
Make a text table showing inter-sequence distances.
@param tableData: A C{defaultdict(dict)} keyed by read ids, whose values
are the dictionaries returned by compareDNAReads.
@param reads1: An C{OrderedDict} of C{... | python | {
"resource": ""
} |
q37674 | get_file_md5sum | train | def get_file_md5sum(path):
"""Calculate the MD5 hash for a file."""
with open(path, 'rb') as fh:
h = str(hashlib.md5(fh.read()).hexdigest())
return h | python | {
"resource": ""
} |
q37675 | smart_open_read | train | def smart_open_read(path=None, mode='rb', encoding=None, try_gzip=False):
"""Open a file for reading or return ``stdin``.
Adapted from StackOverflow user "Wolph"
(http://stackoverflow.com/a/17603000).
"""
assert mode in ('r', 'rb')
assert path is None or isinstance(path, (str, _oldstr))
ass... | python | {
"resource": ""
} |
q37676 | smart_open_write | train | def smart_open_write(path=None, mode='wb', encoding=None):
"""Open a file for writing or return ``stdout``.
Adapted from StackOverflow user "Wolph"
(http://stackoverflow.com/a/17603000).
"""
if path is not None:
# open a file
fh = io.open(path, mode=mode, encoding=encoding)
else... | python | {
"resource": ""
} |
q37677 | get_url_size | train | def get_url_size(url):
"""Get the size of a URL.
Note: Uses requests, so it does not work for FTP URLs.
Source: StackOverflow user "Burhan Khalid".
(http://stackoverflow.com/a/24585314/5651021)
Parameters
----------
url : str
The URL.
Returns
-------
int
The s... | python | {
"resource": ""
} |
q37678 | make_sure_dir_exists | train | def make_sure_dir_exists(dir_, create_subfolders=False):
"""Ensures that a directory exists.
Adapted from StackOverflow users "Bengt" and "Heikki Toivonen"
(http://stackoverflow.com/a/5032238).
Parameters
----------
dir_: str
The directory path.
create_subfolders: bool, optional
... | python | {
"resource": ""
} |
q37679 | get_file_size | train | def get_file_size(path):
"""The the size of a file in bytes.
Parameters
----------
path: str
The path of the file.
Returns
-------
int
The size of the file in bytes.
Raises
------
IOError
If the file does not exist.
OSError
If a file system ... | python | {
"resource": ""
} |
q37680 | gzip_open_text | train | def gzip_open_text(path, encoding=None):
"""Opens a plain-text file that may be gzip'ed.
Parameters
----------
path : str
The file.
encoding : str, optional
The encoding to use.
Returns
-------
file-like
A file-like object.
Notes
-----
Generally, re... | python | {
"resource": ""
} |
q37681 | bisect_index | train | def bisect_index(a, x):
""" Find the leftmost index of an element in a list using binary search.
Parameters
----------
a: list
A sorted list.
x: arbitrary
The element.
Returns
-------
int
The index.
"""
i = bisect.bisect_left(a, x)
if i != len(a) an... | python | {
"resource": ""
} |
q37682 | read_single | train | def read_single(path, encoding = 'UTF-8'):
""" Reads the first column of a tab-delimited text file.
The file can either be uncompressed or gzip'ed.
Parameters
----------
path: str
The path of the file.
enc: str
The file encoding.
Returns
-------
List of str
... | python | {
"resource": ""
} |
q37683 | add_tcp_firewall_rule | train | def add_tcp_firewall_rule(project, access_token, name, tag, port):
"""Adds a TCP firewall rule.
TODO: docstring"""
headers = {
'Authorization': 'Bearer %s' % access_token.access_token
}
payload = {
"name": name,
"kind": "compute#firewall",
"sourceRanges": [... | python | {
"resource": ""
} |
q37684 | update | train | def update(taxids, conn, force_download, silent):
"""Update local UniProt database"""
if not silent:
click.secho("WARNING: Update is very time consuming and can take several "
"hours depending which organisms you are importing!", fg="yellow")
if not taxids:
click... | python | {
"resource": ""
} |
q37685 | web | train | def web(host, port):
"""Start web application"""
from .webserver.web import get_app
get_app().run(host=host, port=port) | python | {
"resource": ""
} |
q37686 | checkCompatibleParams | train | def checkCompatibleParams(initialParams, laterParams):
"""
Check a later set of BLAST parameters against those originally found.
@param initialParams: A C{dict} with the originally encountered BLAST
parameter settings.
@param laterParams: A C{dict} with BLAST parameter settings encountered
... | python | {
"resource": ""
} |
q37687 | GeneSet.to_list | train | def to_list(self):
"""Converts the GeneSet object to a flat list of strings.
Note: see also :meth:`from_list`.
Parameters
----------
Returns
-------
list of str
The data from the GeneSet object as a flat list.
"""
src = self._source ... | python | {
"resource": ""
} |
q37688 | GeneSet.from_list | train | def from_list(cls, l):
"""Generate an GeneSet object from a list of strings.
Note: See also :meth:`to_list`.
Parameters
----------
l: list or tuple of str
A list of strings representing gene set ID, name, genes,
source, collection, and description. The g... | python | {
"resource": ""
} |
q37689 | findPrimer | train | def findPrimer(primer, seq):
"""
Look for a primer sequence.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{list} of zero-based offsets into the sequence at which the
primer can be found. If no instances are found, return an empty
... | python | {
"resource": ""
} |
q37690 | findPrimerBidi | train | def findPrimerBidi(primer, seq):
"""
Look for a primer in a sequence and its reverse complement.
@param primer: A C{str} primer sequence.
@param seq: A BioPython C{Bio.Seq} sequence.
@return: A C{tuple} of two lists. The first contains (zero-based)
ascending offsets into the sequence at wh... | python | {
"resource": ""
} |
q37691 | parseRangeString | train | def parseRangeString(s, convertToZeroBased=False):
"""
Parse a range string of the form 1-5,12,100-200.
@param s: A C{str} specifiying a set of numbers, given in the form of
comma separated numeric ranges or individual indices.
@param convertToZeroBased: If C{True} all indices will have one
... | python | {
"resource": ""
} |
q37692 | nucleotidesToStr | train | def nucleotidesToStr(nucleotides, prefix=''):
"""
Convert offsets and base counts to a string.
@param nucleotides: A C{defaultdict(Counter)} instance, keyed
by C{int} offset, with nucleotides keying the Counters.
@param prefix: A C{str} to put at the start of each line.
@return: A C{str} re... | python | {
"resource": ""
} |
q37693 | DiamondReadsAlignments._getReader | train | def _getReader(self, filename, scoreClass):
"""
Obtain a JSON record reader for DIAMOND records.
@param filename: The C{str} file name holding the JSON.
@param scoreClass: A class to hold and compare scores (see scores.py).
"""
if filename.endswith('.json') or filename.e... | python | {
"resource": ""
} |
q37694 | get_argument_parser | train | def get_argument_parser():
"""Creates the argument parser for the extract_entrez2gene.py script.
Returns
-------
A fully configured `argparse.ArgumentParser` object.
Notes
-----
This function is used by the `sphinx-argparse` extension for sphinx.
"""
desc = 'Generate a mapping of... | python | {
"resource": ""
} |
q37695 | read_gene2acc | train | def read_gene2acc(file_path, logger):
"""Extracts Entrez ID -> gene symbol mapping from gene2accession.gz file.
Parameters
----------
file_path: str
The path of the gene2accession.gz file (or a filtered version thereof).
The file may be gzip'ed.
Returns
-------
dict
... | python | {
"resource": ""
} |
q37696 | write_entrez2gene | train | def write_entrez2gene(file_path, entrez2gene, logger):
"""Writes Entrez ID -> gene symbol mapping to a tab-delimited text file.
Parameters
----------
file_path: str
The path of the output file.
entrez2gene: dict
The mapping of Entrez IDs to gene symbols.
Returns
-------
... | python | {
"resource": ""
} |
q37697 | main | train | def main(args=None):
"""Extracts Entrez ID -> gene symbol mapping and writes it to a 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` m... | python | {
"resource": ""
} |
q37698 | find | train | def find(s):
"""
Find an amino acid whose name or abbreviation is s.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
return: An L{AminoAcid} instance or C{None} if no matching amino acid can
be locate... | python | {
"resource": ""
} |
q37699 | _propertiesOrClustersForSequence | train | def _propertiesOrClustersForSequence(sequence, propertyNames, propertyValues,
missingAAValue):
"""
Extract amino acid property values or cluster numbers for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{st... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.