code stringlengths 1 18.2k |
|---|
Check INT data for max values ext_dat_frac,ext_dat_exp = numpy.frexp(ext_dat) if ext_dat_exp.max() == int(_bitpix) - 1: # Potential problems with byteswapping errormsg += "===================================\n" errormsg += "= WARNING: =\n" errormsg += "= Input image: =\n" errormsg += input+"[%d]\n"%(k+1) errormsg += "=... |
dtype=formats) loc += group_size # Add data from this GPB to table for i in range(1, pcount+1): val = rec[0][i-1] if i in bools: if val: val = 'T' else: val = 'F' cols[i-1].array[k] = val # Based on the first group, add GPB keywords to PRIMARY header if k == 0: # Create separate PyFITS Card objects for each entry in 'r... |
and update Primary HDU with these keywords after PSIZE for i in range(1, pcount+1): #val = rec.field(i-1)[0] val = rec[0][i-1] if val.dtype.kind == 'S': val = val.decode('ascii') if i in bools: if val: val = True else: val = False elif i in floats: # use fromstring, format in Card is deprecated in pyfits 0.9 _str = '%-... |
comm[i-1]) _card = fits.Card.fromstring(_str) else: _card = fits.Card(key=key[i-1], value=val, comment=comm[i-1]) phdr.insert(phdr_indx+i, _card) # deal with bscale/bzero if (_bscale != 1 or _bzero != 0): phdr['BSCALE'] = _bscale phdr['BZERO'] = _bzero #hdulist.append(ext_hdu) # Define new table based on Column definit... |
if errormsg != "": errormsg += "===================================\n" errormsg += "= This file may have been =\n" errormsg += "= written out on a platform =\n" errormsg += "= with a different byte-order. =\n" errormsg += "= =\n" errormsg += "= Please verify that the values =\n" errormsg += "= are correct or apply the ... |
print(errormsg) f1.close() hdulist = fits.HDUList([fits.PrimaryHDU(header=phdr, data=arr_stack)]) hdulist.append(ext_table) stsci2(hdulist,input) return hdulist |
def _loadConfig(self): """ loads configuration from some predictable locations. :return: the config. """ configPath = path.join(self._getConfigPath(), self._name + ".yml") if os.path.exists(configPath): self.logger.warning("Loading config from " + configPath) with open(configPath, 'r') as yml: return yaml.load(yml, Loa... |
def _storeConfig(self, config, configPath): """ Writes the config to the configPath. :param config a dict of config. :param configPath the path to the file to write to, intermediate dirs will be created as necessary. """ self.logger.info("Writing to " + str(configPath)) os.makedirs(os.path.dirname(configPath), exist_ok... |
def _getConfigPath(self): """ Gets the currently configured config path. :return: the path, raises ValueError if it doesn't exist. """ confHome = environ.get('VIBE_CONFIG_HOME') return confHome if confHome is not None else path.join(path.expanduser("~"), '.vibe') |
def configureLogger(self): """ Configures the python logging system to log to a debug file and to stdout for warn and above. :return: the base logger. """ baseLogLevel = logging.DEBUG if self.isDebugLogging() else logging.INFO # create recorder app root logger logger = logging.getLogger(self._name) logger.setLevel(base... |
a higher log level ch = logging.StreamHandler() ch.setLevel(logging.WARN) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHa... |
def ibm_to_ieee(ibm): ''' Translate IBM-format floating point numbers (as bytes) to IEEE 754 64-bit floating point format (as Python float). ''' # IBM mainframe: sign * 0.mantissa * 16 ** (exponent - 64) # Python uses IEEE: sign * 1.mantissa * 2 ** (exponent - 1023) # Pad-out to 8 bytes if necessary. We expect 2 to 8 b... |
to check; bizarre sizes will cause a struct # module unpack error. ibm = ibm.ljust(8, b'\x00') # parse the 64 bits of IBM float as one 8-byte unsigned long long ulong, = struct.unpack('>Q', ibm) # IBM: 1-bit sign, 7-bits exponent, 56-bits mantissa sign = ulong & 0x8000000000000000 exponent = (ulong & 0x7f00000000000000... |
ibm[0:1] == b'\x00': return 0.0 elif ibm[0:1] in b'_.ABCDEFGHIJKLMNOPQRSTUVWXYZ': return float('nan') else: raise ValueError('Neither zero nor NaN: %r' % ibm) # IBM-format exponent is base 16, so the mantissa can have up to 3 # leading zero-bits in the binary mantissa. IEEE format exponent # is base 2, so we don't need... |
the criticisms of IBM-format, its # wobbling precision. if ulong & 0x0080000000000000: shift = 3 elif ulong & 0x0040000000000000: shift = 2 elif ulong & 0x0020000000000000: shift = 1 else: shift = 0 mantissa >>= shift # clear the 1 bit to the left of the binary point # this is implicit in IEEE specification mantissa &=... |
but we subtract 65, because of the # implicit 1 left of the radix point for the IEEE mantissa exponent -= 65 # IBM exponent is base 16, IEEE is base 2, so we multiply by 4 exponent <<= 2 # IEEE exponent is excess 1023, but we also increment for each # right-shift when aligning the mantissa's first 1-bit exponent += shi... |
1023 # IEEE: 1-bit sign, 11-bits exponent, 52-bits mantissa # We didn't shift the sign bit, so it's already in the right spot ieee = sign | (exponent << 52) | mantissa return struct.unpack(">d", struct.pack(">Q", ieee))[0] |
def ieee_to_ibm(ieee): ''' Translate Python floating point numbers to IBM-format (as bytes). ''' # Python uses IEEE: sign * 1.mantissa * 2 ** (exponent - 1023) # IBM mainframe: sign * 0.mantissa * 16 ** (exponent - 64) if ieee == 0.0: return b'\x00' * 8 if ieee is None or math.isnan(ieee): return b'_' + b'\x00' * 7 if ... |
bits = struct.pack('>d', ieee) ulong, = struct.unpack('>Q', bits) sign = (ulong & (1 << 63)) >> 63 # 1-bit sign exponent = ((ulong & (0x7ff << 52)) >> 52) - 1023 # 11-bits exponent mantissa = ulong & 0x000fffffffffffff # 52-bits mantissa/significand if exponent > 248: msg = 'Cannot store magnitude more than ~ 16 ** 63 ... |
-260: msg = 'Cannot store magnitude less than ~ 16 ** -65 as IBM-format' raise Underflow(msg) # IEEE mantissa has an implicit 1 left of the radix: 1.significand # IBM mantissa has an implicit 0 left of the radix: 0.significand # We must bitwise-or the implicit 1.mmm into the mantissa # later we will increment the expon... |
0x0010000000000000 | mantissa # IEEE exponents are for base 2: mantissa * 2 ** exponent # IBM exponents are for base 16: mantissa * 16 ** exponent # We must divide the exponent by 4, since 16 ** x == 2 ** (4 * x) quotient, remainder = divmod(exponent, 4) exponent = quotient # We don't want to lose information; # the re... |
the divided exponent adjusts the mantissa mantissa <<= remainder # Increment exponent, because of earlier adjustment to mantissa # this corresponds to the 1.mantissa vs 0.mantissa implicit bit exponent += 1 # IBM exponents are excess 64 exponent += 64 # IBM has 1-bit sign, 7-bits exponent, and 56-bits mantissa. # We mu... |
exponent <<= 56 # We lose some precision, but who said floats were perfect? return struct.pack('>Q', sign | exponent | mantissa) |
def dumps(columns): ''' Serialize ``columns`` to a JSON formatted ``bytes`` object. ''' fp = BytesIO() dump(columns, fp) fp.seek(0) return fp.read() |
def match(header): ''' Parse the 3-line (240-byte) header of a SAS XPORT file. ''' mo = Library.header_re.match(header) if mo is None: raise ValueError(f'Not a SAS Version 5 or 6 XPORT file') return { 'created': strptime(mo['created']), 'modified': strptime(mo['modified']), 'sas_version': float(mo['version']), 'os_vers... |
def header_match(cls, header): ''' Parse the 4-line (320-byte) library member header. ''' mo = cls.header_re.match(header) if mo is None: msg = f'Expected {cls.header_re.pattern!r}, got {header!r}' raise ValueError(msg) return { 'name': mo['name'].decode().strip(), 'label': mo['label'].decode().strip(), 'type': mo['typ... |
def header_match(cls, data): ''' Parse a member namestrs header (1 line, 80 bytes). ''' mo = cls.header_re.match(data) return int(mo['n_variables']) |
def readall(cls, member, size): ''' Parse variable metadata for a XPORT file member. ''' fp = member.library.fp LINE = member.library.LINE n = cls.header_match(fp.read(LINE)) namestrs = [fp.read(size) for i in range(n)] # Each namestr field is 140 bytes long, but the fields are # streamed together and broken in 80-byte... |
the last byte # of the 80-byte record, the record is padded with ASCII blanks # to 80 bytes. remainder = n * size % LINE if remainder: padding = 80 - remainder fp.read(padding) info = [cls.unpack(s) for s in namestrs] for d in info: d['format'] = Format(**d['format']) d['iformat'] = InputFormat(**d['iformat']) return [... |
def to_jd(year, month, day): '''Determine Julian day count from Islamic date''' return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 1 |
def from_jd(jd): '''Calculate Islamic date from Julian day''' jd = trunc(jd) + 0.5 year = trunc(((30 * (jd - EPOCH)) + 10646) / 10631) month = min(12, ceil((jd - (29 + to_jd(year, 1, 1))) / 29.5) + 1) day = int(jd - to_jd(year, month, 1)) + 1 return (year, month, day) |
def checkAllTriggers(self, action): """ Go over all widgets and let them know they have been edited recently and they need to check for any trigger actions. This would be used right after all the widgets have their values set or forced (e.g. via setAllEntriesFromParList). """ for entry in self.entryNo: entry.widgetEdit... |
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) |
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 ... |
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_... |
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)).fo... |
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 no... |
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.... |
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 |
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 ' + \ 'f... |
return False |
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 ... |
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:p... |
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 automatical... |
= [] 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(co... |
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 v... |
def _toggleSectionActiveState(self, sectionName, state, skipList): """ Make an entire section (minus skipList items) either active or inactive. sectionName is the same as the param's scope. """ # Get model data, the list of pars theParamList = self._taskParsObj.getParList() # Loop over their assoc. entries for i in ran... |
# if it started active, we don't need to reactivate it else: self.entryNo[i].setActiveState(state) |
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 t... |
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... |
= 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... |
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 ... |
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.taskN... |
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 n... |
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 =... |
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+'\... |
def _showAnyHelp(self, kind, tag=None): """ Invoke task/epar/etc. help and put the page in a window. This same logic is used for GUI help, task help, log msgs, etc. """ # sanity check assert kind in ('epar', 'task', 'log'), 'Unknown help kind: '+str(kind) #----------------------------------------- # See if they'd like ... |
== 'epar': self.htmlHelp(helpString=self._appHelpString, title='Parameter Editor Help') if kind == 'task': self.htmlHelp(istask=True, tag=tag) if kind == 'log': self.htmlHelp(helpString='\n'.join(self._msgHistory), title=self._appName+' Event Log') return #----------------------------------------- # Now try to pop up t... |
so build it #--------------------------------------------------------- if kind == 'epar': self.eparHelpWin = self.makeHelpWin(self._appHelpString, title='Parameter Editor Help') if kind == 'task': # Acquire the task help as a string # Need to include the package name for the task to # avoid name conflicts with tasks fr... |
def setAllEntriesFromParList(self, aParList, updateModel=False): """ Set all the parameter entry values in the GUI to the values in the given par list. If 'updateModel' is True, the internal param list will be updated to the new values as well as the GUI entries (slower and not always necessary). Note the corresponding... |
self._taskParsObj.getParList() # we may modify members if len(aParList) != len(theParamList): showwarning(message="Attempting to set parameter values from a "+ \ "list of different length ("+str(len(aParList))+ \ ") than the number shown here ("+ \ str(len(theParamList))+"). Be aware.", title="Parameter List Length Mis... |
= self.entryNo[i] # Set the value in the paramList before setting it in the GUI # This may be in the form of a list, or an IrafParList (getValue) if isinstance(aParList, list): # Since "aParList" can have them in different order and number # than we do, we'll have to first find the matching param. found = False for new... |
and newpar.scope==par.scope: par.set(newpar.value) # same as .get(native=1,prompt=0) found = True break # Now see if newpar was found in our list if not found: pnm = par.name if len(par.scope): pnm = par.scope+'.'+par.name raise UnfoundParamError('Error - Unfound Parameter! \n\n'+\ 'Expected parameter "'+pnm+'" for tas... |
par.value is native; conversion occurs gui_entry.forceValue(par.value, noteEdited=False) # no triggers yet if updateModel: # Update the model values via checkSetSaveEntries self.badEntriesList = self.checkSetSaveEntries(doSave=False) # If there were invalid entries, prepare the message dialog if self.badEntriesList: se... |
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. """ # Ge... |
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 = th... |
== 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+'"') |
def checkSetSaveChildren(self, doSave=True): """Check, then set, then save the parameter settings for all child (pset) windows. Prompts if any problems are found. Returns None on success, list of bad entries on failure. """ if self.isChild: return # Need to get all the entries and verify them. # Save the children in ba... |
n in range (len(self.top.childList)-1, -1, -1): self.badEntriesList = self.top.childList[n]. \ checkSetSaveEntries(doSave=doSave) if self.badEntriesList: ansOKCANCEL = self.processBadEntries(self.badEntriesList, self.top.childList[n].taskName) if not ansOKCANCEL: return self.badEntriesList # If there were no invalid en... |
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) |
def showStatus(self, msg, keep=0, cat=None): """ Show the given status string, but not until any given delay from the previous message has expired. keep is a time (secs) to force the message to remain without being overwritten or cleared. cat is a string category used only in the historical log. """ # prep it, space-wi... |
here is the ideal place to collect a history of messages forhist = msg if cat: forhist = '['+cat+'] '+msg forhist = time.strftime("%a %H:%M:%S")+': '+forhist self._msgHistory.append(forhist) # now set the spacing msg = ' '+msg # stop here if it is a category not shown in the GUI if cat == DBG: return # see if we can sh... |
now >= self._leaveStatusMsgUntil: # we are clear, can show a msg # first see if this msg is '' - if so we will show an important # waiting msg instead of the '', and then pop it off our list if len(msg) < 1 and len(self._statusMsgsToShow) > 0: msg, keep = self._statusMsgsToShow[0] # overwrite both args del self._status... |
status out to the status widget self.top.status.config(text = msg) # reset our delay flag self._leaveStatusMsgUntil = 0 if keep > 0: self._leaveStatusMsgUntil = now + keep else: # there is a previous message still up, is this one important? if len(msg) > 0 and keep > 0: # Uh-oh, this is an important message that we don... |
the other hand we can't show it yet... # So we add it to _statusMsgsToShow and show it later (asap) if (msg,keep) not in self._statusMsgsToShow: if len(self._statusMsgsToShow) < 7: self._statusMsgsToShow.append( (msg,keep) ) # tuple # kick off timer loop to get this one pushed through if len(self._statusMsgsToShow) == ... |
behind...)") |
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.getObjectFromT... |
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... |
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... |
return dlg.getTaskParsObj() # else, returnAs == "status" if dlg is None or dlg.canceled(): return -1 if dlg.executed(): return 1 return 0 |
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) |
def unlearn(taskPkgName, deleteAll=False): """ Find the task named taskPkgName, and delete any/all user-owned .cfg files in the user's resource directory which apply to that task. Like a unix utility, this returns 0 on success (no files found or only 1 found but deleted). For multiple files found, this uses deleteAll, ... |
any files. MUST check return value. This does not prompt the user or print to the screen. """ # this WILL throw an exception if the taskPkgName isn't found flist = cfgpars.getUsrCfgFilesForPyPkg(taskPkgName) # can raise if flist is None or len(flist) == 0: return 0 if len(flist) == 1: os.remove(flist[0]) return 0 # at ... |
found if deleteAll: for f in flist: os.remove(f) return 0 else: return flist |
def diffFromDefaults(theTask, report=False): """ Load the given file (or existing object), and return a dict of its values which are different from the default values. If report is set, print to stdout the differences. """ # get the 2 dicts (trees: dicts of dicts) defaultTree = load(theTask, canExecute=False, strict=Tr... |
thisFlat = cfgpars.flattenDictTree(thisTree) # use the "set" operations till there is a dict.diff() # thanks to: http://stackoverflow.com/questions/715234 diffFlat = dict( set(thisFlat.items()) - \ set(defaultFlat.items()) ) if report: defaults_of_diffs_only = {} # { k:defaultFlat[k] for k in diffFlat.keys() } for k in... |
def _isInstalled(fullFname): """ Return True if the given file name is located in an installed area (versus a user-owned file) """ if not fullFname: return False if not os.path.exists(fullFname): return False instAreas = [] try: import site instAreas = site.getsitepackages() except: pass # python 2.6 and lower don't ha... |
fullFname.find(ia) >= 0: return True return False |
def execEmbCode(SCOPE, NAME, VAL, TEAL, codeStr): """ .cfgspc embedded code execution is done here, in a relatively confined space. The variables available to the code to be executed are: SCOPE, NAME, VAL, PARENT, TEAL The code string itself is expected to set a var named OUT """ # This was all we needed in Python 2.x ... |
return OUT # In Python 3 (& 2.x) be more explicit: http://bugs.python.org/issue4831 PARENT = None if TEAL: PARENT = TEAL.top OUT = None ldict = locals() # will have OUT in it exec(codeStr, globals(), ldict) return ldict['OUT'] |
def print_tasknames(pkgName, aDir, term_width=80, always=False, hidden=None): """ Print a message listing TEAL-enabled tasks available under a given installation directory (where pkgName resides). If always is True, this will always print when tasks are found; otherwise it will only print found tasks when in interactiv... |
""" # See if we can bail out early if not always: # We can't use the sys.ps1 check if in PyRAF since it changes sys if 'pyraf' not in sys.modules: # sys.ps1 is only defined in interactive mode if not hasattr(sys, 'ps1'): return # leave here, we're in someone's script # Check for tasks taskDict = cfgpars.findAllCfgTasks... |
taskDict.values() if len(x) > 0] if hidden: # could even account for a single taskname as input here if needed for x in hidden: if x in tasks: tasks.remove(x) # only be verbose if there something found if len(tasks) > 0: sortedUniqTasks = sorted(set(tasks)) if len(sortedUniqTasks) == 1: tlines = 'The following task in ... |
tlines = 'The following tasks in the '+pkgName+\ ' package can be run with TEAL:\n' tlines += printColsAuto(sortedUniqTasks, term_width=term_width, min_pad=2) print(tlines) |
def getHelpFileAsString(taskname,taskpath): """ This functions will return useful help as a string read from a file in the task's installed directory called "<module>.help". If no such file can be found, it will simply return an empty string. Notes ----- The location of the actual help file will be found under the task... |
This allows the help file to be either in the tasks installed directory or in any sub-directory, such as a "help/" directory. Parameters ---------- taskname: string Value of `__taskname__` for a module/task taskpath: string Value of `__file__` for an installed module which defines the task Returns ------- helpString: s... |
code is stored pathsplit=os.path.split(taskpath) # taskpath should be task's __file__ if taskname.find('.') > -1: # if taskname is given as package.taskname... helpname=taskname.split(".")[1] # taskname should be __taskname__ from task's module else: helpname = taskname localdir = pathsplit[0] if localdir == '': locald... |
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' |
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._saveAn... |
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.ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.