text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Check that the value is a list of IP addresses.
<END_TASK>
<USER_TASK:>
Description:
def is_ip_addr_list(value, min=None, max=None):
"""
Check that the value is a list of IP addresses.
You can optionally specify the minimum and maximum number of members.
Each list member is checked that it is an IP address.
>>> vtor = Validator()
>>> vtor.check('ip_addr_list', ())
[]
>>> vtor.check('ip_addr_list', [])
[]
>>> vtor.check('ip_addr_list', ('1.2.3.4', '5.6.7.8'))
['1.2.3.4', '5.6.7.8']
>>> vtor.check('ip_addr_list', ['a']) # doctest: +SKIP
Traceback (most recent call last):
VdtValueError: the value "a" is unacceptable.
""" |
return [is_ip_addr(mem) for mem in is_list(value, min, max)] |
<SYSTEM_TASK:>
Check that a value is a list, coercing strings into
<END_TASK>
<USER_TASK:>
Description:
def force_list(value, min=None, max=None):
"""
Check that a value is a list, coercing strings into
a list with one member. Useful where users forget the
trailing comma that turns a single value into a list.
You can optionally specify the minimum and maximum number of members.
A minumum of greater than one will fail if the user only supplies a
string.
>>> vtor = Validator()
>>> vtor.check('force_list', ())
[]
>>> vtor.check('force_list', [])
[]
>>> vtor.check('force_list', 'hello')
['hello']
""" |
if not isinstance(value, (list, tuple)):
value = [value]
return is_list(value, min, max) |
<SYSTEM_TASK:>
Check that the value is a list.
<END_TASK>
<USER_TASK:>
Description:
def is_mixed_list(value, *args):
"""
Check that the value is a list.
Allow specifying the type of each member.
Work on lists of specific lengths.
You specify each member as a positional argument specifying type
Each type should be one of the following strings :
'integer', 'float', 'ip_addr', 'string', 'boolean'
So you can specify a list of two strings, followed by
two integers as :
mixed_list('string', 'string', 'integer', 'integer')
The length of the list must match the number of positional
arguments you supply.
>>> vtor = Validator()
>>> mix_str = "mixed_list('integer', 'float', 'ip_addr', 'string', 'boolean')"
>>> check_res = vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', True))
>>> check_res == [1, 2.0, '1.2.3.4', 'a', True]
1
>>> check_res = vtor.check(mix_str, ('1', '2.0', '1.2.3.4', 'a', 'True'))
>>> check_res == [1, 2.0, '1.2.3.4', 'a', True]
1
>>> vtor.check(mix_str, ('b', 2.0, '1.2.3.4', 'a', True)) # doctest: +SKIP
Traceback (most recent call last):
VdtTypeError: the value "b" is of the wrong type.
>>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a')) # doctest: +SKIP
Traceback (most recent call last):
VdtValueTooShortError: the value "(1, 2.0, '1.2.3.4', 'a')" is too short.
>>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', 1, 'b')) # doctest: +SKIP
Traceback (most recent call last):
VdtValueTooLongError: the value "(1, 2.0, '1.2.3.4', 'a', 1, 'b')" is too long.
>>> vtor.check(mix_str, 0) # doctest: +SKIP
Traceback (most recent call last):
VdtTypeError: the value "0" is of the wrong type.
This test requires an elaborate setup, because of a change in error string
output from the interpreter between Python 2.2 and 2.3 .
>>> res_seq = (
... 'passed an incorrect value "',
... 'yoda',
... '" for parameter "mixed_list".',
... )
>>> res_str = "'".join(res_seq)
>>> try:
... vtor.check('mixed_list("yoda")', ('a'))
... except VdtParamError as err:
... str(err) == res_str
1
""" |
try:
length = len(value)
except TypeError:
raise VdtTypeError(value)
if length < len(args):
raise VdtValueTooShortError(value)
elif length > len(args):
raise VdtValueTooLongError(value)
try:
return [fun_dict[arg](val) for arg, val in zip(args, value)]
except KeyError as e:
raise(VdtParamError('mixed_list', e)) |
<SYSTEM_TASK:>
This check matches the value to any of a set of options.
<END_TASK>
<USER_TASK:>
Description:
def is_option(value, *options):
"""
This check matches the value to any of a set of options.
>>> vtor = Validator()
>>> vtor.check('option("yoda", "jedi")', 'yoda')
'yoda'
>>> vtor.check('option("yoda", "jedi")', 'jed') # doctest: +SKIP
Traceback (most recent call last):
VdtValueError: the value "jed" is unacceptable.
>>> vtor.check('option("yoda", "jedi")', 0) # doctest: +SKIP
Traceback (most recent call last):
VdtTypeError: the value "0" is of the wrong type.
""" |
if not isinstance(value, string_types):
raise VdtTypeError(value)
if not value in options:
raise VdtValueError(value)
return value |
<SYSTEM_TASK:>
A constant value HDU will only be recognized as such if the header
<END_TASK>
<USER_TASK:>
Description:
def match_header(cls, header):
"""A constant value HDU will only be recognized as such if the header
contains a valid PIXVALUE and NAXIS == 0.
""" |
pixvalue = header.get('PIXVALUE')
naxis = header.get('NAXIS', 0)
return (super(_ConstantValueImageBaseHDU, cls).match_header(header) and
(isinstance(pixvalue, float) or _is_int(pixvalue)) and
naxis == 0) |
<SYSTEM_TASK:>
Verify that the HDU's data is a constant value array.
<END_TASK>
<USER_TASK:>
Description:
def _check_constant_value_data(self, data):
"""Verify that the HDU's data is a constant value array.""" |
arrayval = data.flat[0]
if np.all(data == arrayval):
return arrayval
return None |
<SYSTEM_TASK:>
Did something which requires a new look. Move scrollbar up.
<END_TASK>
<USER_TASK:>
Description:
def freshenFocus(self):
""" Did something which requires a new look. Move scrollbar up.
This often needs to be delayed a bit however, to let other
events in the queue through first. """ |
self.top.update_idletasks()
self.top.after(10, self.setViewAtTop) |
<SYSTEM_TASK:>
Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this
<END_TASK>
<USER_TASK:>
Description:
def mwl(self, event):
"""Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this """ |
if event.num == 4: # up on Linux
self.top.f.canvas.yview_scroll(-1*self._tmwm, 'units')
elif event.num == 5: # down on Linux
self.top.f.canvas.yview_scroll(1*self._tmwm, 'units')
else: # assume event.delta has the direction, but reversed sign
self.top.f.canvas.yview_scroll(-(event.delta)*self._tmwm, 'units') |
<SYSTEM_TASK:>
Set focus to next item in sequence
<END_TASK>
<USER_TASK:>
Description:
def focusNext(self, event):
"""Set focus to next item in sequence""" |
try:
event.widget.tk_focusNext().focus_set()
except TypeError:
# see tkinter equivalent code for tk_focusNext to see
# commented original version
name = event.widget.tk.call('tk_focusNext', event.widget._w)
event.widget._nametowidget(str(name)).focus_set() |
<SYSTEM_TASK:>
Set focus to previous item in sequence
<END_TASK>
<USER_TASK:>
Description:
def focusPrev(self, event):
"""Set focus to previous item in sequence""" |
try:
event.widget.tk_focusPrev().focus_set()
except TypeError:
# see tkinter equivalent code for tk_focusPrev to see
# commented original version
name = event.widget.tk.call('tk_focusPrev', event.widget._w)
event.widget._nametowidget(str(name)).focus_set() |
<SYSTEM_TASK:>
Scroll the panel down to ensure widget with focus to be visible
<END_TASK>
<USER_TASK:>
Description:
def doScroll(self, event):
"""Scroll the panel down to ensure widget with focus to be visible
Tracks the last widget that doScroll was called for and ignores
repeated calls. That handles the case where the focus moves not
between parameter entries but to someplace outside the hierarchy.
In that case the scrolling is not expected.
Returns false if the scroll is ignored, else true.
""" |
canvas = self.top.f.canvas
widgetWithFocus = event.widget
if widgetWithFocus is self.lastFocusWidget:
return FALSE
self.lastFocusWidget = widgetWithFocus
if widgetWithFocus is None:
return TRUE
# determine distance of widget from top & bottom edges of canvas
y1 = widgetWithFocus.winfo_rooty()
y2 = y1 + widgetWithFocus.winfo_height()
cy1 = canvas.winfo_rooty()
cy2 = cy1 + canvas.winfo_height()
yinc = self.yscrollincrement
if y1<cy1:
# this will continue to work when integer division goes away
sdist = int((y1-cy1-yinc+1.)/yinc)
canvas.yview_scroll(sdist, "units")
elif cy2<y2:
sdist = int((y2-cy2+yinc-1.)/yinc)
canvas.yview_scroll(sdist, "units")
return TRUE |
<SYSTEM_TASK:>
Handle the situation where two par lists do not match.
<END_TASK>
<USER_TASK:>
Description:
def _handleParListMismatch(self, probStr, extra=False):
""" Handle the situation where two par lists do not match.
This is meant to allow subclasses to override. Note that this only
handles "missing" pars and "extra" pars, not wrong-type pars. """ |
errmsg = 'ERROR: mismatch between default and current par lists ' + \
'for task "'+self.taskName+'"'
if probStr:
errmsg += '\n\t'+probStr
errmsg += '\n(try: "unlearn '+self.taskName+'")'
print(errmsg)
return False |
<SYSTEM_TASK:>
This creates self.defaultParamList. It also does some checks
<END_TASK>
<USER_TASK:>
Description:
def _setupDefaultParamList(self):
""" This creates self.defaultParamList. It also does some checks
on the paramList, sets its order if needed, and deletes any extra
or unknown pars if found. We assume the order of self.defaultParamList
is the correct order. """ |
# Obtain the default parameter list
self.defaultParamList = self._taskParsObj.getDefaultParList()
theParamList = self._taskParsObj.getParList()
# Lengths are probably equal but this isn't necessarily an error
# here, so we check for differences below.
if len(self.defaultParamList) != len(theParamList):
# whoa, lengths don't match (could be some missing or some extra)
pmsg = 'Current list not same length as default list'
if not self._handleParListMismatch(pmsg):
return False
# convert current par values to a dict of { par-fullname:par-object }
# for use below
ourpardict = {}
for par in theParamList: ourpardict[par.fullName()] = par
# Sort our paramList according to the order of the defaultParamList
# and repopulate the list according to that order. Create sortednames.
sortednames = [p.fullName() for p in self.defaultParamList]
# Rebuild par list sorted into correct order. Also find/flag any
# missing pars or any extra/unknown pars. This automatically deletes
# "extras" by not adding them to the sorted list in the first place.
migrated = []
newList = []
for fullName in sortednames:
if fullName in ourpardict:
newList.append(ourpardict[fullName])
migrated.append(fullName) # make sure all get moved over
else: # this is a missing par - insert the default version
theDfltVer = \
[p for p in self.defaultParamList if p.fullName()==fullName]
newList.append(copy.deepcopy(theDfltVer[0]))
# Update! Next line writes to the self._taskParsObj.getParList() obj
theParamList[:] = newList # fill with newList, keep same mem pointer
# See if any got left out
extras = [fn for fn in ourpardict if not fn in migrated]
for fullName in extras:
# this is an extra/unknown par - let subclass handle it
if not self._handleParListMismatch('Unexpected par: "'+\
fullName+'"', extra=True):
return False
print('Ignoring unexpected par: "'+p+'"')
# return value indicates that all is well to continue
return True |
<SYSTEM_TASK:>
Save the parameter settings to a user-specified file. Any
<END_TASK>
<USER_TASK:>
Description:
def saveAs(self, event=None):
""" Save the parameter settings to a user-specified file. Any
changes here must be coordinated with the corresponding tpar save_as
function. """ |
self.debug('Clicked Save as...')
# On Linux Pers..Dlg causes the cwd to change, so get a copy of current
curdir = os.getcwd()
# The user wishes to save to a different name
writeProtChoice = self._writeProtectOnSaveAs
if capable.OF_TKFD_IN_EPAR:
# Prompt using native looking dialog
fname = asksaveasfilename(parent=self.top,
title='Save Parameter File As',
defaultextension=self._defSaveAsExt,
initialdir=os.path.dirname(self._getSaveAsFilter()))
else:
# Prompt. (could use tkinter's FileDialog, but this one is prettier)
# initWProtState is only used in the 1st call of a session
from . import filedlg
fd = filedlg.PersistSaveFileDialog(self.top,
"Save Parameter File As", self._getSaveAsFilter(),
initWProtState=writeProtChoice)
if fd.Show() != 1:
fd.DialogCleanup()
os.chdir(curdir) # in case file dlg moved us
return
fname = fd.GetFileName()
writeProtChoice = fd.GetWriteProtectChoice()
fd.DialogCleanup()
if not fname: return # canceled
# First check the child parameters, aborting save if
# invalid entries were encountered
if self.checkSetSaveChildren():
os.chdir(curdir) # in case file dlg moved us
return
# Run any subclass-specific steps right before the save
self._saveAsPreSave_Hook(fname)
# Verify all the entries (without save), keeping track of the invalid
# entries which have been reset to their original input values
self.badEntriesList = self.checkSetSaveEntries(doSave=False)
# If there were invalid entries, prepare the message dialog
if self.badEntriesList:
ansOKCANCEL = self.processBadEntries(self.badEntriesList,
self.taskName)
if not ansOKCANCEL:
os.chdir(curdir) # in case file dlg moved us
return
# If there were no invalid entries or the user says OK, finally
# save to their stated file. Since we have already processed the
# bad entries, there should be none returned.
mstr = "TASKMETA: task="+self.taskName+" package="+self.pkgName
if self.checkSetSaveEntries(doSave=True, filename=fname, comment=mstr,
set_ro=writeProtChoice,
overwriteRO=True):
os.chdir(curdir) # in case file dlg moved us
raise Exception("Unexpected bad entries for: "+self.taskName)
# Run any subclass-specific steps right after the save
self._saveAsPostSave_Hook(fname)
os.chdir(curdir) |
<SYSTEM_TASK:>
Pop up the help in a browser window. By default, this tries to
<END_TASK>
<USER_TASK:>
Description:
def htmlHelp(self, helpString=None, title=None, istask=False, tag=None):
""" Pop up the help in a browser window. By default, this tries to
show the help for the current task. With the option arguments, it can
be used to show any help string. """ |
# Check the help string. If it turns out to be a URL, launch that,
# if not, dump it to a quick and dirty tmp html file to make it
# presentable, and pass that file name as the URL.
if not helpString:
helpString = self.getHelpString(self.pkgName+'.'+self.taskName)
if not title:
title = self.taskName
lwr = helpString.lower()
if lwr.startswith("http:") or lwr.startswith("https:") or \
lwr.startswith("file:"):
url = helpString
if tag and url.find('#') < 0:
url += '#'+tag
# print('LAUNCHING: '+url) # DBG
irafutils.launchBrowser(url, subj=title)
else:
# Write it to a temp HTML file to display
(fd, fname) = tempfile.mkstemp(suffix='.html', prefix='editpar_')
os.close(fd)
f = open(fname, 'w')
if istask and self._knowTaskHelpIsHtml:
f.write(helpString)
else:
f.write('<html><head><title>'+title+'</title></head>\n')
f.write('<body><h3>'+title+'</h3>\n')
f.write('<pre>\n'+helpString+'\n</pre></body></html>')
f.close()
irafutils.launchBrowser("file://"+fname, subj=title) |
<SYSTEM_TASK:>
Return current par value from the GUI. This does not do any
<END_TASK>
<USER_TASK:>
Description:
def getValue(self, name, scope=None, native=False):
""" Return current par value from the GUI. This does not do any
validation, and it it not necessarily the same value saved in the
model, which is always behind the GUI setting, in time. This is NOT
to be used to get all the values - it would not be efficient. """ |
# Get model data, the list of pars
theParamList = self._taskParsObj.getParList()
# NOTE: If par scope is given, it will be used, otherwise it is
# assumed to be unneeded and the first name-match is returned.
fullName = basicpar.makeFullName(scope, name)
# Loop over the parameters to find the requested par
for i in range(self.numParams):
par = theParamList[i] # IrafPar or subclass
entry = self.entryNo[i] # EparOption or subclass
if par.fullName() == fullName or \
(scope is None and par.name == name):
if native:
return entry.convertToNative(entry.choice.get())
else:
return entry.choice.get()
# We didn't find the requested par
raise RuntimeError('Could not find par: "'+fullName+'"') |
<SYSTEM_TASK:>
Internal callback used to make sure the msg list keeps moving.
<END_TASK>
<USER_TASK:>
Description:
def _pushMessages(self):
""" Internal callback used to make sure the msg list keeps moving. """ |
# This continues to get itself called until no msgs are left in list.
self.showStatus('')
if len(self._statusMsgsToShow) > 0:
self.top.after(200, self._pushMessages) |
<SYSTEM_TASK:>
Start the GUI session, or simply load a task's ConfigObj.
<END_TASK>
<USER_TASK:>
Description:
def teal(theTask, parent=None, loadOnly=False, returnAs="dict",
canExecute=True, strict=False, errorsToTerm=False,
autoClose=True, defaults=False):
# overrides=None):
""" Start the GUI session, or simply load a task's ConfigObj. """ |
if loadOnly: # this forces returnAs="dict"
obj = None
try:
obj = cfgpars.getObjectFromTaskArg(theTask, strict, defaults)
# obj.strictUpdate(overrides) # ! would need to re-verify after this !
except Exception as re: # catches RuntimeError and KeyError and ...
# Since we are loadOnly, don't pop up the GUI for this
if strict:
raise
else:
print(re.message.replace('\n\n','\n'))
return obj
else:
assert returnAs in ("dict", "status", None), \
"Invalid value for returnAs arg: "+str(returnAs)
dlg = None
try:
# if setting to all defaults, go ahead and load it here, pre-GUI
if defaults:
theTask = cfgpars.getObjectFromTaskArg(theTask, strict, True)
# now create/run the dialog
dlg = ConfigObjEparDialog(theTask, parent=parent,
autoClose=autoClose,
strict=strict,
canExecute=canExecute)
# overrides=overrides)
except cfgpars.NoCfgFileError as ncf:
log_last_error()
if errorsToTerm:
print(str(ncf).replace('\n\n','\n'))
else:
popUpErr(parent=parent,message=str(ncf),title="Unfound Task")
except Exception as re: # catches RuntimeError and KeyError and ...
log_last_error()
if errorsToTerm:
print(re.message.replace('\n\n','\n'))
else:
popUpErr(parent=parent, message=re.message,
title="Bad Parameters")
# Return, depending on the mode in which we are operating
if returnAs is None:
return
if returnAs == "dict":
if dlg is None or dlg.canceled():
return None
else:
return dlg.getTaskParsObj()
# else, returnAs == "status"
if dlg is None or dlg.canceled():
return -1
if dlg.executed():
return 1
return 0 |
<SYSTEM_TASK:>
Shortcut to load TEAL .cfg files for non-GUI access where
<END_TASK>
<USER_TASK:>
Description:
def load(theTask, canExecute=True, strict=True, defaults=False):
""" Shortcut to load TEAL .cfg files for non-GUI access where
loadOnly=True. """ |
return teal(theTask, parent=None, loadOnly=True, returnAs="dict",
canExecute=canExecute, strict=strict, errorsToTerm=True,
defaults=defaults) |
<SYSTEM_TASK:>
Get a stringified val from a ConfigObj obj and return it as bool
<END_TASK>
<USER_TASK:>
Description:
def cfgGetBool(theObj, name, dflt):
""" Get a stringified val from a ConfigObj obj and return it as bool """ |
strval = theObj.get(name, None)
if strval is None:
return dflt
return strval.lower().strip() == 'true' |
<SYSTEM_TASK:>
Override so that we can run in a different mode.
<END_TASK>
<USER_TASK:>
Description:
def _overrideMasterSettings(self):
""" Override so that we can run in a different mode. """ |
# config-obj dict of defaults
cod = self._getGuiSettings()
# our own GUI setup
self._appName = APP_NAME
self._appHelpString = tealHelpString
self._useSimpleAutoClose = self._do_usac
self._showExtraHelpButton = False
self._saveAndCloseOnExec = cfgGetBool(cod, 'saveAndCloseOnExec', True)
self._showHelpInBrowser = cfgGetBool(cod, 'showHelpInBrowser', False)
self._writeProtectOnSaveAs = cfgGetBool(cod, 'writeProtectOnSaveAsOpt', True)
self._flagNonDefaultVals = cfgGetBool(cod, 'flagNonDefaultVals', None)
self._optFile = APP_NAME.lower()+".optionDB"
# our own colors
# prmdrss teal: #00ffaa, pure cyan (teal) #00ffff (darker) #008080
# "#aaaaee" is a darker but good blue, but "#bbbbff" pops
ltblu = "#ccccff" # light blue
drktl = "#008888" # darkish teal
self._frmeColor = cod.get('frameColor', drktl)
self._taskColor = cod.get('taskBoxColor', ltblu)
self._bboxColor = cod.get('buttonBoxColor', ltblu)
self._entsColor = cod.get('entriesColor', ltblu)
self._flagColor = cod.get('flaggedColor', 'brown')
# double check _canExecute, but only if it is still set to the default
if self._canExecute and self._taskParsObj: # default _canExecute=True
self._canExecute = self._taskParsObj.canExecute()
self._showExecuteButton = self._canExecute
# check on the help string - just to see if it is HTML
# (could use HTMLParser here if need be, be quick and simple tho)
hhh = self.getHelpString(self.pkgName+'.'+self.taskName)
if hhh:
hhh = hhh.lower()
if hhh.find('<html') >= 0 or hhh.find('</html>') > 0:
self._knowTaskHelpIsHtml = True
elif hhh.startswith('http:') or hhh.startswith('https:'):
self._knowTaskHelpIsHtml = True
elif hhh.startswith('file:') and \
(hhh.endswith('.htm') or hhh.endswith('.html')):
self._knowTaskHelpIsHtml = True |
<SYSTEM_TASK:>
Override this so we can handle case of file not writable, as
<END_TASK>
<USER_TASK:>
Description:
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False):
""" Override this so we can handle case of file not writable, as
well as to make our _lastSavedState copy. """ |
self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\
str(set_ro)+', overwriteRO: '+str(overwriteRO))
cantWrite = False
inInstArea = False
if fname in (None, ''): fname = self._taskParsObj.getFilename()
# now do some final checks then save
try:
if _isInstalled(fname): # check: may be installed but not read-only
inInstArea = cantWrite = True
else:
# in case of save-as, allow overwrite of read-only file
if overwriteRO and os.path.exists(fname):
setWritePrivs(fname, True, True) # try make writable
# do the save
rv=self._taskParsObj.saveParList(filename=fname,comment=comment)
except IOError:
cantWrite = True
# User does not have privs to write to this file. Get name of local
# choice and try to use that.
if cantWrite:
fname = self._taskParsObj.getDefaultSaveFilename()
# Tell them the context is changing, and where we are saving
msg = 'Read-only config file for task "'
if inInstArea:
msg = 'Installed config file for task "'
msg += self._taskParsObj.getName()+'" is not to be overwritten.'+\
' Values will be saved to: \n\n\t"'+fname+'".'
showwarning(message=msg, title="Will not overwrite!")
# Try saving to their local copy
rv=self._taskParsObj.saveParList(filename=fname, comment=comment)
# Treat like a save-as (update title for ALL save ops)
self._saveAsPostSave_Hook(fname)
# Limit write privs if requested (only if not in the rc dir)
if set_ro and os.path.dirname(os.path.abspath(fname)) != \
os.path.abspath(self._rcDir):
cfgpars.checkSetReadOnly(fname)
# Before returning, make a copy so we know what was last saved.
# The dict() method returns a deep-copy dict of the keyvals.
self._lastSavedState = self._taskParsObj.dict()
return rv |
<SYSTEM_TASK:>
Override so we can append read-only status.
<END_TASK>
<USER_TASK:>
Description:
def updateTitle(self, atitle):
""" Override so we can append read-only status. """ |
if atitle and os.path.exists(atitle):
if _isInstalled(atitle):
atitle += ' [installed]'
elif not os.access(atitle, os.W_OK):
atitle += ' [read only]'
super(ConfigObjEparDialog, self).updateTitle(atitle) |
<SYSTEM_TASK:>
This is the callback function invoked when an item is edited.
<END_TASK>
<USER_TASK:>
Description:
def edited(self, scope, name, lastSavedVal, newVal, action):
""" This is the callback function invoked when an item is edited.
This is only called for those items which were previously
specified to use this mechanism. We do not turn this on for
all items because the performance might be prohibitive.
This kicks off any previously registered triggers. """ |
# Get name(s) of any triggers that this par triggers
triggerNamesTup = self._taskParsObj.getTriggerStrings(scope, name)
assert triggerNamesTup is not None and len(triggerNamesTup) > 0, \
'Empty trigger name for: "'+name+'", consult the .cfgspc file.'
# Loop through all trigger names - each one is a trigger to kick off -
# in the order that they appear in the tuple we got. Most cases will
# probably only have a single trigger in the tuple.
for triggerName in triggerNamesTup:
# First handle the known/canned trigger names
# print (scope, name, newVal, action, triggerName) # DBG: debug line
# _section_switch_
if triggerName == '_section_switch_':
# Try to uniformly handle all possible par types here, not
# just boolean (e.g. str, int, float, etc.)
# Also, see logic in _BooleanMixin._coerceOneValue()
state = newVal not in self.FALSEVALS
self._toggleSectionActiveState(scope, state, (name,))
continue
# _2_section_switch_ (see notes above in _section_switch_)
if triggerName == '_2_section_switch_':
state = newVal not in self.FALSEVALS
# toggle most of 1st section (as usual) and ALL of next section
self._toggleSectionActiveState(scope, state, (name,))
# get first par of next section (fpons) - is a tuple
fpons = self.findNextSection(scope, name)
nextSectScope = fpons[0]
if nextSectScope:
self._toggleSectionActiveState(nextSectScope, state, None)
continue
# Now handle rules with embedded code (eg. triggerName=='_rule1_')
if '_RULES_' in self._taskParsObj and \
triggerName in self._taskParsObj['_RULES_'].configspec:
# Get codeStr to execute it, but before we do so, check 'when' -
# make sure this is an action that is allowed to cause a trigger
ruleSig = self._taskParsObj['_RULES_'].configspec[triggerName]
chkArgsDict = vtor_checks.sigStrToKwArgsDict(ruleSig)
codeStr = chkArgsDict.get('code') # or None if didn't specify
when2run = chkArgsDict.get('when') # or None if didn't specify
greenlight = False # do we have a green light to eval the rule?
if when2run is None:
greenlight = True # means run rule for any possible action
else: # 'when' was set to something so we need to check action
# check value of action (poor man's enum)
assert action in editpar.GROUP_ACTIONS, \
"Unknown action: "+str(action)+', expected one of: '+ \
str(editpar.GROUP_ACTIONS)
# check value of 'when' (allow them to use comma-sep'd str)
# (readers be aware that values must be those possible for
# 'action', and 'always' is also allowed)
whenlist = when2run.split(',')
# warn for invalid values
for w in whenlist:
if not w in editpar.GROUP_ACTIONS and w != 'always':
print('WARNING: skipping bad value for when kwd: "'+\
w+'" in trigger/rule: '+triggerName)
# finally, do the correlation
greenlight = 'always' in whenlist or action in whenlist
# SECURITY NOTE: because this part executes arbitrary code, that
# code string must always be found only in the configspec file,
# which is intended to only ever be root-installed w/ the pkg.
if codeStr:
if not greenlight:
continue # not an error, just skip this one
self.showStatus("Evaluating "+triggerName+' ...') #dont keep
self.top.update_idletasks() #allow msg to draw prior to exec
# execute it and retrieve the outcome
try:
outval = execEmbCode(scope, name, newVal, self, codeStr)
except Exception as ex:
outval = 'ERROR in '+triggerName+': '+str(ex)
print(outval)
msg = outval+':\n'+('-'*99)+'\n'+traceback.format_exc()
msg += 'CODE: '+codeStr+'\n'+'-'*99+'\n'
self.debug(msg)
self.showStatus(outval, keep=1)
# Leave this debug line in until it annoys someone
msg = 'Value of "'+name+'" triggered "'+triggerName+'"'
stroutval = str(outval)
if len(stroutval) < 30: msg += ' --> "'+stroutval+'"'
self.showStatus(msg, keep=0)
# Now that we have triggerName evaluated to outval, we need
# to look through all the parameters and see if there are
# any items to be affected by triggerName (e.g. '_rule1_')
self._applyTriggerValue(triggerName, outval)
continue
# If we get here, we have an unknown/unusable trigger
raise RuntimeError('Unknown trigger for: "'+name+'", named: "'+ \
str(triggerName)+'". Please consult the .cfgspc file.') |
<SYSTEM_TASK:>
Overridden version for ConfigObj. theTask can be either
<END_TASK>
<USER_TASK:>
Description:
def _setTaskParsObj(self, theTask):
""" Overridden version for ConfigObj. theTask can be either
a .cfg file name or a ConfigObjPars object. """ |
# Create the ConfigObjPars obj
self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask,
self._strict, False)
# Tell it that we can be used for catching debug lines
self._taskParsObj.setDebugLogger(self)
# Immediately make a copy of it's un-tampered internal dict.
# The dict() method returns a deep-copy dict of the keyvals.
self._lastSavedState = self._taskParsObj.dict() |
<SYSTEM_TASK:>
Return a string to be used as the filter arg to the save file
<END_TASK>
<USER_TASK:>
Description:
def _getSaveAsFilter(self):
""" Return a string to be used as the filter arg to the save file
dialog during Save-As. """ |
# figure the dir to use, start with the one from the file
absRcDir = os.path.abspath(self._rcDir)
thedir = os.path.abspath(os.path.dirname(self._taskParsObj.filename))
# skip if not writeable, or if is _rcDir
if thedir == absRcDir or not os.access(thedir, os.W_OK):
thedir = os.path.abspath(os.path.curdir)
# create save-as filter string
filt = thedir+'/*.cfg'
envVarName = APP_NAME.upper()+'_CFG'
if envVarName in os.environ:
upx = os.environ[envVarName]
if len(upx) > 0: filt = upx+"/*.cfg"
# done
return filt |
<SYSTEM_TASK:>
Go through all possible sites to find applicable .cfg files.
<END_TASK>
<USER_TASK:>
Description:
def _getOpenChoices(self):
""" Go through all possible sites to find applicable .cfg files.
Return as an iterable. """ |
tsk = self._taskParsObj.getName()
taskFiles = set()
dirsSoFar = [] # this helps speed this up (skip unneeded globs)
# last dir
aDir = os.path.dirname(self._taskParsObj.filename)
if len(aDir) < 1: aDir = os.curdir
dirsSoFar.append(aDir)
taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk))
# current dir
aDir = os.getcwd()
if aDir not in dirsSoFar:
dirsSoFar.append(aDir)
taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk))
# task's python pkg dir (if tsk == python pkg name)
try:
x, pkgf = cfgpars.findCfgFileForPkg(tsk, '.cfg', taskName=tsk,
pkgObj=self._taskParsObj.getAssocPkg())
taskFiles.update( (pkgf,) )
except cfgpars.NoCfgFileError:
pass # no big deal - maybe there is no python package
# user's own resourceDir
aDir = self._rcDir
if aDir not in dirsSoFar:
dirsSoFar.append(aDir)
taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk))
# extra loc - see if they used the app's env. var
aDir = dirsSoFar[0] # flag to skip this if no env var found
envVarName = APP_NAME.upper()+'_CFG'
if envVarName in os.environ: aDir = os.environ[envVarName]
if aDir not in dirsSoFar:
dirsSoFar.append(aDir)
taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk))
# At the very end, add an option which we will later interpret to mean
# to open the file dialog.
taskFiles = list(taskFiles) # so as to keep next item at end of seq
taskFiles.sort()
taskFiles.append("Other ...")
return taskFiles |
<SYSTEM_TASK:>
Load the parameter settings from a user-specified file.
<END_TASK>
<USER_TASK:>
Description:
def pfopen(self, event=None):
""" Load the parameter settings from a user-specified file. """ |
# Get the selected file name
fname = self._openMenuChoice.get()
# Also allow them to simply find any file - do not check _task_name_...
# (could use tkinter's FileDialog, but this one is prettier)
if fname[-3:] == '...':
if capable.OF_TKFD_IN_EPAR:
fname = askopenfilename(title="Load Config File",
parent=self.top)
else:
from . import filedlg
fd = filedlg.PersistLoadFileDialog(self.top,
"Load Config File",
self._getSaveAsFilter())
if fd.Show() != 1:
fd.DialogCleanup()
return
fname = fd.GetFileName()
fd.DialogCleanup()
if not fname: return # canceled
self.debug('Loading from: '+fname)
# load it into a tmp object (use associatedPkg if we have one)
try:
tmpObj = cfgpars.ConfigObjPars(fname, associatedPkg=\
self._taskParsObj.getAssocPkg(),
strict=self._strict)
except Exception as ex:
showerror(message=ex.message, title='Error in '+os.path.basename(fname))
self.debug('Error in '+os.path.basename(fname))
self.debug(traceback.format_exc())
return
# check it to make sure it is a match
if not self._taskParsObj.isSameTaskAs(tmpObj):
msg = 'The current task is "'+self._taskParsObj.getName()+ \
'", but the selected file is for task "'+ \
str(tmpObj.getName())+'". This file was not loaded.'
showerror(message=msg, title="Error in "+os.path.basename(fname))
self.debug(msg)
self.debug(traceback.format_exc())
return
# Set the GUI entries to these values (let the user Save after)
newParList = tmpObj.getParList()
try:
self.setAllEntriesFromParList(newParList, updateModel=True)
# go ahead and updateModel, even though it will take longer,
# we need it updated for the copy of the dict we make below
except editpar.UnfoundParamError as pe:
showwarning(message=str(pe), title="Error in "+os.path.basename(fname))
# trip any triggers
self.checkAllTriggers('fopen')
# This new fname is our current context
self.updateTitle(fname)
self._taskParsObj.filename = fname # !! maybe try setCurrentContext() ?
self.freshenFocus()
self.showStatus("Loaded values from: "+fname, keep=2)
# Since we are in a new context (and have made no changes yet), make
# a copy so we know what the last state was.
# The dict() method returns a deep-copy dict of the keyvals.
self._lastSavedState = self._taskParsObj.dict() |
<SYSTEM_TASK:>
Override to include ConfigObj filename and specific errors.
<END_TASK>
<USER_TASK:>
Description:
def _handleParListMismatch(self, probStr, extra=False):
""" Override to include ConfigObj filename and specific errors.
Note that this only handles "missing" pars and "extra" pars, not
wrong-type pars. So it isn't that big of a deal. """ |
# keep down the duplicate errors
if extra:
return True # the base class is already stating it will be ignored
# find the actual errors, and then add that to the generic message
errmsg = 'Warning: '
if self._strict:
errmsg = 'ERROR: '
errmsg = errmsg+'mismatch between default and current par lists ' + \
'for task "'+self.taskName+'".'
if probStr:
errmsg += '\n\t'+probStr
errmsg += '\nTry editing/deleting: "' + \
self._taskParsObj.filename+'" (or, if in PyRAF: "unlearn ' + \
self.taskName+'").'
print(errmsg)
return True |
<SYSTEM_TASK:>
Load the default parameter settings into the GUI.
<END_TASK>
<USER_TASK:>
Description:
def _setToDefaults(self):
""" Load the default parameter settings into the GUI. """ |
# Create an empty object, where every item is set to it's default value
try:
tmpObj = cfgpars.ConfigObjPars(self._taskParsObj.filename,
associatedPkg=\
self._taskParsObj.getAssocPkg(),
setAllToDefaults=self.taskName,
strict=False)
except Exception as ex:
msg = "Error Determining Defaults"
showerror(message=msg+'\n\n'+ex.message, title="Error Determining Defaults")
return
# Set the GUI entries to these values (let the user Save after)
tmpObj.filename = self._taskParsObj.filename = '' # name it later
newParList = tmpObj.getParList()
try:
self.setAllEntriesFromParList(newParList) # needn't updateModel yet
self.checkAllTriggers('defaults')
self.updateTitle('')
self.showStatus("Loaded default "+self.taskName+" values via: "+ \
os.path.basename(tmpObj._original_configspec), keep=1)
except editpar.UnfoundParamError as pe:
showerror(message=str(pe), title="Error Setting to Default Values") |
<SYSTEM_TASK:>
Load the parameter settings from a given dict into the GUI.
<END_TASK>
<USER_TASK:>
Description:
def loadDict(self, theDict):
""" Load the parameter settings from a given dict into the GUI. """ |
# We are going to have to merge this info into ourselves so let's
# first make sure all of our models are up to date with the values in
# the GUI right now.
badList = self.checkSetSaveEntries(doSave=False)
if badList:
if not self.processBadEntries(badList, self.taskName):
return
# now, self._taskParsObj is up-to-date
# So now we update _taskParsObj with the input dict
cfgpars.mergeConfigObj(self._taskParsObj, theDict)
# now sync the _taskParsObj dict with its par list model
# '\n'.join([str(jj) for jj in self._taskParsObj.getParList()])
self._taskParsObj.syncParamList(False)
# Set the GUI entries to these values (let the user Save after)
try:
self.setAllEntriesFromParList(self._taskParsObj.getParList(),
updateModel=True)
self.checkAllTriggers('fopen')
self.freshenFocus()
self.showStatus('Loaded '+str(len(theDict))+ \
' user par values for: '+self.taskName, keep=1)
except Exception as ex:
showerror(message=ex.message, title="Error Setting to Loaded Values") |
<SYSTEM_TASK:>
Here we look through the entire .cfgspc to see if any parameters
<END_TASK>
<USER_TASK:>
Description:
def _applyTriggerValue(self, triggerName, outval):
""" Here we look through the entire .cfgspc to see if any parameters
are affected by this trigger. For those that are, we apply the action
to the GUI widget. The action is specified by depType. """ |
# First find which items are dependent upon this trigger (cached)
# e.g. { scope1.name1 : dep'cy-type, scope2.name2 : dep'cy-type, ... }
depParsDict = self._taskParsObj.getParsWhoDependOn(triggerName)
if not depParsDict: return
if 0: print("Dependent parameters:\n"+str(depParsDict)+"\n")
# Get model data, the list of pars
theParamList = self._taskParsObj.getParList()
# Then go through the dependent pars and apply the trigger to them
settingMsg = ''
for absName in depParsDict:
used = False
# For each dep par, loop to find the widget for that scope.name
for i in range(self.numParams):
scopedName = theParamList[i].scope+'.'+theParamList[i].name # diff from makeFullName!!
if absName == scopedName: # a match was found
depType = depParsDict[absName]
if depType == 'active_if':
self.entryNo[i].setActiveState(outval)
elif depType == 'inactive_if':
self.entryNo[i].setActiveState(not outval)
elif depType == 'is_set_by':
self.entryNo[i].forceValue(outval, noteEdited=True)
# WARNING! noteEdited=True may start recursion!
if len(settingMsg) > 0: settingMsg += ", "
settingMsg += '"'+theParamList[i].name+'" to "'+\
outval+'"'
elif depType in ('set_yes_if', 'set_no_if'):
if bool(outval):
newval = 'yes'
if depType == 'set_no_if': newval = 'no'
self.entryNo[i].forceValue(newval, noteEdited=True)
# WARNING! noteEdited=True may start recursion!
if len(settingMsg) > 0: settingMsg += ", "
settingMsg += '"'+theParamList[i].name+'" to "'+\
newval+'"'
else:
if len(settingMsg) > 0: settingMsg += ", "
settingMsg += '"'+theParamList[i].name+\
'" (no change)'
elif depType == 'is_disabled_by':
# this one is only used with boolean types
on = self.entryNo[i].convertToNative(outval)
if on:
# do not activate whole section or change
# any values, only activate this one
self.entryNo[i].setActiveState(True)
else:
# for off, set the bool par AND grey WHOLE section
self.entryNo[i].forceValue(outval, noteEdited=True)
self.entryNo[i].setActiveState(False)
# we'd need this if the par had no _section_switch_
# self._toggleSectionActiveState(
# theParamList[i].scope, False, None)
if len(settingMsg) > 0: settingMsg += ", "
settingMsg += '"'+theParamList[i].name+'" to "'+\
outval+'"'
else:
raise RuntimeError('Unknown dependency: "'+depType+ \
'" for par: "'+scopedName+'"')
used = True
break
# Or maybe it is a whole section
if absName.endswith('._section_'):
scope = absName[:-10]
depType = depParsDict[absName]
if depType == 'active_if':
self._toggleSectionActiveState(scope, outval, None)
elif depType == 'inactive_if':
self._toggleSectionActiveState(scope, not outval, None)
used = True
# Help to debug the .cfgspc rules
if not used:
raise RuntimeError('UNUSED "'+triggerName+'" dependency: '+ \
str({absName:depParsDict[absName]}))
if len(settingMsg) > 0:
# why ?! self.freshenFocus()
self.showStatus('Automatically set '+settingMsg, keep=1) |
<SYSTEM_TASK:>
Reads a shift file from disk and populates a dictionary.
<END_TASK>
<USER_TASK:>
Description:
def readShiftFile(self, filename):
"""
Reads a shift file from disk and populates a dictionary.
""" |
order = []
fshift = open(filename,'r')
flines = fshift.readlines()
fshift.close()
common = [f.strip('#').strip() for f in flines if f.startswith('#')]
c=[line.split(': ') for line in common]
# Remove any line comments in the shift file - lines starting with '#'
# but not part of the common block.
for l in c:
if l[0] not in ['frame', 'refimage', 'form', 'units']:
c.remove(l)
for line in c: line[1]=line[1].strip()
self.update(c)
files = [f.strip().split(' ',1) for f in flines if not (f.startswith('#') or f.strip() == '')]
for f in files:
order.append(f[0])
self['order'] = order
for f in files:
# Check to see if filename provided is a full filename that corresponds
# to a file on the path. If not, try to convert given rootname into
# a valid filename based on available files. This may or may not
# define the correct filename, which is why it prints out what it is
# doing, so that the user can verify and edit the shiftfile if needed.
#NOTE:
# Supporting the specification of only rootnames in the shiftfile with this
# filename expansion is NOT to be documented, but provided solely as
# an undocumented, dangerous and not fully supported helper function for
# some backwards compatibility.
if not os.path.exists(f[0]):
f[0] = fu.buildRootname(f[0])
print('Defining filename in shiftfile as: ', f[0])
f[1] = f[1].split()
try:
f[1] = [float(s) for s in f[1]]
except:
msg = 'Cannot read in ', s, ' from shiftfile ', filename, ' as a float number'
raise ValueError(msg)
msg = "At least 2 and at most 4 shift values should be provided in a shiftfile"
if len(f[1]) < 2:
raise ValueError(msg)
elif len(f[1]) == 3:
f[1].append(1.0)
elif len(f[1]) == 2:
f[1].extend([0.0, 1.0])
elif len(f[1]) > 4:
raise ValueError(msg)
fdict = dict(files)
self.update(fdict) |
<SYSTEM_TASK:>
Writes a shift file object to a file on disk using the convention for shift file format.
<END_TASK>
<USER_TASK:>
Description:
def writeShiftFile(self, filename="shifts.txt"):
"""
Writes a shift file object to a file on disk using the convention for shift file format.
""" |
lines = ['# frame: ', self['frame'], '\n',
'# refimage: ', self['refimage'], '\n',
'# form: ', self['form'], '\n',
'# units: ', self['units'], '\n']
for o in self['order']:
ss = " "
for shift in self[o]:
ss += str(shift) + " "
line = str(o) + ss + "\n"
lines.append(line)
fshifts= open(filename, 'w')
fshifts.writelines(lines)
fshifts.close() |
<SYSTEM_TASK:>
Low-level weaver for instances.
<END_TASK>
<USER_TASK:>
Description:
def weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options):
"""
Low-level weaver for instances.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
""" |
if bag.has(instance):
return Nothing
entanglement = Rollback()
method_matches = make_method_matcher(methods)
logdebug("weave_instance (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)",
instance, aspect, methods, lazy, options)
def fixup(func):
return func.__get__(instance, type(instance))
fixed_aspect = aspect + [fixup] if isinstance(aspect, (list, tuple)) else [aspect, fixup]
for attr in dir(instance):
func = getattr(instance, attr)
if method_matches(attr):
if ismethod(func):
if hasattr(func, '__func__'):
realfunc = func.__func__
else:
realfunc = func.im_func
entanglement.merge(
patch_module(instance, attr, _checked_apply(fixed_aspect, realfunc, module=None), **options)
)
return entanglement |
<SYSTEM_TASK:>
Low-level weaver for "whole module weaving".
<END_TASK>
<USER_TASK:>
Description:
def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options):
"""
Low-level weaver for "whole module weaving".
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
""" |
if bag.has(module):
return Nothing
entanglement = Rollback()
method_matches = make_method_matcher(methods)
logdebug("weave_module (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)",
module, aspect, methods, lazy, options)
for attr in dir(module):
func = getattr(module, attr)
if method_matches(attr):
if isroutine(func):
entanglement.merge(patch_module_function(module, func, aspect, force_name=attr, **options))
elif isclass(func):
entanglement.merge(
weave_class(func, aspect, owner=module, name=attr, methods=methods, lazy=lazy, bag=bag, **options),
# it's not consistent with the other ways of weaving a class (it's never weaved as a routine).
# therefore it's disabled until it's considered useful.
# #patch_module_function(module, getattr(module, attr), aspect, force_name=attr, **options),
)
return entanglement |
<SYSTEM_TASK:>
Low-level attribute patcher.
<END_TASK>
<USER_TASK:>
Description:
def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options):
"""
Low-level attribute patcher.
:param module module: Object to patch.
:param str name: Attribute to patch
:param replacement: The replacement value.
:param original: The original value (in case the object beeing patched uses descriptors or is plain weird).
:param bool aliases: If ``True`` patch all the attributes that have the same original value.
:returns: An :obj:`aspectlib.Rollback` object.
""" |
rollback = Rollback()
seen = False
original = getattr(module, name) if original is UNSPECIFIED else original
location = module.__name__ if hasattr(module, '__name__') else type(module).__module__
target = module.__name__ if hasattr(module, '__name__') else type(module).__name__
try:
replacement.__module__ = location
except (TypeError, AttributeError):
pass
for alias in dir(module):
logdebug("alias:%s (%s)", alias, name)
if hasattr(module, alias):
obj = getattr(module, alias)
logdebug("- %s:%s (%s)", obj, original, obj is original)
if obj is original:
if aliases or alias == name:
logdebug("= saving %s on %s.%s ...", replacement, target, alias)
setattr(module, alias, replacement)
rollback.merge(lambda alias=alias: setattr(module, alias, original))
if alias == name:
seen = True
elif alias == name:
if ismethod(obj):
logdebug("= saving %s on %s.%s ...", replacement, target, alias)
setattr(module, alias, replacement)
rollback.merge(lambda alias=alias: setattr(module, alias, original))
seen = True
else:
raise AssertionError("%s.%s = %s is not %s." % (module, alias, obj, original))
if not seen:
warnings.warn('Setting %s.%s to %s. There was no previous definition, probably patching the wrong module.' % (
target, name, replacement
))
logdebug("= saving %s on %s.%s ...", replacement, target, name)
setattr(module, name, replacement)
rollback.merge(lambda: setattr(module, name, original))
return rollback |
<SYSTEM_TASK:>
Low-level patcher for one function from a specified module.
<END_TASK>
<USER_TASK:>
Description:
def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options):
"""
Low-level patcher for one function from a specified module.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
""" |
logdebug("patch_module_function (module=%s, target=%s, aspect=%s, force_name=%s, **options=%s",
module, target, aspect, force_name, options)
name = force_name or target.__name__
return patch_module(module, name, _checked_apply(aspect, target, module=module), original=target, **options) |
<SYSTEM_TASK:>
Remove byte stuffing from a TSIP packet.
<END_TASK>
<USER_TASK:>
Description:
def unstuff(packet):
"""
Remove byte stuffing from a TSIP packet.
:param packet: TSIP packet with byte stuffing. The packet must already
have been stripped or `ValueError` will be raised.
:type packet: Binary string.
:return: Packet without byte stuffing.
""" |
if is_framed(packet):
raise ValueError('packet contains leading DLE and trailing DLE/ETX')
else:
return packet.replace(CHR_DLE + CHR_DLE, CHR_DLE) |
<SYSTEM_TASK:>
Opens the file for subsequent access.
<END_TASK>
<USER_TASK:>
Description:
def open(self):
""" Opens the file for subsequent access. """ |
if self.handle is None:
self.handle = fits.open(self.fname, mode='readonly')
if self.extn:
if len(self.extn) == 1:
hdu = self.handle[self.extn[0]]
else:
hdu = self.handle[self.extn[0],self.extn[1]]
else:
hdu = self.handle[0]
if isinstance(hdu,fits.hdu.compressed.CompImageHDU):
self.compress = True
return hdu |
<SYSTEM_TASK:>
Reloads the completed measurements from the backing store.
<END_TASK>
<USER_TASK:>
Description:
def reloadCompletedMeasurements(self):
"""
Reloads the completed measurements from the backing store.
""" |
from pathlib import Path
reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()]
logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements')
self.completeMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.COMPLETE]
self.failedMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.FAILED] |
<SYSTEM_TASK:>
Removes files with EXPTIME==0 from filelist.
<END_TASK>
<USER_TASK:>
Description:
def check_exptime(filelist):
"""
Removes files with EXPTIME==0 from filelist.
""" |
toclose = False
removed_files = []
for f in filelist:
if isinstance(f, str):
f = fits.open(f)
toclose = True
try:
exptime = f[0].header['EXPTIME']
except KeyError:
removed_files.append(f)
print("Warning: There are files without keyword EXPTIME")
continue
if exptime <= 0:
removed_files.append(f)
print("Warning: There are files with zero exposure time: keyword EXPTIME = 0.0")
if removed_files != []:
print("Warning: Removing the following files from input list")
for f in removed_files:
print('\t',f.filename() or "")
return removed_files |
<SYSTEM_TASK:>
Checks if a file is in WAIVER of GEIS format and converts it to MEF
<END_TASK>
<USER_TASK:>
Description:
def convert2fits(sci_ivm):
"""
Checks if a file is in WAIVER of GEIS format and converts it to MEF
""" |
removed_files = []
translated_names = []
newivmlist = []
for file in sci_ivm:
#find out what the input is
# if science file is not found on disk, add it to removed_files for removal
try:
imgfits,imgtype = fileutil.isFits(file[0])
except IOError:
print("Warning: File %s could not be found" %file[0])
print("Warning: Removing file %s from input list" %file[0])
removed_files.append(file[0])
continue
# Check for existence of waiver FITS input, and quit if found.
# Or should we print a warning and continue but not use that file
if imgfits and imgtype == 'waiver':
newfilename = waiver2mef(file[0], convert_dq=True)
if newfilename is None:
print("Removing file %s from input list - could not convert WAIVER format to MEF\n" %file[0])
removed_files.append(file[0])
else:
removed_files.append(file[0])
translated_names.append(newfilename)
newivmlist.append(file[1])
# If a GEIS image is provided as input, create a new MEF file with
# a name generated using 'buildFITSName()'
# Convert the corresponding data quality file if present
if not imgfits:
newfilename = geis2mef(file[0], convert_dq=True)
if newfilename is None:
print("Removing file %s from input list - could not convert GEIS format to MEF\n" %file[0])
removed_files.append(file[0])
else:
removed_files.append(file[0])
translated_names.append(newfilename)
newivmlist.append(file[1])
return removed_files, translated_names, newivmlist |
<SYSTEM_TASK:>
Converts input bits value from string to a single integer value or None.
<END_TASK>
<USER_TASK:>
Description:
def interpret_bits_value(val):
"""
Converts input bits value from string to a single integer value or None.
If a comma- or '+'-separated set of values are provided, they are summed.
.. note::
In order to flip the bits of the final result (after summation),
for input of `str` type, prepend '~' to the input string. '~' must
be prepended to the *entire string* and not to each bit flag!
Parameters
----------
val : int, str, None
An integer bit mask or flag, `None`, or a comma- or '+'-separated
string list of integer bit values. If `val` is a `str` and if
it is prepended with '~', then the output bit mask will have its
bits flipped (compared to simple sum of input val).
Returns
-------
bitmask : int or None
Returns and integer bit mask formed from the input bit value
or `None` if input `val` parameter is `None` or an empty string.
If input string value was prepended with '~', then returned
value will have its bits flipped (inverse mask).
""" |
if isinstance(val, int) or val is None:
return val
else:
val = str(val).strip()
if val.startswith('~'):
flip_bits = True
val = val[1:].lstrip()
else:
flip_bits = False
if val.startswith('('):
if val.endswith(')'):
val = val[1:-1].strip()
else:
raise ValueError('Unbalanced parantheses or incorrect syntax.')
if ',' in val:
valspl = val.split(',')
bitmask = 0
for v in valspl:
bitmask += int(v)
elif '+' in val:
valspl = val.split('+')
bitmask = 0
for v in valspl:
bitmask += int(v)
elif val.upper() in ['', 'NONE', 'INDEF']:
return None
else:
bitmask = int(val)
if flip_bits:
bitmask = ~bitmask
return bitmask |
<SYSTEM_TASK:>
Return a Point instance as the displacement of two points.
<END_TASK>
<USER_TASK:>
Description:
def substract(self, pt):
"""Return a Point instance as the displacement of two points.""" |
if isinstance(pt, Point):
return Point(pt.x - self.x, pt.y - self.y, pt.z - self.z)
else:
raise TypeError |
<SYSTEM_TASK:>
Return a Point instance from a given list
<END_TASK>
<USER_TASK:>
Description:
def from_list(cls, l):
"""Return a Point instance from a given list""" |
if len(l) == 3:
x, y, z = map(float, l)
return cls(x, y, z)
elif len(l) == 2:
x, y = map(float, l)
return cls(x, y)
else:
raise AttributeError |
<SYSTEM_TASK:>
Return a Vector as the product of the vector and a real number.
<END_TASK>
<USER_TASK:>
Description:
def multiply(self, number):
"""Return a Vector as the product of the vector and a real number.""" |
return self.from_list([x * number for x in self.to_list()]) |
<SYSTEM_TASK:>
Return a Vector instance as the vector sum of two vectors.
<END_TASK>
<USER_TASK:>
Description:
def sum(self, vector):
"""Return a Vector instance as the vector sum of two vectors.""" |
return self.from_list(
[x + vector.vector[i] for i, x in self.to_list()]
) |
<SYSTEM_TASK:>
Return the dot product of two vectors.
<END_TASK>
<USER_TASK:>
Description:
def dot(self, vector, theta=None):
"""Return the dot product of two vectors.
If theta is given then the dot product is computed as
v1*v1 = |v1||v2|cos(theta). Argument theta
is measured in degrees.
""" |
if theta is not None:
return (self.magnitude() * vector.magnitude() *
math.degrees(math.cos(theta)))
return (reduce(lambda x, y: x + y,
[x * vector.vector[i] for i, x in self.to_list()()])) |
<SYSTEM_TASK:>
Return a Vector instance as the cross product of two vectors
<END_TASK>
<USER_TASK:>
Description:
def cross(self, vector):
"""Return a Vector instance as the cross product of two vectors""" |
return Vector((self.y * vector.z - self.z * vector.y),
(self.z * vector.x - self.x * vector.z),
(self.x * vector.y - self.y * vector.x)) |
<SYSTEM_TASK:>
Return a Vector instance of the unit vector
<END_TASK>
<USER_TASK:>
Description:
def unit(self):
"""Return a Vector instance of the unit vector""" |
return Vector(
(self.x / self.magnitude()),
(self.y / self.magnitude()),
(self.z / self.magnitude())
) |
<SYSTEM_TASK:>
Return the angle between two vectors in degrees.
<END_TASK>
<USER_TASK:>
Description:
def angle(self, vector):
"""Return the angle between two vectors in degrees.""" |
return math.degrees(
math.acos(
self.dot(vector) /
(self.magnitude() * vector.magnitude())
)
) |
<SYSTEM_TASK:>
Return True if vectors are non-parallel.
<END_TASK>
<USER_TASK:>
Description:
def non_parallel(self, vector):
"""Return True if vectors are non-parallel.
Non-parallel vectors are vectors which are neither parallel
nor perpendicular to each other.
""" |
if (self.is_parallel(vector) is not True and
self.is_perpendicular(vector) is not True):
return True
return False |
<SYSTEM_TASK:>
Returns the rotated vector. Assumes angle is in radians
<END_TASK>
<USER_TASK:>
Description:
def rotate(self, angle, axis=(0, 0, 1)):
"""Returns the rotated vector. Assumes angle is in radians""" |
if not all(isinstance(a, int) for a in axis):
raise ValueError
x, y, z = self.x, self.y, self.z
# Z axis rotation
if(axis[2]):
x = (self.x * math.cos(angle) - self.y * math.sin(angle))
y = (self.x * math.sin(angle) + self.y * math.cos(angle))
# Y axis rotation
if(axis[1]):
x = self.x * math.cos(angle) + self.z * math.sin(angle)
z = -self.x * math.sin(angle) + self.z * math.cos(angle)
# X axis rotation
if(axis[0]):
y = self.y * math.cos(angle) - self.z * math.sin(angle)
z = self.y * math.sin(angle) + self.z * math.cos(angle)
return Vector(x, y, z) |
<SYSTEM_TASK:>
Return a Vector instance from two given points.
<END_TASK>
<USER_TASK:>
Description:
def from_points(cls, point1, point2):
"""Return a Vector instance from two given points.""" |
if isinstance(point1, Point) and isinstance(point2, Point):
displacement = point1.substract(point2)
return cls(displacement.x, displacement.y, displacement.z)
raise TypeError |
<SYSTEM_TASK:>
Returns a list of filenames based on the type of IRAF input.
<END_TASK>
<USER_TASK:>
Description:
def irafglob(inlist, atfile=None):
""" Returns a list of filenames based on the type of IRAF input.
Handles lists, wild-card characters, and at-files. For special
at-files, use the atfile keyword to process them.
This function is recursive, so IRAF lists can also contain at-files
and wild-card characters, e.g. `a.fits`, `@file.lst`, `*flt.fits`.
""" |
# Sanity check
if inlist is None or len(inlist) == 0:
return []
# Determine which form of input was provided:
if isinstance(inlist, list):
# python list
flist = []
for f in inlist:
flist += irafglob(f)
elif ',' in inlist:
# comma-separated string list
flist = []
for f in inlist.split(','):
f = f.strip()
flist += irafglob(f)
elif inlist[0] == '@':
# file list
flist = []
for f in open(inlist[1:], 'r').readlines():
f = f.rstrip()
# hook for application specific atfiles.
if atfile:
f = atfile(f)
flist += irafglob(f)
else:
# shell globbing
if osfn:
inlist = osfn(inlist)
flist = glob.glob(inlist)
return flist |
<SYSTEM_TASK:>
Return binary format of packet.
<END_TASK>
<USER_TASK:>
Description:
def pack(self):
"""Return binary format of packet.
The returned string is the binary format of the packet with
stuffing and framing applied. It is ready to be sent to
the GPS.
""" |
# Possible structs for packet ID.
#
try:
structs_ = get_structs_for_fields([self.fields[0]])
except (TypeError):
# TypeError, if self.fields[0] is a wrong argument to `chr()`.
raise PackError(self)
# Possible structs for packet ID + subcode
#
if structs_ == []:
try:
structs_ = get_structs_for_fields([self.fields[0], self.fields[1]])
except (IndexError, TypeError):
# IndexError, if no self.fields[1]
# TypeError, if self.fields[1] is a wrong argument to `chr()`.
raise PackError(self)
# Try to pack the packet with any of the possible structs.
#
for struct_ in structs_:
try:
return struct_.pack(*self.fields)
except struct.error:
pass
# We only get here if the ``return`` inside the``for`` loop
# above wasn't reached, i.e. none of the `structs_` matched.
#
raise PackError(self) |
<SYSTEM_TASK:>
Instantiate `Packet` from binary string.
<END_TASK>
<USER_TASK:>
Description:
def unpack(cls, rawpacket):
"""Instantiate `Packet` from binary string.
:param rawpacket: TSIP pkt in binary format.
:type rawpacket: String.
`rawpacket` must already have framing (DLE...DLE/ETX) removed and
byte stuffing reversed.
""" |
structs_ = get_structs_for_rawpacket(rawpacket)
for struct_ in structs_:
try:
return cls(*struct_.unpack(rawpacket))
except struct.error:
raise
# Try next one.
pass
# Packet ID 0xff is a pseudo-packet representing
# packets unknown to `python-TSIP` in their raw format.
#
return cls(0xff, rawpacket) |
<SYSTEM_TASK:>
Handle standard PRIMARY clipboard access. Note that offset and length
<END_TASK>
<USER_TASK:>
Description:
def ch_handler(offset=0, length=-1, **kw):
""" Handle standard PRIMARY clipboard access. Note that offset and length
are passed as strings. This differs from CLIPBOARD. """ |
global _lastSel
offset = int(offset)
length = int(length)
if length < 0: length = len(_lastSel)
return _lastSel[offset:offset+length] |
<SYSTEM_TASK:>
Put the given string into the given clipboard.
<END_TASK>
<USER_TASK:>
Description:
def put(text, cbname):
""" Put the given string into the given clipboard. """ |
global _lastSel
_checkTkInit()
if cbname == 'CLIPBOARD':
_theRoot.clipboard_clear()
if text:
# for clipboard_append, kwds can be -displayof, -format, or -type
_theRoot.clipboard_append(text)
return
if cbname == 'PRIMARY':
_lastSel = text
_theRoot.selection_handle(ch_handler, selection='PRIMARY')
# we need to claim/own it so that ch_handler is used
_theRoot.selection_own(selection='PRIMARY')
# could add command arg for a func to be called when we lose ownership
return
raise RuntimeError("Unexpected clipboard name: "+str(cbname)) |
<SYSTEM_TASK:>
Get the contents of the given clipboard.
<END_TASK>
<USER_TASK:>
Description:
def get(cbname):
""" Get the contents of the given clipboard. """ |
_checkTkInit()
if cbname == 'PRIMARY':
try:
return _theRoot.selection_get(selection='PRIMARY')
except:
return None
if cbname == 'CLIPBOARD':
try:
return _theRoot.selection_get(selection='CLIPBOARD')
except:
return None
raise RuntimeError("Unexpected clipboard name: "+str(cbname)) |
<SYSTEM_TASK:>
Initiates a new measurement. Accepts a json payload with the following attributes;
<END_TASK>
<USER_TASK:>
Description:
def put(self, measurementId):
"""
Initiates a new measurement. Accepts a json payload with the following attributes;
* duration: in seconds
* startTime OR delay: a date in YMD_HMS format or a delay in seconds
* description: some free text information about the measurement
:return:
""" |
json = request.get_json()
try:
start = self._calculateStartTime(json)
except ValueError:
return 'invalid date format in request', 400
duration = json['duration'] if 'duration' in json else 10
if start is None:
# should never happen but just in case
return 'no start time', 400
else:
scheduled, message = self._measurementController.schedule(measurementId, duration, start,
description=json.get('description'))
return message, 200 if scheduled else 400 |
<SYSTEM_TASK:>
Print elements of list in cols columns
<END_TASK>
<USER_TASK:>
Description:
def printCols(strlist,cols=5,width=80):
"""Print elements of list in cols columns""" |
# This may exist somewhere in the Python standard libraries?
# Should probably rewrite this, it is pretty crude.
nlines = (len(strlist)+cols-1)//cols
line = nlines*[""]
for i in range(len(strlist)):
c, r = divmod(i,nlines)
nwid = c*width//cols - len(line[r])
if nwid>0:
line[r] = line[r] + nwid*" " + strlist[i]
else:
line[r] = line[r] + " " + strlist[i]
for s in line:
print(s) |
<SYSTEM_TASK:>
Strip single or double quotes off string; remove embedded quote pairs
<END_TASK>
<USER_TASK:>
Description:
def stripQuotes(value):
"""Strip single or double quotes off string; remove embedded quote pairs""" |
if value[:1] == '"':
value = value[1:]
if value[-1:] == '"':
value = value[:-1]
# replace "" with "
value = re.sub(_re_doubleq2, '"', value)
elif value[:1] == "'":
value = value[1:]
if value[-1:] == "'":
value = value[:-1]
# replace '' with '
value = re.sub(_re_singleq2, "'", value)
return value |
<SYSTEM_TASK:>
Same thing as glob.glob, but recursively checks subdirs.
<END_TASK>
<USER_TASK:>
Description:
def rglob(root, pattern):
""" Same thing as glob.glob, but recursively checks subdirs. """ |
# Thanks to Alex Martelli for basics on Stack Overflow
retlist = []
if None not in (pattern, root):
for base, dirs, files in os.walk(root):
goodfiles = fnmatch.filter(files, pattern)
retlist.extend(os.path.join(base, f) for f in goodfiles)
return retlist |
<SYSTEM_TASK:>
Convert CL parameter or variable name to Python-acceptable name
<END_TASK>
<USER_TASK:>
Description:
def translateName(s, dot=0):
"""Convert CL parameter or variable name to Python-acceptable name
Translate embedded dollar signs to 'DOLLAR'
Add 'PY' prefix to components that are Python reserved words
Add 'PY' prefix to components start with a number
If dot != 0, also replaces '.' with 'DOT'
""" |
s = s.replace('$', 'DOLLAR')
sparts = s.split('.')
for i in range(len(sparts)):
if sparts[i] == "" or sparts[i][0] in string.digits or \
keyword.iskeyword(sparts[i]):
sparts[i] = 'PY' + sparts[i]
if dot:
return 'DOT'.join(sparts)
else:
return '.'.join(sparts) |
<SYSTEM_TASK:>
In case the _default_root value is required, you may
<END_TASK>
<USER_TASK:>
Description:
def init_tk_default_root(withdraw=True):
""" In case the _default_root value is required, you may
safely call this ahead of time to ensure that it has been
initialized. If it has already been, this is a no-op.
""" |
if not capable.OF_GRAPHICS:
raise RuntimeError("Cannot run this command without graphics")
if not TKNTR._default_root: # TKNTR imported above
junk = TKNTR.Tk()
# tkinter._default_root is now populated (== junk)
retval = TKNTR._default_root
if withdraw and retval:
retval.withdraw()
return retval |
<SYSTEM_TASK:>
Read a line from file while running Tk mainloop.
<END_TASK>
<USER_TASK:>
Description:
def tkreadline(file=None):
"""Read a line from file while running Tk mainloop.
If the file is not line-buffered then the Tk mainloop will stop
running after one character is typed. The function will still work
but Tk widgets will stop updating. This should work OK for stdin and
other line-buffered filehandles. If file is omitted, reads from
sys.stdin.
The file must have a readline method. If it does not have a fileno
method (which can happen e.g. for the status line input on the
graphics window) then the readline method is simply called directly.
""" |
if file is None:
file = sys.stdin
if not hasattr(file, "readline"):
raise TypeError("file must be a filehandle with a readline method")
# Call tkread now...
# BUT, if we get in here for something not GUI-related (e.g. terminal-
# focused code in a sometimes-GUI app) then skip tkread and simply call
# readline on the input eg. stdin. Otherwise we'd fail in _TkRead().read()
try:
fd = file.fileno()
except:
fd = None
if (fd and capable.OF_GRAPHICS):
tkread(fd, 0)
# if EOF was encountered on a tty, avoid reading again because
# it actually requests more data
if not select.select([fd],[],[],0)[0]:
return ''
return file.readline() |
<SYSTEM_TASK:>
Given a URL, try to pop it up in a browser on most platforms.
<END_TASK>
<USER_TASK:>
Description:
def launchBrowser(url, brow_bin='mozilla', subj=None):
""" Given a URL, try to pop it up in a browser on most platforms.
brow_bin is only used on OS's where there is no "open" or "start" cmd.
""" |
if not subj: subj = url
# Tries to use webbrowser module on most OSes, unless a system command
# is needed. (E.g. win, linux, sun, etc)
if sys.platform not in ('os2warp, iphone'): # try webbrowser w/ everything?
import webbrowser
if not webbrowser.open(url):
print("Error opening URL: "+url)
else:
print('Help on "'+subj+'" is now being displayed in a web browser')
return
# Go ahead and fork a subprocess to call the correct binary
pid = os.fork()
if pid == 0: # child
if sys.platform == 'darwin':
if 0 != os.system('open "'+url+'"'): # does not seem to keep '#.*'
print("Error opening URL: "+url)
os._exit(0)
# The following retries if "-remote" doesnt work, opening a new browser
# cmd = brow_bin+" -remote 'openURL("+url+")' '"+url+"' 1> /dev/null 2>&1"
# if 0 != os.system(cmd)
# print "Running "+brow_bin+" for HTML help..."
# os.execvp(brow_bin,[brow_bin,url])
# os._exit(0)
else: # parent
if not subj:
subj = url
print('Help on "'+subj+'" is now being displayed in a browser') |
<SYSTEM_TASK:>
Read nbytes characters from file while running Tk mainloop
<END_TASK>
<USER_TASK:>
Description:
def read(self, file, nbytes):
"""Read nbytes characters from file while running Tk mainloop""" |
if not capable.OF_GRAPHICS:
raise RuntimeError("Cannot run this command without graphics")
if isinstance(file, int):
fd = file
else:
# Otherwise, assume we have Python file object
try:
fd = file.fileno()
except:
raise TypeError("file must be an integer or a filehandle/socket")
init_tk_default_root() # harmless if already done
self.widget = TKNTR._default_root
if not self.widget:
# no Tk widgets yet, so no need for mainloop
# (shouldnt happen now with init_tk_default_root)
s = []
while nbytes>0:
snew = os.read(fd, nbytes) # returns bytes in PY3K
if snew:
if PY3K: snew = snew.decode('ascii','replace')
s.append(snew)
nbytes -= len(snew)
else:
# EOF -- just return what we have so far
break
return "".join(s)
else:
self.nbytes = nbytes
self.value = []
self.widget.tk.createfilehandler(fd,
TKNTR.READABLE | TKNTR.EXCEPTION,
self._read)
try:
self.widget.mainloop()
finally:
self.widget.tk.deletefilehandler(fd)
return "".join(self.value) |
<SYSTEM_TASK:>
Read waiting data and terminate Tk mainloop if done
<END_TASK>
<USER_TASK:>
Description:
def _read(self, fd, mask):
"""Read waiting data and terminate Tk mainloop if done""" |
try:
# if EOF was encountered on a tty, avoid reading again because
# it actually requests more data
if select.select([fd],[],[],0)[0]:
snew = os.read(fd, self.nbytes) # returns bytes in PY3K
if PY3K: snew = snew.decode('ascii','replace')
self.value.append(snew)
self.nbytes -= len(snew)
else:
snew = ''
if (self.nbytes <= 0 or len(snew) == 0) and self.widget:
# stop the mainloop
self.widget.quit()
except OSError:
raise IOError("Error reading from %s" % (fd,)) |
<SYSTEM_TASK:>
A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a
<END_TASK>
<USER_TASK:>
Description:
def _evictStaleDevices(self):
"""
A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a
while.
""" |
while self.running:
expiredDeviceIds = [key for key, value in self.devices.items() if value.hasExpired()]
for key in expiredDeviceIds:
logger.warning("Device timeout, removing " + key)
del self.devices[key]
time.sleep(1)
# TODO send reset after a device fails
logger.warning("DeviceCaretaker is now shutdown") |
<SYSTEM_TASK:>
Parse a comma-separated list of values, or a filename (starting with @)
<END_TASK>
<USER_TASK:>
Description:
def list_parse(name_list):
"""Parse a comma-separated list of values, or a filename (starting with @)
containing a list value on each line.
""" |
if name_list and name_list[0] == '@':
value = name_list[1:]
if not os.path.exists(value):
log.warning('The file %s does not exist' % value)
return
try:
return [v.strip() for v in open(value, 'r').readlines()]
except IOError as e:
log.warning('reading %s failed: %s; ignoring this file' %
(value, e))
else:
return [v.strip() for v in name_list.split(',')] |
<SYSTEM_TASK:>
Create the minimum match dictionary of keys
<END_TASK>
<USER_TASK:>
Description:
def _mmInit(self):
"""Create the minimum match dictionary of keys""" |
# cache references to speed up loop a bit
mmkeys = {}
mmkeysGet = mmkeys.setdefault
minkeylength = self.minkeylength
for key in self.data.keys():
# add abbreviations as short as minkeylength
# always add at least one entry (even for key="")
lenkey = len(key)
start = min(minkeylength,lenkey)
for i in range(start,lenkey+1):
mmkeysGet(key[0:i],[]).append(key)
self.mmkeys = mmkeys |
<SYSTEM_TASK:>
Hook to resolve ambiguities in selected keys
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, key, keylist):
"""Hook to resolve ambiguities in selected keys""" |
raise AmbiguousKeyError("Ambiguous key "+ repr(key) +
", could be any of " + str(sorted(keylist))) |
<SYSTEM_TASK:>
Raises exception if key is ambiguous
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, failobj=None, exact=0):
"""Raises exception if key is ambiguous""" |
if not exact:
key = self.getfullkey(key,new=1)
return self.data.get(key,failobj) |
<SYSTEM_TASK:>
Raises an exception if key is ambiguous
<END_TASK>
<USER_TASK:>
Description:
def _has(self, key, exact=0):
"""Raises an exception if key is ambiguous""" |
if not exact:
key = self.getfullkey(key,new=1)
return key in self.data |
<SYSTEM_TASK:>
Returns a list of all the matching values for key,
<END_TASK>
<USER_TASK:>
Description:
def getall(self, key, failobj=None):
"""Returns a list of all the matching values for key,
containing a single entry for unambiguous matches and
multiple entries for ambiguous matches.""" |
if self.mmkeys is None: self._mmInit()
k = self.mmkeys.get(key)
if not k: return failobj
return list(map(self.data.get, k)) |
<SYSTEM_TASK:>
Returns failobj if key is not found or is ambiguous
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, failobj=None, exact=0):
"""Returns failobj if key is not found or is ambiguous""" |
if not exact:
try:
key = self.getfullkey(key)
except KeyError:
return failobj
return self.data.get(key,failobj) |
<SYSTEM_TASK:>
Returns false if key is not found or is ambiguous
<END_TASK>
<USER_TASK:>
Description:
def _has(self, key, exact=0):
"""Returns false if key is not found or is ambiguous""" |
if not exact:
try:
key = self.getfullkey(key)
return 1
except KeyError:
return 0
else:
return key in self.data |
<SYSTEM_TASK:>
parameter factory function
<END_TASK>
<USER_TASK:>
Description:
def parFactory(fields, strict=0):
"""parameter factory function
fields is a list of the comma-separated fields (as in the .par file).
Each entry is a string or None (indicating that field was omitted.)
Set the strict parameter to a non-zero value to do stricter parsing
(to find errors in the input)""" |
if len(fields) < 3 or None in fields[0:3]:
raise SyntaxError("At least 3 fields must be given")
type = fields[1]
if type in _string_types:
return IrafParS(fields,strict)
elif type == 'R':
return StrictParR(fields,1)
elif type in _real_types:
return IrafParR(fields,strict)
elif type == "I":
return StrictParI(fields,1)
elif type == "i":
return IrafParI(fields,strict)
elif type == "b":
return IrafParB(fields,strict)
elif type == "ar":
return IrafParAR(fields,strict)
elif type == "ai":
return IrafParAI(fields,strict)
elif type == "as":
return IrafParAS(fields,strict)
elif type == "ab":
return IrafParAB(fields,strict)
elif type[:1] == "a":
raise SyntaxError("Cannot handle arrays of type %s" % type)
else:
raise SyntaxError("Cannot handle parameter type %s" % type) |
<SYSTEM_TASK:>
Return true if this parameter is learned
<END_TASK>
<USER_TASK:>
Description:
def isLearned(self, mode=None):
"""Return true if this parameter is learned
Hidden parameters are not learned; automatic parameters inherit
behavior from package/cl; other parameters are learned.
If mode is set, it determines how automatic parameters behave.
If not set, cl.mode parameter determines behavior.
""" |
if "l" in self.mode: return 1
if "h" in self.mode: return 0
if "a" in self.mode:
if mode is None: mode = 'ql' # that is, iraf.cl.mode
if "h" in mode and "l" not in mode:
return 0
return 1 |
<SYSTEM_TASK:>
Checks a single value to see if it is in range or choice list
<END_TASK>
<USER_TASK:>
Description:
def checkOneValue(self,v,strict=0):
"""Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
ValueError if not OK.
""" |
if v in [None, INDEF] or (isinstance(v,str) and v[:1] == ")"):
return v
elif v == "":
# most parameters treat null string as omitted value
return None
elif self.choice is not None and v not in self.choiceDict:
schoice = list(map(self.toString, self.choice))
schoice = "|".join(schoice)
raise ValueError("Parameter %s: "
"value %s is not in choice list (%s)" %
(self.name, str(v), schoice))
elif (self.min not in [None, INDEF] and v<self.min):
raise ValueError("Parameter %s: "
"value `%s' is less than minimum `%s'" %
(self.name, str(v), str(self.min)))
elif (self.max not in [None, INDEF] and v>self.max):
raise ValueError("Parameter %s: "
"value `%s' is greater than maximum `%s'" %
(self.name, str(v), str(self.max)))
return v |
<SYSTEM_TASK:>
Interactively prompt for parameter if necessary
<END_TASK>
<USER_TASK:>
Description:
def _optionalPrompt(self, mode):
"""Interactively prompt for parameter if necessary
Prompt for value if
(1) mode is hidden but value is undefined or bad, or
(2) mode is query and value was not set on command line
Never prompt for "u" mode parameters, which are local variables.
""" |
if (self.mode == "h") or (self.mode == "a" and mode == "h"):
# hidden parameter
if not self.isLegal():
self.getWithPrompt()
elif self.mode == "u":
# "u" is a special mode used for local variables in CL scripts
# They should never prompt under any circumstances
if not self.isLegal():
raise ValueError(
"Attempt to access undefined local variable `%s'" %
self.name)
else:
# query parameter
if self.isCmdline()==0:
self.getWithPrompt() |
<SYSTEM_TASK:>
Get p_filename field for this parameter
<END_TASK>
<USER_TASK:>
Description:
def _getPFilename(self,native,prompt):
"""Get p_filename field for this parameter
Same as get for non-list params
""" |
return self.get(native=native,prompt=prompt) |
<SYSTEM_TASK:>
Get a parameter field value
<END_TASK>
<USER_TASK:>
Description:
def _getField(self, field, native=0, prompt=1):
"""Get a parameter field value""" |
try:
# expand field name using minimum match
field = _getFieldDict[field]
except KeyError as e:
# re-raise the exception with a bit more info
raise SyntaxError("Cannot get field " + field +
" for parameter " + self.name + "\n" + str(e))
if field == "p_value":
# return value of parameter
# Note that IRAF returns the filename for list parameters
# when p_value is used. I consider this a bug, and it does
# not appear to be used by any cl scripts or SPP programs
# in either IRAF or STSDAS. It is also in conflict with
# the IRAF help documentation. I am making p_value exactly
# the same as just a simple CL parameter reference.
return self.get(native=native,prompt=prompt)
elif field == "p_name": return self.name
elif field == "p_xtype": return self.type
elif field == "p_type": return self._getPType()
elif field == "p_mode": return self.mode
elif field == "p_prompt": return self.prompt
elif field == "p_scope": return self.scope
elif field == "p_default" or field == "p_filename":
# these all appear to be equivalent -- they just return the
# current PFilename of the parameter (which is the same as the value
# for non-list parameters, and is the filename for list parameters)
return self._getPFilename(native,prompt)
elif field == "p_maximum":
if native:
return self.max
else:
return self.toString(self.max)
elif field == "p_minimum":
if self.choice is not None:
if native:
return self.choice
else:
schoice = list(map(self.toString, self.choice))
return "|" + "|".join(schoice) + "|"
else:
if native:
return self.min
else:
return self.toString(self.min)
else:
# XXX unimplemented fields:
# p_length: maximum string length in bytes -- what to do with it?
raise RuntimeError("Program bug in IrafPar._getField()\n" +
"Requested field " + field + " for parameter " + self.name) |
<SYSTEM_TASK:>
Set a parameter field value
<END_TASK>
<USER_TASK:>
Description:
def _setField(self, value, field, check=1):
"""Set a parameter field value""" |
try:
# expand field name using minimum match
field = _setFieldDict[field]
except KeyError as e:
raise SyntaxError("Cannot set field " + field +
" for parameter " + self.name + "\n" + str(e))
if field == "p_prompt":
self.prompt = irafutils.removeEscapes(irafutils.stripQuotes(value))
elif field == "p_value":
self.set(value,check=check)
elif field == "p_filename":
# this is only relevant for list parameters (*imcur, *gcur, etc.)
self.set(value,check=check)
elif field == "p_scope":
self.scope = value
elif field == "p_maximum":
self.max = self._coerceOneValue(value)
elif field == "p_minimum":
if isinstance(value,str) and '|' in value:
self._setChoice(irafutils.stripQuotes(value))
else:
self.min = self._coerceOneValue(value)
elif field == "p_mode":
# not doing any type or value checking here -- setting mode is
# rare, so assume that it is being done correctly
self.mode = irafutils.stripQuotes(value)
else:
raise RuntimeError("Program bug in IrafPar._setField()" +
"Requested field " + field + " for parameter " + self.name) |
<SYSTEM_TASK:>
Coerce parameter to appropriate type
<END_TASK>
<USER_TASK:>
Description:
def _coerceValue(self,value,strict=0):
"""Coerce parameter to appropriate type
Should accept None or null string. Must be an array.
""" |
try:
if isinstance(value,str):
# allow single blank-separated string as input
value = value.split()
if len(value) != len(self.value):
raise IndexError
v = len(self.value)*[0]
for i in range(len(v)):
v[i] = self._coerceOneValue(value[i],strict)
return v
except (IndexError, TypeError):
raise ValueError("Value must be a " + repr(len(self.value)) +
"-element array for " + self.name) |
<SYSTEM_TASK:>
Return the computed orientation based on CD matrix.
<END_TASK>
<USER_TASK:>
Description:
def set_orient(self):
""" Return the computed orientation based on CD matrix. """ |
self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22)) |
<SYSTEM_TASK:>
This method would apply the WCS keywords to a position to
<END_TASK>
<USER_TASK:>
Description:
def xy2rd(self,pos):
"""
This method would apply the WCS keywords to a position to
generate a new sky position.
The algorithm comes directly from 'imgtools.xy2rd'
translate (x,y) to (ra, dec)
""" |
if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0:
print('XY2RD only supported for TAN projections.')
raise TypeError
if isinstance(pos,N.ndarray):
# If we are working with an array of positions,
# point to just X and Y values
posx = pos[:,0]
posy = pos[:,1]
else:
# Otherwise, we are working with a single X,Y tuple
posx = pos[0]
posy = pos[1]
xi = self.cd11 * (posx - self.crpix1) + self.cd12 * (posy - self.crpix2)
eta = self.cd21 * (posx - self.crpix1) + self.cd22 * (posy - self.crpix2)
xi = DEGTORAD(xi)
eta = DEGTORAD(eta)
ra0 = DEGTORAD(self.crval1)
dec0 = DEGTORAD(self.crval2)
ra = N.arctan((xi / (N.cos(dec0)-eta*N.sin(dec0)))) + ra0
dec = N.arctan( ((eta*N.cos(dec0)+N.sin(dec0)) /
(N.sqrt((N.cos(dec0)-eta*N.sin(dec0))**2 + xi**2))) )
ra = RADTODEG(ra)
dec = RADTODEG(dec)
ra = DIVMOD(ra, 360.)
# Otherwise, just return the RA,Dec tuple.
return ra,dec |
<SYSTEM_TASK:>
Write out the values of the WCS keywords to the
<END_TASK>
<USER_TASK:>
Description:
def write(self,fitsname=None,wcs=None,archive=True,overwrite=False,quiet=True):
"""
Write out the values of the WCS keywords to the
specified image.
If it is a GEIS image and 'fitsname' has been provided,
it will automatically make a multi-extension
FITS copy of the GEIS and update that file. Otherwise, it
throw an Exception if the user attempts to directly update
a GEIS image header.
If archive=True, also write out archived WCS keyword values to file.
If overwrite=True, replace archived WCS values in file with new values.
If a WCSObject is passed through the 'wcs' keyword, then the WCS keywords
of this object are copied to the header of the image to be updated. A use case
fo rthis is updating the WCS of a WFPC2 data quality (_c1h.fits) file
in order to be in sync with the science (_c0h.fits) file.
""" |
## Start by making sure all derived values are in sync with CD matrix
self.update()
image = self.rootname
_fitsname = fitsname
if image.find('.fits') < 0 and _fitsname is not None:
# A non-FITS image was provided, and openImage made a copy
# Update attributes to point to new copy instead
self.geisname = image
image = self.rootname = _fitsname
# Open image as writable FITS object
fimg = fileutil.openImage(image, mode='update', fitsname=_fitsname)
_root,_iextn = fileutil.parseFilename(image)
_extn = fileutil.getExtn(fimg,_iextn)
# Write out values to header...
if wcs:
_wcsobj = wcs
else:
_wcsobj = self
for key in _wcsobj.wcstrans.keys():
_dkey = _wcsobj.wcstrans[key]
if _dkey != 'pscale':
_extn.header[key] = _wcsobj.__dict__[_dkey]
# Close the file
fimg.close()
del fimg
if archive:
self.write_archive(fitsname=fitsname,overwrite=overwrite,quiet=quiet) |
<SYSTEM_TASK:>
Reset the active WCS keywords to values stored in the
<END_TASK>
<USER_TASK:>
Description:
def restore(self):
""" Reset the active WCS keywords to values stored in the
backup keywords.
""" |
# If there are no backup keys, do nothing...
if len(list(self.backup.keys())) == 0:
return
for key in self.backup.keys():
if key != 'WCSCDATE':
self.__dict__[self.wcstrans[key]] = self.orig_wcs[self.backup[key]]
self.update() |
<SYSTEM_TASK:>
Create backup copies of the WCS keywords with the given prepended
<END_TASK>
<USER_TASK:>
Description:
def archive(self,prepend=None,overwrite=no,quiet=yes):
""" Create backup copies of the WCS keywords with the given prepended
string.
If backup keywords are already present, only update them if
'overwrite' is set to 'yes', otherwise, do warn the user and do nothing.
Set the WCSDATE at this time as well.
""" |
# Verify that existing backup values are not overwritten accidentally.
if len(list(self.backup.keys())) > 0 and overwrite == no:
if not quiet:
print('WARNING: Backup WCS keywords already exist! No backup made.')
print(' The values can only be overridden if overwrite=yes.')
return
# Establish what prepend string to use...
if prepend is None:
if self.prepend is not None:
_prefix = self.prepend
else:
_prefix = DEFAULT_PREFIX
else:
_prefix = prepend
# Update backup and orig_wcs dictionaries
# We have archive keywords and a defined prefix
# Go through and append them to self.backup
self.prepend = _prefix
for key in self.wcstrans.keys():
if key != 'pixel scale':
_archive_key = self._buildNewKeyname(key,_prefix)
else:
_archive_key = self.prepend.lower()+'pscale'
# if key != 'pixel scale':
self.orig_wcs[_archive_key] = self.__dict__[self.wcstrans[key]]
self.backup[key] = _archive_key
self.revert[_archive_key] = key
# Setup keyword to record when these keywords were backed up.
self.orig_wcs['WCSCDATE']= fileutil.getLTime()
self.backup['WCSCDATE'] = 'WCSCDATE'
self.revert['WCSCDATE'] = 'WCSCDATE' |
<SYSTEM_TASK:>
Extract a copy of WCS keywords from an open file header,
<END_TASK>
<USER_TASK:>
Description:
def read_archive(self,header,prepend=None):
""" Extract a copy of WCS keywords from an open file header,
if they have already been created and remember the prefix
used for those keywords. Otherwise, setup the current WCS
keywords as the archive values.
""" |
# Start by looking for the any backup WCS keywords to
# determine whether archived values are present and to set
# the prefix used.
_prefix = None
_archive = False
if header is not None:
for kw in header.items():
if kw[0][1:] in self.wcstrans.keys():
_prefix = kw[0][0]
_archive = True
break
if not _archive:
self.archive(prepend=prepend)
return
# We have archive keywords and a defined prefix
# Go through and append them to self.backup
if _prefix is not None:
self.prepend = _prefix
else:
self.prepend = DEFAULT_PREFIX
for key in self.wcstrans.keys():
_archive_key = self._buildNewKeyname(key,_prefix)
if key!= 'pixel scale':
if _archive_key in header:
self.orig_wcs[_archive_key] = header[_archive_key]
else:
self.orig_wcs[_archive_key] = header[key]
self.backup[key] = _archive_key
self.revert[_archive_key] = key
# Establish plate scale value
_cd11str = self.prepend+'CD1_1'
_cd21str = self.prepend+'CD2_1'
pscale = self.compute_pscale(self.orig_wcs[_cd11str],self.orig_wcs[_cd21str])
_archive_key = self.prepend.lower()+'pscale'
self.orig_wcs[_archive_key] = pscale
self.backup['pixel scale'] = _archive_key
self.revert[_archive_key] = 'pixel scale'
# Setup keyword to record when these keywords were backed up.
if 'WCSCDATE' in header:
self.orig_wcs['WCSCDATE'] = header['WCSCDATE']
else:
self.orig_wcs['WCSCDATE'] = fileutil.getLTime()
self.backup['WCSCDATE'] = 'WCSCDATE'
self.revert['WCSCDATE'] = 'WCSCDATE' |
<SYSTEM_TASK:>
Resets the WCS values to the original values stored in
<END_TASK>
<USER_TASK:>
Description:
def restoreWCS(self,prepend=None):
""" Resets the WCS values to the original values stored in
the backup keywords recorded in self.backup.
""" |
# Open header for image
image = self.rootname
if prepend: _prepend = prepend
elif self.prepend: _prepend = self.prepend
else: _prepend = None
# Open image as writable FITS object
fimg = fileutil.openImage(image, mode='update')
# extract the extension ID being updated
_root,_iextn = fileutil.parseFilename(self.rootname)
_extn = fileutil.getExtn(fimg,_iextn)
if len(self.backup) > 0:
# If it knows about the backup keywords already,
# use this to restore the original values to the original keywords
for newkey in self.revert.keys():
if newkey != 'opscale':
_orig_key = self.revert[newkey]
_extn.header[_orig_key] = _extn.header[newkey]
elif _prepend:
for key in self.wcstrans.keys():
# Get new keyword name based on old keyname
# and prepend string
if key != 'pixel scale':
_okey = self._buildNewKeyname(key,_prepend)
if _okey in _extn.header:
_extn.header[key] = _extn.header[_okey]
else:
print('No original WCS values found. Exiting...')
break
else:
print('No original WCS values found. Exiting...')
fimg.close()
del fimg |
<SYSTEM_TASK:>
Write out the values of the WCS keywords to the NEW
<END_TASK>
<USER_TASK:>
Description:
def createReferenceWCS(self,refname,overwrite=yes):
""" Write out the values of the WCS keywords to the NEW
specified image 'fitsname'.
""" |
hdu = self.createWcsHDU()
# If refname already exists, delete it to make way for new file
if os.path.exists(refname):
if overwrite==yes:
# Remove previous version and re-create with new header
os.remove(refname)
hdu.writeto(refname)
else:
# Append header to existing file
wcs_append = True
oldhdu = fits.open(refname, mode='append')
for e in oldhdu:
if 'extname' in e.header and e.header['extname'] == 'WCS':
wcs_append = False
if wcs_append == True:
oldhdu.append(hdu)
oldhdu.close()
del oldhdu
else:
# No previous file, so generate new one from scratch
hdu.writeto(refname)
# Clean up
del hdu |
<SYSTEM_TASK:>
Returns a one-line string with the current callstack.
<END_TASK>
<USER_TASK:>
Description:
def format_stack(skip=0, length=6, _sep=os.path.sep):
"""
Returns a one-line string with the current callstack.
""" |
return ' < '.join("%s:%s:%s" % (
'/'.join(f.f_code.co_filename.split(_sep)[-2:]),
f.f_lineno,
f.f_code.co_name
) for f in islice(frame_iterator(sys._getframe(1 + skip)), length)) |
<SYSTEM_TASK:>
lists all known active measurements.
<END_TASK>
<USER_TASK:>
Description:
def get(self, deviceId):
"""
lists all known active measurements.
""" |
measurementsByName = self.measurements.get(deviceId)
if measurementsByName is None:
return []
else:
return list(measurementsByName.values()) |
<SYSTEM_TASK:>
details the specific measurement.
<END_TASK>
<USER_TASK:>
Description:
def get(self, deviceId, measurementId):
"""
details the specific measurement.
""" |
record = self.measurements.get(deviceId)
if record is not None:
return record.get(measurementId)
return None |
<SYSTEM_TASK:>
Called when this button is clicked. Execute code from .cfgspc
<END_TASK>
<USER_TASK:>
Description:
def clicked(self):
""" Called when this button is clicked. Execute code from .cfgspc """ |
try:
from . import teal
except:
teal = None
try:
# start drilling down into the tpo to get the code
tealGui = self._mainGuiObj
tealGui.showStatus('Clicked "'+self.getButtonLabel()+'"', keep=1)
pscope = self.paramInfo.scope
pname = self.paramInfo.name
tpo = tealGui._taskParsObj
tup = tpo.getExecuteStrings(pscope, pname)
code = ''
if not tup:
if teal:
teal.popUpErr(tealGui.top, "No action to perform",
"Action Button Error")
return
for exname in tup:
if '_RULES_' in tpo and exname in tpo['_RULES_'].configspec:
ruleSig = tpo['_RULES_'].configspec[exname]
chkArgsDict = vtor_checks.sigStrToKwArgsDict(ruleSig)
code = chkArgsDict.get('code') # a string or None
# now go ahead and execute it
teal.execEmbCode(pscope, pname, self.getButtonLabel(),
tealGui, code)
# done
tealGui.debug('Finished: "'+self.getButtonLabel()+'"')
except Exception as ex:
msg = 'Error executing: "'+self.getButtonLabel()+'"\n'+ex.message
msgFull = msg+'\n'+''.join(traceback.format_exc())
msgFull+= "CODE:\n"+code
if tealGui:
if teal: teal.popUpErr(tealGui.top, msg, "Action Button Error")
tealGui.debug(msgFull)
else:
if teal: teal.popUpErr(None, msg, "Action Button Error")
print(msgFull) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.