_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56000
cpu_source_extraction
train
def cpu_source_extraction(in1, tolerance, neg_comp): """ The following function determines connectivity within a given wavelet decomposition. These connected and labelled structures are thresholded to within some tolerance of the maximum coefficient at the scale. This determines whether on not an object...
python
{ "resource": "" }
q56001
snr_ratio
train
def snr_ratio(in1, in2): """ The following function simply calculates the signal to noise ratio between two signals. INPUTS: in1 (no default): Array containing values for signal 1. in2 (no default): Array containing values for signal 2. OUTPUTS: out1 ...
python
{ "resource": "" }
q56002
RabbitMQContainer.wait_for_start
train
def wait_for_start(self): """ Wait for the RabbitMQ process to be come up. """ er = self.exec_rabbitmqctl( 'wait', ['--pid', '1', '--timeout', str(int(self.wait_timeout))]) output_lines(er, error_exc=TimeoutError)
python
{ "resource": "" }
q56003
RabbitMQContainer.exec_rabbitmqctl
train
def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']): """ Execute a ``rabbitmqctl`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param rabbitmqctl_opts: a list of extra options to...
python
{ "resource": "" }
q56004
RabbitMQContainer.exec_rabbitmqctl_list
train
def exec_rabbitmqctl_list(self, resources, args=[], rabbitmq_opts=['-q', '--no-table-headers']): """ Execute a ``rabbitmqctl`` command to list the given resources. :param resources: the resources to list, e.g. ``'vhosts'`` :param args: a list of args for th...
python
{ "resource": "" }
q56005
RabbitMQContainer.list_users
train
def list_users(self): """ Run the ``list_users`` command and return a list of tuples describing the users. :return: A list of 2-element tuples. The first element is the username, the second a list of tags for the user. """ lines = output_lines(sel...
python
{ "resource": "" }
q56006
RabbitMQContainer.broker_url
train
def broker_url(self): """ Returns a "broker URL" for use with Celery. """ return 'amqp://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.vhost)
python
{ "resource": "" }
q56007
PostgreSQLContainer.exec_pg_success
train
def exec_pg_success(self, cmd): """ Execute a command inside a running container as the postgres user, asserting success. """ result = self.inner().exec_run(cmd, user='postgres') assert result.exit_code == 0, result.output.decode('utf-8') return result
python
{ "resource": "" }
q56008
PostgreSQLContainer.clean
train
def clean(self): """ Remove all data by dropping and recreating the configured database. .. note:: Only the configured database is removed. Any other databases remain untouched. """ self.exec_pg_success(['dropdb', '-U', self.user, self.database]) ...
python
{ "resource": "" }
q56009
PostgreSQLContainer.exec_psql
train
def exec_psql(self, command, psql_opts=['-qtA']): """ Execute a ``psql`` command inside a running container. By default the container's database is connected to. :param command: the command to run (passed to ``-c``) :param psql_opts: a list of extra options to pass to ``psql`` ...
python
{ "resource": "" }
q56010
PostgreSQLContainer.list_databases
train
def list_databases(self): """ Runs the ``\\list`` command and returns a list of column values with information about all databases. """ lines = output_lines(self.exec_psql('\\list')) return [line.split('|') for line in lines]
python
{ "resource": "" }
q56011
PostgreSQLContainer.list_tables
train
def list_tables(self): """ Runs the ``\\dt`` command and returns a list of column values with information about all tables in the database. """ lines = output_lines(self.exec_psql('\\dt')) return [line.split('|') for line in lines]
python
{ "resource": "" }
q56012
PostgreSQLContainer.list_users
train
def list_users(self): """ Runs the ``\\du`` command and returns a list of column values with information about all user roles. """ lines = output_lines(self.exec_psql('\\du')) return [line.split('|') for line in lines]
python
{ "resource": "" }
q56013
PostgreSQLContainer.database_url
train
def database_url(self): """ Returns a "database URL" for use with DJ-Database-URL and similar libraries. """ return 'postgres://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.database)
python
{ "resource": "" }
q56014
from_config
train
def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): fo...
python
{ "resource": "" }
q56015
StatusWorkerThread.flush
train
def flush(self): """ This only needs to be called manually from unit tests """ self.logger.debug('Flush joining') self.queue.join() self.logger.debug('Flush joining ready')
python
{ "resource": "" }
q56016
output_lines
train
def output_lines(output, encoding='utf-8', error_exc=None): """ Convert bytestring container output or the result of a container exec command into a sequence of unicode lines. :param output: Container output bytes or an :class:`docker.models.containers.ExecResult` instance. :param e...
python
{ "resource": "" }
q56017
WeedFS.get_file
train
def get_file(self, fid): """Get file from WeedFS. Returns file content. May be problematic for large files as content is stored in memory. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Content of the file with provided fid or None...
python
{ "resource": "" }
q56018
WeedFS.get_file_url
train
def get_file_url(self, fid, public=None): """ Get url for the file :param string fid: File ID :param boolean public: public or internal url :rtype: string """ try: volume_id, rest = fid.strip().split(",") except ValueError: raise B...
python
{ "resource": "" }
q56019
WeedFS.get_file_location
train
def get_file_location(self, volume_id): """ Get location for the file, WeedFS volume is choosed randomly :param integer volume_id: volume_id :rtype: namedtuple `FileLocation` `{"public_url":"", "url":""}` """ url = ("http://{master_addr}:{master_port}/" ...
python
{ "resource": "" }
q56020
WeedFS.get_file_size
train
def get_file_size(self, fid): """ Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None """ url = self.get_file_url(fid) res = self.conn.head(url...
python
{ "resource": "" }
q56021
WeedFS.file_exists
train
def file_exists(self, fid): """Checks if file with provided fid exists Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: True if file exists. False if not. """ res = self.get_file_size(fid) if res is not None: retur...
python
{ "resource": "" }
q56022
WeedFS.delete_file
train
def delete_file(self, fid): """ Delete file from WeedFS :param string fid: File ID """ url = self.get_file_url(fid) return self.conn.delete_data(url)
python
{ "resource": "" }
q56023
WeedFS.upload_file
train
def upload_file(self, path=None, stream=None, name=None, **kwargs): """ Uploads file to WeedFS I takes either path or stream and name and upload it to WeedFS server. Returns fid of the uploaded file. :param string path: :param string stream: :param stri...
python
{ "resource": "" }
q56024
WeedFS.vacuum
train
def vacuum(self, threshold=0.3): ''' Force garbage collection :param float threshold (optional): The threshold is optional, and will not change the default threshold. :rtype: boolean ''' url = ("http://{master_addr}:{master_port}/" "vol/vacuum?gar...
python
{ "resource": "" }
q56025
WeedFS.version
train
def version(self): ''' Returns Weed-FS master version :rtype: string ''' url = "http://{master_addr}:{master_port}/dir/status".format( master_addr=self.master_addr, master_port=self.master_port) data = self.conn.get_data(url) response_data...
python
{ "resource": "" }
q56026
fft_convolve
train
def fft_convolve(in1, in2, conv_device="cpu", conv_mode="linear", store_on_gpu=False): """ This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU and GPU. INPUTS: in1 (no default): Array containing one set of data, possibl...
python
{ "resource": "" }
q56027
gpu_r2c_fft
train
def gpu_r2c_fft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT. INPUTS: in1 (no default): The array on which the FFT is to be performed. is_gpuarray (default=True): ...
python
{ "resource": "" }
q56028
gpu_c2r_ifft
train
def gpu_c2r_ifft(in1, is_gpuarray=False, store_on_gpu=False): """ This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT. INPUTS: in1 (no default): The array on which the IFFT is to be performed. is_gpuarray (default=True): ...
python
{ "resource": "" }
q56029
pad_array
train
def pad_array(in1): """ Simple convenience function to pad arrays for linear convolution. INPUTS: in1 (no default): Input array which is to be padded. OUTPUTS: out1 Padded version of the input. """ padded_size = 2*np.array(in1.shape) out1 = np.zeros([padd...
python
{ "resource": "" }
q56030
DragonAPI.is_dragon
train
def is_dragon(host, timeout=1): """ Check if host is a dragon. Check if the specified host is a dragon based on simple heuristic. The code simply checks if particular strings are in the index page. It should work for DragonMint or Innosilicon branded miners. """ ...
python
{ "resource": "" }
q56031
DragonAPI.updatePools
train
def updatePools(self, pool1, username1, password1, pool2=None, username2=None, password2=None, pool3=None, username3=None, password3=None): ...
python
{ "resource": "" }
q56032
DragonAPI.updatePassword
train
def updatePassword(self, user, currentPassword, newPassword): """Change the password of a user.""" return self.__post('/api/updatePassword', data={ 'user': user, ...
python
{ "resource": "" }
q56033
DragonAPI.updateNetwork
train
def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None): """Change the current network settings.""" return self.__post('/api/updateNetwork', ...
python
{ "resource": "" }
q56034
DragonAPI.upgradeUpload
train
def upgradeUpload(self, file): """Upgrade the firmware of the miner.""" files = {'upfile': open(file, 'rb')} return self.__post_files('/upgrade/upload', files=files)
python
{ "resource": "" }
q56035
StatusObject.is_program
train
def is_program(self): """ A property which can be used to check if StatusObject uses program features or not. """ from automate.callables import Empty return not (isinstance(self.on_activate, Empty) and isinstance(self.on_deactivate, Empty) ...
python
{ "resource": "" }
q56036
StatusObject.get_as_datadict
train
def get_as_datadict(self): """ Get data of this object as a data dictionary. Used by websocket service. """ d = super().get_as_datadict() d.update(dict(status=self.status, data_type=self.data_type, editable=self.editable)) return d
python
{ "resource": "" }
q56037
StatusObject._do_change_status
train
def _do_change_status(self, status, force=False): """ This function is called by - set_status - _update_program_stack if active program is being changed - thia may be launched by sensor status change. status lock is necessary because these happen from diff...
python
{ "resource": "" }
q56038
AbstractActuator.activate_program
train
def activate_program(self, program): """ Called by program which desires to manipulate this actuator, when it is activated. """ self.logger.debug("activate_program %s", program) if program in self.program_stack: return with self._program_lock: ...
python
{ "resource": "" }
q56039
AbstractActuator.deactivate_program
train
def deactivate_program(self, program): """ Called by program, when it is deactivated. """ self.logger.debug("deactivate_program %s", program) with self._program_lock: self.logger.debug("deactivate_program got through %s", program) if program not in se...
python
{ "resource": "" }
q56040
stream_logs
train
def stream_logs(container, timeout=10.0, **logs_kwargs): """ Stream logs from a Docker container within a timeout. :param ~docker.models.containers.Container container: Container who's log lines to stream. :param timeout: Timeout value in seconds. :param logs_kwargs: Additio...
python
{ "resource": "" }
q56041
fetch_image
train
def fetch_image(client, name): """ Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name. """ try: image = client.images.get(name) except docker.errors.ImageNotFound: name, tag = ...
python
{ "resource": "" }
q56042
_HelperBase._get_id_and_model
train
def _get_id_and_model(self, id_or_model): """ Get both the model and ID of an object that could be an ID or a model. :param id_or_model: The object that could be an ID string or a model object. :param model_collection: The collection to which the model belongs. ...
python
{ "resource": "" }
q56043
_HelperBase.create
train
def create(self, name, *args, **kwargs): """ Create an instance of this resource type. """ resource_name = self._resource_name(name) log.info( "Creating {} '{}'...".format(self._model_name, resource_name)) resource = self.collection.create(*args, name=resource...
python
{ "resource": "" }
q56044
_HelperBase.remove
train
def remove(self, resource, **kwargs): """ Remove an instance of this resource type. """ log.info( "Removing {} '{}'...".format(self._model_name, resource.name)) resource.remove(**kwargs) self._ids.remove(resource.id)
python
{ "resource": "" }
q56045
ContainerHelper.remove
train
def remove(self, container, force=True, volumes=True): """ Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker ...
python
{ "resource": "" }
q56046
NetworkHelper.get_default
train
def get_default(self, create=True): """ Get the default bridge network that containers are connected to if no other network options are specified. :param create: Whether or not to create the network if it doesn't already exist. """ if self._default_network is...
python
{ "resource": "" }
q56047
DockerHelper._helper_for_model
train
def _helper_for_model(self, model_type): """ Get the helper for a given type of Docker model. For use by resource definitions. """ if model_type is models.containers.Container: return self.containers if model_type is models.images.Image: return sel...
python
{ "resource": "" }
q56048
DockerHelper.teardown
train
def teardown(self): """ Clean up all resources when we're done with them. """ self.containers._teardown() self.networks._teardown() self.volumes._teardown() # We need to close the underlying APIClient explicitly to avoid # ResourceWarnings from unclosed H...
python
{ "resource": "" }
q56049
RedisContainer.exec_redis_cli
train
def exec_redis_cli(self, command, args=[], db=0, redis_cli_opts=[]): """ Execute a ``redis-cli`` command inside a running container. :param command: the command to run :param args: a list of args for the command :param db: the db number to query (default ``0``) :param re...
python
{ "resource": "" }
q56050
RedisContainer.list_keys
train
def list_keys(self, pattern='*', db=0): """ Run the ``KEYS`` command and return the list of matching keys. :param pattern: the pattern to filter keys by (default ``*``) :param db: the db number to query (default ``0``) """ lines = output_lines(self.exec_redis_cli('KEYS',...
python
{ "resource": "" }
q56051
threaded
train
def threaded(system, func, *args, **kwargs): """ uses thread_init as a decorator-style """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: if system.raven_client: system.raven_client.captureException(...
python
{ "resource": "" }
q56052
OrderedMatcher.match
train
def match(self, item): """ Return ``True`` if the expected matchers are matched in the expected order, otherwise ``False``. """ if self._position == len(self._matchers): raise RuntimeError('Matcher exhausted, no more matchers to use') matcher = self._matchers...
python
{ "resource": "" }
q56053
UnorderedMatcher.match
train
def match(self, item): """ Return ``True`` if the expected matchers are matched in any order, otherwise ``False``. """ if not self._unused_matchers: raise RuntimeError('Matcher exhausted, no more matchers to use') for matcher in self._unused_matchers: ...
python
{ "resource": "" }
q56054
DataImage.moresane_by_scale
train
def moresane_by_scale(self, start_scale=1, stop_scale=20, subregion=None, sigma_level=4, loop_gain=0.1, tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False, decom_mode="ser", core_count=1, conv_device='cpu', conv_mode='linear', e...
python
{ "resource": "" }
q56055
DataImage.restore
train
def restore(self): """ This method constructs the restoring beam and then adds the convolution to the residual. """ clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2) if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)): ...
python
{ "resource": "" }
q56056
DataImage.handle_input
train
def handle_input(self, input_hdr): """ This method tries to ensure that the input data has the correct dimensions. INPUTS: input_hdr (no default) Header from which data shape is to be extracted. """ input_slice = input_hdr['NAXIS']*[0] for i in range(input...
python
{ "resource": "" }
q56057
DataImage.save_fits
train
def save_fits(self, data, name): """ This method simply saves the model components and the residual. INPUTS: data (no default) Data which is to be saved. name (no default) File name for new .fits file. Will overwrite. """ data = data.reshape(1, 1, dat...
python
{ "resource": "" }
q56058
DataImage.make_logger
train
def make_logger(self, level="INFO"): """ Convenience function which creates a logger for the module. INPUTS: level (default="INFO"): Minimum log level for logged/streamed messages. OUTPUTS: logger Logger for the function. NOTE: Must be bound to ...
python
{ "resource": "" }
q56059
TextUIService.text_ui
train
def text_ui(self): """ Start Text UI main loop """ self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
python
{ "resource": "" }
q56060
Connection._prepare_headers
train
def _prepare_headers(self, additional_headers=None, **kwargs): """Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used wit...
python
{ "resource": "" }
q56061
Connection.head
train
def head(self, url, *args, **kwargs): """Returns response to http HEAD on provided url """ res = self._conn.head(url, headers=self._prepare_headers(**kwargs)) if res.status_code == 200: return res return None
python
{ "resource": "" }
q56062
Connection.get_data
train
def get_data(self, url, *args, **kwargs): """Gets data from url as text Returns content under the provided url as text Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers ...
python
{ "resource": "" }
q56063
Connection.get_raw_data
train
def get_raw_data(self, url, *args, **kwargs): """Gets data from url as bytes Returns content under the provided url as bytes ie. for binary data Args: **url**: address of the wanted data .. versionadded:: 0.3.2 **additional_headers**: (optional)...
python
{ "resource": "" }
q56064
Connection.post_file
train
def post_file(self, url, filename, file_stream, *args, **kwargs): """Uploads file to provided url. Returns contents as text Args: **url**: address where to upload file **filename**: Name of the uploaded file **file_stream**: file like object to upload ...
python
{ "resource": "" }
q56065
Connection.delete_data
train
def delete_data(self, url, *args, **kwargs): """Deletes data under provided url Returns status as boolean. Args: **url**: address of file to be deleted .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be u...
python
{ "resource": "" }
q56066
remove_diacritic
train
def remove_diacritic(*diacritics): """ Given a collection of Unicode diacritics, return a function that takes a string and returns the string without those diacritics. """ def _(text): return unicodedata.normalize("NFC", "".join( ch for ch in unicodedata.normalize("NF...
python
{ "resource": "" }
q56067
deep_merge
train
def deep_merge(*dicts): """ Recursively merge all input dicts into a single dict. """ result = {} for d in dicts: if not isinstance(d, dict): raise Exception('Can only deep_merge dicts, got {}'.format(d)) for k, v in d.items(): # Whenever the value is a dict, ...
python
{ "resource": "" }
q56068
_DefinitionBase.create
train
def create(self, **kwargs): """ Create an instance of this resource definition. Only one instance may exist at any given time. """ if self.created: raise RuntimeError( '{} already created.'.format(self.__model_type__.__name__)) kwargs = self....
python
{ "resource": "" }
q56069
_DefinitionBase.remove
train
def remove(self, **kwargs): """ Remove an instance of this resource definition. """ self.helper.remove(self.inner(), **kwargs) self._inner = None
python
{ "resource": "" }
q56070
_DefinitionBase.setup
train
def setup(self, helper=None, **create_kwargs): """ Setup this resource so that is ready to be used in a test. If the resource has already been created, this call does nothing. For most resources, this just involves creating the resource in Docker. :param helper: The...
python
{ "resource": "" }
q56071
_DefinitionBase.as_fixture
train
def as_fixture(self, name=None): """ A decorator to inject this container into a function as a test fixture. """ if name is None: name = self.name def deco(f): @functools.wraps(f) def wrapper(*args, **kw): with self: ...
python
{ "resource": "" }
q56072
ContainerDefinition.setup
train
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arg...
python
{ "resource": "" }
q56073
ContainerDefinition.teardown
train
def teardown(self): """ Stop and remove the container if it exists. """ while self._http_clients: self._http_clients.pop().close() if self.created: self.halt()
python
{ "resource": "" }
q56074
ContainerDefinition.status
train
def status(self): """ Get the container's current status from Docker. If the container does not exist (before creation and after removal), the status is ``None``. """ if not self.created: return None self.inner().reload() return self.inner().s...
python
{ "resource": "" }
q56075
ContainerDefinition.stop
train
def stop(self, timeout=5): """ Stop the container. The container must have been created. :param timeout: Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 5 (half the Docker default) """ self.inner().stop(timeout=...
python
{ "resource": "" }
q56076
ContainerDefinition.run
train
def run(self, fetch_image=True, **kwargs): """ Create the container and start it. Similar to ``docker run``. :param fetch_image: Whether to try pull the image if it's not found. The behaviour here is similar to ``docker run`` and this parameter defaults to ``...
python
{ "resource": "" }
q56077
ContainerDefinition.wait_for_start
train
def wait_for_start(self): """ Wait for the container to start. By default this will wait for the log lines matching the patterns passed in the ``wait_patterns`` parameter of the constructor using an UnorderedMatcher. For more advanced checks for container startup, this m...
python
{ "resource": "" }
q56078
ContainerDefinition.get_logs
train
def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all', since=None): """ Get container logs. This method does not support streaming, use :meth:`stream_logs` for that. """ return self.inner().logs( stdout=stdout, stderr=stde...
python
{ "resource": "" }
q56079
ContainerDefinition.stream_logs
train
def stream_logs(self, stdout=True, stderr=True, tail='all', timeout=10.0): """ Stream container output. """ return stream_logs( self.inner(), stdout=stdout, stderr=stderr, tail=tail, timeout=timeout)
python
{ "resource": "" }
q56080
ContainerDefinition.wait_for_logs_matching
train
def wait_for_logs_matching(self, matcher, timeout=10, encoding='utf-8', **logs_kwargs): """ Wait for logs matching the given matcher. """ wait_for_logs_matching( self.inner(), matcher, timeout=timeout, encoding=encoding, **logs_kwarg...
python
{ "resource": "" }
q56081
ContainerDefinition.http_client
train
def http_client(self, port=None): """ Construct an HTTP client for this container. """ # Local import to avoid potential circularity. from seaworthy.client import ContainerHttpClient client = ContainerHttpClient.for_container(self, container_port=port) self._http_...
python
{ "resource": "" }
q56082
_dispatch_change_event
train
def _dispatch_change_event(self, object, trait_name, old, new, handler): """ Prepare and dispatch a trait change event to a listener. """ # Extract the arguments needed from the handler. args = self.argument_transform(object, trait_name, old, new) # Send a description of the event to the change event ...
python
{ "resource": "" }
q56083
split
train
def split(value, precision=1): ''' Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". Args ...
python
{ "resource": "" }
q56084
si_format
train
def si_format(value, precision=1, format_str=u'{value} {prefix}', exp_format_str=u'{value}e{expof10}'): ''' Format value to string with SI prefix, using the specified precision. Parameters ---------- value : int, float Input value. precision : int Number of digits ...
python
{ "resource": "" }
q56085
si_parse
train
def si_parse(value): ''' Parse a value expressed using SI prefix units to a floating point number. Parameters ---------- value : str or unicode Value expressed using SI prefix units (as returned by :func:`si_format` function). .. versionchanged:: 1.0 Use unicode string...
python
{ "resource": "" }
q56086
ExternalApi.set_status
train
def set_status(self, name, status): """ Set sensor ``name`` status to ``status``. """ getattr(self.system, name).status = status return True
python
{ "resource": "" }
q56087
ExternalApi.toggle_object_status
train
def toggle_object_status(self, objname): """ Toggle boolean-valued sensor status between ``True`` and ``False``. """ o = getattr(self.system, objname) o.status = not o.status self.system.flush() return o.status
python
{ "resource": "" }
q56088
ExternalApi.log
train
def log(self): """ Return recent log entries as a string. """ logserv = self.system.request_service('LogStoreService') return logserv.lastlog(html=False)
python
{ "resource": "" }
q56089
System.load_or_create
train
def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs): """ Load system from a dump, if dump file exists, or create a new system if it does not exist. """ parser = argparse.ArgumentParser() parser.add_argument('--no_input', action='store_true') ...
python
{ "resource": "" }
q56090
System.cmd_namespace
train
def cmd_namespace(self): """ A read-only property that gives the namespace of the system for evaluating commands. """ import automate ns = dict(list(automate.__dict__.items()) + list(self.namespace.items())) return ns
python
{ "resource": "" }
q56091
System.services_by_name
train
def services_by_name(self): """ A property that gives a dictionary that contains services as values and their names as keys. """ srvs = defaultdict(list) for i in self.services: srvs[i.__class__.__name__].append(i) return srvs
python
{ "resource": "" }
q56092
System.name_to_system_object
train
def name_to_system_object(self, name): """ Give SystemObject instance corresponding to the name """ if isinstance(name, str): if self.allow_name_referencing: name = name else: raise NameError('System.allow_name_referencing is se...
python
{ "resource": "" }
q56093
System.register_service_functions
train
def register_service_functions(self, *funcs): """ Register function in the system namespace. Called by Services. """ for func in funcs: self.namespace[func.__name__] = func
python
{ "resource": "" }
q56094
System.register_service
train
def register_service(self, service): """ Register service into the system. Called by Services. """ if service not in self.services: self.services.append(service)
python
{ "resource": "" }
q56095
System.cleanup
train
def cleanup(self): """ Clean up before quitting """ self.pre_exit_trigger = True self.logger.info("Shutting down %s, please wait a moment.", self.name) for t in threading.enumerate(): if isinstance(t, TimerClass): t.cancel() self....
python
{ "resource": "" }
q56096
System.cmd_exec
train
def cmd_exec(self, cmd): """ Execute commands in automate namespace """ if not cmd: return ns = self.cmd_namespace import copy rval = True nscopy = copy.copy(ns) try: r = eval(cmd, ns) if isinstance(r, Syste...
python
{ "resource": "" }
q56097
PlantUMLService.write_puml
train
def write_puml(self, filename=''): """ Writes PUML from the system. If filename is given, stores result in the file. Otherwise returns result as a string. """ def get_type(o): type = 'program' if isinstance(o, AbstractSensor): type ...
python
{ "resource": "" }
q56098
PlantUMLService.write_svg
train
def write_svg(self): """ Returns PUML from the system as a SVG image. Requires plantuml library. """ import plantuml puml = self.write_puml() server = plantuml.PlantUML(url=self.url) svg = server.processes(puml) return svg
python
{ "resource": "" }
q56099
median_kneighbour_distance
train
def median_kneighbour_distance(X, k=5): """ Calculate the median kneighbor distance. Find the distance between a set of random datapoints and their kth nearest neighbours. This is a heuristic for setting the kernel length scale. """ N_all = X.shape[0] k = min(k, N_all) N_subset = mi...
python
{ "resource": "" }