_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q245400 | sign | train | def sign(uri, headers, credentials):
"""Sign the URI and headers.
A request method of `GET` with no body content is assumed.
:param credentials: A tuple of consumer key, token key, and token secret.
"""
consumer_key, | python | {
"resource": ""
} |
q245401 | parse_docstring | train | def parse_docstring(thing):
"""Parse a Python docstring, or the docstring found on `thing`.
:return: a ``(title, body)`` tuple. As per docstring convention, title is
the docstring's first paragraph and body is the rest.
"""
assert not isinstance(thing, bytes)
doc = cleandoc(thing) if isinst... | python | {
"resource": ""
} |
q245402 | api_url | train | def api_url(string):
"""Ensure that `string` looks like a URL to the API.
This ensures that the API version is specified explicitly (i.e. the path
ends with /api/{version}). If not, version 2.0 is selected. It also
ensures that the path ends with a forward-slash.
This is suitable for use as an arg... | python | {
"resource": ""
} |
q245403 | vars_class | train | def vars_class(cls):
"""Return a dict of vars for the given class, including all ancestors.
This differs from the usual behaviour of `vars` which returns attributes
belonging to the given class and not its ancestors. | python | {
"resource": ""
} |
q245404 | remove_None | train | def remove_None(params: dict):
"""Remove all keys in `params` that have the value of `None`."""
return {
key: value | python | {
"resource": ""
} |
q245405 | OAuthSigner.sign_request | train | def sign_request(self, url, method, body, headers):
"""Sign a request.
:param url: The URL to which the request is to be sent.
:param headers: The headers in the request. These will be updated with
the signature.
"""
# The use of PLAINTEXT here was copied from MAAS, ... | python | {
"resource": ""
} |
q245406 | SpinnerContext.print | train | def print(self, *args, **kwargs):
"""Print inside of the spinner context.
This must be used when inside of a spinner context to ensure that
the line printed doesn't overwrite an already existing spinner line.
"""
| python | {
"resource": ""
} |
q245407 | RaidsType.create | train | async def create(
cls, node: Union[Node, str],
level: Union[RaidLevel, str],
devices: Iterable[Union[BlockDevice, Partition]], *,
name: str = None, uuid: str = None,
spare_devices: Iterable[Union[BlockDevice, Partition]]):
"""
Create a RAID on ... | python | {
"resource": ""
} |
q245408 | StaticRoutesType.create | train | async def create(cls, destination: Union[int, Subnet],
source: Union[int, Subnet], gateway_ip: str, metric: int):
"""
Create a `StaticRoute` in MAAS.
:param name: The name of the `StaticRoute` (optional, will be given a
default value if not specified).
:type... | python | {
"resource": ""
} |
q245409 | CustomizedDist.fetch_build_egg | train | def fetch_build_egg(self, req):
""" Specialized version of Distribution.fetch_build_egg
that respects respects allow_hosts and index_url. """
from setuptools.command.easy_install import easy_install
dist = Distribution({'script_args': ['easy_install']})
dist.parse_config_files()
opts = dist.get_option_dict(... | python | {
"resource": ""
} |
q245410 | V2Client._caching | train | def _caching(self, disk_or_memory, cache_directory=None):
"""
Decorator that allows caching the outputs of the BaseClient get methods.
Cache can be either disk- or memory-based.
Disk-based cache is reloaded automatically between runs if the same
cache directory is specified.
... | python | {
"resource": ""
} |
q245411 | BaseResource.set_subresources | train | def set_subresources(self, **kwargs):
"""Same logic as the original except for the first 'if' clause."""
for attribute_name, resource in self._subresource_map.items():
sub_attr = kwargs.get(attribute_name)
if sub_attr is None:
# Attribute was not found or is null
... | python | {
"resource": ""
} |
q245412 | build_url_base | train | def build_url_base(host, port, is_https):
"""
Make base of url based on config
"""
base = "http"
| python | {
"resource": ""
} |
q245413 | CreateDevice.is_motion_detection_enabled | train | def is_motion_detection_enabled(self):
""" Get current state of Motion Detection """
response = requests.get(self.motion_url, auth=HTTPBasicAuth(
self._username, self._password))
_LOGGING.debug('Response: %s', response.text)
if response.status_code != 200:
_LOGG... | python | {
"resource": ""
} |
q245414 | CreateDevice.put_motion_detection_xml | train | def put_motion_detection_xml(self, xml):
""" Put request with xml Motion Detection """
_LOGGING.debug('xml:')
_LOGGING.debug("%s", xml)
headers = DEFAULT_HEADERS
headers['Content-Length'] = len(xml)
headers['Host'] = self._host
response = requests.put(self.motio... | python | {
"resource": ""
} |
q245415 | DomainValidator._apply_common_rules | train | def _apply_common_rules(self, part, maxlength):
"""This method contains the rules that must be applied to both the
domain and the local part of the e-mail address.
"""
part = part.strip()
if self.fix:
part = part.strip('.')
if not part:
... | python | {
"resource": ""
} |
q245416 | Message.mime | train | def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author:
raise ValueError("You must specify an author.")
if not self.subject:
raise ValueError("You must specify a subject.")
if len(self.recipients) == 0:
raise ValueError("You must specify a... | python | {
"resource": ""
} |
q245417 | Message.attach | train | def attach(self, name, data=None, maintype=None, subtype=None,
inline=False, filename=None, filename_charset='', filename_language='',
encoding=None):
"""Attach a file to this message.
:param name: Path to the file to attach if data is None, or the name
of the file if the ``data`` argument is given
:pa... | python | {
"resource": ""
} |
q245418 | Message.embed | train | def embed(self, name, data=None):
"""Attach an image file and prepare for HTML embedding.
This method should only be used to embed images.
:param name: Path to the image to embed if data is None, or the name
of the file if the ``data`` argument is given
:param data: Contents of the image to embed, or No... | python | {
"resource": ""
} |
q245419 | MockTransport.deliver | train | def deliver(self, message):
"""Concrete message delivery."""
config = self.config
success = config.success
failure = config.failure
exhaustion = config.exhaustion
if getattr(message, 'die', False):
1/0
if failure:
... | python | {
"resource": ""
} |
q245420 | ImmediateManager.startup | train | def startup(self):
"""Perform startup actions.
This just chains down to the transport layer.
"""
log.info("Immediate delivery manager starting.")
| python | {
"resource": ""
} |
q245421 | AddressList.string_addresses | train | def string_addresses(self, encoding=None):
"""Return a list of string representations of the addresses suitable
for usage in an SMTP transaction."""
if not encoding:
encoding = self.encoding
| python | {
"resource": ""
} |
q245422 | ReconnectingWebSocket.run | train | def run(self):
"""
If the connection drops, then run_forever will terminate and a
reconnection attempt will be made.
"""
while True:
self.connect_lock.acquire()
| python | {
"resource": ""
} |
q245423 | ReconnectingWebSocket.send | train | def send(self, data):
"""
This method keeps trying to send a message relying on the run method
to reopen the websocket in case it was closed.
"""
while not self.stopped():
try:
self.ws.send(data)
| python | {
"resource": ""
} |
q245424 | SushiBarClient.__create_channel_run | train | def __create_channel_run(self, channel, username, token):
"""Sends a post request to create the channel run."""
data = {
'channel_id': channel.get_node_id().hex,
'chef_name': self.__get_chef_name(),
'ricecooker_version': __version__,
'started_by_user': use... | python | {
"resource": ""
} |
q245425 | LocalControlSocket.run | train | def run(self):
"""
This override threading.Thread to open socket and wait for messages.
"""
while True:
self.open_lock.acquire()
if | python | {
"resource": ""
} |
q245426 | filter_filenames | train | def filter_filenames(filenames):
"""
Skip files with extentions in `FILE_EXCLUDE_EXTENTIONS` and filenames that
contain `FILE_SKIP_PATTENRS`.
"""
filenames_cleaned = []
for filename in filenames:
keep = True
for pattern in FILE_EXCLUDE_EXTENTIONS:
if filename.endswith... | python | {
"resource": ""
} |
q245427 | filter_thumbnail_files | train | def filter_thumbnail_files(chan_path, filenames, metadata_provider):
"""
We don't want to create `ContentNode` from thumbnail files.
"""
thumbnail_files_to_skip = metadata_provider.get_thumbnail_paths()
filenames_cleaned = []
for filename in filenames:
keep = True
chan_filepath =... | python | {
"resource": ""
} |
q245428 | keep_folder | train | def keep_folder(raw_path):
"""
Keep only folders that don't contain patterns in `DIR_EXCLUDE_PATTERNS`.
"""
keep = True
for pattern in DIR_EXCLUDE_PATTERNS:
| python | {
"resource": ""
} |
q245429 | process_folder | train | def process_folder(channel, rel_path, filenames, metadata_provider):
"""
Create `ContentNode`s from each file in this folder and the node to `channel`
under the path `rel_path`.
"""
LOGGER.debug('IN process_folder ' + str(rel_path) + ' ' + str(filenames))
if not keep_folder(rel_path):
... | python | {
"resource": ""
} |
q245430 | build_ricecooker_json_tree | train | def build_ricecooker_json_tree(args, options, metadata_provider, json_tree_path):
"""
Download all categories, subpages, modules, and resources from open.edu.
"""
LOGGER.info('Starting to build the ricecooker_json_tree')
channeldir = args['channeldir']
if channeldir.endswith(os.path.sep):
... | python | {
"resource": ""
} |
q245431 | TutorialChef.construct_channel | train | def construct_channel(self, *args, **kwargs):
"""
This method is reponsible for creating a `ChannelNode` object from the info
in `channel_info` and populating it with TopicNode and ContentNode children.
"""
# Create channel
################################################... | python | {
"resource": ""
} |
q245432 | read_tree_from_json | train | def read_tree_from_json(srcpath):
"""
Load ricecooker json tree data from json file at `srcpath`.
"""
with open(srcpath) as infile:
json_tree = json.load(infile)
| python | {
"resource": ""
} |
q245433 | get_channel_node_from_json | train | def get_channel_node_from_json(json_tree):
"""
Build `ChannelNode` from json data provided in `json_tree`.
"""
channel = ChannelNode(
title=json_tree['title'],
description=json_tree['description'],
source_domain=json_tree['source_domain'], | python | {
"resource": ""
} |
q245434 | BaseChef.get_channel | train | def get_channel(self, **kwargs):
"""
Call chef script's get_channel method in compatibility mode
...or...
Create a `ChannelNode` from the Chef's `channel_info` class attribute.
Args:
kwargs (dict): additional keyword arguments that `uploadchannel` received
Re... | python | {
"resource": ""
} |
q245435 | JsonTreeChef.construct_channel | train | def construct_channel(self, **kwargs):
"""
Build the channel tree by adding TopicNodes and ContentNode children.
"""
channel = self.get_channel(**kwargs)
json_tree_path = self.get_json_tree_path(**kwargs)
| python | {
"resource": ""
} |
q245436 | LineCook.pre_run | train | def pre_run(self, args, options):
"""
This function is called before `run` in order to build the json tree.
"""
if 'generate' in args and args['generate']:
self.metadata_provider = CsvMetadataProvider(args['channeldir'],
cha... | python | {
"resource": ""
} |
q245437 | calculate_relative_url | train | def calculate_relative_url(url, filename=None, baseurl=None, subpath=None):
"""
Calculate the relative path for a URL relative to a base URL, possibly also injecting in a subpath prefix.
"""
# ensure the provided subpath is a list
if isinstance(subpath, str):
subpath = subpath.strip("/").sp... | python | {
"resource": ""
} |
q245438 | download_file | train | def download_file(url, destpath, filename=None, baseurl=None, subpath=None, middleware_callbacks=None, middleware_kwargs=None, request_fn=sess.get):
"""
Download a file from a URL, into a destination folder, with optional use of relative paths and middleware processors.
- If `filename` is set, that will be... | python | {
"resource": ""
} |
q245439 | File.set_language | train | def set_language(self, language):
""" Set self.language to internal lang. repr. code from str or Language object. """
if isinstance(language, str):
language_obj = languages.getlang(language)
| python | {
"resource": ""
} |
q245440 | Node.get_thumbnail_preset | train | def get_thumbnail_preset(self):
"""
Returns the format preset corresponding to this Node's type, or None if the node doesn't have a format preset.
"""
if isinstance(self, ChannelNode):
return format_presets.CHANNEL_THUMBNAIL
elif isinstance(self, TopicNode):
... | python | {
"resource": ""
} |
q245441 | PDFParser.open | train | def open(self, update=False):
"""
Opens pdf file to read from.
"""
filename = os.path.basename(self.source_path)
folder, _ext = os.path.splitext(filename)
self.path = os.path.sep.join([self.directory, folder, filename])
if not os.path.exists(os.path.dirname(self.p... | python | {
"resource": ""
} |
q245442 | PDFParser.get_toc | train | def get_toc(self, subchapters=False):
"""
Returns table-of-contents information extracted from the PDF doc.
When `subchapters=False`, the output is a list of this form
.. code-block:: python
[
{'title': 'First chapter', 'page_start': 0, 'page_end': 10},
... | python | {
"resource": ""
} |
q245443 | get_metadata_file_path | train | def get_metadata_file_path(channeldir, filename):
"""
Return the path to the metadata file named `filename` that | python | {
"resource": ""
} |
q245444 | _read_csv_lines | train | def _read_csv_lines(path):
"""
Opens CSV file `path` and returns list of rows.
Pass output of this function to `csv.DictReader` for reading data.
"""
csv_file = open(path, 'r')
| python | {
"resource": ""
} |
q245445 | _clean_dict | train | def _clean_dict(row):
"""
Transform empty strings values of dict `row` to None.
"""
row_cleaned = {}
for key, val in row.items():
if val is None or val == '':
| python | {
"resource": ""
} |
q245446 | CsvMetadataProvider.get | train | def get(self, path_tuple):
"""
Returns metadata dict for path in `path_tuple`.
"""
if path_tuple in self.contentcache:
metadata = self.contentcache[path_tuple]
else:
# TODO: make chef robust to missing metadata
# LOGGER.error(
| python | {
"resource": ""
} |
q245447 | CsvMetadataProvider.get_channel_info | train | def get_channel_info(self):
"""
Returns the first data row from Channel.csv
"""
csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self.channelinfo)
csv_lines = _read_csv_lines(csv_filename)
dict_reader = csv.DictReader(csv_lines)
channel_c... | python | {
"resource": ""
} |
q245448 | CsvMetadataProvider.get_thumbnail_paths | train | def get_thumbnail_paths(self):
"""
Helper function used to avoid processing thumbnail files during `os.walk`.
"""
thumbnail_path_tuples = []
# channel thumbnail
channel_info = self.get_channel_info()
chthumbnail_path = channel_info.get('thumbnail_chan_path', None)... | python | {
"resource": ""
} |
q245449 | CsvMetadataProvider._map_exercise_row_to_dict | train | def _map_exercise_row_to_dict(self, row):
"""
Convert dictionary keys from raw CSV Exercise format to ricecooker keys.
"""
row_cleaned = _clean_dict(row)
license_id = row_cleaned[CONTENT_LICENSE_ID_KEY]
if license_id:
license_dict = dict(
licen... | python | {
"resource": ""
} |
q245450 | CsvMetadataProvider._map_exercise_question_row_to_dict | train | def _map_exercise_question_row_to_dict(self, row):
"""
Convert dictionary keys from raw CSV Exercise Question format to ricecooker keys.
"""
row_cleaned = _clean_dict(row)
# Parse answers
all_answers = []
ansA = row_cleaned[EXERCISE_QUESTIONS_OPTION_A_KEY]
... | python | {
"resource": ""
} |
q245451 | CsvMetadataProvider.validate_headers | train | def validate_headers(self):
"""
Check if CSV metadata files have the right format.
"""
super().validate()
self.validate_header(self.channeldir, self.channelinfo, CHANNEL_INFO_HEADER)
| python | {
"resource": ""
} |
q245452 | CsvMetadataProvider.validate_header | train | def validate_header(self, channeldir, filename, expected_header):
"""
Check if CSV metadata file `filename` have the expected header format.
"""
expected = set(expected_header)
csv_filename = get_metadata_file_path(channeldir, filename)
| python | {
"resource": ""
} |
q245453 | CsvMetadataProvider.generate_contentinfo_from_channeldir | train | def generate_contentinfo_from_channeldir(self, args, options):
"""
Create rows in Content.csv for each folder and file in `self.channeldir`.
"""
LOGGER.info('Generating Content.csv rows folders and file in channeldir')
file_path = get_metadata_file_path(self.channeldir, self.cont... | python | {
"resource": ""
} |
q245454 | CsvMetadataProvider.generate_contentinfo_from_folder | train | def generate_contentinfo_from_folder(self, csvwriter, rel_path, filenames):
"""
Create a topic node row in Content.csv for the folder at `rel_path` and
add content node rows for all the files in the `rel_path` folder.
"""
LOGGER.debug('IN process_folder ' + str(rel_path) + ' ... | python | {
"resource": ""
} |
q245455 | CsvMetadataProvider.channeldir_node_to_row | train | def channeldir_node_to_row(self, path_tuple):
"""
Return a dict with keys corresponding to Content.csv columns.
"""
row = dict()
for key in CONTENT_INFO_HEADER:
row[key] = None
row[CONTENT_PATH_KEY] = "/".join(path_tuple) # use / in .csv on Windows and UNIX
... | python | {
"resource": ""
} |
q245456 | CsvMetadataProvider.generate_templates | train | def generate_templates(self, exercise_questions=False):
"""
Create empty .csv files with the right headers and place them in the
Will place files as siblings of directory `channeldir`.
"""
self.generate_template(channeldir=self.channeldir,
filename=... | python | {
"resource": ""
} |
q245457 | CsvMetadataProvider.generate_template | train | def generate_template(self, channeldir, filename, header):
"""
Create empty template .csv file called `filename` as siblings of the
directory `channeldir` with header fields specified in `header`.
"""
file_path = get_metadata_file_path(channeldir, filename)
if not os.path... | python | {
"resource": ""
} |
q245458 | authenticate_user | train | def authenticate_user(token):
"""
Add the content curation Authorizatino `token` header to `config.SESSION`.
"""
config.SESSION.headers.update({"Authorization": "Token {0}".format(token)})
try:
response = config.SESSION.post(config.authentication_url())
| python | {
"resource": ""
} |
q245459 | residue_distances | train | def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model):
"""Distance between the last atom of 2 | python | {
"resource": ""
} |
q245460 | resname_in_proximity | train | def resname_in_proximity(resname, model, chains, resnums, threshold=5):
"""Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython... | python | {
"resource": ""
} |
q245461 | match_structure_sequence | train | def match_structure_sequence(orig_seq, new_seq, match='X', fill_with='X', ignore_excess=False):
"""Correct a sequence to match inserted X's in a structure sequence
This is useful for mapping a sequence obtained from structural tools like MSMS or DSSP
to the sequence obtained by the get_structure_seqs m... | python | {
"resource": ""
} |
q245462 | manual_get_pfam_annotations | train | def manual_get_pfam_annotations(seq, outpath, searchtype='phmmer', force_rerun=False):
"""Retrieve and download PFAM results from the HMMER search tool.
Args:
seq:
outpath:
searchtype:
force_rerun:
Returns:
Todo:
* Document and test!
"""
if op.exists(o... | python | {
"resource": ""
} |
q245463 | is_ipynb | train | def is_ipynb():
"""Return True if the module is running in IPython kernel,
False if in IPython shell or other Python shell.
Copied from: http://stackoverflow.com/a/37661854/1592810
There are other methods there too
>>> is_ipynb()
False
| python | {
"resource": ""
} |
q245464 | clean_single_dict | train | def clean_single_dict(indict, prepend_to_keys=None, remove_keys_containing=None):
"""Clean a dict with values that contain single item iterators to single items
Args:
indict (dict): Dictionary to be cleaned
prepend_to_keys (str): String to prepend to all keys
remove_keys_containing (str... | python | {
"resource": ""
} |
q245465 | double_check_attribute | train | def double_check_attribute(object, setter, backup_attribute, custom_error_text=None):
"""Check if a parameter to be used is None, if it is, then check the specified backup attribute and throw
an error if it is also None.
Args:
object: The original object
setter: Any input object
bac... | python | {
"resource": ""
} |
q245466 | split_folder_and_path | train | def split_folder_and_path(filepath):
"""Split a file path into its folder, filename, and extension
Args:
path (str): Path to a file
Returns:
tuple: of (folder, filename (without extension), extension)
"""
dirname = op.dirname(filepath)
| python | {
"resource": ""
} |
q245467 | outfile_maker | train | def outfile_maker(inname, outext='.out', outname='', outdir='', append_to_name=''):
"""Create a default name for an output file based on the inname name, unless a output name is specified.
Args:
inname: Path to input file
outext: Optional specified extension for output file (with the "."). Defa... | python | {
"resource": ""
} |
q245468 | force_rerun | train | def force_rerun(flag, outfile):
"""Check if we should force rerunning of a command if an output file exists.
Args:
flag (bool): Flag to force rerun.
outfile (str): Path to output file which may already exist.
Returns:
bool: If we should force rerunning of a command
Examples:
... | python | {
"resource": ""
} |
q245469 | gunzip_file | train | def gunzip_file(infile, outfile=None, outdir=None, delete_original=False, force_rerun_flag=False):
"""Decompress a gzip file and optionally set output values.
Args:
infile: Path to .gz file
outfile: Name of output file
outdir: Path to output directory
delete_original: If origina... | python | {
"resource": ""
} |
q245470 | request_file | train | def request_file(link, outfile, force_rerun_flag=False):
"""Download a file given a URL if the outfile does not exist already.
Args:
link (str): Link to download file.
outfile (str): Path to output file, will make a new file if it does not exist. Will not download if it does
exist, ... | python | {
"resource": ""
} |
q245471 | request_json | train | def request_json(link, outfile, force_rerun_flag, outdir=None):
"""Download a file in JSON format from a web request
Args:
link: Link to web request
outfile: Name of output file
outdir: Directory of output file
force_rerun_flag: If true, redownload the file
Returns:
... | python | {
"resource": ""
} |
q245472 | command_runner | train | def command_runner(shell_command, force_rerun_flag, outfile_checker, cwd=None, silent=False):
"""Run a shell command with subprocess, with additional options to check if output file exists and printing stdout.
Args:
shell_command (str): Command as it would be formatted in the command-line (ie. "program... | python | {
"resource": ""
} |
q245473 | dict_head | train | def dict_head(d, N=5):
"""Return the head of a dictionary. It will be random!
Default is to return the first 5 key/value pairs in a dictionary.
Args:
d: Dictionary to get head.
N: Number of elements to display.
| python | {
"resource": ""
} |
q245474 | rank_dated_files | train | def rank_dated_files(pattern, dir, descending=True):
"""Search a directory for files that match a pattern. Return an ordered list of these files by filename.
Args:
pattern: The glob pattern to search for.
dir: Path to directory where the files will be searched for.
descending: Default T... | python | {
"resource": ""
} |
q245475 | find | train | def find(lst, a, case_sensitive=True):
"""Return indices of a list which have elements that match an object or list of objects
Args:
lst: list of values
a: object(s) to check equality
case_sensitive: if the search should be case sensitive
Returns:
list: list of indicies of ... | python | {
"resource": ""
} |
q245476 | filter_list | train | def filter_list(lst, takeout, case_sensitive=True):
"""Return a modified list removing items specified.
Args:
lst: Original list of values
takeout: Object or objects to remove from lst
case_sensitive: if the search should be case sensitive
Returns:
list: Filtered list of va... | python | {
"resource": ""
} |
q245477 | filter_list_by_indices | train | def filter_list_by_indices(lst, indices):
"""Return a modified list containing only the indices indicated.
Args:
lst: Original list of values
indices: List of indices to keep from | python | {
"resource": ""
} |
q245478 | force_string | train | def force_string(val=None):
"""Force a string representation of an object
Args:
val: object to parse into a string
Returns:
str: String representation
"""
if val is None:
return ''
if isinstance(val, list):
| python | {
"resource": ""
} |
q245479 | force_list | train | def force_list(val=None):
"""Force a list representation of an object
Args:
val: object to parse into a list
Returns:
"""
if val is None:
return []
if | python | {
"resource": ""
} |
q245480 | split_list_by_n | train | def split_list_by_n(l, n):
"""Split a list into lists of size n.
Args:
l: List of stuff.
n: Size of new lists.
Returns:
| python | {
"resource": ""
} |
q245481 | input_list_parser | train | def input_list_parser(infile_list):
"""Always return a list of files with varying input.
>>> input_list_parser(['/path/to/folder/'])
['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt']
>>> input_list_parser(['/path/to/file.txt'])
['/path/to/file.txt']
>>> i... | python | {
"resource": ""
} |
q245482 | flatlist_dropdup | train | def flatlist_dropdup(list_of_lists):
"""Make a single list out of a list of lists, and drop all duplicates.
Args:
| python | {
"resource": ""
} |
q245483 | scale_calculator | train | def scale_calculator(multiplier, elements, rescale=None):
"""Get a dictionary of scales for each element in elements.
Examples:
>>> scale_calculator(1, [2,7,8])
{8: 1, 2: 1, 7: 1}
>>> scale_calculator(1, [2,2,2,3,4,5,5,6,7,8])
{2: 3, 3: 1, 4: 1, 5: 2, 6: 1, 7: 1, 8: 1}
... | python | {
"resource": ""
} |
q245484 | label_sequential_regions | train | def label_sequential_regions(inlist):
"""Input a list of labeled tuples and return a dictionary of sequentially labeled regions.
Args:
inlist (list): A list of tuples with the first number representing the index and the second the index label.
Returns:
dict: Dictionary of labeled regions.
... | python | {
"resource": ""
} |
q245485 | SeqProp.sequence_path | train | def sequence_path(self, fasta_path):
"""Provide pointers to the paths of the FASTA file
Args:
fasta_path: Path to FASTA file
"""
if not fasta_path:
self.sequence_dir = None
self.sequence_file = None
else:
if not op.exists(fasta_p... | python | {
"resource": ""
} |
q245486 | SeqProp.feature_path | train | def feature_path(self, gff_path):
"""Load a GFF file with information on a single sequence and store features in the ``features`` attribute
Args:
gff_path: Path to GFF file.
"""
if not gff_path:
self.feature_dir = None
self.feature_file = None
... | python | {
"resource": ""
} |
q245487 | SeqProp.feature_path_unset | train | def feature_path_unset(self):
"""Copy features to memory and remove the association of the feature file."""
if not self.feature_file:
raise IOError('No feature file to unset')
with open(self.feature_path) as handle:
feats = list(GFF.parse(handle))
if len(feat... | python | {
"resource": ""
} |
q245488 | SeqProp.get_dict | train | def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False):
"""Get a dictionary of this object's attributes. Optional format for storage in a Pandas DataFrame.
Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all are returned.
... | python | {
"resource": ""
} |
q245489 | SeqProp.equal_to | train | def equal_to(self, seq_prop):
"""Test if the sequence is equal to another SeqProp's sequence
Args:
seq_prop: SeqProp object
Returns:
bool: If the sequences are the same
| python | {
"resource": ""
} |
q245490 | SeqProp.write_fasta_file | train | def write_fasta_file(self, outfile, force_rerun=False):
"""Write a FASTA file for the protein sequence, ``seq`` will now load directly from this file.
Args:
outfile (str): Path to new FASTA file to be written to
force_rerun (bool): If an existing file should be overwritten
... | python | {
"resource": ""
} |
q245491 | SeqProp.write_gff_file | train | def write_gff_file(self, outfile, force_rerun=False):
"""Write a GFF file for the protein features, ``features`` will now load directly from this file.
Args:
outfile (str): Path to new FASTA file to be written to
force_rerun (bool): If an existing file should be overwritten
... | python | {
"resource": ""
} |
q245492 | SeqProp.add_point_feature | train | def add_point_feature(self, resnum, feat_type=None, feat_id=None, qualifiers=None):
"""Add a feature to the features list describing a single residue.
Args:
resnum (int): Protein sequence residue number
feat_type (str, optional): Optional description of the feature type (ie. 'ca... | python | {
"resource": ""
} |
q245493 | SeqProp.add_region_feature | train | def add_region_feature(self, start_resnum, end_resnum, feat_type=None, feat_id=None, qualifiers=None):
"""Add a feature to the features list describing a region of the protein sequence.
Args:
start_resnum (int): Start residue number of the protein sequence feature
end_resnum (in... | python | {
"resource": ""
} |
q245494 | SeqProp.get_subsequence | train | def get_subsequence(self, resnums, new_id=None, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a list of residue numbers"""
# XTODO: documentation
biop_compound_list = []
for resnum in resnums:
# XTODO can be sped up by separating into range... | python | {
"resource": ""
} |
q245495 | SeqProp.get_subsequence_from_property | train | def get_subsequence_from_property(self, property_key, property_value, condition,
return_resnums=False, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a certain property you want to find in the
original SeqProp's letter_annotation
... | python | {
"resource": ""
} |
q245496 | SeqProp.get_biopython_pepstats | train | def get_biopython_pepstats(self, clean_seq=False):
"""Run Biopython's built in ProteinAnalysis module and store statistics in the ``annotations`` attribute."""
if self.seq:
if clean_seq: # TODO: can make this a property of the SeqProp class
seq = self.seq_str.replace('X', '... | python | {
"resource": ""
} |
q245497 | SeqProp.get_emboss_pepstats | train | def get_emboss_pepstats(self):
"""Run the EMBOSS pepstats program on the protein sequence.
Stores statistics in the ``annotations`` attribute.
Saves a ``.pepstats`` file of the results where the sequence file is located.
"""
if not self.sequence_file:
raise IOError('... | python | {
"resource": ""
} |
q245498 | SeqProp.get_sliding_window_properties | train | def get_sliding_window_properties(self, scale, window):
"""Run a property calculator given a sliding window size
Stores statistics in the ``letter_annotations`` attribute.
Todo:
- Add and document all scales available to set
"""
# XTODO: documentation
if sel... | python | {
"resource": ""
} |
q245499 | SeqProp.blast_pdb | train | def blast_pdb(self, seq_ident_cutoff=0, evalue=0.0001, display_link=False,
outdir=None, force_rerun=False):
"""BLAST this sequence to the PDB"""
if not outdir:
outdir = self.sequence_dir
if not outdir:
raise ValueError('Output directory must be s... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.