_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q228700 | run | train | def run(module_name, args=None, env_vars=None, wait=True, capture_error=False):
# type: (str, list, dict, bool, bool) -> subprocess.Popen
"""Run Python module as a script.
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you mus... | python | {
"resource": ""
} |
q228701 | run_module | train | def run_module(uri, args, env_vars=None, name=DEFAULT_MODULE_NAME, cache=None, wait=True, capture_error=False):
# type: (str, list, dict, str, bool, bool, bool) -> subprocess.Popen
"""Download, prepare and executes a compressed tar file from S3 or provided directory as a module.
SageMaker Python SDK saves ... | python | {
"resource": ""
} |
q228702 | Request.content_type | train | def content_type(self): # type: () -> str
"""The request's content-type.
Returns:
(str): The value, if any, of the header 'ContentType' (used by some AWS services) and 'Content-Type'.
Otherwise, returns 'application/json' as default.
"""
# todo(mvsusp): ... | python | {
"resource": ""
} |
q228703 | Request.accept | train | def accept(self): # type: () -> str
"""The content-type for the response to the client.
Returns:
(str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT
environment variable.
"""
accept = self.headers.get('Accept... | python | {
"resource": ""
} |
q228704 | Request.content | train | def content(self): # type: () -> object
"""The request incoming data.
It automatic decodes from utf-8
Returns:
(obj): incoming data
"""
as_text = self.content_type in _content_types.UTF8_TYPES
return self.get_data(as_text=as_text) | python | {
"resource": ""
} |
q228705 | run | train | def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
"""Download, prepa... | python | {
"resource": ""
} |
q228706 | configure_logger | train | def configure_logger(level, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'):
# type: (int, str) -> None
"""Set logger configuration.
Args:
level (int): Logger level
format (str): Logger format
"""
logging.basicConfig(format=format, level=level)
if level >= logging... | python | {
"resource": ""
} |
q228707 | _timestamp | train | def _timestamp():
"""Return a timestamp with microsecond precision."""
moment = time.time()
moment_us = repr(moment).split('.')[1]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment)) | python | {
"resource": ""
} |
q228708 | split_by_criteria | train | def split_by_criteria(dictionary, keys=None, prefix=None): # type: (dict, set or list or tuple) -> SplitResultSpec
"""Split a dictionary in two by the provided keys.
Args:
dictionary (dict[str, object]): A Python dictionary
keys (sequence [str]): A sequence of keys which will be added the spli... | python | {
"resource": ""
} |
q228709 | default_output_fn | train | def default_output_fn(prediction, accept):
"""Function responsible to serialize the prediction for the response.
Args:
prediction (obj): prediction returned by predict_fn .
accept (str): accept content-type expected by the client.
Returns:
(worker.Response): a Flask response object... | python | {
"resource": ""
} |
q228710 | Transformer.transform | train | def transform(self): # type: () -> _worker.Response
"""Take a request with input data, deserialize it, make a prediction, and return a
serialized response.
Returns:
sagemaker_containers.beta.framework.worker.Response: a Flask response object with
the following args:... | python | {
"resource": ""
} |
q228711 | Transformer._default_transform_fn | train | def _default_transform_fn(self, model, content, content_type, accept):
"""Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Args:
model (obj)... | python | {
"resource": ""
} |
q228712 | training_env | train | def training_env(): # type: () -> _env.TrainingEnv
"""Create a TrainingEnv.
Returns:
TrainingEnv: an instance of TrainingEnv
"""
from sagemaker_containers import _env
return _env.TrainingEnv(
resource_config=_env.read_resource_config(),
input_data_config=_env.read_input_d... | python | {
"resource": ""
} |
q228713 | _write_json | train | def _write_json(obj, path): # type: (object, str) -> None
"""Writes a serializeable object as a JSON file"""
with open(path, 'w') as f:
json.dump(obj, f) | python | {
"resource": ""
} |
q228714 | _create_training_directories | train | def _create_training_directories():
"""Creates the directory structure and files necessary for training under the base path
"""
logger.info('Creating a new training folder under %s .' % base_dir)
os.makedirs(model_dir)
os.makedirs(input_config_dir)
os.makedirs(output_data_dir)
_write_json(... | python | {
"resource": ""
} |
q228715 | num_gpus | train | def num_gpus(): # type: () -> int
"""The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container.
"""
try:
cmd = shlex.split('nvidia-smi --list-gpus')
output = subprocess.check_output(cmd).decode('utf-8')
return... | python | {
"resource": ""
} |
q228716 | write_env_vars | train | def write_env_vars(env_vars=None): # type: (dict) -> None
"""Write the dictionary env_vars in the system, as environment variables.
Args:
env_vars ():
Returns:
"""
env_vars = env_vars or {}
env_vars['PYTHONPATH'] = ':'.join(sys.path)
for name, value in env_vars.items():
... | python | {
"resource": ""
} |
q228717 | TrainingEnv.to_env_vars | train | def to_env_vars(self):
"""Environment variable representation of the training environment
Returns:
dict: an instance of dictionary
"""
env = {
'hosts': self.hosts, 'network_interface_name': self.network_interface_name,
'hps': self.hyperparameters, 'u... | python | {
"resource": ""
} |
q228718 | array_to_npy | train | def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object
"""Convert an array like object to the NPY format.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
... | python | {
"resource": ""
} |
q228719 | npy_to_numpy | train | def npy_to_numpy(npy_array): # type: (object) -> np.array
"""Convert an NPY array into numpy.
Args:
npy_array (npy array): to be converted to numpy array
Returns:
(np.array): converted numpy array.
"""
stream = BytesIO(npy_array)
return np.load(stream, allow_pickle=True) | python | {
"resource": ""
} |
q228720 | array_to_json | train | def array_to_json(array_like): # type: (np.array or Iterable or int or float) -> str
"""Convert an array like object to JSON.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
... | python | {
"resource": ""
} |
q228721 | json_to_numpy | train | def json_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a JSON object to a numpy array.
Args:
string_like (str): JSON string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | python | {
"resource": ""
} |
q228722 | csv_to_numpy | train | def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | python | {
"resource": ""
} |
q228723 | array_to_csv | train | def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str
"""Convert an array like object to CSV.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
... | python | {
"resource": ""
} |
q228724 | decode | train | def decode(obj, content_type):
# type: (np.array or Iterable or int or float, str) -> np.array
"""Decode an object ton a one of the default content types to a numpy array.
Args:
obj (object): to be decoded.
content_type (str): content type to be used.
Returns:
np.array: decoded... | python | {
"resource": ""
} |
q228725 | encode | train | def encode(array_like, content_type):
# type: (np.array or Iterable or int or float, str) -> np.array
"""Encode an array like object in a specific content_type to a numpy array.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-... | python | {
"resource": ""
} |
q228726 | tmpdir | train | def tmpdir(suffix='', prefix='tmp', dir=None): # type: (str, str, str) -> None
"""Create a temporary directory with a context manager. The file is deleted when the context exits.
The prefix, suffix, and dir arguments are the same as for mkstemp().
Args:
suffix (str): If suffix is specified, the ... | python | {
"resource": ""
} |
q228727 | download_and_extract | train | def download_and_extract(uri, name, path): # type: (str, str, str) -> None
"""Download, prepare and install a compressed tar file from S3 or local directory as an entry point.
SageMaker Python SDK saves the user provided entry points as compressed tar files in S3
Args:
name (str): name of the ent... | python | {
"resource": ""
} |
q228728 | s3_download | train | def s3_download(url, dst): # type: (str, str) -> None
"""Download a file from S3.
Args:
url (str): the s3 url of the file.
dst (str): the destination where the file will be saved.
"""
url = parse.urlparse(url)
if url.scheme != 's3':
raise ValueError("Expecting 's3' scheme,... | python | {
"resource": ""
} |
q228729 | matching_args | train | def matching_args(fn, dictionary): # type: (Callable, _mapping.Mapping) -> dict
"""Given a function fn and a dict dictionary, returns the function arguments that match the dict keys.
Example:
def train(channel_dirs, model_dir): pass
dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/mod... | python | {
"resource": ""
} |
q228730 | error_wrapper | train | def error_wrapper(fn, error_class): # type: (Callable or None, Exception) -> ...
"""Wraps function fn in a try catch block that re-raises error_class.
Args:
fn (function): function to wrapped
error_class (Exception): Error class to be re-raised
Returns:
(object): fn wrapped in a t... | python | {
"resource": ""
} |
q228731 | ceph_is_installed | train | def ceph_is_installed(module):
"""
A helper callback to be executed after the connection is made to ensure
that Ceph is installed.
"""
ceph_package = Ceph(module.conn)
if not ceph_package.installed:
host = module.conn.hostname
raise RuntimeError(
'ceph needs to be ins... | python | {
"resource": ""
} |
q228732 | color_format | train | def color_format():
"""
Main entry point to get a colored formatter, it will use the
BASE_FORMAT by default and fall back to no colors if the system
does not support it
"""
str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT
color_format = color_message(str_format)
return... | python | {
"resource": ""
} |
q228733 | mon_status_check | train | def mon_status_check(conn, logger, hostname, args):
"""
A direct check for JSON output on the monitor status.
For newer versions of Ceph (dumpling and newer) a new mon_status command
was added ( `ceph daemon mon mon_status` ) and should be revisited if the
output changes as this check depends on th... | python | {
"resource": ""
} |
q228734 | catch_mon_errors | train | def catch_mon_errors(conn, logger, hostname, cfg, args):
"""
Make sure we are able to catch up common mishaps with monitors
and use that state of a monitor to determine what is missing
and warn apropriately about it.
"""
monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {})
... | python | {
"resource": ""
} |
q228735 | mon_status | train | def mon_status(conn, logger, hostname, args, silent=False):
"""
run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide
not only the output, but be able to return a boolean status of what is
going on.
``False`` represents a monitor that is not doing OK even if it is up and
ru... | python | {
"resource": ""
} |
q228736 | hostname_is_compatible | train | def hostname_is_compatible(conn, logger, provided_hostname):
"""
Make sure that the host that we are connecting to has the same value as the
`hostname` in the remote host, otherwise mons can fail not reaching quorum.
"""
logger.debug('determining if provided host has same hostname in remote')
re... | python | {
"resource": ""
} |
q228737 | make | train | def make(parser):
"""
Ceph MON Daemon management
"""
parser.formatter_class = ToggleRawTextHelpFormatter
mon_parser = parser.add_subparsers(dest='subcommand')
mon_parser.required = True
mon_add = mon_parser.add_parser(
'add',
help=('R|Add a monitor to an existing cluster:\n... | python | {
"resource": ""
} |
q228738 | get_mon_initial_members | train | def get_mon_initial_members(args, error_on_empty=False, _cfg=None):
"""
Read the Ceph config file and return the value of mon_initial_members
Optionally, a NeedHostError can be raised if the value is None.
"""
if _cfg:
cfg = _cfg
else:
cfg = conf.ceph.load(args)
mon_initial_m... | python | {
"resource": ""
} |
q228739 | is_running | train | def is_running(conn, args):
"""
Run a command to check the status of a mon, return a boolean.
We heavily depend on the format of the output, if that ever changes
we need to modify this.
Check daemon status for 3 times
output of the status should be similar to::
mon.mira094: running {"v... | python | {
"resource": ""
} |
q228740 | executable_path | train | def executable_path(conn, executable):
"""
Remote validator that accepts a connection object to ensure that a certain
executable is available returning its full path if so.
Otherwise an exception with thorough details will be raised, informing the
user that the executable was not found.
"""
... | python | {
"resource": ""
} |
q228741 | is_systemd_service_enabled | train | def is_systemd_service_enabled(conn, service='ceph'):
"""
Detects if a systemd service is enabled or not.
"""
_, _, returncode = remoto.process.check(
conn,
[
'systemctl',
'is-enabled',
'--quiet',
'{service}'.format(service=service),
... | python | {
"resource": ""
} |
q228742 | make | train | def make(parser):
"""
Repo definition management
"""
parser.add_argument(
'repo_name',
metavar='REPO-NAME',
help='Name of repo to manage. Can match an entry in cephdeploy.conf'
)
parser.add_argument(
'--repo-url',
help='a repo URL that mirrors/contains ... | python | {
"resource": ""
} |
q228743 | Conf.get_list | train | def get_list(self, section, key):
"""
Assumes that the value for a given key is going to be a list
separated by commas. It gets rid of trailing comments.
If just one item is present it returns a list with a single item, if no
key is found an empty list is returned.
"""
... | python | {
"resource": ""
} |
q228744 | Conf.get_default_repo | train | def get_default_repo(self):
"""
Go through all the repositories defined in the config file and search
for a truthy value for the ``default`` key. If there isn't any return
None.
"""
for repo in self.get_repos():
if self.get_safe(repo, 'default') and self.getbo... | python | {
"resource": ""
} |
q228745 | validate_host_ip | train | def validate_host_ip(ips, subnets):
"""
Make sure that a given host all subnets specified will have at least one IP
in that range.
"""
# Make sure we prune ``None`` arguments
subnets = [s for s in subnets if s is not None]
validate_one_subnet = len(subnets) == 1
def ip_in_one_subnet(ips... | python | {
"resource": ""
} |
q228746 | get_public_network_ip | train | def get_public_network_ip(ips, public_subnet):
"""
Given a public subnet, chose the one IP from the remote host that exists
within the subnet range.
"""
for ip in ips:
if net.ip_in_subnet(ip, public_subnet):
return ip
msg = "IPs (%s) are not valid for any of subnet specified ... | python | {
"resource": ""
} |
q228747 | make | train | def make(parser):
"""
Start deploying a new cluster, and write a CLUSTER.conf and keyring for it.
"""
parser.add_argument(
'mon',
metavar='MON',
nargs='+',
help='initial monitor hostname, fqdn, or hostname:fqdn pair',
type=arg_validators.Hostname(),
)
... | python | {
"resource": ""
} |
q228748 | make | train | def make(parser):
"""
Ceph MDS daemon management
"""
mds_parser = parser.add_subparsers(dest='subcommand')
mds_parser.required = True
mds_create = mds_parser.add_parser(
'create',
help='Deploy Ceph MDS on remote host(s)'
)
mds_create.add_argument(
'mds',
... | python | {
"resource": ""
} |
q228749 | install_yum_priorities | train | def install_yum_priorities(distro, _yum=None):
"""
EPEL started packaging Ceph so we need to make sure that the ceph.repo we
install has a higher priority than the EPEL repo so that when installing
Ceph it will come from the repo file we create.
The name of the package changed back and forth (!) si... | python | {
"resource": ""
} |
q228750 | make_exception_message | train | def make_exception_message(exc):
"""
An exception is passed in and this function
returns the proper string depending on the result
so it is readable enough.
"""
if str(exc):
return '%s: %s\n' % (exc.__class__.__name__, exc)
else:
return '%s\n' % (exc.__class__.__name__) | python | {
"resource": ""
} |
q228751 | platform_information | train | def platform_information(_linux_distribution=None):
""" detect platform information from remote host """
linux_distribution = _linux_distribution or platform.linux_distribution
distro, release, codename = linux_distribution()
if not distro:
distro, release, codename = parse_os_release()
if n... | python | {
"resource": ""
} |
q228752 | write_keyring | train | def write_keyring(path, key, uid=-1, gid=-1):
""" create a keyring file """
# Note that we *require* to avoid deletion of the temp file
# otherwise we risk not being able to copy the contents from
# one file system to the other, hence the `delete=False`
tmp_file = tempfile.NamedTemporaryFile('wb', d... | python | {
"resource": ""
} |
q228753 | create_mon_path | train | def create_mon_path(path, uid=-1, gid=-1):
"""create the mon path if it does not exist"""
if not os.path.exists(path):
os.makedirs(path)
os.chown(path, uid, gid); | python | {
"resource": ""
} |
q228754 | create_done_path | train | def create_done_path(done_path, uid=-1, gid=-1):
"""create a done file to avoid re-doing the mon deployment"""
with open(done_path, 'wb'):
pass
os.chown(done_path, uid, gid); | python | {
"resource": ""
} |
q228755 | create_init_path | train | def create_init_path(init_path, uid=-1, gid=-1):
"""create the init path if it does not exist"""
if not os.path.exists(init_path):
with open(init_path, 'wb'):
pass
os.chown(init_path, uid, gid); | python | {
"resource": ""
} |
q228756 | write_monitor_keyring | train | def write_monitor_keyring(keyring, monitor_keyring, uid=-1, gid=-1):
"""create the monitor keyring file"""
write_file(keyring, monitor_keyring, 0o600, None, uid, gid) | python | {
"resource": ""
} |
q228757 | which | train | def which(executable):
"""find the location of an executable"""
locations = (
'/usr/local/bin',
'/bin',
'/usr/bin',
'/usr/local/sbin',
'/usr/sbin',
'/sbin',
)
for location in locations:
executable_path = os.path.join(location, executable)
... | python | {
"resource": ""
} |
q228758 | make_mon_removed_dir | train | def make_mon_removed_dir(path, file_name):
""" move old monitor data """
try:
os.makedirs('/var/lib/ceph/mon-removed')
except OSError as e:
if e.errno != errno.EEXIST:
raise
shutil.move(path, os.path.join('/var/lib/ceph/mon-removed/', file_name)) | python | {
"resource": ""
} |
q228759 | safe_mkdir | train | def safe_mkdir(path, uid=-1, gid=-1):
""" create path if it doesn't exist """
try:
os.mkdir(path)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.chown(path, uid, gid) | python | {
"resource": ""
} |
q228760 | safe_makedirs | train | def safe_makedirs(path, uid=-1, gid=-1):
""" create path recursively if it doesn't exist """
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.chown(path, uid, gid) | python | {
"resource": ""
} |
q228761 | zeroing | train | def zeroing(dev):
""" zeroing last few blocks of device """
# this kills the crab
#
# sgdisk will wipe out the main copy of the GPT partition
# table (sorry), but it doesn't remove the backup copies, and
# subsequent commands will continue to complain and fail when
# they see those. zeroing... | python | {
"resource": ""
} |
q228762 | enable_yum_priority_obsoletes | train | def enable_yum_priority_obsoletes(path="/etc/yum/pluginconf.d/priorities.conf"):
"""Configure Yum priorities to include obsoletes"""
config = configparser.ConfigParser()
config.read(path)
config.set('main', 'check_obsoletes', '1')
with open(path, 'w') as fout:
config.write(fout) | python | {
"resource": ""
} |
q228763 | vendorize | train | def vendorize(vendor_requirements):
"""
This is the main entry point for vendorizing requirements. It expects
a list of tuples that should contain the name of the library and the
version.
For example, a library ``foo`` with version ``0.0.1`` would look like::
vendor_requirements = [
... | python | {
"resource": ""
} |
q228764 | _keyring_equivalent | train | def _keyring_equivalent(keyring_one, keyring_two):
"""
Check two keyrings are identical
"""
def keyring_extract_key(file_path):
"""
Cephx keyring files may or may not have white space before some lines.
They may have some values in quotes, so a safe way to compare is to
e... | python | {
"resource": ""
} |
q228765 | keytype_path_to | train | def keytype_path_to(args, keytype):
"""
Get the local filename for a keyring type
"""
if keytype == "admin":
return '{cluster}.client.admin.keyring'.format(
cluster=args.cluster)
if keytype == "mon":
return '{cluster}.mon.keyring'.format(
cluster=args.cluster)... | python | {
"resource": ""
} |
q228766 | gatherkeys_missing | train | def gatherkeys_missing(args, distro, rlogger, keypath, keytype, dest_dir):
"""
Get or create the keyring from the mon using the mon keyring by keytype and
copy to dest_dir
"""
args_prefix = [
'/usr/bin/ceph',
'--connect-timeout=25',
'--cluster={cluster}'.format(
c... | python | {
"resource": ""
} |
q228767 | gatherkeys_with_mon | train | def gatherkeys_with_mon(args, host, dest_dir):
"""
Connect to mon and gather keys if mon is in quorum.
"""
distro = hosts.get(host, username=args.username)
remote_hostname = distro.conn.remote_module.shortname()
dir_keytype_mon = ceph_deploy.util.paths.mon.path(args.cluster, remote_hostname)
... | python | {
"resource": ""
} |
q228768 | gatherkeys | train | def gatherkeys(args):
"""
Gather keys from any mon and store in current working directory.
Backs up keys from previous installs and stores new keys.
"""
oldmask = os.umask(0o77)
try:
try:
tmpd = tempfile.mkdtemp()
LOG.info("Storing keys in temp directory %s", tmp... | python | {
"resource": ""
} |
q228769 | make | train | def make(parser):
"""
Gather authentication keys for provisioning new nodes.
"""
parser.add_argument(
'mon',
metavar='HOST',
nargs='+',
help='monitor host to pull keys from',
)
parser.set_defaults(
func=gatherkeys,
) | python | {
"resource": ""
} |
q228770 | get | train | def get(hostname,
username=None,
fallback=None,
detect_sudo=True,
use_rhceph=False,
callbacks=None):
"""
Retrieve the module that matches the distribution of a ``hostname``. This
function will connect to that host and retrieve the distribution
information, then re... | python | {
"resource": ""
} |
q228771 | get_connection | train | def get_connection(hostname, username, logger, threads=5, use_sudo=None, detect_sudo=True):
"""
A very simple helper, meant to return a connection
that will know about the need to use sudo.
"""
if username:
hostname = "%s@%s" % (username, hostname)
try:
conn = remoto.Connection(
... | python | {
"resource": ""
} |
q228772 | get_local_connection | train | def get_local_connection(logger, use_sudo=False):
"""
Helper for local connections that are sometimes needed to operate
on local hosts
"""
return get_connection(
socket.gethostname(), # cannot rely on 'localhost' here
None,
logger=logger,
threads=1,
use_sudo=... | python | {
"resource": ""
} |
q228773 | make | train | def make(parser):
"""
Ceph MGR daemon management
"""
mgr_parser = parser.add_subparsers(dest='subcommand')
mgr_parser.required = True
mgr_create = mgr_parser.add_parser(
'create',
help='Deploy Ceph MGR on remote host(s)'
)
mgr_create.add_argument(
'mgr',
... | python | {
"resource": ""
} |
q228774 | make | train | def make(parser):
"""
Manage packages on remote hosts.
"""
action = parser.add_mutually_exclusive_group()
action.add_argument(
'--install',
metavar='PKG(s)',
help='Comma-separated package(s) to install',
)
action.add_argument(
'--remove',
metavar='P... | python | {
"resource": ""
} |
q228775 | get_bootstrap_osd_key | train | def get_bootstrap_osd_key(cluster):
"""
Read the bootstrap-osd key for `cluster`.
"""
path = '{cluster}.bootstrap-osd.keyring'.format(cluster=cluster)
try:
with open(path, 'rb') as f:
return f.read()
except IOError:
raise RuntimeError('bootstrap-osd keyring not found;... | python | {
"resource": ""
} |
q228776 | create_osd_keyring | train | def create_osd_keyring(conn, cluster, key):
"""
Run on osd node, writes the bootstrap key if not there yet.
"""
logger = conn.logger
path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format(
cluster=cluster,
)
if not conn.remote_module.path_exists(path):
logger.warning('... | python | {
"resource": ""
} |
q228777 | osd_tree | train | def osd_tree(conn, cluster):
"""
Check the status of an OSD. Make sure all are up and in
What good output would look like::
{
"epoch": 8,
"num_osds": 1,
"num_up_osds": 1,
"num_in_osds": "1",
"full": "false",
"nearfull": "false... | python | {
"resource": ""
} |
q228778 | catch_osd_errors | train | def catch_osd_errors(conn, logger, args):
"""
Look for possible issues when checking the status of an OSD and
report them back to the user.
"""
logger.info('checking OSD status...')
status = osd_status_check(conn, args.cluster)
osds = int(status.get('num_osds', 0))
up_osds = int(status.g... | python | {
"resource": ""
} |
q228779 | create_osd | train | def create_osd(
conn,
cluster,
data,
journal,
zap,
fs_type,
dmcrypt,
dmcrypt_dir,
storetype,
block_wal,
block_db,
**kw):
"""
Run on osd node, creates an OSD from a data disk.
"""
ceph_volume_executable = syst... | python | {
"resource": ""
} |
q228780 | make | train | def make(parser):
"""
Prepare a data disk on remote host.
"""
sub_command_help = dedent("""
Create OSDs from a data disk on a remote host:
ceph-deploy osd create {node} --data /path/to/device
For bluestore, optional devices can be used::
ceph-deploy osd create {node} --data /p... | python | {
"resource": ""
} |
q228781 | make_disk | train | def make_disk(parser):
"""
Manage disks on a remote host.
"""
disk_parser = parser.add_subparsers(dest='subcommand')
disk_parser.required = True
disk_zap = disk_parser.add_parser(
'zap',
help='destroy existing data and filesystem on LV or partition',
)
disk_zap.add_a... | python | {
"resource": ""
} |
q228782 | repository_url_part | train | def repository_url_part(distro):
"""
Historically everything CentOS, RHEL, and Scientific has been mapped to
`el6` urls, but as we are adding repositories for `rhel`, the URLs should
map correctly to, say, `rhel6` or `rhel7`.
This function looks into the `distro` object and determines the right url... | python | {
"resource": ""
} |
q228783 | sanitize_args | train | def sanitize_args(args):
"""
args may need a bunch of logic to set proper defaults that argparse is
not well suited for.
"""
if args.release is None:
args.release = 'nautilus'
args.default_release = True
# XXX This whole dance is because --stable is getting deprecated
if arg... | python | {
"resource": ""
} |
q228784 | should_use_custom_repo | train | def should_use_custom_repo(args, cd_conf, repo_url):
"""
A boolean to determine the logic needed to proceed with a custom repo
installation instead of cramming everything nect to the logic operator.
"""
if repo_url:
# repo_url signals a CLI override, return False immediately
return F... | python | {
"resource": ""
} |
q228785 | make_uninstall | train | def make_uninstall(parser):
"""
Remove Ceph packages from remote hosts.
"""
parser.add_argument(
'host',
metavar='HOST',
nargs='+',
help='hosts to uninstall Ceph from',
)
parser.set_defaults(
func=uninstall,
) | python | {
"resource": ""
} |
q228786 | make_purge | train | def make_purge(parser):
"""
Remove Ceph packages from remote hosts and purge all data.
"""
parser.add_argument(
'host',
metavar='HOST',
nargs='+',
help='hosts to purge Ceph from',
)
parser.set_defaults(
func=purge,
) | python | {
"resource": ""
} |
q228787 | make | train | def make(parser):
"""
Ceph RGW daemon management
"""
rgw_parser = parser.add_subparsers(dest='subcommand')
rgw_parser.required = True
rgw_create = rgw_parser.add_parser(
'create',
help='Create an RGW instance'
)
rgw_create.add_argument(
'rgw',
metavar=... | python | {
"resource": ""
} |
q228788 | can_connect_passwordless | train | def can_connect_passwordless(hostname):
"""
Ensure that current host can SSH remotely to the remote
host using the ``BatchMode`` option to prevent a password prompt.
That attempt will error with an exit status of 255 and a ``Permission
denied`` message or a``Host key verification failed`` message.
... | python | {
"resource": ""
} |
q228789 | ip_in_subnet | train | def ip_in_subnet(ip, subnet):
"""Does IP exists in a given subnet utility. Returns a boolean"""
ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16)
netstr, bits = subnet.split('/')
netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16)
mask = (0xffffffff << (32 - in... | python | {
"resource": ""
} |
q228790 | in_subnet | train | def in_subnet(cidr, addrs=None):
"""
Returns True if host is within specified subnet, otherwise False
"""
for address in addrs:
if ip_in_subnet(address, cidr):
return True
return False | python | {
"resource": ""
} |
q228791 | get_chacra_repo | train | def get_chacra_repo(shaman_url):
"""
From a Shaman URL, get the chacra url for a repository, read the
contents that point to the repo and return it as a string.
"""
shaman_response = get_request(shaman_url)
chacra_url = shaman_response.geturl()
chacra_response = get_request(chacra_url)
... | python | {
"resource": ""
} |
q228792 | map_components | train | def map_components(notsplit_packages, components):
"""
Returns a list of packages to install based on component names
This is done by checking if a component is in notsplit_packages,
if it is, we know we need to install 'ceph' instead of the
raw component name. Essentially, this component hasn't b... | python | {
"resource": ""
} |
q228793 | start_mon_service | train | def start_mon_service(distro, cluster, hostname):
"""
start mon service depending on distro init
"""
if distro.init == 'sysvinit':
service = distro.conn.remote_module.which_service()
remoto.process.run(
distro.conn,
[
service,
'ceph... | python | {
"resource": ""
} |
q228794 | VoronoiLayer.__voronoi_finite_polygons_2d | train | def __voronoi_finite_polygons_2d(vor, radius=None):
"""
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
Input diagram
radius : float, optional
Distance to 'points at infinity'.
... | python | {
"resource": ""
} |
q228795 | inline | train | def inline(width=900):
"""display the map inline in ipython
:param width: image width for the browser
"""
from IPython.display import Image, HTML, display, clear_output
import random
import string
import urllib
import os
while True:
fname = ''.join(random.choice(string.asci... | python | {
"resource": ""
} |
q228796 | dot | train | def dot(data, color=None, point_size=2, f_tooltip=None):
"""Create a dot density map
:param data: data access object
:param color: color
:param point_size: point size
:param f_tooltip: function to return a tooltip string for a point
"""
from geoplotlib.layers import DotDensityLayer
_glo... | python | {
"resource": ""
} |
q228797 | hist | train | def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False,
scalemin=0, scalemax=None, f_group=None, show_colorbar=True):
"""Create a 2D histogram
:param data: data access object
:param cmap: colormap name
:param alpha: color alpha
:param colorscale: scaling [l... | python | {
"resource": ""
} |
q228798 | shapefiles | train | def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'):
"""
Load and draws shapefiles
:param fname: full path to the shapefile
:param f_tooltip: function to generate a tooltip on mouseover
:param color: color
:param linewidth: line width
:param shape_type: either ... | python | {
"resource": ""
} |
q228799 | voronoi | train | def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220):
"""
Draw the voronoi tesselation of the points
:param data: data access object
:param line_color: line color
:param line_width: line width
:param f_tooltip: function to generate a tooltip on mo... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.