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 check_oscntab(oscntab, ccdamp, xsize, ysize, leading, trailing):
"""Check if the supplied parameters are in the ``OSCNTAB`` reference file. .. note:: Even if... |
tab = Table.read(oscntab)
ccdamp = ccdamp.lower().rstrip()
for row in tab:
if (row['CCDAMP'].lower().rstrip() in ccdamp and
row['NX'] == xsize and row['NY'] == ysize and
row['TRIMX1'] == leading and row['TRIMX2'] == trailing):
return True
return False |
<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_overscan(xstart, xsize, total_prescan_pixels=24, total_science_pixels=4096):
"""Check image for bias columns. Parameters xstart : int Starting column o... |
hasoverscan = False
leading = 0
trailing = 0
if xstart < total_prescan_pixels:
hasoverscan = True
leading = abs(xstart - total_prescan_pixels)
if (xstart + xsize) > total_science_pixels:
hasoverscan = True
trailing = abs(total_science_pixels -
... |
<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_request(self, request):
""" Ignore unnecessary actions for static file requests, posts, or ajax requests. We're only interested in redirecting follow... |
referer_url = request.META.get('HTTP_REFERER')
return_to_index_url = request.session.get('return_to_index_url')
try:
if all((
return_to_index_url,
referer_url,
request.method == 'GET',
not request.is_ajax(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acs2d(input, exec_path='', time_stamps=False, verbose=False, quiet=False, exe_args=None):
r""" Run the acs2d.e executable as from the shell. Output is automa... |
from stsci.tools import parseinput # Optional package dependency
if exec_path:
if not os.path.exists(exec_path):
raise OSError('Executable not found: ' + exec_path)
call_list = [exec_path]
else:
call_list = ['acs2d.e']
# Parse input to get list of filenames to pro... |
<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(configobj=None):
""" TEAL interface for the `acs2d` function. """ |
acs2d(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet']
) |
<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(configobj=None):
""" TEAL interface for the `acscte` function. """ |
acscte(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet'],
single_core=configobj['single_core']
) |
<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_inputs(self):
"""Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. """ |
valid_detector = True
valid_filter = True
valid_date = True
# Determine the submitted detector is valid
if self.detector not in self._valid_detectors:
msg = ('{} is not a valid detector option.\n'
'Please choose one of the following:\n{}\n'
... |
<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_date(self, fmt='%Y-%m-%d'):
"""Convenience method for determining if the input date is valid. Parameters fmt : str The format of the date string. The ... |
result = None
try:
dt_obj = dt.datetime.strptime(self.date, fmt)
except ValueError:
result = '{} does not match YYYY-MM-DD format'.format(self.date)
else:
if dt_obj < self._acs_installation_date:
result = ('The observation date cannot ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _submit_request(self):
"""Submit a request to the ACS Zeropoint Calculator. If an exception is raised during the request, an error message is given. Otherwis... |
try:
self._response = urlopen(self._url)
except URLError as e:
msg = ('{}\n{}\nThe query failed! Please check your inputs. '
'If the error persists, submit a ticket to the '
'ACS Help Desk at hsthelp.stsci.edu with the error message '
... |
<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_and_format(self):
""" Parse and format the results returned by the ACS Zeropoint Calculator. Using ``beautifulsoup4``, find all the ``<tb> </tb>`` tag... |
soup = BeautifulSoup(self._response.read(), 'html.parser')
# Grab all elements in the table returned by the ZPT calc.
td = soup.find_all('td')
# Remove the units attached to PHOTFLAM and PHOTPLAM column names.
td = [val.text.split(' ')[0] for val in td]
# Turn the si... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self):
"""Submit the request to the ACS Zeropoints Calculator. This method will: * submit the request * parse the response * format the results into a ... |
LOG.info('Checking inputs...')
valid_inputs = self._check_inputs()
if valid_inputs:
LOG.info('Submitting request to {}'.format(self._url))
self._submit_request()
if self._failed:
return
LOG.info('Parsing the response and formatti... |
<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_queryset(self, request):
""" Returns a QuerySet of all model instances that can be edited by the admin site. """ |
qs = self.model._default_manager.get_queryset()
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_view(self, request):
""" Instantiates a class-based view to provide listing functionality for the assigned model. The view class used can be overridden... |
kwargs = {'model_admin': self}
view_class = self.index_view_class
return view_class.as_view(**kwargs)(request) |
<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_view(self, request):
""" Instantiates a class-based view to provide 'creation' functionality for the assigned model, or redirect to Wagtail's create v... |
kwargs = {'model_admin': self}
view_class = self.create_view_class
return view_class.as_view(**kwargs)(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_parent_view(self, request):
""" Instantiates a class-based view to provide a view that allows a parent page to be chosen for a new object, where the a... |
kwargs = {'model_admin': self}
view_class = self.choose_parent_view_class
return view_class.as_view(**kwargs)(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_view(self, request, object_id):
""" Instantiates a class-based view to provide 'edit' functionality for the assigned model, or redirect to Wagtail's edi... |
kwargs = {'model_admin': self, 'object_id': object_id}
view_class = self.edit_view_class
return view_class.as_view(**kwargs)(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm_delete_view(self, request, object_id):
""" Instantiates a class-based view to provide 'delete confirmation' functionality for the assigned model, or ... |
kwargs = {'model_admin': self, 'object_id': object_id}
view_class = self.confirm_delete_view_class
return view_class.as_view(**kwargs)(request) |
<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_templates(self, action='index'):
""" Utility function that provides a list of templates to try for a given view, when the template isn't overridden by on... |
app = self.opts.app_label
model_name = self.opts.model_name
return [
'wagtailmodeladmin/%s/%s/%s.html' % (app, model_name, action),
'wagtailmodeladmin/%s/%s.html' % (app, action),
'wagtailmodeladmin/%s.html' % (action,),
] |
<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_permissions_for_registration(self):
""" Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in se... |
from wagtail.wagtailsnippets.models import SNIPPET_MODELS
if not self.is_pagemodel and self.model not in SNIPPET_MODELS:
return self.permission_helper.get_all_model_permissions()
return Permission.objects.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 get_menu_item(self):
""" Utilised by Wagtail's 'register_menu_item' hook to create a menu for this group with a SubMenu linking to listing pages for any asso... |
if self.modeladmin_instances:
submenu = SubMenu(self.get_submenu_items())
return GroupMenuItem(self, self.get_menu_order(), submenu) |
<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_permissions_for_registration(self):
""" Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to ... |
qs = Permission.objects.none()
for instance in self.modeladmin_instances:
qs = qs | instance.get_permissions_for_registration()
return qs |
<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_admin_urls_for_registration(self):
""" Utilised by Wagtail's 'register_admin_urls' hook to register urls for used by any associated ModelAdmin instances ... |
urls = []
for instance in self.modeladmin_instances:
urls.extend(instance.get_admin_urls_for_registration())
return urls |
<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_shown(self, request):
""" If there aren't any visible items in the submenu, don't bother to show this menu item """ |
for menuitem in self.menu._registered_menu_items:
if menuitem.is_shown(request):
return True
return False |
<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(configobj=None):
""" TEAL interface for the `acscteforwardmodel` function. """ |
acscteforwardmodel(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet'],
single_core=configobj['single_cor... |
<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(configobj=None):
""" TEAL interface for the `acsccd` function. """ |
acsccd(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet'] #,
#dqicorr=configobj['dqicorr'],
#atodcorr=configobj['atodcorr'],
#blevcorr=config... |
<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_search_results(self, request, queryset, search_term):
""" Returns a tuple containing a queryset to implement the search, and a boolean indicating if the ... |
# Apply keyword searches.
def construct_search(field_name):
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):... |
<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_filters_params(self, params=None):
""" Returns all params except IGNORED_PARAMS """ |
if not params:
params = self.params
lookup_params = params.copy() # a dictionary of the query string
# Remove all the parameters that are globally and systematically
# ignored.
for ignored in IGNORED_PARAMS:
if ignored in lookup_params:
d... |
<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_field_label(self, field_name, field=None):
""" Return a label to display for a field """ |
label = None
if field is not None:
label = getattr(field, 'verbose_name', None)
if label is None:
label = getattr(field, 'name', None)
if label is None:
label = field_name
return label.capitalize() |
<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_field_display_value(self, field_name, field=None):
""" Return a display value for a field """ |
"""
Firstly, check for a 'get_fieldname_display' property/method on
the model, and return the value of that, if present.
"""
val_funct = getattr(self.instance, 'get_%s_display' % field_name, None)
if val_funct is not None:
if callable(val_funct):
... |
<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_image_field_display(self, field_name, field):
""" Render an image """ |
image = getattr(self.instance, field_name)
if image:
fltr, _ = Filter.objects.get_or_create(spec='max-400x400')
rendition = image.get_rendition(fltr)
return rendition.img_tag
return self.model_admin.get_empty_value_display() |
<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_document_field_display(self, field_name, field):
""" Render a link to a document """ |
document = getattr(self.instance, field_name)
if document:
return mark_safe(
'<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % (
document.url,
document.title,
document.file_extension.upper(),
... |
<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_dict_for_field(self, field_name):
""" Return a dictionary containing `label` and `value` values to display for a field. """ |
try:
field = self.model._meta.get_field(field_name)
except FieldDoesNotExist:
field = None
return {
'label': self.get_field_label(field_name, field),
'value': self.get_field_display_value(field_name, field),
} |
<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(configobj=None):
""" TEAL interface for the `acssum` function. """ |
acssum(configobj['input'],
configobj['output'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet']
) |
<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_valid_indices(shape, ix0, ix1, iy0, iy1):
"""Give array shape and desired indices, return indices that are correctly bounded by the shape.""" |
ymax, xmax = shape
if ix0 < 0:
ix0 = 0
if ix1 > xmax:
ix1 = xmax
if iy0 < 0:
iy0 = 0
if iy1 > ymax:
iy1 = ymax
if iy1 <= iy0 or ix1 <= ix0:
raise IndexError(
'array[{0}:{1},{2}:{3}] is invalid'.format(iy0, iy1, ix0, ix1))
return list(ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rotate_point(point, angle, ishape, rshape, reverse=False):
"""Transform a point from original image coordinates to rotated image coordinates and back. It as... |
# unpack the image and rotated images shapes
if reverse:
angle = (angle * -1)
temp = ishape
ishape = rshape
rshape = temp
# transform into center of image coordinates
yhalf, xhalf = ishape
yrhalf, xrhalf = rshape
yhalf = yhalf / 2
xhalf = xhalf / 2
yrh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_dq(filename, ext, mask, dqval=16384, verbose=True):
"""Update the given image and DQ extension with the given satellite trails mask and flag. Paramete... |
with fits.open(filename, mode='update') as pf:
dqarr = pf[ext].data
old_mask = (dqval & dqarr) != 0 # Existing flagged trails
new_mask = mask & ~old_mask # Only flag previously unflagged trails
npix_updated = np.count_nonzero(new_mask)
# Update DQ extension only if necess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _satdet_worker(work_queue, done_queue, sigma=2.0, low_thresh=0.1, h_thresh=0.5, small_edge=60, line_len=200, line_gap=75, percentile=(4.5, 93.0), buf=200):
"... |
for fil, chip in iter(work_queue.get, 'STOP'):
try:
result = _detsat_one(
fil, chip, sigma=sigma,
low_thresh=low_thresh, h_thresh=h_thresh,
small_edge=small_edge, line_len=line_len, line_gap=line_gap,
percentile=percentile, buf=buf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self, event: str) -> Callable: """ Decorator for subscribing a function to a specific event. :param event: Name of the event to subscribe to. :type event: ... |
def outer(func):
self.add_event(func, event)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return outer |
<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_event(self, func: Callable, event: str) -> None: """ Adds a function to a event. :param func: The function to call when event is emitted :type func: Calla... |
self._events[event].add(func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, event: str, *args, **kwargs) -> None: """ Emit an event and run the subscribed functions. :param event: Name of the event. :type event: str .. note... |
threads = kwargs.pop('threads', None)
if threads:
events = [
Thread(target=f, args=args, kwargs=kwargs) for f in
self._event_funcs(event)
]
for event in events:
event.start()
else:
for func in 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 emit_only(self, event: str, func_names: Union[str, List[str]], *args, **kwargs) -> None: """ Specifically only emits certain subscribed events. :param event: ... |
if isinstance(func_names, str):
func_names = [func_names]
for func in self._event_funcs(event):
if func.__name__ in func_names:
func(*args, **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 emit_after(self, event: str) -> Callable: """ Decorator that emits events after the function is completed. :param event: Name of the event. :type event: str :... |
def outer(func):
@wraps(func)
def wrapper(*args, **kwargs):
returned = func(*args, **kwargs)
self.emit(event)
return returned
return wrapper
return outer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_event(self, func_name: str, event: str) -> None: """ Removes a subscribed function from a specific event. :param func_name: The name of the function to... |
event_funcs_copy = self._events[event].copy()
for func in self._event_funcs(event):
if func.__name__ == func_name:
event_funcs_copy.remove(func)
if self._events[event] == event_funcs_copy:
err_msg = "function doesn't exist inside event {} ".format(event... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _event_funcs(self, event: str) -> Iterable[Callable]: """ Returns an Iterable of the functions subscribed to a event. :param event: Name of the event. :type e... |
for func in self._events[event]:
yield func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _event_func_names(self, event: str) -> List[str]: """ Returns string name of each function subscribed to an event. :param event: Name of the event. :type even... |
return [func.__name__ for func in self._events[event]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _subscribed_event_count(self) -> int: """ Returns the total amount of subscribed events. :return: Integer amount events. :rtype: int """ |
event_counter = Counter() # type: Dict[Any, int]
for key, values in self._events.items():
event_counter[key] = len(values)
return sum(event_counter.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform_correction(image, output, stat="pmode1", maxiter=15, sigrej=2.0, lower=None, upper=None, binwidth=0.3, mask=None, dqbits=None, rpt_clean=0, atol=0.01,... |
# construct the frame to be cleaned, including the
# associated data stuctures needed for cleaning
frame = StripeArray(image)
# combine user mask with image's DQ array:
mask = _mergeUserMaskAndDQ(frame.dq, mask, dqbits)
# Do the stripe cleaning
Success, NUpdRows, NMaxIter, Bkgrnd, STDDEVC... |
<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(configobj=None):
"""TEAL interface for the `clean` function.""" |
clean(configobj['input'],
suffix=configobj['suffix'],
stat=configobj['stat'],
maxiter=configobj['maxiter'],
sigrej=configobj['sigrej'],
lower=configobj['lower'],
upper=configobj['upper'],
binwidth=configobj['binwidth'],
mask1=configobj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_arrays(self):
"""Get the SCI and ERR data.""" |
self.science = self.hdulist['sci', 1].data
self.err = self.hdulist['err', 1].data
self.dq = self.hdulist['dq', 1].data
if (self.ampstring == 'ABCD'):
self.science = np.concatenate(
(self.science, self.hdulist['sci', 2].data[::-1, :]), axis=1)
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 ingest_flatfield(self):
"""Process flatfield.""" |
self.invflat = extract_flatfield(
self.hdulist[0].header, self.hdulist[1])
# If BIAS or DARK, set flatfield to unity
if self.invflat is None:
self.invflat = np.ones_like(self.science)
return
# Apply the flatfield if necessary
if self.flatco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ingest_flash(self):
"""Process post-flash.""" |
self.flash = extract_flash(self.hdulist[0].header, self.hdulist[1])
# Set post-flash to zeros
if self.flash is None:
self.flash = np.zeros_like(self.science)
return
# Apply the flash subtraction if necessary.
# Not applied to ERR, to be consistent with... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ingest_dark(self):
"""Process dark.""" |
self.dark = extract_dark(self.hdulist[0].header, self.hdulist[1])
# If BIAS or DARK, set dark to zeros
if self.dark is None:
self.dark = np.zeros_like(self.science)
return
# Apply the dark subtraction if necessary.
# Effect of DARK on ERR is insignific... |
<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_corrected(self, output, clobber=False):
"""Write out the destriped data.""" |
# un-apply the flatfield if necessary
if self.flatcorr != 'COMPLETE':
self.science = self.science / self.invflat
self.err = self.err / self.invflat
# un-apply the post-flash if necessary
if self.flshcorr != 'COMPLETE':
self.science = self.science + ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calacs(input_file, exec_path=None, time_stamps=False, temp_files=False, verbose=False, debug=False, quiet=False, single_core=False, exe_args=None):
""" Run t... |
if exec_path:
if not os.path.exists(exec_path):
raise OSError('Executable not found: ' + exec_path)
call_list = [exec_path]
else:
call_list = ['calacs.e']
if time_stamps:
call_list.append('-t')
if temp_files:
call_list.append('-s')
if verbose:... |
<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(configobj=None):
""" TEAL interface for the `calacs` function. """ |
calacs(configobj['input_file'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
temp_files=configobj['temp_files'],
verbose=configobj['verbose'],
debug=configobj['debug'],
quiet=configobj['quiet'],
single_core=conf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_any_permissions(self, user):
""" Return a boolean to indicate whether the supplied user has any permissions at all on the associated model """ |
for perm in self.get_all_model_permissions():
if self.has_specific_permission(user, perm.codename):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acsrej(input, output, exec_path='', time_stamps=False, verbose=False, shadcorr=False, crrejtab='', crmask=False, scalense=None, initgues='', skysub='', crsigm... |
from stsci.tools import parseinput # Optional package dependency
if exec_path:
if not os.path.exists(exec_path):
raise OSError('Executable not found: ' + exec_path)
call_list = [exec_path]
else:
call_list = ['acsrej.e']
# Parse input to get list of filenames to pr... |
<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(configobj=None):
""" TEAL interface for the `acsrej` function. """ |
acsrej(configobj['input'],
configobj['output'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
shadcorr=configobj['shadcorr'],
crrejtab=configobj['crrejtab'],
crmask=configobj['crmask... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parent_after_fork_release():
""" Call all parent after fork callables, release the lock and print all prepare and parent callback exceptions. """ |
prepare_exceptions = list(_prepare_call_exceptions)
del _prepare_call_exceptions[:]
exceptions = _call_atfork_list(_parent_call_list)
_fork_lock.release()
_print_exception_list(prepare_exceptions, 'before fork')
_print_exception_list(exceptions, 'after fork from parent') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_exception_list(exceptions, message, output_file=None):
""" Given a list of sys.exc_info tuples, print them all using the traceback module preceeded by... |
output_file = output_file or sys.stderr
message = 'Exception %s:\n' % message
for exc_type, exc_value, exc_traceback in exceptions:
output_file.write(message)
traceback.print_exception(exc_type, exc_value, exc_traceback,
file=output_file)
output_fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe(value):
"""Wraps an object with a Maybe instance. Something("I'm a value") Nothing Testing for value: True False False True Simplifying IF statements: ... |
if isinstance(value, Maybe):
return value
if value is not None:
return Something(value)
return Nothing() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup(self):
'''Setup the connection.'''
log.debug( 'New request from address %s, port %d', self.client_address )
try:
self.transport.load_server_moduli()
except:
log.exception( '(Failed to load moduli -- gex will be unsupported.)' )
rais... |
<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_channel_shell_request(self, channel):
'''Request to start a shell on the given channel'''
try:
self.channels[channel].start()
except KeyError:
log.error('Requested to start a channel (%r) that was not previously set up.', channel)
return False
... |
<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_channel_pty_request(self, channel, term, width, height, pixelwidth,
pixelheight, modes):
'''Request to allocate a PTY terminal.'''
#self.sshterm = term
#print "term: %r, modes: %r" % (term, modes)
log.debug('PTY requested. Setting up %r.', 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 collect(self, order_ref):
"""Collects the result of a sign or auth order using the ``orderRef`` as reference. RP should keep on calling collect every two sec... |
response = self.client.post(
self._collect_endpoint, json={"orderRef": order_ref}
)
if response.status_code == 200:
return response.json()
else:
raise get_json_error_class(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 cancel(self, order_ref):
"""Cancels an ongoing sign or auth order. This is typically used if the user cancels the order in your service or app. :param order_... |
response = self.client.post(self._cancel_endpoint, json={"orderRef": order_ref})
if response.status_code == 200:
return response.json() == {}
else:
raise get_json_error_class(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 writemessage(self, text):
"""Put data in output queue, rebuild the prompt and entered data""" |
# Need to grab the input queue lock to ensure the entered data doesn't change
# before we're done rebuilding it.
# Note that writemessage will eventually call writecooked
self.IQUEUELOCK.acquire()
TelnetHandlerBase.writemessage(self, text)
self.IQUEUELOCK.release() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writecooked(self, text):
"""Put data directly into the output queue""" |
# Ensure this is the only thread writing
self.OQUEUELOCK.acquire()
TelnetHandlerBase.writecooked(self, text)
self.OQUEUELOCK.release() |
<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_certificate(certificate_path, destination_folder, password=None):
"""Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This meth... |
try:
# Attempt Linux and Darwin call first.
p = subprocess.Popen(
["openssl", "version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
sout, serr = p.communicate()
openssl_executable_version = sout.decode().lower()
if not (
openssl_executa... |
<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_delimiter(self, char):
'''Process chars while not in a part'''
if char in self.whitespace:
return
if char in self.quote_chars:
# Store the quote type (' or ") and switch to quote processing.
self.inquote = char
self.process_char = 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 process_part(self, char):
'''Process chars while in a part'''
if char in self.whitespace or char == self.eol_char:
# End of the part.
self.parts.append( ''.join(self.part) )
self.part = []
# Switch back to processing a delimiter.
self.proce... |
<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_quote(self, char):
'''Process character while in a quote'''
if char == self.inquote:
# Quote is finished, switch to part processing.
self.process_char = self.process_part
return
try:
self.part.append(char)
except:
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 process_escape(self, char):
'''Handle the char after the escape char'''
# Always only run once, switch back to the last processor.
self.process_char = self.last_process_char
if self.part == [] and char in self.whitespace:
# Special case where \ is by itself and not at the... |
<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(self, line):
'''Step through the line and process each character'''
self.raw = self.raw + line
try:
if not line[-1] == self.eol_char:
# Should always be here, but add it just in case.
line = line + self.eol_char
except IndexError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setterm(self, term):
"Set the curses structures for this terminal"
log.debug("Setting termtype to %s" % (term, ))
curses.setupterm(term) # This will raise if the termtype is not supported
self.TERM = term
self.ESCSEQ = {}
for k in self.KEYS.keys():
str = 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 setup(self):
"Connect incoming connection to a telnet session"
try:
self.TERM = self.request.term
except:
pass
self.setterm(self.TERM)
self.sock = self.request._sock
for k in self.DOACK.keys():
self.sendcommand(self.DOACK[k], 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 finish(self):
"End this session"
log.debug("Session disconnected.")
try:
self.sock.shutdown(socket.SHUT_RDWR)
except: pass
self.session_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 _readline_echo(self, char, echo):
|
if self._readline_do_echo(echo):
self.write(char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _readline_insert(self, char, echo, insptr, line):
"""Deal properly with inserted chars in a line.""" |
if not self._readline_do_echo(echo):
return
# Write out the remainder of the line
self.write(char + ''.join(line[insptr:]))
# Cursor Left to the current insert point
char_count = len(line) - insptr
self.write(self.CODES['CSRLEFT'] * char_count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ansi_to_curses(self, char):
'''Handles reading ANSI escape sequences'''
# ANSI sequences are:
# ESC [ <key>
# If we see ESC, read a char
if char != ESC:
return char
# If we see [, read another char
if self.getc(block=True) != ANSI_START_SEQ:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeline(self, text):
"""Send a packet with line ending.""" |
log.debug('writing line %r' % text)
self.write(text+chr(10)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writemessage(self, text):
"""Write out an asynchronous message, then reconstruct the prompt and entered text.""" |
log.debug('writing message %r', text)
self.write(chr(10)+text+chr(10))
self.write(self._current_prompt+''.join(self._current_line)) |
<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, text):
"""Send a packet to the socket. This function cooks output.""" |
text = str(text) # eliminate any unicode or other snigglets
text = text.replace(IAC, IAC+IAC)
text = text.replace(chr(10), chr(13)+chr(10))
self.writecooked(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inputcooker_getc(self, block=True):
"""Get one character from the raw queue. Optionally blocking. Raise EOFError on end of stream. SHOULD ONLY BE CALLED FRO... |
if self.rawq:
ret = self.rawq[0]
self.rawq = self.rawq[1:]
return ret
if not block:
if not self.inputcooker_socket_ready():
return ''
ret = self.sock.recv(20)
self.eof = not(ret)
self.rawq = self.rawq + ret
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inputcooker_store(self, char):
"""Put the cooked data in the correct queue""" |
if self.sb:
self.sbdataq = self.sbdataq + char
else:
self.inputcooker_store_queue(char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inputcooker(self):
"""Input Cooker - Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an I... |
try:
while True:
c = self._inputcooker_getc()
if not self.iacseq:
if c == IAC:
self.iacseq += c
continue
elif c == chr(13) and not(self.sb):
c2 = self._inp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmdHISTORY(self, params):
""" Display the command history """ |
cnt = 0
self.writeline('Command history\n')
for line in self.history:
cnt = cnt + 1
self.writeline("%-5d : %s" % (cnt, ''.join(line))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def authentication_ok(self):
'''Checks the authentication and sets the username of the currently connected terminal. Returns True or False'''
username = None
password = None
if self.authCallback:
if self.authNeedUser:
username = self.readline(prompt=self.PROM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect(self, order_ref):
"""Collect the progress status of the order with the specified order reference. :param order_ref: The UUID string specifying which ... |
try:
out = self.client.service.Collect(order_ref)
except Error as e:
raise get_error_class(e, "Could not complete Collect call.")
return self._dictify(out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dictify(self, doc):
"""Transforms the replies to a regular Python dict with strings and datetimes. Tested with BankID version 2.5 return data. :param doc: T... |
return {
k: (self._dictify(doc[k]) if hasattr(doc[k], "_xsd_type") else doc[k])
for k in doc
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intercept_image_formats(self, options):
""" Load all image formats if needed. """ |
if 'entityTypes' in options:
for entity in options['entityTypes']:
if entity['type'] == ENTITY_TYPES.IMAGE and 'imageFormats' in entity:
if entity['imageFormats'] == '__all__':
entity['imageFormats'] = get_all_image_formats()
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 CopyFromDateTimeString(self, time_string):
"""Copies a Delphi TDateTime timestamp from a string. Args: time_string (str):
date and time value formatted as: ... |
date_time_values = self._CopyDateTimeFromString(time_string)
year = date_time_values.get('year', 0)
month = date_time_values.get('month', 0)
day_of_month = date_time_values.get('day_of_month', 0)
hours = date_time_values.get('hours', 0)
minutes = date_time_values.get('minutes', 0)
seconds ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _AdjustForTimeZoneOffset( self, year, month, day_of_month, hours, minutes, time_zone_offset):
"""Adjusts the date and time values for a time zone offset. Arg... |
hours_from_utc, minutes_from_utc = divmod(time_zone_offset, 60)
minutes += minutes_from_utc
# Since divmod makes sure the sign of minutes_from_utc is positive
# we only need to check the upper bound here, because hours_from_utc
# remains signed it is corrected accordingly.
if minutes >= 60:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _CopyDateFromString(self, date_string):
"""Copies a date from a string. Args: date_string (str):
date value formatted as: YYYY-MM-DD Returns: tuple[int, int... |
date_string_length = len(date_string)
# The date string should at least contain 'YYYY-MM-DD'.
if date_string_length < 10:
raise ValueError('Date string too short.')
if date_string[4] != '-' or date_string[7] != '-':
raise ValueError('Invalid date string.')
try:
year = int(date_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _CopyTimeFromString(self, time_string):
"""Copies a time from a string. Args: time_string (str):
time value formatted as: hh:mm:ss.######[+-]##:## Where # a... |
time_string_length = len(time_string)
# The time string should at least contain 'hh:mm:ss'.
if time_string_length < 8:
raise ValueError('Time string too short.')
if time_string[2] != ':' or time_string[5] != ':':
raise ValueError('Invalid time string.')
try:
hours = int(time_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetDayOfYear(self, year, month, day_of_month):
"""Retrieves the day of the year for a specific day of a month in a year. Args: year (int):
year e.g. 1970. ... |
if month not in range(1, 13):
raise ValueError('Month value out of bounds.')
days_per_month = self._GetDaysPerMonth(year, month)
if day_of_month < 1 or day_of_month > days_per_month:
raise ValueError('Day of month value out of bounds.')
day_of_year = day_of_month
for past_month in ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetDaysPerMonth(self, year, month):
"""Retrieves the number of days in a month of a specific year. Args: year (int):
year e.g. 1970. month (int):
month, w... |
if month not in range(1, 13):
raise ValueError('Month value out of bounds.')
days_per_month = self._DAYS_PER_MONTH[month - 1]
if month == 2 and self._IsLeapYear(year):
days_per_month += 1
return days_per_month |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetNumberOfDaysInCentury(self, year):
"""Retrieves the number of days in a century. Args: year (int):
year in the century e.g. 1970. Returns: int: number o... |
if year < 0:
raise ValueError('Year value out of bounds.')
year, _ = divmod(year, 100)
if self._IsLeapYear(year):
return 36525
return 36524 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetNumberOfSecondsFromElements( self, year, month, day_of_month, hours, minutes, seconds):
"""Retrieves the number of seconds from the date and time element... |
if not year or not month or not day_of_month:
return None
# calendar.timegm does not sanity check the time elements.
if hours is None:
hours = 0
elif hours not in range(0, 24):
raise ValueError('Hours value: {0!s} out of bounds.'.format(hours))
if minutes is None:
minutes ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetTimeValues(self, number_of_seconds):
"""Determines time values. Args: number_of_seconds (int|decimal.Decimal):
number of seconds. Returns: tuple[int, in... |
number_of_seconds = int(number_of_seconds)
number_of_minutes, seconds = divmod(number_of_seconds, 60)
number_of_hours, minutes = divmod(number_of_minutes, 60)
number_of_days, hours = divmod(number_of_hours, 24)
return number_of_days, hours, minutes, seconds |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.