INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Clears prices according to auction type. | def _clearPrices(self):
""" Clears prices according to auction type.
"""
for offbid in self.offers + self.bids:
if self.auctionType == DISCRIMINATIVE:
offbid.clearedPrice = offbid.price
elif self.auctionType == FIRST_PRICE:
offbid.clearedPr... |
Clip cleared prices according to guarantees and limits. | def _clipPrices(self):
""" Clip cleared prices according to guarantees and limits.
"""
# Guarantee that cleared offer prices are >= offers.
if self.guaranteeOfferPrice:
for offer in self.offers:
if offer.accepted and offer.clearedPrice < offer.price:
... |
Logs offer/bid cleared values. | def _logClearances(self):
""" Logs offer/bid cleared values.
"""
for offer in self.offers:
logger.info("%.2fMW offer cleared at %.2f$/MWh for %s (%.2f)." %
(offer.clearedQuantity, offer.clearedPrice,
offer.generator.name, offer.revenue... |
Try make a GET request with an HTTP client against a certain path and
return once any response has been received, ignoring any errors.
:param ContainerHttpClient client:
The HTTP client to use to connect to the container.
:param timeout:
Timeout value in seconds.
:param path:
HT... | def wait_for_response(client, timeout, path='/', expected_status_code=None):
"""
Try make a GET request with an HTTP client against a certain path and
return once any response has been received, ignoring any errors.
:param ContainerHttpClient client:
The HTTP client to use to connect to the con... |
:param container:
The container to make requests against.
:param container_port:
The container port to make requests against. If ``None``, the first
container port is used.
:returns:
A ContainerClient object configured to make requests to the
c... | def for_container(cls, container, container_port=None):
"""
:param container:
The container to make requests against.
:param container_port:
The container port to make requests against. If ``None``, the first
container port is used.
:returns:
... |
Make a request against a container.
:param method:
The HTTP method to use.
:param list path:
The HTTP path (either absolute or relative).
:param dict url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param kwargs:
... | def request(self, method, path=None, url_kwargs=None, **kwargs):
"""
Make a request against a container.
:param method:
The HTTP method to use.
:param list path:
The HTTP path (either absolute or relative).
:param dict url_kwargs:
Parameters t... |
Sends a GET request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def get(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a GET request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Opti... |
Sends an OPTIONS request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response obj... | def options(self, path=None, url_kwargs=None, **kwargs):
"""
Sends an OPTIONS request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
... |
Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def head(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a POST request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def post(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a POST request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def put(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Opti... |
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def patch(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object | def delete(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
O... |
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the
different methods to be used almost interchangeably.
INPUTS:
in1 (no default): Array on which the decomposition is to be performed.
scale_count (no default): ... | def iuwt_decomposition(in1, scale_count, scale_adjust=0, mode='ser', core_count=2, store_smoothed=False,
store_on_gpu=False):
"""
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the
different methods to be used almost interchang... |
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the
different methods to be used almost interchangeably.
INPUTS:
in1 (no default): Array on which the decomposition is to be performed.
scale_adjust (no default): ... | def iuwt_recomposition(in1, scale_adjust=0, mode='ser', core_count=1, store_on_gpu=False, smoothed_array=None):
"""
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the
different methods to be used almost interchangeably.
INPUTS:
in1 ... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no default): Array on which the decomposition is to be performed.
scale_count ... | def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no default): Array containing wavelet coefficients.
scale_adjust (no de... | def ser_iuwt_recomposition(in1, scale_adjust, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no de... |
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on which filtering is to be performed.
scale ... | def ser_a_trous(C0, filter, scale):
"""
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on whic... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for multiple CPU cores. NOTE: Python is not well suited
to multiprocessing - this may not improve execution speed.
INPUTS:
in1 ... | def mp_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed, core_count):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for multiple CPU cores. NOTE: Python is not well sui... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for multiple CPU cores.
INPUTS:
in1 (no default): Array containing wavelet coefficients.
scale_adjust (no d... | def mp_iuwt_recomposition(in1, scale_adjust, core_count, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for multiple CPU cores.
INPUTS:
in1 ... |
This is a reimplementation of the a trous filter which makes use of multiprocessing. In particular,
it divides the input array of dimensions NxN into M smaller arrays of dimensions (N/M)xN, where M is the
number of cores which are to be used.
INPUTS:
C0 (no default): The current array wh... | def mp_a_trous(C0, wavelet_filter, scale, core_count):
"""
This is a reimplementation of the a trous filter which makes use of multiprocessing. In particular,
it divides the input array of dimensions NxN into M smaller arrays of dimensions (N/M)xN, where M is the
number of cores which are to be used.
... |
This is the convolution step of the a trous algorithm.
INPUTS:
C0 (no default): The current array which is to be decomposed.
wavelet_filter (no default): The filter-bank which is applied to the elements of the transform.
scale (no default): The scale at which d... | def mp_a_trous_kernel(C0, wavelet_filter, scale, slice_ind, slice_width, r_or_c="row"):
"""
This is the convolution step of the a trous algorithm.
INPUTS:
C0 (no default): The current array which is to be decomposed.
wavelet_filter (no default): The filter-bank which is ap... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a GPU.
INPUTS:
in1 (no default): Array on which the decomposition is to be performed.
scale_count (no defaul... | def gpu_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed, store_on_gpu):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a GPU.
INPUTS:
in1 (... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no default): Array containing wavelet coefficients.
scale_adjust (no default): In... | def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no ... |
Simple convenience function so that the a trous kernels can be easily accessed by any function. | def gpu_a_trous():
"""
Simple convenience function so that the a trous kernels can be easily accessed by any function.
"""
ker1 = SourceModule("""
__global__ void gpu_a_trous_row_kernel(float *in1, float *in2, float *wfil, int *scale)
{
... |
logout and remove all session data | def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('main')) |
display some user info to show we have authenticated successfully | def info(request):
"""
display some user info to show we have authenticated successfully
"""
if check_key(request):
api = get_api(request)
user = api.users(id='self')
print dir(user)
return render_to_response('djfoursquare/info.html', {'user': user})
else:
ret... |
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to. | def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... |
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in seconds.
:param timeout_msg:
Message to raise in the ex... | def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in ... |
Get per-program state. | def get_state(self, caller):
"""
Get per-program state.
"""
if caller in self.state:
return self.state[caller]
else:
rv = self.state[caller] = DictObject()
return rv |
Value might be either name registered in System namespace, or object, either
StatusObject or Callable. If Callable, evaluate :meth:`.call` method. If StatusObject,
return status. | def call_eval(self, value, caller, return_value=True, **kwargs):
"""
Value might be either name registered in System namespace, or object, either
StatusObject or Callable. If Callable, evaluate :meth:`.call` method. If StatusObject,
return status.
"""
value = ... |
This function basically sets up :attr:`.system`, if it is not yet set up. After that,
other Callable initialization actions are performed.
:param init: value ``True`` is given when running this at the initialization phase. Then system
attribute is set already, but calla... | def setup_callable_system(self, system, init=False):
"""
This function basically sets up :attr:`.system`, if it is not yet set up. After that,
other Callable initialization actions are performed.
:param init: value ``True`` is given when running this at the initialization ph... |
Return object for given name registered in System namespace. | def name_to_system_object(self, value):
"""
Return object for given name registered in System namespace.
"""
if not self.system:
raise SystemNotReady
if isinstance(value, (str, Object)):
rv = self.system.name_to_system_object(value)
return rv ... |
Recursively collect all potential triggers/targets in this node and its children.
Define targets and triggers of this particular callable in :meth:`_give_triggers`
and :meth:`_give_targets`.
:param str target: valid values: ``'targets'`` and ``'triggers'`` | def collect(self, target):
"""Recursively collect all potential triggers/targets in this node and its children.
Define targets and triggers of this particular callable in :meth:`_give_triggers`
and :meth:`_give_targets`.
:param str target: valid values: ``'targets'`` and ``'triggers'``
... |
Recursively cancel all threaded background processes of this Callable.
This is called automatically for actions if program deactivates. | def cancel(self, caller):
"""
Recursively cancel all threaded background processes of this Callable.
This is called automatically for actions if program deactivates.
"""
for o in {i for i in self.children if isinstance(i, AbstractCallable)}:
o.cancel(caller) |
Give string representation of the callable. | def give_str(self):
"""
Give string representation of the callable.
"""
args = self._args[:]
kwargs = self._kwargs
return self._give_str(args, kwargs) |
Give indented string representation of the callable.
This is used in :ref:`automate-webui`. | def give_str_indented(self, tags=False):
"""
Give indented string representation of the callable.
This is used in :ref:`automate-webui`.
"""
args = self._args[:]
kwargs = self._kwargs
rv = self._give_str_indented(args, kwargs, tags)
if not tags:
... |
Prepares the request and catches common errors and returns tuple of data and the request response.
Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes
:param endpoint: full endpoint url
:type endpoint: str
:param params: parameters ... | def _make_request(self, endpoint, params):
"""
Prepares the request and catches common errors and returns tuple of data and the request response.
Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes
:param endpoint: full endpoint url... |
Creates a short url if valid
:param str long_url: The url to shorten.
:param custom_ending: The custom url to create if available.
:type custom_ending: str or None
:param bool is_secret: if not public, it's secret
:return: a short link
:rtype: str | def shorten(self, long_url, custom_ending=None, is_secret=False):
"""
Creates a short url if valid
:param str long_url: The url to shorten.
:param custom_ending: The custom url to create if available.
:type custom_ending: str or None
:param bool is_secret: if not public,... |
Returns the short url ending from a short url or an short url ending.
Example:
- Given `<your Polr server>/5N3f8`, return `5N3f8`.
- Given `5N3f8`, return `5N3f8`.
:param lookup_url: A short url or short url ending
:type lookup_url: str
:return: The url ending
... | def _get_ending(self, lookup_url):
"""
Returns the short url ending from a short url or an short url ending.
Example:
- Given `<your Polr server>/5N3f8`, return `5N3f8`.
- Given `5N3f8`, return `5N3f8`.
:param lookup_url: A short url or short url ending
:type ... |
Looks up the url_ending to obtain information about the short url.
If it exists, the API will return a dictionary with information, including
the long_url that is the destination of the given short url URL.
The lookup object looks like something like this:
.. code-block:: python
... | def lookup(self, lookup_url, url_key=None):
"""
Looks up the url_ending to obtain information about the short url.
If it exists, the API will return a dictionary with information, including
the long_url that is the destination of the given short url URL.
The lookup object look... |
The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the
central lobe of the PSF.
INPUTS:
psf (no default): Array containing the psf for the image in question.
cdelt1, cdelt2 (no default): Header of the psf. | def beam_fit(psf, cdelt1, cdelt2):
"""
The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the
central lobe of the PSF.
INPUTS:
psf (no default): Array containing the psf for the image in question.
cdelt1, cdelt2 (no default... |
Setup argparse arguments.
:return: The parser which :class:`MypolrCli` expects parsed arguments from.
:rtype: argparse.ArgumentParser | def make_argparser():
"""
Setup argparse arguments.
:return: The parser which :class:`MypolrCli` expects parsed arguments from.
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(prog='mypolr',
description="Interacts with the Polr Project's... |
This function estimates the noise using the MAD estimator.
INPUTS:
in1 (no default): The array from which the noise is estimated
OUTPUTS:
out1 An array of per-scale noise estimates. | def estimate_threshold(in1, edge_excl=0, int_excl=0):
"""
This function estimates the noise using the MAD estimator.
INPUTS:
in1 (no default): The array from which the noise is estimated
OUTPUTS:
out1 An array of per-scale noise estimates.
"""
... |
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 thresholded.
sigma_level (no default): The number of est... | 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.
INPUTS:
in1 (no default): Array containing the wavelet decomposition.
tolerance (no default): Percentage of maximum coefficient at which objects are deemed significant.
mode (default="cpu"):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 extr... | 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 extr... | 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.
INPUTS:
in1 (no default): Array containing values for signal 1.
in2 (no default): Array containing values for signal 2.
OUTPUTS:
out1 The ratio of the signal to noise ... | 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.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command exit code and output | 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.
:param resources: the resources to list, e.g. ``'vhosts'``
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command ... | 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.
:return:
A list of 2-element tuples. The first element is the queue name,
the second is the current queue size. | 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.
:return:
A list of 2-element tuples. The first element is the username, the
second a list of tags for the user. | 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.
.. note::
Only the configured database is removed. Any other databases
remain untouched. | 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.
:param command: the command to run (passed to ``-c``)
:param psql_opts: a list of extra options to pass to ``psql``
:returns: a tuple of the command exit code and output | 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.
Exceptions that can be ignored are found in mypolr.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.
:param output:
Container output bytes or an
:class:`docker.models.containers.ExecResult` instance.
:param encoding:
The encoding to use when converting bytes to unicode
... | 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.
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 if file doesn't
exist o... | 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 location for the file,
WeedFS volume is choosed randomly
:param integer volume_id: volume_id
:rtype: namedtuple `FileLocation` `{"public_url":"", "url":""}` | 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}/"
... |
Get url for the file
:param string fid: File ID
:param boolean public: public or internal url
:rtype: string | 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... |
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 | 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
Args:
**fid**: File identifier <volume_id>,<file_name_hash>
Returns:
True if file exists. False if not. | 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
:param string fid: File ID | 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
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 string name:
:rtype: string or None | 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
:param float threshold (optional): The threshold is optional, and
will not change the default threshold.
:rtype: boolean | 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
:rtype: string | 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.
INPUTS:
in1 (no default): Array containing one set of data, possibly an image.
in2 (no default): Gpuarray containing the FFT of the PSF.
... | 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.
INPUTS:
in1 (no default): The array on which the FFT is to be performed.
is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
store_on_gp... | 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.
INPUTS:
in1 (no default): The array on which the IFFT is to be performed.
is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
store_on_... | 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.
INPUTS:
in1 (no default): Input array which is to be padded.
OUTPUTS:
out1 Padded version of the input. | 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.
INPUTS:
in1 (no default): Array containing data which has been FFTed and IFFTed.
OUTPUTS:
in1 FFT-shifted version of in1. | 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.
INPUTS:
in1 (no default): Array containing data which has been padded.
OUTPUTS:
gpu_out1 Array containing unpadded, contiguous data. | 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.
INPUTS:
in1 (no default): Array containing data which is to be scaled. | 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.
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. | 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.
This does not directly change sta... | 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.
:param ~docker.models.containers.Container container:
Container who's log lines to stream.
:param timeout:
Timeout value in seconds.
:param logs_kwargs:
Additional keyword arguments to pass to ``container.logs()``. For
ex... | 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.
Each log line is decoded and any trailing whitespace is stripped before the
line is matched.
:param ~docker.models.containers.Container container:
Container who's log lines to wait... | 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.