_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q36600 | ApiServiceSetupInfo.add_role_type_info | train | def add_role_type_info(self, role_type, config):
"""
Add a role type setup info.
@param role_type: Role type
@param config: A dictionary of role type configuration
"""
rt_config = config_to_api_list(config)
rt_config['roleType'] = role_type
if self.config is None:
self.config = {... | python | {
"resource": ""
} |
q36601 | ApiServiceSetupInfo.add_role_info | train | def add_role_info(self, role_name, role_type, host_id, config=None):
"""
Add a role info. The role will be created along with the service setup.
@param role_name: Role name
@param role_type: Role type
@param host_id: The host where the role should run
@param config: (Optional) A dictionary of r... | python | {
"resource": ""
} |
q36602 | create_host | train | def create_host(resource_root, host_id, name, ipaddr, rack_id=None):
"""
Create a host
@param resource_root: The root Resource object.
@param host_id: Host id
@param name: Host name
@param ipaddr: IP address
@param rack_id: Rack id. Default None
@return: An ApiHost object
"""
apihost = ApiHost(resou... | python | {
"resource": ""
} |
q36603 | get_all_hosts | train | def get_all_hosts(resource_root, view=None):
"""
Get all hosts
@param resource_root: The root Resource object.
@return: A list of ApiHost objects.
"""
return call(resource_root.get, HOSTS_PATH, ApiHost, True,
params=view and dict(view=view) or None) | python | {
"resource": ""
} |
q36604 | ApiHost.enter_maintenance_mode | train | def enter_maintenance_mode(self):
"""
Put the host in maintenance mode.
@return: Reference to the completed command.
@since: API v2
"""
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(get_host(self._get_resource_root(), self.hostId))
return cmd | python | {
"resource": ""
} |
q36605 | ApiHost.migrate_roles | train | def migrate_roles(self, role_names_to_migrate, destination_host_id,
clear_stale_role_data):
"""
Migrate roles from this host to a different host.
Currently, this command applies only to HDFS NameNode, JournalNode,
and Failover Controller roles. In order to migrate these roles:
- HDFS High ... | python | {
"resource": ""
} |
q36606 | get_host_map | train | def get_host_map(root):
''' Gets a mapping between CM hostId and Nagios host information
The key is the CM hostId
The value is an object containing the Nagios hostname and host address
'''
hosts_map = {}
for host in root.get_all_hosts():
hosts_map[host.hostId] = {"hostname": NAGIOS_HOSTNAME_FOR... | python | {
"resource": ""
} |
q36607 | get_services | train | def get_services(root, hosts_map, view=None):
''' Gets a list of objects representing the Nagios services.
Each object contains the Nagios hostname, service name, service display
name, and service health summary.
'''
services_list = []
mgmt_service = root.get_cloudera_manager().get_service()
serv... | python | {
"resource": ""
} |
q36608 | submit_status_external_cmd | train | def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file ... | python | {
"resource": ""
} |
q36609 | Resource.invoke | train | def invoke(self, method, relpath=None, params=None, data=None, headers=None):
"""
Invoke an API method.
@return: Raw body or JSON dictionary (if response content type is JSON).
"""
path = self._join_uri(relpath)
resp = self._client.execute(method,
path,
... | python | {
"resource": ""
} |
q36610 | create_host_template | train | def create_host_template(resource_root, name, cluster_name):
"""
Create a host template.
@param resource_root: The root Resource object.
@param name: Host template name
@param cluster_name: Cluster name
@return: An ApiHostTemplate object for the created host template.
@since: API v3
"""
apitemplate = ... | python | {
"resource": ""
} |
q36611 | get_host_template | train | def get_host_template(resource_root, name, cluster_name):
"""
Lookup a host template by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@return: An ApiHostTemplate object.
@since: API v3
"""
return call(... | python | {
"resource": ""
} |
q36612 | get_all_host_templates | train | def get_all_host_templates(resource_root, cluster_name="default"):
"""
Get all host templates in a cluster.
@param cluster_name: Cluster name.
@return: ApiList of ApiHostTemplate objects for all host templates in a cluster.
@since: API v3
"""
return call(resource_root.get,
HOST_TEMPLATES_PATH % (clu... | python | {
"resource": ""
} |
q36613 | delete_host_template | train | def delete_host_template(resource_root, name, cluster_name):
"""
Delete a host template identified by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@return: The deleted ApiHostTemplate object.
@since: API ... | python | {
"resource": ""
} |
q36614 | update_host_template | train | def update_host_template(resource_root, name, cluster_name, api_host_template):
"""
Update a host template identified by name in the specified cluster.
@param resource_root: The root Resource object.
@param name: Host template name.
@param cluster_name: Cluster name.
@param api_host_template: The updated ho... | python | {
"resource": ""
} |
q36615 | ApiHostTemplate.rename | train | def rename(self, new_name):
"""
Rename a host template.
@param new_name: New host template name.
@return: An ApiHostTemplate object.
"""
update = copy.copy(self)
update.name = new_name
return self._do_update(update) | python | {
"resource": ""
} |
q36616 | ApiHostTemplate.set_role_config_groups | train | def set_role_config_groups(self, role_config_group_refs):
"""
Updates the role config groups in a host template.
@param role_config_group_refs: List of role config group refs.
@return: An ApiHostTemplate object.
"""
update = copy.copy(self)
update.roleConfigGroupRefs = role_config_group_refs... | python | {
"resource": ""
} |
q36617 | list_supported_categories | train | def list_supported_categories():
"""
Prints a list of supported external account category names.
For example, "AWS" is a supported external account category name.
"""
categories = get_supported_categories(api)
category_names = [category.name for category in categories]
print ("Supported account categories... | python | {
"resource": ""
} |
q36618 | list_supported_types | train | def list_supported_types(category_name):
"""
Prints a list of supported external account type names for the given
category_name. For example, "AWS_ACCESS_KEY_AUTH" is a supported external
account type name for external account category "AWS".
"""
types = get_supported_types(api, category_name)
type_names ... | python | {
"resource": ""
} |
q36619 | list_credentials_by_name | train | def list_credentials_by_name(type_name):
"""
Prints a list of available credential names for the given type_name.
"""
accounts = get_all_external_accounts(api, type_name)
account_names = [account.name for account in accounts]
print ("List of credential names for '{0}': [{1}]".format(
type_name, COMMA_WI... | python | {
"resource": ""
} |
q36620 | call_s3guard_prune | train | def call_s3guard_prune(credential_name):
"""
Runs S3Guard prune command on external account associated with the
given credential_name.
""" # Get the AWS credential account associated with the credential
account = get_external_account(api, credential_name)
# Invoke the prune command for the account by its n... | python | {
"resource": ""
} |
q36621 | initialize_api | train | def initialize_api(args):
"""
Initializes the global API instance using the given arguments.
@param args: arguments provided to the script.
"""
global api
api = ApiResource(server_host=args.hostname, server_port=args.port,
username=args.username, password=args.password,
... | python | {
"resource": ""
} |
q36622 | validate_api_compatibility | train | def validate_api_compatibility(args):
"""
Validates the API version.
@param args: arguments provided to the script.
"""
if args.api_version and args.api_version < MINIMUM_SUPPORTED_API_VERSION:
print("ERROR: Given API version: {0}. Minimum supported API version: {1}"
.format(args.api_version, MI... | python | {
"resource": ""
} |
q36623 | get_login_credentials | train | def get_login_credentials(args):
"""
Gets the login credentials from the user, if not specified while invoking
the script.
@param args: arguments provided to the script.
"""
if not args.username:
args.username = raw_input("Enter Username: ")
if not args.password:
args.password = getpass.ge... | python | {
"resource": ""
} |
q36624 | main | train | def main():
"""
The "main" entry that controls the flow of the script based
on the provided arguments.
"""
setup_logging(logging.INFO)
# Parse arguments
parser = argparse.ArgumentParser(
description="A utility to interact with AWS using Cloudera Manager.")
parser.add_argument('-H', '--hostname', ac... | python | {
"resource": ""
} |
q36625 | get_root_resource | train | def get_root_resource(server_host, server_port=None,
username="admin", password="admin",
use_tls=False, version=API_CURRENT_VERSION):
"""
See ApiResource.
"""
return ApiResource(server_host, server_port, username, password, use_tls,
version) | python | {
"resource": ""
} |
q36626 | ApiResource.create_cluster | train | def create_cluster(self, name, version=None, fullVersion=None):
"""
Create a new cluster.
@param name: Cluster name.
@param version: Cluster major CDH version, e.g. 'CDH5'. Ignored if
fullVersion is specified.
@param fullVersion: Complete CDH version, e.g. '5.1.2'. Overrides major
versi... | python | {
"resource": ""
} |
q36627 | ApiResource.create_host | train | def create_host(self, host_id, name, ipaddr, rack_id = None):
"""
Create a host.
@param host_id: The host id.
@param name: Host name
@param ipaddr: IP address
@param rack_id: Rack id. Default None.
@return: An ApiHost object
"""
return hosts.create_host(self, host_id, name, ... | python | {
"resource": ""
} |
q36628 | ApiResource.get_metrics | train | def get_metrics(self, path, from_time, to_time, metrics, view, params=None):
"""
Generic function for querying metrics.
@param from_time: A datetime; start of the period to query (optional).
@param to_time: A datetime; end of the period to query (default = now).
@param metrics: List of metrics to q... | python | {
"resource": ""
} |
q36629 | ApiResource.query_timeseries | train | def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
"""
Query time series.
@param query: Query string.
@param from_time: Start of the period to query (optional).
@param to_time: End of the period to query (default = now).
@return: A list of ApiTimeSeriesResponse.
... | python | {
"resource": ""
} |
q36630 | echo | train | def echo(root_resource, message):
"""Have the server echo our message back."""
params = dict(message=message)
return root_resource.get(ECHO_PATH, params) | python | {
"resource": ""
} |
q36631 | echo_error | train | def echo_error(root_resource, message):
"""Generate an error, but we get to set the error message."""
params = dict(message=message)
return root_resource.get(ECHO_ERROR_PATH, params) | python | {
"resource": ""
} |
q36632 | ClouderaShell.service_action | train | def service_action(self, service, action):
"Perform given action on service for the selected cluster"
try:
service = api.get_cluster(self.cluster).get_service(service)
except ApiException:
print("Service not found")
return None
if action == "start":
... | python | {
"resource": ""
} |
q36633 | ClouderaShell.cluster_autocomplete | train | def cluster_autocomplete(self, text, line, start_index, end_index):
"autocomplete for the use command, obtain list of clusters first"
if not self.CACHED_CLUSTERS:
clusters = [cluster.name for cluster in api.get_all_clusters()]
self.CACHED_CLUSTERS = clusters
if text:
... | python | {
"resource": ""
} |
q36634 | ClouderaShell.roles_autocomplete | train | def roles_autocomplete(self, text, line, start_index, end_index):
"Return full list of roles"
if '-' not in line:
# Append a dash to each service, makes for faster autocompletion of
# roles
return [s + '-' for s in self.services_autocomplete(text, line, start_index, e... | python | {
"resource": ""
} |
q36635 | query_events | train | def query_events(resource_root, query_str=None):
"""
Search for events.
@param query_str: Query string.
@return: A list of ApiEvent.
"""
params = None
if query_str:
params = dict(query=query_str)
return call(resource_root.get, EVENTS_PATH, ApiEventQueryResult,
params=params) | python | {
"resource": ""
} |
q36636 | configure | train | def configure(config=None, bind_in_runtime=True):
"""Create an injector with a callable config or raise an exception when already configured."""
global _INJECTOR
with _INJECTOR_LOCK:
if _INJECTOR:
raise InjectorException('Injector is already configured')
_INJECTOR = Injector(co... | python | {
"resource": ""
} |
q36637 | configure_once | train | def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with _INJECTOR_LOCK:
if _INJECTOR:
return _INJECTOR
return configure(config, bind_in_runtime=bind_in_runtime) | python | {
"resource": ""
} |
q36638 | clear_and_configure | train | def clear_and_configure(config=None, bind_in_runtime=True):
"""Clear an existing injector and create another one with a callable config."""
with _INJECTOR_LOCK:
clear()
return configure(config, bind_in_runtime=bind_in_runtime) | python | {
"resource": ""
} |
q36639 | autoparams | train | def autoparams(*selected_args):
"""Return a decorator that will inject args into a function using type annotations, Python >= 3.5 only.
For example::
@inject.autoparams()
def refresh_cache(cache: RedisCache, db: DbInterface):
pass
There is an option to specify which arguments ... | python | {
"resource": ""
} |
q36640 | Binder.bind | train | def bind(self, cls, instance):
"""Bind a class to an instance."""
self._check_class(cls)
self._bindings[cls] = lambda: instance
logger.debug('Bound %s to an instance %s', cls, instance)
return self | python | {
"resource": ""
} |
q36641 | Binder.bind_to_constructor | train | def bind_to_constructor(self, cls, constructor):
"""Bind a class to a callable singleton constructor."""
self._check_class(cls)
if constructor is None:
raise InjectorException('Constructor cannot be None, key=%s' % cls)
self._bindings[cls] = _ConstructorBinding(constructor)
... | python | {
"resource": ""
} |
q36642 | Binder.bind_to_provider | train | def bind_to_provider(self, cls, provider):
"""Bind a class to a callable instance provider executed for each injection."""
self._check_class(cls)
if provider is None:
raise InjectorException('Provider cannot be None, key=%s' % cls)
self._bindings[cls] = provider
logg... | python | {
"resource": ""
} |
q36643 | Injector.get_instance | train | def get_instance(self, cls):
"""Return an instance for a class."""
binding = self._bindings.get(cls)
if binding:
return binding()
# Try to create a runtime binding.
with _BINDING_LOCK:
binding = self._bindings.get(cls)
if binding:
... | python | {
"resource": ""
} |
q36644 | read_csv | train | def read_csv(
filename: Union[PathLike, Iterator[str]],
delimiter: Optional[str]=',',
first_column_names: Optional[bool]=None,
dtype: str='float32',
) -> AnnData:
"""Read ``.csv`` file.
Same as :func:`~anndata.read_text` but with default delimiter ``','``.
Parameters
----------
fil... | python | {
"resource": ""
} |
q36645 | read_umi_tools | train | def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData:
"""Read a gzipped condensed count matrix from umi_tools.
Parameters
----------
filename
File name to read from.
"""
# import pandas for conversion of a dict of dicts into a matrix
# import gzip to read a gzippe... | python | {
"resource": ""
} |
q36646 | read_loom | train | def read_loom(filename: PathLike, sparse: bool = True, cleanup: bool = False, X_name: str = 'spliced',
obs_names: str = 'CellID', var_names: str = 'Gene', dtype: str='float32', **kwargs) -> AnnData:
"""Read ``.loom``-formatted hdf5 file.
This reads the whole file into memory.
Beware that you... | python | {
"resource": ""
} |
q36647 | read_mtx | train | def read_mtx(filename: PathLike, dtype: str='float32') -> AnnData:
"""Read ``.mtx`` file.
Parameters
----------
filename
The filename.
dtype
Numpy data type.
"""
from scipy.io import mmread
# could be rewritten accounting for dtype to be more performant
X = mmread(fs... | python | {
"resource": ""
} |
q36648 | iter_lines | train | def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]:
""" Helper for iterating only nonempty lines without line breaks"""
for line in file_like:
line = line.rstrip('\r\n')
if line:
yield line | python | {
"resource": ""
} |
q36649 | read_zarr | train | def read_zarr(store):
"""Read from a hierarchical Zarr array store.
Parameters
----------
store
The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class.
"""
if isinstance(store, Path):
store = str(store)
import zarr
f = zarr.open(store, mode='r')
d =... | python | {
"resource": ""
} |
q36650 | read_h5ad | train | def read_h5ad(filename, backed: Optional[str] = None, chunk_size: int = 6000):
"""Read ``.h5ad``-formatted hdf5 file.
Parameters
----------
filename
File name of data file.
backed : {``None``, ``'r'``, ``'r+'``}
If ``'r'``, load :class:`~anndata.AnnData` in ``backed`` mode instead
... | python | {
"resource": ""
} |
q36651 | _read_args_from_h5ad | train | def _read_args_from_h5ad(
adata: AnnData = None,
filename: Optional[PathLike] = None,
mode: Optional[str] = None,
chunk_size: int = 6000
):
"""Return a tuple with the parameters for initializing AnnData.
Parameters
----------
filename
Defaults to the objects filename if ``None``... | python | {
"resource": ""
} |
q36652 | make_index_unique | train | def make_index_unique(index: pd.Index, join: str = '-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.An... | python | {
"resource": ""
} |
q36653 | _find_corresponding_multicol_key | train | def _find_corresponding_multicol_key(key, keys_multicol):
"""Find the corresponding multicolumn key."""
for mk in keys_multicol:
if key.startswith(mk) and 'of' in key:
return mk
return None | python | {
"resource": ""
} |
q36654 | _gen_keys_from_multicol_key | train | def _gen_keys_from_multicol_key(key_multicol, n_keys):
"""Generates single-column keys from multicolumn key."""
keys = [('{}{:03}of{:03}')
.format(key_multicol, i+1, n_keys) for i in range(n_keys)]
return keys | python | {
"resource": ""
} |
q36655 | _check_2d_shape | train | def _check_2d_shape(X):
"""Check shape of array or sparse matrix.
Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.
"""
if X.dtype.names is None and len(X.shape) != 2:
raise ValueError('X needs to be 2-dimensional, not '
'{}-dimensional.'.format(le... | python | {
"resource": ""
} |
q36656 | BoundRecArr.to_df | train | def to_df(self) -> pd.DataFrame:
"""Convert to pandas dataframe."""
df = pd.DataFrame(index=RangeIndex(0, self.shape[0], name=None))
for key in self.keys():
value = self[key]
for icolumn, column in enumerate(value.T):
df['{}{}'.format(key, icolumn+1)] = co... | python | {
"resource": ""
} |
q36657 | AnnDataFileManager.isopen | train | def isopen(self) -> bool:
"""State of backing file."""
if self._file is None:
return False
# try accessing the id attribute to see if the file is open
return bool(self._file.id) | python | {
"resource": ""
} |
q36658 | AnnData.transpose | train | def transpose(self) -> 'AnnData':
"""Transpose whole object.
Data matrix is transposed, observations and variables are interchanged.
"""
if not self.isbacked: X = self._X
else: X = self.file['X']
if self.isview:
raise ValueError(
'You\'re tryi... | python | {
"resource": ""
} |
q36659 | AnnData.copy | train | def copy(self, filename: Optional[PathLike] = None) -> 'AnnData':
"""Full copy, optionally on disk."""
if not self.isbacked:
return AnnData(self._X.copy() if self._X is not None else None,
self._obs.copy(),
self._var.copy(),
... | python | {
"resource": ""
} |
q36660 | AnnData.write_h5ad | train | def write_h5ad(
self,
filename: Optional[PathLike] = None,
compression: Optional[str] = None,
compression_opts: Union[int, Any] = None,
force_dense: Optional[bool] = None
):
"""Write ``.h5ad``-formatted hdf5 file.
.. note::
Setting compression to... | python | {
"resource": ""
} |
q36661 | AnnData.write_csvs | train | def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','):
"""Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
---... | python | {
"resource": ""
} |
q36662 | AnnData.write_loom | train | def write_loom(self, filename: PathLike, write_obsm_varm: bool = False):
"""Write ``.loom``-formatted hdf5 file.
Parameters
----------
filename
The filename.
"""
from .readwrite.write import write_loom
write_loom(filename, self, write_obsm_varm = writ... | python | {
"resource": ""
} |
q36663 | AnnData.write_zarr | train | def write_zarr(
self,
store: Union[MutableMapping, PathLike],
chunks: Union[bool, int, Tuple[int, ...]],
):
"""Write a hierarchical Zarr array store.
Parameters
----------
store
The filename, a :class:`~typing.MutableMapping`, or a Zarr storage cl... | python | {
"resource": ""
} |
q36664 | AnnData._to_dict_fixed_width_arrays | train | def _to_dict_fixed_width_arrays(self, var_len_str=True):
"""A dict of arrays that stores data and annotation.
It is sufficient for reconstructing the object.
"""
self.strings_to_categoricals()
obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str)
var_rec, ... | python | {
"resource": ""
} |
q36665 | Parser._expose_rule_functions | train | def _expose_rule_functions(self, expose_all_rules=False):
"""add parse functions for public grammar rules
Defines a function for each public grammar rule, based on
introspecting the grammar. For example, the `c_interval` rule
is exposed as a method `parse_c_interval` and used like this:... | python | {
"resource": ""
} |
q36666 | format_sequence | train | def format_sequence(seq, start=None, end=None, group_size=3):
"""print seq from [start, end) in groups of size
3 6 9 12 15
| | | | |
2001 AAA BBB CCC DDD EEE
"""
width = 100
loc_width = 9
sep = " "
body_sep = " : "
start = start or 0
end = e... | python | {
"resource": ""
} |
q36667 | _stage_from_version | train | def _stage_from_version(version):
"""return "prd", "stg", or "dev" for the given version string. A value is always returned"""
if version:
m = re.match(r"^(?P<xyz>\d+\.\d+\.\d+)(?P<extra>.*)", version)
if m:
return "stg" if m.group("extra") else "prd"
return "dev" | python | {
"resource": ""
} |
q36668 | _get_ncbi_db_url | train | def _get_ncbi_db_url():
"""returns NCBI DB URL based on environment variables and code version
* if NCBI_DB_URL is set, use that
* Otherwise, if _NCBI_URL_KEY is set, use that as the name of a
config file entry and use the corresponding URL
* Otherwise,
"""
if "NCBI_DB_URL" in os.enviro... | python | {
"resource": ""
} |
q36669 | NCBI_postgresql._get_cursor | train | def _get_cursor(self, n_retries=1):
"""Returns a context manager for obtained from a single or pooled
connection, and sets the PostgreSQL search_path to the schema
specified in the connection URL.
Although *connections* are threadsafe, *cursors* are bound to
connections and are ... | python | {
"resource": ""
} |
q36670 | Projector.project_interval_forward | train | def project_interval_forward(self, c_interval):
"""
project c_interval on the source transcript to the
destination transcript
:param c_interval: an :class:`hgvs.interval.Interval` object on the source transcript
:returns: c_interval: an :class:`hgvs.interval.Interval` object on ... | python | {
"resource": ""
} |
q36671 | Projector.project_interval_backward | train | def project_interval_backward(self, c_interval):
"""
project c_interval on the destination transcript to the
source transcript
:param c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript
:returns: c_interval: an :class:`hgvs.interval.Interval` obje... | python | {
"resource": ""
} |
q36672 | VariantMapper._convert_edit_check_strand | train | def _convert_edit_check_strand(strand, edit_in):
"""
Convert an edit from one type to another, based on the stand and type
"""
if isinstance(edit_in, hgvs.edit.NARefAlt):
if strand == 1:
edit_out = copy.deepcopy(edit_in)
else:
try:
... | python | {
"resource": ""
} |
q36673 | AssemblyMapper.t_to_p | train | def t_to_p(self, var_t):
"""Return a protein variant, or "non-coding" for non-coding variant types
CAUTION: Unlike other x_to_y methods that always return
SequenceVariant instances, this method returns a string when
the variant type is ``n``. This is intended as a convenience,
... | python | {
"resource": ""
} |
q36674 | AssemblyMapper._fetch_AlignmentMapper | train | def _fetch_AlignmentMapper(self, tx_ac, alt_ac=None, alt_aln_method=None):
"""convenience version of VariantMapper._fetch_AlignmentMapper that
derives alt_ac from transcript, assembly, and alt_aln_method
used to instantiate the AssemblyMapper instance
"""
if alt_ac is None:
... | python | {
"resource": ""
} |
q36675 | AssemblyMapper._maybe_normalize | train | def _maybe_normalize(self, var):
"""normalize variant if requested, and ignore HGVSUnsupportedOperationError
This is better than checking whether the variant is intronic because
future UTAs will support LRG, which will enable checking intronic variants.
"""
if self.normalize:
... | python | {
"resource": ""
} |
q36676 | AlignmentMapper._parse_cigar | train | def _parse_cigar(self, cigar):
"""For a given CIGAR string, return the start positions of
each aligned segment in ref and tgt, and a list of CIGAR operators.
"""
ces = [m.groupdict() for m in cigar_re.finditer(cigar)]
ref_pos = [None] * len(ces)
tgt_pos = [None] * len(ces... | python | {
"resource": ""
} |
q36677 | AlignmentMapper._map | train | def _map(self, from_pos, to_pos, pos, base):
"""Map position between aligned sequences
Positions in this function are 0-based.
"""
pos_i = -1
while pos_i < len(self.cigar_op) and pos >= from_pos[pos_i + 1]:
pos_i += 1
if pos_i == -1 or pos_i == len(self.ciga... | python | {
"resource": ""
} |
q36678 | build_tx_cigar | train | def build_tx_cigar(exons, strand):
"""builds a single CIGAR string representing an alignment of the
transcript sequence to a reference sequence, including introns.
The input exons are expected to be in transcript order, and the
resulting CIGAR is also in transcript order.
>>> build_tx_cigar([], 1)... | python | {
"resource": ""
} |
q36679 | AltSeqToHgvsp._check_if_ins_is_dup | train | def _check_if_ins_is_dup(self, start, insertion):
"""Helper to identify an insertion as a duplicate
:param start: 1-based insertion start
:type start: int
:param insertion: sequence
:type insertion: str
:return (is duplicate, variant start)
:rtype (bool, int)
... | python | {
"resource": ""
} |
q36680 | AltSeqToHgvsp._create_variant | train | def _create_variant(self,
start,
end,
ref,
alt,
fsext_len=None,
is_dup=False,
acc=None,
is_ambiguous=False,
... | python | {
"resource": ""
} |
q36681 | connect | train | def connect(db_url=None,
pooling=hgvs.global_config.uta.pooling,
application_name=None,
mode=None,
cache=None):
"""Connect to a UTA database instance and return a UTA interface instance.
:param db_url: URL for database connection
:type db_url: string
:par... | python | {
"resource": ""
} |
q36682 | UTABase.get_tx_for_region | train | def get_tx_for_region(self, alt_ac, alt_aln_method, start_i, end_i):
"""
return transcripts that overlap given region
:param str alt_ac: reference sequence (e.g., NC_000007.13)
:param str alt_aln_method: alignment method (e.g., splign)
:param int start_i: 5' bound of region
... | python | {
"resource": ""
} |
q36683 | UTABase.get_tx_identity_info | train | def get_tx_identity_info(self, tx_ac):
"""returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
al... | python | {
"resource": ""
} |
q36684 | UTABase.get_similar_transcripts | train | def get_similar_transcripts(self, tx_ac):
"""Return a list of transcripts that are similar to the given
transcript, with relevant similarity criteria.
>> sim_tx = hdp.get_similar_transcripts('NM_001285829.1')
>> dict(sim_tx[0])
{ 'cds_eq': False,
'cds_es_fp_eq': False,
... | python | {
"resource": ""
} |
q36685 | _make_key | train | def _make_key(func,
args,
kwds,
typed,
kwd_mark=(object(), ),
fasttypes={int, str, frozenset, type(None)},
sorted=sorted,
tuple=tuple,
type=type,
len=len):
'Make a cache key from optionally ... | python | {
"resource": ""
} |
q36686 | Normalizer._get_boundary | train | def _get_boundary(self, var):
"""Get the position of exon-intron boundary for current variant
"""
if var.type == "r" or var.type == "n":
if self.cross_boundaries:
return 0, float("inf")
else:
# Get genomic sequence access number for this tr... | python | {
"resource": ""
} |
q36687 | Normalizer._get_tgt_length | train | def _get_tgt_length(self, var):
"""Get the total length of the whole reference sequence
"""
if var.type == "g" or var.type == "m":
return float("inf")
else:
# Get genomic sequence access number for this transcript
identity_info = self.hdp.get_tx_identi... | python | {
"resource": ""
} |
q36688 | Normalizer._fetch_bounded_seq | train | def _fetch_bounded_seq(self, var, start, end, window_size, boundary):
"""Fetch reference sequence from hgvs data provider.
The start position is 0 and the interval is half open
"""
var_len = end - start - window_size
start = start if start >= boundary[0] else boundary[0]
... | python | {
"resource": ""
} |
q36689 | Normalizer._get_ref_alt | train | def _get_ref_alt(self, var, boundary):
"""Get reference allele and alternative allele of the variant
"""
# Get reference allele
if var.posedit.edit.type == "ins" or var.posedit.edit.type == "dup":
ref = ""
else:
# For NARefAlt and Inv
if var.p... | python | {
"resource": ""
} |
q36690 | trim_common_suffixes | train | def trim_common_suffixes(strs, min_len=0):
"""
trim common suffixes
>>> trim_common_suffixes('A', 1)
(0, 'A')
"""
if len(strs) < 2:
return 0, strs
rev_strs = [s[::-1] for s in strs]
trimmed, rev_strs = trim_common_prefixes(rev_strs, min_len)
if trimmed:
strs = [... | python | {
"resource": ""
} |
q36691 | trim_common_prefixes | train | def trim_common_prefixes(strs, min_len=0):
"""trim common prefixes"""
trimmed = 0
if len(strs) > 1:
s1 = min(strs)
s2 = max(strs)
for i in range(len(s1) - min_len):
if s1[i] != s2[i]:
break
trimmed = i + 1
if trimmed > 0:
strs =... | python | {
"resource": ""
} |
q36692 | normalize_alleles_left | train | def normalize_alleles_left(ref, start, stop, alleles, bound, ref_step, shuffle=True):
"""
Normalize loci by removing extraneous reference padding
>>> normalize_alleles_left('A', 1, 2, 'A', 1, 2)
shuffled_alleles(start=1, stop=2, alleles='A')
"""
normalized_alleles = namedtuple('shuffled_allel... | python | {
"resource": ""
} |
q36693 | validate_type_ac_pair | train | def validate_type_ac_pair(type, ac):
"""validate that accession is correct for variant type AND that
accession is fully specified.
"""
assert type in valid_pairs, "Unknown variant type " + type
if valid_pairs[type].match(ac):
return (ValidationLevel.VALID,
"Accession ({ac})... | python | {
"resource": ""
} |
q36694 | AltSeqBuilder.build_altseq | train | def build_altseq(self):
"""given a variant and a sequence, incorporate the variant and return the new sequence
Data structure returned is analogous to the data structure used to return the variant sequence,
but with an additional parameter denoting the start of a frameshift that should affect a... | python | {
"resource": ""
} |
q36695 | AltSeqBuilder._incorporate_dup | train | def _incorporate_dup(self):
"""Incorporate dup into sequence"""
seq, cds_start, cds_stop, start, end = self._setup_incorporate()
dup_seq = seq[start:end]
seq[end:end] = dup_seq
is_frameshift = len(dup_seq) % 3 != 0
variant_start_aa = int(math.ceil((self._var_c.posedit.p... | python | {
"resource": ""
} |
q36696 | AltSeqBuilder._incorporate_inv | train | def _incorporate_inv(self):
"""Incorporate inv into sequence"""
seq, cds_start, cds_stop, start, end = self._setup_incorporate()
seq[start:end] = list(reverse_complement(''.join(seq[start:end])))
is_frameshift = False
variant_start_aa = max(int(math.ceil((self._var_c.posedit.po... | python | {
"resource": ""
} |
q36697 | AltSeqBuilder._create_no_protein | train | def _create_no_protein(self):
"""Create a no-protein result"""
alt_data = AltTranscriptData([],
None,
None,
False,
None,
... | python | {
"resource": ""
} |
q36698 | S3PreparedRequest.prepare_headers | train | def prepare_headers(self, headers, metadata, queue_derive=True):
"""Convert a dictionary of metadata into S3 compatible HTTP
headers, and append headers to ``headers``.
:type metadata: dict
:param metadata: Metadata to be converted into S3 HTTP Headers
and appen... | python | {
"resource": ""
} |
q36699 | load_ia_module | train | def load_ia_module(cmd):
"""Dynamically import ia module."""
try:
if cmd in list(cmd_aliases.keys()) + list(cmd_aliases.values()):
_module = 'internetarchive.cli.ia_{0}'.format(cmd)
return __import__(_module, fromlist=['internetarchive.cli'])
else:
_module = '... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.