text stringlengths 18 773k |
|---|
def load_all(stream):
"""
Parse all YAML documents in a stream
and produce corresponding YAMLDict objects.
"""
loader = YAMLDictLoader(stream)
try:
while loader.check_data():
yield loader.get_data()
finally:
loader.dispose() |
def dump(data, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
[data],
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) |
def dump_all(data_list, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
data_list,
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) |
def traverse(self, callback):
''' Traverse through all keys and values (in-order)
and replace keys and values with the return values
from the callback function.
'''
def _traverse_node(path, node, callback):
ret_val = callback(path, node)
if ret_val... |
def update(self, yaml_dict):
''' Update the content (i.e. keys and values) with yaml_dict.
'''
def _update_node(base_node, update_node):
if isinstance(update_node, YAMLDict) or \
isinstance(update_node, dict):
if not (isinstance(base_node, YAMLDict... |
def rebase(self, yaml_dict):
''' Use yaml_dict as self's new base and update with existing
reverse of update.
'''
base = yaml_dict.clone()
base.update(self)
self.clear()
self.update(base) |
def limit(self, keys):
''' Remove all keys other than the keys specified.
'''
if not isinstance(keys, list) and not isinstance(keys, tuple):
keys = [keys]
remove_keys = [k for k in self.keys() if k not in keys]
for k in remove_keys:
self.pop(k) |
def save(yaml_dict, filepath):
'''
Save YAML settings to the specified file path.
'''
yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False) |
def save_all(yaml_dicts, filepath):
'''
Save *all* YAML settings to the specified file path.
'''
yamldict.dump_all(yaml_dicts, open(filepath, 'w'),
default_flow_style=False) |
def update_from_file(yaml_dict, filepaths):
'''
Override YAML settings with loaded values from filepaths.
- File paths in the list gets the priority by their orders of the list.
'''
# load YAML settings with only fields in yaml_dict
yaml_dict.update(registry.load(filepaths, list(yaml_dict))... |
def update_from_env(yaml_dict, prefix=None):
'''
Override YAML settings with values from the environment variables.
- The letter '_' is delimit the hierarchy of the YAML settings such
that the value of 'config.databases.local' will be overridden
by CONFIG_DATABASES_LOCAL.
'''
... |
def circle(rad=0.5):
"""Draw a circle"""
_ctx = _state["ctx"]
_ctx.arc(0, 0, rad, 0, 2 * math.pi)
_ctx.set_line_width(0)
_ctx.stroke_preserve()
# _ctx.set_source_rgb(0.3, 0.4, 0.6)
_ctx.fill() |
def line(x, y, width=0.1):
"""Draw a line"""
ctx = _state["ctx"]
ctx.move_to(0, 0)
ctx.line_to(x, y)
ctx.close_path()
# _ctx.set_source_rgb (0.3, 0.2, 0.5)
ctx.set_line_width(width)
ctx.stroke() |
def triangle(rad=0.5):
"""Draw a triangle"""
# half_height = math.sqrt(3) * side / 6
# half_height = side / 2
ctx = _state["ctx"]
side = 3 * rad / math.sqrt(3)
ctx.move_to(0, -rad / 2)
ctx.line_to(-side / 2, -rad / 2)
ctx.line_to(0, rad)
ctx.line_to(side / 2, -rad / 2)
ctx.close_... |
def box(side=1):
"""Draw a box"""
half_side = side / 2
_state["ctx"].rectangle(-half_side, -half_side, side, side)
_state["ctx"].fill() |
def _dump_header(self):
"""Initially dump file heads and tails."""
with open(self._file, 'w') as _file:
_file.write(self._hsrt)
self._sptr = _file.tell()
_file.write(self._hend) |
def find_version(
package_name: str, version_module_name: str = '_version',
version_variable_name: str = 'VERSION') -> str:
"""Simulate behaviour of "from package_name._version import VERSION", and return VERSION."""
version_module = importlib.import_module(
'{}.{}'.format(package_name.r... |
def find_packages(root_directory: str = '.') -> t.List[str]:
"""Find packages to pack."""
exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else []
packages_list = setuptools.find_packages(root_directory, exclude=exclude)
return packages_list |
def parse_requirements(
requirements_path: str = 'requirements.txt') -> t.List[str]:
"""Read contents of requirements.txt file and return data from its relevant lines.
Only non-empty and non-comment lines are relevant.
"""
requirements = []
with HERE.joinpath(requirements_path).open() as re... |
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers in given list and partition them into 2 groups."""
versions_min, ve... |
def find_required_python_version(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Optional[str]:
"""Determine the minimum required Python version."""
versions_min, versions_only = partition_version_classifiers(
... |
def parse_rst(text: str) -> docutils.nodes.document:
"""Parse text assuming it's an RST markup."""
parser = docutils.parsers.rst.Parser()
components = (docutils.parsers.rst.Parser,)
settings = docutils.frontend.OptionParser(components=components).get_default_values()
document = docutils.utils.new_do... |
def resolve_relative_rst_links(text: str, base_link: str):
"""Resolve all relative links in a given RST document.
All links of form `link`_ become `link <base_link/link>`_.
"""
document = parse_rst(text)
visitor = SimpleRefCounter(document)
document.walk(visitor)
for target in visitor.refer... |
def visit_reference(self, node: docutils.nodes.reference) -> None:
"""Called for "reference" nodes."""
# if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \
# or not all(_ in node.attributes for _ in ('name', 'refuri')):
# return
path... |
def try_fields(cls, *names) -> t.Optional[t.Any]:
"""Return first existing of given class field names."""
for name in names:
if hasattr(cls, name):
return getattr(cls, name)
raise AttributeError((cls, names)) |
def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str:
"""Parse readme and resolve relative links in it if it is feasible.
Links are resolved if readme is in rst format and the package is hosted on GitHub.
"""
with HERE.joinpath(readme_path).open(encodin... |
def prepare(cls) -> None:
"""Fill in possibly missing package metadata."""
if cls.version is None:
cls.version = find_version(cls.name)
if cls.long_description is None:
cls.long_description = cls.parse_readme()
if cls.packages is None:
cls.packages = f... |
def setup(cls) -> None:
"""Run setuptools.setup() with correct arguments."""
cls.prepare()
setuptools.setup(
name=cls.name, version=cls.version, description=cls.description,
long_description=cls.long_description, url=cls.url, download_url=cls.download_url,
aut... |
def surface_to_image(surface):
"""Renders current buffer surface to IPython image"""
from IPython.display import Image
buf = BytesIO()
surface.write_to_png(buf)
data = buf.getvalue()
buf.close()
return Image(data=data) |
def get_npimage(transparent=False, y_origin="top"):
""" Returns a WxHx[3-4] numpy array representing the RGB picture.
If `transparent` is True the image is WxHx4 and represents a RGBA picture,
i.e. array[i,j] is the [r,g,b,a] value of the pixel at position [i,j].
If `transparent` is false, a RGB array ... |
def check_limits(user_rule):
"""Stop recursion if resolution is too low on number of components is too high """
def wrapper(*args, **kwargs):
"""The body of the decorator """
global _state
_state["cnt_elements"] += 1
_state["depth"] += 1
matrix = _state["ctx"].get_matrix... |
def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None):
"""Initializes global state"""
global _background_color
_background_color = background_color
global _ctx
global cnt_elements
global MAX_DEPTH
global WIDTH
global HEIGHT
_init_state()
sys.setr... |
def htmlcolor_to_rgb(str_color):
"""function to convert HTML-styly color string to RGB values
Args:
s: Color in HTML format
Returns:
list of three RGB color components
"""
if not (str_color.startswith('#') and len(str_color) == 7):
raise ValueError("Bad html color format. E... |
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None):
"""Compile docstrings into HTML strings, with shortcode support."""
if not is_two_file:
_, data = self.split_metadata(data, None, lang)
new_data, shortcodes = sc.extract_shortcodes(data)
... |
def compile(self, source, dest, is_two_file=True, post=None, lang=None):
"""Compile the docstring into HTML and save as dest."""
makedirs(os.path.dirname(dest))
with io.open(dest, "w+", encoding="utf8") as out_file:
with io.open(source, "r", encoding="utf8") as in_file:
... |
def create_post(self, path, **kw):
"""Create a new post."""
content = kw.pop('content', None)
onefile = kw.pop('onefile', False)
# is_page is not used by create_post as of now.
kw.pop('is_page', False)
metadata = {}
metadata.update(self.default_metadata)
m... |
def _append_value(self, value, _file, _name):
"""Call this function to write contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
* _name - str, name of current content dict
"""
if self._flag:
_k... |
def _append_array(self, value, _file):
"""Call this function to write array contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
if not value:
self._append_none(None, _file)
return
_... |
def _append_branch(self, value, _file):
"""Call this function to write branch contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
if not value:
return
# return self._append_none(None, _file)... |
def _append_bytes(self, value, _file):
"""Call this function to write bytes contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
# binascii.a2b_base64(Data) -> v... |
def _append_number(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write number contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_text = value
_labs = ' {text}'.format(text=_... |
def _append_value(self, value, _file, _name):
"""Call this function to write contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
* _name - str, name of current content dict
"""
_tabs = '\t' * self._tctr
... |
def _append_array(self, value, _file):
"""Call this function to write array contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_labs = ' ['
_file.write(_labs)
self._tctr += 1
for _item in... |
def _append_object(self, value, _file):
"""Call this function to write object contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_labs = ' {'
_file.write(_labs)
self._tctr += 1
for (_item,... |
def _append_string(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write string contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_text = str(value).replace('"', '\\"')
_labs ... |
def _append_bytes(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write bytes contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
#... |
def _append_date(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write date contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
_... |
def start(self, verbose=None, end_in_new_line=None):
"""Start the stopwatch if it is paused.
If the stopwatch is already started, then nothing will happen.
Parameters
----------
verbose : Optional[bool]
Wether to log. If `None`, use `verbose_start` set during initia... |
def pause(self):
"""Pause the stopwatch.
If the stopwatch is already paused, nothing will happen.
"""
if self._end_time is not None:
# the stopwatch is already paused
return
self._end_time = datetime.datetime.now()
self._elapsed_time += self._end_... |
def get_elapsed_time(self):
"""Get the elapsed time of the current split.
"""
if self._start_time is None or self._end_time is not None:
# the stopwatch is paused
return self._elapsed_time
return self._elapsed_time + (datetime.datetime.now() - self._start_time) |
def split(self, verbose=None, end_in_new_line=None):
"""Save the elapsed time of the current split and restart the stopwatch.
The current elapsed time will be appended to :attr:`split_elapsed_time`.
If the stopwatch is paused, then it will remain paused.
Otherwise, it will continue runn... |
def reset(self):
"""Reset the stopwatch.
"""
self._start_time = None
self._end_time = None
self._elapsed_time = datetime.timedelta()
self._cumulative_elapsed_time = datetime.timedelta()
self.split_elapsed_time = [] |
def bbduk_trim(forward_in, forward_out, reverse_in='NA', reverse_out='NA', returncmd=False, **kwargs):
"""
Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can
be overwritten by using keyword parameters.
:param forward_in: Forward reads you want ... |
def genome_size(peaks_file, haploid=True):
"""
Finds the genome size of an organsim, based on the peaks file created by kmercountexact.sh
:param peaks_file: Path to peaks file created by kmercountexact.
:param haploid: Set to True if organism of interest is haploid, False if not. Default True.
:retu... |
def DownloadAccount(self, next_page_token=None, max_results=None):
"""Downloads multiple accounts from Gitkit server.
Args:
next_page_token: string, pagination token.
max_results: pagination size.
Returns:
An array of accounts.
"""
param = {}
if next_page_token:
param['... |
def UploadAccount(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response... |
def GetPublicCert(self):
"""Download Gitkit public cert.
Returns:
dict of public certs.
"""
cert_url = self.google_api_url + 'publicKeys'
resp, content = self.http.request(cert_url)
if resp.status == 200:
return simplejson.loads(content)
else:
raise errors.GitkitServerEr... |
def _InvokeGitkitApi(self, method, params=None, need_service_account=True):
"""Invokes Gitkit API, with optional access token for service account.
Args:
method: string, the api method name.
params: dict of optional parameters for the API.
need_service_account: false if service account is not ... |
def _GetAccessToken(self):
"""Gets oauth2 access token for Gitkit API using service account.
Returns:
string, oauth2 access token.
"""
d = {
'assertion': self._GenerateAssertion(),
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
}
try:
body = parse.url... |
def _GenerateAssertion(self):
"""Generates the signed assertion that will be used in the request.
Returns:
string, signed Json Web Token (JWT) assertion.
"""
now = int(time.time())
payload = {
'aud': RpcHelper.TOKEN_ENDPOINT,
'scope': 'https://www.googleapis.com/auth/identityt... |
def _CheckGitkitError(self, raw_response):
"""Raises error if API invocation failed.
Args:
raw_response: string, the http response.
Raises:
GitkitClientError: if the error code is 4xx.
GitkitServerError: if the response if malformed.
Returns:
Successful response as dict.
"... |
def FromDictionary(cls, dictionary):
"""Initializes from user specified dictionary.
Args:
dictionary: dict of user specified attributes
Returns:
GitkitUser object
"""
if 'user_id' in dictionary:
raise errors.GitkitClientError('use localId instead')
if 'localId' not in dictiona... |
def ToRequest(self):
"""Converts to gitkit api request parameter dict.
Returns:
Dict, containing non-empty user attributes.
"""
param = {}
if self.email:
param['email'] = self.email
if self.user_id:
param['localId'] = self.user_id
if self.name:
param['displayName'] =... |
def VerifyGitkitToken(self, jwt):
"""Verifies a Gitkit token string.
Args:
jwt: string, the token to be checked
Returns:
GitkitUser, if the token is valid. None otherwise.
"""
certs = self.rpc_helper.GetPublicCert()
crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days
parsed =... |
def GetUserByEmail(self, email):
"""Gets user info by email.
Args:
email: string, the user email.
Returns:
GitkitUser, containing the user info.
"""
user = self.rpc_helper.GetAccountInfoByEmail(email)
return GitkitUser.FromApiResponse(user) |
def GetUserById(self, local_id):
"""Gets user info by id.
Args:
local_id: string, the user id at Gitkit server.
Returns:
GitkitUser, containing the user info.
"""
user = self.rpc_helper.GetAccountInfoById(local_id)
return GitkitUser.FromApiResponse(user) |
def UploadUsers(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple users to Gitkit server.
Args:
hash_algorithm: string, the hash algorithm.
hash_key: array, raw key of the hash algorithm.
accounts: list of GitkitUser.
Returns:
A dict of failed accounts. The key is the ... |
def GetAllUsers(self, pagination_size=10):
"""Gets all user info from Gitkit server.
Args:
pagination_size: int, how many users should be returned per request.
The account info are retrieved in pagination.
Yields:
A generator to iterate all users.
"""
next_page_token, account... |
def GetOobResult(self, param, user_ip, gitkit_token=None):
"""Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
... |
def _BuildOobLink(self, param, mode):
"""Builds out-of-band URL.
Gitkit API GetOobCode() is called and the returning code is combined
with Gitkit widget URL to building the out-of-band url.
Args:
param: dict of request.
mode: string, Gitkit widget mode to handle the oob action after user
... |
def run_subprocess(command):
"""
command is the command to run, as a string.
runs a subprocess, returns stdout and stderr from the subprocess as strings.
"""
x = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
out, err = x.communicate()
out = out.decode('utf-8')
err = err.decode('ut... |
def kwargs_to_string(kwargs):
"""
Given a set of kwargs, turns them into a string which can then be passed to a command.
:param kwargs: kwargs from a function call.
:return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
"""
outstr = ''
for ... |
def read_mash_output(result_file):
"""
:param result_file: Tab-delimited result file generated by mash dist.
:return: mash_results: A list with each entry in the result file as an entry, with attributes reference, query,
distance, pvalue, and matching_hash
"""
with open(result_file) as handle:
... |
def read_mash_screen(screen_result):
"""
:param screen_result: Tab-delimited result file generated by mash screen.
:return: results: A list with each line in the result file as an entry, with attributes identity, shared_hashes,
median_multiplicity, pvalue, and query_id
"""
with open(screen_resul... |
def run_cmd(cmd):
"""
Runs a command using subprocess, and returns both the stdout and stderr from that command
If exit code from command is non-zero, raises subproess.CalledProcessError
:param cmd: command to run as a string, as it would be called on the command line
:return: out, err: Strings that... |
def write_to_logfile(logfile, out, err, cmd):
"""
Writes stdout, stderr, and a command to a logfile
:param logfile: Path to file to write output to.
:param out: Stdout of program called, as a string
:param err: Stderr of program called, as a string
:param cmd: command that was used
"""
w... |
def find_paired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2'):
"""
Looks at a directory to try to find paired fastq files. Should be able to find anything fastq.
:param fastq_directory: Complete path to directory containing fastq files.
:param forward_id: Identifier for forward reads. Defau... |
def find_unpaired_reads(fastq_directory, forward_id='_R1', reverse_id='_R2', find_fasta=False):
"""
Looks at a directory to find unpaired fastq files.
:param fastq_directory: Complete path to directory containing fastq files.
:param forward_id: Identifier for forward reads. Default _R1.
:param rever... |
def find_genusspecific_allele_list(profiles_file, target_genus):
"""
A new way of making our specific databases: Make our profiles file have lists of every gene/allele present for
each genus instead of just excluding a few genes for each. This way, should have much smaller databases
while managing to ma... |
def setup_allelespecific_database(fasta_file, database_folder, allele_list):
"""
Since some genera have some rMLST genes missing, or two copies of some genes, genus-specific databases are needed.
This will take only the alleles known to be part of each genus and write them to a genus-specific file.
:par... |
def extract_rmlst_genes(pair, database, forward_out, reverse_out, threads=12, logfile=None):
"""
Given a pair of reads and an rMLST database, will extract reads that contain sequence from the database.
:param pair: List containing path to forward reads at index 0 and path to reverse reads at index 1.
:p... |
def find_cross_contamination(databases, pair, tmpdir='tmp', log='log.txt', threads=1):
"""
Usese mash to find out whether or not a sample has more than one genus present, indicating cross-contamination.
:param databases: A databases folder, which must contain refseq.msh, a mash sketch that has one represent... |
def number_of_bases_above_threshold(high_quality_base_count, base_count_cutoff=2, base_fraction_cutoff=None):
"""
Finds if a site has at least two bases of high quality, enough that it can be considered
fairly safe to say that base is actually there.
:param high_quality_base_count: Dictionary of count ... |
def find_if_multibase(column, quality_cutoff, base_cutoff, base_fraction_cutoff):
"""
Finds if a position in a pileup has more than one base present.
:param column: A pileupColumn generated by pysam
:param quality_cutoff: Desired minimum phred quality for a base in order to be counted towards a multi-al... |
def get_contig_names(fasta_file):
"""
Gets contig names from a fasta file using SeqIO.
:param fasta_file: Full path to uncompressed, fasta-formatted file
:return: List of contig names.
"""
contig_names = list()
for contig in SeqIO.parse(fasta_file, 'fasta'):
contig_names.append(conti... |
def read_contig(contig_name, bamfile_name, reference_fasta, quality_cutoff=20, base_cutoff=2, base_fraction_cutoff=None):
"""
Examines a contig to find if there are positions where more than one base is present.
:param contig_name: Name of contig as a string.
:param bamfile_name: Full path to bamfile. M... |
def find_rmlst_type(kma_report, rmlst_report):
"""
Uses a report generated by KMA to determine what allele is present for each rMLST gene.
:param kma_report: The .res report generated by KMA.
:param rmlst_report: rMLST report file to write information to.
:return: a sorted list of loci present, in f... |
def base_dict_to_string(base_dict):
"""
Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4
:param base_dict: Dictionary of bases and counts created by find_if_multibase
:return: String representing that dictionary.
"""
outstr = ''
# First, sort base_dict so that m... |
def find_total_sequence_length(fasta_file):
"""
Totals up number of bases in a fasta file.
:param fasta_file: Path to an uncompressed, fasta-formatted file.
:return: Number of total bases in file, as an int.
"""
total_length = 0
for sequence in SeqIO.parse(fasta_file, 'fasta'):
total... |
def estimate_percent_contamination(contamination_report_file):
"""
Estimates the percent contamination of a sample (and standard deviation).
:param contamination_report_file: File created by read_contig,
:return: Estimated percent contamination and standard deviation.
"""
contam_levels = list()
... |
def find_contamination(pair, output_folder, databases_folder, forward_id='_R1', threads=1, keep_files=False,
quality_cutoff=20, base_cutoff=2, base_fraction_cutoff=0.05, cgmlst_db=None, Xmx=None, tmpdir=None,
data_type='Illumina', use_rmlst=False):
"""
This needs so... |
def write_output(output_report, sample_name, multi_positions, genus, percent_contam, contam_stddev, total_gene_length,
database_download_date, snp_cutoff=3, cgmlst=None):
"""
Function that writes the output generated by ConFindr to a report file. Appends to a file that already exists,
or cr... |
def check_acceptable_xmx(xmx_string):
"""
BBTools can have their memory set manually. This will check that the memory setting is actually valid
:param xmx_string: The users requested XMX, as a string.
:return: True if the Xmx string will be accepted by BBTools, otherwise false.
"""
acceptable_xm... |
def char_code(columns, name=None):
"""
Character set code field.
:param name: name for the field
:return: an instance of the Character set code field rules
"""
if name is None:
name = 'Char Code Field (' + str(columns) + ' columns)'
if columns <= 0:
raise BaseException()
... |
def make_choice_validator(
choices, default_key=None, normalizer=None):
"""
Returns a callable that accepts the choices provided.
Choices should be provided as a list of 2-tuples, where the first
element is a string that should match user input (the key); the
second being the value associat... |
def prompt(question, validator=None,
choices=None, default_key=NotImplemented,
normalizer=str.lower,
_stdin=None, _stdout=None):
"""
Prompt user for question, maybe choices, and get answer.
Arguments:
question
The question to prompt. It will only be prompted o... |
def prompt_overwrite_json(original, new, target_path, dumps=json_dumps):
"""
Prompt end user with a diff of original and new json that may
overwrite the file at the target_path. This function only displays
a confirmation prompt and it is up to the caller to implement the
actual functionality. Opti... |
def locate_package_entry_file(working_dir, package_name):
"""
Locate a single npm package to return its browser or main entry.
"""
basedir = join(working_dir, 'node_modules', package_name)
package_json = join(basedir, 'package.json')
if not exists(package_json):
logger.debug(
... |
def render_pictures(context, selection='recent', amount=3):
"""Template tag to render a list of pictures."""
pictures = Image.objects.filter(
folder__id__in=Gallery.objects.filter(is_published=True).values_list(
'folder__pk', flat=True))
if selection == 'recent':
context.update({... |
def add_header(self, entry):
"""Parses the VCF Header field and returns the number of samples in the VCF file"""
info = entry.split('\t')
self.n_individuals = len(info)-9
for i,v in enumerate(info[9:]):
self.individuals[v] = i
return self.n_individuals > 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.