code stringlengths 1 18.2k |
|---|
def flagThisPar(self, currentVal, force): """ If this par's value is different from the default value, it is here that we flag it somehow as such. This basic version simply makes the surrounding text red (or returns it to normal). May be overridden. Leave force at False if you want to allow this mehtod to make smart ti... |
because it is already the right color. Set force to true if you think we got out of sync and need to be fixed. """ # Get out ASAP if we can if (not force) and (not self._flagNonDefaultVals): return # handle simple case before comparing values (quick return) if force and not self._flagNonDefaultVals: self._flagged = Fal... |
= self.convertToNative(currentVal) defaultNative = self.convertToNative(self.defaultParamInfo.value) # par.value is same as par.get(native=1,prompt=0) # flag or unflag as needed if currentNative != defaultNative: if not self._flagged or force: self._flagged = True self.promptLabel.configure(fg=self._flaggedColor) # was... |
def keypress(self, event): """Allow keys typed in widget to select items""" try: self.choice.set(self.shortcuts[event.keysym]) except KeyError: # key not found (probably a bug, since we intend to catch # only events from shortcut keys, but ignore it anyway) pass |
def postcmd(self): """Make sure proper entry is activated when menu is posted""" value = self.choice.get() try: index = self.paramInfo.choice.index(value) self.entry.menu.activate(index) except ValueError: # initial null value may not be in list pass |
def convertToNative(self, aVal): """ Convert to native bool; interpret certain strings. """ if aVal is None: return None if isinstance(aVal, bool): return aVal # otherwise interpret strings return str(aVal).lower() in ('1','on','yes','true') |
def toggle(self, event=None): """Toggle value between Yes and No""" if self.choice.get() == "yes": self.rbno.select() else: self.rbyes.select() self.widgetEdited() |
def entryCheck(self, event = None, repair = True): """ Ensure any INDEF entry is uppercase, before base class behavior """ valupr = self.choice.get().upper() if valupr.strip() == 'INDEF': self.choice.set(valupr) return EparOption.entryCheck(self, event, repair = repair) |
def xyinterp(x,y,xval): """ :Purpose: Interpolates y based on the given xval. x and y are a pair of independent/dependent variable arrays that must be the same length. The x array must also be sorted. xval is a user-specified value. This routine looks up xval in the x array and uses that information to properly interpo... |
the searchsorted method on the X array to determine the bin in which xval falls; then use that information to compute the corresponding y value. See Also ======== numpy Parameters ========== x: 1D numpy array independent variable array: MUST BE SORTED y: 1D numpy array dependent variable array xval: float the x value a... |
======= y: float the value of y corresponding to xval Raises ====== ValueError: If arrays are unequal length; or x array is unsorted; or if xval falls outside the bounds of x (extrapolation is unsupported :version: 0.1 last modified 2006-07-06 """ #Enforce conditions on x, y, and xval: #x and y must correspond if len(x... |
#Extrapolation not supported if xval < x[0]: raise ValueError("Value %f < min(x) %f: Extrapolation unsupported"%(xval,x[0])) if xval > x[-1]: raise ValueError("Value > max(x): Extrapolation unsupported") #This algorithm only works on sorted data if x.argsort().all() != N.arange(len(x)).all(): raise ValueError("Input ar... |
x[lo]) except ZeroDivisionError: seg = 0.0 yval = y[lo] + seg*(y[hi] - y[lo]) return yval |
def _setSampleSizeBytes(self): """ updates the current record of the packet size per sample and the relationship between this and the fifo reads. """ self.sampleSizeBytes = self.getPacketSize() if self.sampleSizeBytes > 0: self.maxBytesPerFifoRead = (32 // self.sampleSizeBytes) |
def getPacketSize(self): """ the current packet size. :return: the current packet size based on the enabled registers. """ size = 0 if self.isAccelerometerEnabled(): size += 6 if self.isGyroEnabled(): size += 6 if self.isTemperatureEnabled(): size += 2 return size |
def initialiseDevice(self): """ performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return: """ logger.debug("Initialising device") self.getInterruptStatus() self.setAccelerometerSensitivity(self._accelerationFactor * 32768.0) self.setGyroSensitivity(self._... |
standby modes self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_PWR_MGMT_2, 0x00) # Enables any I2C master interrupt source to generate an interrupt self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_INT_ENABLE, 0x01) # enable the FIFO self.enableFifo() logger.debug("Initialised device") |
def enableAccelerometer(self): """ Specifies the device should write acceleration values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling acceleration sensor") self.fifoSensorMask |= self.enableAccelerometerMask self._accelEnabled = True self._setSampleSizeBytes() |
def disableAccelerometer(self): """ Specifies the device should NOT write acceleration values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling acceleration sensor") self.fifoSensorMask &= ~self.enableAccelerometerMask self._accelEnabled = False self._setSampleSizeBytes() |
def enableGyro(self): """ Specifies the device should write gyro values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling gyro sensor") self.fifoSensorMask |= self.enableGyroMask self._gyroEnabled = True self._setSampleSizeBytes() |
def disableGyro(self): """ Specifies the device should NOT write gyro values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling gyro sensor") self.fifoSensorMask &= ~self.enableGyroMask self._gyroEnabled = False self._setSampleSizeBytes() |
def enableTemperature(self): """ Specifies the device should write temperature values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Enabling temperature sensor") self.fifoSensorMask |= self.enableTemperatureMask self._setSampleSizeBytes() |
def disableTemperature(self): """ Specifies the device should NOT write temperature values to the FIFO, is not applied until enableFIFO is called. :return: """ logger.debug("Disabling temperature sensor") self.fifoSensorMask &= ~self.enableTemperatureMask self._setSampleSizeBytes() |
def setGyroSensitivity(self, value): """ Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the self tests) :param value: the target sensitivity. """ try: self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_GYRO_CONFIG, {250: 0, 500: 8, 1000: 16, 2000: 24}[valu... |
a valid sensitivity (250,500,1000,2000)") |
def setAccelerometerSensitivity(self, value): """ Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if the value provided is not valid. :param value: the target sensitivity. """ # note that this implicitly disables the self tests on each axis # i.e. the full byte ... |
the next two # values are the actual sensitivity and the last 3 are unused # the 2 [accel] bits are translated by the device as follows; 00 = 2g, 01 = 4g, 10 = 8g, 11 = 16g # in binary we get 2 = 0, 4 = 1000, 8 = 10000, 16 = 11000 # so the 1st 3 bits are always |
0 try: self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_ACCEL_CONFIG, {2: 0, 4: 8, 8: 16, 16: 24}[value]) self._accelerationFactor = value / 32768.0 self.accelerometerSensitivity = value logger.debug("Set accelerometer sensitivity = %d", value) except KeyError: raise ArgumentError(value + " is not a valid sensit... |
def setSampleRate(self, targetSampleRate): """ Sets the internal sample rate of the MPU-6050, this requires writing a value to the device to set the sample rate as Gyroscope Output Rate / (1 + SMPLRT_DIV) where the gryoscope outputs at 8kHz and the peak sampling rate is 1kHz. The target sample rate is therefore capped ... |
= int((8000 / min(targetSampleRate, 1000)) - 1) self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_SMPLRT_DIV, sampleRateDenominator) self.fs = 8000.0 / (sampleRateDenominator + 1.0) logger.debug("Set sample rate = %d", self.fs) |
def resetFifo(self): """ Resets the FIFO by first disabling the FIFO then sending a FIFO_RESET and then re-enabling the FIFO. :return: """ logger.debug("Resetting FIFO") self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL, 0b00000000) pass self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_USER_CTRL,... |
def enableFifo(self): """ Enables the FIFO, resets it and then sets which values should be written to the FIFO. :return: """ logger.debug("Enabling FIFO") self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_EN, 0) self.resetFifo() self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_FIFO_EN, self.fifoSensor... |
def getFifoCount(self): """ gets the amount of data available on the FIFO right now. :return: the number of bytes available on the FIFO which will be proportional to the number of samples available based on the values the device is configured to sample. """ bytes = self.i2c_io.readBlock(self.MPU6050_ADDRESS, self.MPU60... |
def getDataFromFIFO(self, bytesToRead): """ reads the specified number of bytes from the FIFO, should be called after a call to getFifoCount to ensure there is new data available (to avoid reading duplicate data). :param bytesToRead: the number of bytes to read. :return: the bytes read. """ return self.i2c_io.readBlock... |
def provideData(self): """ reads a batchSize batch of data from the FIFO while attempting to optimise the number of times we have to read from the device itself. :return: a list of data where each item is a single sample of data converted into real values and stored as a dict. """ samples = [] fifoBytesAvailable = 0 fi... |
%d samples", self.samplesPerBatch) iterations = 0 # allow 1.5x the expected duration of the batch breakTime = time() + ((self.samplesPerBatch / self.fs) * 1.5) overdue = False while len(samples) < self.samplesPerBatch and not overdue: iterations += 1 if iterations > self.samplesPerBatch and iterations % 100 == 0: if ti... |
< self.sampleSizeBytes or fifoWasReset: interrupt = self.getInterruptStatus() fifoBytesAvailable = self.getFifoCount() fifoWasReset = False logger.debug("Start sample loop [available: %d , required: %d]", fifoBytesAvailable, self.sampleSizeBytes) if interrupt & 0x10: logger.error("FIFO OVERFLOW, RESETTING [available: %... |
True elif interrupt & 0x02 or interrupt & 0x01: # wait for at least 1 sample to arrive, should be a VERY short wait while fifoBytesAvailable < self.sampleSizeBytes: logger.debug("Waiting for sample [available: %d , required: %d]", fifoBytesAvailable, self.sampleSizeBytes) fifoBytesAvailable = self.getFifoCount() logger... |
it up # if we have more than 1 sample available then ensure we read as many as we can at once (albeit within # the limits of the max i2c read size of 32 bytes) if fifoBytesAvailable > self.sampleSizeBytes: fifoReadBytes = min(fifoBytesAvailable // self.sampleSizeBytes, self.maxBytesPerFifoRead) * self.sampleSizeBytes l... |
than we need to fulfil the batch samplesToRead = fifoReadBytes // self.sampleSizeBytes excessSamples = self.samplesPerBatch - len(samples) - samplesToRead if excessSamples < 0: samplesToRead += excessSamples fifoReadBytes = int(samplesToRead * self.sampleSizeBytes) logger.debug("Excess samples to read [available: %d , ... |
and convert to the actual values fifoBytes = self.getDataFromFIFO(fifoReadBytes) samples.extend([self.unpackSample(fifoBytes[i:i + self.sampleSizeBytes]) for i in range(0, len(fifoBytes), self.sampleSizeBytes)]) # track the count here so we can avoid going back to the FIFO each time fifoBytesAvailable -= fifoReadBytes ... |
def unpackSample(self, rawData): """ unpacks a single sample of data (where sample length is based on the currently enabled sensors). :param rawData: the data to convert :return: a converted data set. """ length = len(rawData) # TODO error if not multiple of 2 # logger.debug(">> unpacking sample %d length %d", self._sa... |
the data in a dictionary mpu6050 = collections.OrderedDict() mpu6050[SAMPLE_TIME] = self._sampleIdx / self.fs sensorIdx = 0 if self.isAccelerometerEnabled(): mpu6050[ACCEL_X] = unpacked[sensorIdx] * self._accelerationFactor sensorIdx += 1 mpu6050[ACCEL_Y] = unpacked[sensorIdx] * self._accelerationFactor sensorIdx += 1 ... |
mpu6050[GYRO_Y] = unpacked[sensorIdx] * self._gyroFactor sensorIdx += 1 mpu6050[GYRO_Z] = unpacked[sensorIdx] * self._gyroFactor sensorIdx += 1 # TODO should we send as a dict so the keys are available? output = list(mpu6050.values()) self._sampleIdx += 1 # logger.debug("<< unpacked sample length %d into vals size %d",... |
def wrap(text, width, *args, **kwargs): """ Like :func:`textwrap.wrap` but preserves existing newlines which :func:`textwrap.wrap` does not otherwise handle well. See Also -------- :func:`textwrap.wrap` """ return sum([textwrap.wrap(line, width, *args, **kwargs) if line else [''] for line in text.splitlines()], []) |
def textbox(text, width=78, boxchar='#', indent=0): """ Outputs line-wrapped text wrapped in a box drawn with a repeated (usually ASCII) character. For example: >>> print(textbox('Text to wrap', width=16)) ################ # # # Text to wrap # # # ################ Parameters ---------- text : string The text to wrap wi... |
the wrapped text is padded with an additional column of whitespace on each side, the minimum width is 5--any width less than that is is automatically increased to 5 (default: 78) boxchar : string (No pun intended.) The character to draw the box with. May also be a string of multiple characters (default: '#') indent : i... |
should be indented. (default: 0) """ min_width = len(boxchar) * 2 + 3 width = max(width-indent, min_width) indentspace = indent * ' ' wrap_width = width - min_width + 1 q, r = divmod(width, len(boxchar)) # The top/bottom border top_border = indentspace + boxchar * q + boxchar[:r] top_padding = indentspace + boxchar + '... |
lines = ['%s%s %s %s' % (indentspace, boxchar, line.ljust(wrap_width), boxchar) for line in wrap(text, wrap_width)] top = [top_border, top_padding] bottom = [top_padding, top_border] return '\n'.join(top + lines + bottom) |
def main(): """Entrypoint function.""" parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', help='Hydro Quebec username') parser.add_argument('-p', '--password', help='Password') parser.add_argument('-j', '--json', action='store_true', default=False, help='Json output') parser.add_argument('-i', '... |
option') raw_group.add_argument('--detailled-energy', action='store_true', default=False, help='Get raw json output download') raw_group.add_argument('--start-date', default=(datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)).strftime("%Y-%m-%d"), help='Start date for detailled-output') raw_group.add_argu... |
client.fetch_data() else: start_date = datetime.datetime.strptime(args.start_date, '%Y-%m-%d') end_date = datetime.datetime.strptime(args.end_date, '%Y-%m-%d') async_func = client.fetch_data_detailled_energy_use(start_date, end_date) try: fut = asyncio.wait([async_func]) loop.run_until_complete(fut) except BaseExceptio... |
def easter(year): '''Calculate western easter''' # formula taken from http://aa.usno.navy.mil/faq/docs/easter.html c = trunc(year / 100) n = year - 19 * trunc(year / 19) k = trunc((c - 17) / 25) i = c - trunc(c / 4) - trunc((c - k) / 3) + (19 * n) + 15 i = i - 30 * trunc(i / 30) i = i - trunc(i |
/ 28) * (1 - trunc(i / 28) * trunc(29 / (i + 1)) * trunc((21 - n) / 11)) j = year + trunc(year / 4) + i + 2 - c + trunc(c / 4) j = j - 7 * trunc(j / 7) l = i - j month = 3 + trunc((l + 40) / 44) day = l + |
28 - 31 * trunc(month / 4) return year, int(month), int(day) |
def independence_day(year, observed=None): '''July 4th''' day = 4 if observed: if calendar.weekday(year, JUL, 4) == SAT: day = 3 if calendar.weekday(year, JUL, 4) == SUN: day = 5 return (year, JUL, day) |
def columbus_day(year, country='usa'): '''in USA: 2nd Monday in Oct Elsewhere: Oct 12''' if country == 'usa': return nth_day_of_month(2, MON, OCT, year) else: return (year, OCT, 12) |
def thanksgiving(year, country='usa'): '''USA: last Thurs. of November, Canada: 2nd Mon. of October''' if country == 'usa': if year in [1940, 1941]: return nth_day_of_month(3, THU, NOV, year) elif year == 1939: return nth_day_of_month(4, THU, NOV, year) else: return nth_day_of_month(0, THU, NOV, year) if country == 'ca... |
def linefit(x, y, weights=None): """ Parameters ---------- y: 1D numpy array The data to be fitted x: 1D numpy array The x values of the y array. x and y must have the same shape. weights: 1D numpy array, must have the same shape as x and y weight values Examples -------- >>> import numpy as N >>> from numpy.core impor... |
= N.array([-5, -4 ,-3 ,-2 ,-1, 0, 1, 2, 3, 4, 5]) >>> y = N.array([1, 5, 4, 7, 10, 8, 9, 13, 14, 13, 18]) >>> around(linefit(x,y), decimals=5) array([9.27273, 1.43636]) >>> x = N.array([1.3,1.3,2.0,2.0,2.7,3.3,3.3,3.7,3.7,4.,4.,4.,4.7,4.7,5.,5.3,5.3,5.3,5.7,6.,6.,6.3,6.7]) >>> y = N.array([2.3,1.8,2.8,1.5,2.2,3.8,1.8,3... |
if weights is None: for i in N.arange(n): w[i,i] = 1 else: if len(weights) != n: print("Error: Weights must have the same size as X and Y.\n") return for i in N.arange(n): w[i,i] = weights[i] x = x.astype(N.float) y = y.astype(N.float) # take the weighted avg for calculatiing the covarince Xavg = N.sum(N.dot(w,x)) / N.... |
Xavg xmt = N.transpose(xm) ym = y - Yavg b1 = N.dot(xmt,N.dot(w,ym)) / N.dot(xmt ,N.dot(w,xm)) b0 = Yavg - b1 * Xavg return b0, b1 |
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Analysing ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.COMPLETE) if measurement is not None: if measurement.inflate(): data... |
self._jsonify(data.peakSpectrum('sum')) } } for name, data in measurement.data.items() } return data, 200 else: return None, 404 else: return None, 404 |
def _applyTargetState(targetState, md, httpclient): """ compares the current device state against the targetStateProvider and issues updates as necessary to ensure the device is at that state. :param md: :param targetState: the target state. :param httpclient: the http client :return: """ anyUpdate = False if md['fs'] ... |
md['name']) anyUpdate = True if md['samplesPerBatch'] != targetState.samplesPerBatch: logger.info("Updating samplesPerBatch from " + str(md['samplesPerBatch']) + " to " + str( targetState.samplesPerBatch) + " for " + md['name']) anyUpdate = True if md['gyroEnabled'] != targetState.gyroEnabled: logger.info("Updating gyr... |
" + str(md['gyroSens']) + " to " + str(targetState.gyroSens) + " for " + md[ 'name']) anyUpdate = True if md['accelerometerEnabled'] != targetState.accelerometerEnabled: logger.info("Updating accelerometerEnabled from " + str(md['accelerometerEnabled']) + " to " + str( targetState.accelerometerEnabled) + " for " + md['... |
for " + md['name']) anyUpdate = True if anyUpdate: payload = marshal(targetState, targetStateFields) logger.info("Applying target state change " + md['name'] + " - " + str(payload)) if RecordingDeviceStatus.INITIALISED.name == md.get('status'): try: httpclient.patch(md['serviceURL'], json=payload) except Exception as e... |
target state, we continue") |
def updateDeviceState(self, device): """ Updates the target state on the specified device. :param targetState: the target state to reach. :param device: the device to update. :return: """ # this is only threadsafe because the targetstate is effectively immutable, if it becomes mutable in future then # funkiness may res... |
def updateTargetState(self, newState): """ Updates the system target state and propagates that to all devices. :param newState: :return: """ self._targetStateProvider.state = loadTargetState(newState, self._targetStateProvider.state) for device in self.deviceController.getDevices(): self.updateDeviceState(device.payloa... |
def convert(input, width=132, output=None, keep=False): """Input ASCII trailer file "input" will be read. The contents will then be written out to a FITS file in the same format as used by 'stwfits' from IRAF. Parameters =========== input : str Filename of input ASCII trailer file width : int Number of characters wide ... |
Filename to use for writing out converted FITS trailer file If None, input filename will be converted from *.tra -> *_trl.fits [Default: None] keep : bool Specifies whether or not to keep any previously written FITS files [Default: False] """ # open input trailer file trl = open(input) # process all lines lines = np.ar... |
close ASCII trailer file now that we have processed all the lines trl.close() if output is None: # create fits file rootname,suffix = os.path.splitext(input) s = suffix[1:].replace('ra','rl') fitsname = "{}_{}{}fits".format(rootname,s,os.path.extsep) else: fitsname = output full_name = os.path.abspath(os.path.join(os.p... |
line_fmt = "{}A".format(width) tbhdu = fits.BinTableHDU.from_columns([fits.Column(name='TEXT_FILE',format=line_fmt,array=lines)]) tbhdu.writeto(fitsname) print("Created output FITS filename for trailer:{} {}".format(os.linesep,full_name)) os.remove(input) |
def flatten_errors(cfg, res, levels=None, results=None): """ An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. (This is a recursive funct... |
of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) If ``validate`` was called with ``preserve_errors=False`` (the default) then ``result`` will always be ``False``. *list of sections* is a flattened list of sections that the key was found in. If the section was missing (or a ... |
key will be ``None``. If the value (or section) was missing then ``result`` will be ``False``. If ``validate`` was called with ``preserve_errors=True`` and a value was present, but failed the check, then ``result`` will be the exception object returned. You can use this as a string that describes the failure. For examp... |
None: # first time called levels = [] results = [] if res == True: return results if res == False or isinstance(res, Exception): results.append((levels[:], None, res)) if levels: levels.pop() return results for (key, val) in res.items(): if val == True: continue if isinstance(cfg.get(key), dict): # Go down one level le... |
level if levels: levels.pop() # return results |
def get_extra_values(conf, _prepend=()): """ Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a list of tuples where each tuple represents either an extra section, or an extra value. The tuples contain two values, a tuple representing the section the value ... |
section the first member will be an empty tuple. For values in the 'foo' section the first member will be ``('foo',)``. For members in the 'bar' subsection of the 'foo' section the first member will be ``('foo', 'bar')``. NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't been validated it will ... |
name in conf.extra_values]) for name in conf.sections: if name not in conf.extra_values: out.extend(get_extra_values(conf[name], _prepend + (name,))) return out |
def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ # switch off interpolation before we try and fetch anything ! save_interp = self.section.main.interpolation self.section.main.interpolation = False # Start at section that... |
val is not None and not isinstance(val, Section): break # try "DEFAULT" next val = current_section.get('DEFAULT', {}).get(key) if val is not None and not isinstance(val, Section): break # move up to parent and try again # top-level's parent is itself if current_section.parent is current_section: # reached top level, ti... |
self.section.main.interpolation = save_interp if val is None: raise MissingInterpolationOption(key) return val, current_section |
def pop(self, key, default=MISSING): """ 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' """ try: val = self[key] except KeyError: if default is MISSING: raise val = default else: del self[key] return val |
def popitem(self): """Pops the first (key,val)""" sequence = (self.scalars + self.sections) if not sequence: raise KeyError(": 'popitem(): dictionary is empty'") key = sequence[0] val = self[key] del self[key] return key, val |
def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = None self.defaults =... |
def items(self): """D.items() -> list of D's (key, value) pairs, as 2-tuples""" return list(zip((self.scalars + self.sections), list(self.values()))) |
def dict(self): """ Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() # doctest: +SKIP >>> n == a # doctest: +SKIP 1 >>> n is a # doctest: +SKIP 0 """ newdict = {} for entry in self: ... |
isinstance(this_entry, Section): this_entry = this_entry.dict() elif isinstance(this_entry, list): # create a copy rather than a reference this_entry = list(this_entry) elif isinstance(this_entry, tuple): # create a copy rather than a reference this_entry = tuple(this_entry) newdict[entry] = this_entry return newdict |
def merge(self, indict): """ A recursive update - useful for merging config files. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ... [section1] ... option1 = False ... # end of file'''.splitlines() >>> c1 = ConfigObj(... |
'False', 'subsection': {'more_options': 'False'}}}) """ for key, val in list(indict.items()): if (key in self and isinstance(self[key], dict) and isinstance(val, dict)): self[key].merge(val) else: self[key] = val |
def rename(self, oldkey, newkey): """ Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments. """ if oldkey in self.scalars: the_list = self.scalars elif oldkey in self.sections:... |
val = self[oldkey] dict.__delitem__(self, oldkey) dict.__setitem__(self, newkey, val) the_list.remove(oldkey) the_list.insert(pos, newkey) comm = self.comments[oldkey] inline_comment = self.inline_comments[oldkey] del self.comments[oldkey] del self.inline_comments[oldkey] self.comments[newkey] = comm self.inline_commen... |
def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs): """ Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False... |
Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ... |
to be discarded. See the encode and decode methods for examples, including functions. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ... |
'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIEN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.