sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def getObjectFromTaskArg(theTask, strict, setAllToDefaults): """ Take the arg (usually called theTask), which can be either a subclass of ConfigObjPars, or a string package name, or a .cfg filename - no matter what it is - take it and return a ConfigObjPars object. strict - bool - warning severity, pass...
Take the arg (usually called theTask), which can be either a subclass of ConfigObjPars, or a string package name, or a .cfg filename - no matter what it is - take it and return a ConfigObjPars object. strict - bool - warning severity, passed to the ConfigObjPars() ctor setAllToDefaults - bool - if theTa...
entailment
def getEmbeddedKeyVal(cfgFileName, kwdName, dflt=None): """ Read a config file and pull out the value of a given keyword. """ # Assume this is a ConfigObj file. Use that s/w to quickly read it and # put it in dict format. Assume kwd is at top level (not in a section). # The input may also be a .cfgspc...
Read a config file and pull out the value of a given keyword.
entailment
def findCfgFileForPkg(pkgName, theExt, pkgObj=None, taskName=None): """ Locate the configuration files for/from/within a given python package. pkgName is a string python package name. This is used unless pkgObj is given, in which case pkgName is taken from pkgObj.__name__. theExt is either '.cfg' or '....
Locate the configuration files for/from/within a given python package. pkgName is a string python package name. This is used unless pkgObj is given, in which case pkgName is taken from pkgObj.__name__. theExt is either '.cfg' or '.cfgspc'. If the task name is known, it is given as taskName, otherwise o...
entailment
def findAllCfgTasksUnderDir(aDir): """ Finds all installed tasks by examining any .cfg files found on disk at and under the given directory, as an installation might be. This returns a dict of { file name : task name } """ retval = {} for f in irafutils.rglob(aDir, '*.cfg'): retv...
Finds all installed tasks by examining any .cfg files found on disk at and under the given directory, as an installation might be. This returns a dict of { file name : task name }
entailment
def getCfgFilesInDirForTask(aDir, aTask, recurse=False): """ This is a specialized function which is meant only to keep the same code from needlessly being much repeated throughout this application. This must be kept as fast and as light as possible. This checks a given directory for .cfg f...
This is a specialized function which is meant only to keep the same code from needlessly being much repeated throughout this application. This must be kept as fast and as light as possible. This checks a given directory for .cfg files matching a given task. If recurse is True, it will ...
entailment
def getParsObjForPyPkg(pkgName, strict): """ Locate the appropriate ConfigObjPars (or subclass) within the given package. NOTE this begins the same way as getUsrCfgFilesForPyPkg(). Look for .cfg file matches in these places, in this order: 1 - any named .cfg file in current directory match...
Locate the appropriate ConfigObjPars (or subclass) within the given package. NOTE this begins the same way as getUsrCfgFilesForPyPkg(). Look for .cfg file matches in these places, in this order: 1 - any named .cfg file in current directory matching given task 2 - if there exists a ~/...
entailment
def getUsrCfgFilesForPyPkg(pkgName): """ See if the user has one of their own local .cfg files for this task, such as might be created automatically during the save of a read-only package, and return their names. """ # Get the python package and it's .cfg file thePkg, theFile = findCfgFileFo...
See if the user has one of their own local .cfg files for this task, such as might be created automatically during the save of a read-only package, and return their names.
entailment
def checkSetReadOnly(fname, raiseOnErr = False): """ See if we have write-privileges to this file. If we do, and we are not supposed to, then fix that case. """ if os.access(fname, os.W_OK): # We can write to this but it is supposed to be read-only. Fix it. # Take away usr-write, leave grou...
See if we have write-privileges to this file. If we do, and we are not supposed to, then fix that case.
entailment
def flattenDictTree(aDict): """ Takes a dict of vals and dicts (so, a tree) as input, and returns a flat dict (only one level) as output. All key-vals are moved to the top level. Sub-section dict names (keys) are ignored/dropped. If there are name collisions, an error is raised. """ retval = {} ...
Takes a dict of vals and dicts (so, a tree) as input, and returns a flat dict (only one level) as output. All key-vals are moved to the top level. Sub-section dict names (keys) are ignored/dropped. If there are name collisions, an error is raised.
entailment
def countKey(theDict, name): """ Return the number of times the given par exists in this dict-tree, since the same key name may be used in different sections/sub-sections. """ retval = 0 for key in theDict: val = theDict[key] if isinstance(val, dict): retval += countKey(val,...
Return the number of times the given par exists in this dict-tree, since the same key name may be used in different sections/sub-sections.
entailment
def findFirstPar(theDict, name, _depth=0): """ Find the given par. Return tuple: (its own (sub-)dict, its value). Returns the first match found, without checking whether the given key name is unique or whether it is used in multiple sections. """ for key in theDict: val = theDict[key] # ...
Find the given par. Return tuple: (its own (sub-)dict, its value). Returns the first match found, without checking whether the given key name is unique or whether it is used in multiple sections.
entailment
def findScopedPar(theDict, scope, name): """ Find the given par. Return tuple: (its own (sub-)dict, its value). """ # Do not search (like findFirstPar), but go right to the correct # sub-section, and pick it up. Assume it is there as stated. if len(scope): theDict = theDict[scope] # ! only goe...
Find the given par. Return tuple: (its own (sub-)dict, its value).
entailment
def setPar(theDict, name, value): """ Sets a par's value without having to give its scope/section. """ section, previousVal = findFirstPar(theDict, name) # "section" is the actual object, not a copy section[name] = value
Sets a par's value without having to give its scope/section.
entailment
def mergeConfigObj(configObj, inputDict): """ Merge the inputDict values into an existing given configObj instance. The inputDict is a "flat" dict - it has no sections/sub-sections. The configObj may have sub-sections nested to any depth. This will raise a DuplicateKeyError if one of the inputDict key...
Merge the inputDict values into an existing given configObj instance. The inputDict is a "flat" dict - it has no sections/sub-sections. The configObj may have sub-sections nested to any depth. This will raise a DuplicateKeyError if one of the inputDict keys is used more than once in configObj (e.g. wi...
entailment
def findTheLost(config_file, configspec_file, skipHidden=True): """ Find any lost/missing parameters in this cfg file, compared to what the .cfgspc says should be there. This method is recommended by the ConfigObj docs. Return a stringified list of item errors. """ # do some sanity checking, but don't (...
Find any lost/missing parameters in this cfg file, compared to what the .cfgspc says should be there. This method is recommended by the ConfigObj docs. Return a stringified list of item errors.
entailment
def isHiddenName(astr): """ Return True if this string name denotes a hidden par or section """ if astr is not None and len(astr) > 2 and astr.startswith('_') and \ astr.endswith('_'): return True else: return False
Return True if this string name denotes a hidden par or section
entailment
def flattened2str(flattened, missing=False, extra=False): """ Return a pretty-printed multi-line string version of the output of flatten_errors. Know that flattened comes in the form of a list of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) so we ...
Return a pretty-printed multi-line string version of the output of flatten_errors. Know that flattened comes in the form of a list of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) so we turn that into a string. Set missing to True if all the input ...
entailment
def getDefaultSaveFilename(self, stub=False): """ Return name of file where we are expected to be saved if no files for this task have ever been saved, and the user wishes to save. If stub is True, the result will be <dir>/<taskname>_stub.cfg instead of <dir>/<taskname>.cfg. """ ...
Return name of file where we are expected to be saved if no files for this task have ever been saved, and the user wishes to save. If stub is True, the result will be <dir>/<taskname>_stub.cfg instead of <dir>/<taskname>.cfg.
entailment
def syncParamList(self, firstTime, preserve_order=True): """ Set or reset the internal param list from the dict's contents. """ # See the note in setParam about this design. # Get latest par values from dict. Make sure we do not # change the id of the __paramList pointer here. ...
Set or reset the internal param list from the dict's contents.
entailment
def getDefaultParList(self): """ Return a par list just like ours, but with all default values. """ # The code below (create a new set-to-dflts obj) is correct, but it # adds a tenth of a second to startup. Clicking "Defaults" in the # GUI does not call this. But this can be used to se...
Return a par list just like ours, but with all default values.
entailment
def setParam(self, name, val, scope='', check=1, idxHint=None): """ Find the ConfigObj entry. Update the __paramList. """ theDict, oldVal = findScopedPar(self, scope, name) # Set the value, even if invalid. It needs to be set before # the validation step (next). theDict[name] ...
Find the ConfigObj entry. Update the __paramList.
entailment
def saveParList(self, *args, **kw): """Write parameter data to filename (string or filehandle)""" if 'filename' in kw: filename = kw['filename'] if not filename: filename = self.getFilename() if not filename: raise ValueError("No filename specified to ...
Write parameter data to filename (string or filehandle)
entailment
def run(self, *args, **kw): """ This may be overridden by a subclass. """ if self._runFunc is not None: # remove the two args sent by EditParDialog which we do not use if 'mode' in kw: kw.pop('mode') if '_save' in kw: kw.pop('_save') return self._runFunc(s...
This may be overridden by a subclass.
entailment
def triggerLogicToStr(self): """ Print all the trigger logic to a string and return it. """ try: import json except ImportError: return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n"+json.dumps(self._allTriggers, indent=3) ...
Print all the trigger logic to a string and return it.
entailment
def _findAssociatedConfigSpecFile(self, cfgFileName): """ Given a config file, find its associated config-spec file, and return the full pathname of the file. """ # Handle simplest 2 cases first: co-located or local .cfgspc file retval = "."+os.sep+self.__taskName+".cfgspc" if o...
Given a config file, find its associated config-spec file, and return the full pathname of the file.
entailment
def _getParamsFromConfigDict(self, cfgObj, scopePrefix='', initialPass=False, dumpCfgspcTo=None): """ Walk the given ConfigObj dict pulling out IRAF-like parameters into a list. Since this operates on a dict this can be called recursively. This is also our chance...
Walk the given ConfigObj dict pulling out IRAF-like parameters into a list. Since this operates on a dict this can be called recursively. This is also our chance to find and pull out triggers and such dependencies.
entailment
def getTriggerStrings(self, parScope, parName): """ For a given item (scope + name), return all strings (in a tuple) that it is meant to trigger, if any exist. Returns None is none. """ # The data structure of _allTriggers was chosen for how easily/quickly # this particular access can b...
For a given item (scope + name), return all strings (in a tuple) that it is meant to trigger, if any exist. Returns None is none.
entailment
def getExecuteStrings(self, parScope, parName): """ For a given item (scope + name), return all strings (in a tuple) that it is meant to execute, if any exist. Returns None is none. """ # The data structure of _allExecutes was chosen for how easily/quickly # this particular access can b...
For a given item (scope + name), return all strings (in a tuple) that it is meant to execute, if any exist. Returns None is none.
entailment
def getPosArgs(self): """ Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file. """ if len(self._posArgs) < 1: return [] # The first item in the tuple is the index, so we now sort by it self._posArgs.sort() # Build a return list r...
Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file.
entailment
def getKwdArgs(self, flatten = False): """ Return a dict of all normal dict parameters - that is, all parameters NOT marked with "pos=N" in the .cfgspc file. This will also exclude all hidden parameters (metadata, rules, etc). """ # Start with a full deep-copy. What complicate...
Return a dict of all normal dict parameters - that is, all parameters NOT marked with "pos=N" in the .cfgspc file. This will also exclude all hidden parameters (metadata, rules, etc).
entailment
def tryValue(self, name, val, scope=''): """ For the given item name (and scope), we are being asked to try the given value to see if it would pass validation. We are not to set it, but just try it. We return a tuple: If it fails, we return: (False, the last known valid va...
For the given item name (and scope), we are being asked to try the given value to see if it would pass validation. We are not to set it, but just try it. We return a tuple: If it fails, we return: (False, the last known valid value). On success, we return: (True, None)...
entailment
def listTheExtras(self, deleteAlso): """ Use ConfigObj's get_extra_values() call to find any extra/unknown parameters we may have loaded. Return a string similar to findTheLost. If deleteAlso is True, this will also delete any extra/unknown items. """ # get list of extras ...
Use ConfigObj's get_extra_values() call to find any extra/unknown parameters we may have loaded. Return a string similar to findTheLost. If deleteAlso is True, this will also delete any extra/unknown items.
entailment
def get(self): """ Reloads the measurements from the backing store. :return: 200 if success. """ try: self._measurementController.reloadCompletedMeasurements() return None, 200 except: logger.exception("Failed to reload measurements") ...
Reloads the measurements from the backing store. :return: 200 if success.
entailment
def handle(self, data): """ Writes each sample to a csv file. :param data: the samples. :return: """ self.logger.debug("Handling " + str(len(data)) + " data items") for datum in data: if isinstance(datum, dict): # these have to wrapped ...
Writes each sample to a csv file. :param data: the samples. :return:
entailment
def start(self, measurementId): """ Posts to the target to tell it a named measurement is starting. :param measurementId: """ self.sendURL = self.rootURL + measurementId + '/' + self.deviceName self.startResponseCode = self._doPut(self.sendURL)
Posts to the target to tell it a named measurement is starting. :param measurementId:
entailment
def handle(self, data): """ puts the data in the target. :param data: the data to post. :return: """ self.dataResponseCode.append(self._doPut(self.sendURL + '/data', data=data))
puts the data in the target. :param data: the data to post. :return:
entailment
def stop(self, measurementId, failureReason=None): """ informs the target the named measurement has completed :param measurementId: the measurement that has completed. :return: """ if failureReason is None: self.endResponseCode = self._doPut(self.sendURL + "/c...
informs the target the named measurement has completed :param measurementId: the measurement that has completed. :return:
entailment
def dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum(' 1.2')) 16777218 >>> int(dottedQuadToNum(' 1.2.3 ')) 16908291 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 >>> dottedQuadToNum('255.255.2...
Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum(' 1.2')) 16777218 >>> int(dottedQuadToNum(' 1.2.3 ')) 16908291 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 >>> dottedQuadToNum('255.255.255.255') 4294967295 >>> dotte...
entailment
def numToDottedQuad(num): """ Convert long int to dotted quad string >>> numToDottedQuad(long(-1)) Traceback (most recent call last): ValueError: Not a good numeric IP: -1 >>> numToDottedQuad(long(1)) '0.0.0.1' >>> numToDottedQuad(long(16777218)) '1.0.0.2' >>> numToDottedQuad(lo...
Convert long int to dotted quad string >>> numToDottedQuad(long(-1)) Traceback (most recent call last): ValueError: Not a good numeric IP: -1 >>> numToDottedQuad(long(1)) '0.0.0.1' >>> numToDottedQuad(long(16777218)) '1.0.0.2' >>> numToDottedQuad(long(16908291)) '1.2.0.3' >>> nu...
entailment
def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_para...
Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_param(('', ''), (0, 1.0), to_float=True) [0.0, 1.0] >>> _i...
entailment
def is_integer(value, min=None, max=None): """ A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is r...
A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor = Validator() >>> vtor.check('...
entailment
def is_float(value, min=None, max=None): """ A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative...
A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor = Validator() >>> vtor.che...
entailment
def is_boolean(value): """ Check if the value represents a boolean. >>> vtor = Validator() >>> vtor.check('boolean', 0) 0 >>> vtor.check('boolean', False) 0 >>> vtor.check('boolean', '0') 0 >>> vtor.check('boolean', 'off') 0 >>> vtor.check('boolean', 'false') 0 >...
Check if the value represents a boolean. >>> vtor = Validator() >>> vtor.check('boolean', 0) 0 >>> vtor.check('boolean', False) 0 >>> vtor.check('boolean', '0') 0 >>> vtor.check('boolean', 'off') 0 >>> vtor.check('boolean', 'false') 0 >>> vtor.check('boolean', 'no') ...
entailment
def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. >>> vtor = Validator() >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ')...
Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. >>> vtor = Validator() >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ') '1.2.3' >>> vtor.check('ip...
entailment
def is_list(value, min=None, max=None): """ Check that the value is a list of values. You can optionally specify the minimum and maximum number of members. It does no check on list members. >>> vtor = Validator() >>> vtor.check('list', ()) [] >>> vtor.check('list', []) [] >>> ...
Check that the value is a list of values. You can optionally specify the minimum and maximum number of members. It does no check on list members. >>> vtor = Validator() >>> vtor.check('list', ()) [] >>> vtor.check('list', []) [] >>> vtor.check('list', (1, 2)) [1, 2] >>> vtor.c...
entailment
def is_int_list(value, min=None, max=None): """ Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. >>> vtor = Validator() >>> vtor.check('int_list', ()) [] >>> vtor.check(...
Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. >>> vtor = Validator() >>> vtor.check('int_list', ()) [] >>> vtor.check('int_list', []) [] >>> vtor.check('int_list', (1...
entailment
def is_bool_list(value, min=None, max=None): """ Check that the value is a list of booleans. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a boolean. >>> vtor = Validator() >>> vtor.check('bool_list', ()) [] >>> vtor.check...
Check that the value is a list of booleans. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a boolean. >>> vtor = Validator() >>> vtor.check('bool_list', ()) [] >>> vtor.check('bool_list', []) [] >>> check_res = vtor.check('...
entailment
def is_float_list(value, min=None, max=None): """ Check that the value is a list of floats. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a float. >>> vtor = Validator() >>> vtor.check('float_list', ()) [] >>> vtor.check('...
Check that the value is a list of floats. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a float. >>> vtor = Validator() >>> vtor.check('float_list', ()) [] >>> vtor.check('float_list', []) [] >>> vtor.check('float_list', (...
entailment
def is_string_list(value, min=None, max=None): """ Check that the value is a list of strings. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a string. >>> vtor = Validator() >>> vtor.check('string_list', ()) [] >>> vtor.che...
Check that the value is a list of strings. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a string. >>> vtor = Validator() >>> vtor.check('string_list', ()) [] >>> vtor.check('string_list', []) [] >>> vtor.check('string_lis...
entailment
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', ()) [] ...
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...
entailment
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 great...
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 s...
entailment
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_ad...
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 spec...
entailment
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:...
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. >>> vt...
entailment
def check(self, check, value, missing=False): """ Usage: check(check, value) Arguments: check: string representing check to apply (including arguments) value: object to be checked Returns value, converted to correct type if necessary If the check fails, ...
Usage: check(check, value) Arguments: check: string representing check to apply (including arguments) value: object to be checked Returns value, converted to correct type if necessary If the check fails, raises a ``ValidateError`` subclass. >>> vtor = Validator...
entailment
def _unquote(self, val): """Unquote a value if necessary.""" if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]): val = val[1:-1] return val
Unquote a value if necessary.
entailment
def _list_handle(self, listmatch): """Take apart a ``keyword=list('val, 'val')`` type string.""" out = [] name = listmatch.group(1) args = listmatch.group(2) for arg in self._list_members.findall(args): out.append(self._unquote(arg)) return name, out
Take apart a ``keyword=list('val, 'val')`` type string.
entailment
def get_default_value(self, check): """ Given a check, return the default value for the check (converted to the right type). If the check doesn't specify a default value then a ``KeyError`` will be raised. """ fun_name, fun_args, fun_kwargs, default = self._parse...
Given a check, return the default value for the check (converted to the right type). If the check doesn't specify a default value then a ``KeyError`` will be raised.
entailment
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_heade...
A constant value HDU will only be recognized as such if the header contains a valid PIXVALUE and NAXIS == 0.
entailment
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
Verify that the HDU's data is a constant value array.
entailment
def get_current_index(self): """ Return currently selected index (or -1) """ # Need to convert to int; currently API returns a tuple of string curSel = self.__lb.curselection() if curSel and len(curSel) > 0: return int(curSel[0]) else: return -1
Return currently selected index (or -1)
entailment
def convert(input): """Input GEIS files "input" will be read and a HDUList object will be returned that matches the waiver-FITS format written out by 'stwfits' in IRAF. The user can use the writeto method to write the HDUList object to a FITS file. """ global dat cardLen = fits.C...
Input GEIS files "input" will be read and a HDUList object will be returned that matches the waiver-FITS format written out by 'stwfits' in IRAF. The user can use the writeto method to write the HDUList object to a FITS file.
entailment
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) ...
loads configuration from some predictable locations. :return: the config.
entailment
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)) ...
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.
entailment
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')
Gets the currently configured config path. :return: the path, raises ValueError if it doesn't exist.
entailment
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 log...
Configures the python logging system to log to a debug file and to stdout for warn and above. :return: the base logger.
entailment
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 ...
Translate IBM-format floating point numbers (as bytes) to IEEE 754 64-bit floating point format (as Python float).
entailment
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.is...
Translate Python floating point numbers to IBM-format (as bytes).
entailment
def dumps(columns): ''' Serialize ``columns`` to a JSON formatted ``bytes`` object. ''' fp = BytesIO() dump(columns, fp) fp.seek(0) return fp.read()
Serialize ``columns`` to a JSON formatted ``bytes`` object.
entailment
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']), ...
Parse the 3-line (240-byte) header of a SAS XPORT file.
entailment
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':...
Parse the 4-line (320-byte) library member header.
entailment
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'])
Parse a member namestrs header (1 line, 80 bytes).
entailment
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 ...
Parse variable metadata for a XPORT file member.
entailment
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
Determine Julian day count from Islamic date
entailment
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)
Calculate Islamic date from Julian day
entailment
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). ""...
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).
entailment
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)
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.
entailment
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') ...
Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this
entailment
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_f...
Set focus to next item in sequence
entailment
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('...
Set focus to previous item in sequence
entailment
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...
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 i...
entailment
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 defau...
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.
entailment
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 def...
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.
entailment
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() ...
Make an entire section (minus skipList items) either active or inactive. sectionName is the same as the param's scope.
entailment
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 curren...
Save the parameter settings to a user-specified file. Any changes here must be coordinated with the corresponding tpar save_as function.
entailment
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 o...
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.
entailment
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) #---------------------...
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.
entailment
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 n...
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 TparDisplay method.
entailment
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 ...
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.
entailment
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 #...
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.
entailment
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)
Internal callback used to make sure the msg list keeps moving.
entailment
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...
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.
entailment
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...
Start the GUI session, or simply load a task's ConfigObj.
entailment
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, default...
Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True.
entailment
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...
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, returning the file-name-list i...
entailment
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, canExe...
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.
entailment
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() ...
Return True if the given file name is located in an installed area (versus a user-owned file)
entailment
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 """ ...
.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
entailment
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 i...
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 interactive mode. The parameter 'hidden' supports a ...
entailment
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 fil...
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's installed directory...
entailment
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'
Get a stringified val from a ConfigObj obj and return it as bool
entailment