text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_remote_spec(filename, encoding='binary', cache=True, show_progress=True, **kwargs):
"""Read FITS or ASCII spectrum from a remote location. Parameters fi... |
with get_readable_fileobj(filename, encoding=encoding, cache=cache,
show_progress=show_progress) as fd:
header, wavelengths, fluxes = read_spec(fd, fname=filename, **kwargs)
return header, wavelengths, fluxes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_spec(filename, fname='', **kwargs):
"""Read FITS or ASCII spectrum. Parameters filename : str or file pointer Spectrum file name or pointer. fname : str... |
if isinstance(filename, str):
fname = filename
elif not fname: # pragma: no cover
raise exceptions.SynphotError('Cannot determine filename.')
if fname.endswith('fits') or fname.endswith('fit'):
read_func = read_fits_spec
else:
read_func = read_ascii_spec
return re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ascii_spec(filename, wave_unit=u.AA, flux_unit=units.FLAM, **kwargs):
"""Read ASCII spectrum. ASCII table must have following columns: #. Wavelength dat... |
header = {}
dat = ascii.read(filename, **kwargs)
wave_unit = units.validate_unit(wave_unit)
flux_unit = units.validate_unit(flux_unit)
wavelengths = dat.columns[0].data.astype(np.float64) * wave_unit
fluxes = dat.columns[1].data.astype(np.float64) * flux_unit
return header, wavelengths,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_fits_spec(filename, ext=1, wave_col='WAVELENGTH', flux_col='FLUX', wave_unit=u.AA, flux_unit=units.FLAM):
"""Read FITS spectrum. Wavelength and flux uni... |
fs = fits.open(filename)
header = dict(fs[str('PRIMARY')].header)
wave_dat = fs[ext].data.field(wave_col).copy()
flux_dat = fs[ext].data.field(flux_col).copy()
fits_wave_unit = fs[ext].header.get('TUNIT1')
fits_flux_unit = fs[ext].header.get('TUNIT2')
if fits_wave_unit is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spectral_density_vega(wav, vegaflux):
"""Flux equivalencies between PHOTLAM and VEGAMAG. Parameters wav : `~astropy.units.quantity.Quantity` Quantity associa... |
vega_photlam = vegaflux.to(
PHOTLAM, equivalencies=u.spectral_density(wav)).value
def converter(x):
"""Set nan/inf to -99 mag."""
val = -2.5 * np.log10(x / vega_photlam)
result = np.zeros(val.shape, dtype=np.float64) - 99
mask = np.isfinite(val)
if result.ndim >... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_unit(input_unit):
"""Validate unit. To be compatible with existing SYNPHOT data files: * 'angstroms' and 'inversemicrons' are accepted although unre... |
if isinstance(input_unit, str):
input_unit_lowcase = input_unit.lower()
# Backward-compatibility
if input_unit_lowcase == 'angstroms':
output_unit = u.AA
elif input_unit_lowcase == 'inversemicrons':
output_unit = u.micron ** -1
elif input_unit_lowcas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, device):
"""Add device.""" |
if not isinstance(device, Device):
raise TypeError()
self.__devices.append(device) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_import(self, json_response):
"""Import data from json response.""" |
if 'data' not in json_response:
raise PyVLXException('no element data found: {0}'.format(
json.dumps(json_response)))
data = json_response['data']
for item in data:
if 'category' not in item:
raise PyVLXException('no element category: {0}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_window_opener(self, item):
"""Load window opener from JSON.""" |
window = Window.from_config(self.pyvlx, item)
self.add(window) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_roller_shutter(self, item):
"""Load roller shutter from JSON.""" |
rollershutter = RollerShutter.from_config(self.pyvlx, item)
self.add(rollershutter) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_blind(self, item):
"""Load blind from JSON.""" |
blind = Blind.from_config(self.pyvlx, item)
self.add(blind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_terminal_size(fallback=(80, 24)):
""" Return tuple containing columns and rows of controlling terminal, trying harder than shutil.get_terminal_size to fi... |
for stream in [sys.__stdout__, sys.__stderr__, sys.__stdin__]:
try:
# Make WINSIZE call to terminal
data = fcntl.ioctl(stream.fileno(), TIOCGWINSZ, b"\x00\x00\00\x00")
except OSError:
pass
else:
# Unpack two shorts from ioctl call
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_json(self):
""" Run checks on self.files, printing json object containing information relavent to the CS50 IDE plugin at the end. """ |
checks = {}
for file in self.files:
try:
results = self._check(file)
except Error as e:
checks[file] = {
"error": e.msg
}
else:
checks[file] = {
"score": results.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_score(self):
""" Run checks on self.files, printing raw percentage to stdout. """ |
diffs = 0
lines = 0
for file in self.files:
try:
results = self._check(file)
except Error as e:
termcolor.cprint(e.msg, "yellow", file=sys.stderr)
continue
diffs += results.diffs
lines += results.l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check(self, file):
""" Run apropriate check based on `file`'s extension and return it, otherwise raise an Error """ |
if not os.path.exists(file):
raise Error("file \"{}\" not found".format(file))
_, extension = os.path.splitext(file)
try:
check = self.extension_map[extension[1:]]
except KeyError:
magic_type = magic.from_file(file)
for name, cls in self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_diff(old, new):
""" Returns a generator yielding the side-by-side diff of `old` and `new`). """ |
return map(lambda l: l.rstrip(),
icdiff.ConsoleDiff(cols=COLUMNS).make_table(old.splitlines(), new.splitlines())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unified(old, new):
""" Returns a generator yielding a unified diff between `old` and `new`. """ |
for diff in difflib.ndiff(old.splitlines(), new.splitlines()):
if diff[0] == " ":
yield diff
elif diff[0] == "?":
continue
else:
yield termcolor.colored(diff, "red" if diff[0] == "-" else "green", attrs=["bold"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def char_diff(self, old, new):
""" Return color-coded character-based diff between `old` and `new`. """ |
def color_transition(old_type, new_type):
new_color = termcolor.colored("", None, "on_red" if new_type ==
"-" else "on_green" if new_type == "+" else None)
return "{}{}".format(termcolor.RESET, new_color[:-len(termcolor.RESET)])
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _char_diff(self, old, new, transition, fmt=lambda c: c):
""" Returns a char-based diff between `old` and `new` where each character is formatted by `fmt` and... |
differ = difflib.ndiff(old, new)
# Type of difference.
dtype = None
# Buffer for current line.
line = []
while True:
# Get next diff or None if we're at the end.
d = next(differ, (None,))
if d[0] != dtype:
line += tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frame_from_raw(raw):
"""Create and return frame from raw bytes.""" |
command, payload = extract_from_frame(raw)
frame = create_frame(command)
if frame is None:
PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
return None
frame.validate_payload_len(payload)
frame.from_payload(payload)
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_frame(command):
"""Create and return empty Frame from Command.""" |
# pylint: disable=too-many-branches,too-many-return-statements
if command == Command.GW_ERROR_NTF:
return FrameErrorNotification()
if command == Command.GW_COMMAND_SEND_REQ:
return FrameCommandSendRequest()
if command == Command.GW_COMMAND_SEND_CFM:
return FrameCommandSendConfir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_received(self, data):
"""Handle data received.""" |
self.tokenizer.feed(data)
while self.tokenizer.has_tokens():
raw = self.tokenizer.get_next_token()
frame = frame_from_raw(raw)
if frame is not None:
self.frame_received_cb(frame) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def connect(self):
"""Connect to gateway via SSL.""" |
tcp_client = TCPTransport(self.frame_received_cb, self.connection_closed_cb)
self.transport, _ = await self.loop.create_connection(
lambda: tcp_client,
host=self.config.host,
port=self.config.port,
ssl=self.create_ssl_context())
self.connected = T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, frame):
"""Write frame to Bus.""" |
if not isinstance(frame, FrameBase):
raise PyVLXException("Frame not of type FrameBase", frame_type=type(frame))
PYVLXLOG.debug("SEND: %s", frame)
self.transport.write(slip_pack(bytes(frame))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_ssl_context():
"""Create and return SSL Context.""" |
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frame_received_cb(self, frame):
"""Received message.""" |
PYVLXLOG.debug("REC: %s", frame)
for frame_received_cb in self.frame_received_cbs:
# pylint: disable=not-callable
self.loop.create_task(frame_received_cb(frame)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def process_frame(self, frame):
"""Update nodes via frame, usually received by house monitor.""" |
if isinstance(frame, FrameNodeStatePositionChangedNotification):
if frame.node_id not in self.pyvlx.nodes:
return
node = self.pyvlx.nodes[frame.node_id]
if isinstance(node, OpeningDevice):
node.position = Position(frame.current_position)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, scene):
"""Add scene, replace existing scene if scene with scene_id is present.""" |
if not isinstance(scene, Scene):
raise TypeError()
for i, j in enumerate(self.__scenes):
if j.scene_id == scene.scene_id:
self.__scenes[i] = scene
return
self.__scenes.append(scene) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def best_prefix(bytes, system=NIST):
"""Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. ... |
if isinstance(bytes, Bitmath):
value = bytes.bytes
else:
value = bytes
return Byte(value).best_prefix(system=system) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_device_capacity(device_fd):
"""Create bitmath instances of the capacity of a system block device Make one or more ioctl request to query the capacity o... |
if os_name() != 'posix':
raise NotImplementedError("'bitmath.query_device_capacity' is not supported on this platform: %s" % os_name())
s = os.stat(device_fd.name).st_mode
if not stat.S_ISBLK(s):
raise ValueError("The file descriptor provided is not of a device type")
# The keys of th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_string(s):
"""Parse a string with units and try to make a bitmath object out of it. String inputs may include whitespace characters between the value a... |
# Strings only please
if not isinstance(s, (str, unicode)):
raise ValueError("parse_string only accepts string inputs but a %s was given" %
type(s))
# get the index of the first alphabetic character
try:
index = list([i.isalpha() for i in s]).index(True)
ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_string_unsafe(s, system=SI):
"""Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate ... |
if not isinstance(s, (str, unicode)) and \
not isinstance(s, numbers.Number):
raise ValueError("parse_string_unsafe only accepts string/number inputs but a %s was given" %
type(s))
######################################################################
# Is the input... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(fmt_str=None, plural=False, bestprefix=False):
"""Context manager for printing bitmath instances. ``fmt_str`` - a formatting mini-language compat form... |
if 'bitmath' not in globals():
import bitmath
if plural:
orig_fmt_plural = bitmath.format_plural
bitmath.format_plural = True
if fmt_str:
orig_fmt_str = bitmath.format_string
bitmath.format_string = fmt_str
yield
if plural:
bitmath.format_plural =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli_script_main(cli_args):
""" A command line interface to basic bitmath operations. """ |
choices = ALL_UNIT_TYPES
parser = argparse.ArgumentParser(
description='Converts from one type of size to another.')
parser.add_argument('--from-stdin', default=False, action='store_true',
help='Reads number from stdin rather than the cli')
parser.add_argument(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_setup(self):
"""Setup basic parameters for this class. `base` is the numeric base which when raised to `power` is equivalent to 1 unit of the correspondi... |
(self._base, self._power, self._name_singular, self._name_plural) = self._setup()
self._unit_value = self._base ** self._power |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix type. :param number value: The input value to be normalized :raise... |
if isinstance(value, self.valid_types):
self._byte_value = value * self._unit_value
self._bit_value = self._byte_value * 8.0
else:
raise ValueError("Initialization value '%s' is of an invalid type: %s. "
"Must be one of %s" % (
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def system(self):
"""The system of units used to measure an instance""" |
if self._base == 2:
return "NIST"
elif self._base == 10:
return "SI"
else:
# I don't expect to ever encounter this logic branch, but
# hey, it's better to have extra test coverage than
# insufficient test coverage.
raise Va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_other(cls, item):
"""Factory function to return instances of `item` converted into a new instance of ``cls``. Because this is a class method, it may be ... |
if isinstance(item, Bitmath):
return cls(bits=item.bits)
else:
raise ValueError("The provided items must be a valid bitmath class: %s" %
str(item.__class__)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(self, fmt):
"""Return a representation of this instance formatted with user supplied syntax""" |
_fmt_params = {
'base': self.base,
'bin': self.bin,
'binary': self.binary,
'bits': self.bits,
'bytes': self.bytes,
'power': self.power,
'system': self.system,
'unit': self.unit,
'unit_plural': self.unit_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix type""" |
self._bit_value = value * self._unit_value
self._byte_value = self._bit_value / 8.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_from_frame(data):
"""Extract payload and command from frame.""" |
if len(data) <= 4:
raise PyVLXException("could_not_extract_from_frame_too_short", data=data)
length = data[0] * 256 + data[1] - 1
if len(data) != length + 3:
raise PyVLXException("could_not_extract_from_frame_invalid_length", data=data, current_length=len(data), expected_length=length + 3)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_meta(obj):
"""Extract metadata, if any, from given object.""" |
if hasattr(obj, 'meta'): # Spectrum or model
meta = deepcopy(obj.meta)
elif isinstance(obj, dict): # Metadata
meta = deepcopy(obj)
else: # Number
meta = {}
return meta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_meta(left, right, result, clean=True):
"""Merge metadata from left and right onto results. This is used during class initialization. This should also ... |
# Copies are returned because they need some clean-up below.
left = BaseSpectrum._get_meta(left)
right = BaseSpectrum._get_meta(right)
# Remove these from going into result to avoid mess.
# header = FITS header metadata
# expr = ASTROLIB PYSYNPHOT expression
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_generic_param(pval, def_unit, equivalencies=[]):
"""Process generic model parameter.""" |
if isinstance(pval, u.Quantity):
outval = pval.to(def_unit, equivalencies).value
else: # Assume already in desired unit
outval = pval
return outval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_wave_param(self, pval):
"""Process individual model parameter representing wavelength.""" |
return self._process_generic_param(
pval, self._internal_wave_unit, equivalencies=u.spectral()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waveset(self):
"""Optimal wavelengths for sampling the spectrum or bandpass.""" |
w = get_waveset(self.model)
if w is not None:
utils.validate_wavelengths(w)
w = w * self._internal_wave_unit
return w |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waverange(self):
"""Range of `waveset`.""" |
if self.waveset is None:
x = [None, None]
else:
x = u.Quantity([self.waveset.min(), self.waveset.max()])
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_wavelengths(self, wave):
"""Validate wavelengths for sampling.""" |
if wave is None:
if self.waveset is None:
raise exceptions.SynphotError(
'self.waveset is undefined; '
'Provide wavelengths for sampling.')
wavelengths = self.waveset
else:
w = self._process_wave_param(wave)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def integrate(self, wavelengths=None, **kwargs):
"""Perform integration. This uses any analytical integral that the underlying model has (i.e., ``self.model.inte... |
# Cannot integrate per Hz units natively across wavelength
# without converting them to per Angstrom unit first, so
# less misleading to just disallow that option for now.
if 'flux_unit' in kwargs:
self._validate_flux_unit(kwargs['flux_unit'], wav_only=True)
x = sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def force_extrapolation(self):
"""Force the underlying model to extrapolate. An example where this is useful: You create a source spectrum with non-default extra... |
# We use _model here in case the spectrum is redshifted.
if isinstance(self._model, Empirical1D):
self._model.fill_value = np.nan
is_forced = True
else:
is_forced = False
return is_forced |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def taper(self, wavelengths=None):
"""Taper the spectrum or bandpass. The wavelengths to use for the first and last points are calculated by using the same ratio... |
x = self._validate_wavelengths(wavelengths)
# Calculate new end points for tapering
w1 = x[0] ** 2 / x[1]
w2 = x[-1] ** 2 / x[-2]
# Special handling for empirical data.
# This is to be compatible with ASTROLIB PYSYNPHOT behavior.
if isinstance(self._model, Empi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_arrays(self, wavelengths, **kwargs):
"""Get sampled spectrum or bandpass in user units.""" |
x = self._validate_wavelengths(wavelengths)
y = self(x, **kwargs)
if isinstance(wavelengths, u.Quantity):
w = x.to(wavelengths.unit, u.spectral())
else:
w = x
return w, y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_plot(x, y, title='', xlog=False, ylog=False, left=None, right=None, bottom=None, top=None, save_as=''):
# pragma: no cover """Plot worker. Parameters x, ... |
try:
import matplotlib.pyplot as plt
except ImportError:
log.error('No matplotlib installation found; plotting disabled '
'as a result.')
return
fig, ax = plt.subplots()
ax.plot(x, y)
# Custom wavelength limits
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_flux_param(self, pval, wave):
"""Process individual model parameter representing flux.""" |
if isinstance(pval, u.Quantity):
self._validate_flux_unit(pval.unit)
outval = units.convert_flux(self._redshift_model(wave), pval,
self._internal_flux_unit).value
else: # Assume already in internal unit
outval = pval
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model(self):
"""Model of the spectrum with given redshift.""" |
if self.z == 0:
m = self._model
else:
# wavelength
if self._internal_wave_unit.physical_type == 'length':
rs = self._redshift_model.inverse
# frequency or wavenumber
# NOTE: This will never execute as long as internal wavelengt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def z(self, what):
"""Change redshift.""" |
if not isinstance(what, numbers.Real):
raise exceptions.SynphotError(
'Redshift must be a real scalar number.')
self._z = float(what)
self._redshift_model = RedshiftScaleFactor(self._z)
if self.z_type == 'wavelength_only':
self._redshift_flux_mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_fits(self, filename, wavelengths=None, flux_unit=None, area=None, vegaspec=None, **kwargs):
"""Write the spectrum to a FITS file. Parameters filename : st... |
w, y = self._get_arrays(wavelengths, flux_unit=flux_unit, area=area,
vegaspec=vegaspec)
# There are some standard keywords that should be added
# to the extension header.
bkeys = {'tdisp1': 'G15.7', 'tdisp2': 'G15.7'}
if 'expr' in self.meta:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename, keep_neg=False, **kwargs):
"""Create a spectrum from file. If filename has 'fits' or 'fit' suffix, it is read as FITS. Otherwise, it... |
header, wavelengths, fluxes = specio.read_spec(filename, **kwargs)
return cls(Empirical1D, points=wavelengths, lookup_table=fluxes,
keep_neg=keep_neg, meta={'header': header}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename, **kwargs):
"""Creates a bandpass from file. If filename has 'fits' or 'fit' suffix, it is read as FITS. Otherwise, it is read as ASC... |
if 'flux_unit' not in kwargs:
kwargs['flux_unit'] = cls._internal_flux_unit
if ((filename.endswith('fits') or filename.endswith('fit')) and
'flux_col' not in kwargs):
kwargs['flux_col'] = 'THROUGHPUT'
header, wavelengths, throughput = specio.read_spec(f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_bins(self, binset):
"""Calculated binned wavelength centers, edges, and flux. By contrast, the native waveset and flux should be considered samples of ... |
if binset is None:
if self.bandpass.waveset is not None:
self._binset = self.bandpass.waveset
elif self.spectrum.waveset is not None:
self._binset = self.spectrum.waveset
log.info('Bandpass waveset is undefined; '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_binned(self, wavelengths=None, flux_unit=None, **kwargs):
"""Sample binned observation without interpolation. To sample unbinned data, use ``__call__`... |
x = self._validate_binned_wavelengths(wavelengths)
i = np.searchsorted(self.binset, x)
if not np.allclose(self.binset[i].value, x.value):
raise exceptions.InterpolationNotAllowed(
'Some or all wavelength values are not in binset.')
y = self.binflux[i]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_binned_arrays(self, wavelengths, flux_unit, area=None, vegaspec=None):
"""Get binned observation in user units.""" |
x = self._validate_binned_wavelengths(wavelengths)
y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area,
vegaspec=vegaspec)
if isinstance(wavelengths, u.Quantity):
w = x.to(wavelengths.unit, u.spectral())
else:
w = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binned_waverange(self, cenwave, npix, **kwargs):
"""Calculate the wavelength range covered by the given number of pixels centered on the given central wavele... |
# Calculation is done in the unit of cenwave.
if not isinstance(cenwave, u.Quantity):
cenwave = cenwave * self._internal_wave_unit
bin_wave = units.validate_quantity(
self.binset, cenwave.unit, equivalencies=u.spectral())
return binning.wave_range(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binned_pixelrange(self, waverange, **kwargs):
"""Calculate the number of pixels within the given wavelength range and `binset`. Parameters waverange : tuple ... |
x = units.validate_quantity(
waverange, self._internal_wave_unit, equivalencies=u.spectral())
return binning.pixel_range(self.binset.value, x.value, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, binned=True, wavelengths=None, flux_unit=None, area=None, vegaspec=None, **kwargs):
# pragma: no cover """Plot the observation. .. note:: Uses ``m... |
if binned:
w, y = self._get_binned_arrays(wavelengths, flux_unit, area=area,
vegaspec=vegaspec)
else:
w, y = self._get_arrays(wavelengths, flux_unit=flux_unit,
area=area, vegaspec=vegaspec)
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_spectrum(self, binned=True, wavelengths=None):
"""Reduce the observation to an empirical source spectrum. An observation is a complex object with some res... |
if binned:
w, y = self._get_binned_arrays(
wavelengths, self._internal_flux_unit)
else:
w, y = self._get_arrays(
wavelengths, flux_unit=self._internal_flux_unit)
header = {'observation': str(self), 'binned': binned}
return SourceS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def do_api_call(self):
"""Start. Sending and waiting for answer.""" |
self.pyvlx.connection.register_frame_received_cb(
self.response_rec_callback)
await self.send_frame()
await self.start_timeout()
await self.response_received_or_timeout.wait()
await self.stop_timeout()
self.pyvlx.connection.unregister_frame_received_cb(self.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def start_timeout(self):
"""Start timeout.""" |
self.timeout_handle = self.pyvlx.connection.loop.call_later(
self.timeout_in_seconds, self.timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def main():
"""Load devices and scenes, run first scene.""" |
pyvlx = PyVLX('pyvlx.yaml')
# Alternative:
# pyvlx = PyVLX(host="192.168.2.127", password="velux123", timeout=60)
await pyvlx.load_devices()
print(pyvlx.devices[1])
print(pyvlx.devices['Fenster 4'])
await pyvlx.load_scenes()
print(pyvlx.scenes[0])
print(pyvlx.scenes['Bath Closed']... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def set_state(self, parameter):
"""Set switch to desired state.""" |
command_send = CommandSend(pyvlx=self.pyvlx, node_id=self.node_id, parameter=parameter)
await command_send.do_api_call()
if not command_send.success:
raise PyVLXException("Unable to send command")
self.parameter = parameter
await self.after_update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def etau_madau(wave, z, **kwargs):
"""Madau 1995 extinction for a galaxy at given redshift. This is the Lyman-alpha prescription from the photo-z code BPZ. The L... |
if not isinstance(z, numbers.Real):
raise exceptions.SynphotError(
'Redshift must be a real scalar number.')
if np.isscalar(wave) or len(wave) <= 1:
raise exceptions.SynphotError('Wavelength has too few data points')
wave = units.validate_quantity(wave, u.AA, **kwargs).value
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extinction_curve(self, ebv, wavelengths=None):
"""Generate extinction curve. .. math:: A(V) = R(V) \\; \\times \\; E(B-V) THRU = 10^{-0.4 \\; A(V)} Parameter... |
if isinstance(ebv, u.Quantity) and ebv.unit.decompose() == u.mag:
ebv = ebv.value
elif not isinstance(ebv, numbers.Real):
raise exceptions.SynphotError('E(B-V)={0} is invalid.'.format(ebv))
x = self._validate_wavelengths(wavelengths).value
y = 10 ** (-0.4 * self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_fits(self, filename, wavelengths=None, **kwargs):
"""Write the reddening law to a FITS file. :math:`R(V)` column is automatically named 'Av/E(B-V)'. Param... |
w, y = self._get_arrays(wavelengths)
kwargs['flux_col'] = 'Av/E(B-V)'
kwargs['flux_unit'] = self._internal_flux_unit
# No need to trim/pad zeroes, unless user chooses to do so.
if 'pad_zero_ends' not in kwargs:
kwargs['pad_zero_ends'] = False
if 'trim_zero'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename, **kwargs):
"""Create a reddening law from file. If filename has 'fits' or 'fit' suffix, it is read as FITS. Otherwise, it is read as... |
if 'flux_unit' not in kwargs:
kwargs['flux_unit'] = cls._internal_flux_unit
if ((filename.endswith('fits') or filename.endswith('fit')) and
'flux_col' not in kwargs):
kwargs['flux_col'] = 'Av/E(B-V)'
header, wavelengths, rvs = specio.read_spec(filename,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_payload_len(self, payload):
"""Validate payload len.""" |
if not hasattr(self, "PAYLOAD_LEN"):
# No fixed payload len, e.g. within FrameGetSceneListNotification
return
# pylint: disable=no-member
if len(payload) != self.PAYLOAD_LEN:
raise PyVLXException("Invalid payload len", expected_len=self.PAYLOAD_LEN, current_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_frame(command, payload):
"""Build raw bytes from command and payload.""" |
packet_length = 2 + len(payload) + 1
ret = struct.pack("BB", 0, packet_length)
ret += struct.pack(">H", command.value)
ret += payload
ret += struct.pack("B", calc_crc(ret))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def run(self, wait_for_completion=True):
"""Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target posi... |
activate_scene = ActivateScene(
pyvlx=self.pyvlx,
wait_for_completion=wait_for_completion,
scene_id=self.scene_id)
await activate_scene.do_api_call()
if not activate_scene.success:
raise PyVLXException("Unable to activate scene") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, scene):
"""Add scene.""" |
if not isinstance(scene, Scene):
raise TypeError()
self.__scenes.append(scene) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_import(self, json_response):
"""Import scenes from JSON response.""" |
if 'data' not in json_response:
raise PyVLXException('no element data found: {0}'.format(
json.dumps(json_response)))
data = json_response['data']
for item in data:
self.load_scene(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_scene(self, item):
"""Load scene from json.""" |
scene = Scene.from_config(self.pyvlx, item)
self.add(scene) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_raw(self, raw):
"""Parse alias array from raw bytes.""" |
if not isinstance(raw, bytes):
raise PyVLXException("AliasArray::invalid_type_if_raw", type_raw=type(raw))
if len(raw) != 21:
raise PyVLXException("AliasArray::invalid_size", size=len(raw))
nbr_of_alias = raw[0]
if nbr_of_alias > 5:
raise PyVLXExcepti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
return None, raw
length = raw[1:].index(SLIP_END)
slip_packet = decode(raw[1:length+1])
new_raw = raw[length+2:]
return slip_packet, new_raw |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw):
"""Python implementation of ``calcbinflux``. This is only used if ``synphot.synphot_utils`` C-e... |
binflux = np.empty(shape=(len_binwave, ), dtype=np.float64)
intwave = np.empty(shape=(len_binwave, ), dtype=np.float64)
# Note that, like all Python striding, the range over which
# we integrate is [first:last).
for i in range(len(i_beg)):
first = i_beg[i]
last = i_end[i]
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pixel_range(bins, waverange, mode='round'):
"""Calculate the number of pixels within the given wavelength range and the given bins. Parameters bins : array-l... |
mode = mode.lower()
if mode not in ('round', 'min', 'max', 'none'):
raise exceptions.SynphotError(
'mode={0} is invalid, must be "round", "min", "max", '
'or "none".'.format(mode))
if waverange[0] < waverange[-1]:
wave1 = waverange[0]
wave2 = waverange[-1]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 PyVLXException("Login to KLF 200 failed, check credentials") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 version")
self.version = get_version.version
get_protocol_version = GetProtocolVersion(pyvlx=self)
await get_protocol_ver... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(pyvlx=self)
self.connection.write(frame) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_config(cls, pyvlx, item):
"""Read scene from configuration.""" |
name = item['name']
ident = item['id']
return cls(pyvlx, ident, name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_authorization_token)
except InvalidToken:
if not retry and add_authorization_token:
await self.refresh_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 element token found in response: {0}'.format(json.dumps(json_response)))
self.token = json_response['toke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 found in response: {0}'.format(json.dumps(json_response)))
elif not json_response['result']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
raise PyVLXException('Could not evaluate errors {0}'.format(json.dumps(json_response)))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temperature(self, what):
"""Set temperature.""" |
self._temperature = units.validate_quantity(what, u.K) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename, temperature_key='DEFT', beamfill_key='BEAMFILL', **kwargs):
"""Creates a thermal spectral element from file. .. note:: Only FITS for... |
if not (filename.endswith('fits') or filename.endswith('fit')):
raise exceptions.SynphotError('Only FITS format is supported.')
# Extra info from table header
ext = kwargs.get('ext', 1)
tab_hdr = fits.getheader(filename, ext=ext)
temperature = tab_hdr.get(temperatu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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([value >> 8 & 255, value & 255]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.CURRENT_POSITION:
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.