INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
map all read sets against all fasta files | def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... |
Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines. | def get_conn(self, *args, **kwargs):
"""
Returns a connection object from the router given ``args``.
Useful in cases where a connection cannot be automatically determined
during all steps of the process. An example of this would be
Redis pipelines.
"""
connection... |
mask (make lower case) regions of sequence found in gaps between model alignments | def mask_sequence(seq, gaps):
"""
mask (make lower case) regions of sequence found in gaps between model alignments
"""
seq = [i.upper() for i in seq]
for gap in gaps:
for i in range(gap[0] - 1, gap[1]):
seq[i] = seq[i].lower()
return ''.join(seq) |
1) parse hmm output into dictionary (sequence must pass bit_thresh and inc == '!')
seq2hmm[seq] = {model: [sstart, ssend, length, strand, score]}
2) determine which model (archaea, bacteria, eukarya) the sequence most closely matches
seq2hmm[seq] = [model, sstart, send, length, strand, score], [mod... | def find_23S(fastas, hmms, bit_thresh = float(20), length_thresh = 500, masking = True, buffer = 0):
"""
1) parse hmm output into dictionary (sequence must pass bit_thresh and inc == '!')
seq2hmm[seq] = {model: [sstart, ssend, length, strand, score]}
2) determine which model (archaea, bacteria, euk... |
run cmsearch: comapre 23S sequences to ssu-align's CM | def run_cmsearch(fastas, threads, cm):
"""
run cmsearch: comapre 23S sequences to ssu-align's CM
"""
out = []
for fasta in fastas:
cmsearch = '%s.23S.cmsearch' % (fasta.name.rsplit('.', 1)[0])
if os.path.exists(cmsearch) is False:
p = Popen('\
cmsearch... |
return the non-direct init if the direct algorithm has been selected. | def __get_nondirect_init(self, init):
"""
return the non-direct init if the direct algorithm has been selected.
"""
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
... |
reflect a data word, i.e. reverts the bit order. | def reflect(self, data, width):
"""
reflect a data word, i.e. reverts the bit order.
"""
x = data & 0x01
for i in range(width - 1):
data >>= 1
x = (x << 1) | (data & 0x01)
return x |
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end. | def bit_by_bit(self, in_data):
"""
Classic simple and slow CRC implementation. This function iterates bit
by bit over the augmented input message and returns the calculated CRC
value at the end.
"""
# If the input data is a string, convert to bytes.
if isinstance... |
This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead. | def gen_table(self):
"""
This function generates the CRC table used for the table_driven CRC
algorithm. The Python version cannot handle tables of an index width
other than 8. See the generated C code for tables with different sizes
instead.
"""
table_length = 1... |
The Standard table_driven CRC algorithm. | def table_driven(self, in_data):
"""
The Standard table_driven CRC algorithm.
"""
# If the input data is a string, convert to bytes.
if isinstance(in_data, str):
in_data = [ord(c) for c in in_data]
tbl = self.gen_table()
register = self.DirectInit <<... |
:type taxF: file
:param taxF: The taxonomy output file to parse
:type level: string
:param level: The level of the phylogenetic assignment at which to cut off
every assigned taxonomic string.
:rtype: dict
:return: A dictionary of taxonomy strings keyed on OTU ID | def prune_taxonomy(taxF, level):
"""
:type taxF: file
:param taxF: The taxonomy output file to parse
:type level: string
:param level: The level of the phylogenetic assignment at which to cut off
every assigned taxonomic string.
:rtype: dict
:return: A dictionary of taxon... |
get_publisher | def get_publisher():
"""get_publisher"""
log.info("initializing publisher")
pub = None
auth_url = ""
if FORWARD_ENDPOINT_TYPE == "redis":
auth_url = FORWARD_BROKER_URL
else:
auth_url = FORWARD_BROKER_URL
pub = Publisher(name="{}_{}".format(SOURCE, "-redis"),
... |
recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject | def recv_msg(body,
message):
"""recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject
"""
log.info(("ca... |
consume_network_packet_messages_from_redis
Setup a ``celery_connectors.KombuSubscriber`` to consume meessages
from the ``FORWARD_BROKER_URL`` broker in the ``FORWARD_QUEUE``
queue. | def consume_network_packet_messages_from_redis():
"""consume_network_packet_messages_from_redis
Setup a ``celery_connectors.KombuSubscriber`` to consume meessages
from the ``FORWARD_BROKER_URL`` broker in the ``FORWARD_QUEUE``
queue.
"""
# end of recv_message
# Initialize KombuSubscriber
... |
parse masked sequence into non-masked and masked regions | def parse_masked(seq, min_len):
"""
parse masked sequence into non-masked and masked regions
"""
nm, masked = [], [[]]
prev = None
for base in seq[1]:
if base.isupper():
nm.append(base)
if masked != [[]] and len(masked[-1]) < min_len:
nm.extend(mas... |
remove masked regions from fasta file as long as
they are longer than min_len | def strip_masked(fasta, min_len, print_masked):
"""
remove masked regions from fasta file as long as
they are longer than min_len
"""
for seq in parse_fasta(fasta):
nm, masked = parse_masked(seq, min_len)
nm = ['%s removed_masked >=%s' % (seq[0], min_len), ''.join(nm)]
yield ... |
Return arcsine transformed relative abundance from a BIOM format file.
:type biomfile: BIOM format file
:param biomfile: BIOM format file used to obtain relative abundances for each OTU in
a SampleID, which are used as node sizes in network plots.
:type return: Dictionary of dictionar... | def get_relative_abundance(biomfile):
"""
Return arcsine transformed relative abundance from a BIOM format file.
:type biomfile: BIOM format file
:param biomfile: BIOM format file used to obtain relative abundances for each OTU in
a SampleID, which are used as node sizes in network... |
build_training_request
:param csv_file: csv file built with prepare_dataset.py
:param meta_file: metadata file built with prepare_dataset.py
:param predict_feature: feature (column) to predict
:param ignore_features: features to remove from the csv
before the split of test +... | def build_training_request(
csv_file=ev(
"CSV_FILE",
"/tmp/cleaned_attack_scans.csv"),
meta_file=ev(
"CSV_META_FILE",
"/tmp/cleaned_metadata.json"),
predict_feature=ev(
"PREDICT_FEATURE",
"label_value"),
ignore_featu... |
Find an OTU ID in a Newick-format tree.
Return the starting position of the ID or None if not found. | def find_otu(otuid, tree):
"""
Find an OTU ID in a Newick-format tree.
Return the starting position of the ID or None if not found.
"""
for m in re.finditer(otuid, tree):
before, after = tree[m.start()-1], tree[m.start()+len(otuid)]
if before in ["(", ",", ")"] and after in [":", ";"... |
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names | def newick_replace_otuids(tree, biomf):
"""
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names
"""
for val, id_, md in biomf.iter(axis="observation"):
otu_loc = find_otu(id_, tree)
if otu_loc is not None:
tree = tree[:otu_loc] + \
... |
start_consumers_for_queue
:param prefix_name:
:param num_workers:
:param tasks:
:param queue_to_consume:
:param shutdown_msg:
:param consumer_class:
:param need_response:
:param callback: | def start_consumers_for_queue(prefix_name="worker",
num_workers=2,
tasks=None,
queue_to_consume=None,
shutdown_msg="SHUTDOWN",
consumer_class=None,
... |
Create mash files for multiple fasta files
Input:
fastas <list[str]> -- paths to fasta files
mash_file <str> -- path to output mash file
threads <int> -- # threads for parallelization
kmer <int> -- kmer size for mash sketching
force <boolean> -- force ... | def make_mashes(fastas, mash_file, threads, kmer = 21, force = False):
"""
Create mash files for multiple fasta files
Input:
fastas <list[str]> -- paths to fasta files
mash_file <str> -- path to output mash file
threads <int> -- # threads for parallelization
kmer <... |
Combine mash files into single sketch
Input:
sketches <list[str]> -- paths to sketch files
pasted_mash <str> -- path to output mash file
force <boolean> -- force overwrite of all mash file | def paste_mashes(sketches, pasted_mash, force = False):
"""
Combine mash files into single sketch
Input:
sketches <list[str]> -- paths to sketch files
pasted_mash <str> -- path to output mash file
force <boolean> -- force overwrite of all mash file
"""
if os.path.isf... |
Use mash to estimate ANI of genomes
Input:
fastas <list[str]> -- paths to fasta files
sim_threshold <float> -- fractional cutoff % identity for cluster joining
mash_file <str> -- pasted sketch file of all fastas being compared
threads <int> -- number threads ... | def ani(fastas, mash_file, sim_threshold, threads):
"""
Use mash to estimate ANI of genomes
Input:
fastas <list[str]> -- paths to fasta files
sim_threshold <float> -- fractional cutoff % identity for cluster joining
mash_file <str> -- pasted sketch file of all fastas b... |
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome | def genome_info(genome, info):
"""
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
"""
try:
scg = info['#SCG... |
choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome | def print_clusters(fastas, info, ANI):
"""
choose represenative genome and
print cluster information
*if ggKbase table is provided, use SCG info to choose best genome
"""
header = ['#cluster', 'num. genomes', 'rep.', 'genome', '#SCGs', '#SCG duplicates', \
'genome size (bp)', 'fragm... |
convert ggKbase genome info tables to dictionary | def parse_ggKbase_tables(tables, id_type):
"""
convert ggKbase genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('name'):
header = line
h... |
convert checkM genome info tables to dictionary | def parse_checkM_tables(tables):
"""
convert checkM genome info tables to dictionary
"""
g2info = {}
for table in tables:
for line in open(table):
line = line.strip().split('\t')
if line[0].startswith('Bin Id'):
header = line
header[8] ... |
get genome lengths | def genome_lengths(fastas, info):
"""
get genome lengths
"""
if info is False:
info = {}
for genome in fastas:
name = genome.rsplit('.', 1)[0].rsplit('/', 1)[-1].rsplit('.contigs')[0]
if name in info:
continue
length = 0
fragments = 0
for s... |
listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this number of seconds per loop
``L... | def listen_on_tcp_port():
"""listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this nu... |
Returns a list of db keys to route the given call to.
:param attr: Name of attribute being called on the connection.
:param args: List of arguments being passed to ``attr``.
:param kwargs: Dictionary of keyword arguments being passed to ``attr``.
>>> redis = Cluster(router=BaseRouter)
... | def get_dbs(self, attr, args, kwargs, **fkwargs):
"""
Returns a list of db keys to route the given call to.
:param attr: Name of attribute being called on the connection.
:param args: List of arguments being passed to ``attr``.
:param kwargs: Dictionary of keyword arguments bein... |
Call method to perform any setup | def setup_router(self, args, kwargs, **fkwargs):
"""
Call method to perform any setup
"""
self._ready = self._setup_router(args=args, kwargs=kwargs, **fkwargs)
return self._ready |
Perform routing and return db_nums | def _route(self, attr, args, kwargs, **fkwargs):
"""
Perform routing and return db_nums
"""
return self.cluster.hosts.keys() |
Iterates through all connections which were previously listed as unavailable
and marks any that have expired their retry_timeout as being up. | def check_down_connections(self):
"""
Iterates through all connections which were previously listed as unavailable
and marks any that have expired their retry_timeout as being up.
"""
now = time.time()
for db_num, marked_down_at in self._down_connections.items():
... |
Marks all connections which were previously listed as unavailable as being up. | def flush_down_connections(self):
"""
Marks all connections which were previously listed as unavailable as being up.
"""
self._get_db_attempts = 0
for db_num in self._down_connections.keys():
self.mark_connection_up(db_num) |
Compute standby power
Parameters
----------
df : pandas.DataFrame or pandas.Series
Electricity Power
resolution : str, default='d'
Resolution of the computation. Data will be resampled to this resolution (as mean) before computation
of the minimum.
String that can be pa... | def standby(df, resolution='24h', time_window=None):
"""
Compute standby power
Parameters
----------
df : pandas.DataFrame or pandas.Series
Electricity Power
resolution : str, default='d'
Resolution of the computation. Data will be resampled to this resolution (as mean) before ... |
Compute the share of the standby power in the total consumption.
Parameters
----------
df : pandas.DataFrame or pandas.Series
Power (typically electricity, can be anything)
resolution : str, default='d'
Resolution of the computation. Data will be resampled to this resolution (as mean) ... | def share_of_standby(df, resolution='24h', time_window=None):
"""
Compute the share of the standby power in the total consumption.
Parameters
----------
df : pandas.DataFrame or pandas.Series
Power (typically electricity, can be anything)
resolution : str, default='d'
Resolution... |
Toggle counter for gas boilers
Counts the number of times the gas consumption increases with more than 3kW
Parameters
----------
ts: Pandas Series
Gas consumption in minute resolution
Returns
-------
int | def count_peaks(ts):
"""
Toggle counter for gas boilers
Counts the number of times the gas consumption increases with more than 3kW
Parameters
----------
ts: Pandas Series
Gas consumption in minute resolution
Returns
-------
int
"""
on_toggles = ts.diff() > 3000
... |
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input timeseries
norm : int | float, optional
denominator... | def load_factor(ts, resolution=None, norm=None):
"""
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input ti... |
build_new_deep_neural_network_from_env_variables
Build a new deep neural network from environment variables:
``CSV_FILE`` - file to process created during prepare dataset
``CSV_META_FILE`` - metadata header file created during prepare dataset
``PREDICT_FEATURE`` - column to predict
``TEST_SIZE`` -... | def build_new_deep_neural_network_from_env_variables():
"""build_new_deep_neural_network_from_env_variables
Build a new deep neural network from environment variables:
``CSV_FILE`` - file to process created during prepare dataset
``CSV_META_FILE`` - metadata header file created during prepare dataset
... |
create_layer_2_socket | def create_layer_2_socket():
"""create_layer_2_socket"""
# create a socket for recording layer 2, 3 and 4 frames
s = None
try:
log.info("Creating l234 socket")
s = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.ntohs(0x0003))
... |
get top hits after sorting by column number | def top_hits(hits, num, column, reverse):
"""
get top hits after sorting by column number
"""
hits.sort(key = itemgetter(column), reverse = reverse)
for hit in hits[0:num]:
yield hit |
parse b6 output with sorting | def numBlast_sort(blast, numHits, evalueT, bitT):
"""
parse b6 output with sorting
"""
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
'qstart', 'qend', 'tstart', 'tend', 'evalue', 'bitscore']
yield header
hmm = {h:[] for h in header}
for line in blast:
... |
parse b6 output | def numBlast(blast, numHits, evalueT = False, bitT = False, sort = False):
"""
parse b6 output
"""
if sort is True:
for hit in numBlast_sort(blast, numHits, evalueT, bitT):
yield hit
return
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
... |
parse hmm domain table output
this version is faster but does not work unless the table is sorted | def numDomtblout(domtblout, numHits, evalueT, bitT, sort):
"""
parse hmm domain table output
this version is faster but does not work unless the table is sorted
"""
if sort is True:
for hit in numDomtblout_sort(domtblout, numHits, evalueT, bitT):
yield hit
return
head... |
convert stockholm to fasta | def stock2fa(stock):
"""
convert stockholm to fasta
"""
seqs = {}
for line in stock:
if line.startswith('#') is False and line.startswith(' ') is False and len(line) > 3:
id, seq = line.strip().split()
id = id.rsplit('/', 1)[0]
id = re.split('[0-9]\|', id,... |
concatenate alignments | def concat_align(fastas):
"""
concatenate alignments
"""
# read in sequences
fa2len = {}
seqs = {}
IDs = []
for fasta in fastas:
seqs[fasta] = {}
for seq in parse_fasta(fasta):
ID = seq[0].split('>')[1].split()[0]
IDs.append(ID)
seqs[fa... |
Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : str or datetime.time
Daily closing time. Default: '17:00'
off_days :... | def week_schedule(index, on_time=None, off_time=None, off_days=None):
""" Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : st... |
Draw a carpet plot of a pandas timeseries.
The carpet plot reads like a letter. Every day one line is added to the
bottom of the figure, minute for minute moving from left (morning) to right
(evening).
The color denotes the level of consumption and is scaled logarithmically.
If vmin and vmax are no... | def carpet(timeseries, **kwargs):
"""
Draw a carpet plot of a pandas timeseries.
The carpet plot reads like a letter. Every day one line is added to the
bottom of the figure, minute for minute moving from left (morning) to right
(evening).
The color denotes the level of consumption and is scale... |
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plot_ids: [str]
List of id's to plot
Returns
-------
matplotlib figure | def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None):
"""
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plo... |
calculate percent identity | def calc_pident_ignore_gaps(a, b):
"""
calculate percent identity
"""
m = 0 # matches
mm = 0 # mismatches
for A, B in zip(list(a), list(b)):
if A == '-' or A == '.' or B == '-' or B == '.':
continue
if A == B:
m += 1
else:
mm += 1
t... |
skip column if either is a gap | def remove_gaps(A, B):
"""
skip column if either is a gap
"""
a_seq, b_seq = [], []
for a, b in zip(list(A), list(B)):
if a == '-' or a == '.' or b == '-' or b == '.':
continue
a_seq.append(a)
b_seq.append(b)
return ''.join(a_seq), ''.join(b_seq) |
compare pairs of sequences | def compare_seqs(seqs):
"""
compare pairs of sequences
"""
A, B, ignore_gaps = seqs
a, b = A[1], B[1] # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
if ignore_gaps is True:
pident = calc_pident_ignore_gaps(a, b... |
calculate Levenshtein ratio of sequences | def compare_seqs_leven(seqs):
"""
calculate Levenshtein ratio of sequences
"""
A, B, ignore_gaps = seqs
a, b = remove_gaps(A[1], B[1]) # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
pident = lr(a, b) * 100
return A... |
make pairwise sequence comparisons between aligned sequences | def pairwise_compare(afa, leven, threads, print_list, ignore_gaps):
"""
make pairwise sequence comparisons between aligned sequences
"""
# load sequences into dictionary
seqs = {seq[0]: seq for seq in nr_fasta([afa], append_index = True)}
num_seqs = len(seqs)
# define all pairs
pairs = (... |
- convert list of comparisons to dictionary
- print list of pidents (if requested) to stderr | def to_dictionary(pw, print_list):
"""
- convert list of comparisons to dictionary
- print list of pidents (if requested) to stderr
"""
pairs = {}
for p in pw:
a, b, pident = p
if a not in pairs:
pairs[a] = {a: '-'}
if b not in pairs:
pairs[b] = {b... |
print matrix of pidents to stdout | def print_pairwise(pw, median = False):
"""
print matrix of pidents to stdout
"""
names = sorted(set([i for i in pw]))
if len(names) != 0:
if '>' in names[0]:
yield ['#'] + [i.split('>')[1] for i in names if '>' in i]
else:
yield ['#'] + names
for a in... |
print stats for comparisons | def print_comps(comps):
"""
print stats for comparisons
"""
if comps == []:
print('n/a')
else:
print('# min: %s, max: %s, mean: %s' % \
(min(comps), max(comps), np.mean(comps))) |
print min. pident within each clade and then matrix of between-clade max. | def compare_clades(pw):
"""
print min. pident within each clade and then matrix of between-clade max.
"""
names = sorted(set([i for i in pw]))
for i in range(0, 4):
wi, bt = {}, {}
for a in names:
for b in pw[a]:
if ';' not in a or ';' not in b:
... |
convert matrix to dictionary of comparisons | def matrix2dictionary(matrix):
"""
convert matrix to dictionary of comparisons
"""
pw = {}
for line in matrix:
line = line.strip().split('\t')
if line[0].startswith('#'):
names = line[1:]
continue
a = line[0]
for i, pident in enumerate(line[1:]... |
Set argument parser option. | def setoption(parser, metadata=None):
"""Set argument parser option."""
parser.add_argument('-v', action='version',
version=__version__)
subparsers = parser.add_subparsers(help='sub commands help')
create_cmd = subparsers.add_parser('create')
create_cmd.add_argument('name',
... |
Validate url.
:rtype: str
:return: url
:param str url: package homepage url. | def valid_url(url):
"""Validate url.
:rtype: str
:return: url
:param str url: package homepage url.
"""
regex = re.compile(
r'^(?:http)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))'
r'(?:/?|[/?]\S+)$', re.IGNORECA... |
Parse argument options. | def parse_options(metadata):
"""Parse argument options."""
parser = argparse.ArgumentParser(description='%(prog)s usage:',
prog=__prog__)
setoption(parser, metadata=metadata)
return parser |
Execute main processes. | def main():
"""Execute main processes."""
try:
pkg_version = Update()
if pkg_version.updatable():
pkg_version.show_message()
metadata = control.retreive_metadata()
parser = parse_options(metadata)
argvs = sys.argv
if len(argvs) <= 1:
parser... |
Set name:value property to Package object. | def _set_param(self, name, value):
"""Set name:value property to Package object."""
if name == 'status':
setattr(self, name, self.metadata.status().get(value))
elif name == 'license':
setattr(self, name, self.metadata.licenses().get(value))
elif name == 'name':
... |
Check key and set default vaule when it does not exists. | def _check_or_set_default_params(self):
"""Check key and set default vaule when it does not exists."""
if not hasattr(self, 'date'):
self._set_param('date', datetime.utcnow().strftime('%Y-%m-%d'))
if not hasattr(self, 'version'):
self._set_param('version', self.default_ve... |
Move directory from working directory to output directory. | def move(self):
"""Move directory from working directory to output directory."""
if not os.path.isdir(self.outdir):
os.makedirs(self.outdir)
shutil.move(self.tmpdir, os.path.join(self.outdir, self.name)) |
Initialize VCS repository. | def vcs_init(self):
"""Initialize VCS repository."""
VCS(os.path.join(self.outdir, self.name), self.pkg_data) |
example_capture
An example capture script
Change the network interface by ``export CAP_DEVICE=eth0`` | def example_capture():
"""example_capture
An example capture script
Change the network interface by ``export CAP_DEVICE=eth0``
"""
dev = ev(
"CAP_DEVICE",
"lo")
"""
Ignore ports for forwarding to consolidators:
Redis Internal VM: 6379, 16379
RabbitMQ Internal VM... |
capture_udp_packets
Capture ``UDP`` packets and call the ``handle_packets`` method
Change the network interface by ``export CAP_DEVICE=eth0`` | def capture_udp_packets():
"""capture_udp_packets
Capture ``UDP`` packets and call the ``handle_packets`` method
Change the network interface by ``export CAP_DEVICE=eth0``
"""
dev = ev(
"CAP_DEVICE",
"lo")
"""
Ignore ports for forwarding to consolidators:
Redis VM: 6... |
Finds the location of the current Steam installation on Windows machines.
Returns None for any non-Windows machines, or for Windows machines where
Steam is not installed. | def find_steam_location():
"""
Finds the location of the current Steam installation on Windows machines.
Returns None for any non-Windows machines, or for Windows machines where
Steam is not installed.
"""
if registry is None:
return None
key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\... |
convert_pkt_to_json
Inspired by:
https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py
This function convert a Scapy packet to JSON
:param pkg: A kamene package
:type pkg: objects
:return: A JSON data
:rtype: dict() | def convert_pkt_to_json(pkg):
""" convert_pkt_to_json
Inspired by:
https://gist.githubusercontent.com/cr0hn/1b0c2e672cd0721d3a07/raw/9144676ceb12dbd545e6dce366822bbedde8de2c/pkg_to_json.py
This function convert a Scapy packet to JSON
:param pkg: A kamene package
:type pkg: objects
:return:... |
Plot PCoA principal coordinates scaled by the relative abundances of
otu_name. | def plot_PCoA(cat_data, otu_name, unifrac, names, colors, xr, yr, outDir,
save_as, plot_style):
"""
Plot PCoA principal coordinates scaled by the relative abundances of
otu_name.
"""
fig = plt.figure(figsize=(14, 8))
ax = fig.add_subplot(111)
for i, cat in enumerate(cat_data):... |
print line if starts with ... | def print_line(l):
"""
print line if starts with ...
"""
print_lines = ['# STOCKHOLM', '#=GF', '#=GS', ' ']
if len(l.split()) == 0:
return True
for start in print_lines:
if l.startswith(start):
return True
return False |
Split up the column data in a biom table by mapping category value. | def split_by_category(biom_cols, mapping, category_id):
"""
Split up the column data in a biom table by mapping category value.
"""
columns = defaultdict(list)
for i, col in enumerate(biom_cols):
columns[mapping[col['id']][category_id]].append((i, col))
return columns |
convert stockholm to single line format | def stock2one(stock):
"""
convert stockholm to single line format
"""
lines = {}
for line in stock:
line = line.strip()
if print_line(line) is True:
yield line
continue
if line.startswith('//'):
continue
ID, seq = line.rsplit(' ', 1... |
Statics the methods. wut. | def math_func(f):
"""
Statics the methods. wut.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if len(args) > 0:
return_type = type(args[0])
if kwargs.has_key('return_type'):
return_type = kwargs['return_type']
kwargs.pop('return_type')
re... |
Show stats when pings are done | def dump_stats(myStats):
"""
Show stats when pings are done
"""
print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP))
if myStats.pktsSent > 0:
myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) \
/ myStats.pktsSent
print(("%d packets transmitted, %d pack... |
Send >count< ping to >destIP< with the given >timeout< and display
the result. | def verbose_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
"""
Send >count< ping to >destIP< with the given >timeout< and display
the result.
"""
signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl-C
if hasattr(signa... |
bootstrap-py package updatable?. | def updatable(self):
"""bootstrap-py package updatable?."""
if self.latest_version > self.current_version:
updatable_version = self.latest_version
else:
updatable_version = False
return updatable_version |
Show message updatable. | def show_message(self):
"""Show message updatable."""
print(
'current version: {current_version}\n'
'latest version : {latest_version}'.format(
current_version=self.current_version,
latest_version=self.latest_version)) |
Traverse the input otu-sequence file, collect the non-unique OTU IDs and
file the sequences associated with then under the unique OTU ID as defined
by the input matrix.
:@type otuF: file
:@param otuF: The output file from QIIME's pick_otus.py
:@type nuniqueF: file
:@param nuniqueF: The matrix o... | def condense_otus(otuF, nuniqueF):
"""
Traverse the input otu-sequence file, collect the non-unique OTU IDs and
file the sequences associated with then under the unique OTU ID as defined
by the input matrix.
:@type otuF: file
:@param otuF: The output file from QIIME's pick_otus.py
:@type nu... |
determine if read overlaps with rna, if so count bases | def rna_bases(rna_cov, scaffold, bases, line):
"""
determine if read overlaps with rna, if so count bases
"""
start = int(line[3])
stop = start + bases - 1
if scaffold not in rna_cov:
return rna_cov
for pos in rna_cov[scaffold][2]:
ol = get_overlap([start, stop], pos)
... |
parse ggKbase scaffold-to-bin mapping
- scaffolds-to-bins and bins-to-scaffolds | def parse_s2bins(s2bins):
"""
parse ggKbase scaffold-to-bin mapping
- scaffolds-to-bins and bins-to-scaffolds
"""
s2b = {}
b2s = {}
for line in s2bins:
line = line.strip().split()
s, b = line[0], line[1]
if 'UNK' in b:
continue
if len(line) > 2... |
parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges] | def parse_rna(rna, s2bins, min_rna):
"""
parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges]
"""
rna_cov = {}
for seq in parse_fasta(rna):
# check that length passes threshold
length = len(seq[1])
if length < min_rna:
con... |
remove any bins that don't have 16S | def filter_missing_rna(s2bins, bins2s, rna_cov):
"""
remove any bins that don't have 16S
"""
for bin, scaffolds in list(bins2s.items()):
c = 0
for s in scaffolds:
if s in rna_cov:
c += 1
if c == 0:
del bins2s[bin]
for scaffold, bin in l... |
calculate bin coverage | def calc_bin_cov(scaffolds, cov):
"""
calculate bin coverage
"""
bases = sum([cov[i][0] for i in scaffolds if i in cov])
length = sum([cov[i][1] for i in scaffolds if i in cov])
if length == 0:
return 0
return float(float(bases)/float(length)) |
1. determine bin coverage
2. determine rRNA gene coverage
3. compare | def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0):
"""
1. determine bin coverage
2. determine rRNA gene coverage
3. compare
"""
cov = {} # cov[scaffold] = [bases, length]
s2bins, bins2s = parse_s2bins(s2bins)
rna_cov = parse_rna(rna, s2bins, min_rna)
s2bins, bins2s = fi... |
Make sure there is at least a translation has been filled in. If a
default language has been specified, make sure that it exists amongst
translations. | def clean(self):
"""
Make sure there is at least a translation has been filled in. If a
default language has been specified, make sure that it exists amongst
translations.
"""
# First make sure the super's clean method is called upon.
super(TranslationFormSet, se... |
If a default language has been set, and is still available in
`self.available_languages`, return it and remove it from the list.
If not, simply pop the first available language. | def _get_default_language(self):
"""
If a default language has been set, and is still available in
`self.available_languages`, return it and remove it from the list.
If not, simply pop the first available language.
"""
assert hasattr(self, 'available_languages'), \
... |
Construct the form, overriding the initial value for `language_code`. | def _construct_form(self, i, **kwargs):
"""
Construct the form, overriding the initial value for `language_code`.
"""
if not settings.HIDE_LANGUAGE:
self._construct_available_languages()
form = super(TranslationFormSet, self)._construct_form(i, **kwargs)
if ... |
Split the list of OTUs (and associated sequence ids) into two lists:
those occurring in more than some percentage of samples and those less than
the cutoff.
:type otus: dict
:param otus: {otuid: [taxonomy, [sequence IDs]]}
:type nsamples: int
:param nsamples: The total number of samples in the ... | def filter_by_sample_pct(otus, nsamples, pct, phyl_level):
"""
Split the list of OTUs (and associated sequence ids) into two lists:
those occurring in more than some percentage of samples and those less than
the cutoff.
:type otus: dict
:param otus: {otuid: [taxonomy, [sequence IDs]]}
:type... |
Split the list of OTUs (and associated sequence ids) into two lists:
those occurring associated with more than some percentage of total sequences
and those less than the cutoff.
:type otus: dict
:param otus: {otuid: [taxonomy, [sequence IDs]]}
:type nseqs: int
:param nseqs: The total number of ... | def filter_by_sequence_pct(otus, nseqs, pct, phyl_level):
"""
Split the list of OTUs (and associated sequence ids) into two lists:
those occurring associated with more than some percentage of total sequences
and those less than the cutoff.
:type otus: dict
:param otus: {otuid: [taxonomy, [seque... |
merge separate fastq files | def fq_merge(R1, R2):
"""
merge separate fastq files
"""
c = itertools.cycle([1, 2, 3, 4])
for r1, r2 in zip(R1, R2):
n = next(c)
if n == 1:
pair = [[], []]
pair[0].append(r1.strip())
pair[1].append(r2.strip())
if n == 4:
yield pair |
Creates hash ring. | def _build_circle(self):
"""
Creates hash ring.
"""
total_weight = 0
for node in self._nodes:
total_weight += self._weights.get(node, 1)
for node in self._nodes:
weight = self._weights.get(node, 1)
ks = math.floor((40 * len(self._... |
Return node position(integer) for a given key. Else return None | def _get_node_pos(self, key):
"""
Return node position(integer) for a given key. Else return None
"""
if not self._hashring:
return None
key = self._gen_key(key)
nodes = self._sorted_keys
pos = bisect(nodes, key)
if pos == len(nodes):
... |
Return long integer for a given key, that represent it place on
the hash ring. | def _gen_key(self, key):
"""
Return long integer for a given key, that represent it place on
the hash ring.
"""
b_key = self._md5_digest(key)
return self._hashi(b_key, lambda x: x) |
Removes node from circle and rebuild it. | def remove_node(self, node):
"""
Removes node from circle and rebuild it.
"""
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._hashring = dict()
self._sorted_keys = []
... |
Adds node to circle and rebuild it. | def add_node(self, node, weight=1):
"""
Adds node to circle and rebuild it.
"""
self._nodes.add(node)
self._weights[node] = weight
self._hashring = dict()
self._sorted_keys = []
self._build_circle() |
process_ether_frame
Convert a complex nested json dictionary
to a flattened dictionary and capture
all unique keys for table construction
:param id: key for this msg
:param msg: ether frame for packet | def process_ether_frame(self,
id=None,
msg=None):
"""process_ether_frame
Convert a complex nested json dictionary
to a flattened dictionary and capture
all unique keys for table construction
:param id: key for this msg
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.