text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``"""
return self.logger.debug(self._indent(msg, indent), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info(self, msg, indent=0, **kwargs): """invoke ``self.info.debug``"""
return self.logger.info(self._indent(msg, indent), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def warning(self, msg, indent=0, **kwargs): """invoke ``self.logger.warning``"""
return self.logger.warning(self._indent(msg, indent), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``"""
return self.logger.error(self._indent(msg, indent), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def critical(self, msg, indent=0, **kwargs): """invoke ``self.logger.critical``"""
return self.logger.critical(self._indent(msg, indent), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self, msg, indent=0, style="", **kwargs): """ Print message to console, indent format may apply. """
if self.enable_verbose: new_msg = self.MessageTemplate.with_style.format( indent=self.tab * indent, style=style, msg=msg, ) print(new_msg, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_all_handler(self): """ Unlink the file handler association. """
for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) self._handler_cache.append(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recover_all_handler(self): """ Relink the file handler association you just removed. """
for handler in self._handler_cache: self.logger.addHandler(handler) self._handler_cache = list()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """
ltfh = FileHandler(fname) self._log.addHandler(ltfh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_dir_rec(path: Path): """ Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path """
if not path.exists() or not path.is_dir(): return for sub in path.iterdir(): if sub.is_dir(): delete_dir_rec(sub) else: sub.unlink() path.rmdir()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dir_rec(path: Path): """ Create a folder recursive. :param path: path :type path: ~pathlib.Path """
if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: prot...
protime = Timestamp() protime.FromDatetime(time) return protime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: p...
for trigger, entry_point in plugins.items(): try: plugin_class = entry_point.load() version = str(plugin_class._info.version) print( f"{trigger} (ok)\n" f" {version}" ) except Exception: print( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2): """ Determines whether two windows overlap """
return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and yl2 < yl1+ny1 and yl2+ny2 > yl1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup...
if not backup: fname = filedialog.asksaveasfilename( defaultextension='.json', filetypes=[('json files', '.json'), ], initialdir=g.cpars['app_directory'] ) else: fname = os.path.join(os.path.expanduser('~/.hdriver'), 'app.json') if not fname:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The curr...
g.clog.debug('Entering postJSON') # encode data as json json_data = json.dumps(data).encode('utf-8') # Send the xml to the server url = urllib.parse.urljoin(g.cpars['hipercam_server'], g.SERVER_POST_PATH) g.clog.debug('Server URL = ' + url) opener = urllib.request.build_opener() g.cl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createJSON(g, full=True): """ Create JSON compatible dictionary from current settings Parameters g : hcam_drivers.globals.Container Container with globals ""...
data = dict() if 'gps_attached' not in g.cpars: data['gps_attached'] = 1 else: data['gps_attached'] = 1 if g.cpars['gps_attached'] else 0 data['appdata'] = g.ipars.dumpJSON() data['user'] = g.rpars.dumpJSON() if full: data['hardware'] = g.ccd_hw.dumpJSON() data['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Co...
if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers are not active') return False run_number = getRunNumber(g) tcs_table = g.info.tcs_table g.clog.info('Adding TCS table data to run{:04d}.fits'.format(run_number)) url = g.cpars['hipercam_server'] + 'addhdu' t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execCommand(g, command, timeout=10): """ Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container obje...
if not g.cpars['hcam_server_on']: g.clog.warn('execCommand: servers are not active') return False try: url = g.cpars['hipercam_server'] + command g.clog.info('execCommand, command = "' + command + '"') response = urllib.request.urlopen(url, timeout=timeout) rs =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isRunActive(g): """ Polls the data server to see if a run is active """
if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: raise DriverError('isRunActive error: ' + str(rs.err)) if rs.state == 'idl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """
if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=False) try: msg = rs.msg excep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getRunNumber(g): """ Polls the data server to find the current run number. Throws exceptions if it can't determine it. """
if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if rs.ok: return rs.run else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkSimbad(g, target, maxobj=5, timeout=5): """ Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or ra...
url = 'http://simbad.u-strasbg.fr/simbad/sim-script' q = 'set limit ' + str(maxobj) + \ '\nformat object form1 "Target: %IDLIST(1) | %COO(A D;ICRS)"\nquery ' \ + target query = urllib.parse.urlencode({'submit': 'submit script', 'script': q}) resp = urllib.request.urlopen(url, query.enco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Version of run that traps Exceptions and stores them in the fifo """
try: threading.Thread.run(self) except Exception: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0][:-1] tback = (self.name + ' Traceback (most recent call last):\n' + ''.join(traceback.format_tb(tb))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_root(w): """ Simple method to access root for a widget """
next_level = w while next_level.master: next_level = next_level.master return next_level
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_from_plugin(plugin: APlugin): """ Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. g...
# get last update date plugin.log.info('Get last update') plugin.update_last_update() # load old save state save_state = plugin.load_save_state() if plugin.last_update <= save_state.last_update: plugin.log.info('No update. Nothing to do.') return # get download links plu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(plugin_name: str, options: List[str] = None) -> PluginState: """ Run a plugin so use the download routine and clean up after. :param plugin_name: name of ...
if options is None: options = [] if plugin_name not in dynamic_data.AVAIL_PLUGINS: msg = 'Plugin ' + plugin_name + ' was not found.' logging.error(msg) print(msg) return PluginState.NOT_FOUND try: plugin_class = dynamic_data.AVAIL_PLUGINS[plugin_name].load(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """
with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYPI_JSON_URL).data.decode('utf-8') releases = json.loads(pypi_json).get('releases', []) online_version = Version('0.0.0') for release in releases: cur_ve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setupNodding(self): """ Setup Nodding for GTC """
g = get_root(self).globals if not self.nod(): # re-enable clear mode box if not drift if not self.isDrift(): self.clear.enable() # clear existing nod pattern self.nodPattern = {} self.check() return # Do ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freeze(self): """ Freeze all settings so they cannot be altered """
self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.disable() self.wframe.disable(everything=True) self.nmult.disable() self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unfreeze(self): """ Reverse of freeze """
self.app.enable() self.clear.enable() self.nod.enable() self.led.enable() self.dummy.enable() self.readSpeed.enable() self.expose.enable() self.number.enable() self.wframe.enable() self.nmult.enable() self.frozen = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getRtplotWins(self): """" Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are no...
try: if self.isFF(): return 'fullframe\r\n' elif self.isDrift(): xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() nwin = 2*self.wframe.npair.value() ret = str(xbin) + ' ' + str(ybin) + ' ' + s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadJSON(self, json_string): """ Sets the values of the run parameters given an JSON string """
g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: widget.set(val) setField(self.prog_ob.obid, 'OB') setField(self.target, 'target') setField(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freeze(self): """ Freeze all settings so that they can't be altered """
self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') self.comment.configure(state='disable')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unfreeze(self): """ Unfreeze all settings so that they can be altered """
g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob.configure(state='normal') self.pi.configure(state='normal') self.target.enab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkUpdate(self, *args): """ Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recur...
g = get_root(self).globals if not self.check(): g.clog.warn('Current observing parameters are not valid.') return False if not g.ipars.check(): g.clog.warn('Current instrument parameters are not valid.') return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, *args): """ Updates values. You should run a check on the instrument and target parameters before calling this. """
g = get_root(self).globals expTime, deadTime, cycleTime, dutyCycle, frameRate = g.ipars.timing() total, peak, peakSat, peakWarn, ston, ston3 = \ self.counts(expTime, cycleTime) if cycleTime < 0.01: self.cadence.config(text='{0:7.5f} s'.format(cycleTime)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable(self): """ Disable the button, if in non-expert mode. """
w.ActButton.disable(self) g = get_root(self).globals if self._expert: self.config(bg=g.COL['start']) else: self.config(bg=g.COL['startD'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setExpert(self): """ Turns on 'expert' status whereby the button is always enabled, regardless of its activity status. """
w.ActButton.setExpert(self) g = get_root(self).globals self.config(bg=g.COL['start'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Carries out the action associated with the Load button """
g = get_root(self).globals fname = filedialog.askopenfilename( defaultextension='.json', filetypes=[('json files', '.json'), ('fits files', '.fits')], initialdir=g.cpars['app_directory']) if not fname: g.clog.warn('Aborted load from disk') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Carries out the action associated with the Save button """
g = get_root(self).globals g.clog.info('\nSaving current application to disk') # check instrument parameters if not g.ipars.check(): g.clog.warn('Invalid instrument parameters; save failed.') return False # check run parameters rok, msg = g.rpar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Carries out the action associated with the Unfreeze button """
g = get_root(self).globals g.ipars.unfreeze() g.rpars.unfreeze() g.observe.load.enable() self.disable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qualname(self) -> str: """ Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name. """
if self.module: return self.module + '.' + self.name return self.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs) -> Any: """ Returns the value for ``self.name`` given the class-under-construction's...
value = self.default if self.inherit and base_classes_meta is not None: value = getattr(base_classes_meta, self.name, value) if Meta is not None: value = getattr(Meta, self.name, value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_key_release_repeat(self, *dummy): """ Avoid repeated trigger of callback. When holding a key down, multiple key press and release events are fired in succ...
self.has_prev_key_release = self.after_idle(self.on_key_release, dummy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub(self, num): """ Subtracts num from the current value """
try: val = self.value() - num except: val = -num self.set(max(0, val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, num): """ Adds num to the current value, jumping up the next multiple of mfac if the result is not a multiple already """
try: val = self.value() + num except: val = num chunk = self.mfac.value() if val % chunk > 0: if num > 0: val = chunk*(val // chunk + 1) elif num < 0: val = chunk*(val // chunk) val = max(self._min...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, num): """ Sets current value to num """
if self.validate(num) is not None: self.index = self.allowed.index(num) IntegerEntry.set(self, num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_unbind(self): """ Unsets key bindings. """
self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self.unbind('<Control-Down>') self.unbind('<Double-Button-1>') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, value): """ This prevents setting any value more precise than 0.00001 """
try: # trap blank fields here if value: v = float(value) if (v != 0 and v < self.fmin) or v > self.fmax: return None if abs(round(100000*v)-100000*v) > 1.e-12: return None return value ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_min(self, fmin): """ Updates minimum value """
if round(100000*fmin) != 100000*fmin: raise DriverError('utils.widgets.Expose.set_min: ' + 'fmin must be a multiple of 0.00001') self.fmin = fmin self.set(self.fmin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable(self): """ Disable the button, if in non-expert mode; unset its activity flag come-what-may. """
if not self._expert: self.config(state='disable') self._active = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """
self._expert = False if self._active: self.enable() else: self.disable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, quantity): """ Adds an angle to the value """
newvalue = self._value + quantity self.set(newvalue.deg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub(self, quantity): """ Subtracts an angle from the value """
newvalue = self._value - quantity self.set(newvalue.deg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Carries out the action associated with Stop button """
g = get_root(self).globals g.clog.debug('Stop pressed') # Stop exposure meter # do this first, so timer doesn't also try to enable idle mode g.info.timer.stop() def stop_in_background(): try: self.stopping = True if execComma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self): """ Checks the status of the stop exposure command This is run in background and can take a few seconds """
g = get_root(self).globals if self.stopped_ok: # Exposure stopped OK; modify buttons self.disable() # try and write FITS table before enabling start button, otherwise # a new start will clear table try: insertFITSHDU(g) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modver(self, *args): """ Switches colour of verify button """
g = get_root(self).globals if self.ok(): tname = self.val.get() if tname in self.successes: # known to be in simbad self.verify.config(bg=g.COL['start']) elif tname in self.failures: # known not to be in simbad ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Carries out the action associated with Verify button """
tname = self.val.get() g = get_root(self).globals g.clog.info('Checking ' + tname + ' in simbad') try: ret = checkSimbad(g, tname) if len(ret) == 0: self.verify.config(bg=g.COL['stop']) g.clog.warn('No matches to "' + tname + '" fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def act(self): """ Power on action """
g = get_root(self).globals g.clog.debug('Power on pressed') if execCommand(g, 'online'): g.clog.info('ESO server online') g.cpars['eso_server_online'] = True if not isPoweredOn(g): success = execCommand(g, 'pon') if not succe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setExpertLevel(self): """ Modifies widget according to expertise level, which in this case is just matter of hiding or revealing the button to set CCD temps ...
g = get_root(self).globals level = g.cpars['expert_level'] if level == 0: if self.val.get() == 'CCD TECs': self.val.set('Observe') self._changed() self.tecs.grid_forget() else: self.tecs.grid(row=0, column=3, sticky=tk....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Starts the timer from zero """
self.startTime = time.time() self.configure(text='{0:<d} s'.format(0)) self.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumpJSON(self): """ Return dictionary of data for FITS headers. """
g = get_root(self).globals return dict( RA=self.ra['text'], DEC=self.dec['text'], tel=g.cpars['telins_name'], alt=self._getVal(self.alt), az=self._getVal(self.az), secz=self._getVal(self.airmass), pa=self._getVal(self.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_tcs_table(self): """ Periodically update a table of info from the TCS. Only works at GTC """
g = get_root(self).globals if not g.cpars['tcs_on'] or not g.cpars['telins_name'].lower() == 'gtc': self.after(60000, self.update_tcs_table) return try: tel_server = tcs.get_telescope_server() telpars = tel_server.getTelescopeParams() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_tcs(self): """ Periodically update TCS info. A long running process, so run in a thread and fill a queue """
g = get_root(self).globals if not g.cpars['tcs_on']: self.after(20000, self.update_tcs) return if g.cpars['telins_name'] == 'WHT': tcsfunc = tcs.getWhtTcs elif g.cpars['telins_name'] == 'GTC': tcsfunc = tcs.getGtcTcs else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_slidepos(self): """ Periodically update the slide position. Also farmed out to a thread to avoid hanging GUI main thread """
g = get_root(self).globals if not g.cpars['focal_plane_slide_on']: self.after(20000, self.update_slidepos) return def slide_threaded_update(): try: (pos_ms, pos_mm, pos_px), msg = g.fpslide.slide.return_position() self.slide_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame binned...
# needs some mods for ultracam ?? xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xsl, xsr, ys, nx, ny in self: if xbin > 1: xsl = xbin*((xsl-1)//xbin)+1 self.xsl[n].set(xsl) xsr = xbin*((xsr-1025)//xbin)+1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable(self, everything=False): """ Disable all but possibly not binning, which is needed for FF apps Parameters --------- everything : bool disable binning...
self.freeze() if not everything: self.xbin.enable() self.ybin.enable() self.frozen = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable(self): """ Enables WinPair settings """
npair = self.npair.value() for label, xsl, xsr, ys, nx, ny in \ zip(self.label[:npair], self.xsl[:npair], self.xsr[:npair], self.ys[:npair], self.nx[:npair], self.ny[:npair]): label.config(state='normal') xsl.enable() xsr.enable() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self): """ Synchronise the settings. This routine changes the window settings so that the pixel start values are shifted downwards until they are synchr...
xbin = self.xbin.value() ybin = self.ybin.value() if xbin == 1 and ybin == 1: self.sbutt.config(state='disable') return for n, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self): if (xsll-1) % xbin != 0: xsll = xbin * ((xsll-1)//...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable(self): """ Enables WinQuad setting """
nquad = self.nquad.value() for label, xsll, xsul, xslr, xsur, ys, nx, ny in \ zip(self.label[:nquad], self.xsll[:nquad], self.xsul[:nquad], self.xslr[:nquad], self.xsur[:nquad], self.ys[:nquad], self.nx[:nquad], self.ny[:nquad]): label...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self, *args): """ Synchronise the settings. This means that the pixel start values are shifted downwards so that they are synchronised with a full-frame...
xbin = self.xbin.value() ybin = self.ybin.value() n = 0 for xs, ys, nx, ny in self: if xbin > 1 and xs % xbin != 1: if xs < 1025: xs = xbin*((xs-1)//xbin)+1 else: xs = xbin*((xs-1025)//xbin)+1025 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freeze(self): """ Freeze all settings so they can't be altered """
for xs, ys, nx, ny in \ zip(self.xs, self.ys, self.nx, self.ny): xs.disable() ys.disable() nx.disable() ny.disable() self.nwin.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.froz...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable(self): """ Enables all settings """
nwin = self.nwin.value() for label, xs, ys, nx, ny in \ zip(self.label[:nwin], self.xs[:nwin], self.ys[:nwin], self.nx[:nwin], self.ny[:nwin]): label.config(state='normal') xs.enable() ys.enable() nx.enable() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_download(self, link_item_dict: Dict[str, LinkItem], folder: Path, log: bool = True) -> Tuple[ Dict[str, LinkItem], Dict[str, LinkItem]]: """ Check if th...
succeed = {link: item for link, item in link_item_dict.items() if folder.joinpath(item.name).is_file()} lost = {link: item for link, item in link_item_dict.items() if link not in succeed} if lost and log: for link, item in lost.items(): self.log.error(f"Not download...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_as_file(self, url: str, folder: Path, name: str, delay: float = 0) -> str: """ Download the given url to the given target folder. :param url: link :t...
while folder.joinpath(name).exists(): # TODO: handle already existing files self.log.warning('already exists: ' + name) name = name + '_d' with self._downloader.request('GET', url, preload_content=False, retries=urllib3.util.retry.Retry(3)) as reader: if reader.sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_save_state(self, link_item_dict: Dict[str, LinkItem]) -> SaveState: """ Create protobuf savestate of the module and the given data. :param link_item_d...
return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, self.last_update, link_item_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_save_state(self, data_dict: Dict[str, LinkItem]): # TODO: add progressbar """ Save meta data about the downloaded things and the plugin to file. :param ...
json_data = json_format.MessageToJson(self._create_save_state(data_dict).to_protobuf()) with self._save_state_file.open(mode='w', encoding="utf8") as writer: writer.write(json_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_save_state(self) -> SaveState: """ Load the savestate of the plugin. :return: savestate :rtype: ~unidown.plugin.save_state.SaveState :raises ~unidown.plu...
if not self._save_state_file.exists(): self.log.info("No savestate file found.") return SaveState(dynamic_data.SAVE_STATE_VERSION, self.info, datetime(1970, 1, 1), {}) savestat_proto = "" with self._save_state_file.open(mode='r', encoding="utf8") as data_file: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_updated_data(self, old_data: Dict[str, LinkItem]) -> Dict[str, LinkItem]: """ Get links who needs to be downloaded by comparing old and the new data. :par...
if not self.download_data: return {} new_link_item_dict = {} for link, link_item in tqdm(self.download_data.items(), desc="Compare with save", unit="item", leave=True, mininterval=1, ncols=100, disable=dynamic_data.DISABLE_TQDM): # TOD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_options_dic(self, options: List[str]) -> Dict[str, str]: """ Convert the option list to a dictionary where the key is the option and the value is the rel...
options_dic = {} for option in options: cur_option = option.split("=") if len(cur_option) != 2: self.log.warning(f"'{option}' is not valid and will be ignored.") options_dic[cur_option[0]] = cur_option[1] return options_dic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_plugins() -> Dict[str, pkg_resources.EntryPoint]: """ Get all available plugins for unidown. :return: plugin name list :rtype: Dict[str, ~pkg_resources.En...
return {entry.name: entry for entry in pkg_resources.iter_entry_points('unidown.plugin')}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _equation_of_time(t): """ Find the difference between apparent and mean solar time Parameters t : `~astropy.time.Time` times (array) Returns ret1 : `~astropy...
# Julian centuries since J2000.0 T = (t - Time("J2000")).to(u.year).value / 100 # obliquity of ecliptic (Meeus 1998, eq 22.2) poly_pars = (84381.448, 46.8150, 0.00059, 0.001813) eps = u.Quantity(polyval(T, poly_pars), u.arcsec) y = np.tan(eps/2)**2 # Sun's mean longitude (Meeus 1998, eq ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _astropy_time_from_LST(t, LST, location, prev_next): """ Convert a Local Sidereal Time to an astropy Time object. The local time is related to the LST throug...
# now we need to figure out time to return from LST raSun = coord.get_sun(t).ra # calculate Greenwich Apparent Solar Time, which we will use as ~UTC for now with warnings.catch_warnings(): warnings.simplefilter('ignore') # ignore astropy deprecation warnings lon = location.long...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _two_point_interp(times, altitudes, horizon=0*u.deg): """ Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the ...
if not isinstance(times, Time): return MAGIC_TIME else: slope = (altitudes[1] - altitudes[0])/(times[1].jd - times[0].jd) return Time(times[1].jd - ((altitudes[1] - horizon)/slope).value, format='jd')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_dirs(main_dir: Path, logfilepath: Path): """ Initialize the main directories. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfi...
global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH MAIN_DIR = main_dir TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('savestates/')) LOGFILE_PATH = MAIN_DIR.joinpath(logfilepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(): """ Reset all dynamic variables to the default values. """
global MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR, LOGFILE_PATH, USING_CORES, LOG_LEVEL, DISABLE_TQDM, \ SAVE_STATE_VERSION MAIN_DIR = Path('./') TEMP_DIR = MAIN_DIR.joinpath(Path('temp/')) DOWNLOAD_DIR = MAIN_DIR.joinpath(Path('downloads/')) SAVESTAT_DIR = MAIN_DIR.joinpath(Path('saves...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_dirs(): """ Check the directories if they exist. :raises FileExistsError: if a file exists but is not a directory """
dirs = [MAIN_DIR, TEMP_DIR, DOWNLOAD_DIR, SAVESTAT_DIR] for directory in dirs: if directory.exists() and not directory.is_dir(): raise FileExistsError(str(directory.resolve()) + " cannot be used as a directory.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_hstring(hs): """ Parse a single item from the telescope server into name, value, comment. """
# split the string on = and /, also stripping whitespace and annoying quotes name, value, comment = yield_three( [val.strip().strip("'") for val in filter(None, re.split("[=/]+", hs))] ) # if comment has a slash in it, put it back together try: len(comment) except: pass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_header_from_telpars(telpars): """ Create a list of fits header items from GTC telescope pars. The GTC telescope server gives a list of string describi...
# pars is a list of strings describing tel info in FITS # style, each entry in the list is a different class of # thing (weather, telescope, instrument etc). # first, we munge it into a single list of strings, each one # describing a single item whilst also stripping whitespace pars = [val.str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_gtc_header_table_row(t, telpars): """ Add a row with current values to GTC table Arguments --------- t : `~astropy.table.Table` The table to append row t...
now = Time.now().mjd hdr = create_header_from_telpars(telpars) # make dictionary of vals to put in table vals = {k: v for k, v in hdr.items() if k in VARIABLE_GTC_KEYS} vals['MJD'] = now # store LST as hourangle vals['LST'] = Longitude(vals['LST'], unit=u.hour).hourangle t.add_row(vals...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns a string with the article + the word. """
return "%s %s" % (_article(word, article, gender, role), word)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def singularize(word, pos=NOUN, gender=MALE, role=SUBJECT, custom={}): """ Returns the singular of a given word. The inflection is based on probability rather th...
w = word.lower().capitalize() if word in custom: return custom[word] if word in singular: return singular[word] if pos == NOUN: for a, b in singular_inflections: if w.endswith(a): return w[:-len(a)] + b # Default rule: strip known plural suffi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_words_from_dataset(dataset): """Return a set of all words in a dataset. :param dataset: A list of tuples of the form ``(words, label)`` where ``words`` ...
# Words may be either a string or a list of tokens. Return an iterator # of tokens accordingly def tokenize(words): if isinstance(words, basestring): return word_tokenize(words, include_punc=False) else: return words all_words = chain.from_iterable(tokenize(words...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_extractor(document, train_set): """A basic document feature extractor that returns a dict indicating what words in ``train_set`` are contained in ``doc...
word_features = _get_words_from_dataset(train_set) tokens = _get_document_tokens(document) features = dict(((u'contains({0})'.format(word), (word in tokens)) for word in word_features)) return features
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains_extractor(document): """A basic document feature extractor that returns a dict of words that the document contains."""
tokens = _get_document_tokens(document) features = dict((u'contains({0})'.format(w), True) for w in tokens) return features
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_data(self, dataset, format=None): """Reads a data file and returns and iterable that can be used as testing or training data."""
# Attempt to detect file format if "format" isn't specified if not format: format_class = formats.detect(dataset) else: if format not in formats.AVAILABLE.keys(): raise ValueError("'{0}' format not supported.".format(format)) format_class = fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_features(self, text): """Extracts features from a body of text. :rtype: dictionary of features """
# Feature extractor may take one or two arguments try: return self.feature_extractor(text, self.train_set) except (TypeError, AttributeError): return self.feature_extractor(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train(self, *args, **kwargs): """Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK clas...
try: self.classifier = self.nltk_class.train(self.train_features, *args, **kwargs) return self.classifier except AttributeError: raise ValueError("NLTKClassifier must have a nltk_class" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify(self, text): """Classifies the text. :param str text: A string of text. """
text_features = self.extract_features(text) return self.classifier.classify(text_features)