code stringlengths 1 18.2k |
|---|
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 lead... |
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle. """ # Parse out any extension specified in filename _indx = filename.find('[') if... |
it out... if repr(extn).find(',') > 1: _extns = extn.split(',') # Two values given for extension: # for example, 'sci,1' or 'dq,1' _extn = [_extns[0],int(_extns[1])] elif repr(extn).find('/') > 1: # We are working with GEIS group syntax _indx = str(extn[:extn.find('/')]) _extn = [int(_indx)] elif isinstance(extn, str):... |
_nextn = int(extn) else: # We only have EXTNAME specified... _nextn = extn _extn = [_nextn] else: # Only integer extension number given, or default of 0 is used. _extn = [int(extn)] else: _fname = filename _extn = None return _fname,_extn |
def _shape(self): """ Returns the shape of the data array associated with this file.""" hdu = self.open() _shape = hdu.shape if not self.inmemory: self.close() del hdu return _shape |
def _data(self): """ Returns the data array associated with this file/extenstion.""" hdu = self.open() _data = hdu.data.copy() if not self.inmemory: self.close() del hdu return _data |
def type(self): """ Returns the shape of the data array associated with this file.""" hdu = self.open() _type = hdu.data.dtype.name if not self.inmemory: self.close() del hdu return _type |
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.compre... |
def overlapsWith(self, targetStartTime, duration): """ Tests if the given times overlap with this measurement. :param targetStartTime: the target start time. :param duration: the duration :return: true if the given times overlap with this measurement. """ targetEndTime = targetStartTime + datetime.timedelta(days=0, sec... |
def updateDeviceStatus(self, deviceName, state, reason=None): """ Updates the current device status. :param deviceName: the device name. :param state: the state. :param reason: the reason for the change. :return: """ logger.info('Updating recording device state for ' + deviceName + ' to ' + state.name + ('' if reason i... |
is not None: if currentState['state'] == MeasurementStatus.RECORDING.name: count = currentState['count'] self.recordingDevices[deviceName] = { 'state': state.name, 'reason': reason, 'time': datetime.datetime.utcnow().strftime(DATETIME_FORMAT), 'count': count } |
def stillRecording(self, deviceId, dataCount): """ For a device that is recording, updates the last timestamp so we now when we last received data. :param deviceId: the device id. :param dataCount: the no of items of data recorded in this batch. :return: """ status = self.recordingDevices[deviceId] if status is not Non... |
def inflate(self): """ loads the recording into memory and returns it as a Signal :return: """ if self.measurementParameters['accelerometerEnabled']: if len(self.data) == 0: logger.info('Loading measurement data for ' + self.name) self.data = {name: self._loadXYZ(name) for name, value in self.recordingDevices.items()} ... |
def _sweep(self): """ Checks the state of each measurement and verifies their state, if an active measurement is now complete then passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts. :return: """ while self.running: for am in list(self.activeMeasurements): now ... |
if recordingDeviceCount > 0: if all(entry['state'] == RecordStatus.COMPLETE.name for entry in am.recordingDevices.values()): logger.info("Detected completedmeasurement " + am.id) self._moveToComplete(am) # we have reached the end time and we have either all failed devices or no devices == kill if now > (am.endTime + da... |
failed measurement " + am.id + " with " + str(recordingDeviceCount) + " devices, allFailed: " + str(allFailed)) self._moveToFailed(am) # we are well past the end time and we have failed devices or an ongoing recording == kill or deathbed if now > (am.endTime + datetime.timedelta(days=0, seconds=self.maxTimeTilDeathbedS... |
", assumed dead") self._moveToFailed(am) elif all(entry['state'] == RecordStatus.RECORDING.name for entry in am.recordingDevices.values()): self._handleDeathbed(am) time.sleep(0.1) logger.warning("MeasurementCaretaker is now shutdown") |
def schedule(self, name, duration, startTime, description=None): """ Schedules a new measurement with the given name. :param name: :param duration: :param startTime: :param description: :return: a tuple boolean: measurement was scheduled if true message: description, generally only used as an error code """ if self._cl... |
" + str(duration) + "s") self.activeMeasurements.append(am) devices = self.deviceController.scheduleMeasurement(am.id, am.duration, am.startTime) anyFail = False for device, status in devices.items(): if status == 200: deviceStatus = RecordStatus.SCHEDULED else: deviceStatus = RecordStatus.FAILED anyFail = True am.upda... |
def _clashes(self, startTime, duration): """ verifies that this measurement does not clash with an already scheduled measurement. :param startTime: the start time. :param duration: the duration. :return: true if the measurement is allowed. """ return [m for m in self.activeMeasurements if m.overlapsWith(startTime, dura... |
def startMeasurement(self, measurementId, deviceId): """ Starts the measurement for the device. :param deviceId: the device that is starting. :param measurementId: the measurement that is started. :return: true if it started (i.e. device and measurement exists). """ am, handler = self.getDataHandler(measurementId, devi... |
def getDataHandler(self, measurementId, deviceId): """ finds the handler. :param measurementId: the measurement :param deviceId: the device. :return: active measurement and handler """ am = next((m for m in self.activeMeasurements if m.id == measurementId), None) if am is None: return None, None else: device = self.dev... |
def recordData(self, measurementId, deviceId, data): """ Passes the data to the handler. :param deviceId: the device the data comes from. :param measurementId: the measurement id. :param data: the data. :return: true if the data was handled. """ am, handler = self.getDataHandler(measurementId, deviceId) if handler is n... |
measurementId) return False |
def completeMeasurement(self, measurementId, deviceId): """ Completes the measurement session. :param deviceId: the device id. :param measurementId: the measurement id. :return: true if it was completed. """ am, handler = self.getDataHandler(measurementId, deviceId) if handler is not None: handler.stop(measurementId) a... |
def failMeasurement(self, measurementId, deviceName, failureReason=None): """ Fails the measurement session. :param deviceName: the device name. :param measurementId: the measurement name. :param failureReason: why it failed. :return: true if it was completed. """ am, handler = self.getDataHandler(measurementId, device... |
def _deleteCompletedMeasurement(self, measurementId): """ Deletes the named measurement from the completed measurement store if it exists. :param measurementId: :return: String: error messages Integer: count of measurements deleted """ message, count, deleted = self.deleteFrom(measurementId, self.completeMeasurements) ... |
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.completeMeasuremen... |
MeasurementStatus.FAILED] |
def getMeasurements(self, measurementStatus=None): """ Gets all available measurements. :param measurementStatus return only the measurements in the given state. :return: """ if measurementStatus is None: return self.activeMeasurements + self.completeMeasurements + self.failedMeasurements elif measurementStatus == Meas... |
def getMeasurement(self, measurementId, measurementStatus=None): """ Gets the measurement with the given id. :param measurementId: the id. :param measurementStatus: the status of the requested measurement. :return: the matching measurement or none if it doesn't exist. """ return next((x for x in self.getMeasurements(me... |
def store(self, measurement): """ Writes the measurement metadata to disk on completion. :param activeMeasurement: the measurement that has completed. :returns the persisted metadata. """ os.makedirs(self._getPathToMeasurementMetaDir(measurement.idAsPath), exist_ok=True) output = marshal(measurement, measurementFields)... |
def load(self, path): """ Loads a CompletedMeasurement from the path.á :param path: the path at which the data is found. :return: the measurement """ meta = self._loadMetaFromJson(path) return CompleteMeasurement(meta, self.dataDir) if meta is not None else None |
def _loadMetaFromJson(self, path): """ Reads the json meta into memory. :return: the meta. """ try: with (path / 'metadata.json').open() as infile: return json.load(infile) except FileNotFoundError: logger.error('Metadata does not exist at ' + str(path)) return None |
def editMeasurement(self, measurementId, data): """ Edits the specified measurement with the provided data. :param measurementId: the measurement id. :param data: the data to update. :return: true if the measurement was edited """ oldMeasurement = self.getMeasurement(measurementId, measurementStatus=MeasurementStatus.C... |
oldMeasurement.duration)) newDuration = newEnd - newStart newDevices = data.get('devices', None) if newName: logger.info('Updating name from ' + oldMeasurement.name + ' to ' + newName) newMeasurement.updateName(newName) createdFilteredCopy = True deleteOld = True if newDesc: logger.info('Updating description from ' + s... |
== newMeasurement.name: newMeasurement.updateName(newMeasurement.name + '-' + str(int(time.time()))) newMeasurement.duration = newDuration createdFilteredCopy = True if createdFilteredCopy: logger.info('Copying measurement data from ' + oldMeasurement.idAsPath + ' to ' + newMeasurement.idAsPath) newMeasurementPath = se... |
from ' + str(renames[0]) + ' to ' + str(renames[1])) deviceState = newMeasurement.recordingDevices.get(renames[0]) newMeasurement.recordingDevices[renames[1]] = deviceState del newMeasurement.recordingDevices[renames[0]] os.rename(os.path.join(self._getPathToMeasurementMetaDir(newMeasurement.idAsPath), renames[0]), os.... |
def _filterCopy(self, dataFile, newStart, newEnd, newDataDir): """ Copies the data file to a new file in the tmp dir, filtering it according to newStart and newEnd and adjusting the times as appropriate so it starts from 0. :param dataFile: the input file. :param newStart: the new start time. :param newEnd: the new end... |
device name & no of rows in the data. """ import csv pathToData = os.path.split(dataFile) dataFileName = pathToData[1] dataDeviceName = os.path.split(pathToData[0])[1] os.makedirs(os.path.join(newDataDir, dataDeviceName), exist_ok=True) outputFile = os.path.join(newDataDir, dataDeviceName, dataFileName) dataCount = 0 r... |
<= time <= newEnd: newRow = row[:] if newStart > 0: newRow[0] = "{0:.3f}".format(time - newStart) writer.writerow(newRow) dataCount += 1 else: logger.warning('Ignoring empty row ' + str(rowNum) + ' in ' + str(dataFile)) rowNum += 1 return dataDeviceName, dataCount |
def checkFiles(filelist,ivmlist = None): """ - Converts waiver fits sciece and data quality files to MEF format - Converts GEIS science and data quality files to MEF format - Checks for stis association tables and splits them into single imsets - Removes files with EXPTIME=0 and the corresponding ivm files - Removes fi... |
with missing PA_V3 keyword The list of science files should match the list of ivm files at the end. """ toclose = False if isinstance(filelist[0], str): toclose = True newfilelist, ivmlist = checkFITSFormat(filelist, ivmlist) # check for STIS association files. This must be done before # the other checks in order to ha... |
newfilelist == []: return [], [] removed_expt_files = check_exptime(newfilelist) newfilelist, ivmlist = update_input(newfilelist, ivmlist, removed_expt_files) if newfilelist == []: return [], [] removed_ngood_files = checkNGOODPIX(newfilelist) newfilelist, ivmlist = update_input(newfilelist, ivmlist, removed_ngood_file... |
for hdul in newfilelist] return newfilelist, ivmlist |
def checkFITSFormat(filelist, ivmlist=None): """ This code will check whether or not files are GEIS or WAIVER FITS and convert them to MEF if found. It also keeps the IVMLIST consistent with the input filelist, in the case that some inputs get dropped during the check/conversion. """ if ivmlist is None: ivmlist = [None... |
= convert2fits(sci_ivm) newfilelist, ivmlist = update_input(filelist, ivmlist, removed_files) if newfilelist == [] and translated_names == []: return [], [] elif translated_names != []: newfilelist.extend(translated_names) ivmlist.extend(newivmlist) return newfilelist, ivmlist |
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 EX... |
[]: print("Warning: Removing the following files from input list") for f in removed_files: print('\t',f.filename() or "") return removed_files |
def checkNGOODPIX(filelist): """ Only for ACS, WFC3 and STIS, check NGOODPIX If all pixels are 'bad' on all chips, exclude this image from further processing. Similar checks requiring comparing 'driz_sep_bits' against WFPC2 c1f.fits arrays and NICMOS DQ arrays will need to be done separately (and later). """ toclose = ... |
fileutil.getKeyword(inputfile,'instrume') in supported_instruments: inputfile = fits.open(inputfile) toclose = True elif inputfile[0].header['instrume'] not in supported_instruments: continue ngood = 0 for extn in inputfile: if 'EXTNAME' in extn.header and extn.header['EXTNAME'] == 'SCI': ngood += extn.header['NGOODPIX... |
f in removed_files: print('\t',f.filename() or "") return removed_files |
def stisObsCount(input): """ Input: A stis multiextension file Output: Number of stis science extensions in input """ count = 0 toclose = False if isinstance(input, str): input = fits.open(input) toclose = True for ext in input: if 'extname' in ext.header: if (ext.header['extname'].upper() == 'SCI'): count += 1 if tocl... |
def splitStis(stisfile, sci_count): """ Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Returns ------- names: list a list with the names of the new flt files. """ newfiles =... |
= fits.open(stisfile) toclose = True else: f = stisfile hdu0 = f[0].copy() stisfilename = stisfile.filename() for count in range(1,sci_count+1): fitsobj = fits.HDUList() fitsobj.append(hdu0) hdu = f[('sci',count)].copy() fitsobj.append(hdu) rootname = hdu.header['EXPNAME'] newfilename = fileutil.buildNewRootname(rootna... |
hdu = f[('err',count)].copy() fitsobj.append(hdu) # Copy the dq extension hdu = f[('dq',count)].copy() fitsobj.append(hdu) fitsobj[1].header['EXTVER'] = 1 fitsobj[2].header['EXTVER'] = 1 fitsobj[3].header['EXTVER'] = 1 except ValueError: print('\nWarning:') print('Extension version %d of the input file %s does not' %(c... |
the disk. # If the file does exist, replace it. if (os.path.exists(newfilename)): os.remove(newfilename) print(" Replacing "+newfilename+"...") # Write out the new file fitsobj.writeto(newfilename) # Insure returned HDUList is associated with a file fitsobj.close() fitsobj = fits.open(newfilename, mode='update') newfil... |
if sptfile: hdu0 = sptfile[0].copy() try: for count in range(1,sci_count+1): fitsobj = fits.HDUList() fitsobj.append(hdu0) hdu = sptfile[count].copy() fitsobj.append(hdu) rootname = hdu.header['EXPNAME'] newfilename = fileutil.buildNewRootname(rootname, extn='_spt.fits') fitsobj[1].header['EXTVER'] = 1 if (os.path.exis... |
def stisExt2PrimKw(stisfiles): """ Several kw which are usually in the primary header are in the extension header for STIS. They are copied to the primary header for convenience. List if kw: 'DATE-OBS', 'EXPEND', 'EXPSTART', 'EXPTIME' """ kw_list = ['DATE-OBS', 'EXPEND', 'EXPSTART', 'EXPTIME'] for sfile in stisfiles: t... |
in kw_list: sfile[0].header[k] = sfile[1].header[k] sfile[0].header.comments[k] = "Copied from extension header" if toclose: sfile.close() |
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.isF... |
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], co... |
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 pres... |
%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 |
def waiver2mef(sciname, newname=None, convert_dq=True, writefits=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ if isinstance(sciname, fits.HDUList): filename = sciname.filename() el... |
= fileutil.buildNewRootname(filename, extn='_c1f.fits') dqexists = os.path.exists(_dqname) if convert_dq and dqexists: try: dqfile = convertwaiveredfits.convertwaiveredfits(_dqname) dqfitsname = fileutil.buildNewRootname(_dqname, extn='_c1h.fits') except Exception: print("Could not read data quality file %s" % _dqname)... |
fexists = os.path.exists(fitsname) if (fexists and clobber) or not fexists: print('Writing out WAIVERED as MEF to ', fitsname) if ASTROPY_VER_GE13: fimg.writeto(fitsname, overwrite=clobber) else: fimg.writeto(fitsname, clobber=clobber) if dqexists: print('Writing out WAIVERED as MEF to ', dqfitsname) if ASTROPY_VER_GE1... |
mode='update', memmap=False) return fimg except IOError: print('Warning: File %s could not be found' % sciname) return None |
def geis2mef(sciname, convert_dq=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ clobber = True mode = 'update' memmap = True # Input was specified as a GEIS image, but no FITS copy #... |
make a copy # then open the FITS copy... try: # Open as a GEIS image for reading only fimg = readgeis.readgeis(sciname) except Exception: raise IOError("Could not open GEIS input: %s" % sciname) #check for the existence of a data quality file _dqname = fileutil.buildNewRootname(sciname, extn='.c1h') dqexists = os.path.... |
quality file %s" % _dqname) # Check to see if user wanted to update GEIS header. # or write out a multi-extension FITS file and return a handle to it # User wants to make a FITS copy and update it # using the filename they have provided fitsname = fileutil.buildFITSName(sciname) # Write out GEIS image as multi-extensio... |
and clobber) or not fexists: print('Writing out GEIS as MEF to ', fitsname) if ASTROPY_VER_GE13: fimg.writeto(fitsname, overwrite=clobber) else: fimg.writeto(fitsname, clobber=clobber) if dqexists: print('Writing out GEIS as MEF to ', dqfitsname) if ASTROPY_VER_GE13: dqfile.writeto(dqfitsname, overwrite=clobber) else: ... |
def journals(self): """ Retrieve journals attribute for this very Issue """ try: target = self._item_path json_data = self._redmine.get(target % str(self.id), parms={'include': 'journals'}) data = self._redmine.unwrap_json(None, json_data) journals = [Journal(redmine=self._redmine, data=journal, type='issue_journal') f... |
def save(self, notes=None): '''Save all changes back to Redmine with optional notes.''' # Capture the notes if given if notes: self._changes['notes'] = notes # Call the base-class save function super(Issue, self).save() |
def set_status(self, new_status, notes=None): '''Save all changes and set to the given new_status''' self.status_id = new_status try: self.status['id'] = self.status_id # We don't have the id to name mapping, so blank the name self.status['name'] = None except: pass self.save(notes) |
def resolve(self, notes=None): '''Save all changes and resolve this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes) |
def close(self, notes=None): '''Save all changes and close this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_CLOSED, notes=notes) |
def _objectify(self, json_data=None, data={}): '''Return an object derived from the given json data.''' if json_data: # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which likely # contains an error message instead of data raise RedmineError(json_data) # ... |
{<data>} try: data = data[self._item_type] except KeyError: pass # If there's no ID but a source path if ('id' not in data) and ('_source_path' in data): # use the path between /projects/ and .json as the ID data['id'] = data['_source_path']\ .partition('/projects/')[2]\ .partition('.json')[0] # Call the base class obj... |
def new(self, page_name, **dict): ''' Create a new item with the provided dict information at the given page_name. Returns the new item. As of version 2.2 of Redmine, this doesn't seem to function. ''' self._item_new_path = '/projects/%s/wiki/%s.json' % \ (self._project.identifier, page_name) # Call the base class new ... |
def _set_version(self, version): ''' Set up this object based on the capabilities of the known versions of Redmine ''' # Store the version we are evaluating self.version = version or None # To evaluate the version capabilities, # assume the best-case if no version is provided. version_check = version or 9999.0 if versi... |
version 1.0 and higher.') ## SECURITY AUGMENTATION # All versions support the key in the request # (http://server/stuff.json?key=blah) # But versions 1.1 and higher can put the key in a header field # for better security. # If no version was provided (0.0) then assume we should # set the key with the request. self.key_... |
in the header or # it gets the hose, but not for 1.0. self.impersonation_supported = version_check >= 2.2 self.has_project_memberships = version_check >= 1.4 self.has_project_versions = version_check >= 1.3 self.has_wiki_pages = version_check >= 2.2 ## ITEM MANAGERS # Step through all the item managers by version # and... |
self._item_managers_by_version[manager_version] for attribute_name, item in managers.iteritems(): setattr(self, attribute_name, Redmine_Items_Manager(self, item)) |
def loadTargetState(targetStateConfig, existingTargetState=None): """ extracts a new TargetState object from the specified configuration :param targetStateConfig: the config dict. :param existingTargetState: the existing state :return: """ from analyser.common.targetstatecontroller import TargetState targetState = Targ... |
None: targetState.samplesPerBatch = val val = targetStateConfig.get('gyroEnabled') if val is not None: targetState.gyroEnabled = val val = targetStateConfig.get('gyroSens') if val is not None: targetState.gyroSens = val val = targetStateConfig.get('accelerometerEnabled') if val is not None: targetState.accelerometerEna... |
def interpret_bit_flags(bit_flags, flip_bits=None): """ Converts input bit flags to a single integer value (bitmask) or `None`. When input is a list of flags (either a Python list of integer flags or a sting of comma- or '+'-separated list of flags), the returned bitmask is obtained by summing input flags. .. note:: In... |
`str` type, prepend '~' to the input string. '~' must be prepended to the *entire string* and not to each bit flag! For input that is already a bitmask or a Python list of bit flags, set `flip_bits` for `True` in order to flip the bits of the returned bitmask. Parameters ---------- bit_flags : int, str, list, None An i... |
a string of comma- or '+'-separated list of integer bit flags, or a Python list of integer bit flags. If `bit_flags` is a `str` and if it is prepended with '~', then the output bitmask will have its bits flipped (compared to simple sum of input flags). For input `bit_flags` that is already a bitmask or a Python list of... |
be controlled through `flip_bits` parameter. flip_bits : bool, None Indicates whether or not to flip the bits of the returned bitmask obtained from input bit flags. This parameter must be set to `None` when input `bit_flags` is either `None` or a Python list of flags. Returns ------- bitmask : int or None Returns and i... |
`None` if input `bit_flags` parameter is `None` or an empty string. If input string value was prepended with '~' (or `flip_bits` was set to `True`), then returned value will have its bits flipped (inverse mask). Examples -------- >>> from stsci.tools.bitmask import interpret_bit_flags >>> "{0:016b}".format(0xFFFF & int... |
& interpret_bit_flags([4, 8, 16])) '0000000000011100' >>> "{0:016b}".format(0xFFFF & interpret_bit_flags([4, 8, 16], flip_bits=True)) '1111111111100011' """ has_flip_bits = flip_bits is not None flip_bits = bool(flip_bits) allow_non_flags = False if _is_int(bit_flags): return (~int(bit_flags) if flip_bits else int(bit_... |
raise TypeError( "Keyword argument 'flip_bits' is not permitted for " "comma-separated string lists of bit flags. Prepend '~' to " "the string to indicate bit-flipping." ) bit_flags = str(bit_flags).strip() if bit_flags.upper() in ['', 'NONE', 'INDEF']: return None # check whether bitwise-NOT is present and if it is, c... |
= True bit_flags = bit_flags[1:].lstrip() else: if bitflip_pos > 0: raise ValueError("Bitwise-NOT must precede bit flag list.") flip_bits = False # basic check for correct use of parenthesis: while True: nlpar = bit_flags.count('(') nrpar = bit_flags.count(')') if nlpar == 0 and nrpar == 0: break if nlpar != nrpar: rai... |
> 0 or rpar_pos < (len(bit_flags) - 1): raise ValueError("Incorrect syntax (incorrect use of " "parenthesis) in bit flag list.") bit_flags = bit_flags[1:-1].strip() if ',' in bit_flags: bit_flags = bit_flags.split(',') elif '+' in bit_flags: bit_flags = bit_flags.split('+') else: if bit_flags == '': raise ValueError( "... |
len(bit_flags) == 1 elif hasattr(bit_flags, '__iter__'): if not all([_is_int(flag) for flag in bit_flags]): raise TypeError("Each bit flag in a list must be an integer.") else: raise TypeError("Unsupported type for argument 'bit_flags'.") bitset = set(map(int, bit_flags)) if len(bitset) != len(bit_flags): warnings.warn... |
powers of two) " "bit flags") bitmask += v if flip_bits: bitmask = ~bitmask return bitmask |
def bitfield_to_boolean_mask(bitfield, ignore_flags=0, flip_bits=None, good_mask_value=True, dtype=np.bool_): """ bitfield_to_boolean_mask(bitfield, ignore_flags=None, flip_bits=None, \ good_mask_value=True, dtype=numpy.bool\_) Converts an array of bit fields to a boolean (or integer) mask array according to a bitmask ... |
array of bit flags. By default, values different from zero are interpreted as "bad" values and values equal to zero are considered as "good" values. However, see ``ignore_flags`` parameter on how to selectively ignore some bits in the ``bitfield`` array data. ignore_flags : int, str, list, None (Default = 0) An integer... |
list of integer bit flags that indicate what bits in the input ``bitfield`` should be *ignored* (i.e., zeroed), or `None`. | Setting ``ignore_flags`` to `None` effectively will make `bitfield_to_boolean_mask` interpret all ``bitfield`` elements as "good" regardless of their value. | When ``ignore_flags`` argument is an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.