text stringlengths 81 112k |
|---|
Return the 0-based position of `item` in this IpRange.
>>> r = IpRange('127.0.0.1', '127.255.255.255')
>>> r.index('127.0.0.1')
0
>>> r.index('127.255.255.255')
16777214
>>> r.index('10.0.0.1')
Traceback (most recent call last):
...
ValueErro... |
Detach daemon process.
Forks the current process into a parent and a detached child. The
child process resides in its own process group, has no controlling
terminal attached and is cleaned up by the init process.
Returns ``True`` for the parent and ``False`` for the child.
def _detach_process():
... |
Block until a predicate becomes true.
``predicate`` is a function taking no arguments. The call to
``_block`` blocks until ``predicate`` returns a true value. This
is done by polling ``predicate``.
``timeout`` is either ``True`` (block indefinitely) or a timeout
in seconds.
The return value i... |
Return the PID of the process owning the lock.
Returns ``None`` if no lock is present.
def read_pid(self):
"""
Return the PID of the process owning the lock.
Returns ``None`` if no lock is present.
"""
try:
with open(self._path, 'r') as f:
s... |
Find the file handles used by our logger's handlers.
def _get_logger_file_handles(self):
"""
Find the file handles used by our logger's handlers.
"""
handles = []
for handler in self.logger.handlers:
# The following code works for logging's SysLogHandler,
... |
Check if the daemon is running.
def is_running(self):
"""
Check if the daemon is running.
"""
pid = self.get_pid()
if pid is None:
return False
# The PID file may still exist even if the daemon isn't running,
# for example if it has crashed.
t... |
Get the event for a signal.
Checks if the signal has been enabled and raises a
``ValueError`` if not.
def _get_signal_event(self, s):
'''
Get the event for a signal.
Checks if the signal has been enabled and raises a
``ValueError`` if not.
'''
try:
... |
Send a signal to the daemon process.
The signal must have been enabled using the ``signals``
parameter of :py:meth:`Service.__init__`. Otherwise, a
``ValueError`` is raised.
def send_signal(self, s):
"""
Send a signal to the daemon process.
The signal must have been en... |
Tell the daemon process to stop.
Sends the SIGTERM signal to the daemon process, requesting it
to terminate.
If ``block`` is true then the call blocks until the daemon
process has exited. This may take some time since the daemon
process will complete its on-going backup activit... |
Kill the daemon process.
Sends the SIGKILL signal to the daemon process, killing it. You
probably want to try :py:meth:`stop` first.
If ``block`` is true then the call blocks until the daemon
process has exited. ``block`` can either be ``True`` (in which
case it blocks indefini... |
Start the daemon process.
The daemon process is started in the background and the calling
process returns.
Once the daemon process is initialized it calls the
:py:meth:`run` method.
If ``block`` is true then the call blocks until the daemon
process has started. ``block... |
Create a new environment
Usage:
datacats create [-bin] [--interactive] [-s NAME] [--address=IP] [--syslog]
[--ckan=CKAN_VERSION] [--no-datapusher] [--site-url SITE_URL]
[--no-init-db] ENVIRONMENT_DIR [PORT]
Options:
--address=IP Address to listen on (Linux-only)
--... |
Resets a site to the default state. This will re-initialize the
database and recreate the administrator account.
Usage:
datacats reset [-iyn] [-s NAME] [ENVIRONMENT]
Options:
-i --interactive Don't detach from the web container
-s --site=NAME The site to reset [default: primary]
-y --yes ... |
Initialize a purged environment or copied environment directory
Usage:
datacats init [-in] [--syslog] [-s NAME] [--address=IP] [--interactive]
[--site-url SITE_URL] [ENVIRONMENT_DIR [PORT]] [--no-init-db]
Options:
--address=IP Address to listen on (Linux-only)
--interactive ... |
Common parts of create and init: Install, init db, start site, sysadmin
def finish_init(environment, start_web, create_sysadmin, log_syslog=False,
do_install=True, quiet=False, site_url=None, interactive=False,
init_db=True):
"""
Common parts of create and init: Install, init db... |
Save profile settings into user profile directory
def save(self):
"""
Save profile settings into user profile directory
"""
config = self.profiledir + '/config'
if not isdir(self.profiledir):
makedirs(self.profiledir)
cp = SafeConfigParser()
cp.add_... |
Generate a new ssh private and public key
def generate_ssh_key(self):
"""
Generate a new ssh private and public key
"""
web_command(
command=["ssh-keygen", "-q", "-t", "rsa", "-N", "", "-C",
"datacats generated {0}@{1}".format(
g... |
Sends "create project" command to the remote server
def create(self, environment, target_name):
"""
Sends "create project" command to the remote server
"""
remote_server_command(
["ssh", environment.deploy_target, "create", target_name],
environment, self,
... |
Return True if password was set successfully
def admin_password(self, environment, target_name, password):
"""
Return True if password was set successfully
"""
try:
remote_server_command(
["ssh", environment.deploy_target,
"admin_password"... |
Return True if deployment was successful
def deploy(self, environment, target_name, stream_output=None):
"""
Return True if deployment was successful
"""
try:
remote_server_command(
[
"rsync", "-lrv", "--safe-links", "--munge-links",
... |
Compute the number of mini-batches required to cover a data set of
size `n` using batches of size `batch_size`.
Parameters
----------
n: int
the number of samples in the data set
batch_size: int
the mini-batch size
Returns
-------
int: the number of batches required
de... |
Get the number of indices that would be generated by this
sampler.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown.
def num_indices_generated(self):
... |
Create an iterator that generates in-order mini-batches of sample
indices. The batches will have `batch_size` elements, with the
exception of the final batch which will have less if there are not
enough samples left to fill it.
The generated mini-batches indices take the form of 1D NumP... |
Create an iterator that generates randomly shuffled mini-batches of
sample indices. The batches will have `batch_size` elements, with the
exception of the final batch which will have less if there are not
enough samples left to fill it.
The generated mini-batches indices take the form o... |
Create an iterator that generates randomly shuffled mini-batches of
sample indices. The batches will have `batch_size` elements.
The generated mini-batches indices take the form of 1D NumPy integer
arrays.
Parameters
----------
batch_size: int
Mini-batch siz... |
Compute sample weight given an array of sample classes. The weights
are assigned on a per-class basis and the per-class weights are
inversely proportional to their frequency.
Parameters
----------
y: NumPy array, 1D dtype=int
sample classes, values must be 0 or posit... |
Create an iterator that generates randomly shuffled mini-batches of
sample indices. The batches will have `batch_size` elements.
The generated mini-batches indices take the form of 1D NumPy integer
arrays.
Parameters
----------
batch_size: int
Mini-batch siz... |
Construct a `WeightedSubsetSampler` that compensates for class
imbalance.
Parameters
----------
y: NumPy array, 1D dtype=int
sample classes, values must be 0 or positive
indices: NumPy array, 1D dtype=int
An array of indices that identify the subset of sa... |
Wait up to timeout seconds for service at host:port
to start.
Returns True if service becomes available, False if the
container stops or raises ServiceTimeout if timeout is
reached.
def wait_for_service_available(container, url, timeout):
"""
Wait up to timeout seconds for service at host:port... |
Get the path of the given file within the batchup data directory
Parameters
----------
filename: str
The filename to locate within the batchup data directory
Returns
-------
str
The full path of the file
def get_data_path(filename):
"""
Get the path of the given file w... |
Download a file to a given path from a given URL, if it does not exist.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_url: str
The URL from which to download the file
Returns
-------
str
The path of the file
def d... |
Compute the SHA-256 hash of the file at the given path
Parameters
----------
path: str
The path of the file
Returns
-------
str
The SHA-256 HEX digest
def compute_sha256(path):
"""
Compute the SHA-256 hash of the file at the given path
Parameters
----------
... |
Verify the integrity of a file by checking its SHA-256 hash.
If no digest is supplied, the digest is printed to the console.
Closely follows the code in `torchvision.datasets.utils.check_integrity`
Parameters
----------
path: str
The path of the file to check
sha256: str
The ex... |
Download a file to a given path from a given URL, if it does not exist.
After downloading it, verify it integrity by checking the SHA-256 hash.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_url: str
The URL from which to download t... |
Copy a file to a given path from a given path, if it does not exist.
After copying it, verify it integrity by checking the SHA-256 hash.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_path: str
The path from which to copy the file
... |
Create ckanext-(name) in target directory.
def ckan_extension_template(name, target):
"""
Create ckanext-(name) in target directory.
"""
setupdir = '{0}/ckanext-{1}theme'.format(target, name)
extdir = setupdir + '/ckanext/{0}theme'.format(name)
templatedir = extdir + '/templates/'
staticdir... |
Run a command or interactive shell within this environment
Usage:
datacats [-d] [-s NAME] shell [ENVIRONMENT [COMMAND...]]
Options:
-d --detach Run the resulting container in the background
-s --site=NAME Specify a site to run the shell on [default: primary]
ENVIRONMENT may be an environment name or a ... |
Run a paster command from the current directory
Usage:
datacats paster [-d] [-s NAME] [COMMAND...]
Options:
-s --site=NAME Specify a site to run this paster command on [default: primary]
-d --detach Run the resulting container in the background
You must be inside a datacats environment to run this. The... |
Add a site's configuration to the source dir and site dir
def save_new_site(site_name, sitedir, srcdir, port, address, site_url,
passwords):
"""
Add a site's configuration to the source dir and site dir
"""
cp = ConfigParser.SafeConfigParser()
cp.read([srcdir + '/.datacats-environment'])
... |
Save an environment's configuration to the source dir and data dir
def save_new_environment(name, datadir, srcdir, ckan_version,
deploy_target=None, always_prod=False):
"""
Save an environment's configuration to the source dir and data dir
"""
with open(datadir + '/.version', 'w') as f:
... |
:param environment_name: exising environment name, path or None to
look in current or parent directories for project
returns (srcdir, extension_dir, datadir)
extension_dir is the name of extension directory user was in/referenced,
default: 'ckan'. This value is used by the paster cli command.
... |
Load configuration values for an environment
:param srcdir: environment source directory
:param datadir: environment data direcory, if None will be discovered
from srcdir
:param allow_old: Don't throw an exception if this is an old site
This is only valid for sites... |
Load configuration values for a site.
Returns (port, address, site_url, passwords)
def load_site(srcdir, datadir, site_name=None):
"""
Load configuration values for a site.
Returns (port, address, site_url, passwords)
"""
if site_name is None:
site_name = 'primary'
if not validate... |
Check if a new environment or site can be created at the given path.
Returns (name, datadir, sitedir, srcdir) or raises DatacatsError
def new_environment_check(srcpath, site_name, ckan_version):
"""
Check if a new environment or site can be created at the given path.
Returns (name, datadir, sitedir, ... |
Return True if the directories and containers we're expecting
are present in datadir, sitedir and containers
def data_complete(datadir, sitedir, get_container_name):
"""
Return True if the directories and containers we're expecting
are present in datadir, sitedir and containers
"""
if any(not p... |
Create expected directories in datadir, sitedir
and optionally srcdir
def create_directories(datadir, sitedir, srcdir=None):
"""
Create expected directories in datadir, sitedir
and optionally srcdir
"""
# It's possible that the datadir already exists
# (we're making a secondary site)
if... |
Populate venv from preloaded image
def create_virtualenv(srcdir, datadir, preload_image, get_container_name):
"""
Populate venv from preloaded image
"""
try:
if docker.is_boot2docker():
docker.data_only_container(
get_container_name('venv'),
['/usr/li... |
Copy ckan source, datapusher source (optional), who.ini and schema.xml
from preload image into srcdir
def create_source(srcdir, preload_image, datapusher=False):
"""
Copy ckan source, datapusher source (optional), who.ini and schema.xml
from preload image into srcdir
"""
try:
docker.web... |
Start all supporting containers (containers required for CKAN to
operate) if they aren't already running, along with some extra
containers specified by the user
def start_supporting_containers(sitedir, srcdir, passwords,
get_container_name, extra_containers, log_syslog=False):
"""
Start all sup... |
Stop postgres and solr containers, along with any specified extra containers
def stop_supporting_containers(get_container_name, extra_containers):
"""
Stop postgres and solr containers, along with any specified extra containers
"""
docker.remove_container(get_container_name('postgres'))
docker.remo... |
Return a list of containers tracked by this environment that are running
def containers_running(get_container_name):
"""
Return a list of containers tracked by this environment that are running
"""
running = []
for n in ['web', 'postgres', 'solr', 'datapusher', 'redis']:
info = docker.inspe... |
Gets the names of all of the sites from the datadir and stores them
in self.sites. Also returns this list.
def _load_sites(self):
"""
Gets the names of all of the sites from the datadir and stores them
in self.sites. Also returns this list.
"""
if not self.sites:
... |
Save environment settings in the directory that need to be saved
even when creating only a new sub-site env.
def save_site(self, create=True):
"""
Save environment settings in the directory that need to be saved
even when creating only a new sub-site env.
"""
self._load_... |
Save environment settings into environment directory, overwriting
any existing configuration and discarding site config
def save(self):
"""
Save environment settings into environment directory, overwriting
any existing configuration and discarding site config
"""
task.sa... |
Return a Environment object with settings for a new project.
No directories or containers are created by this call.
:params path: location for new project directory, may be relative
:params ckan_version: release of CKAN to install
:params site_name: The name of the site to install datab... |
Return an Environment object based on an existing environnment+site.
:param environment_name: exising environment name, path or None to
look in current or parent directories for project
:param data_only: set to True to only load from data dir, not
the project dir; Used for purgi... |
Return True if all the expected datadir files are present
def data_complete(self):
"""
Return True if all the expected datadir files are present
"""
return task.data_complete(self.datadir, self.sitedir,
self._get_container_name) |
raise a DatacatsError if the datadir or volumes are missing or damaged
def require_data(self):
"""
raise a DatacatsError if the datadir or volumes are missing or damaged
"""
files = task.source_missing(self.target)
if files:
raise DatacatsError('Missing files in sour... |
Call once for new projects to create the initial project directories.
def create_directories(self, create_project_dir=True):
"""
Call once for new projects to create the initial project directories.
"""
return task.create_directories(self.datadir, self.sitedir,
self.target i... |
Populate venv from preloaded image
def create_virtualenv(self):
"""
Populate venv from preloaded image
"""
return task.create_virtualenv(self.target, self.datadir,
self._preload_image(), self._get_container_name) |
Empty our virtualenv so that new (or older) dependencies may be
installed
def clean_virtualenv(self):
"""
Empty our virtualenv so that new (or older) dependencies may be
installed
"""
self.user_run_script(
script=scripts.get_script_path('clean_virtualenv.sh')... |
Populate ckan directory from preloaded image and copy
who.ini and schema.xml info conf directory
def create_source(self, datapusher=True):
"""
Populate ckan directory from preloaded image and copy
who.ini and schema.xml info conf directory
"""
task.create_source(self.tar... |
Start all supporting containers (containers required for CKAN to
operate) if they aren't already running.
:param log_syslog: A flag to redirect all container logs to host's syslog
def start_supporting_containers(self, log_syslog=False):
"""
Start all supporting containers (containe... |
Use make-config to generate an initial development.ini file
def create_ckan_ini(self):
"""
Use make-config to generate an initial development.ini file
"""
self.run_command(
command='/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config'
' ckan /project/dev... |
Use config-tool to update development.ini with our environment settings
:param skin: use environment template skin plugin True/False
def update_ckan_ini(self, skin=True):
"""
Use config-tool to update development.ini with our environment settings
:param skin: use environment template ... |
Create an example ckan extension for this environment and install it
def create_install_template_skin(self):
"""
Create an example ckan extension for this environment and install it
"""
ckan_extension_template(self.name, self.target)
self.install_package_develop('ckanext-' + sel... |
Run db init to create all ckan tables
:param retry_seconds: how long to retry waiting for db to start
def ckan_db_init(self, retry_seconds=DB_INIT_RETRY_SECONDS):
"""
Run db init to create all ckan tables
:param retry_seconds: how long to retry waiting for db to start
"""
... |
Start the apache server or paster serve
:param log_syslog: A flag to redirect all container logs to host's syslog
:param production: True for apache, False for paster serve + debug on
:param paster_reload: Instruct paster to watch for file changes
def start_ckan(self, production=False, log_sys... |
Create run/development.ini in datadir with debug and site_url overridden
and with correct db passwords inserted
def _create_run_ini(self, port, production, output='development.ini',
source='development.ini', override_site_url=True):
"""
Create run/development.ini in data... |
Start web container on port with command
def _run_web_container(self, port, command, address, log_syslog=False,
datapusher=True, interactive=False):
"""
Start web container on port with command
"""
if is_boot2docker():
ro = {}
volumes_f... |
Wait for the web server to become available or raise DatacatsError
if it fails to start.
def wait_for_web_available(self):
"""
Wait for the web server to become available or raise DatacatsError
if it fails to start.
"""
try:
if not wait_for_service_available(... |
Return a port number from 5000-5999 based on the environment name
to be used as a default when the user hasn't selected one.
def _choose_port(self):
"""
Return a port number from 5000-5999 based on the environment name
to be used as a default when the user hasn't selected one.
"... |
Return another port from the 5000-5999 range
def _next_port(self, port):
"""
Return another port from the 5000-5999 range
"""
port = 5000 + (port + 1) % 1000
if port == self.port:
raise DatacatsError('Too many instances running')
return port |
Stop and remove the web container
def stop_ckan(self):
"""
Stop and remove the web container
"""
remove_container(self._get_container_name('web'), force=True)
remove_container(self._get_container_name('datapusher'), force=True) |
return just the port number for the web container, or None if
not running
def _current_web_port(self):
"""
return just the port number for the web container, or None if
not running
"""
info = inspect_container(self._get_container_name('web'))
if info is None:
... |
Add a container as a 'extra'. These are running containers which are not necessary for
running default CKAN but are useful for certain extensions
:param container: The container name to add
:param error_on_exists: Raise a DatacatsError if the extra container already exists.
def add_extra_contai... |
Return the url of the web server or None if not running
def web_address(self):
"""
Return the url of the web server or None if not running
"""
port = self._current_web_port()
address = self.address or '127.0.0.1'
if port is None:
return None
return 'h... |
create 'admin' account with given password
def create_admin_set_password(self, password):
"""
create 'admin' account with given password
"""
with open(self.sitedir + '/run/admin.json', 'w') as out:
json.dump({
'name': 'admin',
'email': 'none',... |
launch interactive shell session with all writable volumes
:param: list of strings to execute instead of bash
def interactive_shell(self, command=None, paster=False, detach=False):
"""
launch interactive shell session with all writable volumes
:param: list of strings to execute instea... |
Install from requirements.txt file found in psrc
:param psrc: name of directory in environment directory
def install_package_requirements(self, psrc, stream_output=None):
"""
Install from requirements.txt file found in psrc
:param psrc: name of directory in environment directory
... |
Remove uploaded files, postgres db, solr index, venv
def purge_data(self, which_sites=None, never_delete=False):
"""
Remove uploaded files, postgres db, solr index, venv
"""
# Default to the set of all sites
if not exists(self.datadir + '/.version'):
format_version =... |
:param container: 'web', 'solr' or 'postgres'
:param tail: number of lines to show
:param follow: True to return generator instead of list
:param timestamps: True to include timestamps
def logs(self, container, tail='all', follow=False, timestamps=False):
"""
:param container: '... |
Create/replace ~/.datacats/run/proxy-environment and return
entry for ro mount for containers
def _proxy_settings(self):
"""
Create/replace ~/.datacats/run/proxy-environment and return
entry for ro mount for containers
"""
if not ('https_proxy' in environ or 'HTTPS_PROXY... |
Gets the full name of a container of the type specified.
Currently the supported types are:
- 'venv'
- 'postgres'
- 'solr'
- 'web'
- 'pgdata'
- 'lessc'
- 'datapusher'
- 'redis'
The name will be formatted appr... |
Recompiles less files in an environment.
Usage:
datacats less [ENVIRONMENT]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
def less(environment, opts):
# pylint: disable=unused-argument
"""Recompiles less files in an environment.
Usage:
datacats less [ENVIRONM... |
Decorator applied to a dataset conversion function that converts acquired
source files into a dataset file that BatchUp can use.
Parameters
----------
source_file: list of `AbstractSourceFile` instances
A list of files to be acquired
target_filename: str or callable
The name of the ... |
Delete the cache (converted files) for a dataset.
Parameters
----------
filenames: str
Filenames of files to delete
def delete_dataset_cache(*filenames):
"""
Delete the cache (converted files) for a dataset.
Parameters
----------
filenames: str
Filenames of files to de... |
Download the file and return its path
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the download failed.
def acquire(self, **kwargs):
"""
Download the file and return its path
Returns
------... |
Copy the file and return its path
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the copy failed.
def acquire(self, **kwargs):
"""
Copy the file and return its path
Returns
-------
st... |
Copy the file and return its path
Returns
-------
str or None
The path of the file or None if it does not exist or if
verification failed.
def acquire(self, **kwargs):
"""
Copy the file and return its path
Returns
-------
str or ... |
A function which retries a given function num times and calls retry_notif each
time the function is retried.
:param func: The function to retry num times.
:param num: The number of times to try before giving up.
:param retry_notif: Will be called with the same parameter as func if we have to retry the
... |
Retrieve a result from executing a task. Note that tasks are executed
in order and that if the next task has not yet completed, this call
will block until the result is available.
Returns
-------
A result from the result buffer.
def retrieve(self):
"""
Retrieve ... |
Install or reinstall Python packages within this environment
Usage:
datacats install [-q] [--address=IP] [ENVIRONMENT [PACKAGE ...]]
datacats install -c [q] [--address=IP] [ENVIRONMENT]
Options:
--address=IP The address to bind to when reloading after install
-c --clean Reinstall packages ... |
Migrate an environment to a given revision of the datadir format.
Usage:
datacats migrate [-y] [-r VERSION] [ENVIRONMENT_DIR]
Options:
-r --revision=VERSION The version of the datadir format you want
to convert to [default: 2]
-y --yes Answer yes to all questions.
Defaul... |
Deploy environment to production DataCats.com cloud service
Usage:
datacats deploy [--create] [ENVIRONMENT [TARGET_NAME]]
Options:
--create Create a new environment on DataCats.com instead
of updating an existing environment
ENVIRONMENT may be an environment name or a pat... |
Trim the mini-batch `batch` to the size `length`.
`batch` can be:
- a NumPy array, in which case it's first axis will be trimmed to size
`length`
- a tuple, in which case `_trim_batch` applied recursively to
each element and the resulting tuple returned
As a consequence, mini-batches can b... |
Apply a function to all the samples that are accessed as mini-batches
obtained from an iterator.
Returns the per-sample results.
The function `func` should return the result for each sample in the
mini-batch as an array. To return multiple results (e.g. loss and errors)
return a tuple of arrays (e.... |
Apply a function to all the samples that are accessed as mini-batches
obtained from an iterator.
Returns the across-samples mean of the results returned by `func`
The `sum_axis` arguments tells `mean_batch_map` how to process the
results of `func` before accumulating them:
- If `sum_axis` is `None`... |
Helper function to coerce an object into a data source, selecting the
appropriate data source class for the given object. If `x` is already
a data source it is returned as is.
Parameters
----------
x: any
The object to coerce. If `x` is a data source, it is returned as is.
If it is ... |
A batch oriented implementation of `map`.
Applies a function to all the samples in this data source by breaking
the data into mini-batches and applying the function to each
mini-batch.
Returns the per-sample results.
This method is a wrapper around the :func:`batch_map` function... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.