code stringlengths 1 18.2k |
|---|
leap_suppression_days * 4 + 1 over_cycle_yrs = 4000. over_cycle_days = 1460969 # intercal_cycle_days * 10 - 1 elif method in (128, 'madler'): # Year 15 is a leap year, then year 20 and multiples of 4, not multiples of 128 y5 = 16 J = J - DAYS_IN_YEAR * 16 - 4 leap_suppression_yrs = 128 leap_suppression_days = 46751 # 3... |
else: raise ValueError("Unknown leap year method. Try: continuous, romme, madler or equinox") if over_cycle_days: y0 = trunc(J / over_cycle_days) * over_cycle_yrs J = J % over_cycle_days if intercal_cycle_days: y1 = trunc(J / intercal_cycle_days) * intercal_cycle_yrs J = J % intercal_cycle_days if leap_suppression_days... |
LEAP_CYCLE_DAYS == LEAP_CYCLE_DAYS - 1: J = 1460 else: J = J % LEAP_CYCLE_DAYS # 0 <= J <= 1460 # J needs to be 365 here on leap days ONLY y4 = trunc(J / DAYS_IN_YEAR) if J == DAYS_IN_YEAR * 4: y4 = y4 - 1 J = 365.0 else: J = J % DAYS_IN_YEAR year = y0 + y1 + y2 + |
y3 + y4 + y5 month = trunc(J / 30.) J = J - month * 30 return year + 1, month + 1, trunc(J) + 1 |
def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour) |
def to_jd(year, month, day): '''Obtain Julian day for Indian Civil date''' gyear = year + 78 leap = isleap(gyear) # // Is this a leap year ? # 22 - leap = 21 if leap, 22 non-leap start = gregorian.to_jd(gyear, 3, 22 - leap) if leap: Caitra = 31 else: Caitra = 30 if month == 1: jd = start + (day - 1) |
else: jd = start + Caitra m = month - 2 m = min(m, 5) jd += m * 31 if month >= 8: m = month - 7 jd += m * 30 jd += day - 1 return jd |
def from_jd(jd): '''Calculate Indian Civil date from Julian day Offset in years from Saka era to Gregorian epoch''' start = 80 # Day offset between Saka and Gregorian jd = trunc(jd) + 0.5 greg = gregorian.from_jd(jd) # Gregorian date for Julian day leap = isleap(greg[0]) # Is this a leap year? # Tentative year in Saka ... |
at start of Gregorian year greg0 = gregorian.to_jd(greg[0], 1, 1) yday = jd - greg0 # Day number (0 based) in Gregorian year if leap: Caitra = 31 # Days in Caitra this year else: Caitra = 30 if yday < start: # Day is at the end of the preceding Saka year year -= 1 yday += Caitra + (31 * 5) + |
(30 * 3) + 10 + start yday -= start if yday < Caitra: month = 1 day = yday + 1 else: mday = yday - Caitra if (mday < (31 * 5)): month = trunc(mday / 31) + 2 day = (mday % 31) + 1 else: mday -= 31 * 5 month = trunc(mday / 30) + 7 day = (mday |
% 30) + 1 return (year, month, int(day)) |
def format_stack(skip=0, length=6, _sep=os.path.sep): """ Returns a one-line string with the current callstack. """ return ' < '.join("%s:%s:%s" % ( '/'.join(f.f_code.co_filename.split(_sep)[-2:]), f.f_lineno, f.f_code.co_name ) for f in islice(frame_iterator(sys._getframe(1 + skip)), length)) |
def log(func=None, stacktrace=10, stacktrace_align=60, attributes=(), module=True, call=True, call_args=True, call_args_repr=repr, result=True, exception=True, exception_repr=repr, result_repr=strip_non_ascii, use_logging='CRITICAL', print_to=None): """ Decorates `func` to have logging. Args func (function): Function t... |
case the function is a instance method. module (bool): Show the module. call (bool): If ``True``, then show calls. If ``False`` only show the call details on exceptions (if ``exception`` is enabled) (default: ``True``) call_args (bool): If ``True``, then show call arguments. (default: ``True``) call_args_repr (bool): F... |
``True``) exception (bool): If ``True``, then show exceptions. (default: ``True``) exception_repr (function): Function to convert an exception to a string. (default: ``repr``) result_repr (function): Function to convert the result object to a string. (default: ``strip_non_ascii`` - like ``str`` but nonascii characters ... |
case you don't want to use logging module. (default: ``None`` - printing is disabled) Returns: A decorator or a wrapper. Example:: >>> @log(print_to=sys.stdout) ... def a(weird=False): ... if weird: ... raise RuntimeError('BOOM!') >>> a() a() <<< ... a => None >>> try: ... a(weird=True) ... except Exception: ... pass #... |
to logs just errors, or just results, example:: >>> import aspectlib >>> with aspectlib.weave(float, log(call=False, result=False, print_to=sys.stdout)): ... try: ... float('invalid') ... except Exception as e: ... pass # naughty code! float('invalid') <<< ... float ~ raised ValueError(...float...invalid...) This makes... |
naughty code! float('invalid') <<< ... float ~ raised ValueError(...float...invalid...) .. versionchanged:: 0.5.0 Renamed `arguments` to `call_args`. Renamed `arguments_repr` to `call_args_repr`. Added `call` option. """ loglevel = use_logging and ( logging._levelNames if hasattr(logging, '_levelNames') else logging._n... |
exc, exc_info=True) class __logged__(Aspect): __slots__ = 'cutpoint_function', 'final_function', 'binding', '__name__', '__weakref__' bind = False def __init__(self, cutpoint_function, binding=None): mimic(self, cutpoint_function) self.cutpoint_function = cutpoint_function self.final_function = super(__logged__, self).... |
= instance.__class__ else: instance_type = type(instance) info = [] for key in attributes: if key.endswith('()'): callarg = key = key.rstrip('()') else: callarg = False val = getattr(instance, key, _missing) if val is not _missing and key != name: info.append(' %s=%s' % ( key, call_args_repr(val() if callarg else val) ... |
''.join(info), name ) else: sig = buf = name if call_args: buf += '(%s%s)' % ( ', '.join(repr(i) for i in (args if call_args is True else args[:call_args])), ((', ' if args else '') + ', '.join('%s=%r' % i for i in kwargs.items())) if kwargs and call_args is True else '', ) if stacktrace: buf = ("%%-%ds <<< %%s" % stac... |
length=stacktrace)) if call: dump(buf) try: res = yield except Exception as exc: if exception: if not call: dump(buf) dump('%s ~ raised %s' % (sig, exception_repr(exc))) raise if result: dump('%s => %s' % (sig, result_repr(res))) if func: return __logged__(func) else: return __logged__ |
def wireHandlers(cfg): """ If the device is configured to run against a remote server, ping that device on a scheduled basis with our current state. :param cfg: the config object. :return: """ logger = logging.getLogger('recorder') httpPoster = cfg.handlers.get('remote') csvLogger = cfg.handlers.get('local') activeHand... |
else: logger.info("App is running in standalone mode, logging data to local filesystem") activeHandler = csvLogger else: logger.info("App is running against remote server, logging data to " + httpPoster.target) activeHandler = httpPoster heartbeater.serverURL = httpPoster.target heartbeater.ping() if activeHandler is n... |
def main(args=None): """ The main routine. """ cfg.configureLogger() wireHandlers(cfg) # get config from a flask standard place not our config yml app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort()) |
def get(self, deviceId): """ lists all known active measurements. """ measurementsByName = self.measurements.get(deviceId) if measurementsByName is None: return [] else: return list(measurementsByName.values()) |
def get(self, deviceId, measurementId): """ details the specific measurement. """ record = self.measurements.get(deviceId) if record is not None: return record.get(measurementId) return None |
def put(self, deviceId, measurementId): """ Schedules a new measurement at the specified time. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was scheduled, 400 if the device is busy, 500 if the device is bad. """ record = self.measurements.get(deviceId) if... |
x in measurement.statuses if x.name is 'COMPLETE' or x.name is 'FAILED']) > 0: logger.info('Overwriting existing completed measurement ' + x.name) measurement = None if measurement is None: logger.info('Initiating measurement ' + measurementId) measurement = ScheduledMeasurement(measurementId, self.recordingDevices.get... |
enable the measurement to be cleaned up by the ScheduledMeasurement record[measurementId] = measurement return measurement, 200 else: return measurement, 400 else: return 'unknown device ' + deviceId, 400 |
def delete(self, deviceId, measurementId): """ Deletes a stored measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if it was deleted, 400 if no such measurement (or device). """ record = self.measurements.get(deviceId) if record is not None: popped = rec... |
def get(self, deviceId, measurementId): """ signals a stop for the given measurement. :param deviceId: the device to measure. :param measurementId: the name of the measurement. :return: 200 if stop is signalled, 400 if it doesn't exist or is not running. """ record = self.measurements.get(deviceId) if record is not Non... |
400 return '', 400 |
def schedule(self, duration, at=None, delay=None, callback=None): """ schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callback: a callback. :return: nothing. """ delay = se... |
+ 's in ' + str(delay) + 's') self.statuses.append({'name': ScheduledMeasurementStatus.SCHEDULED.name, 'time': datetime.utcnow()}) threading.Timer(delay, self.execute, [duration]).start() |
def execute(self, duration): """ Executes the measurement, recording the event status. :param duration: the time to run for. :return: nothing. """ self.statuses.append({'name': ScheduledMeasurementStatus.RUNNING.name, 'time': datetime.utcnow()}) try: self.recording = True self.device.start(self.name, durationInSeconds=... |
point by refactoring the way measurements are stored if self.callback is not None: self.callback() |
def calculateDelay(self, at, delay): """ Creates the delay from now til the specified start time, uses "at" if available. :param at: the start time in %a %b %d %H:%M:%S %Y format. :param delay: the delay from now til start. :return: the delay. """ if at is not None: return max((datetime.strptime(at, DATETIME_FORMAT) - ... |
def launch_and_wait(mp_proc_list, pool_size): """ Given a list of multiprocessing.Process objects which have not yet been started, this function launches them and blocks until the last finishes. This makes sure that only <pool_size> processes are ever working at any one time (this number does not include the main proce... |
analogous to multiprocessing.Pool with the exceptions that: 1 - The caller will get to use the multiprocessing.Process model of using shared memory (inheritance) to pass arg data to the child, 2 - maxtasksperchild is always 1, 3 - no function return value is kept/tranferred (not yet implemented) """ # Sanity check if l... |
watching procs = [] for p in mp_proc_list: procs.append(WatchedProcess(p)) # Launch all of them, but only so pool_size are running at any time keep_going = True while (keep_going): # Before we start any more, find out how many are running. First go # through the list of those started and see if alive. Update state. for... |
been started if not p.process.is_alive(): p.state = 2 # process has finished or been terminated assert p.process.exitcode is not None, \ "Process is not alive but has no exitcode? "+ \ str(p.process) # now figure num_running num_running = len([p for p in procs if p.state == 1]) # Start some. Only as many as pool_size s... |
num_to_start = len([p for p in procs if p.state == 0]) if num_to_start < 1: # all have been started, can finally leave loop and go wait break if num_avail_cpus > 0 and num_to_start > 0: num_to_start_now = min(num_avail_cpus, num_to_start) started_now = 0 for p in procs: if started_now < num_to_start_now and p.state == ... |
# else: otherwise, all cpus are in use, just wait ... # sleep to tame loop activity, but also must sleep a bit after each # start call so that the call to is_alive() woorks correctly time.sleep(1) # Out of the launching loop, can now wait on all procs left. for p in procs: p.join_process() # Check all exit codes before... |
in procs: if 0 != p.process.exitcode: raise RuntimeError("Problem during: "+str(p.process.name)+ \ ', exitcode: '+str(p.process.exitcode)+'. Check log.') |
def best_tile_layout(pool_size): """ Determine and return the best layout of "tiles" for fastest overall parallel processing of a rectangular image broken up into N smaller equally-sized rectangular tiles, given as input the number of processes/chunks which can be run/worked at the same time (pool_size). This attempts ... |
over (and thus not really taking advantage of pooling). Since we can vary the size of the rectangles, there is not much (any?) benefit to pooling. Returns a tuple of ( <num tiles in X dir>, <num in Y direction> ) This assumes the image in question is relatively close to square, and so the returned tuple attempts to giv... |
as squarishly-blocked as possible, except in cases where speed would be sacrificed. EXAMPLES: For pool_size of 4, the best result is 2x2. For pool_size of 6, the best result is 2x3. For pool_size of 5, a result of 1x5 is better than a result of 2x2 (which would leave one core unused), and 1x5 is also better than a resu... |
require one core to work twice while all others wait). For higher, odd pool_size values (say 39), it is deemed best to sacrifice a few unused cores to satisfy our other constraints, and thus the result of 6x6 is best (giving 36 tiles and 3 unused cores). """ # Easy answer sanity-checks if pool_size < 2: return (1, 1) #... |
mapping of hard-coded results. While we agree # that many of these are unlikely pool_size values, they are easy # to accomodate. mapping = { 0:(1,1), 1:(1,1), 2:(1,2), 3:(1,3), 4:(2,2), 5:(1,5), 6:(2,3), 7:(2,3), 8:(2,4), 9:(3,3), 10:(2,5), 11:(2,5), 14:(2,7), 18:(3,6), 19:(3,6), 28:(4,7), 29:(4,7), 32:(4,8), 33:(4,8),... |
(for the sake of # simplicity), go with it. We *could* get much fancier here... # Use floor-rounding (not ceil) so that the total number of resulting # tiles is <= pool_size. xnum = int(math.sqrt(pool_size)) ynum = int((1.*pool_size)/xnum) return (xnum, ynum) |
def _accept(self): """ Work loop runs forever (or until running is False) :return: """ logger.warning("Reactor " + self._name + " is starting") while self.running: try: self._completeTask() except: logger.exception("Unexpected exception during request processing") logger.warning("Reactor " + self._name + " is terminati... |
def offer(self, requestType, *args): """ public interface to the reactor. :param requestType: :param args: :return: """ if self._funcsByRequest.get(requestType) is not None: self._workQueue.put((requestType, list(*args))) else: logger.error("Ignoring unknown request on reactor " + self._name + " " + requestType) |
def clicked(self): """ Called when this button is clicked. Execute code from .cfgspc """ try: from . import teal except: teal = None try: # start drilling down into the tpo to get the code tealGui = self._mainGuiObj tealGui.showStatus('Clicked "'+self.getButtonLabel()+'"', keep=1) pscope = self.paramInfo.scope pname = ... |
action to perform", "Action Button Error") return for exname in tup: if '_RULES_' in tpo and exname in tpo['_RULES_'].configspec: ruleSig = tpo['_RULES_'].configspec[exname] chkArgsDict = vtor_checks.sigStrToKwArgsDict(ruleSig) code = chkArgsDict.get('code') # a string or None # now go ahead and execute it teal.execEmb... |
tealGui: if teal: teal.popUpErr(tealGui.top, msg, "Action Button Error") tealGui.debug(msgFull) else: if teal: teal.popUpErr(None, msg, "Action Button Error") print(msgFull) |
def ndarr2str(arr, encoding='ascii'): """ This is used to ensure that the return value of arr.tostring() is actually a string. This will prevent lots of if-checks in calling code. As of numpy v1.6.1 (in Python 3.2.3), the tostring() function still returns type 'bytes', not 'str' as it advertises. """ # be fast, don't c... |
# call will fail anyway if not retval = arr.tostring() # would rather check "if isinstance(retval, bytes)", but support 2.5. # could rm the if PY3K check, but it makes this faster on 2.x. if PY3K and not isinstance(retval, str): return retval.decode(encoding) else: # is str return retval |
def ndarr2bytes(arr, encoding='ascii'): """ This is used to ensure that the return value of arr.tostring() is actually a *bytes* array in PY3K. See notes in ndarr2str above. Even though we consider it a bug that numpy's tostring() function returns a bytes array in PY3K, there are actually many instances where that is w... |
in those instances to ensure that when/if this numpy "bug" is "fixed", that our calling code still gets bytes where it needs/expects them. """ # be fast, don't check - just assume 'arr' is a numpy array - the tostring # call will fail anyway if not retval = arr.tostring() # would rather check "if not isinstance(retval,... |
isinstance(retval, str): # Take note if this ever gets used. If this ever occurs, it # is likely wildly inefficient since numpy.tostring() is now # returning unicode and numpy surely has a tobytes() func by now. # If so, add a code path to call its tobytes() func at our start. return retval.encode(encoding) else: # is ... |
def tobytes(s, encoding='ascii'): """ Convert string s to the 'bytes' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, this is technically the same as the str type in terms of the character data in memory. """ # NOTE: after we abandon 2.5, we might simply... |
we abandon all 2.*, del this and prepend byte strings with 'b' if PY3K: if isinstance(s, bytes): return s else: return s.encode(encoding) else: # for py2.6 on (before 3.0), bytes is same as str; 2.5 has no bytes # but handle if unicode is passed if isinstance(s, unicode): return s.encode(encoding) else: return s |
def tostr(s, encoding='ascii'): """ Convert string-like-thing s to the 'str' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. In Pythons before 3.0, str and bytes are the same type. In Python 3+, this may require a decoding step. """ if PY3K: if isinstance(s, str): # str == uni... |
is type bytes return s.decode(encoding) else: # for py2.6 on (before 3.0), bytes is same as str; 2.5 has no bytes # but handle if unicode is passed if isinstance(s, unicode): return s.encode(encoding) else: return s |
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep): """ Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function to sleep till next retry. Example:: >>> should_fail = lambda foo=[1,2,3]: foo an... |
>>> @retry ... def bad_func(): ... raise OSError('Tough luck!') ... >>> bad_func() Traceback (most recent call last): ... OSError: Tough luck! """ @Aspect(bind=True) def retry_aspect(cutpoint, *args, **kwargs): for count in range(retries + 1): try: if count and cleanup: cleanup(*args, **kwargs) yield break except excep... |
else: timeout = backoff(count) logger.exception("%s(%s, %s) raised exception %s. %s retries left. Sleeping %s secs.", cutpoint.__name__, args, kwargs, exc, retries - count, timeout) sleep(timeout) return retry_aspect if func is None else retry_aspect(func) |
def loadSignal(self, name, start=None, end=None): """ Loads the named entry from the upload cache as a signal. :param name: the name. :param start: the time to start from in HH:mm:ss.SSS format :param end: the time to end at in HH:mm:ss.SSS format. :return: the signal if the named upload exists. """ entry = self._getCa... |
start=start, end=end) else: return None |
def _getCacheEntry(self, name): """ :param name: the name of the cache entry. :return: the entry or none. """ return next((x for x in self._uploadCache if x['name'] == name), None) |
def _convertTmp(self, tmpCacheEntry): """ Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries. :param tmpCacheEntry: the cache entry. :return: """ from analyser.common.signal import loadSignalFromWav tmpCacheEntry['status'] = 'converting' logger.info("Loading " + tmpCacheEn... |
self._tmpCache.remove(tmpCacheEntry) self._conversionCache.append(tmpCacheEntry) srcFs = signal.fs completeSamples = signal.samples outputFileName = os.path.join(self._uploadDir, tmpCacheEntry['name']) if srcFs > 1024: self.writeOutput(outputFileName, completeSamples, srcFs, 1000) else: self.writeOutput(outputFileName,... |
def writeChunk(self, stream, filename, chunkIdx=None): """ Streams an uploaded chunk to a file. :param stream: the binary stream that contains the file. :param filename: the name of the file. :param chunkIdx: optional chunk index (for writing to a tmp dir) :return: no of bytes written or -1 if there was an error. """ i... |
None else filename + '.' + str(chunkIdx) outputDir = self._uploadDir if chunkIdx is None else self._tmpDir chunkFilePath = os.path.join(outputDir, outputFileName) if os.path.exists(chunkFilePath) and os.path.isfile(chunkFilePath): logger.error('Uploaded file already exists: ' + chunkFilePath) return -1 else: chunkFile ... |
def finalise(self, filename, totalChunks, status): """ Completes the upload which means converting to a single 1kHz sample rate file output file. :param filename: :param totalChunks: :param status: :return: """ def getChunkIdx(x): try: return int(x.suffix[1:]) except ValueError: return -1 def isChunkFile(x): return x.i... |
+ '.*') if isChunkFile(file)] # TODO if len(chunks) != totalChunks then error with open(asSingleFile, 'xb') as wfd: for f in [x[1] for x in sorted(chunks, key=lambda tup: tup[0])]: with open(f, 'rb') as fd: logger.info("cat " + f + " with " + asSingleFile) shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) self.cleanupChunk... |
def writeOutput(self, filename, samples, srcFs, targetFs): """ Resamples the signal to the targetFs and writes it to filename. :param filename: the filename. :param signal: the signal to resample. :param targetFs: the target fs. :return: None """ import librosa inputLength = samples.shape[-1] if srcFs != targetFs: if i... |
+ str(targetFs) + "Hz") outputSamples = samples targetFs = srcFs else: logger.info("Resampling " + str(inputLength) + " samples from " + str(srcFs) + "Hz to " + str(targetFs) + "Hz") outputSamples = librosa.resample(samples, srcFs, targetFs, res_type='kaiser_fast') else: outputSamples = samples logger.info("Writing out... |
def delete(self, name): """ Deletes the named entry. :param name: the entry. :return: the deleted entry. """ i, entry = next(((i, x) for i, x in enumerate(self._uploadCache) if x['name'] == name), (None, None)) if entry is not None: logger.info("Deleting " + name) os.remove(str(entry['path'])) del self._uploadCache[i] ... |
def eparOptionFactory(master, statusBar, param, defaultParam, doScroll, fieldWidths, plugIn=None, editedCallbackObj=None, helpCallbackObj=None, mainGuiObj=None, defaultsVerb="Default", bg=None, indent=False, flagging=False, flaggedColor=None): """Return EparOption item of appropriate type for the parameter param""" # A... |
not in the dictionary eparOption = _eparOptionDict.get(param.type, StringEparOption) # Create it eo = eparOption(master, statusBar, param, defaultParam, doScroll, fieldWidths, defaultsVerb, bg, indent=indent, helpCallbackObj=helpCallbackObj, mainGuiObj=mainGuiObj) eo.setEditedCallbackObj(editedCallbackObj) eo.setIsFlag... |
def extraBindingsForSelectableText(self): """ Collect in 1 place the bindings needed for watchTextSelection() """ # See notes in watchTextSelection self.entry.bind('<FocusIn>', self.watchTextSelection, "+") self.entry.bind('<ButtonRelease-1>', self.watchTextSelection, "+") self.entry.bind('<B1-Motion>', self.watchTextS... |
def focusOut(self, event=None): """Clear selection (if text is selected in this widget)""" # do nothing if this isn't a text-enabled widget if not self.isSelectable: return if self.entryCheck(event) is None: # Entry value is OK # Save the last selection so it can be restored if we # come right back to this widget. Then... |
try: if not entry.selection_present(): self.lastSelection = None else: self.lastSelection = (entry.index(SEL_FIRST), entry.index(SEL_LAST)) except AttributeError: pass if USING_X and sys.platform == 'darwin': pass # do nothing here - we need it left selected for cut/paste else: entry.selection_clear() else: return "bre... |
def watchTextSelection(self, event=None): """ Callback used to see if there is a new text selection. In certain cases we manually add the text to the clipboard (though on most platforms the correct behavior happens automatically). """ # Note that this isn't perfect - it is a key click behind when # selections are made ... |
be fixed with after(). if self.entry.selection_present(): # entry must be text entry type i1 = self.entry.index(SEL_FIRST) i2 = self.entry.index(SEL_LAST) if i1 >= 0 and i2 >= 0 and i2 > i1: sel = self.entry.get()[i1:i2] # Add to clipboard on platforms where necessary. print('selected: "'+sel+'"') |
def focusIn(self, event=None): """Select all text (if applicable) on taking focus""" try: # doScroll returns false if the call was ignored because the # last call also came from this widget. That avoids unwanted # scrolls and text selection when the focus moves in and out # of the window. if self.doScroll(event): self.... |
to what it was on the last FocusOut if self.lastSelection: self.entry.selection_range(*self.lastSelection) except AttributeError: pass |
def widgetEdited(self, event=None, val=None, action='entry', skipDups=True): """ A general method for firing any applicable triggers when a value has been set. This is meant to be easily callable from any part of this class (or its subclasses), so that it can be called as soon as need be (immed. on click?). This is sma... |
of any/all duplicate successive calls (unless skipDups is False). If val is None, it will use the GUI entry's current value via choice.get(). See teal.py for a description of action. """ # be as lightweight as possible if obj doesn't care about this stuff if not self._editedCallbackObj and not self._flagNonDefaultVals:... |
it is given if curVal is None: curVal = self.choice.get() # do any flagging self.flagThisPar(curVal, False) # see if this is a duplicate successive call for the same value if skipDups and curVal==self._lastWidgetEditedVal: return # pull trigger if not self._editedCallbackObj: return self._editedCallbackObj.edited(self.... |
def popupChoices(self, event=None): """Popup right-click menu of special parameter operations Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled instance attributes to determine which items are available. """ # don't bother if all items are disabled if NORMAL not in (self.browserEnabled, self.clearEnab... |
= "File Browser", state = self.browserEnabled, command = self.fileBrowser) self.menu.add_command(label = "Directory Browser", state = self.browserEnabled, command = self.dirBrowser) # Handle file and directory in the same function (filedlg) else: self.menu.add_command(label = "File/Directory Browser", state = self.brow... |
self.helpEnabled, command = self.helpOnParam) # Get the current y-coordinate of the Entry ycoord = self.entry.winfo_rooty() # Get the current x-coordinate of the cursor xcoord = self.entry.winfo_pointerx() - XSHIFT # Display the Menu as a popup as it is not associated with a Button self.menu.tk_popup(xcoord, ycoord) |
def fileBrowser(self): """Invoke a tkinter file dialog""" if capable.OF_TKFD_IN_EPAR: fname = askopenfilename(parent=self.entry, title="Select File") else: from . import filedlg self.fd = filedlg.PersistLoadFileDialog(self.entry, "Select File", "*") if self.fd.Show() != 1: self.fd.DialogCleanup() return fname = self.fd... |
def dirBrowser(self): """Invoke a tkinter directory dialog""" if capable.OF_TKFD_IN_EPAR: fname = askdirectory(parent=self.entry, title="Select Directory") else: raise NotImplementedError('Fix popupChoices() logic.') if not fname: return # canceled self.choice.set(fname) # don't select when we go back to widget to redu... |
def forceValue(self, newVal, noteEdited=False): """Force-set a parameter entry to the given value""" if newVal is None: newVal = "" self.choice.set(newVal) if noteEdited: self.widgetEdited(val=newVal, skipDups=False) |
def unlearnValue(self): """Unlearn a parameter value by setting it back to its default""" defaultValue = self.defaultParamInfo.get(field = "p_filename", native = 0, prompt = 0) self.choice.set(defaultValue) |
def setActiveState(self, active): """ Use this to enable or disable (grey out) a parameter. """ st = DISABLED if active: st = NORMAL self.entry.configure(state=st) self.inputLabel.configure(state=st) self.promptLabel.configure(state=st) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.