code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
gene_name = entry.find("./gene/name[@type='primary']") return gene_name.text if gene_name is not None and gene_name.text.strip() else None
def get_gene_name(cls, entry)
get primary gene name from XML node entry :param entry: XML node entry :return: str
4.23242
4.229963
1.000581
alternative_gene_names = [] for alternative_gene_name in entry.iterfind("./gene/name"): if alternative_gene_name.attrib['type'] != 'primary': alternative_gene_name_dict = { 'type_': alternative_gene_name.attrib['type'], 'nam...
def get_other_gene_names(cls, entry)
get list of `models.OtherGeneName` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.models.OtherGeneName` objects
2.924767
2.581899
1.132797
return [models.Accession(accession=x.text) for x in entry.iterfind("./accession")]
def get_accessions(cls, entry)
get list of models.Accession from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Accession` objects
7.749928
6.34387
1.22164
db_refs = [] for db_ref in entry.iterfind("./dbReference"): db_ref_dict = {'identifier': db_ref.attrib['id'], 'type_': db_ref.attrib['type']} db_refs.append(models.DbReference(**db_ref_dict)) return db_refs
def get_db_references(cls, entry)
get list of `models.DbReference` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.DbReference`
3.556499
2.889838
1.230691
features = [] for feature in entry.iterfind("./feature"): feature_dict = { 'description': feature.attrib.get('description'), 'type_': feature.attrib['type'], 'identifier': feature.attrib.get('id') } features....
def get_features(cls, entry)
get list of `models.Feature` from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Feature`
4.054425
3.280081
1.236074
query_full = "./protein/recommendedName/fullName" full_name = entry.find(query_full).text short_name = None query_short = "./protein/recommendedName/shortName" short_name_tag = entry.find(query_short) if short_name_tag is not None: short_name = short...
def get_recommended_protein_name(cls, entry)
get recommended full and short protein name as tuple from XML node :param entry: XML node entry :return: (str, str) => (full, short)
2.953061
2.389272
1.235966
query = "./organismHost/dbReference[@type='NCBI Taxonomy']" return [models.OrganismHost(taxid=x.get('id')) for x in entry.iterfind(query)]
def get_organism_hosts(cls, entry)
get list of `models.OrganismHost` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.OrganismHost` objects
7.165486
4.987479
1.436695
pmids = [] for citation in entry.iterfind("./reference/citation"): for pubmed_ref in citation.iterfind('dbReference[@type="PubMed"]'): pmid_number = pubmed_ref.get('id') if pmid_number in self.pmids: pmid_sqlalchemy_obj = self...
def get_pmids(self, entry)
get `models.Pmid` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Pmid` objects
3.037084
2.913155
1.042541
comments = [] query = "./comment[@type='function']" for comment in entry.iterfind(query): text = comment.find('./text').text comments.append(models.Function(text=text)) return comments
def get_functions(cls, entry)
get `models.Function` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.Function` objects
6.580895
6.239107
1.054782
if url: version_url = os.path.join(os.path.dirname(url), defaults.VERSION_FILE_NAME) else: url = os.path.join(defaults.XML_DIR_NAME, defaults.SWISSPROT_FILE_NAME) version_url = os.path.join(defaults.XML_DIR_NAME, defaults.VERSION_FILE_NAME) xml_file_...
def download(cls, url=None, force_download=False)
Downloads uniprot_sprot.xml.gz and reldate.txt (release date information) from URL or file path .. note:: only URL/path of xml.gz is needed and valid value for parameter url. URL/path for reldate.txt have to be the same folder :param str url: UniProt gzipped URL or file pa...
2.258849
2.238795
1.008957
file_name = urlparse(url).path.split('/')[-1] return os.path.join(PYUNIPROT_DATA_DIR, file_name)
def get_path_to_file_from_url(cls, url)
standard file path :param str url: download URL
4.027803
5.235821
0.769278
fd = open(path_to_export_file, 'w') header = "format-version: 0.1\ndata: {}\n".format(time.strftime("%d:%m:%Y %H:%M")) header += "ontology: {}\n".format(name_of_ontology) header += 'synonymtypedef: GENE_NAME "GENE NAME"\nsynonymtypedef: ALTERNATIVE_NAME "ALTERNATIVE NAME"\n' ...
def export_obo(self, path_to_export_file, name_of_ontology="uniprot", taxids=None)
export complete database to OBO (http://www.obofoundry.org/) file :param path_to_export_file: path to export file :param taxids: NCBI taxonomy identifiers to export (optional)
2.449454
2.466246
0.993191
if not nodes: return [] resolved = [] for node in nodes: if node in resolved: continue self.resolve_node(node, resolved) return resolved
def resolve_nodes(self, nodes)
Resolve a given set of nodes. Dependencies of the nodes, even if they are not in the given list will also be resolved! :param list nodes: List of nodes to be resolved :return: A list of resolved nodes
3.156354
3.538948
0.89189
if seen is None: seen = [] if resolved is None: resolved = [] if node is None: dependencies = sorted(self._nodes.keys()) else: dependencies = self._nodes[node] seen.append(node) for dependency in dependencies: ...
def resolve_node(self, node=None, resolved=None, seen=None)
Resolve a single node or all when node is omitted.
2.25999
2.203624
1.025579
seqLen = len(seq) start = 0 while start < seqLen: triplet = str(seq[start:start + 3]) if triplet in codons: yield start start = start + 3
def findCodons(seq, codons)
Find all instances of the codons in 'codons' in the given sequence. seq: A Bio.Seq.Seq instance. codons: A set of codon strings. Return: a generator yielding matching codon offsets.
2.860126
2.81159
1.017263
for frame in range(3): target = seq[frame:] for (codons, codonType, color) in ( (START_CODONS, 'start', 'green'), (STOP_CODONS, 'stop', 'red')): offsets = list(map(offsetAdjuster, findCodons(target, codons))) if offsets: fi...
def addORFs(fig, seq, minX, maxX, offsetAdjuster)
fig is a matplotlib figure. seq is a Bio.Seq.Seq. minX: the smallest x coordinate. maxX: the largest x coordinate. featureEndpoints: an array of features as returned by addFeatures (may be empty). offsetAdjuster: a function to adjust feature X axis offsets for plotting.
3.429562
3.431767
0.999357
from tempfile import mkdtemp from shutil import rmtree dir = mkdtemp() file1 = join(dir, 'file1.fasta') with open(file1, 'w') as fp: print(reads[0].toString('fasta'), end='', file=fp) file2 = join(dir, 'file2.fasta') with open(file2, 'w') as fp: print(reads[1].toStrin...
def needle(reads)
Run a Needleman-Wunsch alignment and return the two sequences. @param reads: An iterable of two reads. @return: A C{Reads} instance with the two aligned sequences.
3.527024
3.451277
1.021947
buf = bytearray() delim_len = len(delimiter) while len(buf) < max_bytes: c = stream.read(1) if not c: break buf += c if buf[-delim_len:] == delimiter: return bytes(buf[:-delim_len])
def read_until(stream, delimiter, max_bytes=16)
Read until we have found the given delimiter. :param file stream: readable file-like object. :param bytes delimiter: delimiter string. :param int max_bytes: maximum bytes to read. :rtype: bytes|None
2.414315
2.705172
0.892481
# TODO(vovan): Add support for chunk extensions: # TODO(vovan): http://tools.ietf.org/html/rfc2616#section-3.6.1 while True: chunk_len = read_until(stream, b'\r\n') if chunk_len is None: raise DechunkError( 'Could not extract chunk size: unexpected end of ...
def dechunk(stream)
De-chunk HTTP body stream. :param file stream: readable file-like object. :rtype: __generator[bytes] :raise: DechunkError
2.858376
2.767553
1.032817
if isinstance(stream_or_generator, types.GeneratorType): yield from stream_or_generator elif hasattr(stream_or_generator, 'read'): while True: chunk = stream_or_generator.read(CHUNK_SIZE) if not chunk: break # no more data yield chunk ...
def to_chunks(stream_or_generator)
This generator function receives file-like or generator as input and returns generator. :param file|__generator[bytes] stream_or_generator: readable stream or generator. :rtype: __generator[bytes] :raise: TypeError
2.666922
2.607301
1.022867
if compression not in SUPPORTED_COMPRESSIONS: raise TypeError('Unsupported compression type: %s' % (compression,)) de_compressor = DECOMPRESSOR_FACTORIES[compression]() try: for chunk in chunks: try: yield de_compressor.decompress(chunk) except ...
def decompress(chunks, compression)
Decompress :param __generator[bytes] chunks: compressed body chunks. :param str compression: compression constant. :rtype: __generator[bytes] :return: decompressed chunks. :raise: TypeError, DecompressError
3.557715
3.139334
1.133271
if not (chunked or compression): return to_chunks(stream) generator = stream if chunked: generator = dechunk(generator) if compression: generator = decompress(to_chunks(generator), compression) return generator
def read_body_stream(stream, chunked=False, compression=None)
Read HTTP body stream, yielding blocks of bytes. De-chunk and de-compress data if needed. :param file stream: readable stream. :param bool chunked: whether stream is chunked. :param str|None compression: compression type is stream is compressed, otherwise None. :rtype: __generator[bytes...
4.434918
4.661427
0.951408
try: return self._decompressobj.decompress(chunk) except zlib.error: # ugly hack to work with raw deflate content that may # be sent by microsoft servers. For more information, see: # http://carsten.codimi.de/gzip.yaws/ # http://www.p...
def decompress(self, chunk)
Decompress the chunk of data. :param bytes chunk: data chunk :rtype: bytes
5.913694
5.962596
0.991799
if outputDir: if exists(outputDir): if not force: print('Will not overwrite pre-existing files. Use --force to ' 'make me.', file=sys.stderr) sys.exit(1) else: mkdir(outputDir) else: outputDir = mkdtemp() ...
def makeOuputDir(outputDir, force)
Create or check for an output directory. @param outputDir: A C{str} output directory name, or C{None}. @param force: If C{True}, allow overwriting of pre-existing files. @return: The C{str} output directory name.
3.561278
3.658144
0.97352
executor.execute( 'samtools mpileup -u -v -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
def samtoolsMpileup(outFile, referenceFile, alignmentFile, executor)
Use samtools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance.
3.437738
4.093574
0.839789
executor.execute( 'bcftools mpileup -Ov -f %s %s > %s' % (referenceFile, alignmentFile, outFile))
def bcftoolsMpileup(outFile, referenceFile, alignmentFile, executor)
Use bcftools mpileup to generate VCF. @param outFile: The C{str} name to write the output to. @param referenceFile: The C{str} name of the FASTA file with the reference sequence. @param alignmentFile: The C{str} name of the SAM or BAM alignment file. @param executor: An C{Executor} instance.
3.211561
4.061136
0.790803
bgz = vcfFile + '.gz' executor.execute('bgzip -c %s > %s' % (vcfFile, bgz)) executor.execute('tabix %s' % bgz) executor.execute( 'bcftools consensus %s < %s | ' 'filter-fasta.py --idLambda \'lambda id: "%s"\' > %s' % (bgz, referenceFile, id_, outFile))
def bcftoolsConsensus(outFile, vcfFile, id_, referenceFile, executor)
Use bcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param referenceFile: The C{str} name of the...
3.877607
4.210299
0.920982
executor.execute( 'vcfutils.pl vcf2fq < %s | ' 'filter-fasta.py --fastq --quiet --saveAs fasta ' '--idLambda \'lambda id: "%s"\' > %s' % (vcfFile, id_, outFile))
def vcfutilsConsensus(outFile, vcfFile, id_, _, executor)
Use vcftools to extract consensus FASTA. @param outFile: The C{str} name to write the output to. @param vcfFile: The C{str} name of the VCF file with the calls from the pileup. @param id_: The C{str} identifier to use in the resulting FASTA sequence. @param executor: An C{Executor} instance.
10.314904
11.110373
0.928403
xBase = int(x) * self.xScale yBase = int(y) * self.yScale for xOffset in range(self.xScale): for yOffset in range(self.yScale): self.data[yBase + yOffset, xBase + xOffset] = value
def set(self, x, y, value)
Set the data at (x, y) to value.
2.451422
2.370404
1.034179
if formatter_class is None: formatter_class = argparse.RawTextHelpFormatter parser = argparse.ArgumentParser( prog=prog, description=desc, formatter_class=formatter_class, add_help=False ) g = parser.add_argument_group('Help') g.add_argument('-h', '--help', action='hel...
def get_argument_parser(prog=None, desc=None, formatter_class=None)
Create an argument parser. Parameters ---------- prog: str The program name. desc: str The program description. formatter_class: argparse formatter class, optional The argparse formatter class to use. Returns ------- `argparse.ArgumentParser` The arguemn...
2.217477
2.550417
0.869457
g = parser.add_argument_group('Reporting options') g.add_argument( '-l', '--log-file', default=None, type=str, metavar=file_mv, help='Path of log file (if specified, report to stdout AND file.' ) g.add_argument('-q', '--quiet', action='store_true', help=...
def add_reporting_args(parser)
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
3.929502
3.939042
0.997578
resource_groups = {r.index: r for r in self.get_objects_by_type('resourceGroupEx')} return OrderedDict(sorted(resource_groups.items()))
def get_resource_groups(self)
:return: dictionary {resource group id: object} of all resource groups.
8.406564
5.690845
1.477208
if not self.resource_groups: return self.ports else: active_ports = OrderedDict() for resource_group in self.resource_groups.values(): for active_port in resource_group.active_ports: active_ports[active_port] = self.ports[...
def get_active_ports(self)
:return: dictionary {index: object} of all ports.
2.824251
2.559928
1.103254
if state: activePorts = self.rePortInList.findall(self.activePortList) self.activeCapturePortList = "{{" + activePorts[0] + "}}" else: self.activeCapturePortList = "{{""}}" if (writeToHw): self.ix_command('write')
def enable_capture_state(self, state, writeToHw=False)
Enable/Disable capture on resource group
9.612957
10.32467
0.931067
ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: if depth <= 0: return self depth -= 1 parent = ctx_dict.get('_parent') if parent is None: return None return parent.get_containing(name, depth = ...
def get_containing(self, name, depth = 0)
Return the n-th (n = ``depth``) context containing attribute named ``name``.
2.928708
2.703697
1.083223
if self._translator is None: languages = self.lang if not languages: return gettext.NullTranslations() if not isinstance(languages, list): languages = [languages] translator = gettext.NullTranslations() for name...
def translator(self)
Get a valid translator object from one or several languages names.
3.057546
2.968223
1.030093
if title in self._cache: return self._cache[title] lineage = [] gi = int(title.split('|')[1]) query = 'SELECT taxID from gi_taxid where gi = %d' % gi try: while True: self._cursor.execute(query) taxID = self._curs...
def lineage(self, title)
Get lineage information from the taxonomy database for a given title. @param title: A C{str} sequence title (e.g., from a BLAST hit). Of the form 'gi|63148399|gb|DQ011818.1| Description...'. It is the gi number (63148399 in this example) that is looked up in the taxonomy dat...
2.926004
2.642
1.107496
self._cursor.close() self._db.close() self._cursor = self._db = self._cache = None
def close(self)
Close the database connection and render self invalid. Any subsequent re-use of self will raise an error.
5.075912
3.827902
1.32603
delay_in_seconds = delay.total_seconds() return partial(retry_loop, retries, delay_in_seconds, conditions)
def retry_handler(retries=0, delay=timedelta(), conditions=[])
A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. ...
4.459749
4.915564
0.907271
delay_in_seconds = delay.total_seconds() def decorator(function): @wraps(function) def wrapper(*args, **kwargs): func = partial(function, *args, **kwargs) return retry_loop(retries, delay_in_seconds, conditions, func) return wrapper ...
def retry(retries=0, delay=timedelta(), conditions=[])
A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry...
2.686253
3.42741
0.783756
if not isinstance(retries, Integral): raise TypeError(retries) if delay_in_seconds < 0: raise TypeError(delay_in_seconds) attempts = 0 value = None err = None while attempts <= retries: try: value = function() for condition in conditions: ...
def retry_loop(retries, delay_in_seconds, conditions, function)
Actually performs the retry loop used by the retry decorator and handler functions. Failures for retrying are defined by the RetryConditions passed in. If the maximum number of retries has been reached then it raises the most recent error or a ValueError on the most recent result value. Args: ...
2.723583
2.626584
1.03693
assert isinstance(gene_ontology, GeneOntology) assert isinstance(l, list) assert len(l) == 17 go_term = gene_ontology[l[4]] qualifier = l[3] or [] with_from = l[7] or None db_name = l[9] or None db_syn = l[10] or [] ext = l[15] or [] ...
def from_list(cls, gene_ontology, l)
Initialize a `GOAnnotation` object from a list (in GAF2.1 order). TODO: docstring
2.911218
2.727931
1.067189
go_id = self.go_term.id qual_str = '|'.join(self.qualifier) db_ref_str = '|'.join(self.db_ref) taxon_str = '|'.join(self.taxon) # with_from is currently left as a string # with_from = '|'.join() with_from_str = self.with_from or '' db_na...
def as_list(self)
Returns GO annotation as a flat list (in GAF 2.1 format order).
3.079676
2.860412
1.076655
fieldNames = fieldNames or FIELDS.split() nFields = len(fieldNames) if not nFields: raise ValueError('fieldNames cannot be empty.') c = Counter(fieldNames) if c.most_common(1)[0][1] > 1: raise ValueError( 'fieldNames contains duplicated names: %s.' % (',...
def diamondTabularFormatToDicts(filename, fieldNames=None)
Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -help' to see the full list. If C{None}, a default set of fields w...
3.358222
3.108236
1.080427
with as_handle(self._filename) as fp: previousQtitle = None subjectsSeen = {} record = {} for line in fp: line = line[:-1] try: (qtitle, stitle, bitscore, evalue, qframe, qseq, qstar...
def records(self)
Parse the DIAMOND output and yield records. This will be used to read original DIAMOND output (either from stdin or from a file) to turn the DIAMOND results into Python dictionaries that will then be stored in our JSON format. @return: A generator that produces C{dict}s containing 'alig...
3.065308
2.964021
1.034172
if writeBytes: fp.write(dumps(self.params, sort_keys=True).encode('UTF-8')) fp.write(b'\n') for record in self.records(): fp.write(dumps(record, sort_keys=True).encode('UTF-8')) fp.write(b'\n') else: fp.write(six.u(...
def saveAsJSON(self, fp, writeBytes=False)
Write the records out as JSON. The first JSON object saved contains information about the DIAMOND algorithm. @param fp: A C{str} file pointer to write to. @param writeBytes: If C{True}, the JSON will be written out as bytes (not strings). This is required when we are writing to a BZ...
1.753922
1.712107
1.024423
alignments = [] getScore = itemgetter('bits' if self._hspClass is HSP else 'expect') for diamondAlignment in diamondDict['alignments']: alignment = Alignment(diamondAlignment['length'], diamondAlignment['title']) alignments.appe...
def _dictToAlignments(self, diamondDict, read)
Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.alignmen...
4.337292
4.529177
0.957633
return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
def object_as_dict(obj)
Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058
2.903785
2.549982
1.138747
pk_field_instance = getattr(self.object_class, self.pk_field) qs = self.object_class.query.filter(pk_field_instance == model_id) model = qs.one_or_none() if not model: raise ReferenceNotFoundError return model
def fetch_object(self, model_id)
Fetch the model by its ID.
3.725744
3.53637
1.05355
DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%8==0, "bytecount: expects len(rx_dat)=8*x, but len(rx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 MAX_BYTES_LG = floor(log(MAX_BYTES,2)) MIN_COUNT_WIDTH = int(MAX_BYTES_LG) + 1 assert len(count)>=MIN_COUNT_WIDTH, "bytec...
def bytecount(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, count, MAX_BYTES=1500 )
Counts bytes in a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop count - (o) byte count MAX_BYTES - a limit: maximum numbe...
3.012937
3.102889
0.97101
file_mv = cli.file_mv desc = 'Extracts gene-level expression data from StringTie output.' parser = cli.get_argument_parser(desc) parser.add_argument( '-s', '--stringtie-file', type=str, required=True, metavar=file_mv, help= ) parser.add_argument( '-g', '--gene-fil...
def get_argument_parser()
Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx.
3.77732
4.037973
0.935449
return IxeApp(logger, IxTclHalApi(TclClient(logger, host, port, rsa_id)))
def init_ixe(logger, host, port=4555, rsa_id=None)
Connect to Tcl Server and Create IxExplorer object. :param logger: python logger object :param host: host (IxTclServer) IP address :param port: Tcl Server port :param rsa_id: full path to RSA ID file for Linux based IxVM :return: IXE object
13.369046
14.272754
0.936683
self.api._tcl_handler.connect() if user: self.session.login(user)
def connect(self, user=None)
Connect to host. :param user: if user - login session.
23.203985
23.205563
0.999932
self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1) self.chassis_chain[chassis].connect()
def add(self, chassis)
add chassis. :param chassis: chassis IP address.
4.850063
5.674791
0.854668
for port_location in ports_locations: ip, card, port = port_location.split('/') chassis = self.get_objects_with_attribute('chassis', 'ipAddress', ip)[0].id uri = '{} {} {}'.format(chassis, card, port) port = IxePort(parent=self, uri=uri) port...
def reserve_ports(self, ports_locations, force=False, clear=True, phy_mode=IxePhyMode.ignore)
Reserve ports and reset factory defaults. :param ports_locations: list of ports ports_locations <ip, card, port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user :param clear: True - clear port configuration and statistics, False - leave port as is...
4.307017
3.80356
1.132365
port_list = [] for port in ports: port_list.append(self.set_ports_list(port)) t_end = time.time() + timeout ports_not_in_up = [] ports_in_up = [] while time.time() < t_end: # ixCheckLinkState can take few seconds on some ports when link is...
def wait_for_up(self, timeout=16, ports=None)
Wait until ports reach up state. :param timeout: seconds to wait. :param ports: list of ports to wait for. :return:
3.218441
3.214896
1.001103
port_list = self.set_ports_list(*ports) self.api.call_rc('ixClearStats {}'.format(port_list)) self.api.call_rc('ixClearPacketGroups {}'.format(port_list))
def clear_all_stats(self, *ports)
Clear all statistic counters (port, streams and packet groups) on list of ports. :param ports: list of ports to clear.
8.310327
7.795565
1.066033
port_list = self.set_ports_list(*ports) if start_packet_groups: port_list_for_packet_groups = self.ports.values() port_list_for_packet_groups = self.set_ports_list(*port_list_for_packet_groups) self.api.call_rc('ixClearTimeStamp {}'.format(port_list_for_pack...
def start_transmit(self, blocking=False, start_packet_groups=True, *ports)
Start transmit on ports. :param blocking: True - wait for traffic end, False - return after traffic start. :param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports.
3.154155
3.062871
1.029803
port_list = self.set_ports_list(*ports) if clear_time_stamps: self.api.call_rc('ixClearTimeStamp {}'.format(port_list)) self.api.call_rc('ixStartPacketGroups {}'.format(port_list))
def start_packet_groups(self, clear_time_stamps=True, *ports)
Start packet groups on ports. :param clear_time_stamps: True - clear time stamps, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports.
5.201653
5.422229
0.95932
port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopTransmit {}'.format(port_list)) time.sleep(0.2)
def stop_transmit(self, *ports)
Stop traffic on ports. :param ports: list of ports to stop traffic on, if empty start on all ports.
10.577854
11.929341
0.886709
port_list = self.set_ports_list(*ports) self.api.call_rc('ixCheckTransmitDone {}'.format(port_list))
def wait_transmit(self, *ports)
Wait for traffic end on ports. :param ports: list of ports to wait for, if empty wait for all ports.
17.582968
18.228683
0.964577
IxeCapture.current_object = None IxeCaptureBuffer.current_object = None if not ports: ports = self.ports.values() for port in ports: port.captureBuffer = None port_list = self.set_ports_list(*ports) self.api.call_rc('ixStartCapture {}'.fo...
def start_capture(self, *ports)
Start capture on ports. :param ports: list of ports to start capture on, if empty start on all ports.
8.665235
9.341269
0.927629
port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopCapture {}'.format(port_list)) nPackets = {} for port in (ports if ports else self.ports.values()): nPackets[port] = port.capture.nPackets if nPackets[port]: if cap_file_for...
def stop_capture(self, cap_file_name=None, cap_file_format=IxeCapFileFormat.mem, *ports)
Stop capture on ports. :param cap_file_name: prefix for the capture file name. Capture files for each port are saved as individual pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :param ports: list of ports to stop traffic on, if empty stop all po...
4.903557
3.940756
1.244319
cap_files = {} for port in ports: if port.cap_file_name: with open(port.cap_file_name) as f: cap_files[port] = f.read().splitlines() else: cap_files[port] = None return cap_files
def get_cap_files(self, *ports)
:param ports: list of ports to get capture files names for. :return: dictionary (port, capture file)
2.240331
2.307961
0.970697
if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() groupIdOffset = start_offset signatureOffset = start_offset + 4 n...
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True)
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_por...
2.621909
2.453209
1.068767
if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self.ports.values(): tx_ports[port] = port.streams.values() for port in rx_ports: port.set_receive_modes(IxeReceiveMode.widePacke...
def set_prbs(self, rx_ports=None, tx_ports=None)
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX PRBS. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX PRBS. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_p...
5.53779
4.426775
1.250976
c = str(c) if c[0:3] == 'chr': c = c[3:] if c == '23': c = 'X' if c == '24': c = 'Y' return 'chr' + c
def chr22XY(c)
force to name from 1..22, 23, 24, X, Y, M to in chr1..chr22, chrX, chrY, chrM str or ints accepted >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23"...
2.256038
2.530259
0.891624
namespaces = infer_namespaces(ac) if not namespaces: return None if len(namespaces) > 1: raise BioutilsError("Multiple namespaces possible for {}".format(ac)) return namespaces[0]
def infer_namespace(ac)
Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infe...
4.759747
2.504932
1.90015
return [v for k, v in ac_namespace_regexps.items() if k.match(ac)]
def infer_namespaces(ac)
infer possible namespaces of given accession based on syntax Always returns a list, possibly empty >>> infer_namespaces("ENST00000530893.6") ['ensembl'] >>> infer_namespaces("ENST00000530893") ['ensembl'] >>> infer_namespaces("ENSQ00000530893") [] >>> infer_namespaces("NM_01234") ['...
8.811722
11.922978
0.739054
if len([interval for interval in self if other in interval]) > 0: # if other is already represented return # remove any intervals which are fully represented by the interval we are adding to_remove = [interval for interval in self if interval in other] self._data.di...
def _add(self, other)
Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that any requirements have already been checked and that this function is being called by an internal function such as union(), intersection() or add(). :param other: An Interval to add to this ...
5.372101
4.656855
1.15359
# if self or other is empty the intersection will be empty result = IntervalSet() for other_inter in other: for interval in self: this_intervals_intersection = other_inter.intersect(interval) if this_intervals_intersection is not None: ...
def intersection(self, other)
Returns a new IntervalSet which represents the intersection of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet. :param other: An IntervalSet to intersect with this one.
4.406684
4.024697
1.094911
result = IntervalSet() for el in self: result.add(el) for el in other: result.add(el) return result
def union(self, other)
Returns a new IntervalSet which represents the union of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet :param other: An IntervalSet to union with this one.
2.790392
2.541057
1.098123
if other.empty(): return to_add = set() for inter in self: if inter.overlaps(other): # if it overlaps with this interval then the union will be a single interval to_add.add(inter.union(other)) if len(to_add) == 0: # other must not overl...
def add(self, other)
Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing Interval objects in self. This has no effect if the Interval is already represented. :param other: an Interval to add to this IntervalSet.
4.195842
3.835651
1.093906
intervals = other if isinstance(other, IntervalSet) else IntervalSet((other,)) result = IntervalSet() for left in self: for right in intervals: left = left - right if isinstance(left, IntervalSet): for interval in left: ...
def difference(self, other)
Subtract an Interval or IntervalSet from the intervals in the set.
2.867483
2.339586
1.225637
if self._pebble.firmware_version.major < 3: self._send_legacy_notification(subject, message, sender, source) else: self._send_modern_notification(subject, message, sender, source, actions)
def send_notification(self, subject="", message="", sender="", source=None, actions=None)
Sends a notification. Blocks as long as necessary. :param subject: The subject. :type subject: str :param message: The message. :type message: str :param sender: The sender. :type sender: str :param source: The source of the notification :type source: .Le...
3.950014
4.636727
0.851897
lst = [ b"hello world", b"this is bytes", b"awesome django", b"djipsum is awesome", b"\x00\x01\x02\x03\x04\x05\x06\x07", b"\x0b\x0c\x0e\x0f" ] return self.randomize(lst)
def randomBinaryField(self)
Return random bytes format.
3.866021
3.60017
1.073844
try: available_choices = model_class._meta.get_field(field_name).get_choices()[1:] return self.randomize([ci[0] for ci in available_choices]) except AttributeError: lst = [ "Enthusiastically whiteboard synergistic methods", "A...
def randomCharField(self, model_class, field_name)
Checking if `field_name` has choices. Then, returning random value from it. Result of: `available_choices` [ ('project', 'I wanna to talk about project'), ('feedback', 'I want to report a bugs or give feedback'), ('hello', 'I just want to say hello') ]
16.721235
15.975697
1.046667
randint = lambda max: ",".join( [str(x) for x in random.sample(range(1, 10), max)] ) lst = [ randint(3), randint(5), randint(7), randint(9) ] return self.randomize(lst)
def randomCommaSeparatedIntegerField(self)
Return the unique integers in the string such as below: '6,1,7' or '4,5,1,3,2' or '2,7,9,3,5,4,1' or '3,9,2,8,7,1,5,4,6'
3.562212
3.802977
0.93669
decimal_field = model_class._meta.get_field(field_name) max_digits = None decimal_places = None if decimal_field.max_digits is not None: max_digits = decimal_field.max_digits if decimal_field.decimal_places is not None: decimal_places = decimal_f...
def randomDecimalField(self, model_class, field_name)
Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number.
2.366777
2.356887
1.004197
lst = [ "sample-slug-{}".format(uuid.uuid4().hex), "awesome-djipsum-{}".format(uuid.uuid4().hex), "unique-slug-{}".format(uuid.uuid4().hex) ] return self.randomize(lst)
def randomSlugField(self)
Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True)
4.796998
4.399745
1.09029
uuid1 = uuid.uuid1().hex uuid3 = uuid.uuid3( uuid.NAMESPACE_URL, self.randomize(['python', 'django', 'awesome']) ).hex uuid4 = uuid.uuid4().hex uuid5 = uuid.uuid5( uuid.NAMESPACE_DNS, self.randomize(['python', 'django', 'aw...
def randomUUIDField(self)
Return the unique uuid from uuid1, uuid3, uuid4, or uuid5.
2.377825
2.10934
1.127284
# Getting related object type # Eg: <django.db.models.fields.related.ForeignKey: test_ForeignKey> instance = getattr(model_class, field_name).field # Getting the model name by instance to find/create first id/pk. # Eg: <class 'django.contrib.auth.models.User'> r...
def getOrCreateForeignKey(self, model_class, field_name)
Return related random object to set as ForeignKey.
6.827024
6.330263
1.078474
return self._get(GetBytesFlashRequest(offset=offset, length=length))
def get_flash_region(self, offset, length)
Retrieves the contents of a region of flash from the watch. This only works on watches running non-release firmware. Raises :exc:`.GetBytesError` on failure. :return: The retrieved data :rtype: bytes
18.902418
24.538347
0.770322
# We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(ScreenshotResponse) self._pebble.send_packet(ScreenshotRequest()) return self._read_screenshot(queue)
def grab_image(self)
Takes a screenshot. Blocks until completion, or raises a :exc:`.ScreenshotError` on failure. While this method is executing, "progress" events will periodically be emitted with the following signature: :: (downloaded_so_far, total_size) :return: A list of bytearrays in RGB8 format, where e...
13.017352
14.238406
0.914242
from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
def trade_day(dt, cal='US')
Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24'
6.179526
8.23091
0.750771
dt = pd.Timestamp('now', tz=tz) if typ == 'date': if trading: return trade_day(dt=dt, cal=cal).strftime('%Y-%m-%d') else: return dt.strftime('%Y-%m-%d') if typ == 'time': return dt.strftime('%Y-%m-%d %H:%M:%S') if typ == 'time_path': return dt.strftime('%Y-%m-%d/%H-%M-%S') if ...
def cur_time(typ='date', tz=DEFAULT_TZ, trading=True, cal='US')
Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(t...
2.592003
2.319539
1.117464
if len(data_kw) == 0: return pd.DataFrame() return pd.DataFrame(pd.concat([ data.assign(ticker=ticker).set_index('ticker', append=True) .unstack('ticker').swaplevel(0, 1, axis=1) for ticker, data in data_kw.items() ], axis=1))
def cat_data(data_kw)
Concatenate data with ticker as sub column index Args: data_kw: key = ticker, value = pd.DataFrame Returns: pd.DataFrame Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(...
3.082102
3.23508
0.952713
from collections import OrderedDict return pd.DataFrame( pd.Series(data_list).apply(OrderedDict).tolist(), **kwargs ).drop(columns=[] if exc_cols is None else exc_cols)
def to_frame(data_list, exc_cols=None, **kwargs)
Dict in Python 3.6 keeps insertion order, but cannot be relied upon This method is to keep column names in order In Python 3.7 this method is redundant Args: data_list: list of dict exc_cols: exclude columns Returns: pd.DataFrame Example: >>> d_list = [ ......
4.931409
6.253967
0.788525
from scipy.interpolate import interp1d from collections import OrderedDict if isinstance(y, pd.DataFrame): return pd.DataFrame(OrderedDict([(col, spline_curve( x, y.loc[:, col], step=step, val_min=val_min, val_max=val_max, kind=kind )) for col in y.columns])) fitted_cur...
def spline_curve(x, y, step, val_min=0, val_max=None, kind='quadratic', **kwargs)
Fit spline curve for given x, y values Args: x: x-values y: y-values step: step size for interpolation val_min: minimum value of result val_max: maximum value of result kind: for scipy.interpolate.interp1d Specifies the kind of interpolation as a string (‘lin...
2.234981
2.27943
0.9805
if is_pct: space = ' ' if digit < 0 else '' fmt = f'{{:{space}.{abs(int(digit))}%}}' return lambda vv: 'NaN' if np.isnan(vv) else fmt.format(vv) else: return lambda vv: 'NaN' if np.isnan(vv) else ( f'{{:,.{digit}f}}'.format(vv) if vv else '-' + ' ' * abs(digit) ...
def format_float(digit=0, is_pct=False)
Number display format for pandas Args: digit: number of digits to keep if negative, add one space in front of positive pct is_pct: % display Returns: lambda function to format floats Examples: >>> format_float(0)(1e5) '100,000' >>> format_flo...
3.60441
3.779306
0.953723
if not hasattr(instance, '__dict__'): return '' if public_only: inst_dict = {k: v for k, v in instance.__dict__.items() if k[0] != '_'} else: inst_dict = instance.__dict__ if fmt == 'json': return json.dumps(inst_dict, indent=2) elif fmt == 'str': return to_str(inst_dict, public_only=public_o...
def inst_repr(instance, fmt='str', public_only=True)
Generate class instance signature from its __dict__ From python 3.6 dict is ordered and order of attributes will be preserved automatically Args: instance: class instance fmt: ['json', 'str'] public_only: if display public members only Returns: str: string or json represent...
2.033966
2.174697
0.935287
expr = " {0} ".format(operator).join(conditions) return ["({0})".format(expr)] if expr else []
def concat_expr(operator, conditions)
Concatenate `conditions` with `operator` and wrap it by (). It returns a string in a list or empty list, if `conditions` is empty.
4.461503
4.714738
0.946289
if isinstance(source, SQLConstructor): (sql, params, _) = source.compile() self.join_params.extend(params) jsrc = '( {0} )'.format(sql) if source.table_alias: jsrc += ' AS ' + source.table_alias on = on.format(r=source.tabl...
def join(self, source, op='LEFT JOIN', on='')
Join `source`. >>> sc = SQLConstructor('main', ['c1', 'c2']) >>> sc.join('sub', 'JOIN', 'main.id = sub.id') >>> (sql, params, keys) = sc.compile() >>> sql 'SELECT c1, c2 FROM main JOIN sub ON main.id = sub.id' It is possible to pass another `SQLConstructor` as a source....
3.55824
2.931334
1.213864
params = self.column_params + self.join_params + self.params if self.limit and self.limit >= 0: self.sql_limit = 'LIMIT ?' params += [self.limit] return (self.sql, params, self.keys)
def compile(self)
Compile SQL and return 3-tuple ``(sql, params, keys)``. Example usage:: (sql, params, keys) = sc.compile() for row in cursor.execute(sql, params): record = dict(zip(keys, row))
5.909153
5.115899
1.155057
params = self._adapt_params(params) qs = ['?'] * numq flatten = flatten or self._default_flatten(numq) expr = repeat(adapt_matcher(matcher)(lhs, *qs), len(params)) self.conditions.extend(expr) self.params.extend(flatten(params))
def add_and_matches(self, matcher, lhs, params, numq=1, flatten=None)
Add AND conditions to match to `params`. :type matcher: str or callable :arg matcher: if `str`, `matcher.format` is used. :type lhs: str :arg lhs: the first argument to `matcher`. :type params: list :arg params: each element should be able to feed into sqlit...
7.674743
6.363172
1.206119
matcher = adapt_matcher(matcher) notmatcher = negate(matcher) self.add_and_matches(matcher, lhs, match_params, numq, flatten) self.add_or_matches(matcher, lhs, include_params, numq, flatten) self.add_and_matches(notmatcher, lhs, exclude_params, numq, flatten)
def add_matches(self, matcher, lhs, match_params=[], include_params=[], exclude_params=[], numq=1, flatten=None)
Quick way to call `add_or_matches` and `add_and_matches`.
2.555605
2.242005
1.139874
self.group_by.append(column) if chooser: i = self.columns.index(chooser) self.columns[i] = '{0}({1})'.format(aggregate, self.columns[i])
def uniquify_by(self, column, chooser=None, aggregate='MAX')
Group by `column` and run `aggregate` function on `chooser` column.
3.351482
2.892423
1.158711
if self.conditions: expr = " AND ".join(self.conditions) params = self.params self.params = [] self.conditions = [] else: expr = '1' params = [] self.add_column('({0}) AS {1}'.format(expr, column), ...
def move_where_clause_to_column(self, column='condition', key=None)
Move whole WHERE clause to a column named `column`.
4.161673
4.035949
1.031151
'''remove upper and right axis''' for loc, spine in ax.spines.items(): if loc in which: spine.set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left')
def remove_axis_junk(ax, which=['right', 'top'])
remove upper and right axis
2.30718
2.188506
1.054226
''' on axes plot the signal contributions args: :: ax : matplotlib.axes.AxesSubplot object z : np.ndarray T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, scaling_factor : float, s...
def plot_signal_sum(ax, z, fname='LFPsum.h5', unit='mV', ylabels=True, scalebar=True, vlimround=None, T=[0, 1000], color='k', label='')
on axes plot the signal contributions args: :: ax : matplotlib.axes.AxesSubplot object z : np.ndarray T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, scaling_factor : float, scaling facto...
3.393941
2.465986
1.376302