_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14700 | raise_api_error | train | def raise_api_error(resp, state=None):
"""Raise an exception with a pretty message in various states of upload"""
# TODO: Refactor into an Exception class
error_code = resp.status_code
if error_code == 402:
error_message = (
"Please add a payment method to upload more samples. If yo... | python | {
"resource": ""
} |
q14701 | pretty_print_error | train | def pretty_print_error(err_json):
"""Pretty print Flask-Potion error messages for the user."""
# Special case validation errors
if len(err_json) == 1 and "validationOf" in err_json[0]:
required_fields = ", ".join(err_json[0]["validationOf"]["required"])
return "Validation error. Requires pro... | python | {
"resource": ""
} |
q14702 | OneCodexBase.delete | train | def delete(self):
"""Delete this object from the One Codex server."""
check_bind(self)
if self.id is None:
raise ServerError("{} object does not exist yet".format(self.__class__.name))
elif not self.__class__._has_schema_method("destroy"):
raise MethodNotSupported... | python | {
"resource": ""
} |
q14703 | OneCodexBase.save | train | def save(self):
"""Either create or persist changes on this object back to the One Codex server."""
check_bind(self)
creating = self.id is None
if creating and not self.__class__._has_schema_method("create"):
raise MethodNotSupported("{} do not support creating.".format(self... | python | {
"resource": ""
} |
q14704 | interleaved_filename | train | def interleaved_filename(file_path):
"""Return filename used to represent a set of paired-end files. Assumes Illumina-style naming
conventions where each file has _R1_ or _R2_ in its name."""
if not isinstance(file_path, tuple):
raise OneCodexException("Cannot get the interleaved filename without a ... | python | {
"resource": ""
} |
q14705 | _file_size | train | def _file_size(file_path, uncompressed=False):
"""Return size of a single file, compressed or uncompressed"""
_, ext = os.path.splitext(file_path)
if uncompressed:
if ext in {".gz", ".gzip"}:
with gzip.GzipFile(file_path, mode="rb") as fp:
try:
fp.see... | python | {
"resource": ""
} |
q14706 | _call_init_upload | train | def _call_init_upload(file_name, file_size, metadata, tags, project, samples_resource):
"""Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_si... | python | {
"resource": ""
} |
q14707 | _make_retry_fields | train | def _make_retry_fields(file_name, metadata, tags, project):
"""Generate fields to send to init_multipart_upload in the case that a Sample upload via
fastx-proxy fails.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
metad... | python | {
"resource": ""
} |
q14708 | _direct_upload | train | def _direct_upload(file_obj, file_name, fields, session, samples_resource):
"""Uploads a single file-like object via our validating proxy. Maintains compatibility with direct upload
to a user's S3 bucket as well in case we disable our validating proxy.
Parameters
----------
file_obj : `FASTXInterle... | python | {
"resource": ""
} |
q14709 | upload_sequence_fileobj | train | def upload_sequence_fileobj(file_obj, file_name, fields, retry_fields, session, samples_resource):
"""Uploads a single file-like object to the One Codex server via either fastx-proxy or directly
to S3.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
... | python | {
"resource": ""
} |
q14710 | upload_document | train | def upload_document(file_path, session, documents_resource, progressbar=None):
"""Uploads multiple document files to the One Codex server directly to S3 via an intermediate
bucket.
Parameters
----------
file_path : `str`
A path to a file on the system.
session : `requests.Session`
... | python | {
"resource": ""
} |
q14711 | upload_document_fileobj | train | def upload_document_fileobj(file_obj, file_name, session, documents_resource, log=None):
"""Uploads a single file-like object to the One Codex server directly to S3.
Parameters
----------
file_obj : `FilePassthru`, or a file-like object
If a file-like object is given, its mime-type will be sent... | python | {
"resource": ""
} |
q14712 | _s3_intermediate_upload | train | def _s3_intermediate_upload(file_obj, file_name, fields, session, callback_url):
"""Uploads a single file-like object to an intermediate S3 bucket which One Codex can pull from
after receiving a callback.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
... | python | {
"resource": ""
} |
q14713 | merge_strings_files | train | def merge_strings_files(old_strings_file, new_strings_file):
""" Merges the old strings file with the new one.
Args:
old_strings_file (str): The path to the old strings file (previously produced, and possibly altered)
new_strings_file (str): The path to the new strings file (newly produced).
... | python | {
"resource": ""
} |
q14714 | LocalizationCommandLineOperation.configure_parser | train | def configure_parser(self, parser):
"""
Adds the necessary supported arguments to the argument parser.
Args:
parser (argparse.ArgumentParser): The parser to add arguments to.
"""
parser.add_argument("--log_path", default="", help="The log file path")
parser.a... | python | {
"resource": ""
} |
q14715 | LocalizationCommandLineOperation.run_with_standalone_parser | train | def run_with_standalone_parser(self):
"""
Will run the operation as standalone with a new ArgumentParser
"""
parser = argparse.ArgumentParser(description=self.description())
self.configure_parser(parser)
self.run(parser.parse_args()) | python | {
"resource": ""
} |
q14716 | DistanceMixin.alpha_diversity | train | def alpha_diversity(self, metric="simpson", rank="auto"):
"""Caculate the diversity within a community.
Parameters
----------
metric : {'simpson', 'chao1', 'shannon'}
The diversity metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', ... | python | {
"resource": ""
} |
q14717 | DistanceMixin.beta_diversity | train | def beta_diversity(self, metric="braycurtis", rank="auto"):
"""Calculate the diversity between two communities.
Parameters
----------
metric : {'jaccard', 'braycurtis', 'cityblock'}
The distance metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'orde... | python | {
"resource": ""
} |
q14718 | DistanceMixin.unifrac | train | def unifrac(self, weighted=True, rank="auto"):
"""A beta diversity metric that takes into account the relative relatedness of community
members. Weighted UniFrac looks at abundances, unweighted UniFrac looks at presence.
Parameters
----------
weighted : `bool`
Calcul... | python | {
"resource": ""
} |
q14719 | fetch_api_key_from_uname | train | def fetch_api_key_from_uname(username, password, server_url):
"""
Retrieves an API key from the One Codex webpage given the username and password
"""
# TODO: Hit programmatic endpoint to fetch JWT key, not API key
with requests.Session() as session:
# get the login page normally
text... | python | {
"resource": ""
} |
q14720 | check_version | train | def check_version(version, server):
"""Check if the current CLI version is supported by the One Codex backend.
Parameters
----------
version : `string`
Current version of the One Codex client library
server : `string`
Complete URL to One Codex server, e.g., https://app.onecodex.com
... | python | {
"resource": ""
} |
q14721 | pprint | train | def pprint(j, no_pretty):
"""
Prints as formatted JSON
"""
if not no_pretty:
click.echo(
json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(",", ": "))
)
else:
click.echo(j) | python | {
"resource": ""
} |
q14722 | is_insecure_platform | train | def is_insecure_platform():
"""
Checks if the current system is missing an SSLContext object
"""
v = sys.version_info
if v.major == 3:
return False # Python 2 issue
if v.major == 2 and v.minor == 7 and v.micro >= 9:
return False # >= 2.7.9 includes the new SSL updates
try... | python | {
"resource": ""
} |
q14723 | warn_if_insecure_platform | train | def warn_if_insecure_platform():
"""
Produces a nice message if SSLContext object is not available.
Also returns True -> platform is insecure
False -> platform is secure
"""
m = (
"\n"
"#################################################################################... | python | {
"resource": ""
} |
q14724 | download_file_helper | train | def download_file_helper(url, input_path):
"""
Manages the chunked downloading of a file given an url
"""
r = requests.get(url, stream=True)
if r.status_code != 200:
cli_log.error("Failed to download file: %s" % r.json()["message"])
local_full_path = get_download_dest(input_path, r.url)
... | python | {
"resource": ""
} |
q14725 | check_for_allowed_file | train | def check_for_allowed_file(f):
"""
Checks a file extension against a list of seq file exts
"""
for ext in SUPPORTED_EXTENSIONS:
if f.endswith(ext):
return True
log.error("Failed upload: Not an allowed file extension: %s", f)
raise SystemExit | python | {
"resource": ""
} |
q14726 | TaxonomyMixin.tree_build | train | def tree_build(self):
"""Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or
`SampleCollection`.
Returns
-------
`skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current
analysis and their parents leading back... | python | {
"resource": ""
} |
q14727 | TaxonomyMixin.tree_prune_tax_ids | train | def tree_prune_tax_ids(self, tree, tax_ids):
"""Prunes a tree back to contain only the tax_ids in the list and their parents.
Parameters
----------
tree : `skbio.tree.TreeNode`
The root node of the tree to perform this operation on.
tax_ids : `list`
A `li... | python | {
"resource": ""
} |
q14728 | TaxonomyMixin.tree_prune_rank | train | def tree_prune_rank(self, tree, rank="species"):
"""Takes a TreeNode tree and prunes off any tips not at the specified rank and backwards up
until all of the tips are at the specified rank.
Parameters
----------
tree : `skbio.tree.TreeNode`
The root node of the tree ... | python | {
"resource": ""
} |
q14729 | write_file_elements_to_strings_file | train | def write_file_elements_to_strings_file(file_path, file_elements):
""" Write elements to the string file
Args:
file_path (str): The path to the strings file
file_elements (list) : List of elements to write to the file.
"""
f = open_strings_file(file_path, "w")
for element in file_el... | python | {
"resource": ""
} |
q14730 | setup_logging | train | def setup_logging(args=None):
""" Setup logging module.
Args:
args (optional): The arguments returned by the argparse module.
"""
logging_level = logging.WARNING
if args is not None and args.verbose:
logging_level = logging.INFO
config = {"level": logging_level, "format": "jtloc... | python | {
"resource": ""
} |
q14731 | extract_header_comment_key_value_tuples_from_file | train | def extract_header_comment_key_value_tuples_from_file(file_descriptor):
""" Extracts tuples representing comments and localization entries from strings file.
Args:
file_descriptor (file): The file to read the tuples from
Returns:
list : List of tuples representing the headers and localizat... | python | {
"resource": ""
} |
q14732 | extract_jtl_string_pairs_from_text_file | train | def extract_jtl_string_pairs_from_text_file(results_dict, file_path):
""" Extracts all string pairs matching the JTL pattern from given text file.
This can be used as an "extract_func" argument in the extract_string_pairs_in_directory method.
Args:
results_dict (dict): The dict to add the the stri... | python | {
"resource": ""
} |
q14733 | extract_string_pairs_in_directory | train | def extract_string_pairs_in_directory(directory_path, extract_func, filter_func):
""" Retrieves all string pairs in the directory
Args:
directory_path (str): The path of the directory containing the file to extract string pairs from.
extract_func (function): Function for extracting the localiza... | python | {
"resource": ""
} |
q14734 | write_entry_to_file | train | def write_entry_to_file(file_descriptor, entry_comment, entry_key):
""" Writes a localization entry to the file
Args:
file_descriptor (file, instance): The file to write the entry to.
entry_comment (str): The entry's comment.
entry_key (str): The entry's key.
"""
escaped_key = r... | python | {
"resource": ""
} |
q14735 | append_dictionary_to_file | train | def append_dictionary_to_file(localization_key_to_comment, file_path, section_name):
""" Appends dictionary of localization keys and comments to a file
Args:
localization_key_to_comment (dict): A mapping between localization keys and comments.
file_path (str): The path of the file to append to.... | python | {
"resource": ""
} |
q14736 | write_dict_to_new_file | train | def write_dict_to_new_file(file_name, localization_key_to_comment):
""" Writes dictionary of localization keys and comments to a file.
Args:
localization_key_to_comment (dict): A mapping between localization keys and comments.
file_name (str): The path of the file to append to.
"""
out... | python | {
"resource": ""
} |
q14737 | find_files | train | def find_files(base_dir, extensions, exclude_dirs=list()):
""" Find all files matching the given extensions.
Args:
base_dir (str): Path of base directory to search in.
extensions (list): A list of file extensions to search for.
exclude_dirs (list): A list of directories to exclude from ... | python | {
"resource": ""
} |
q14738 | should_include_file_in_search | train | def should_include_file_in_search(file_name, extensions, exclude_dirs):
""" Whether or not a filename matches a search criteria according to arguments.
Args:
file_name (str): A file path to check.
extensions (list): A list of file extensions file should match.
exclude_dirs (list): A lis... | python | {
"resource": ""
} |
q14739 | AnalysisMixin._get_auto_rank | train | def _get_auto_rank(self, rank):
"""Tries to figure out what rank we should use for analyses"""
if rank == "auto":
# if we're an accessor for a ClassificationsDataFrame, use its _rank property
if self.__class__.__name__ == "OneCodexAccessor":
return self._rank
... | python | {
"resource": ""
} |
q14740 | AnalysisMixin._guess_normalized | train | def _guess_normalized(self):
"""Returns true if the collated counts in `self._results` appear to be normalized.
Notes
-----
It's possible that the _results df has already been normalized, which can cause some
methods to fail. This method lets us guess whether that's true and act... | python | {
"resource": ""
} |
q14741 | AnalysisMixin.to_df | train | def to_df(
self,
rank="auto",
top_n=None,
threshold=None,
remove_zeros=True,
normalize="auto",
table_format="wide",
):
"""Takes the ClassificationsDataFrame associated with these samples, or SampleCollection,
does some filtering, and returns a ... | python | {
"resource": ""
} |
q14742 | OneCodexPDFExporter.from_notebook_node | train | def from_notebook_node(self, nb, resources=None, **kw):
"""Takes output of OneCodexHTMLExporter and runs Weasyprint to get a PDF."""
from weasyprint import HTML, CSS
nb = copy.deepcopy(nb)
output, resources = super(OneCodexPDFExporter, self).from_notebook_node(
nb, resource... | python | {
"resource": ""
} |
q14743 | OneCodexDocumentExporter.from_notebook_node | train | def from_notebook_node(self, nb, resources=None, **kw):
"""Takes PDF output from PDFExporter and uploads to One Codex Documents portal."""
output, resources = super(OneCodexDocumentExporter, self).from_notebook_node(
nb, resources=resources, **kw
)
from onecodex import Api
... | python | {
"resource": ""
} |
q14744 | generate_strings | train | def generate_strings(project_base_dir, localization_bundle_path, tmp_directory, exclude_dirs, include_strings_file,
special_ui_components_prefix):
"""
Calls the builtin 'genstrings' command with JTLocalizedString as the string to search for,
and adds strings extracted from UI elements i... | python | {
"resource": ""
} |
q14745 | SampleCollection.filter | train | def filter(self, filter_func):
"""Return a new SampleCollection containing only samples meeting the filter criteria.
Will pass any kwargs (e.g., field or skip_missing) used when instantiating the current class
on to the new SampleCollection that is returned.
Parameters
--------... | python | {
"resource": ""
} |
q14746 | SampleCollection._classification_fetch | train | def _classification_fetch(self, skip_missing=None):
"""Turns a list of objects associated with a classification result into a list of
Classifications objects.
Parameters
----------
skip_missing : `bool`
If an analysis was not successful, exclude it, warn, and keep go... | python | {
"resource": ""
} |
q14747 | SampleCollection._collate_metadata | train | def _collate_metadata(self):
"""Turns a list of objects associated with a classification result into a DataFrame of
metadata.
Returns
-------
None, but stores a result in self._cached.
"""
import pandas as pd
DEFAULT_FIELDS = None
metadata = []
... | python | {
"resource": ""
} |
q14748 | SampleCollection._collate_results | train | def _collate_results(self, field=None):
"""For a list of objects associated with a classification result, return the results as a
DataFrame and dict of taxa info.
Parameters
----------
field : {'readcount_w_children', 'readcount', 'abundance'}
Which field to use for ... | python | {
"resource": ""
} |
q14749 | SampleCollection.to_otu | train | def to_otu(self, biom_id=None):
"""Converts a list of objects associated with a classification result into a `dict` resembling
an OTU table.
Parameters
----------
biom_id : `string`, optional
Optionally specify an `id` field for the generated v1 BIOM file.
R... | python | {
"resource": ""
} |
q14750 | localization_merge_back | train | def localization_merge_back(updated_localizable_file, old_translated_file, new_translated_file, merged_translated_file):
""" Generates a file merging the old translations and the new ones.
Args:
updated_localizable_file (str): The path to the updated localization strings file, meaning the strings that
... | python | {
"resource": ""
} |
q14751 | boxplot | train | def boxplot(df, category, quantity, category_type="N", title=None, xlabel=None, ylabel=None):
"""Plot a simple boxplot using Altair.
Parameters
----------
df : `pandas.DataFrame`
Contains columns matching 'category' and 'quantity' labels, at a minimum.
category : `string`
The name o... | python | {
"resource": ""
} |
q14752 | dendrogram | train | def dendrogram(tree):
"""Plot a simple square dendrogram using Altair.
Parameters
----------
tree : `dict` returned by `scipy.cluster.hierarchy.dendrogram`
Contains, at a minimum, 'icoord', 'dcoord', and 'leaves' keys. Scipy does all the work of
determining where the lines in the tree should go... | python | {
"resource": ""
} |
q14753 | add_genstrings_comments_to_file | train | def add_genstrings_comments_to_file(localization_file, genstrings_err):
""" Adds the comments produced by the genstrings script for duplicate keys.
Args:
localization_file (str): The path to the strings file.
"""
errors_to_log = [line for line in genstrings_err.splitlines() if "used with mult... | python | {
"resource": ""
} |
q14754 | ResourceDownloadMixin.download | train | def download(self, path=None, file_obj=None, progressbar=False):
"""Downloads files from One Codex.
Parameters
----------
path : `string`, optional
Full path to save the file to. If omitted, defaults to the original filename
in the current working directory.
... | python | {
"resource": ""
} |
q14755 | prepare_for_translation | train | def prepare_for_translation(localization_bundle_path):
""" Prepares the localization bundle for translation.
This means, after creating the strings files using genstrings.sh, this will produce '.pending' files, that contain
the files that are yet to be translated.
Args:
localization_bundle_pat... | python | {
"resource": ""
} |
q14756 | onecodex | train | def onecodex(ctx, api_key, no_pprint, verbose, telemetry):
"""One Codex v1 API command line interface"""
# set up the context for sub commands
click.Context.get_usage = click.Context.get_help
ctx.obj = {}
ctx.obj["API_KEY"] = api_key
ctx.obj["NOPPRINT"] = no_pprint
ctx.obj["TELEMETRY"] = tel... | python | {
"resource": ""
} |
q14757 | classifications | train | def classifications(ctx, classifications, results, readlevel, readlevel_path):
"""Retrieve performed metagenomic classifications"""
# basic operation -- just print
if not readlevel and not results:
cli_resource_fetcher(ctx, "classifications", classifications)
# fetch the results
elif not r... | python | {
"resource": ""
} |
q14758 | schema_resolve_refs | train | def schema_resolve_refs(schema, ref_resolver=None, root=None):
"""
Helper method for decoding references. Self-references are resolved automatically; other references are
resolved using a callback function.
:param object schema:
:param callable ref_resolver:
:param None root:
:return:
"... | python | {
"resource": ""
} |
q14759 | reference | train | def reference(text=None, label=None):
"""Add a reference to the bibliography and insert a superscript number.
Parameters
----------
text : `string`, optional
The complete text of the reference, e.g. Roo, et al. "How to Python." Nature, 2019.
label : `string`, optional
A short label ... | python | {
"resource": ""
} |
q14760 | extract_element_internationalized_comment | train | def extract_element_internationalized_comment(element):
""" Extracts the xib element's comment, if the element has been internationalized.
Args:
element (element): The element from which to extract the comment.
Returns:
The element's internationalized comment, None if it does not exist, or... | python | {
"resource": ""
} |
q14761 | add_string_pairs_from_attributed_ui_element | train | def add_string_pairs_from_attributed_ui_element(results, ui_element, comment_prefix):
""" Adds string pairs from a UI element with attributed text
Args:
results (list): The list to add the results to.
attributed_element (element): The element from the xib that contains, to extract the fragments... | python | {
"resource": ""
} |
q14762 | add_string_pairs_from_label_element | train | def add_string_pairs_from_label_element(xib_file, results, label, special_ui_components_prefix):
""" Adds string pairs from a label element.
Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
label (element): The label element from the xib, to ex... | python | {
"resource": ""
} |
q14763 | add_string_pairs_from_text_field_element | train | def add_string_pairs_from_text_field_element(xib_file, results, text_field, special_ui_components_prefix):
""" Adds string pairs from a textfield element.
Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
text_field(element): The textfield eleme... | python | {
"resource": ""
} |
q14764 | add_string_pairs_from_text_view_element | train | def add_string_pairs_from_text_view_element(xib_file, results, text_view, special_ui_components_prefix):
""" Adds string pairs from a textview element.
Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
text_view(element): The textview element fr... | python | {
"resource": ""
} |
q14765 | add_string_pairs_from_button_element | train | def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix):
""" Adds strings pairs from a button xib element.
Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
button(element): The button element from the x... | python | {
"resource": ""
} |
q14766 | localization_diff | train | def localization_diff(localizable_file, translated_file, excluded_strings_file, output_translation_file):
""" Generates a strings file representing the strings that were yet to be translated.
Args:
localizable_file (str): The path to the localization strings file, meaning the file that represents the s... | python | {
"resource": ""
} |
q14767 | add_404_page | train | def add_404_page(app):
"""Build an extra ``404.html`` page if no ``"404"`` key is in the
``html_additional_pages`` config.
"""
is_epub = isinstance(app.builder, EpubBuilder)
config_pages = app.config.html_additional_pages
if not is_epub and "404" not in config_pages:
yield ("404", {}, "... | python | {
"resource": ""
} |
q14768 | singlehtml_sidebars | train | def singlehtml_sidebars(app):
"""When using a ``singlehtml`` builder, replace the
``html_sidebars`` config with ``singlehtml_sidebars``. This can be
used to change what sidebars are rendered for the single page called
``"index"`` by the builder.
"""
if app.config.singlehtml_sidebars is not None ... | python | {
"resource": ""
} |
q14769 | get_version | train | def get_version(name, version_length=2, placeholder="x"):
"""Ensures that the named package is installed and returns version
strings to be used by Sphinx.
Sphinx uses ``version`` to mean an abbreviated form of the full
version string, which is called ``release``. In ``conf.py``::
release, vers... | python | {
"resource": ""
} |
q14770 | set_is_pallets_theme | train | def set_is_pallets_theme(app):
"""Set the ``is_pallets_theme`` config to ``True`` if the current
theme is a decedent of the ``pocoo`` theme.
"""
if app.config.is_pallets_theme is not None:
return
theme = getattr(app.builder, "theme", None)
while theme is not None:
if theme.name... | python | {
"resource": ""
} |
q14771 | only_pallets_theme | train | def only_pallets_theme(default=None):
"""Create a decorator that calls a function only if the
``is_pallets_theme`` config is ``True``.
Used to prevent Sphinx event callbacks from doing anything if the
Pallets themes are installed but not used. ::
@only_pallets_theme()
def inject_value(... | python | {
"resource": ""
} |
q14772 | ExampleRunner.declare_example | train | def declare_example(self, source):
"""Execute the given code, adding it to the runner's namespace."""
with patch_modules():
code = compile(source, "<docs>", "exec")
exec(code, self.namespace) | python | {
"resource": ""
} |
q14773 | setup | train | def setup(
*,
verbose: bool = False,
quiet: bool = False,
color: str = "auto",
title: str = "auto",
timestamp: bool = False
) -> None:
""" Configure behavior of message functions.
:param verbose: Whether :func:`debug` messages should get printed
:param quiet: Hide every message exce... | python | {
"resource": ""
} |
q14774 | process_tokens | train | def process_tokens(
tokens: Sequence[Token], *, end: str = "\n", sep: str = " "
) -> Tuple[str, str]:
""" Returns two strings from a list of tokens.
One containing ASCII escape codes, the other
only the 'normal' characters
"""
# Flatten the list of tokens in case some of them are of
# class... | python | {
"resource": ""
} |
q14775 | message | train | def message(
*tokens: Token,
end: str = "\n",
sep: str = " ",
fileobj: FileObj = sys.stdout,
update_title: bool = False
) -> None:
""" Helper method for error, warning, info, debug
"""
if using_colorama():
global _INITIALIZED
if not _INITIALIZED:
colorama.ini... | python | {
"resource": ""
} |
q14776 | fatal | train | def fatal(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message and call ``sys.exit`` """
error(*tokens, **kwargs)
sys.exit(1) | python | {
"resource": ""
} |
q14777 | info_section | train | def info_section(*tokens: Token, **kwargs: Any) -> None:
""" Print an underlined section name """
# We need to know the length of the section:
process_tokens_kwargs = kwargs.copy()
process_tokens_kwargs["color"] = False
no_color = _process_tokens(tokens, **process_tokens_kwargs)
info(*tokens, **... | python | {
"resource": ""
} |
q14778 | info_1 | train | def info_1(*tokens: Token, **kwargs: Any) -> None:
""" Print an important informative message """
info(bold, blue, "::", reset, *tokens, **kwargs) | python | {
"resource": ""
} |
q14779 | dot | train | def dot(*, last: bool = False, fileobj: Any = None) -> None:
""" Print a dot without a newline unless it is the last one.
Useful when you want to display a progress with very little
knowledge.
:param last: whether this is the last dot (will insert a newline)
"""
end = "\n" if last else ""
... | python | {
"resource": ""
} |
q14780 | info_count | train | def info_count(i: int, n: int, *rest: Token, **kwargs: Any) -> None:
""" Display a counter before the rest of the message.
``rest`` and ``kwargs`` are passed to :func:`info`
Current index should start at 0 and end at ``n-1``, like in ``enumerate()``
:param i: current index
:param n: total number ... | python | {
"resource": ""
} |
q14781 | info_progress | train | def info_progress(prefix: str, value: float, max_value: float) -> None:
""" Display info progress in percent.
:param value: the current value
:param max_value: the max value
:param prefix: the prefix message to print
"""
if sys.stdout.isatty():
percent = float(value) / max_value * 100... | python | {
"resource": ""
} |
q14782 | debug | train | def debug(*tokens: Token, **kwargs: Any) -> None:
""" Print a debug message.
Messages are shown only when ``CONFIG["verbose"]`` is true
"""
if not CONFIG["verbose"] or CONFIG["record"]:
return
message(*tokens, **kwargs) | python | {
"resource": ""
} |
q14783 | indent_iterable | train | def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]:
"""Indent an iterable."""
return [" " * num + l for l in elems] | python | {
"resource": ""
} |
q14784 | indent | train | def indent(text: str, num: int = 2) -> str:
"""Indent a piece of text."""
lines = text.splitlines()
return "\n".join(indent_iterable(lines, num=num)) | python | {
"resource": ""
} |
q14785 | ask_string | train | def ask_string(*question: Token, default: Optional[str] = None) -> Optional[str]:
"""Ask the user to enter a string.
"""
tokens = get_ask_tokens(question)
if default:
tokens.append("(%s)" % default)
info(*tokens)
answer = read_input()
if not answer:
return default
return ... | python | {
"resource": ""
} |
q14786 | ask_password | train | def ask_password(*question: Token) -> str:
"""Ask the user to enter a password.
"""
tokens = get_ask_tokens(question)
info(*tokens)
answer = read_password()
return answer | python | {
"resource": ""
} |
q14787 | ask_choice | train | def ask_choice(
*prompt: Token, choices: List[Any], func_desc: Optional[FuncDesc] = None
) -> Any:
"""Ask the user to choose from a list of choices.
:return: the selected choice
``func_desc`` will be called on every list item for displaying
and sorting the list. If not given, will default to
t... | python | {
"resource": ""
} |
q14788 | ask_yes_no | train | def ask_yes_no(*question: Token, default: bool = False) -> bool:
"""Ask the user to answer by yes or no"""
while True:
tokens = [green, "::", reset] + list(question) + [reset]
if default:
tokens.append("(Y/n)")
else:
tokens.append("(y/N)")
info(*tokens)
... | python | {
"resource": ""
} |
q14789 | did_you_mean | train | def did_you_mean(message: str, user_input: str, choices: Sequence[str]) -> str:
""" Given a list of choices and an invalid user input, display the closest
items in the list that match the input.
"""
if not choices:
return message
else:
result = {
difflib.SequenceMatcher(... | python | {
"resource": ""
} |
q14790 | Timer.stop | train | def stop(self) -> None:
""" Stop the timer and emit a nice log """
end_time = datetime.datetime.now()
elapsed_time = end_time - self.start_time
elapsed_seconds = elapsed_time.seconds
hours, remainder = divmod(int(elapsed_seconds), 3600)
minutes, seconds = divmod(remainder... | python | {
"resource": ""
} |
q14791 | xmllint_format | train | def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... | python | {
"resource": ""
} |
q14792 | Resolver.download_to_directory | train | def download_to_directory(self, directory, url, basename=None, overwrite=False, subdir=None):
"""
Download a file to the workspace.
Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.
If basename is not given but subdir is, assume user know... | python | {
"resource": ""
} |
q14793 | Resolver.workspace_from_url | train | def workspace_from_url(self, mets_url, dst_dir=None, clobber_mets=False, mets_basename=None, download=False, baseurl=None):
"""
Create a workspace from a METS by URL.
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Ta... | python | {
"resource": ""
} |
q14794 | Resolver.workspace_from_nothing | train | def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False):
"""
Create an empty workspace.
"""
if directory is None:
directory = tempfile.mkdtemp(prefix=TMP_PREFIX)
if not exists(directory):
makedirs(directory)
mets_... | python | {
"resource": ""
} |
q14795 | OcrdXmlDocument.to_xml | train | def to_xml(self, xmllint=False):
"""
Serialize all properties as pretty-printed XML
Args:
xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing
"""
root = self._tree.getroot()
ret = ET.tostring(ET.ElementTree(root), pretty_print=True)
... | python | {
"resource": ""
} |
q14796 | workspace_cli | train | def workspace_cli(ctx, directory, mets_basename, backup):
"""
Working with workspace
"""
ctx.obj = WorkspaceCtx(os.path.abspath(directory), mets_basename, automatic_backup=backup) | python | {
"resource": ""
} |
q14797 | workspace_clone | train | def workspace_clone(ctx, clobber_mets, download, mets_url, workspace_dir):
"""
Create a workspace from a METS_URL and return the directory
METS_URL can be a URL, an absolute path or a path relative to $PWD.
If WORKSPACE_DIR is not provided, creates a temporary directory.
"""
workspace = ctx.re... | python | {
"resource": ""
} |
q14798 | workspace_create | train | def workspace_create(ctx, clobber_mets, directory):
"""
Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD"
"""
workspace = ctx.resolver.workspace_from_nothing(
directory=os.path.abspath(directory),
mets_basename=ctx.mets_basename,
clobber_mets=clobber... | python | {
"resource": ""
} |
q14799 | workspace_add_file | train | def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, force, local_filename):
"""
Add a file LOCAL_FILENAME to METS in a workspace.
"""
workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)
if not local_filen... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.