INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
This function performs the thresholding of the values in array in1 based on the estimated standard deviation given by the MAD ( median absolute deviation ) estimator about zero.
def apply_threshold(in1, threshold, sigma_level=4): """ This function performs the thresholding of the values in array in1 based on the estimated standard deviation given by the MAD (median absolute deviation) estimator about zero. INPUTS: in1 (no default): The array which is to be th...
Convenience function for allocating work to cpu or gpu depending on the selected mode.
def source_extraction(in1, tolerance, mode="cpu", store_on_gpu=False, neg_comp=False): """ Convenience function for allocating work to cpu or gpu, depending on the selected mode. INPUTS: in1 (no default): Array containing the wavelet decomposition. tolerance (no de...
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 is to be considered as significant. Significant objects are extracted an...
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...
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 is to be considered as significant. Significant objects are extracted an...
def gpu_source_extraction(in1, tolerance, store_on_gpu, 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...
The following function simply calculates the signal to noise ratio between two signals.
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 ...
Wait for the RabbitMQ process to be come up.
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)
Execute a rabbitmqctl command inside a running container.
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...
Execute a rabbitmqctl command to list the given resources.
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...
Run the list_queues command ( for the default vhost ) and return a list of tuples describing the queues.
def list_queues(self): """ Run the ``list_queues`` command (for the default vhost) and return a list of tuples describing the queues. :return: A list of 2-element tuples. The first element is the queue name, the second is the current queue size. """ ...
Run the list_users command and return a list of tuples describing the users.
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...
Returns a broker URL for use with Celery.
def broker_url(self): """ Returns a "broker URL" for use with Celery. """ return 'amqp://{}:{}@{}/{}'.format( self.user, self.password, self.name, self.vhost)
Execute a command inside a running container as the postgres user asserting success.
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
Remove all data by dropping and recreating the configured database.
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]) ...
Execute a psql command inside a running container. By default the container s database is connected to.
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`` ...
Runs the \\ list command and returns a list of column values with information about all databases.
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]
Runs the \\ dt command and returns a list of column values with information about all tables in the database.
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]
Runs the \\ du command and returns a list of column values with information about all user roles.
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]
Returns a database URL for use with DJ - Database - URL and similar libraries.
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)
Generate a matrix from a configuration dictionary.
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...
Generate a matrix from a. ini file. Configuration is expected to be in a [ matrix ] section.
def from_file(filename, section='matrix'): """ Generate a matrix from a .ini file. Configuration is expected to be in a ``[matrix]`` section. """ config = parse_config(open(filename), section=section) return from_config(config)
Generate a matrix from a. ini file. Configuration is expected to be in a [ matrix ] section.
def from_string(string, section='matrix'): """ Generate a matrix from a .ini file. Configuration is expected to be in a ``[matrix]`` section. """ config = parse_config(StringIO(string), section=section) return from_config(config)
Decorator/ wrapper function to force return None instead of raising module exceptions.
def no_raise(f): """Decorator/wrapper function to force return None instead of raising module exceptions. Exceptions that can be ignored are found in mypolr.exceptions.""" @wraps(f) def new_f(*args, **kwargs): try: return f(*args, **kwargs) except MypolrError: pa...
This only needs to be called manually from unit tests
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')
Convert bytestring container output or the result of a container exec command into a sequence of unicode lines.
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...
Get file from WeedFS.
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...
Get url for the file
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...
Get location for the file WeedFS volume is choosed randomly
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}/" ...
Gets size of uploaded file Or None if file doesn t exist.
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...
Checks if file with provided fid exists
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...
Delete file from WeedFS
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)
Uploads file to WeedFS
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...
Force garbage collection
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...
Returns Weed - FS master version
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...
This function determines the convolution of two inputs using the FFT. Contains an implementation for both CPU and GPU.
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...
This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT.
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): ...
This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT.
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): ...
Simple convenience function to pad arrays for linear convolution.
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...
This function performs the FFT shift operation on the GPU to restore the correct output shape.
def fft_shift(in1): """ This function performs the FFT shift operation on the GPU to restore the correct output shape. INPUTS: in1 (no default): Array containing data which has been FFTed and IFFTed. OUTPUTS: in1 FFT-shifted version of in1. """ ker = SourceMo...
This function unpads an array on the GPU in such a way as to make it contiguous.
def contiguous_slice(in1): """ This function unpads an array on the GPU in such a way as to make it contiguous. INPUTS: in1 (no default): Array containing data which has been padded. OUTPUTS: gpu_out1 Array containing unpadded, contiguous data. """ ker = SourceMod...
This function performs in - place scaling after the IFFT without recompilation.
def scale_fft(in1): """ This function performs in-place scaling after the IFFT without recompilation. INPUTS: in1 (no default): Array containing data which is to be scaled. """ ker = SourceModule(""" __global__ void scale_fft_ker(float *in1) ...
Check if host is a dragon.
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. """ ...
Authenticate with the miner and obtain a JSON web token ( JWT ).
def auth(self): """Authenticate with the miner and obtain a JSON web token (JWT).""" response = requests.post( parse.urljoin(self.base_url, '/api/auth'), timeout=self.timeout, data={'username': self.username, 'password': self.password}) response.raise_for_stat...
Change the pools of the miner. This call will restart cgminer.
def updatePools(self, pool1, username1, password1, pool2=None, username2=None, password2=None, pool3=None, username3=None, password3=None): ...
Change the password of a user.
def updatePassword(self, user, currentPassword, newPassword): """Change the password of a user.""" return self.__post('/api/updatePassword', data={ 'user': user, ...
Change the current network settings.
def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None): """Change the current network settings.""" return self.__post('/api/updateNetwork', ...
Upgrade the firmware of the miner.
def upgradeUpload(self, file): """Upgrade the firmware of the miner.""" files = {'upfile': open(file, 'rb')} return self.__post_files('/upgrade/upload', files=files)
A property which can be used to check if StatusObject uses program features or not.
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) ...
Define how status is displayed in UIs ( add units etc. ).
def get_status_display(self, **kwargs): """ Define how status is displayed in UIs (add units etc.). """ if 'value' in kwargs: value = kwargs['value'] else: value = self.status if self.show_stdev_seconds: stdev = self.stdev(self.sho...
Get data of this object as a data dictionary. Used by websocket service.
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
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 different threads.
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...
Compatibility to actuator class. Also: class: ~automate. callables. builtin_callables. SetStatus callable can be used for sensors too if so desired.
def set_status(self, status, origin=None, force=False): """ Compatibility to actuator class. Also :class:`~automate.callables.builtin_callables.SetStatus` callable can be used for sensors too, if so desired. """ if status != self.default: self._se...
For programs to set current status of the actuator. Each active program has its status in: attr:. program_stack dictionary and the highest priority is realized in the actuator
def set_status(self, status, origin=None, force=False): """ For programs, to set current status of the actuator. Each active program has its status in :attr:`.program_stack` dictionary and the highest priority is realized in the actuator """ if not self.slave and origin not in s...
Called by program which desires to manipulate this actuator when it is activated.
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: ...
Called by program when it is deactivated.
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...
Stream logs from a Docker container within a timeout.
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...
Wait for matching log line ( s ) from the given container by streaming the container s stdout and/ or stderr outputs.
def wait_for_logs_matching(container, matcher, timeout=10, encoding='utf-8', **logs_kwargs): """ Wait for matching log line(s) from the given container by streaming the container's stdout and/or stderr outputs. Each log line is decoded and any trailing whitespace is stripped ...
Fetch an image if it isn t already present.
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 = ...
Get both the model and ID of an object that could be an ID or a model.
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. ...
Create an instance of this resource type.
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...
Remove an instance of this resource type.
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)
Create a new container.
def create(self, name, image, fetch_image=False, network=None, volumes={}, **kwargs): """ Create a new container. :param name: The name for the container. This will be prefixed with the namespace. :param image: The image tag or image ob...
Remove a container.
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 ...
Get the default bridge network that containers are connected to if no other network options are specified.
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...
Create a new network.
def create(self, name, check_duplicate=True, **kwargs): """ Create a new network. :param name: The name for the network. This will be prefixed with the namespace. :param check_duplicate: Whether or not to check for networks with the same name. Docker ...
Get the helper for a given type of Docker model. For use by resource definitions.
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...
Clean up all resources when we re done with them.
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...
Execute a redis - cli command inside a running container.
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...
Run the KEYS command and return the list of matching keys.
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',...
uses thread_init as a decorator - style
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(...
List the processes running inside a container. We use an exec rather than container. top () because we want to run ps inside the container. This is because we want to get PIDs and usernames in the container s namespaces. container. top () uses ps from outside the container in the host s namespaces. Note that this requi...
def list_container_processes(container): """ List the processes running inside a container. We use an exec rather than `container.top()` because we want to run 'ps' inside the container. This is because we want to get PIDs and usernames in the container's namespaces. `container.top()` uses 'ps' from...
Build a tree structure from a list of PsRow objects.: param ps_rows: a list of PsRow objects: return: a PsTree object
def build_process_tree(ps_rows): """ Build a tree structure from a list of PsRow objects. :param ps_rows: a list of PsRow objects :return: a PsTree object """ ps_tree = None for row in ps_rows: if row.ppid == 0: if ps_tree is not None: raise PsException("T...
Посмотреть баланс основного счёта.
def cmd_balance(): """ Посмотреть баланс основного счёта. """ r = rocket.operations.cool_feed.get(params={"per_page": 1}) r = handle_error(r) j = r.json() template = "".join([ click.style("{rur} {code}, ", fg="green", bold=True), "{miles} рокетрублей"]) click.echo(templa...
Return True if the expected matchers are matched in the expected order otherwise False.
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...
Return an args string for the repr.
def args_str(self): """ Return an args string for the repr. """ matched = [str(m) for m in self._matchers[:self._position]] unmatched = [str(m) for m in self._matchers[self._position:]] return 'matched=[{}], unmatched=[{}]'.format( ', '.join(matched), ', '.joi...
Return True if the expected matchers are matched in any order otherwise False.
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: ...
Return an args string for the repr.
def args_str(self): """ Return an args string for the repr. """ matched = [str(m) for m in self._used_matchers] unmatched = [str(m) for m in self._unused_matchers] return 'matched=[{}], unmatched=[{}]'.format( ', '.join(matched), ', '.join(unmatched))
Primary method for wavelet analysis and subsequent deconvolution.
def moresane(self, subregion=None, scale_count=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', extraction_mode='cpu', enforce_positivit...
Extension of the MORESANE algorithm. This takes a scale - by - scale approach attempting to remove all sources at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous scales to remove the sources uncovered by the deconvolution.
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...
This method constructs the restoring beam and then adds the convolution to the residual.
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)): ...
This method tries to ensure that the input data has the correct dimensions.
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...
This method simply saves the model components and the residual.
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...
Convenience function which creates a logger for the module.
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 ...
List actuators programs or sensors ( what is string )
def ls(self, what): """List actuators, programs or sensors (what is string)""" for i in getattr(self.system, what): self.logger.info('%s: %s: %s', i.__class__.__name__, i, i.status) return True
Print Automate help if no parameter is given. Otherwise act as pydoc. help ()
def help(self, *args, **kwargs): """Print Automate help if no parameter is given. Otherwise, act as pydoc.help()""" if len(args) > 0 or len(kwargs) > 0: import pydoc pydoc.help(*args, **kwargs) else: hstr = helpstr for i in hstr.split("...
Start Text UI main loop
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()
Prepare headers for http communication.
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...
Returns response to http HEAD on provided url
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
Gets data from url as text
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 ...
Gets data from url as bytes
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)...
Uploads file to provided url.
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 ...
Deletes data under provided url
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...
Показывает последние операции в ленте.
def cmd_feed(): """ Показывает последние операции в ленте. """ r = rocket.operations.cool_feed.get() r = handle_error(r) j = r.json() lines = [] for date, operations in sorted(list(j["dates"].items())): lines += [[ click.style("===== %s =====" % date, fg="blue", bol...
Перевести деньги на номер карты.
def cmd_transfer(recipient, amount): """ Перевести деньги на номер карты. """ r = rocket.card2card.transfer.post(params={ "source_card": recipient, "amount": amount }) r = handle_error(r) j = r.json() if j["status"] == "approved": template = "".join([ ...
Given a collection of Unicode diacritics return a function that takes a Unicode character and returns the member of the collection the character has ( or None ).
def extract_diacritic(*diacritics): """ Given a collection of Unicode diacritics, return a function that takes a Unicode character and returns the member of the collection the character has (or None). """ def _(ch): decomposed_form = unicodedata.normalize("NFD", ch) for diacritic...
Add the given breathing to the given ( possibly accented ) character.
def add_breathing(ch, breathing): """ Add the given breathing to the given (possibly accented) character. """ decomposed = unicodedata.normalize("NFD", ch) if len(decomposed) > 1 and decomposed[1] == LONG: return unicodedata.normalize( "NFC", decomposed[0:2] + breathing + decompo...
Given a collection of Unicode diacritics return a function that takes a string and returns the string without those diacritics.
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...
Change digital Pin value ( boolean ). Also PWM supported ( float )
def change_digital(self, pin_nr, value): """ Change digital Pin value (boolean). Also PWM supported(float)""" if not self._board: return with self._lock: self._act_digital[pin_nr].pin.write(value)
Recursively merge all input dicts into a single dict.
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, ...
Create an instance of this resource definition.
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....
Remove an instance of this resource definition.
def remove(self, **kwargs): """ Remove an instance of this resource definition. """ self.helper.remove(self.inner(), **kwargs) self._inner = None