text stringlengths 81 112k |
|---|
Decode SLIP message.
def decode(raw):
"""Decode SLIP message."""
return raw \
.replace(bytes([SLIP_ESC, SLIP_ESC_END]), bytes([SLIP_END])) \
.replace(bytes([SLIP_ESC, SLIP_ESC_ESC]), bytes([SLIP_ESC])) |
Encode SLIP message.
def encode(raw):
"""Encode SLIP message."""
return raw \
.replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
.replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END])) |
Get the next slip packet from raw data.
Returns the extracted packet plus the raw data with the remaining data stream.
def get_next_slip(raw):
"""
Get the next slip packet from raw data.
Returns the extracted packet plus the raw data with the remaining data stream.
"""
if not is_slip(raw):
... |
Enable house status monitor.
async def set_utc(pyvlx):
"""Enable house status monitor."""
setutc = SetUTC(pyvlx=pyvlx)
await setutc.do_api_call()
if not setutc.success:
raise PyVLXException("Unable to set utc.") |
Handle incoming API frame, return True if this was the expected frame.
async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if not isinstance(frame, FrameSetUTCConfirmation):
return False
self.success = True
return... |
Python implementation of ``calcbinflux``.
This is only used if ``synphot.synphot_utils`` C-extension
import fails.
See docstrings.py
def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw):
"""Python implementation of ``calcbinflux``.
This is only used if ``synphot.synphot_utils`` C-ext... |
Calculate the edges of wavelength bins given the centers.
The algorithm calculates bin edges as the midpoints between bin centers
and treats the first and last bins as symmetric about their centers.
Parameters
----------
centers : array-like or `~astropy.units.quantity.Quantity`
Sequence o... |
Calculate the widths of wavelengths bins given their edges.
Parameters
----------
edges : array-like or `~astropy.units.quantity.Quantity`
Sequence of bin edges. Must be 1D and have at least two values.
If not a Quantity, assumed to be in Angstrom.
Returns
-------
widths : `~as... |
Calculate the centers of wavelengths bins given their edges.
Parameters
----------
edges : array-like or `~astropy.units.quantity.Quantity`
Sequence of bin edges. Must be 1D and have at least two values.
If not a Quantity, assumed to be in Angstrom.
Returns
-------
centers : `~... |
Calculate the wavelength range covered by the given number of pixels
centered on the given central wavelength of the given bins.
Parameters
----------
bins : array-like
Wavelengths at bin centers, each centered on a pixel.
Must be 1D array.
cenwave : float
Desired central w... |
Calculate the number of pixels within the given wavelength range
and the given bins.
Parameters
----------
bins : array-like
Wavelengths at bin centers, each centered on a pixel.
Must be 1D array.
waverange : tuple of float
Lower and upper limits of the desired wavelength r... |
Connect to KLF 200.
async def connect(self):
"""Connect to KLF 200."""
PYVLXLOG.warning("Connecting to KLF 200.")
await self.connection.connect()
login = Login(pyvlx=self, password=self.config.password)
await login.do_api_call()
if not login.success:
raise Py... |
Retrieve version and protocol version from API.
async def update_version(self):
"""Retrieve version and protocol version from API."""
get_version = GetVersion(pyvlx=self)
await get_version.do_api_call()
if not get_version.success:
raise PyVLXException("Unable to retrieve ver... |
Send frame to API via connection.
async def send_frame(self, frame):
"""Send frame to API via connection."""
if not self.connection.connected:
await self.connect()
await self.update_version()
await set_utc(pyvlx=self)
await house_status_monitor_enable(pyv... |
Read scene from configuration.
def from_config(cls, pyvlx, item):
"""Read scene from configuration."""
name = item['name']
ident = item['id']
return cls(pyvlx, ident, name) |
Send api call.
async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False):
"""Send api call."""
if add_authorization_token and not self.token:
await self.refresh_token()
try:
return await self._api_call_impl(verb, action, params, add_... |
Refresh API token from KLF 200.
async def refresh_token(self):
"""Refresh API token from KLF 200."""
json_response = await self.api_call('auth', 'login', {'password': self.config.password}, add_authorization_token=False)
if 'token' not in json_response:
raise PyVLXException('no elem... |
Create http body for rest request.
def create_body(action, params):
"""Create http body for rest request."""
body = {}
body['action'] = action
if params is not None:
body['params'] = params
return body |
Evaluate rest response.
def evaluate_response(json_response):
"""Evaluate rest response."""
if 'errors' in json_response and json_response['errors']:
Interface.evaluate_errors(json_response)
elif 'result' not in json_response:
raise PyVLXException('no element result fou... |
Evaluate rest errors.
def evaluate_errors(json_response):
"""Evaluate rest errors."""
if 'errors' not in json_response or \
not isinstance(json_response['errors'], list) or \
not json_response['errors'] or \
not isinstance(json_response['errors'][0], int):
r... |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = bytes([self.node_id])
ret += string_to_bytes(self.name, 64)
return ret |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.node_id = payload[0]
self.name = bytes_to_string(payload[1:65]) |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.status = SetNodeNameConfirmationStatus(payload[0])
self.node_id = payload[1] |
Convert FrameGet[All]Node[s]InformationNotification into Node object.
def convert_frame_to_node(pyvlx, frame):
"""Convert FrameGet[All]Node[s]InformationNotification into Node object."""
# pylint: disable=too-many-return-statements
if frame.node_type == NodeTypeWithSubtype.WINDOW_OPENER:
return Win... |
Set temperature.
def temperature(self, what):
"""Set temperature."""
self._temperature = units.validate_quantity(what, u.K) |
Apply emissivity to an existing beam to produce a thermal
source spectrum (without optical counterpart).
Thermal source spectrum is calculated as follow:
#. Create a blackbody spectrum in PHOTLAM per square arcsec
with `temperature`.
#. Multiply the blackbody wit... |
Creates a thermal spectral element from file.
.. note::
Only FITS format is supported.
Parameters
----------
filename : str
Thermal spectral element filename.
temperature_key, beamfill_key : str
Keywords in FITS *table extension* that store... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.status = AllNodesInformationStatus(payload[0])
self.number_of_nodes = payload[1] |
Return Payload.
def get_payload(self):
"""Return Payload."""
payload = bytes()
payload += bytes([self.node_id])
payload += bytes([self.order >> 8 & 255, self.order & 255])
payload += bytes([self.placement])
payload += bytes(string_to_bytes(self.name, 64))
payload... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.node_id = payload[0]
self.order = payload[1] * 256 + payload[2]
self.placement = payload[3]
self.name = bytes_to_string(payload[4:68])
self.velocity = Velocity(payload[6... |
Set internal raw state from parameter.
def from_parameter(self, parameter):
"""Set internal raw state from parameter."""
if not isinstance(parameter, Parameter):
raise Exception("parameter::from_parameter_wrong_object")
self.raw = parameter.raw |
Create raw out of position vlaue.
def from_int(value):
"""Create raw out of position vlaue."""
if not isinstance(value, int):
raise PyVLXException("value_has_to_be_int")
if not Parameter.is_valid_int(value):
raise PyVLXException("value_out_of_range")
return bytes... |
Test if value can be rendered out of int.
def is_valid_int(value):
"""Test if value can be rendered out of int."""
if 0 <= value <= Parameter.MAX: # This includes ON and OFF
return True
if value == Parameter.UNKNOWN_VALUE:
return True
if value == Parameter.CURRE... |
Test if raw packets are valid for initialization of Position.
def from_raw(raw):
"""Test if raw packets are valid for initialization of Position."""
if not isinstance(raw, bytes):
raise PyVLXException("Position::raw_must_be_bytes")
if len(raw) != 2:
raise PyVLXException(... |
Create raw value out of percent position.
def from_percent(position_percent):
"""Create raw value out of percent position."""
if not isinstance(position_percent, int):
raise PyVLXException("Position::position_percent_has_to_be_int")
if position_percent < 0:
raise PyVLXEx... |
Return product as human readable string.
def product(self):
"""Return product as human readable string."""
if self.product_group == 14 and self.product_type == 3:
return "KLF 200"
return "Unknown Product: {}:{}".format(self.product_group, self.product_type) |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = self._software_version
ret += bytes([self.hardware_version, self.product_group, self.product_type])
return ret |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self._software_version = payload[0:6]
self.hardware_version = payload[6]
self.product_group = payload[7]
self.product_type = payload[8] |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = bytes([self.session_id >> 8 & 255, self.session_id & 255])
ret += bytes([self.originator.value])
ret += bytes([self.priority.value])
ret += bytes([self.scene_id])
ret += bytes([self.velocity.value])
... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.session_id = payload[0]*256 + payload[1]
self.originator = Originator(payload[2])
self.priority = Priority(payload[3])
self.scene_id = payload[4]
self.velocity = Velocit... |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = bytes([self.status.value])
ret += bytes([self.session_id >> 8 & 255, self.session_id & 255])
return ret |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.status = ActivateSceneConfirmationStatus(payload[0])
self.session_id = payload[1]*256 + payload[2] |
Return Payload.
def get_payload(self):
"""Return Payload."""
# Session id
ret = bytes([self.session_id >> 8 & 255, self.session_id & 255])
ret += bytes([self.originator.value])
ret += bytes([self.priority.value])
ret += bytes([0]) # ParameterActive pointing to main para... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.session_id = payload[0]*256 + payload[1]
self.originator = Originator(payload[2])
self.priority = Priority(payload[3])
len_node_ids = payload[41]
if len_node_ids > 20:
... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.session_id = payload[0]*256 + payload[1]
self.status = CommandSendConfirmationStatus(payload[2]) |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = bytes([self.session_id >> 8 & 255, self.session_id & 255])
ret += bytes([self.status_id])
ret += bytes([self.index_id])
ret += bytes([self.node_parameter])
ret += bytes([self.parameter_value >> 8 & 255, s... |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.session_id = payload[0]*256 + payload[1]
self.status_id = payload[2]
self.index_id = payload[3]
self.node_parameter = payload[4]
self.parameter_value = payload[5]*256 + ... |
Return Payload.
def get_payload(self):
"""Return Payload."""
ret = bytes([self.session_id >> 8 & 255, self.session_id & 255])
ret += bytes([self.index_id])
ret += bytes([self.node_parameter])
ret += bytes([self.seconds >> 8 & 255, self.seconds & 255])
return ret |
Init frame from binary data.
def from_payload(self, payload):
"""Init frame from binary data."""
self.session_id = payload[0]*256 + payload[1]
self.index_id = payload[2]
self.node_parameter = payload[3]
self.seconds = payload[4]*256 + payload[5] |
Log packets from Bus.
async def main(loop):
"""Log packets from Bus."""
# Setting debug
PYVLXLOG.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
PYVLXLOG.addHandler(stream_handler)
# Connecting to KLF 200
pyvlx = PyVLX('pyvlx.yaml... |
Change name of node.
async def rename(self, name):
"""Change name of node."""
set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name)
await set_node_name.do_api_call()
if not set_node_name.success:
raise PyVLXException("Unable to rename node")
... |
Set window to desired position.
Parameters:
* position: Position object containing the target position.
* wait_for_completion: If set, function will return
after device has reached target position.
async def set_position(self, position, wait_for_completion=True):
... |
Open window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
async def open(self, wait_for_completion=True):
"""Open window.
Parameters:
* wait_for_completion: If set, function will return
... |
Close window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
async def close(self, wait_for_completion=True):
"""Close window.
Parameters:
* wait_for_completion: If set, function will return
... |
Stop window.
Parameters:
* wait_for_completion: If set, function will return
after device has reached target position.
async def stop(self, wait_for_completion=True):
"""Stop window.
Parameters:
* wait_for_completion: If set, function will return
... |
Return sampleset of a model or `None` if undefined.
Model could be a real model or evaluated sampleset.
def _get_sampleset(model):
"""Return sampleset of a model or `None` if undefined.
Model could be a real model or evaluated sampleset."""
if isinstance(model, Model):
if hasattr(model, 'sample... |
Simple merge of samplesets.
def _merge_sampleset(model1, model2):
"""Simple merge of samplesets."""
w1 = _get_sampleset(model1)
w2 = _get_sampleset(model2)
return merge_wavelengths(w1, w2) |
One of the models is either ``RedshiftScaleFactor`` or ``Scale``.
Possible combos::
RedshiftScaleFactor | Model
Scale | Model
Model | Scale
def _shift_wavelengths(model1, model2):
"""One of the models is either ``RedshiftScaleFactor`` or ``Scale``.
Possible combos::
Reds... |
Get optimal wavelengths for sampling a given model.
Parameters
----------
model : `~astropy.modeling.Model`
Model.
Returns
-------
waveset : array-like or `None`
Optimal wavelengths. `None` if undefined.
Raises
------
synphot.exceptions.SynphotError
Invalid... |
Return metadata of a model.
Model could be a real model or evaluated metadata.
def _get_meta(model):
"""Return metadata of a model.
Model could be a real model or evaluated metadata."""
if isinstance(model, Model):
w = model.meta
else:
w = model # Already metadata
return w |
Simple merge of samplesets.
def _merge_meta(model1, model2):
"""Simple merge of samplesets."""
w1 = _get_meta(model1)
w2 = _get_meta(model2)
return metadata.merge(w1, w2, metadata_conflicts='silent') |
Get metadata for a given model.
Parameters
----------
model : `~astropy.modeling.Model`
Model.
Returns
-------
metadata : dict
Metadata for the model.
Raises
------
synphot.exceptions.SynphotError
Invalid model.
def get_metadata(model):
"""Get metadata... |
Peak wavelength in Angstrom when the curve is expressed as
power density.
def lambda_max(self):
"""Peak wavelength in Angstrom when the curve is expressed as
power density."""
return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).value |
Tuple defining the default ``bounding_box`` limits,
``(x_low, x_high)``.
.. math::
x_{\\textnormal{low}} = 0
x_{\\textnormal{high}} = \\log(\\lambda_{\\textnormal{max}} \\;\
(1 + \\textnormal{factor}))
Parameters
----------
factor : float
... |
Return ``x`` array that samples the feature.
Parameters
----------
factor_bbox : float
Factor for ``bounding_box`` calculations.
num : int
Number of points to generate.
def sampleset(self, factor_bbox=10.0, num=1000):
"""Return ``x`` array that samples ... |
Evaluate the model.
Parameters
----------
x : number or ndarray
Wavelengths in Angstrom.
temperature : number
Temperature in Kelvin.
Returns
-------
y : number or ndarray
Blackbody radiation in PHOTLAM per steradian.
def eva... |
Evaluate the model.
Parameters
----------
x : number or ndarray
Wavelengths in Angstrom.
temperature : number
Temperature in Kelvin.
Returns
-------
y : number or ndarray
Blackbody radiation in PHOTLAM.
def evaluate(self, x,... |
Calculate sampleset for each model.
def _calc_sampleset(w1, w2, step, minimal):
"""Calculate sampleset for each model."""
if minimal:
arr = [w1 - step, w1, w2, w2 + step]
else:
arr = np.arange(w1 - step, w2 + step + step, step)
return arr |
Return ``x`` array that samples the feature.
Parameters
----------
step : float
Distance of first and last points w.r.t. bounding box.
minimal : bool
Only return the minimal points needed to define the box;
i.e., box edges and a point outside on each... |
One dimensional constant flux model function.
Parameters
----------
x : number or ndarray
Wavelengths in Angstrom.
Returns
-------
y : number or ndarray
Flux in PHOTLAM.
def evaluate(self, x, *args):
"""One dimensional constant flux mode... |
Remove negative flux.
def _process_neg_flux(self, x, y):
"""Remove negative flux."""
if self._keep_neg: # Nothing to do
return y
old_y = None
if np.isscalar(y): # pragma: no cover
if y < 0:
n_neg = 1
old_x = x
... |
Evaluate the model.
Parameters
----------
inputs : number or ndarray
Wavelengths in same unit as ``points``.
Returns
-------
y : number or ndarray
Flux or throughput in same unit as ``lookup_table``.
def evaluate(self, inputs):
"""Evalua... |
GaussianAbsorption1D model function.
def evaluate(x, amplitude, mean, stddev):
"""
GaussianAbsorption1D model function.
"""
return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev) |
GaussianAbsorption1D model function derivatives.
def fit_deriv(x, amplitude, mean, stddev):
"""
GaussianAbsorption1D model function derivatives.
"""
import operator
return list(map(
operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev))) |
Return ``x`` array that samples the feature.
Parameters
----------
factor_step : float
Factor for sample step calculation. The step is calculated
using ``factor_step * self.fwhm``.
kwargs : dict
Keyword(s) for ``bounding_box`` calculation.
def sampl... |
Return flux in PHOTLAM. Assume input wavelength is in Angstrom.
def evaluate(self, x, *args):
"""Return flux in PHOTLAM. Assume input wavelength is in Angstrom."""
xx = x / self.x_0
y = (self.amplitude * xx ** (-self.alpha)) * self._flux_unit
flux = units.convert_flux(x, y, units.PHOTLA... |
Return ``x`` array that samples the feature.
def sampleset(self):
"""Return ``x`` array that samples the feature."""
x1, x4 = self.bounding_box
dw = self.width * 0.5
x2 = self.x_0 - dw
x3 = self.x_0 + dw
if self._n_models == 1:
w = [x1, x2, x3, x4]
e... |
From the given request, add a snippet to the page.
def get_payment_request(self, cart, request):
"""
From the given request, add a snippet to the page.
"""
try:
self.charge(cart, request)
thank_you_url = OrderModel.objects.get_latest_url()
js_expressi... |
Use the Stripe token from the request and charge immediately.
This view is invoked by the Javascript function `scope.charge()` delivered
by `get_payment_request`.
def charge(self, cart, request):
"""
Use the Stripe token from the request and charge immediately.
This view is invo... |
Refund the payment using Stripe's refunding API.
def refund_payment(self):
"""
Refund the payment using Stripe's refunding API.
"""
Money = MoneyMaker(self.currency)
filter_kwargs = {
'transaction_id__startswith': 'ch_',
'payment_method': StripePayment.na... |
Create an instance of the US Weather Forecast Service with
typical starting settings.
def create(self):
"""
Create an instance of the US Weather Forecast Service with
typical starting settings.
"""
self.service.create()
# Set env vars for immediate use
z... |
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry app.
def add_to_manifest(self, manifest):
"""
... |
Creating this service is handled asynchronously so this method will
simply check if the create is in progress. If it is not in progress,
we could probably infer it either failed or succeeded.
def _create_in_progress(self):
"""
Creating this service is handled asynchronously so this met... |
Create an instance of the Predix Cache Service with they typical
starting settings.
:param max_wait: service is created asynchronously, so will only wait
this number of seconds before giving up.
def create(self, max_wait=180, **kwargs):
"""
Create an instance of the Predix ... |
Add useful details to the manifest about this service so
that it can be used in an application.
:param manifest: A predix.admin.app.Manifest object instance
that manages reading/writing manifest config for a
cloud foundry app.
def add_to_manifest(self, manifest):
"""
... |
Will return the uri for an existing instance.
def _get_uri(self):
"""
Will return the uri for an existing instance.
"""
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['uri'] |
Will return the zone id for an existing instance.
def _get_zone_id(self):
"""
Will return the zone id for an existing instance.
"""
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['zone']['http-header-va... |
Create an instance of the Access Control Service with the typical
starting settings.
def create(self):
"""
Create an instance of the Access Control Service with the typical
starting settings.
"""
self.service.create()
# Set environment variables for immediate us... |
Grant the given client id all the scopes and authorities
needed to work with the access control service.
def grant_client(self, client_id):
"""
Grant the given client id all the scopes and authorities
needed to work with the access control service.
"""
zone = self.servic... |
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry app.
def add_to_manifest(self, manifest):
"""
... |
Generic GET with headers
def get(self, path):
"""
Generic GET with headers
"""
uri = self.config.get_target() + path
headers = self._get_headers()
logging.debug("URI=GET " + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(... |
Generic POST with headers
def post(self, path, data):
"""
Generic POST with headers
"""
uri = self.config.get_target() + path
headers = self._post_headers()
logging.debug("URI=POST " + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BOD... |
Generic DELETE with headers
def delete(self, path, data=None, params=None):
"""
Generic DELETE with headers
"""
uri = self.config.get_target() + path
headers = {
'Authorization': self.config.get_access_token()
}
logging.debug("URI=DELETE " + str(... |
Returns a flat list of the names for the organizations
user belongs.
def get_orgs(self):
"""
Returns a flat list of the names for the organizations
user belongs.
"""
orgs = []
for resource in self._get_orgs()['resources']:
orgs.append(resource['entity... |
Returns a flat list of the names for the apps in
the organization.
def get_apps(self):
"""
Returns a flat list of the names for the apps in
the organization.
"""
apps = []
for resource in self._get_apps()['resources']:
apps.append(resource['entity']['... |
Calls CF's associate user with org. Valid roles include `user`, `auditor`,
`manager`,`billing_manager`
def add_user(self, user_name, role='user'):
"""
Calls CF's associate user with org. Valid roles include `user`, `auditor`,
`manager`,`billing_manager`
"""
role_uri = se... |
Calls CF's remove user with org
def remove_user(self, user_name, role):
"""
Calls CF's remove user with org
"""
role_uri = self._get_role_uri(role=role)
return self.api.delete(path=role_uri, data={'username': user_name}) |
add messages to the rx_queue
:param id: str message Id
:param body: str the message body
:param tags: dict[string->string] tags to be associated with the message
:return: self
def add_message(self, id, body, tags=False):
"""
add messages to the rx_queue
:param id... |
Publish all messages that have been added to the queue for configured protocol
:return: None
def publish_queue(self):
"""
Publish all messages that have been added to the queue for configured protocol
:return: None
"""
self.last_send_time = time.time()
try:
... |
generator for acks to yield messages to the user in a async configuration
:return: messages as they come in
def ack_generator(self):
"""
generator for acks to yield messages to the user in a async configuration
:return: messages as they come in
"""
if self.config.is_sync... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.