INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
process_ip_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: ip frame for packet | def process_ip_frame(self,
id=None,
msg=None):
"""process_ip_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 ... |
process_ipvsix_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: ipv6 frame for packet | def process_ipvsix_frame(self,
id=None,
msg=None):
"""process_ipvsix_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... |
process_tcp_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: tcp frame for packet | def process_tcp_frame(self,
id=None,
msg=None):
"""process_tcp_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
:pa... |
process_udp_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: udp frame for packet | def process_udp_frame(self,
id=None,
msg=None):
"""process_udp_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
:pa... |
process_dns_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: dns frame for packet | def process_dns_frame(self,
id=None,
msg=None):
"""process_dns_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
:pa... |
process_icmp_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: icmp frame for packet | def process_icmp_frame(self,
id=None,
msg=None):
"""process_icmp_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
... |
process_arp_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: arp frame for packet | def process_arp_frame(self,
id=None,
msg=None):
"""process_arp_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
:pa... |
process_raw_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: raw frame for packet | def process_raw_frame(self,
id=None,
msg=None):
"""process_raw_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
:pa... |
process_pad_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: pad frame for packet | def process_pad_frame(self,
id=None,
msg=None):
"""process_pad_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
:pa... |
build_flat_msg
:param id: unique id for this message
:param msg: message dictionary to flatten | def build_flat_msg(self,
id=None,
msg=None):
"""build_flat_msg
:param id: unique id for this message
:param msg: message dictionary to flatten
"""
flat_msg = {}
if not id:
log.error("Please pass in an id")
... |
build_all_keys_dict | def build_all_keys_dict(self):
"""build_all_keys_dict"""
log.info("finding keys")
for k in self.eth_keys:
ak = "{}".format(k)
if ak not in self.all_keys:
self.all_keys[ak] = k
# end of building all eths
for k in self.ip_keys:
a... |
flatten_all | def flatten_all(self):
"""flatten_all"""
log.info("flattening - START")
self.all_rows = []
for idx, r in enumerate(self.all_flat):
new_row = {"idx": idx}
for k in self.all_keys_list:
if k in r:
new_row[k] = r[k]
... |
create_json_archive | def create_json_archive(self):
"""create_json_archive"""
archive_data = {"packets": self.recv_msgs,
"dataset": self.dataset_name,
"num_packets": len(self.recv_msgs),
"created": rnow()}
self.write_to_file(archive_data,
... |
convert_to_df | def convert_to_df(self):
"""convert_to_df"""
log.info(("converting={}")
.format(len(self.all_rows)))
if len(self.all_rows) == 0:
return
self.df = pd.DataFrame(self.all_rows).set_index("idx")
if len(self.df) != len(self.all_rows):
log.e... |
write_to_file
:param data_dict:
:param output_file_path: | def write_to_file(self,
data_dict,
output_file_path):
"""write_to_file
:param data_dict:
:param output_file_path:
"""
log.info("saving={}".format(output_file_path))
with open(output_file_path, "w") as output_file:
... |
save_df_as_csv | def save_df_as_csv(self):
"""save_df_as_csv"""
if len(self.all_rows) == 0:
log.info(("no df={} to save")
.format(self.df))
return
else:
log.info(("saving "
"packets={} file={} rows={}")
.format(... |
save_data | def save_data(self):
"""save_data"""
state = ""
try:
state = "create_json_archive"
log.info("creating json archive")
self.create_json_archive()
state = "building_unique_keys"
log.info("processing all unique keys")
self.bu... |
handle_msg
:param body: dictionary contents from the message body
:param org_message: message object can ack, requeue or reject | def handle_msg(self,
body,
org_message):
"""handle_msg
:param body: dictionary contents from the message body
:param org_message: message object can ack, requeue or reject
"""
if os.path.exists(self.stop_for_file):
log.info(("De... |
publish_predictions_to_core | def publish_predictions_to_core(self):
"""publish_predictions_to_core"""
status = FAILED
msg = "not started"
try:
msg = "generating request"
log.info(msg)
# noqa https://stackoverflow.com/questions/29815129/pandas-dataframe-to-list-of-dictionaries
... |
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions | def _init_data_map(self):
""" OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions """
if self._data_map is not None:
return # Initiation happens once
# Parse and validate the FGDC metadata root
if self._xml_tree is None:
fgdc_ro... |
Ensures complete removal of raster_info given the two roots: <spdoinfo> and <spref> | def _update_raster_info(self, **update_props):
""" Ensures complete removal of raster_info given the two roots: <spdoinfo> and <spref> """
xpath_map = self._data_structures[update_props['prop']]
return [
update_complex(xpath_root=self._data_map.get('_raster_info_root'), xpath_map=x... |
Returns True if there exists a custom image for app_id. | def has_custom_image(user_context, app_id):
"""Returns True if there exists a custom image for app_id."""
possible_paths = _valid_custom_image_paths(user_context, app_id)
return any(map(os.path.exists, possible_paths)) |
Returns the custom image associated with a given app. If there are
multiple candidate images on disk, one is chosen arbitrarily. | def get_custom_image(user_context, app_id):
"""Returns the custom image associated with a given app. If there are
multiple candidate images on disk, one is chosen arbitrarily."""
possible_paths = _valid_custom_image_paths(user_context, app_id)
existing_images = filter(os.path.exists, possible_paths)
if len(ex... |
Sets the custom image for `app_id` to be the image located at
`image_path`. If there already exists a custom image for `app_id` it will
be deleted. Returns True is setting the image was successful. | def set_custom_image(user_context, app_id, image_path):
"""Sets the custom image for `app_id` to be the image located at
`image_path`. If there already exists a custom image for `app_id` it will
be deleted. Returns True is setting the image was successful."""
if image_path is None:
return False
if not os... |
Read an orthography profile from a metadata file or a default tab-separated profile file. | def from_file(cls, fname, form=None):
"""
Read an orthography profile from a metadata file or a default tab-separated profile file.
"""
try:
tg = TableGroup.from_file(fname)
opfname = None
except JSONDecodeError:
tg = TableGroup.fromvalue(cls.M... |
Create a Profile instance from the Unicode graphemes found in `text`.
Parameters
----------
text
mapping
Returns
-------
A Profile instance. | def from_text(cls, text, mapping='mapping'):
"""
Create a Profile instance from the Unicode graphemes found in `text`.
Parameters
----------
text
mapping
Returns
-------
A Profile instance.
"""
graphemes = Counter(grapheme_patter... |
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file | def split_fasta(f, id2f):
"""
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file
"""
opened = {}
for seq in parse_fasta(f):
id = seq[0].split('>')[1].split()[0]
if id not in id2f:
continue
fasta = id2f[id]
... |
Check whether `pathname` is a valid user data directory
This method is meant to be called on the contents of the userdata dir.
As such, it will return True when `pathname` refers to a directory name
that can be interpreted as a users' userID. | def _is_user_directory(self, pathname):
"""Check whether `pathname` is a valid user data directory
This method is meant to be called on the contents of the userdata dir.
As such, it will return True when `pathname` refers to a directory name
that can be interpreted as a users' userID.
"""... |
Returns an array of user ids for users on the filesystem | def local_users(self):
"""Returns an array of user ids for users on the filesystem"""
# Any users on the machine will have an entry inside of the userdata
# folder. As such, the easiest way to find a list of all users on the
# machine is to just list the folders inside userdata
u... |
Calculates the temperature equivalent from a series of average daily temperatures
according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2
Parameters
----------
series : Pandas Series
Returns
-------
Pandas Series | def calculate_temperature_equivalent(temperatures):
"""
Calculates the temperature equivalent from a series of average daily temperatures
according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2
Parameters
----------
series : Pandas Series
Returns
-------
Pandas... |
Calculates degree days, starting with a series of temperature equivalent values
Parameters
----------
temperature_equivalent : Pandas Series
base_temperature : float
cooling : bool
Set True if you want cooling degree days instead of heating degree days
Returns
-------
Pandas Se... | def _calculate_degree_days(temperature_equivalent, base_temperature, cooling=False):
"""
Calculates degree days, starting with a series of temperature equivalent values
Parameters
----------
temperature_equivalent : Pandas Series
base_temperature : float
cooling : bool
Set True if y... |
Compute degree-days for heating and/or cooling
Parameters
----------
ts : pandas.Series
Contains ambient (outside) temperature. Series name (ts.name) does not matter.
heating_base_temperatures: list
For each base temperature the heating degree-days will be computed
cooling_base_temp... | def compute_degree_days(ts, heating_base_temperatures, cooling_base_temperatures):
"""
Compute degree-days for heating and/or cooling
Parameters
----------
ts : pandas.Series
Contains ambient (outside) temperature. Series name (ts.name) does not matter.
heating_base_temperatures: list
... |
Development status. | def status(self):
"""Development status."""
return {self._acronym_status(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_status)} |
OSI Approved license. | def licenses(self):
"""OSI Approved license."""
return {self._acronym_lic(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} |
Remove prefix. | def licenses_desc(self):
"""Remove prefix."""
return {self._acronym_lic(l): l.split(self.prefix_lic)[1]
for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} |
Convert license acronym. | def _acronym_lic(self, license_statement):
"""Convert license acronym."""
pat = re.compile(r'\(([\w+\W?\s?]+)\)')
if pat.search(license_statement):
lic = pat.search(license_statement).group(1)
if lic.startswith('CNRI'):
acronym_licence = lic[:4]
... |
calc MD5 based on path | def calcMD5(path):
"""
calc MD5 based on path
"""
# check that file exists
if os.path.exists(path) is False:
yield False
else:
command = ['md5sum', path]
p = Popen(command, stdout = PIPE)
for line in p.communicate()[0].splitlines():
yield line.decode('... |
* comfirm that downloaded files match md5 checksum on server
* if md5 is False, only check path for the download | def md5check(f, ftp, md5, exclude):
"""
* comfirm that downloaded files match md5 checksum on server
* if md5 is False, only check path for the download
"""
files = glob(f)
# if no md5 file is specified: download files if path does not exist
if md5 is False:
if len(files) == 0:
... |
download files with wget | def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10):
"""
download files with wget
"""
# file name
if f is False:
f = ftp.rsplit('/', 1)[-1]
# downloaded file if it does not already exist
# check md5s on server (optional)
t = 0
while md5check(f, ft... |
check that at least one of
queries is in list, l | def check(line, queries):
"""
check that at least one of
queries is in list, l
"""
line = line.strip()
spLine = line.replace('.', ' ').split()
matches = set(spLine).intersection(queries)
if len(matches) > 0:
return matches, line.split('\t')
return matches, False |
search entrez using specified database
and accession | def entrez(db, acc):
"""
search entrez using specified database
and accession
"""
c1 = ['esearch', '-db', db, '-query', acc]
c2 = ['efetch', '-db', 'BioSample', '-format', 'docsum']
p1 = Popen(c1, stdout = PIPE, stderr = PIPE)
p2 = Popen(c2, stdin = p1.stdout, stdout = PIPE, stderr = PIP... |
attempt to use NCBI Entrez to get
BioSample ID | def searchAccession(acc):
"""
attempt to use NCBI Entrez to get
BioSample ID
"""
# try genbank file
# genome database
out, error = entrez('genome', acc)
for line in out.splitlines():
line = line.decode('ascii').strip()
if 'Assembly_Accession' in line or 'BioSample' in lin... |
download genome info from NCBI | def getFTPs(accessions, ftp, search, exclude, convert = False, threads = 1, attempt = 1,
max_attempts = 2):
"""
download genome info from NCBI
"""
info = wget(ftp)[0]
allMatches = []
for genome in open(info, encoding = 'utf8'):
genome = str(genome)
matches, genomeInfo... |
download genomes from NCBI | def download(args):
"""
download genomes from NCBI
"""
accessions, infoFTP = set(args['g']), args['i']
search, exclude = args['s'], args['e']
FTPs = getFTPs(accessions, infoFTP, search, exclude, threads = args['t'],
convert = args['convert'])
if args['test'] is True:
for ... |
remove pesky characters from fasta file header | def fix_fasta(fasta):
"""
remove pesky characters from fasta file header
"""
for seq in parse_fasta(fasta):
seq[0] = remove_char(seq[0])
if len(seq[1]) > 0:
yield seq |
Plot transformed LDA data. | def plot_LDA(X_lda, y_lda, class_colors, exp_var, style, fig_size, label_pad,
font_size, sids, dim=2, zangles=None, pt_size=250, out_fp=""):
"""
Plot transformed LDA data.
"""
cats = class_colors.keys()
fig = plt.figure(figsize=fig_size)
if dim == 3:
try:
assert ... |
Run LinearDiscriminantAnalysis on input dataframe (df) and return
transformed data, scalings and explained variance by discriminants. | def run_LDA(df):
"""
Run LinearDiscriminantAnalysis on input dataframe (df) and return
transformed data, scalings and explained variance by discriminants.
"""
# Prep variables for sklearn LDA
X = df.iloc[:, 1:df.shape[1]].values # input data matrix
y = df["Condition"].values ... |
Compute a DataFrame summary of a Stats object. | def _calc_frames(stats):
"""
Compute a DataFrame summary of a Stats object.
"""
timings = []
callers = []
for key, values in iteritems(stats.stats):
timings.append(
pd.Series(
key + values[:-1],
index=timing_colnames,
)
)
... |
get unmapped reads | def unmapped(sam, mates):
"""
get unmapped reads
"""
for read in sam:
if read.startswith('@') is True:
continue
read = read.strip().split()
if read[2] == '*' and read[6] == '*':
yield read
elif mates is True:
if read[2] == '*' or re... |
Preprocess text for SugarTeX Pandoc filter.
Replaces 'ˎ' with `$` (except `\ˎ`), replaces `\ˎ` with `ˎ` | def sugartex_preprocess(source: str) -> str:
"""
Preprocess text for SugarTeX Pandoc filter.
Replaces 'ˎ' with `$` (except `\ˎ`), replaces `\ˎ` with `ˎ`
"""
rep = {r'\ˎ': 'ˎ', 'ˎ': '$'}
return re.sub(r'\\ˎ|ˎ', lambda m: rep[m.group(0)], source) |
Replace all with SugarTeX.
Runs ``sugartex_preprocess`` then iterates via regex and
replaces each math between '$...$'. | def sugartex_replace_all(string):
"""
Replace all with SugarTeX.
Runs ``sugartex_preprocess`` then iterates via regex and
replaces each math between '$...$'.
"""
string = sugartex_preprocess(string).replace(r'\$', SESSION_ID)
return re.sub(
r'(?<=\$)[^$]*(?=\$)',
lambda m: su... |
Usage: pre-sugartex [OPTIONS]
Reads from stdin and writes to stdout.
When no options: only replace
U+02CE Modifier Letter Low Grave Accent
(that looks like low '`') with $
Options:
--all Full SugarTeX replace with regexp,
--kiwi Same as above but with kiwi flavor,
--... | def main():
"""
Usage: pre-sugartex [OPTIONS]
Reads from stdin and writes to stdout.
When no options: only replace
U+02CE Modifier Letter Low Grave Accent
(that looks like low '`') with $
Options:
--all Full SugarTeX replace with regexp,
--kiwi Same as above but wi... |
execute jobs in processes using N threads | def parallel(processes, threads):
"""
execute jobs in processes using N threads
"""
pool = multithread(threads)
pool.map(run_process, processes)
pool.close()
pool.join() |
the final log processor that structlog requires to render. | def define_log_renderer(fmt, fpath, quiet):
"""
the final log processor that structlog requires to render.
"""
# it must accept a logger, method_name and event_dict (just like processors)
# but must return the rendered string, not a dictionary.
# TODO tty logic
if fmt:
return struct... |
Add unique id, type and hostname | def _structlog_default_keys_processor(logger_class, log_method, event):
''' Add unique id, type and hostname '''
global HOSTNAME
if 'id' not in event:
event['id'] = '%s_%s' % (
datetime.utcnow().strftime('%Y%m%dT%H%M%S'),
uuid.uuid1().hex
)
if 'type' not in even... |
log processors that structlog executes before final rendering | def define_log_processors():
"""
log processors that structlog executes before final rendering
"""
# these processors should accept logger, method_name and event_dict
# and return a new dictionary which will be passed as event_dict to the next one.
return [
structlog.processors.TimeStamp... |
configures a logger when required write to stderr or a file | def _configure_logger(fmt, quiet, level, fpath,
pre_hooks, post_hooks, metric_grouping_interval):
"""
configures a logger when required write to stderr or a file
"""
# NOTE not thread safe. Multiple BaseScripts cannot be instantiated concurrently.
level = getattr(logging, level.upper())
gl... |
Instead of using a processor, adding basic information like caller, filename etc
here. | def _add_base_info(self, event_dict):
"""
Instead of using a processor, adding basic information like caller, filename etc
here.
"""
f = sys._getframe()
level_method_frame = f.f_back
caller_frame = level_method_frame.f_back
return event_dict |
Process event and call :meth:`logging.Logger.debug` with the result. | def debug(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.debug` with the result.
"""
if not self._logger.isEnabledFor(logging.DEBUG):
return
kw = self._add_base_info(kw)
kw['level'] = "debug"
return self._proxy_to_log... |
Process event and call :meth:`logging.Logger.info` with the result. | def info(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.info` with the result.
"""
if not self._logger.isEnabledFor(logging.INFO):
return
kw = self._add_base_info(kw)
kw['level'] = "info"
return self._proxy_to_logger(... |
Process event and call :meth:`logging.Logger.warning` with the result. | def warning(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.warning` with the result.
"""
if not self._logger.isEnabledFor(logging.WARNING):
return
kw = self._add_base_info(kw)
kw['level'] = "warning"
return self._prox... |
Process event and call :meth:`logging.Logger.error` with the result. | def error(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.error` with the result.
"""
if not self._logger.isEnabledFor(logging.ERROR):
return
kw = self._add_base_info(kw)
kw['level'] = "error"
return self._proxy_to_log... |
Process event and call :meth:`logging.Logger.critical` with the result. | def critical(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.critical` with the result.
"""
if not self._logger.isEnabledFor(logging.CRITICAL):
return
kw = self._add_base_info(kw)
kw['level'] = "critical"
return self._... |
Process event and call :meth:`logging.Logger.error` with the result,
after setting ``exc_info`` to `True`. | def exception(self, event=None, *args, **kw):
"""
Process event and call :meth:`logging.Logger.error` with the result,
after setting ``exc_info`` to `True`.
"""
if not self._logger.isEnabledFor(logging.ERROR):
return
kw = self._add_base_info(kw)
kw['l... |
Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that the stdblib's support for format strings can be used. | def _proxy_to_logger(self, method_name, event, *event_args,
**event_kw):
"""
Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that ... |
Given four points of a rectangle, translate the
rectangle to the specified x and y coordinates and,
optionally, change the width.
:type rect: list of tuples
:param rect: Four points describing a rectangle.
:type x: float
:param x: The amount to shift the rectangle along the x-axis.
:type y:... | def translate(rect, x, y, width=1):
"""
Given four points of a rectangle, translate the
rectangle to the specified x and y coordinates and,
optionally, change the width.
:type rect: list of tuples
:param rect: Four points describing a rectangle.
:type x: float
:param x: The amount to sh... |
For core OTU data file, returns Genus-species identifier for each data
entry.
:type core_fp: str
:param core_fp: A file containing core OTU data.
:rtype: str
:return: Returns genus-species identifier based on identified taxonomical
level. | def load_core_file(core_fp):
"""
For core OTU data file, returns Genus-species identifier for each data
entry.
:type core_fp: str
:param core_fp: A file containing core OTU data.
:rtype: str
:return: Returns genus-species identifier based on identified taxonomical
level.
"""... |
Given a list of OTUs and a number of groups containing subsets of
the OTU set, plot a presence/absence bar chart showing which species
belong to which groups.
:type otus: list
:param otus: A list of OTU identifiers (names or otherwise) ordered
by greatest presence across the groups... | def plot_overlaps(otus, group_otus, group_colors,
out_fp, fig_size=None, title="",
filter_common=False):
"""
Given a list of OTUs and a number of groups containing subsets of
the OTU set, plot a presence/absence bar chart showing which species
belong to which groups.... |
remove problem characters from string | def remove_bad(string):
"""
remove problem characters from string
"""
remove = [':', ',', '(', ')', ' ', '|', ';', '\'']
for c in remove:
string = string.replace(c, '_')
return string |
make copy of sequences with short identifier | def get_ids(a):
"""
make copy of sequences with short identifier
"""
a_id = '%s.id.fa' % (a.rsplit('.', 1)[0])
a_id_lookup = '%s.id.lookup' % (a.rsplit('.', 1)[0])
if check(a_id) is True:
return a_id, a_id_lookup
a_id_f = open(a_id, 'w')
a_id_lookup_f = open(a_id_lookup, 'w')
... |
convert fasta to phylip because RAxML is ridiculous | def convert2phylip(convert):
"""
convert fasta to phylip because RAxML is ridiculous
"""
out = '%s.phy' % (convert.rsplit('.', 1)[0])
if check(out) is False:
convert = open(convert, 'rU')
out_f = open(out, 'w')
alignments = AlignIO.parse(convert, "fasta")
AlignIO.writ... |
run FastTree | def run_fast(aligned, threads, cluster, node):
"""
run FastTree
"""
tree = '%s.fasttree.nwk' % (aligned.rsplit('.', 1)[0])
if check(tree) is False:
if 'FastTreeV' in os.environ:
ft = os.environ['FastTreeV']
os.environ['OMP_NUM_THREADS'] = str(threads)
else:
... |
run raxml | def run_raxml(rax_out, boot, a_id_phylip, threads, aligned, model, cluster, node):
"""
run raxml
"""
# set ppn based on threads
if threads > 24:
ppn = 24
else:
ppn = threads
if 'raxml' in os.environ:
raxml = os.environ['raxml']
threads = '-T %s' % (threads)
... |
run IQ-Tree | def run_iqtree(phy, model, threads, cluster, node):
"""
run IQ-Tree
"""
# set ppn based on threads
if threads > 24:
ppn = 24
else:
ppn = threads
tree = '%s.treefile' % (phy)
if check(tree) is False:
if model is False:
model = 'TEST'
dir = os.ge... |
get the names for sequences in the raxml tree | def fix_tree(tree, a_id_lookup, out):
"""
get the names for sequences in the raxml tree
"""
if check(out) is False and check(tree) is True:
tree = open(tree).read()
for line in open(a_id_lookup):
id, name, header = line.strip().split('\t')
tree = tree.replace(id+'... |
run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads)
store all files in raxml_a_b
1. give every sequence a short identifier
2. convert fasta to phylip
3. run raxml
4. convert ids in raxml tree to original names | def rax(a, boot, threads, \
fast = False, run_rax = False, run_iq = False, model = False, cluster = False, node = False):
"""
run raxml on 'a' (alignment) with 'boot' (bootstraps) and 'threads' (threads)
store all files in raxml_a_b
1. give every sequence a short identifier
2. convert fa... |
send_arp_msg
Send an ``ARP`` message to the network device (``enp0s3`` by default). | def send_arp_msg():
"""send_arp_msg
Send an ``ARP`` message to the network device (``enp0s3`` by default).
"""
dev = os.getenv(
"ARP_INTERFACE",
"enp0s3").strip().lstrip()
network_details = netifaces.ifaddresses(
dev)
dst_ip = os.getenv(
"ARP_DS... |
shutdown_consumers
:param num_workers:
:param tasks:
:param shutdown_msg: | def shutdown_consumers(num_workers=2,
tasks=None,
shutdown_msg="SHUTDOWN"):
"""shutdown_consumers
:param num_workers:
:param tasks:
:param shutdown_msg:
"""
if tasks:
# Add a poison pill for each consumer
for i in range(num_workers):... |
Creates a new Nydus cluster from the given settings.
:param settings: Dictionary of the cluster settings.
:returns: Configured instance of ``nydus.db.base.Cluster``.
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> 'router': 'nydus.db.routers.redis.Partition... | def create_cluster(settings):
"""
Creates a new Nydus cluster from the given settings.
:param settings: Dictionary of the cluster settings.
:returns: Configured instance of ``nydus.db.base.Cluster``.
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> '... |
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange effects. However, we would see the same
effects when an... | def _get_translation(self, field, code):
"""
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange ef... |
Wrapper to allow for easy unicode representation of an object by
the specified property. If this wrapper is not able to find the
right translation of the specified property, it will return the
default value instead.
Example::
def __unicode__(self):
return uni... | def unicode_wrapper(self, property, default=ugettext('Untitled')):
"""
Wrapper to allow for easy unicode representation of an object by
the specified property. If this wrapper is not able to find the
right translation of the specified property, it will return the
default value in... |
remove insertion columns from aligned fasta file | def strip_inserts(fasta):
"""
remove insertion columns from aligned fasta file
"""
for seq in parse_fasta(fasta):
seq[1] = ''.join([b for b in seq[1] if b == '-' or b.isupper()])
yield seq |
Given a string as input, return a space-delimited string of Unicode characters
(code points rendered as glyphs).
Parameters
----------
string : str
A Unicode string to be tokenized into graphemes.
Returns
-------
result : str
String returne... | def characters(self, string, segment_separator=' ', separator=' # ',):
"""
Given a string as input, return a space-delimited string of Unicode characters
(code points rendered as glyphs).
Parameters
----------
string : str
A Unicode string to be tokenized into... |
Transform a string's graphemes into the mappings given in a different column
in the orthography profile.
Parameters
----------
word : str
The input string to be tokenized.
column : str (default = "Grapheme")
The label of the column to transform to. Defau... | def transform(self, word, column=Profile.GRAPHEME_COL, error=errors.replace):
"""
Transform a string's graphemes into the mappings given in a different column
in the orthography profile.
Parameters
----------
word : str
The input string to be tokenized.
... |
Function to tokenize input string and return output of str with ortho rules
applied.
Parameters
----------
word : str
The input string to be tokenized.
Returns
-------
result : str
Result of the orthography rules applied to the input str. | def rules(self, word):
"""
Function to tokenize input string and return output of str with ortho rules
applied.
Parameters
----------
word : str
The input string to be tokenized.
Returns
-------
result : str
Result of the ... |
Given a string that is space-delimited on Unicode grapheme clusters,
group Unicode modifier letters with their preceding base characters,
deal with tie bars, etc.
Parameters
----------
string : str
A Unicode string tokenized into grapheme clusters to be tokenized int... | def combine_modifiers(self, graphemes):
"""
Given a string that is space-delimited on Unicode grapheme clusters,
group Unicode modifier letters with their preceding base characters,
deal with tie bars, etc.
Parameters
----------
string : str
A Unicode... |
parse catalytic RNAs to gff format | def parse_catalytic(insertion, gff):
"""
parse catalytic RNAs to gff format
"""
offset = insertion['offset']
GeneStrand = insertion['strand']
if type(insertion['intron']) is not str:
return gff
for intron in parse_fasta(insertion['intron'].split('|')):
ID, annot, strand, pos ... |
parse ORF to gff format | def parse_orf(insertion, gff):
"""
parse ORF to gff format
"""
offset = insertion['offset']
if type(insertion['orf']) is not str:
return gff
for orf in parse_fasta(insertion['orf'].split('|')):
ID = orf[0].split('>')[1].split()[0]
Start, End, strand = [int(i) for i in orf... |
parse insertion to gff format | def parse_insertion(insertion, gff):
"""
parse insertion to gff format
"""
offset = insertion['offset']
for ins in parse_fasta(insertion['insertion sequence'].split('|')):
strand = insertion['strand']
ID = ins[0].split('>')[1].split()[0]
Start, End = [int(i) for i in ins[0].s... |
parse rRNA to gff format | def parse_rRNA(insertion, seq, gff):
"""
parse rRNA to gff format
"""
offset = insertion['offset']
strand = insertion['strand']
for rRNA in parse_masked(seq, 0)[0]:
rRNA = ''.join(rRNA)
Start = seq[1].find(rRNA) + 1
End = Start + len(rRNA) - 1
if strand == '-':
... |
convert iTable to gff file | def iTable2GFF(iTable, fa, contig = False):
"""
convert iTable to gff file
"""
columns = ['#seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute']
gff = {c:[] for c in columns}
for insertion in iTable.iterrows():
insertion = insertion[1]
if insert... |
Plot a smoothed (by kernel density estimate) histogram.
:type data: numpy array
:param data: An array containing the data to be plotted
:type ax: matplotlib.Axes
:param ax: The Axes object to draw to
:type title: str
:param title: The plot title
:type color: str
:param color: The colo... | def plot_kde(data, ax, title=None, color='r', fill_bt=True):
"""
Plot a smoothed (by kernel density estimate) histogram.
:type data: numpy array
:param data: An array containing the data to be plotted
:type ax: matplotlib.Axes
:param ax: The Axes object to draw to
:type title: str
:par... |
Styles an axes to appear like ggplot2
Must be called after all plot and axis manipulation operations have been
carried out (needs to know final tick spacing) | def ggplot2_style(ax):
"""
Styles an axes to appear like ggplot2
Must be called after all plot and axis manipulation operations have been
carried out (needs to know final tick spacing)
"""
#set the style of the major and minor grid lines, filled blocks
ax.grid(True, 'major', color='w', lines... |
Given an abundance table, group the counts by every
taxonomic level. | def summarize_taxa(biom):
"""
Given an abundance table, group the counts by every
taxonomic level.
"""
tamtcounts = defaultdict(int)
tot_seqs = 0.0
for row, col, amt in biom['data']:
tot_seqs += amt
rtax = biom['rows'][row]['metadata']['taxonomy']
for i, t in enumera... |
connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the forwarded packets
:param max_retries: retries, -1 = infinite
:param sleep_interval: how often to retry in this loop | def connect_forwarder(forward_host=None,
forward_port=None,
max_retries=-1,
sleep_interval=1.0):
"""connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the forwarded packets
:param ma... |
Returns the path to the custom image set for this game, or None if
no image is set | def custom_image(self, user):
"""Returns the path to the custom image set for this game, or None if
no image is set"""
for ext in self.valid_custom_image_extensions():
image_location = self._custom_image_path(user, ext)
if os.path.isfile(image_location):
r... |
Sets a custom image for the game. `image_path` should refer to
an image file on disk | def set_image(self, user, image_path):
"""Sets a custom image for the game. `image_path` should refer to
an image file on disk"""
_, ext = os.path.splitext(image_path)
shutil.copy(image_path, self._custom_image_path(user, ext)) |
get a list of mapped reads | def sam_list(sam):
"""
get a list of mapped reads
"""
list = []
for file in sam:
for line in file:
if line.startswith('@') is False:
line = line.strip().split()
id, map = line[0], int(line[1])
if map != 4 and map != 8:
list.append(id)
return set(list) |
get a list of mapped reads
require that both pairs are mapped in the sam file in order to remove the reads | def sam_list_paired(sam):
"""
get a list of mapped reads
require that both pairs are mapped in the sam file in order to remove the reads
"""
list = []
pair = ['1', '2']
prev = ''
for file in sam:
for line in file:
if line.startswith('@') is False:
line = line.strip().split()
id, map = line[0], int(... |
require that both pairs are mapped in the sam file in order to remove the reads | def filter_paired(list):
"""
require that both pairs are mapped in the sam file in order to remove the reads
"""
pairs = {}
filtered = []
for id in list:
read = id.rsplit('/')[0]
if read not in pairs:
pairs[read] = []
pairs[read].append(id)
for read in pairs:
ids = pairs[read]
if len(ids) == 2:
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.