repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ejeschke/ginga
ginga/misc/Task.py
Task.init_and_start
def init_and_start(self, taskParent, override={}): """Convenience method to initialize and start a task. """ tag = self.initialize(taskParent, override=override) self.start() return tag
python
def init_and_start(self, taskParent, override={}): """Convenience method to initialize and start a task. """ tag = self.initialize(taskParent, override=override) self.start() return tag
[ "def", "init_and_start", "(", "self", ",", "taskParent", ",", "override", "=", "{", "}", ")", ":", "tag", "=", "self", ".", "initialize", "(", "taskParent", ",", "override", "=", "override", ")", "self", ".", "start", "(", ")", "return", "tag" ]
Convenience method to initialize and start a task.
[ "Convenience", "method", "to", "initialize", "and", "start", "a", "task", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L127-L133
train
24,700
ejeschke/ginga
ginga/misc/Task.py
Task.wait
def wait(self, timeout=None): """This method waits for an executing task to finish. Subclass can override this method if necessary. """ self.ev_done.wait(timeout=timeout) if not self.ev_done.is_set(): raise TaskTimeout("Task %s timed out." % self) # --> self.result is set # If it is an exception, then raise it in this waiter if isinstance(self.result, Exception): raise self.result # Release waiters and perform callbacks # done() has already been called, because of self.ev_done check # "asynchronous" tasks should could call done() here #self.done(self.result) return self.result
python
def wait(self, timeout=None): """This method waits for an executing task to finish. Subclass can override this method if necessary. """ self.ev_done.wait(timeout=timeout) if not self.ev_done.is_set(): raise TaskTimeout("Task %s timed out." % self) # --> self.result is set # If it is an exception, then raise it in this waiter if isinstance(self.result, Exception): raise self.result # Release waiters and perform callbacks # done() has already been called, because of self.ev_done check # "asynchronous" tasks should could call done() here #self.done(self.result) return self.result
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "ev_done", ".", "wait", "(", "timeout", "=", "timeout", ")", "if", "not", "self", ".", "ev_done", ".", "is_set", "(", ")", ":", "raise", "TaskTimeout", "(", "\"Task %s ti...
This method waits for an executing task to finish. Subclass can override this method if necessary.
[ "This", "method", "waits", "for", "an", "executing", "task", "to", "finish", ".", "Subclass", "can", "override", "this", "method", "if", "necessary", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L173-L192
train
24,701
ejeschke/ginga
ginga/misc/Task.py
Task.done
def done(self, result, noraise=False): """This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end. """ # [??] Should this be in a critical section? # Has done() already been called on this task? if self.ev_done.is_set(): # ?? if isinstance(self.result, Exception) and (not noraise): raise self.result return self.result # calculate running time and other finalization self.endtime = time.time() try: self.totaltime = self.endtime - self.starttime except AttributeError: # task was not initialized properly self.totaltime = 0.0 self.result = result # Release thread waiters self.ev_done.set() # Perform callbacks for event-style waiters self.make_callback('resolved', self.result) # If the result is an exception, then our final act is to raise # it in the caller, unless the caller explicitly supressed that if isinstance(result, Exception) and (not noraise): raise result return result
python
def done(self, result, noraise=False): """This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end. """ # [??] Should this be in a critical section? # Has done() already been called on this task? if self.ev_done.is_set(): # ?? if isinstance(self.result, Exception) and (not noraise): raise self.result return self.result # calculate running time and other finalization self.endtime = time.time() try: self.totaltime = self.endtime - self.starttime except AttributeError: # task was not initialized properly self.totaltime = 0.0 self.result = result # Release thread waiters self.ev_done.set() # Perform callbacks for event-style waiters self.make_callback('resolved', self.result) # If the result is an exception, then our final act is to raise # it in the caller, unless the caller explicitly supressed that if isinstance(result, Exception) and (not noraise): raise result return result
[ "def", "done", "(", "self", ",", "result", ",", "noraise", "=", "False", ")", ":", "# [??] Should this be in a critical section?", "# Has done() already been called on this task?", "if", "self", ".", "ev_done", ".", "is_set", "(", ")", ":", "# ??", "if", "isinstance...
This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end.
[ "This", "method", "is", "called", "when", "a", "task", "has", "finished", "executing", ".", "Subclass", "can", "override", "this", "method", "if", "desired", "but", "should", "call", "superclass", "method", "at", "the", "end", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L210-L244
train
24,702
ejeschke/ginga
ginga/misc/Task.py
Task.runTask
def runTask(self, task, timeout=None): """Run a child task to completion. Returns the result of the child task. """ # Initialize the task. task.initialize(self) # Start the task. task.start() # Lets other threads run time.sleep(0) # Wait for it to finish. res = task.wait(timeout=timeout) # Now we're done return res
python
def runTask(self, task, timeout=None): """Run a child task to completion. Returns the result of the child task. """ # Initialize the task. task.initialize(self) # Start the task. task.start() # Lets other threads run time.sleep(0) # Wait for it to finish. res = task.wait(timeout=timeout) # Now we're done return res
[ "def", "runTask", "(", "self", ",", "task", ",", "timeout", "=", "None", ")", ":", "# Initialize the task.", "task", ".", "initialize", "(", "self", ")", "# Start the task.", "task", ".", "start", "(", ")", "# Lets other threads run", "time", ".", "sleep", "...
Run a child task to completion. Returns the result of the child task.
[ "Run", "a", "child", "task", "to", "completion", ".", "Returns", "the", "result", "of", "the", "child", "task", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L263-L280
train
24,703
ejeschke/ginga
ginga/misc/Task.py
SequentialTaskset.execute
def execute(self): """Run all child tasks, in order, waiting for completion of each. Return the result of the final child task's execution. """ while self.index < len(self.tasklist): res = self.step() self.logger.debug('SeqSet task %i has completed with result %s' % (self.index, res)) # Returns result of last task to quit return res
python
def execute(self): """Run all child tasks, in order, waiting for completion of each. Return the result of the final child task's execution. """ while self.index < len(self.tasklist): res = self.step() self.logger.debug('SeqSet task %i has completed with result %s' % (self.index, res)) # Returns result of last task to quit return res
[ "def", "execute", "(", "self", ")", ":", "while", "self", ".", "index", "<", "len", "(", "self", ".", "tasklist", ")", ":", "res", "=", "self", ".", "step", "(", ")", "self", ".", "logger", ".", "debug", "(", "'SeqSet task %i has completed with result %s...
Run all child tasks, in order, waiting for completion of each. Return the result of the final child task's execution.
[ "Run", "all", "child", "tasks", "in", "order", "waiting", "for", "completion", "of", "each", ".", "Return", "the", "result", "of", "the", "final", "child", "task", "s", "execution", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L428-L438
train
24,704
ejeschke/ginga
ginga/misc/Task.py
oldConcurrentAndTaskset.execute
def execute(self): """Run all child tasks concurrently in separate threads. Return 0 after all child tasks have completed execution. """ self.count = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Register termination callbacks for all my child tasks. for task in list(self.taskseq): self.taskset.append(task) task.add_callback('resolved', self.child_done, self.count) self.count += 1 self.numtasks = self.count # Now start each child task. with self.regcond: for task in list(self.taskset): task.initialize(self) task.start() # Account for time needed to start subtasks self.totaltime = time.time() - self.totaltime # Now give up the critical section and wait for last child # task to terminate. while self.count > 0: self.regcond.wait() # Scan results for errors (exceptions) and raise the first one we find for key in self.results.keys(): value = self.results[key] if isinstance(value, Exception): (count, task) = key self.logger.error("Child task %s terminated with exception: %s" % ( task.tag, str(value))) raise value return 0
python
def execute(self): """Run all child tasks concurrently in separate threads. Return 0 after all child tasks have completed execution. """ self.count = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Register termination callbacks for all my child tasks. for task in list(self.taskseq): self.taskset.append(task) task.add_callback('resolved', self.child_done, self.count) self.count += 1 self.numtasks = self.count # Now start each child task. with self.regcond: for task in list(self.taskset): task.initialize(self) task.start() # Account for time needed to start subtasks self.totaltime = time.time() - self.totaltime # Now give up the critical section and wait for last child # task to terminate. while self.count > 0: self.regcond.wait() # Scan results for errors (exceptions) and raise the first one we find for key in self.results.keys(): value = self.results[key] if isinstance(value, Exception): (count, task) = key self.logger.error("Child task %s terminated with exception: %s" % ( task.tag, str(value))) raise value return 0
[ "def", "execute", "(", "self", ")", ":", "self", ".", "count", "=", "0", "self", ".", "taskset", "=", "[", "]", "self", ".", "results", "=", "{", "}", "self", ".", "totaltime", "=", "time", ".", "time", "(", ")", "# Register termination callbacks for a...
Run all child tasks concurrently in separate threads. Return 0 after all child tasks have completed execution.
[ "Run", "all", "child", "tasks", "concurrently", "in", "separate", "threads", ".", "Return", "0", "after", "all", "child", "tasks", "have", "completed", "execution", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L473-L514
train
24,705
ejeschke/ginga
ginga/misc/Task.py
newConcurrentAndTaskset.execute
def execute(self): """Run all child tasks concurrently in separate threads. Return last result after all child tasks have completed execution. """ with self._lock_c: self.count = 0 self.numtasks = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Start all tasks for task in self.taskseq: self.taskset.append(task) self.numtasks += 1 task.init_and_start(self) num_tasks = self.getNumTasks() # Wait on each task to clean up results while num_tasks > 0: self.check_state() for i in range(num_tasks): try: try: task = self.getTask(i) except IndexError: # A task got deleted from the set. Jump back out # to outer loop and repoll the number of tasks break #self.logger.debug("waiting on %s" % task) res = task.wait(timeout=self.idletime) #self.logger.debug("finished: %s" % task) self.child_done(res, task) except TaskTimeout: continue except Exception as e: #self.logger.warning("Subtask propagated exception: %s" % str(e)) self.child_done(e, task) continue # wait a bit and try again #self.ev_quit.wait(self.idletime) # re-get number of tasks, in case some were added or deleted num_tasks = self.getNumTasks() # Scan results for errors (exceptions) and raise the first one we find for key in self.results.keys(): value = self.results[key] if isinstance(value, Exception): (count, task) = key self.logger.error("Child task %s terminated with exception: %s" % ( task.tag, str(value))) raise value # Return value of last child to complete return value
python
def execute(self): """Run all child tasks concurrently in separate threads. Return last result after all child tasks have completed execution. """ with self._lock_c: self.count = 0 self.numtasks = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Start all tasks for task in self.taskseq: self.taskset.append(task) self.numtasks += 1 task.init_and_start(self) num_tasks = self.getNumTasks() # Wait on each task to clean up results while num_tasks > 0: self.check_state() for i in range(num_tasks): try: try: task = self.getTask(i) except IndexError: # A task got deleted from the set. Jump back out # to outer loop and repoll the number of tasks break #self.logger.debug("waiting on %s" % task) res = task.wait(timeout=self.idletime) #self.logger.debug("finished: %s" % task) self.child_done(res, task) except TaskTimeout: continue except Exception as e: #self.logger.warning("Subtask propagated exception: %s" % str(e)) self.child_done(e, task) continue # wait a bit and try again #self.ev_quit.wait(self.idletime) # re-get number of tasks, in case some were added or deleted num_tasks = self.getNumTasks() # Scan results for errors (exceptions) and raise the first one we find for key in self.results.keys(): value = self.results[key] if isinstance(value, Exception): (count, task) = key self.logger.error("Child task %s terminated with exception: %s" % ( task.tag, str(value))) raise value # Return value of last child to complete return value
[ "def", "execute", "(", "self", ")", ":", "with", "self", ".", "_lock_c", ":", "self", ".", "count", "=", "0", "self", ".", "numtasks", "=", "0", "self", ".", "taskset", "=", "[", "]", "self", ".", "results", "=", "{", "}", "self", ".", "totaltime...
Run all child tasks concurrently in separate threads. Return last result after all child tasks have completed execution.
[ "Run", "all", "child", "tasks", "concurrently", "in", "separate", "threads", ".", "Return", "last", "result", "after", "all", "child", "tasks", "have", "completed", "execution", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L572-L634
train
24,706
ejeschke/ginga
ginga/misc/Task.py
WorkerThread.execute
def execute(self, task): """Execute a task. """ taskid = str(task) res = None try: # Try to run the task. If we catch an exception, then # it becomes the result. self.time_start = time.time() self.setstatus('executing %s' % taskid) self.logger.debug("now executing task '%s'" % taskid) try: res = task.execute() except UserTaskException as e: res = e except Exception as e: self.logger.error("Task '%s' raised exception: %s" % (str(task), str(e))) res = e try: (type, value, tb) = sys.exc_info() self.logger.debug("Traceback:\n%s" % "".join(traceback.format_tb(tb))) # NOTE: to avoid creating a cycle that might cause # problems for GC--see Python library doc for sys # module tb = None except Exception as e: self.logger.debug("Traceback information unavailable.") finally: self.logger.debug("done executing task '%s'" % str(task)) self.setstatus('cleaning %s' % taskid) # Wake up waiters on other threads task.done(res, noraise=True) self.time_start = 0.0 self.setstatus('idle')
python
def execute(self, task): """Execute a task. """ taskid = str(task) res = None try: # Try to run the task. If we catch an exception, then # it becomes the result. self.time_start = time.time() self.setstatus('executing %s' % taskid) self.logger.debug("now executing task '%s'" % taskid) try: res = task.execute() except UserTaskException as e: res = e except Exception as e: self.logger.error("Task '%s' raised exception: %s" % (str(task), str(e))) res = e try: (type, value, tb) = sys.exc_info() self.logger.debug("Traceback:\n%s" % "".join(traceback.format_tb(tb))) # NOTE: to avoid creating a cycle that might cause # problems for GC--see Python library doc for sys # module tb = None except Exception as e: self.logger.debug("Traceback information unavailable.") finally: self.logger.debug("done executing task '%s'" % str(task)) self.setstatus('cleaning %s' % taskid) # Wake up waiters on other threads task.done(res, noraise=True) self.time_start = 0.0 self.setstatus('idle')
[ "def", "execute", "(", "self", ",", "task", ")", ":", "taskid", "=", "str", "(", "task", ")", "res", "=", "None", "try", ":", "# Try to run the task. If we catch an exception, then", "# it becomes the result.", "self", ".", "time_start", "=", "time", ".", "time...
Execute a task.
[ "Execute", "a", "task", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L868-L912
train
24,707
ejeschke/ginga
ginga/misc/Task.py
ThreadPool.startall
def startall(self, wait=False, **kwdargs): """Start all of the threads in the thread pool. If _wait_ is True then don't return until all threads are up and running. Any extra keyword arguments are passed to the worker thread constructor. """ self.logger.debug("startall called") with self.regcond: while self.status != 'down': if self.status in ('start', 'up') or self.ev_quit.is_set(): # For now, abandon additional request to start self.logger.error("ignoring duplicate request to start thread pool") return self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() #assert(self.status == 'down') if self.ev_quit.is_set(): return self.runningcount = 0 self.status = 'start' self.workers = [] if wait: tpool = self else: tpool = None # Start all worker threads self.logger.debug("starting threads in thread pool") for i in range(self.numthreads): t = self.workerClass(self.queue, logger=self.logger, ev_quit=self.ev_quit, tpool=tpool, **kwdargs) self.workers.append(t) t.start() # if started with wait=True, then expect that threads will register # themselves and last one up will set status to "up" if wait: # Threads are on the way up. Wait until last one starts. while self.status != 'up' and not self.ev_quit.is_set(): self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() else: # otherwise, we just assume the pool is up self.status = 'up' self.logger.debug("startall done")
python
def startall(self, wait=False, **kwdargs): """Start all of the threads in the thread pool. If _wait_ is True then don't return until all threads are up and running. Any extra keyword arguments are passed to the worker thread constructor. """ self.logger.debug("startall called") with self.regcond: while self.status != 'down': if self.status in ('start', 'up') or self.ev_quit.is_set(): # For now, abandon additional request to start self.logger.error("ignoring duplicate request to start thread pool") return self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() #assert(self.status == 'down') if self.ev_quit.is_set(): return self.runningcount = 0 self.status = 'start' self.workers = [] if wait: tpool = self else: tpool = None # Start all worker threads self.logger.debug("starting threads in thread pool") for i in range(self.numthreads): t = self.workerClass(self.queue, logger=self.logger, ev_quit=self.ev_quit, tpool=tpool, **kwdargs) self.workers.append(t) t.start() # if started with wait=True, then expect that threads will register # themselves and last one up will set status to "up" if wait: # Threads are on the way up. Wait until last one starts. while self.status != 'up' and not self.ev_quit.is_set(): self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() else: # otherwise, we just assume the pool is up self.status = 'up' self.logger.debug("startall done")
[ "def", "startall", "(", "self", ",", "wait", "=", "False", ",", "*", "*", "kwdargs", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"startall called\"", ")", "with", "self", ".", "regcond", ":", "while", "self", ".", "status", "!=", "'down'", ...
Start all of the threads in the thread pool. If _wait_ is True then don't return until all threads are up and running. Any extra keyword arguments are passed to the worker thread constructor.
[ "Start", "all", "of", "the", "threads", "in", "the", "thread", "pool", ".", "If", "_wait_", "is", "True", "then", "don", "t", "return", "until", "all", "threads", "are", "up", "and", "running", ".", "Any", "extra", "keyword", "arguments", "are", "passed"...
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L999-L1048
train
24,708
ejeschke/ginga
ginga/misc/Task.py
ThreadPool.stopall
def stopall(self, wait=False): """Stop all threads in the worker pool. If _wait_ is True then don't return until all threads are down. """ self.logger.debug("stopall called") with self.regcond: while self.status != 'up': if self.status in ('stop', 'down') or self.ev_quit.is_set(): # For now, silently abandon additional request to stop self.logger.warning("ignoring duplicate request to stop thread pool.") return self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() #assert(self.status == 'up') self.logger.debug("stopping threads in thread pool") self.status = 'stop' # Signal to all threads to terminate. self.ev_quit.set() if wait: # Threads are on the way down. Wait until last one quits. while self.status != 'down': self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() self.logger.debug("stopall done")
python
def stopall(self, wait=False): """Stop all threads in the worker pool. If _wait_ is True then don't return until all threads are down. """ self.logger.debug("stopall called") with self.regcond: while self.status != 'up': if self.status in ('stop', 'down') or self.ev_quit.is_set(): # For now, silently abandon additional request to stop self.logger.warning("ignoring duplicate request to stop thread pool.") return self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() #assert(self.status == 'up') self.logger.debug("stopping threads in thread pool") self.status = 'stop' # Signal to all threads to terminate. self.ev_quit.set() if wait: # Threads are on the way down. Wait until last one quits. while self.status != 'down': self.logger.debug("waiting for threads: count=%d" % self.runningcount) self.regcond.wait() self.logger.debug("stopall done")
[ "def", "stopall", "(", "self", ",", "wait", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"stopall called\"", ")", "with", "self", ".", "regcond", ":", "while", "self", ".", "status", "!=", "'up'", ":", "if", "self", ".", "statu...
Stop all threads in the worker pool. If _wait_ is True then don't return until all threads are down.
[ "Stop", "all", "threads", "in", "the", "worker", "pool", ".", "If", "_wait_", "is", "True", "then", "don", "t", "return", "until", "all", "threads", "are", "down", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L1064-L1093
train
24,709
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
wcs_pix_transform
def wcs_pix_transform(ct, i, format=0): """Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS corrected pixel value """ z1 = float(ct.z1) z2 = float(ct.z2) i = float(i) yscale = 128.0 / (z2 - z1) if (format == 'T' or format == 't'): format = 1 if (i == 0): t = 0. else: if (ct.zt == W_LINEAR): t = ((i - 1) * (z2 - z1) / 199.0) + z1 t = max(z1, min(z2, t)) else: t = float(i) if (format > 1): t = (z2 - t) * yscale return (t)
python
def wcs_pix_transform(ct, i, format=0): """Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS corrected pixel value """ z1 = float(ct.z1) z2 = float(ct.z2) i = float(i) yscale = 128.0 / (z2 - z1) if (format == 'T' or format == 't'): format = 1 if (i == 0): t = 0. else: if (ct.zt == W_LINEAR): t = ((i - 1) * (z2 - z1) / 199.0) + z1 t = max(z1, min(z2, t)) else: t = float(i) if (format > 1): t = (z2 - t) * yscale return (t)
[ "def", "wcs_pix_transform", "(", "ct", ",", "i", ",", "format", "=", "0", ")", ":", "z1", "=", "float", "(", "ct", ".", "z1", ")", "z2", "=", "float", "(", "ct", ".", "z2", ")", "i", "=", "float", "(", "i", ")", "yscale", "=", "128.0", "/", ...
Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS corrected pixel value
[ "Computes", "the", "WCS", "corrected", "pixel", "value", "given", "a", "coordinate", "transformation", "and", "the", "raw", "pixel", "value", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L947-L977
train
24,710
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_DataListener.handle_request
def handle_request(self): """ Handles incoming connections, one at the time. """ try: (request, client_address) = self.get_request() except socket.error as e: # Error handling goes here. self.logger.error("error opening the connection: %s" % ( str(e))) for exctn in sys.exc_info(): print(exctn) return try: self.RequestHandlerClass(request, client_address, self) except Exception as e: # Error handling goes here. self.logger.error('error handling the request: %s' % ( str(e))) for exctn in sys.exc_info(): print(exctn) return
python
def handle_request(self): """ Handles incoming connections, one at the time. """ try: (request, client_address) = self.get_request() except socket.error as e: # Error handling goes here. self.logger.error("error opening the connection: %s" % ( str(e))) for exctn in sys.exc_info(): print(exctn) return try: self.RequestHandlerClass(request, client_address, self) except Exception as e: # Error handling goes here. self.logger.error('error handling the request: %s' % ( str(e))) for exctn in sys.exc_info(): print(exctn) return
[ "def", "handle_request", "(", "self", ")", ":", "try", ":", "(", "request", ",", "client_address", ")", "=", "self", ".", "get_request", "(", ")", "except", "socket", ".", "error", "as", "e", ":", "# Error handling goes here.", "self", ".", "logger", ".", ...
Handles incoming connections, one at the time.
[ "Handles", "incoming", "connections", "one", "at", "the", "time", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L144-L167
train
24,711
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_DataListener.mainloop
def mainloop(self): """main control loop.""" try: while (not self.ev_quit.is_set()): try: self.handle_request() except socketTimeout: continue finally: self.socket.close()
python
def mainloop(self): """main control loop.""" try: while (not self.ev_quit.is_set()): try: self.handle_request() except socketTimeout: continue finally: self.socket.close()
[ "def", "mainloop", "(", "self", ")", ":", "try", ":", "while", "(", "not", "self", ".", "ev_quit", ".", "is_set", "(", ")", ")", ":", "try", ":", "self", ".", "handle_request", "(", ")", "except", "socketTimeout", ":", "continue", "finally", ":", "se...
main control loop.
[ "main", "control", "loop", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L169-L179
train
24,712
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_RequestHandler.handle_feedback
def handle_feedback(self, pkt): """This part of the protocol is used by IRAF to erase a frame in the framebuffers. """ self.logger.debug("handle feedback") self.frame = self.decode_frameno(pkt.z & 0o7777) - 1 # erase the frame buffer self.server.controller.init_frame(self.frame) self.server.controller.set_frame(self.frame)
python
def handle_feedback(self, pkt): """This part of the protocol is used by IRAF to erase a frame in the framebuffers. """ self.logger.debug("handle feedback") self.frame = self.decode_frameno(pkt.z & 0o7777) - 1 # erase the frame buffer self.server.controller.init_frame(self.frame) self.server.controller.set_frame(self.frame)
[ "def", "handle_feedback", "(", "self", ",", "pkt", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"handle feedback\"", ")", "self", ".", "frame", "=", "self", ".", "decode_frameno", "(", "pkt", ".", "z", "&", "0o7777", ")", "-", "1", "# erase th...
This part of the protocol is used by IRAF to erase a frame in the framebuffers.
[ "This", "part", "of", "the", "protocol", "is", "used", "by", "IRAF", "to", "erase", "a", "frame", "in", "the", "framebuffers", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L379-L388
train
24,713
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_RequestHandler.handle_lut
def handle_lut(self, pkt): """This part of the protocol is used by IRAF to set the frame number. """ self.logger.debug("handle lut") if pkt.subunit & COMMAND: data_type = str(pkt.nbytes / 2) + 'h' #size = struct.calcsize(data_type) line = pkt.datain.read(pkt.nbytes) n = len(line) if (n < pkt.nbytes): return try: x = struct.unpack(data_type, line) except Exception as e: self.logger.error("Error unpacking struct: %s" % (str(e))) return if len(x) < 14: # pad it with zeroes y = [] for i in range(14): try: y.append(x[i]) except Exception: y.append(0) x = y del(y) if len(x) == 14: z = int(x[0]) # frames start from 1, we start from 0 self.frame = self.decode_frameno(z) - 1 if (self.frame > MAX_FRAMES): self.logger.error("attempt to select non existing frame.") return # init the framebuffer #self.server.controller.init_frame(self.frame) try: self.server.controller.get_frame(self.frame) except KeyError: self.server.controller.init_frame(self.frame) return self.logger.error("unable to select a frame.") return self.logger.error("what shall I do?")
python
def handle_lut(self, pkt): """This part of the protocol is used by IRAF to set the frame number. """ self.logger.debug("handle lut") if pkt.subunit & COMMAND: data_type = str(pkt.nbytes / 2) + 'h' #size = struct.calcsize(data_type) line = pkt.datain.read(pkt.nbytes) n = len(line) if (n < pkt.nbytes): return try: x = struct.unpack(data_type, line) except Exception as e: self.logger.error("Error unpacking struct: %s" % (str(e))) return if len(x) < 14: # pad it with zeroes y = [] for i in range(14): try: y.append(x[i]) except Exception: y.append(0) x = y del(y) if len(x) == 14: z = int(x[0]) # frames start from 1, we start from 0 self.frame = self.decode_frameno(z) - 1 if (self.frame > MAX_FRAMES): self.logger.error("attempt to select non existing frame.") return # init the framebuffer #self.server.controller.init_frame(self.frame) try: self.server.controller.get_frame(self.frame) except KeyError: self.server.controller.init_frame(self.frame) return self.logger.error("unable to select a frame.") return self.logger.error("what shall I do?")
[ "def", "handle_lut", "(", "self", ",", "pkt", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"handle lut\"", ")", "if", "pkt", ".", "subunit", "&", "COMMAND", ":", "data_type", "=", "str", "(", "pkt", ".", "nbytes", "/", "2", ")", "+", "'h'"...
This part of the protocol is used by IRAF to set the frame number.
[ "This", "part", "of", "the", "protocol", "is", "used", "by", "IRAF", "to", "set", "the", "frame", "number", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L390-L438
train
24,714
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_RequestHandler.handle_imcursor
def handle_imcursor(self, pkt): """This part of the protocol is used by IRAF to read the cursor position and keystrokes from the display client. """ self.logger.debug("handle imcursor") if pkt.tid & IIS_READ: if pkt.tid & IMC_SAMPLE: self.logger.debug("SAMPLE") # return the cursor position wcsflag = int(pkt.z) #wcsflag = 0 res = self.server.controller.get_keystroke() self.return_cursor(pkt.dataout, res.x, res.y, res.frame, wcsflag, '0', '') else: self.logger.debug("OTHER") res = self.server.controller.get_keystroke() self.logger.debug("FRAME=%d X,Y=%f,%f" % ( res.frame, res.x, res.y)) ## sx = self.x self.x = res.x self.y = res.y self.frame = res.frame ## sy = self.y ## frame = self.frame #wcsflag = 1 wcsflag = 0 #self.return_cursor(pkt.dataout, sx, sy, frame, 1, key, '') self.return_cursor(pkt.dataout, res.x, res.y, res.frame, wcsflag, res.key, '') else: self.logger.debug("READ") # read the cursor position in logical coordinates sx = int(pkt.x) sy = int(pkt.y) wx = float(pkt.x) wy = float(pkt.y) wcs = int(pkt.z) if wcs: # decode the WCS info for the current frame try: fb = self.server.controller.get_frame(self.frame) except KeyError: # the selected frame does not exist, create it fb = self.server.controller.init_frame(self.frame) fb.ct = self.wcs_update(fb.wcs) if fb.ct.valid: if abs(fb.ct.a) > 0.001: sx = int((wx - fb.ct.tx) / fb.ct.a) if abs(fb.ct.d) > 0.001: sy = int((wy - fb.ct.ty) / fb.ct.d) self.server.controller.set_cursor(sx, sy)
python
def handle_imcursor(self, pkt): """This part of the protocol is used by IRAF to read the cursor position and keystrokes from the display client. """ self.logger.debug("handle imcursor") if pkt.tid & IIS_READ: if pkt.tid & IMC_SAMPLE: self.logger.debug("SAMPLE") # return the cursor position wcsflag = int(pkt.z) #wcsflag = 0 res = self.server.controller.get_keystroke() self.return_cursor(pkt.dataout, res.x, res.y, res.frame, wcsflag, '0', '') else: self.logger.debug("OTHER") res = self.server.controller.get_keystroke() self.logger.debug("FRAME=%d X,Y=%f,%f" % ( res.frame, res.x, res.y)) ## sx = self.x self.x = res.x self.y = res.y self.frame = res.frame ## sy = self.y ## frame = self.frame #wcsflag = 1 wcsflag = 0 #self.return_cursor(pkt.dataout, sx, sy, frame, 1, key, '') self.return_cursor(pkt.dataout, res.x, res.y, res.frame, wcsflag, res.key, '') else: self.logger.debug("READ") # read the cursor position in logical coordinates sx = int(pkt.x) sy = int(pkt.y) wx = float(pkt.x) wy = float(pkt.y) wcs = int(pkt.z) if wcs: # decode the WCS info for the current frame try: fb = self.server.controller.get_frame(self.frame) except KeyError: # the selected frame does not exist, create it fb = self.server.controller.init_frame(self.frame) fb.ct = self.wcs_update(fb.wcs) if fb.ct.valid: if abs(fb.ct.a) > 0.001: sx = int((wx - fb.ct.tx) / fb.ct.a) if abs(fb.ct.d) > 0.001: sy = int((wy - fb.ct.ty) / fb.ct.d) self.server.controller.set_cursor(sx, sy)
[ "def", "handle_imcursor", "(", "self", ",", "pkt", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"handle imcursor\"", ")", "if", "pkt", ".", "tid", "&", "IIS_READ", ":", "if", "pkt", ".", "tid", "&", "IMC_SAMPLE", ":", "self", ".", "logger", ...
This part of the protocol is used by IRAF to read the cursor position and keystrokes from the display client.
[ "This", "part", "of", "the", "protocol", "is", "used", "by", "IRAF", "to", "read", "the", "cursor", "position", "and", "keystrokes", "from", "the", "display", "client", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L632-L689
train
24,715
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_RequestHandler.handle
def handle(self): """ This is where the action starts. """ self.logger = self.server.logger # create a packet structure packet = iis() packet.datain = self.rfile packet.dataout = self.wfile # decode the header size = struct.calcsize('8h') line = packet.datain.read(size) n = len(line) if n < size: return while n > 0: try: bytes = struct.unpack('8h', line) except Exception: self.logger.error('error unpacking the data.') for exctn in sys.exc_info(): print(exctn) # TODO: verify checksum # decode the packet fields subunit = bytes[2] subunit077 = subunit & 0o77 tid = bytes[0] x = bytes[4] & 0o177777 y = bytes[5] & 0o177777 z = bytes[6] & 0o177777 t = bytes[7] & 0o17777 ndatabytes = - bytes[1] # are the bytes packed? if (not(tid & PACKED)): ndatabytes *= 2 # populate the packet structure packet.subunit = subunit packet.subunit077 = subunit077 packet.tid = tid packet.x = x packet.y = y packet.z = z packet.t = t packet.nbytes = ndatabytes # decide what to do, depending on the # value of subunit self.logger.debug("PACKET IS %o" % packet.subunit) if packet.subunit077 == FEEDBACK: self.handle_feedback(packet) elif packet.subunit077 == LUT: self.handle_lut(packet) # read the next packet line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == MEMORY: self.handle_memory(packet) if self.needs_update: #self.display_image() pass # read the next packet line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == WCS: self.handle_wcs(packet) line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == IMCURSOR: self.handle_imcursor(packet) line = packet.datain.read(size) n = len(line) continue else: self.logger.debug('?NO OP (0%o)' % (packet.subunit077)) if not (packet.tid & IIS_READ): # OK, discard the rest of the data nbytes = packet.nbytes while nbytes > 0: # for (nbytes = ndatabytes; nbytes > 0; nbytes -= n): if nbytes < SZ_FIFOBUF: n = nbytes else: n = SZ_FIFOBUF m = self.rfile.read(n) if m <= 0: break nbytes -= n # read the next packet line = packet.datain.read(size) n = len(line) if n < size: return # <--- end of the while (n) loop if self.needs_update: self.display_image() self.needs_update = False
python
def handle(self): """ This is where the action starts. """ self.logger = self.server.logger # create a packet structure packet = iis() packet.datain = self.rfile packet.dataout = self.wfile # decode the header size = struct.calcsize('8h') line = packet.datain.read(size) n = len(line) if n < size: return while n > 0: try: bytes = struct.unpack('8h', line) except Exception: self.logger.error('error unpacking the data.') for exctn in sys.exc_info(): print(exctn) # TODO: verify checksum # decode the packet fields subunit = bytes[2] subunit077 = subunit & 0o77 tid = bytes[0] x = bytes[4] & 0o177777 y = bytes[5] & 0o177777 z = bytes[6] & 0o177777 t = bytes[7] & 0o17777 ndatabytes = - bytes[1] # are the bytes packed? if (not(tid & PACKED)): ndatabytes *= 2 # populate the packet structure packet.subunit = subunit packet.subunit077 = subunit077 packet.tid = tid packet.x = x packet.y = y packet.z = z packet.t = t packet.nbytes = ndatabytes # decide what to do, depending on the # value of subunit self.logger.debug("PACKET IS %o" % packet.subunit) if packet.subunit077 == FEEDBACK: self.handle_feedback(packet) elif packet.subunit077 == LUT: self.handle_lut(packet) # read the next packet line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == MEMORY: self.handle_memory(packet) if self.needs_update: #self.display_image() pass # read the next packet line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == WCS: self.handle_wcs(packet) line = packet.datain.read(size) n = len(line) continue elif packet.subunit077 == IMCURSOR: self.handle_imcursor(packet) line = packet.datain.read(size) n = len(line) continue else: self.logger.debug('?NO OP (0%o)' % (packet.subunit077)) if not (packet.tid & IIS_READ): # OK, discard the rest of the data nbytes = packet.nbytes while nbytes > 0: # for (nbytes = ndatabytes; nbytes > 0; nbytes -= n): if nbytes < SZ_FIFOBUF: n = nbytes else: n = SZ_FIFOBUF m = self.rfile.read(n) if m <= 0: break nbytes -= n # read the next packet line = packet.datain.read(size) n = len(line) if n < size: return # <--- end of the while (n) loop if self.needs_update: self.display_image() self.needs_update = False
[ "def", "handle", "(", "self", ")", ":", "self", ".", "logger", "=", "self", ".", "server", ".", "logger", "# create a packet structure", "packet", "=", "iis", "(", ")", "packet", ".", "datain", "=", "self", ".", "rfile", "packet", ".", "dataout", "=", ...
This is where the action starts.
[ "This", "is", "where", "the", "action", "starts", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L691-L804
train
24,716
ejeschke/ginga
experimental/plugins/IIS_DataListener.py
IIS_RequestHandler.display_image
def display_image(self, reset=1): """Utility routine used to display an updated frame from a framebuffer. """ try: fb = self.server.controller.get_frame(self.frame) except KeyError: # the selected frame does not exist, create it fb = self.server.controller.init_frame(self.frame) if not fb.height: width = fb.width height = int(len(fb.buffer) / width) fb.height = height # display the image if (len(fb.buffer) > 0) and (height > 0): self.server.controller.display(self.frame, width, height, True) else: self.server.controller.display(self.frame, fb.width, fb.height, False)
python
def display_image(self, reset=1): """Utility routine used to display an updated frame from a framebuffer. """ try: fb = self.server.controller.get_frame(self.frame) except KeyError: # the selected frame does not exist, create it fb = self.server.controller.init_frame(self.frame) if not fb.height: width = fb.width height = int(len(fb.buffer) / width) fb.height = height # display the image if (len(fb.buffer) > 0) and (height > 0): self.server.controller.display(self.frame, width, height, True) else: self.server.controller.display(self.frame, fb.width, fb.height, False)
[ "def", "display_image", "(", "self", ",", "reset", "=", "1", ")", ":", "try", ":", "fb", "=", "self", ".", "server", ".", "controller", ".", "get_frame", "(", "self", ".", "frame", ")", "except", "KeyError", ":", "# the selected frame does not exist, create ...
Utility routine used to display an updated frame from a framebuffer.
[ "Utility", "routine", "used", "to", "display", "an", "updated", "frame", "from", "a", "framebuffer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IIS_DataListener.py#L806-L826
train
24,717
ejeschke/ginga
ginga/rv/plugins/Contents.py
Contents._highlight_path
def _highlight_path(self, hl_path, tf): """Highlight or unhighlight a single entry. Examples -------- >>> hl_path = self._get_hl_key(chname, image) >>> self._highlight_path(hl_path, True) """ fc = self.settings.get('row_font_color', 'green') try: self.treeview.highlight_path(hl_path, tf, font_color=fc) except Exception as e: self.logger.info('Error changing highlight on treeview path ' '({0}): {1}'.format(hl_path, str(e)))
python
def _highlight_path(self, hl_path, tf): """Highlight or unhighlight a single entry. Examples -------- >>> hl_path = self._get_hl_key(chname, image) >>> self._highlight_path(hl_path, True) """ fc = self.settings.get('row_font_color', 'green') try: self.treeview.highlight_path(hl_path, tf, font_color=fc) except Exception as e: self.logger.info('Error changing highlight on treeview path ' '({0}): {1}'.format(hl_path, str(e)))
[ "def", "_highlight_path", "(", "self", ",", "hl_path", ",", "tf", ")", ":", "fc", "=", "self", ".", "settings", ".", "get", "(", "'row_font_color'", ",", "'green'", ")", "try", ":", "self", ".", "treeview", ".", "highlight_path", "(", "hl_path", ",", "...
Highlight or unhighlight a single entry. Examples -------- >>> hl_path = self._get_hl_key(chname, image) >>> self._highlight_path(hl_path, True)
[ "Highlight", "or", "unhighlight", "a", "single", "entry", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Contents.py#L403-L418
train
24,718
ejeschke/ginga
ginga/rv/plugins/Contents.py
Contents.update_highlights
def update_highlights(self, old_highlight_set, new_highlight_set): """Unhighlight the entries represented by ``old_highlight_set`` and highlight the ones represented by ``new_highlight_set``. Both are sets of keys. """ if not self.gui_up: return un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # unhighlight entries that should NOT be highlighted any more for key in un_hilite_set: self._highlight_path(key, False) # highlight new entries that should be for key in re_hilite_set: self._highlight_path(key, True)
python
def update_highlights(self, old_highlight_set, new_highlight_set): """Unhighlight the entries represented by ``old_highlight_set`` and highlight the ones represented by ``new_highlight_set``. Both are sets of keys. """ if not self.gui_up: return un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # unhighlight entries that should NOT be highlighted any more for key in un_hilite_set: self._highlight_path(key, False) # highlight new entries that should be for key in re_hilite_set: self._highlight_path(key, True)
[ "def", "update_highlights", "(", "self", ",", "old_highlight_set", ",", "new_highlight_set", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "un_hilite_set", "=", "old_highlight_set", "-", "new_highlight_set", "re_hilite_set", "=", "new_highlight_set", ...
Unhighlight the entries represented by ``old_highlight_set`` and highlight the ones represented by ``new_highlight_set``. Both are sets of keys.
[ "Unhighlight", "the", "entries", "represented", "by", "old_highlight_set", "and", "highlight", "the", "ones", "represented", "by", "new_highlight_set", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Contents.py#L420-L439
train
24,719
ejeschke/ginga
ginga/rv/plugins/Catalogs.py
CatalogListing.show_selection
def show_selection(self, star): """This method is called when the user clicks on a plotted star in the fitsviewer. """ try: # NOTE: this works around a quirk of Qt widget set where # selecting programatically in the table triggers the widget # selection callback (see select_star_cb() in Catalogs.py for Qt) self._select_flag = True self.mark_selection(star) finally: self._select_flag = False
python
def show_selection(self, star): """This method is called when the user clicks on a plotted star in the fitsviewer. """ try: # NOTE: this works around a quirk of Qt widget set where # selecting programatically in the table triggers the widget # selection callback (see select_star_cb() in Catalogs.py for Qt) self._select_flag = True self.mark_selection(star) finally: self._select_flag = False
[ "def", "show_selection", "(", "self", ",", "star", ")", ":", "try", ":", "# NOTE: this works around a quirk of Qt widget set where", "# selecting programatically in the table triggers the widget", "# selection callback (see select_star_cb() in Catalogs.py for Qt)", "self", ".", "_selec...
This method is called when the user clicks on a plotted star in the fitsviewer.
[ "This", "method", "is", "called", "when", "the", "user", "clicks", "on", "a", "plotted", "star", "in", "the", "fitsviewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Catalogs.py#L1028-L1040
train
24,720
ejeschke/ginga
ginga/rv/plugins/Catalogs.py
CatalogListing.select_star_cb
def select_star_cb(self, widget, res_dict): """This method is called when the user selects a star from the table. """ keys = list(res_dict.keys()) if len(keys) == 0: self.selected = [] self.replot_stars() else: idx = int(keys[0]) star = self.starlist[idx] if not self._select_flag: self.mark_selection(star, fromtable=True) return True
python
def select_star_cb(self, widget, res_dict): """This method is called when the user selects a star from the table. """ keys = list(res_dict.keys()) if len(keys) == 0: self.selected = [] self.replot_stars() else: idx = int(keys[0]) star = self.starlist[idx] if not self._select_flag: self.mark_selection(star, fromtable=True) return True
[ "def", "select_star_cb", "(", "self", ",", "widget", ",", "res_dict", ")", ":", "keys", "=", "list", "(", "res_dict", ".", "keys", "(", ")", ")", "if", "len", "(", "keys", ")", "==", "0", ":", "self", ".", "selected", "=", "[", "]", "self", ".", ...
This method is called when the user selects a star from the table.
[ "This", "method", "is", "called", "when", "the", "user", "selects", "a", "star", "from", "the", "table", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Catalogs.py#L1308-L1320
train
24,721
ejeschke/ginga
ginga/BaseImage.py
BaseImage._calc_order
def _calc_order(self, order): """Called to set the order of a multi-channel image. The order should be determined by the loader, but this will make a best guess if passed `order` is `None`. """ if order is not None and order != '': self.order = order.upper() else: shape = self.shape if len(shape) <= 2: self.order = 'M' else: depth = shape[-1] # TODO: need something better here than a guess! if depth == 1: self.order = 'M' elif depth == 2: self.order = 'AM' elif depth == 3: self.order = 'RGB' elif depth == 4: self.order = 'RGBA'
python
def _calc_order(self, order): """Called to set the order of a multi-channel image. The order should be determined by the loader, but this will make a best guess if passed `order` is `None`. """ if order is not None and order != '': self.order = order.upper() else: shape = self.shape if len(shape) <= 2: self.order = 'M' else: depth = shape[-1] # TODO: need something better here than a guess! if depth == 1: self.order = 'M' elif depth == 2: self.order = 'AM' elif depth == 3: self.order = 'RGB' elif depth == 4: self.order = 'RGBA'
[ "def", "_calc_order", "(", "self", ",", "order", ")", ":", "if", "order", "is", "not", "None", "and", "order", "!=", "''", ":", "self", ".", "order", "=", "order", ".", "upper", "(", ")", "else", ":", "shape", "=", "self", ".", "shape", "if", "le...
Called to set the order of a multi-channel image. The order should be determined by the loader, but this will make a best guess if passed `order` is `None`.
[ "Called", "to", "set", "the", "order", "of", "a", "multi", "-", "channel", "image", ".", "The", "order", "should", "be", "determined", "by", "the", "loader", "but", "this", "will", "make", "a", "best", "guess", "if", "passed", "order", "is", "None", "....
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/BaseImage.py#L221-L242
train
24,722
ejeschke/ginga
ginga/BaseImage.py
BaseImage.cutout_data
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None): """cut out data area based on coords. """ view = np.s_[y1:y2:ystep, x1:x2:xstep] data = self._slice(view) if astype: data = data.astype(astype, copy=False) return data
python
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None): """cut out data area based on coords. """ view = np.s_[y1:y2:ystep, x1:x2:xstep] data = self._slice(view) if astype: data = data.astype(astype, copy=False) return data
[ "def", "cutout_data", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "xstep", "=", "1", ",", "ystep", "=", "1", ",", "astype", "=", "None", ")", ":", "view", "=", "np", ".", "s_", "[", "y1", ":", "y2", ":", "ystep", ",", "x1"...
cut out data area based on coords.
[ "cut", "out", "data", "area", "based", "on", "coords", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/BaseImage.py#L293-L300
train
24,723
ejeschke/ginga
ginga/BaseImage.py
BaseImage.get_shape_mask
def get_shape_mask(self, shape_obj): """ Return full mask where True marks pixels within the given shape. """ wd, ht = self.get_size() yi = np.mgrid[:ht].reshape(-1, 1) xi = np.mgrid[:wd].reshape(1, -1) pts = np.asarray((xi, yi)).T contains = shape_obj.contains_pts(pts) return contains
python
def get_shape_mask(self, shape_obj): """ Return full mask where True marks pixels within the given shape. """ wd, ht = self.get_size() yi = np.mgrid[:ht].reshape(-1, 1) xi = np.mgrid[:wd].reshape(1, -1) pts = np.asarray((xi, yi)).T contains = shape_obj.contains_pts(pts) return contains
[ "def", "get_shape_mask", "(", "self", ",", "shape_obj", ")", ":", "wd", ",", "ht", "=", "self", ".", "get_size", "(", ")", "yi", "=", "np", ".", "mgrid", "[", ":", "ht", "]", ".", "reshape", "(", "-", "1", ",", "1", ")", "xi", "=", "np", ".",...
Return full mask where True marks pixels within the given shape.
[ "Return", "full", "mask", "where", "True", "marks", "pixels", "within", "the", "given", "shape", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/BaseImage.py#L348-L357
train
24,724
ejeschke/ginga
ginga/BaseImage.py
BaseImage.get_shape_view
def get_shape_view(self, shape_obj, avoid_oob=True): """ Calculate a bounding box in the data enclosing `shape_obj` and return a view that accesses it and a mask that is True only for pixels enclosed in the region. If `avoid_oob` is True (default) then the bounding box is clipped to avoid coordinates outside of the actual data. """ x1, y1, x2, y2 = [int(np.round(n)) for n in shape_obj.get_llur()] if avoid_oob: # avoid out of bounds indexes wd, ht = self.get_size() x1, x2 = max(0, x1), min(x2, wd - 1) y1, y2 = max(0, y1), min(y2, ht - 1) # calculate pixel containment mask in bbox yi = np.mgrid[y1:y2 + 1].reshape(-1, 1) xi = np.mgrid[x1:x2 + 1].reshape(1, -1) pts = np.asarray((xi, yi)).T contains = shape_obj.contains_pts(pts) view = np.s_[y1:y2 + 1, x1:x2 + 1] return (view, contains)
python
def get_shape_view(self, shape_obj, avoid_oob=True): """ Calculate a bounding box in the data enclosing `shape_obj` and return a view that accesses it and a mask that is True only for pixels enclosed in the region. If `avoid_oob` is True (default) then the bounding box is clipped to avoid coordinates outside of the actual data. """ x1, y1, x2, y2 = [int(np.round(n)) for n in shape_obj.get_llur()] if avoid_oob: # avoid out of bounds indexes wd, ht = self.get_size() x1, x2 = max(0, x1), min(x2, wd - 1) y1, y2 = max(0, y1), min(y2, ht - 1) # calculate pixel containment mask in bbox yi = np.mgrid[y1:y2 + 1].reshape(-1, 1) xi = np.mgrid[x1:x2 + 1].reshape(1, -1) pts = np.asarray((xi, yi)).T contains = shape_obj.contains_pts(pts) view = np.s_[y1:y2 + 1, x1:x2 + 1] return (view, contains)
[ "def", "get_shape_view", "(", "self", ",", "shape_obj", ",", "avoid_oob", "=", "True", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "[", "int", "(", "np", ".", "round", "(", "n", ")", ")", "for", "n", "in", "shape_obj", ".", "get_llur", ...
Calculate a bounding box in the data enclosing `shape_obj` and return a view that accesses it and a mask that is True only for pixels enclosed in the region. If `avoid_oob` is True (default) then the bounding box is clipped to avoid coordinates outside of the actual data.
[ "Calculate", "a", "bounding", "box", "in", "the", "data", "enclosing", "shape_obj", "and", "return", "a", "view", "that", "accesses", "it", "and", "a", "mask", "that", "is", "True", "only", "for", "pixels", "enclosed", "in", "the", "region", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/BaseImage.py#L359-L383
train
24,725
ejeschke/ginga
ginga/BaseImage.py
BaseImage.cutout_shape
def cutout_shape(self, shape_obj): """ Cut out and return a portion of the data corresponding to `shape_obj`. A masked numpy array is returned, where the pixels not enclosed in the shape are masked out. """ view, mask = self.get_shape_view(shape_obj) # cutout our enclosing (possibly shortened) bbox data = self._slice(view) # mask non-containing members mdata = np.ma.array(data, mask=np.logical_not(mask)) return mdata
python
def cutout_shape(self, shape_obj): """ Cut out and return a portion of the data corresponding to `shape_obj`. A masked numpy array is returned, where the pixels not enclosed in the shape are masked out. """ view, mask = self.get_shape_view(shape_obj) # cutout our enclosing (possibly shortened) bbox data = self._slice(view) # mask non-containing members mdata = np.ma.array(data, mask=np.logical_not(mask)) return mdata
[ "def", "cutout_shape", "(", "self", ",", "shape_obj", ")", ":", "view", ",", "mask", "=", "self", ".", "get_shape_view", "(", "shape_obj", ")", "# cutout our enclosing (possibly shortened) bbox", "data", "=", "self", ".", "_slice", "(", "view", ")", "# mask non-...
Cut out and return a portion of the data corresponding to `shape_obj`. A masked numpy array is returned, where the pixels not enclosed in the shape are masked out.
[ "Cut", "out", "and", "return", "a", "portion", "of", "the", "data", "corresponding", "to", "shape_obj", ".", "A", "masked", "numpy", "array", "is", "returned", "where", "the", "pixels", "not", "enclosed", "in", "the", "shape", "are", "masked", "out", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/BaseImage.py#L385-L399
train
24,726
ejeschke/ginga
ginga/misc/Callback.py
Callbacks.remove_callback
def remove_callback(self, name, fn, *args, **kwargs): """Remove a specific callback that was added. """ try: tup = (fn, args, kwargs) if tup in self.cb[name]: self.cb[name].remove(tup) except KeyError: raise CallbackError("No callback category of '%s'" % ( name))
python
def remove_callback(self, name, fn, *args, **kwargs): """Remove a specific callback that was added. """ try: tup = (fn, args, kwargs) if tup in self.cb[name]: self.cb[name].remove(tup) except KeyError: raise CallbackError("No callback category of '%s'" % ( name))
[ "def", "remove_callback", "(", "self", ",", "name", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tup", "=", "(", "fn", ",", "args", ",", "kwargs", ")", "if", "tup", "in", "self", ".", "cb", "[", "name", "]", ":...
Remove a specific callback that was added.
[ "Remove", "a", "specific", "callback", "that", "was", "added", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Callback.py#L83-L92
train
24,727
ejeschke/ginga
ginga/qtw/QtHelp.py
cmap2pixmap
def cmap2pixmap(cmap, steps=50): """Convert a Ginga colormap into a QPixmap """ import numpy as np inds = np.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [cmap.clst[int(x * n)] for x in inds] rgbas = [QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups] im = QImage(steps, 1, QImage.Format_Indexed8) im.setColorTable(rgbas) for i in range(steps): im.setPixel(i, 0, i) im = im.scaled(128, 32) pm = QPixmap.fromImage(im) return pm
python
def cmap2pixmap(cmap, steps=50): """Convert a Ginga colormap into a QPixmap """ import numpy as np inds = np.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [cmap.clst[int(x * n)] for x in inds] rgbas = [QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups] im = QImage(steps, 1, QImage.Format_Indexed8) im.setColorTable(rgbas) for i in range(steps): im.setPixel(i, 0, i) im = im.scaled(128, 32) pm = QPixmap.fromImage(im) return pm
[ "def", "cmap2pixmap", "(", "cmap", ",", "steps", "=", "50", ")", ":", "import", "numpy", "as", "np", "inds", "=", "np", ".", "linspace", "(", "0", ",", "1", ",", "steps", ")", "n", "=", "len", "(", "cmap", ".", "clst", ")", "-", "1", "tups", ...
Convert a Ginga colormap into a QPixmap
[ "Convert", "a", "Ginga", "colormap", "into", "a", "QPixmap" ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/QtHelp.py#L293-L309
train
24,728
ejeschke/ginga
ginga/qtw/QtHelp.py
Timer.start
def start(self, duration=None): """Start the timer. If `duration` is not None, it should specify the time to expiration in seconds. """ if duration is None: duration = self.duration self.set(duration)
python
def start(self, duration=None): """Start the timer. If `duration` is not None, it should specify the time to expiration in seconds. """ if duration is None: duration = self.duration self.set(duration)
[ "def", "start", "(", "self", ",", "duration", "=", "None", ")", ":", "if", "duration", "is", "None", ":", "duration", "=", "self", ".", "duration", "self", ".", "set", "(", "duration", ")" ]
Start the timer. If `duration` is not None, it should specify the time to expiration in seconds.
[ "Start", "the", "timer", ".", "If", "duration", "is", "not", "None", "it", "should", "specify", "the", "time", "to", "expiration", "in", "seconds", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/QtHelp.py#L258-L265
train
24,729
ejeschke/ginga
ginga/rv/plugins/ScreenShot.py
ScreenShot._snap_cb
def _snap_cb(self, w): """This function is called when the user clicks the 'Snap' button. """ # Clear the snap image viewer self.scrnimage.clear() self.scrnimage.redraw_now(whence=0) self.fv.update_pending() format = self.tosave_type if self._screen_size: # snap image using actual viewer self.fv.error_wrap(self.fitsimage.save_rgb_image_as_file, self.tmpname, format=format) else: # we will be using shot generator, not actual viewer. # check that shot generator size matches UI params self.check_and_adjust_dimensions() # copy background color of viewer to shot generator bg = self.fitsimage.get_bg() self.shot_generator.set_bg(*bg) # add the main canvas from channel viewer to shot generator c1 = self.fitsimage.get_canvas() c2 = self.shot_generator.get_canvas() c2.delete_all_objects(redraw=False) c2.add(c1, redraw=False) # hack to fix a few problem graphics self.shot_generator._imgobj = self.fitsimage._imgobj # scale of the shot generator should be the scale of channel # viewer multiplied by the ratio of window sizes scale_x, scale_y = self.fitsimage.get_scale_xy() c1_wd, c1_ht = self.fitsimage.get_window_size() c2_wd, c2_ht = self.shot_generator.get_window_size() scale_wd = float(c2_wd) / float(c1_wd) scale_ht = float(c2_ht) / float(c1_ht) scale = max(scale_wd, scale_ht) scale_x *= scale scale_y *= scale self.shot_generator.scale_to(scale_x, scale_y) self.fitsimage.copy_attributes(self.shot_generator, self.transfer_attrs) # snap image self.fv.error_wrap(self.shot_generator.save_rgb_image_as_file, self.tmpname, format=format) c2.delete_all_objects(redraw=False) self.shot_generator._imgobj = None self.saved_type = format img = RGBImage(logger=self.logger) img.load_file(self.tmpname) # load the snapped image into the screenshot viewer self.scrnimage.set_image(img)
python
def _snap_cb(self, w): """This function is called when the user clicks the 'Snap' button. """ # Clear the snap image viewer self.scrnimage.clear() self.scrnimage.redraw_now(whence=0) self.fv.update_pending() format = self.tosave_type if self._screen_size: # snap image using actual viewer self.fv.error_wrap(self.fitsimage.save_rgb_image_as_file, self.tmpname, format=format) else: # we will be using shot generator, not actual viewer. # check that shot generator size matches UI params self.check_and_adjust_dimensions() # copy background color of viewer to shot generator bg = self.fitsimage.get_bg() self.shot_generator.set_bg(*bg) # add the main canvas from channel viewer to shot generator c1 = self.fitsimage.get_canvas() c2 = self.shot_generator.get_canvas() c2.delete_all_objects(redraw=False) c2.add(c1, redraw=False) # hack to fix a few problem graphics self.shot_generator._imgobj = self.fitsimage._imgobj # scale of the shot generator should be the scale of channel # viewer multiplied by the ratio of window sizes scale_x, scale_y = self.fitsimage.get_scale_xy() c1_wd, c1_ht = self.fitsimage.get_window_size() c2_wd, c2_ht = self.shot_generator.get_window_size() scale_wd = float(c2_wd) / float(c1_wd) scale_ht = float(c2_ht) / float(c1_ht) scale = max(scale_wd, scale_ht) scale_x *= scale scale_y *= scale self.shot_generator.scale_to(scale_x, scale_y) self.fitsimage.copy_attributes(self.shot_generator, self.transfer_attrs) # snap image self.fv.error_wrap(self.shot_generator.save_rgb_image_as_file, self.tmpname, format=format) c2.delete_all_objects(redraw=False) self.shot_generator._imgobj = None self.saved_type = format img = RGBImage(logger=self.logger) img.load_file(self.tmpname) # load the snapped image into the screenshot viewer self.scrnimage.set_image(img)
[ "def", "_snap_cb", "(", "self", ",", "w", ")", ":", "# Clear the snap image viewer", "self", ".", "scrnimage", ".", "clear", "(", ")", "self", ".", "scrnimage", ".", "redraw_now", "(", "whence", "=", "0", ")", "self", ".", "fv", ".", "update_pending", "(...
This function is called when the user clicks the 'Snap' button.
[ "This", "function", "is", "called", "when", "the", "user", "clicks", "the", "Snap", "button", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ScreenShot.py#L272-L332
train
24,730
ejeschke/ginga
ginga/rv/plugins/ScreenShot.py
ScreenShot._save_cb
def _save_cb(self, w): """This function is called when the user clicks the 'Save' button. We save the last taken shot to the folder and name specified. """ format = self.saved_type if format is None: return self.fv.show_error("Please save an image first.") # create filename filename = self.w.name.get_text().strip() if len(filename) == 0: return self.fv.show_error("Please set a name for saving the file") self.save_name = filename if not filename.lower().endswith('.' + format): filename = filename + '.' + format # join to path path = self.w.folder.get_text().strip() if path == '': path = filename else: self.save_path = path path = os.path.join(path, filename) # copy last saved file self.fv.error_wrap(shutil.copyfile, self.tmpname, path)
python
def _save_cb(self, w): """This function is called when the user clicks the 'Save' button. We save the last taken shot to the folder and name specified. """ format = self.saved_type if format is None: return self.fv.show_error("Please save an image first.") # create filename filename = self.w.name.get_text().strip() if len(filename) == 0: return self.fv.show_error("Please set a name for saving the file") self.save_name = filename if not filename.lower().endswith('.' + format): filename = filename + '.' + format # join to path path = self.w.folder.get_text().strip() if path == '': path = filename else: self.save_path = path path = os.path.join(path, filename) # copy last saved file self.fv.error_wrap(shutil.copyfile, self.tmpname, path)
[ "def", "_save_cb", "(", "self", ",", "w", ")", ":", "format", "=", "self", ".", "saved_type", "if", "format", "is", "None", ":", "return", "self", ".", "fv", ".", "show_error", "(", "\"Please save an image first.\"", ")", "# create filename", "filename", "="...
This function is called when the user clicks the 'Save' button. We save the last taken shot to the folder and name specified.
[ "This", "function", "is", "called", "when", "the", "user", "clicks", "the", "Save", "button", ".", "We", "save", "the", "last", "taken", "shot", "to", "the", "folder", "and", "name", "specified", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ScreenShot.py#L354-L380
train
24,731
ejeschke/ginga
ginga/rv/plugins/ScreenShot.py
ScreenShot._lock_aspect_cb
def _lock_aspect_cb(self, w, tf): """This function is called when the user clicks the 'Lock aspect' checkbox. `tf` is True if checked, False otherwise. """ self._lock_aspect = tf self.w.aspect.set_enabled(tf) if self._lock_aspect: self._set_aspect_cb() else: wd, ht = self.get_wdht() _as = self.calc_aspect_str(wd, ht) self.w.aspect.set_text(_as)
python
def _lock_aspect_cb(self, w, tf): """This function is called when the user clicks the 'Lock aspect' checkbox. `tf` is True if checked, False otherwise. """ self._lock_aspect = tf self.w.aspect.set_enabled(tf) if self._lock_aspect: self._set_aspect_cb() else: wd, ht = self.get_wdht() _as = self.calc_aspect_str(wd, ht) self.w.aspect.set_text(_as)
[ "def", "_lock_aspect_cb", "(", "self", ",", "w", ",", "tf", ")", ":", "self", ".", "_lock_aspect", "=", "tf", "self", ".", "w", ".", "aspect", ".", "set_enabled", "(", "tf", ")", "if", "self", ".", "_lock_aspect", ":", "self", ".", "_set_aspect_cb", ...
This function is called when the user clicks the 'Lock aspect' checkbox. `tf` is True if checked, False otherwise.
[ "This", "function", "is", "called", "when", "the", "user", "clicks", "the", "Lock", "aspect", "checkbox", ".", "tf", "is", "True", "if", "checked", "False", "otherwise", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ScreenShot.py#L494-L505
train
24,732
ejeschke/ginga
ginga/rv/plugins/ScreenShot.py
ScreenShot._screen_size_cb
def _screen_size_cb(self, w, tf): """This function is called when the user clicks the 'Screen size' checkbox. `tf` is True if checked, False otherwise. """ self._screen_size = tf self.w.width.set_enabled(not tf) self.w.height.set_enabled(not tf) self.w.lock_aspect.set_enabled(not tf) if self._screen_size: wd, ht = self.fitsimage.get_window_size() self._configure_cb(self.fitsimage, wd, ht)
python
def _screen_size_cb(self, w, tf): """This function is called when the user clicks the 'Screen size' checkbox. `tf` is True if checked, False otherwise. """ self._screen_size = tf self.w.width.set_enabled(not tf) self.w.height.set_enabled(not tf) self.w.lock_aspect.set_enabled(not tf) if self._screen_size: wd, ht = self.fitsimage.get_window_size() self._configure_cb(self.fitsimage, wd, ht)
[ "def", "_screen_size_cb", "(", "self", ",", "w", ",", "tf", ")", ":", "self", ".", "_screen_size", "=", "tf", "self", ".", "w", ".", "width", ".", "set_enabled", "(", "not", "tf", ")", "self", ".", "w", ".", "height", ".", "set_enabled", "(", "not"...
This function is called when the user clicks the 'Screen size' checkbox. `tf` is True if checked, False otherwise.
[ "This", "function", "is", "called", "when", "the", "user", "clicks", "the", "Screen", "size", "checkbox", ".", "tf", "is", "True", "if", "checked", "False", "otherwise", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ScreenShot.py#L517-L527
train
24,733
ejeschke/ginga
ginga/util/io_asdf.py
load_asdf
def load_asdf(asdf_obj, data_key='sci', wcs_key='wcs', header_key='meta'): """ Load from an ASDF object. Parameters ---------- asdf_obj : obj ASDF or ASDF-in-FITS object. data_key, wcs_key, header_key : str Key values to specify where to find data, WCS, and header in ASDF. Returns ------- data : ndarray or `None` Image data, if found. wcs : obj or `None` GWCS object or models, if found. ahdr : dict Header containing metadata. """ asdf_keys = asdf_obj.keys() if wcs_key in asdf_keys: wcs = asdf_obj[wcs_key] else: wcs = None if header_key in asdf_keys: ahdr = asdf_obj[header_key] else: ahdr = {} # TODO: What about non-image ASDF data, such as table? if data_key in asdf_keys: data = np.asarray(asdf_obj[data_key]) else: data = None return data, wcs, ahdr
python
def load_asdf(asdf_obj, data_key='sci', wcs_key='wcs', header_key='meta'): """ Load from an ASDF object. Parameters ---------- asdf_obj : obj ASDF or ASDF-in-FITS object. data_key, wcs_key, header_key : str Key values to specify where to find data, WCS, and header in ASDF. Returns ------- data : ndarray or `None` Image data, if found. wcs : obj or `None` GWCS object or models, if found. ahdr : dict Header containing metadata. """ asdf_keys = asdf_obj.keys() if wcs_key in asdf_keys: wcs = asdf_obj[wcs_key] else: wcs = None if header_key in asdf_keys: ahdr = asdf_obj[header_key] else: ahdr = {} # TODO: What about non-image ASDF data, such as table? if data_key in asdf_keys: data = np.asarray(asdf_obj[data_key]) else: data = None return data, wcs, ahdr
[ "def", "load_asdf", "(", "asdf_obj", ",", "data_key", "=", "'sci'", ",", "wcs_key", "=", "'wcs'", ",", "header_key", "=", "'meta'", ")", ":", "asdf_keys", "=", "asdf_obj", ".", "keys", "(", ")", "if", "wcs_key", "in", "asdf_keys", ":", "wcs", "=", "asd...
Load from an ASDF object. Parameters ---------- asdf_obj : obj ASDF or ASDF-in-FITS object. data_key, wcs_key, header_key : str Key values to specify where to find data, WCS, and header in ASDF. Returns ------- data : ndarray or `None` Image data, if found. wcs : obj or `None` GWCS object or models, if found. ahdr : dict Header containing metadata.
[ "Load", "from", "an", "ASDF", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/io_asdf.py#L23-L66
train
24,734
ejeschke/ginga
ginga/rv/plugins/Colorbar.py
Colorbar._match_cmap
def _match_cmap(self, fitsimage, colorbar): """ Help method to change the ColorBar to match the cut levels or colormap used in a ginga ImageView. """ rgbmap = fitsimage.get_rgbmap() loval, hival = fitsimage.get_cut_levels() colorbar.set_range(loval, hival) # If we are sharing a ColorBar for all channels, then store # to change the ColorBar's rgbmap to match our colorbar.set_rgbmap(rgbmap)
python
def _match_cmap(self, fitsimage, colorbar): """ Help method to change the ColorBar to match the cut levels or colormap used in a ginga ImageView. """ rgbmap = fitsimage.get_rgbmap() loval, hival = fitsimage.get_cut_levels() colorbar.set_range(loval, hival) # If we are sharing a ColorBar for all channels, then store # to change the ColorBar's rgbmap to match our colorbar.set_rgbmap(rgbmap)
[ "def", "_match_cmap", "(", "self", ",", "fitsimage", ",", "colorbar", ")", ":", "rgbmap", "=", "fitsimage", ".", "get_rgbmap", "(", ")", "loval", ",", "hival", "=", "fitsimage", ".", "get_cut_levels", "(", ")", "colorbar", ".", "set_range", "(", "loval", ...
Help method to change the ColorBar to match the cut levels or colormap used in a ginga ImageView.
[ "Help", "method", "to", "change", "the", "ColorBar", "to", "match", "the", "cut", "levels", "or", "colormap", "used", "in", "a", "ginga", "ImageView", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Colorbar.py#L88-L98
train
24,735
ejeschke/ginga
ginga/rv/plugins/Colorbar.py
Colorbar.rgbmap_cb
def rgbmap_cb(self, rgbmap, channel): """ This method is called when the RGBMap is changed. We update the ColorBar to match. """ if not self.gui_up: return fitsimage = channel.fitsimage if fitsimage != self.fv.getfocus_fitsimage(): return False self.change_cbar(self.fv, channel)
python
def rgbmap_cb(self, rgbmap, channel): """ This method is called when the RGBMap is changed. We update the ColorBar to match. """ if not self.gui_up: return fitsimage = channel.fitsimage if fitsimage != self.fv.getfocus_fitsimage(): return False self.change_cbar(self.fv, channel)
[ "def", "rgbmap_cb", "(", "self", ",", "rgbmap", ",", "channel", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "fitsimage", "=", "channel", ".", "fitsimage", "if", "fitsimage", "!=", "self", ".", "fv", ".", "getfocus_fitsimage", "(", ")", ...
This method is called when the RGBMap is changed. We update the ColorBar to match.
[ "This", "method", "is", "called", "when", "the", "RGBMap", "is", "changed", ".", "We", "update", "the", "ColorBar", "to", "match", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Colorbar.py#L130-L140
train
24,736
ejeschke/ginga
ginga/util/addons.py
show_mode_indicator
def show_mode_indicator(viewer, tf, corner='ur'): """Show a keyboard mode indicator in one of the corners. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the mark; else remove it if present. corner : str One of 'll', 'lr', 'ul' or 'ur' selecting a corner. The default is 'ur'. """ tag = '_$mode_indicator' canvas = viewer.get_private_canvas() try: indic = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: indic.corner = corner except KeyError: if tf: # force a redraw if the mode changes bm = viewer.get_bindmap() bm.add_callback('mode-set', lambda *args: viewer.redraw(whence=3)) Indicator = canvas.get_draw_class('modeindicator') canvas.add(Indicator(corner=corner), tag=tag, redraw=False) canvas.update_canvas(whence=3)
python
def show_mode_indicator(viewer, tf, corner='ur'): """Show a keyboard mode indicator in one of the corners. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the mark; else remove it if present. corner : str One of 'll', 'lr', 'ul' or 'ur' selecting a corner. The default is 'ur'. """ tag = '_$mode_indicator' canvas = viewer.get_private_canvas() try: indic = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: indic.corner = corner except KeyError: if tf: # force a redraw if the mode changes bm = viewer.get_bindmap() bm.add_callback('mode-set', lambda *args: viewer.redraw(whence=3)) Indicator = canvas.get_draw_class('modeindicator') canvas.add(Indicator(corner=corner), tag=tag, redraw=False) canvas.update_canvas(whence=3)
[ "def", "show_mode_indicator", "(", "viewer", ",", "tf", ",", "corner", "=", "'ur'", ")", ":", "tag", "=", "'_$mode_indicator'", "canvas", "=", "viewer", ".", "get_private_canvas", "(", ")", "try", ":", "indic", "=", "canvas", ".", "get_object_by_tag", "(", ...
Show a keyboard mode indicator in one of the corners. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the mark; else remove it if present. corner : str One of 'll', 'lr', 'ul' or 'ur' selecting a corner. The default is 'ur'.
[ "Show", "a", "keyboard", "mode", "indicator", "in", "one", "of", "the", "corners", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/addons.py#L44-L81
train
24,737
ejeschke/ginga
ginga/util/addons.py
show_color_bar
def show_color_bar(viewer, tf, side='bottom'): """Show a color bar in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. side : str One of 'top' or 'bottom'. The default is 'bottom'. """ tag = '_$color_bar' canvas = viewer.get_private_canvas() try: cbar = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: cbar.side = side except KeyError: if tf: Cbar = canvas.get_draw_class('colorbar') canvas.add(Cbar(side=side), tag=tag, redraw=False) canvas.update_canvas(whence=3)
python
def show_color_bar(viewer, tf, side='bottom'): """Show a color bar in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. side : str One of 'top' or 'bottom'. The default is 'bottom'. """ tag = '_$color_bar' canvas = viewer.get_private_canvas() try: cbar = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: cbar.side = side except KeyError: if tf: Cbar = canvas.get_draw_class('colorbar') canvas.add(Cbar(side=side), tag=tag, redraw=False) canvas.update_canvas(whence=3)
[ "def", "show_color_bar", "(", "viewer", ",", "tf", ",", "side", "=", "'bottom'", ")", ":", "tag", "=", "'_$color_bar'", "canvas", "=", "viewer", ".", "get_private_canvas", "(", ")", "try", ":", "cbar", "=", "canvas", ".", "get_object_by_tag", "(", "tag", ...
Show a color bar in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. side : str One of 'top' or 'bottom'. The default is 'bottom'.
[ "Show", "a", "color", "bar", "in", "the", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/addons.py#L84-L114
train
24,738
ejeschke/ginga
ginga/util/addons.py
show_focus_indicator
def show_focus_indicator(viewer, tf, color='white'): """Show a focus indicator in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. color : str Color for the focus indicator. """ tag = '_$focus_indicator' canvas = viewer.get_private_canvas() try: fcsi = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: fcsi.color = color except KeyError: if tf: Fcsi = canvas.get_draw_class('focusindicator') fcsi = Fcsi(color=color) canvas.add(fcsi, tag=tag, redraw=False) viewer.add_callback('focus', fcsi.focus_cb) canvas.update_canvas(whence=3)
python
def show_focus_indicator(viewer, tf, color='white'): """Show a focus indicator in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. color : str Color for the focus indicator. """ tag = '_$focus_indicator' canvas = viewer.get_private_canvas() try: fcsi = canvas.get_object_by_tag(tag) if not tf: canvas.delete_object_by_tag(tag) else: fcsi.color = color except KeyError: if tf: Fcsi = canvas.get_draw_class('focusindicator') fcsi = Fcsi(color=color) canvas.add(fcsi, tag=tag, redraw=False) viewer.add_callback('focus', fcsi.focus_cb) canvas.update_canvas(whence=3)
[ "def", "show_focus_indicator", "(", "viewer", ",", "tf", ",", "color", "=", "'white'", ")", ":", "tag", "=", "'_$focus_indicator'", "canvas", "=", "viewer", ".", "get_private_canvas", "(", ")", "try", ":", "fcsi", "=", "canvas", ".", "get_object_by_tag", "("...
Show a focus indicator in the window. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. tf : bool If True, show the color bar; else remove it if present. color : str Color for the focus indicator.
[ "Show", "a", "focus", "indicator", "in", "the", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/addons.py#L117-L149
train
24,739
ejeschke/ginga
ginga/util/addons.py
add_zoom_buttons
def add_zoom_buttons(viewer, canvas=None, color='black'): """Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should be added. If not supplied defaults to the private canvas of the viewer. color : str A color name, hex triplet. The default is 'black'. """ def zoom(box, canvas, event, pt, viewer, n): zl = viewer.get_zoom() zl += n if zl == 0.0: zl += n viewer.zoom_to(zl + n) def add_buttons(viewer, canvas, tag): objs = [] wd, ht = viewer.get_window_size() SquareBox = canvas.get_draw_class('squarebox') Text = canvas.get_draw_class('text') Compound = canvas.get_draw_class('compoundobject') x1, y1 = wd - 20, ht // 2 + 20 zoomin = SquareBox(x1, y1, 15, color='yellow', fill=True, fillcolor='gray', fillalpha=0.5, coord='window') zoomin.editable = False zoomin.pickable = True zoomin.add_callback('pick-down', zoom, viewer, 1) objs.append(zoomin) x2, y2 = wd - 20, ht // 2 - 20 zoomout = SquareBox(x2, y2, 15, color='yellow', fill=True, fillcolor='gray', fillalpha=0.5, coord='window') zoomout.editable = False zoomout.pickable = True zoomout.add_callback('pick-down', zoom, viewer, -1) objs.append(zoomout) objs.append(Text(x1 - 4, y1 + 6, text='+', fontsize=18, color=color, coord='window')) objs.append(Text(x2 - 4, y2 + 6, text='--', fontsize=18, color=color, coord='window')) obj = Compound(*objs) obj.opaque = False canvas.add(obj, tag=tag) def zoom_resize(viewer, width, height, canvas, tag): try: canvas.get_object_by_tag(tag) except KeyError: return False canvas.delete_object_by_tag(tag) add_buttons(viewer, canvas, tag) tag = '_$zoom_buttons' if canvas is None: canvas = viewer.get_private_canvas() canvas.ui_set_active(True) canvas.register_for_cursor_drawing(viewer) canvas.set_draw_mode('pick') viewer.add_callback('configure', zoom_resize, canvas, tag) add_buttons(viewer, canvas, tag)
python
def add_zoom_buttons(viewer, canvas=None, color='black'): """Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should be added. If not supplied defaults to the private canvas of the viewer. color : str A color name, hex triplet. The default is 'black'. """ def zoom(box, canvas, event, pt, viewer, n): zl = viewer.get_zoom() zl += n if zl == 0.0: zl += n viewer.zoom_to(zl + n) def add_buttons(viewer, canvas, tag): objs = [] wd, ht = viewer.get_window_size() SquareBox = canvas.get_draw_class('squarebox') Text = canvas.get_draw_class('text') Compound = canvas.get_draw_class('compoundobject') x1, y1 = wd - 20, ht // 2 + 20 zoomin = SquareBox(x1, y1, 15, color='yellow', fill=True, fillcolor='gray', fillalpha=0.5, coord='window') zoomin.editable = False zoomin.pickable = True zoomin.add_callback('pick-down', zoom, viewer, 1) objs.append(zoomin) x2, y2 = wd - 20, ht // 2 - 20 zoomout = SquareBox(x2, y2, 15, color='yellow', fill=True, fillcolor='gray', fillalpha=0.5, coord='window') zoomout.editable = False zoomout.pickable = True zoomout.add_callback('pick-down', zoom, viewer, -1) objs.append(zoomout) objs.append(Text(x1 - 4, y1 + 6, text='+', fontsize=18, color=color, coord='window')) objs.append(Text(x2 - 4, y2 + 6, text='--', fontsize=18, color=color, coord='window')) obj = Compound(*objs) obj.opaque = False canvas.add(obj, tag=tag) def zoom_resize(viewer, width, height, canvas, tag): try: canvas.get_object_by_tag(tag) except KeyError: return False canvas.delete_object_by_tag(tag) add_buttons(viewer, canvas, tag) tag = '_$zoom_buttons' if canvas is None: canvas = viewer.get_private_canvas() canvas.ui_set_active(True) canvas.register_for_cursor_drawing(viewer) canvas.set_draw_mode('pick') viewer.add_callback('configure', zoom_resize, canvas, tag) add_buttons(viewer, canvas, tag)
[ "def", "add_zoom_buttons", "(", "viewer", ",", "canvas", "=", "None", ",", "color", "=", "'black'", ")", ":", "def", "zoom", "(", "box", ",", "canvas", ",", "event", ",", "pt", ",", "viewer", ",", "n", ")", ":", "zl", "=", "viewer", ".", "get_zoom"...
Add zoom buttons to a canvas. Parameters ---------- viewer : an ImageView subclass instance If True, show the color bar; else remove it if present. canvas : a DrawingCanvas instance The canvas to which the buttons should be added. If not supplied defaults to the private canvas of the viewer. color : str A color name, hex triplet. The default is 'black'.
[ "Add", "zoom", "buttons", "to", "a", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/addons.py#L152-L220
train
24,740
ejeschke/ginga
ginga/gtkw/ImageViewGtk.py
ImageViewGtk.expose_event
def expose_event(self, widget, event): """When an area of the window is exposed, we just copy out of the server-side, off-screen surface to that area. """ x, y, width, height = event.area self.logger.debug("surface is %s" % self.surface) if self.surface is not None: win = widget.get_window() cr = win.cairo_create() # set clip area for exposed region cr.rectangle(x, y, width, height) cr.clip() # Paint from off-screen surface cr.set_source_surface(self.surface, 0, 0) cr.set_operator(cairo.OPERATOR_SOURCE) cr.paint() return False
python
def expose_event(self, widget, event): """When an area of the window is exposed, we just copy out of the server-side, off-screen surface to that area. """ x, y, width, height = event.area self.logger.debug("surface is %s" % self.surface) if self.surface is not None: win = widget.get_window() cr = win.cairo_create() # set clip area for exposed region cr.rectangle(x, y, width, height) cr.clip() # Paint from off-screen surface cr.set_source_surface(self.surface, 0, 0) cr.set_operator(cairo.OPERATOR_SOURCE) cr.paint() return False
[ "def", "expose_event", "(", "self", ",", "widget", ",", "event", ")", ":", "x", ",", "y", ",", "width", ",", "height", "=", "event", ".", "area", "self", ".", "logger", ".", "debug", "(", "\"surface is %s\"", "%", "self", ".", "surface", ")", "if", ...
When an area of the window is exposed, we just copy out of the server-side, off-screen surface to that area.
[ "When", "an", "area", "of", "the", "window", "is", "exposed", "we", "just", "copy", "out", "of", "the", "server", "-", "side", "off", "-", "screen", "surface", "to", "that", "area", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtkw/ImageViewGtk.py#L150-L169
train
24,741
ejeschke/ginga
ginga/gtkw/ImageViewGtk.py
ImageViewGtk.size_request
def size_request(self, widget, requisition): """Callback function to request our desired size. """ requisition.width, requisition.height = self.get_desired_size() return True
python
def size_request(self, widget, requisition): """Callback function to request our desired size. """ requisition.width, requisition.height = self.get_desired_size() return True
[ "def", "size_request", "(", "self", ",", "widget", ",", "requisition", ")", ":", "requisition", ".", "width", ",", "requisition", ".", "height", "=", "self", ".", "get_desired_size", "(", ")", "return", "True" ]
Callback function to request our desired size.
[ "Callback", "function", "to", "request", "our", "desired", "size", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtkw/ImageViewGtk.py#L195-L199
train
24,742
ejeschke/ginga
ginga/rv/Control.py
GingaShell.get_plugin_spec
def get_plugin_spec(self, name): """Get the specification attributes for plugin with name `name`.""" l_name = name.lower() for spec in self.plugins: name = spec.get('name', spec.get('klass', spec.module)) if name.lower() == l_name: return spec raise KeyError(name)
python
def get_plugin_spec(self, name): """Get the specification attributes for plugin with name `name`.""" l_name = name.lower() for spec in self.plugins: name = spec.get('name', spec.get('klass', spec.module)) if name.lower() == l_name: return spec raise KeyError(name)
[ "def", "get_plugin_spec", "(", "self", ",", "name", ")", ":", "l_name", "=", "name", ".", "lower", "(", ")", "for", "spec", "in", "self", ".", "plugins", ":", "name", "=", "spec", ".", "get", "(", "'name'", ",", "spec", ".", "get", "(", "'klass'", ...
Get the specification attributes for plugin with name `name`.
[ "Get", "the", "specification", "attributes", "for", "plugin", "with", "name", "name", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L397-L404
train
24,743
ejeschke/ginga
ginga/rv/Control.py
GingaShell.help_text
def help_text(self, name, text, text_kind='plain', trim_pfx=0): """ Provide help text for the user. This method will convert the text as necessary with docutils and display it in the WBrowser plugin, if available. If the plugin is not available and the text is type 'rst' then the text will be displayed in a plain text widget. Parameters ---------- name : str Category of help to show. text : str The text to show. Should be plain, HTML or RST text text_kind : str (optional) One of 'plain', 'html', 'rst'. Default is 'plain'. trim_pfx : int (optional) Number of spaces to trim off the beginning of each line of text. """ if trim_pfx > 0: # caller wants to trim some space off the front # of each line text = toolbox.trim_prefix(text, trim_pfx) if text_kind == 'rst': # try to convert RST to HTML using docutils try: overrides = {'input_encoding': 'ascii', 'output_encoding': 'utf-8'} text_html = publish_string(text, writer_name='html', settings_overrides=overrides) # docutils produces 'bytes' output, but webkit needs # a utf-8 string text = text_html.decode('utf-8') text_kind = 'html' except Exception as e: self.logger.error("Error converting help text to HTML: %s" % ( str(e))) # revert to showing RST as plain text else: raise ValueError( "I don't know how to display text of kind '%s'" % (text_kind)) if text_kind == 'html': self.help(text=text, text_kind='html') else: self.show_help_text(name, text)
python
def help_text(self, name, text, text_kind='plain', trim_pfx=0): """ Provide help text for the user. This method will convert the text as necessary with docutils and display it in the WBrowser plugin, if available. If the plugin is not available and the text is type 'rst' then the text will be displayed in a plain text widget. Parameters ---------- name : str Category of help to show. text : str The text to show. Should be plain, HTML or RST text text_kind : str (optional) One of 'plain', 'html', 'rst'. Default is 'plain'. trim_pfx : int (optional) Number of spaces to trim off the beginning of each line of text. """ if trim_pfx > 0: # caller wants to trim some space off the front # of each line text = toolbox.trim_prefix(text, trim_pfx) if text_kind == 'rst': # try to convert RST to HTML using docutils try: overrides = {'input_encoding': 'ascii', 'output_encoding': 'utf-8'} text_html = publish_string(text, writer_name='html', settings_overrides=overrides) # docutils produces 'bytes' output, but webkit needs # a utf-8 string text = text_html.decode('utf-8') text_kind = 'html' except Exception as e: self.logger.error("Error converting help text to HTML: %s" % ( str(e))) # revert to showing RST as plain text else: raise ValueError( "I don't know how to display text of kind '%s'" % (text_kind)) if text_kind == 'html': self.help(text=text, text_kind='html') else: self.show_help_text(name, text)
[ "def", "help_text", "(", "self", ",", "name", ",", "text", ",", "text_kind", "=", "'plain'", ",", "trim_pfx", "=", "0", ")", ":", "if", "trim_pfx", ">", "0", ":", "# caller wants to trim some space off the front", "# of each line", "text", "=", "toolbox", ".",...
Provide help text for the user. This method will convert the text as necessary with docutils and display it in the WBrowser plugin, if available. If the plugin is not available and the text is type 'rst' then the text will be displayed in a plain text widget. Parameters ---------- name : str Category of help to show. text : str The text to show. Should be plain, HTML or RST text text_kind : str (optional) One of 'plain', 'html', 'rst'. Default is 'plain'. trim_pfx : int (optional) Number of spaces to trim off the beginning of each line of text.
[ "Provide", "help", "text", "for", "the", "user", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L455-L510
train
24,744
ejeschke/ginga
ginga/rv/Control.py
GingaShell.load_file
def load_file(self, filepath, chname=None, wait=True, create_channel=True, display_image=True, image_loader=None): """Load a file and display it. Parameters ---------- filepath : str The path of the file to load (must reference a local file). chname : str, optional The name of the channel in which to display the image. wait : bool, optional If `True`, then wait for the file to be displayed before returning (synchronous behavior). create_channel : bool, optional Create channel. display_image : bool, optional If not `False`, then will load the image. image_loader : func, optional A special image loader, if provided. Returns ------- image The image object that was loaded. """ if not chname: channel = self.get_current_channel() else: if not self.has_channel(chname) and create_channel: self.gui_call(self.add_channel, chname) channel = self.get_channel(chname) chname = channel.name if image_loader is None: image_loader = self.load_image cache_dir = self.settings.get('download_folder', self.tmpdir) info = iohelper.get_fileinfo(filepath, cache_dir=cache_dir) # check that file is locally accessible if not info.ondisk: errmsg = "File must be locally loadable: %s" % (filepath) self.gui_do(self.show_error, errmsg) return filepath = info.filepath kwargs = {} idx = None if info.numhdu is not None: kwargs['idx'] = info.numhdu try: image = image_loader(filepath, **kwargs) except Exception as e: errmsg = "Failed to load '%s': %s" % (filepath, str(e)) self.gui_do(self.show_error, errmsg) return future = Future.Future() future.freeze(image_loader, filepath, **kwargs) # Save a future for this image to reload it later if we # have to remove it from memory image.set(loader=image_loader, image_future=future) if image.get('path', None) is None: image.set(path=filepath) # Assign a name to the image if the loader did not. name = image.get('name', None) if name is None: name = iohelper.name_image_from_path(filepath, idx=idx) image.set(name=name) if display_image: # Display image. If the wait parameter is False then don't wait # for the image to load into the viewer if wait: self.gui_call(self.add_image, name, image, chname=chname) else: self.gui_do(self.add_image, name, image, chname=chname) else: self.gui_do(self.bulk_add_image, name, image, chname) # Return the image return image
python
def load_file(self, filepath, chname=None, wait=True, create_channel=True, display_image=True, image_loader=None): """Load a file and display it. Parameters ---------- filepath : str The path of the file to load (must reference a local file). chname : str, optional The name of the channel in which to display the image. wait : bool, optional If `True`, then wait for the file to be displayed before returning (synchronous behavior). create_channel : bool, optional Create channel. display_image : bool, optional If not `False`, then will load the image. image_loader : func, optional A special image loader, if provided. Returns ------- image The image object that was loaded. """ if not chname: channel = self.get_current_channel() else: if not self.has_channel(chname) and create_channel: self.gui_call(self.add_channel, chname) channel = self.get_channel(chname) chname = channel.name if image_loader is None: image_loader = self.load_image cache_dir = self.settings.get('download_folder', self.tmpdir) info = iohelper.get_fileinfo(filepath, cache_dir=cache_dir) # check that file is locally accessible if not info.ondisk: errmsg = "File must be locally loadable: %s" % (filepath) self.gui_do(self.show_error, errmsg) return filepath = info.filepath kwargs = {} idx = None if info.numhdu is not None: kwargs['idx'] = info.numhdu try: image = image_loader(filepath, **kwargs) except Exception as e: errmsg = "Failed to load '%s': %s" % (filepath, str(e)) self.gui_do(self.show_error, errmsg) return future = Future.Future() future.freeze(image_loader, filepath, **kwargs) # Save a future for this image to reload it later if we # have to remove it from memory image.set(loader=image_loader, image_future=future) if image.get('path', None) is None: image.set(path=filepath) # Assign a name to the image if the loader did not. name = image.get('name', None) if name is None: name = iohelper.name_image_from_path(filepath, idx=idx) image.set(name=name) if display_image: # Display image. If the wait parameter is False then don't wait # for the image to load into the viewer if wait: self.gui_call(self.add_image, name, image, chname=chname) else: self.gui_do(self.add_image, name, image, chname=chname) else: self.gui_do(self.bulk_add_image, name, image, chname) # Return the image return image
[ "def", "load_file", "(", "self", ",", "filepath", ",", "chname", "=", "None", ",", "wait", "=", "True", ",", "create_channel", "=", "True", ",", "display_image", "=", "True", ",", "image_loader", "=", "None", ")", ":", "if", "not", "chname", ":", "chan...
Load a file and display it. Parameters ---------- filepath : str The path of the file to load (must reference a local file). chname : str, optional The name of the channel in which to display the image. wait : bool, optional If `True`, then wait for the file to be displayed before returning (synchronous behavior). create_channel : bool, optional Create channel. display_image : bool, optional If not `False`, then will load the image. image_loader : func, optional A special image loader, if provided. Returns ------- image The image object that was loaded.
[ "Load", "a", "file", "and", "display", "it", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L615-L710
train
24,745
ejeschke/ginga
ginga/rv/Control.py
GingaShell.add_download
def add_download(self, info, future): """ Hand off a download to the Downloads plugin, if it is present. Parameters ---------- info : `~ginga.misc.Bunch.Bunch` A bunch of information about the URI as returned by `ginga.util.iohelper.get_fileinfo()` future : `~ginga.misc.Future.Future` A future that represents the future computation to be performed after downloading the file. Resolving the future will trigger the computation. """ if self.gpmon.has_plugin('Downloads'): obj = self.gpmon.get_plugin('Downloads') self.gui_do(obj.add_download, info, future) else: self.show_error("Please activate the 'Downloads' plugin to" " enable download functionality")
python
def add_download(self, info, future): """ Hand off a download to the Downloads plugin, if it is present. Parameters ---------- info : `~ginga.misc.Bunch.Bunch` A bunch of information about the URI as returned by `ginga.util.iohelper.get_fileinfo()` future : `~ginga.misc.Future.Future` A future that represents the future computation to be performed after downloading the file. Resolving the future will trigger the computation. """ if self.gpmon.has_plugin('Downloads'): obj = self.gpmon.get_plugin('Downloads') self.gui_do(obj.add_download, info, future) else: self.show_error("Please activate the 'Downloads' plugin to" " enable download functionality")
[ "def", "add_download", "(", "self", ",", "info", ",", "future", ")", ":", "if", "self", ".", "gpmon", ".", "has_plugin", "(", "'Downloads'", ")", ":", "obj", "=", "self", ".", "gpmon", ".", "get_plugin", "(", "'Downloads'", ")", "self", ".", "gui_do", ...
Hand off a download to the Downloads plugin, if it is present. Parameters ---------- info : `~ginga.misc.Bunch.Bunch` A bunch of information about the URI as returned by `ginga.util.iohelper.get_fileinfo()` future : `~ginga.misc.Future.Future` A future that represents the future computation to be performed after downloading the file. Resolving the future will trigger the computation.
[ "Hand", "off", "a", "download", "to", "the", "Downloads", "plugin", "if", "it", "is", "present", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L712-L732
train
24,746
ejeschke/ginga
ginga/rv/Control.py
GingaShell.open_file_cont
def open_file_cont(self, pathspec, loader_cont_fn): """Open a file and do some action on it. Parameters ---------- pathspec : str The path of the file to load (can be a URI, but must reference a local file). loader_cont_fn : func (data_obj) -> None A continuation consisting of a function of one argument that does something with the data_obj created by the loader """ info = iohelper.get_fileinfo(pathspec) filepath = info.filepath if not os.path.exists(filepath): errmsg = "File does not appear to exist: '%s'" % (filepath) self.gui_do(self.show_error, errmsg) return try: typ, subtyp = iohelper.guess_filetype(filepath) except Exception as e: self.logger.warning("error determining file type: %s; " "assuming 'image/fits'" % (str(e))) # Can't determine file type: assume and attempt FITS typ, subtyp = 'image', 'fits' mimetype = "%s/%s" % (typ, subtyp) try: opener_class = loader.get_opener(mimetype) except KeyError: # TODO: here pop up a dialog asking which loader to use errmsg = "No registered opener for: '%s'" % (mimetype) self.gui_do(self.show_error, errmsg) return # kwd args to pass to opener kwargs = dict() inherit_prihdr = self.settings.get('inherit_primary_header', False) kwargs['inherit_primary_header'] = inherit_prihdr # open the file and load the items named by the index opener = opener_class(self.logger) try: with opener.open_file(filepath) as io_f: io_f.load_idx_cont(info.idx, loader_cont_fn, **kwargs) except Exception as e: errmsg = "Error opening '%s': %s" % (filepath, str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "\n".join(traceback.format_tb(tb)) except Exception as e: tb_str = "Traceback information unavailable." self.gui_do(self.show_error, errmsg + '\n' + tb_str)
python
def open_file_cont(self, pathspec, loader_cont_fn): """Open a file and do some action on it. Parameters ---------- pathspec : str The path of the file to load (can be a URI, but must reference a local file). loader_cont_fn : func (data_obj) -> None A continuation consisting of a function of one argument that does something with the data_obj created by the loader """ info = iohelper.get_fileinfo(pathspec) filepath = info.filepath if not os.path.exists(filepath): errmsg = "File does not appear to exist: '%s'" % (filepath) self.gui_do(self.show_error, errmsg) return try: typ, subtyp = iohelper.guess_filetype(filepath) except Exception as e: self.logger.warning("error determining file type: %s; " "assuming 'image/fits'" % (str(e))) # Can't determine file type: assume and attempt FITS typ, subtyp = 'image', 'fits' mimetype = "%s/%s" % (typ, subtyp) try: opener_class = loader.get_opener(mimetype) except KeyError: # TODO: here pop up a dialog asking which loader to use errmsg = "No registered opener for: '%s'" % (mimetype) self.gui_do(self.show_error, errmsg) return # kwd args to pass to opener kwargs = dict() inherit_prihdr = self.settings.get('inherit_primary_header', False) kwargs['inherit_primary_header'] = inherit_prihdr # open the file and load the items named by the index opener = opener_class(self.logger) try: with opener.open_file(filepath) as io_f: io_f.load_idx_cont(info.idx, loader_cont_fn, **kwargs) except Exception as e: errmsg = "Error opening '%s': %s" % (filepath, str(e)) try: (type, value, tb) = sys.exc_info() tb_str = "\n".join(traceback.format_tb(tb)) except Exception as e: tb_str = "Traceback information unavailable." self.gui_do(self.show_error, errmsg + '\n' + tb_str)
[ "def", "open_file_cont", "(", "self", ",", "pathspec", ",", "loader_cont_fn", ")", ":", "info", "=", "iohelper", ".", "get_fileinfo", "(", "pathspec", ")", "filepath", "=", "info", ".", "filepath", "if", "not", "os", ".", "path", ".", "exists", "(", "fil...
Open a file and do some action on it. Parameters ---------- pathspec : str The path of the file to load (can be a URI, but must reference a local file). loader_cont_fn : func (data_obj) -> None A continuation consisting of a function of one argument that does something with the data_obj created by the loader
[ "Open", "a", "file", "and", "do", "some", "action", "on", "it", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L772-L833
train
24,747
ejeschke/ginga
ginga/rv/Control.py
GingaShell.open_uris
def open_uris(self, uris, chname=None, bulk_add=False): """Open a set of URIs. Parameters ---------- uris : list of str The URIs of the files to load chname: str, optional (defaults to channel with focus) The name of the channel in which to load the items bulk_add : bool, optional (defaults to False) If True, then all the data items are loaded into the channel without disturbing the current item there. If False, then the first item loaded will be displayed and the rest of the items will be loaded as bulk. """ if len(uris) == 0: return if chname is None: channel = self.get_channel_info() if channel is None: # No active channel to load these into return chname = channel.name channel = self.get_channel_on_demand(chname) def show_dataobj_bulk(data_obj): self.gui_do(channel.add_image, data_obj, bulk_add=True) def load_file_bulk(filepath): self.nongui_do(self.open_file_cont, filepath, show_dataobj_bulk) def show_dataobj(data_obj): self.gui_do(channel.add_image, data_obj, bulk_add=False) def load_file(filepath): self.nongui_do(self.open_file_cont, filepath, show_dataobj) # determine whether first file is loaded as a bulk load if bulk_add: self.open_uri_cont(uris[0], load_file_bulk) else: self.open_uri_cont(uris[0], load_file) self.update_pending() for uri in uris[1:]: # rest of files are all loaded using bulk load self.open_uri_cont(uri, load_file_bulk) self.update_pending()
python
def open_uris(self, uris, chname=None, bulk_add=False): """Open a set of URIs. Parameters ---------- uris : list of str The URIs of the files to load chname: str, optional (defaults to channel with focus) The name of the channel in which to load the items bulk_add : bool, optional (defaults to False) If True, then all the data items are loaded into the channel without disturbing the current item there. If False, then the first item loaded will be displayed and the rest of the items will be loaded as bulk. """ if len(uris) == 0: return if chname is None: channel = self.get_channel_info() if channel is None: # No active channel to load these into return chname = channel.name channel = self.get_channel_on_demand(chname) def show_dataobj_bulk(data_obj): self.gui_do(channel.add_image, data_obj, bulk_add=True) def load_file_bulk(filepath): self.nongui_do(self.open_file_cont, filepath, show_dataobj_bulk) def show_dataobj(data_obj): self.gui_do(channel.add_image, data_obj, bulk_add=False) def load_file(filepath): self.nongui_do(self.open_file_cont, filepath, show_dataobj) # determine whether first file is loaded as a bulk load if bulk_add: self.open_uri_cont(uris[0], load_file_bulk) else: self.open_uri_cont(uris[0], load_file) self.update_pending() for uri in uris[1:]: # rest of files are all loaded using bulk load self.open_uri_cont(uri, load_file_bulk) self.update_pending()
[ "def", "open_uris", "(", "self", ",", "uris", ",", "chname", "=", "None", ",", "bulk_add", "=", "False", ")", ":", "if", "len", "(", "uris", ")", "==", "0", ":", "return", "if", "chname", "is", "None", ":", "channel", "=", "self", ".", "get_channel...
Open a set of URIs. Parameters ---------- uris : list of str The URIs of the files to load chname: str, optional (defaults to channel with focus) The name of the channel in which to load the items bulk_add : bool, optional (defaults to False) If True, then all the data items are loaded into the channel without disturbing the current item there. If False, then the first item loaded will be displayed and the rest of the items will be loaded as bulk.
[ "Open", "a", "set", "of", "URIs", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L835-L886
train
24,748
ejeschke/ginga
ginga/rv/Control.py
GingaShell.zoom_in
def zoom_in(self): """Zoom the view in one zoom step. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_in'): viewer.zoom_in() return True
python
def zoom_in(self): """Zoom the view in one zoom step. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_in'): viewer.zoom_in() return True
[ "def", "zoom_in", "(", "self", ")", ":", "viewer", "=", "self", ".", "getfocus_viewer", "(", ")", "if", "hasattr", "(", "viewer", ",", "'zoom_in'", ")", ":", "viewer", ".", "zoom_in", "(", ")", "return", "True" ]
Zoom the view in one zoom step.
[ "Zoom", "the", "view", "in", "one", "zoom", "step", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L923-L929
train
24,749
ejeschke/ginga
ginga/rv/Control.py
GingaShell.zoom_out
def zoom_out(self): """Zoom the view out one zoom step. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_out'): viewer.zoom_out() return True
python
def zoom_out(self): """Zoom the view out one zoom step. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_out'): viewer.zoom_out() return True
[ "def", "zoom_out", "(", "self", ")", ":", "viewer", "=", "self", ".", "getfocus_viewer", "(", ")", "if", "hasattr", "(", "viewer", ",", "'zoom_out'", ")", ":", "viewer", ".", "zoom_out", "(", ")", "return", "True" ]
Zoom the view out one zoom step.
[ "Zoom", "the", "view", "out", "one", "zoom", "step", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L931-L937
train
24,750
ejeschke/ginga
ginga/rv/Control.py
GingaShell.zoom_fit
def zoom_fit(self): """Zoom the view to fit the image entirely in the window. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_fit'): viewer.zoom_fit() return True
python
def zoom_fit(self): """Zoom the view to fit the image entirely in the window. """ viewer = self.getfocus_viewer() if hasattr(viewer, 'zoom_fit'): viewer.zoom_fit() return True
[ "def", "zoom_fit", "(", "self", ")", ":", "viewer", "=", "self", ".", "getfocus_viewer", "(", ")", "if", "hasattr", "(", "viewer", ",", "'zoom_fit'", ")", ":", "viewer", ".", "zoom_fit", "(", ")", "return", "True" ]
Zoom the view to fit the image entirely in the window.
[ "Zoom", "the", "view", "to", "fit", "the", "image", "entirely", "in", "the", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L947-L953
train
24,751
ejeschke/ginga
ginga/rv/Control.py
GingaShell.prev_img_ws
def prev_img_ws(self, ws, loop=True): """Go to the previous image in the focused channel in the workspace. """ channel = self.get_active_channel_ws(ws) if channel is None: return channel.prev_image() return True
python
def prev_img_ws(self, ws, loop=True): """Go to the previous image in the focused channel in the workspace. """ channel = self.get_active_channel_ws(ws) if channel is None: return channel.prev_image() return True
[ "def", "prev_img_ws", "(", "self", ",", "ws", ",", "loop", "=", "True", ")", ":", "channel", "=", "self", ".", "get_active_channel_ws", "(", "ws", ")", "if", "channel", "is", "None", ":", "return", "channel", ".", "prev_image", "(", ")", "return", "Tru...
Go to the previous image in the focused channel in the workspace.
[ "Go", "to", "the", "previous", "image", "in", "the", "focused", "channel", "in", "the", "workspace", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L962-L969
train
24,752
ejeschke/ginga
ginga/rv/Control.py
GingaShell.next_img_ws
def next_img_ws(self, ws, loop=True): """Go to the next image in the focused channel in the workspace. """ channel = self.get_active_channel_ws(ws) if channel is None: return channel.next_image() return True
python
def next_img_ws(self, ws, loop=True): """Go to the next image in the focused channel in the workspace. """ channel = self.get_active_channel_ws(ws) if channel is None: return channel.next_image() return True
[ "def", "next_img_ws", "(", "self", ",", "ws", ",", "loop", "=", "True", ")", ":", "channel", "=", "self", ".", "get_active_channel_ws", "(", "ws", ")", "if", "channel", "is", "None", ":", "return", "channel", ".", "next_image", "(", ")", "return", "Tru...
Go to the next image in the focused channel in the workspace.
[ "Go", "to", "the", "next", "image", "in", "the", "focused", "channel", "in", "the", "workspace", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L971-L978
train
24,753
ejeschke/ginga
ginga/rv/Control.py
GingaShell.prev_img
def prev_img(self, loop=True): """Go to the previous image in the channel. """ channel = self.get_current_channel() if channel is None: self.show_error("Please create a channel.", raisetab=True) return channel.prev_image() return True
python
def prev_img(self, loop=True): """Go to the previous image in the channel. """ channel = self.get_current_channel() if channel is None: self.show_error("Please create a channel.", raisetab=True) return channel.prev_image() return True
[ "def", "prev_img", "(", "self", ",", "loop", "=", "True", ")", ":", "channel", "=", "self", ".", "get_current_channel", "(", ")", "if", "channel", "is", "None", ":", "self", ".", "show_error", "(", "\"Please create a channel.\"", ",", "raisetab", "=", "Tru...
Go to the previous image in the channel.
[ "Go", "to", "the", "previous", "image", "in", "the", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L980-L988
train
24,754
ejeschke/ginga
ginga/rv/Control.py
GingaShell.next_img
def next_img(self, loop=True): """Go to the next image in the channel. """ channel = self.get_current_channel() if channel is None: self.show_error("Please create a channel.", raisetab=True) return channel.next_image() return True
python
def next_img(self, loop=True): """Go to the next image in the channel. """ channel = self.get_current_channel() if channel is None: self.show_error("Please create a channel.", raisetab=True) return channel.next_image() return True
[ "def", "next_img", "(", "self", ",", "loop", "=", "True", ")", ":", "channel", "=", "self", ".", "get_current_channel", "(", ")", "if", "channel", "is", "None", ":", "self", ".", "show_error", "(", "\"Please create a channel.\"", ",", "raisetab", "=", "Tru...
Go to the next image in the channel.
[ "Go", "to", "the", "next", "image", "in", "the", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L990-L998
train
24,755
ejeschke/ginga
ginga/rv/Control.py
GingaShell.close_plugins
def close_plugins(self, channel): """Close all plugins associated with the channel.""" opmon = channel.opmon for key in opmon.get_active(): obj = opmon.get_plugin(key) try: self.gui_call(obj.close) except Exception as e: self.logger.error( "Failed to continue operation: %s" % (str(e)))
python
def close_plugins(self, channel): """Close all plugins associated with the channel.""" opmon = channel.opmon for key in opmon.get_active(): obj = opmon.get_plugin(key) try: self.gui_call(obj.close) except Exception as e: self.logger.error( "Failed to continue operation: %s" % (str(e)))
[ "def", "close_plugins", "(", "self", ",", "channel", ")", ":", "opmon", "=", "channel", ".", "opmon", "for", "key", "in", "opmon", ".", "get_active", "(", ")", ":", "obj", "=", "opmon", ".", "get_plugin", "(", "key", ")", "try", ":", "self", ".", "...
Close all plugins associated with the channel.
[ "Close", "all", "plugins", "associated", "with", "the", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1227-L1237
train
24,756
ejeschke/ginga
ginga/rv/Control.py
GingaShell.add_channel
def add_channel(self, chname, workspace=None, num_images=None, settings=None, settings_template=None, settings_share=None, share_keylist=None): """Create a new Ginga channel. Parameters ---------- chname : str The name of the channel to create. workspace : str or None The name of the workspace in which to create the channel num_images : int or None The cache size for the number of images to keep in memory settings : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences. If not given, one will be created. settings_template : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences template settings_share : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences instance to share with newly created settings share_keylist : list of str List of names of settings that should be shared Returns ------- channel : `~ginga.misc.Bunch.Bunch` The channel info bunch. """ with self.lock: if self.has_channel(chname): return self.get_channel(chname) if chname in self.ds.get_tabnames(None): raise ValueError("Tab name already in use: '%s'" % (chname)) name = chname if settings is None: settings = self.prefs.create_category('channel_' + name) try: settings.load(onError='raise') except Exception as e: self.logger.warning("no saved preferences found for channel " "'%s': %s" % (name, str(e))) # copy template settings to new channel if settings_template is not None: osettings = settings_template osettings.copy_settings(settings) else: try: # use channel_Image as a template if one was not # provided osettings = self.prefs.get_settings('channel_Image') self.logger.debug("Copying settings from 'Image' to " "'%s'" % (name)) osettings.copy_settings(settings) except KeyError: pass if (share_keylist is not None) and (settings_share is not None): # caller wants us to share settings with another viewer settings_share.share_settings(settings, keylist=share_keylist) # Make sure these preferences are at least defined if num_images is None: num_images = settings.get('numImages', self.settings.get('numImages', 1)) settings.set_defaults(switchnew=True, numImages=num_images, raisenew=True, genthumb=True, focus_indicator=False, preload_images=False, sort_order='loadtime') self.logger.debug("Adding channel '%s'" % (chname)) channel = Channel(chname, self, datasrc=None, settings=settings) bnch = self.add_viewer(chname, settings, workspace=workspace) # for debugging bnch.image_viewer.set_name('channel:%s' % (chname)) opmon = self.get_plugin_manager(self.logger, self, self.ds, self.mm) channel.widget = bnch.widget channel.container = bnch.container channel.workspace = bnch.workspace channel.connect_viewer(bnch.image_viewer) channel.viewer = bnch.image_viewer # older name, should eventually be deprecated channel.fitsimage = bnch.image_viewer channel.opmon = opmon name = chname.lower() self.channel[name] = channel # Update the channels control self.channel_names.append(chname) self.channel_names.sort() if len(self.channel_names) == 1: self.cur_channel = channel # Prepare local plugins for this channel for spec in self.get_plugins(): opname = spec.get('klass', spec.get('module')) if spec.get('ptype', 'global') == 'local': opmon.load_plugin(opname, spec, chinfo=channel) self.make_gui_callback('add-channel', channel) return channel
python
def add_channel(self, chname, workspace=None, num_images=None, settings=None, settings_template=None, settings_share=None, share_keylist=None): """Create a new Ginga channel. Parameters ---------- chname : str The name of the channel to create. workspace : str or None The name of the workspace in which to create the channel num_images : int or None The cache size for the number of images to keep in memory settings : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences. If not given, one will be created. settings_template : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences template settings_share : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences instance to share with newly created settings share_keylist : list of str List of names of settings that should be shared Returns ------- channel : `~ginga.misc.Bunch.Bunch` The channel info bunch. """ with self.lock: if self.has_channel(chname): return self.get_channel(chname) if chname in self.ds.get_tabnames(None): raise ValueError("Tab name already in use: '%s'" % (chname)) name = chname if settings is None: settings = self.prefs.create_category('channel_' + name) try: settings.load(onError='raise') except Exception as e: self.logger.warning("no saved preferences found for channel " "'%s': %s" % (name, str(e))) # copy template settings to new channel if settings_template is not None: osettings = settings_template osettings.copy_settings(settings) else: try: # use channel_Image as a template if one was not # provided osettings = self.prefs.get_settings('channel_Image') self.logger.debug("Copying settings from 'Image' to " "'%s'" % (name)) osettings.copy_settings(settings) except KeyError: pass if (share_keylist is not None) and (settings_share is not None): # caller wants us to share settings with another viewer settings_share.share_settings(settings, keylist=share_keylist) # Make sure these preferences are at least defined if num_images is None: num_images = settings.get('numImages', self.settings.get('numImages', 1)) settings.set_defaults(switchnew=True, numImages=num_images, raisenew=True, genthumb=True, focus_indicator=False, preload_images=False, sort_order='loadtime') self.logger.debug("Adding channel '%s'" % (chname)) channel = Channel(chname, self, datasrc=None, settings=settings) bnch = self.add_viewer(chname, settings, workspace=workspace) # for debugging bnch.image_viewer.set_name('channel:%s' % (chname)) opmon = self.get_plugin_manager(self.logger, self, self.ds, self.mm) channel.widget = bnch.widget channel.container = bnch.container channel.workspace = bnch.workspace channel.connect_viewer(bnch.image_viewer) channel.viewer = bnch.image_viewer # older name, should eventually be deprecated channel.fitsimage = bnch.image_viewer channel.opmon = opmon name = chname.lower() self.channel[name] = channel # Update the channels control self.channel_names.append(chname) self.channel_names.sort() if len(self.channel_names) == 1: self.cur_channel = channel # Prepare local plugins for this channel for spec in self.get_plugins(): opname = spec.get('klass', spec.get('module')) if spec.get('ptype', 'global') == 'local': opmon.load_plugin(opname, spec, chinfo=channel) self.make_gui_callback('add-channel', channel) return channel
[ "def", "add_channel", "(", "self", ",", "chname", ",", "workspace", "=", "None", ",", "num_images", "=", "None", ",", "settings", "=", "None", ",", "settings_template", "=", "None", ",", "settings_share", "=", "None", ",", "share_keylist", "=", "None", ")"...
Create a new Ginga channel. Parameters ---------- chname : str The name of the channel to create. workspace : str or None The name of the workspace in which to create the channel num_images : int or None The cache size for the number of images to keep in memory settings : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences. If not given, one will be created. settings_template : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences template settings_share : `~ginga.misc.Settings.SettingGroup` or `None` Viewer preferences instance to share with newly created settings share_keylist : list of str List of names of settings that should be shared Returns ------- channel : `~ginga.misc.Bunch.Bunch` The channel info bunch.
[ "Create", "a", "new", "Ginga", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1344-L1462
train
24,757
ejeschke/ginga
ginga/rv/Control.py
GingaShell.delete_channel
def delete_channel(self, chname): """Delete a given channel from viewer.""" name = chname.lower() if len(self.channel_names) < 1: self.logger.error('Delete channel={0} failed. ' 'No channels left.'.format(chname)) return with self.lock: channel = self.channel[name] # Close local plugins open on this channel self.close_plugins(channel) try: idx = self.channel_names.index(chname) except ValueError: idx = 0 # Update the channels control self.channel_names.remove(channel.name) self.channel_names.sort() self.ds.remove_tab(chname) del self.channel[name] self.prefs.remove_settings('channel_' + chname) # pick new channel num_channels = len(self.channel_names) if num_channels > 0: if idx >= num_channels: idx = num_channels - 1 self.change_channel(self.channel_names[idx]) else: self.cur_channel = None self.make_gui_callback('delete-channel', channel)
python
def delete_channel(self, chname): """Delete a given channel from viewer.""" name = chname.lower() if len(self.channel_names) < 1: self.logger.error('Delete channel={0} failed. ' 'No channels left.'.format(chname)) return with self.lock: channel = self.channel[name] # Close local plugins open on this channel self.close_plugins(channel) try: idx = self.channel_names.index(chname) except ValueError: idx = 0 # Update the channels control self.channel_names.remove(channel.name) self.channel_names.sort() self.ds.remove_tab(chname) del self.channel[name] self.prefs.remove_settings('channel_' + chname) # pick new channel num_channels = len(self.channel_names) if num_channels > 0: if idx >= num_channels: idx = num_channels - 1 self.change_channel(self.channel_names[idx]) else: self.cur_channel = None self.make_gui_callback('delete-channel', channel)
[ "def", "delete_channel", "(", "self", ",", "chname", ")", ":", "name", "=", "chname", ".", "lower", "(", ")", "if", "len", "(", "self", ".", "channel_names", ")", "<", "1", ":", "self", ".", "logger", ".", "error", "(", "'Delete channel={0} failed. '", ...
Delete a given channel from viewer.
[ "Delete", "a", "given", "channel", "from", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1464-L1501
train
24,758
ejeschke/ginga
ginga/rv/Control.py
GingaShell.add_menu
def add_menu(self, name): """Add a menu with name `name` to the global menu bar. Returns a menu widget. """ if self.menubar is None: raise ValueError("No menu bar configured") return self.menubar.add_name(name)
python
def add_menu(self, name): """Add a menu with name `name` to the global menu bar. Returns a menu widget. """ if self.menubar is None: raise ValueError("No menu bar configured") return self.menubar.add_name(name)
[ "def", "add_menu", "(", "self", ",", "name", ")", ":", "if", "self", ".", "menubar", "is", "None", ":", "raise", "ValueError", "(", "\"No menu bar configured\"", ")", "return", "self", ".", "menubar", ".", "add_name", "(", "name", ")" ]
Add a menu with name `name` to the global menu bar. Returns a menu widget.
[ "Add", "a", "menu", "with", "name", "name", "to", "the", "global", "menu", "bar", ".", "Returns", "a", "menu", "widget", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1750-L1756
train
24,759
ejeschke/ginga
ginga/rv/Control.py
GingaShell.get_menu
def get_menu(self, name): """Get the menu with name `name` from the global menu bar. Returns a menu widget. """ if self.menubar is None: raise ValueError("No menu bar configured") return self.menubar.get_menu(name)
python
def get_menu(self, name): """Get the menu with name `name` from the global menu bar. Returns a menu widget. """ if self.menubar is None: raise ValueError("No menu bar configured") return self.menubar.get_menu(name)
[ "def", "get_menu", "(", "self", ",", "name", ")", ":", "if", "self", ".", "menubar", "is", "None", ":", "raise", "ValueError", "(", "\"No menu bar configured\"", ")", "return", "self", ".", "menubar", ".", "get_menu", "(", "name", ")" ]
Get the menu with name `name` from the global menu bar. Returns a menu widget.
[ "Get", "the", "menu", "with", "name", "name", "from", "the", "global", "menu", "bar", ".", "Returns", "a", "menu", "widget", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1758-L1764
train
24,760
ejeschke/ginga
ginga/rv/Control.py
GingaShell.register_viewer
def register_viewer(self, vclass): """Register a channel viewer with the reference viewer. `vclass` is the class of the viewer. """ self.viewer_db[vclass.vname] = Bunch.Bunch(vname=vclass.vname, vclass=vclass, vtypes=vclass.vtypes)
python
def register_viewer(self, vclass): """Register a channel viewer with the reference viewer. `vclass` is the class of the viewer. """ self.viewer_db[vclass.vname] = Bunch.Bunch(vname=vclass.vname, vclass=vclass, vtypes=vclass.vtypes)
[ "def", "register_viewer", "(", "self", ",", "vclass", ")", ":", "self", ".", "viewer_db", "[", "vclass", ".", "vname", "]", "=", "Bunch", ".", "Bunch", "(", "vname", "=", "vclass", ".", "vname", ",", "vclass", "=", "vclass", ",", "vtypes", "=", "vcla...
Register a channel viewer with the reference viewer. `vclass` is the class of the viewer.
[ "Register", "a", "channel", "viewer", "with", "the", "reference", "viewer", ".", "vclass", "is", "the", "class", "of", "the", "viewer", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1848-L1854
train
24,761
ejeschke/ginga
ginga/rv/Control.py
GingaShell.get_viewer_names
def get_viewer_names(self, dataobj): """Returns a list of viewer names that are registered that can view `dataobj`. """ res = [] for bnch in self.viewer_db.values(): for vtype in bnch.vtypes: if isinstance(dataobj, vtype): res.append(bnch.vname) return res
python
def get_viewer_names(self, dataobj): """Returns a list of viewer names that are registered that can view `dataobj`. """ res = [] for bnch in self.viewer_db.values(): for vtype in bnch.vtypes: if isinstance(dataobj, vtype): res.append(bnch.vname) return res
[ "def", "get_viewer_names", "(", "self", ",", "dataobj", ")", ":", "res", "=", "[", "]", "for", "bnch", "in", "self", ".", "viewer_db", ".", "values", "(", ")", ":", "for", "vtype", "in", "bnch", ".", "vtypes", ":", "if", "isinstance", "(", "dataobj",...
Returns a list of viewer names that are registered that can view `dataobj`.
[ "Returns", "a", "list", "of", "viewer", "names", "that", "are", "registered", "that", "can", "view", "dataobj", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1856-L1865
train
24,762
ejeschke/ginga
ginga/rv/Control.py
GingaShell.make_viewer
def make_viewer(self, vname, channel): """Make a viewer whose type name is `vname` and add it to `channel`. """ if vname not in self.viewer_db: raise ValueError("I don't know how to build a '%s' viewer" % ( vname)) stk_w = channel.widget bnch = self.viewer_db[vname] viewer = bnch.vclass(logger=self.logger, settings=channel.settings) stk_w.add_widget(viewer.get_widget(), title=vname) # let the GUI respond to this widget addition self.update_pending() # let the channel object do any necessary initialization channel.connect_viewer(viewer) # finally, let the viewer do any viewer-side initialization viewer.initialize_channel(self, channel)
python
def make_viewer(self, vname, channel): """Make a viewer whose type name is `vname` and add it to `channel`. """ if vname not in self.viewer_db: raise ValueError("I don't know how to build a '%s' viewer" % ( vname)) stk_w = channel.widget bnch = self.viewer_db[vname] viewer = bnch.vclass(logger=self.logger, settings=channel.settings) stk_w.add_widget(viewer.get_widget(), title=vname) # let the GUI respond to this widget addition self.update_pending() # let the channel object do any necessary initialization channel.connect_viewer(viewer) # finally, let the viewer do any viewer-side initialization viewer.initialize_channel(self, channel)
[ "def", "make_viewer", "(", "self", ",", "vname", ",", "channel", ")", ":", "if", "vname", "not", "in", "self", ".", "viewer_db", ":", "raise", "ValueError", "(", "\"I don't know how to build a '%s' viewer\"", "%", "(", "vname", ")", ")", "stk_w", "=", "chann...
Make a viewer whose type name is `vname` and add it to `channel`.
[ "Make", "a", "viewer", "whose", "type", "name", "is", "vname", "and", "add", "it", "to", "channel", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1867-L1889
train
24,763
ejeschke/ginga
ginga/rv/Control.py
GingaShell.collapse_pane
def collapse_pane(self, side): """ Toggle collapsing the left or right panes. """ # TODO: this is too tied to one configuration, need to figure # out how to generalize this hsplit = self.w['hpnl'] sizes = hsplit.get_sizes() lsize, msize, rsize = sizes if self._lsize is None: self._lsize, self._rsize = lsize, rsize self.logger.debug("left=%d mid=%d right=%d" % ( lsize, msize, rsize)) if side == 'right': if rsize < 10: # restore pane rsize = self._rsize msize -= rsize else: # minimize pane self._rsize = rsize msize += rsize rsize = 0 elif side == 'left': if lsize < 10: # restore pane lsize = self._lsize msize -= lsize else: # minimize pane self._lsize = lsize msize += lsize lsize = 0 hsplit.set_sizes([lsize, msize, rsize])
python
def collapse_pane(self, side): """ Toggle collapsing the left or right panes. """ # TODO: this is too tied to one configuration, need to figure # out how to generalize this hsplit = self.w['hpnl'] sizes = hsplit.get_sizes() lsize, msize, rsize = sizes if self._lsize is None: self._lsize, self._rsize = lsize, rsize self.logger.debug("left=%d mid=%d right=%d" % ( lsize, msize, rsize)) if side == 'right': if rsize < 10: # restore pane rsize = self._rsize msize -= rsize else: # minimize pane self._rsize = rsize msize += rsize rsize = 0 elif side == 'left': if lsize < 10: # restore pane lsize = self._lsize msize -= lsize else: # minimize pane self._lsize = lsize msize += lsize lsize = 0 hsplit.set_sizes([lsize, msize, rsize])
[ "def", "collapse_pane", "(", "self", ",", "side", ")", ":", "# TODO: this is too tied to one configuration, need to figure", "# out how to generalize this", "hsplit", "=", "self", ".", "w", "[", "'hpnl'", "]", "sizes", "=", "hsplit", ".", "get_sizes", "(", ")", "lsi...
Toggle collapsing the left or right panes.
[ "Toggle", "collapsing", "the", "left", "or", "right", "panes", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2214-L2247
train
24,764
ejeschke/ginga
ginga/rv/Control.py
GingaShell.quit
def quit(self, *args): """Quit the application. """ self.logger.info("Attempting to shut down the application...") if self.layout_file is not None: self.error_wrap(self.ds.write_layout_conf, self.layout_file) self.stop() self.w.root = None while len(self.ds.toplevels) > 0: w = self.ds.toplevels.pop() w.delete()
python
def quit(self, *args): """Quit the application. """ self.logger.info("Attempting to shut down the application...") if self.layout_file is not None: self.error_wrap(self.ds.write_layout_conf, self.layout_file) self.stop() self.w.root = None while len(self.ds.toplevels) > 0: w = self.ds.toplevels.pop() w.delete()
[ "def", "quit", "(", "self", ",", "*", "args", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Attempting to shut down the application...\"", ")", "if", "self", ".", "layout_file", "is", "not", "None", ":", "self", ".", "error_wrap", "(", "self", ".",...
Quit the application.
[ "Quit", "the", "application", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2266-L2278
train
24,765
ejeschke/ginga
ginga/rv/Control.py
GingaShell.showxy
def showxy(self, viewer, data_x, data_y): """Called by the mouse-tracking callback to handle reporting of cursor position to various plugins that subscribe to the 'field-info' callback. """ # This is an optimization to get around slow coordinate # transformation by astropy and possibly other WCS packages, # which causes delay for other mouse tracking events, e.g. # the zoom plugin. # We only update the under cursor information every period # defined by (self.cursor_interval) sec. # # If the refresh interval has expired then update the info; # otherwise (re)set the timer until the end of the interval. cur_time = time.time() elapsed = cur_time - self._cursor_last_update if elapsed > self.cursor_interval: # cancel timer self._cursor_task.clear() self.gui_do_oneshot('field-info', self._showxy, viewer, data_x, data_y) else: # store needed data into the timer data area self._cursor_task.data.setvals(viewer=viewer, data_x=data_x, data_y=data_y) # calculate delta until end of refresh interval period = self.cursor_interval - elapsed # set timer conditionally (only if it hasn't yet been set) self._cursor_task.cond_set(period) return True
python
def showxy(self, viewer, data_x, data_y): """Called by the mouse-tracking callback to handle reporting of cursor position to various plugins that subscribe to the 'field-info' callback. """ # This is an optimization to get around slow coordinate # transformation by astropy and possibly other WCS packages, # which causes delay for other mouse tracking events, e.g. # the zoom plugin. # We only update the under cursor information every period # defined by (self.cursor_interval) sec. # # If the refresh interval has expired then update the info; # otherwise (re)set the timer until the end of the interval. cur_time = time.time() elapsed = cur_time - self._cursor_last_update if elapsed > self.cursor_interval: # cancel timer self._cursor_task.clear() self.gui_do_oneshot('field-info', self._showxy, viewer, data_x, data_y) else: # store needed data into the timer data area self._cursor_task.data.setvals(viewer=viewer, data_x=data_x, data_y=data_y) # calculate delta until end of refresh interval period = self.cursor_interval - elapsed # set timer conditionally (only if it hasn't yet been set) self._cursor_task.cond_set(period) return True
[ "def", "showxy", "(", "self", ",", "viewer", ",", "data_x", ",", "data_y", ")", ":", "# This is an optimization to get around slow coordinate", "# transformation by astropy and possibly other WCS packages,", "# which causes delay for other mouse tracking events, e.g.", "# the zoom plug...
Called by the mouse-tracking callback to handle reporting of cursor position to various plugins that subscribe to the 'field-info' callback.
[ "Called", "by", "the", "mouse", "-", "tracking", "callback", "to", "handle", "reporting", "of", "cursor", "position", "to", "various", "plugins", "that", "subscribe", "to", "the", "field", "-", "info", "callback", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2539-L2568
train
24,766
ejeschke/ginga
ginga/rv/Control.py
GingaShell._cursor_timer_cb
def _cursor_timer_cb(self, timer): """Callback when the cursor timer expires. """ data = timer.data self.gui_do_oneshot('field-info', self._showxy, data.viewer, data.data_x, data.data_y)
python
def _cursor_timer_cb(self, timer): """Callback when the cursor timer expires. """ data = timer.data self.gui_do_oneshot('field-info', self._showxy, data.viewer, data.data_x, data.data_y)
[ "def", "_cursor_timer_cb", "(", "self", ",", "timer", ")", ":", "data", "=", "timer", ".", "data", "self", ".", "gui_do_oneshot", "(", "'field-info'", ",", "self", ".", "_showxy", ",", "data", ".", "viewer", ",", "data", ".", "data_x", ",", "data", "."...
Callback when the cursor timer expires.
[ "Callback", "when", "the", "cursor", "timer", "expires", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2570-L2575
train
24,767
ejeschke/ginga
ginga/rv/Control.py
GingaShell._showxy
def _showxy(self, viewer, data_x, data_y): """Update the info from the last position recorded under the cursor. """ self._cursor_last_update = time.time() try: image = viewer.get_image() if (image is None) or not isinstance(image, BaseImage.BaseImage): # No compatible image loaded for this channel return settings = viewer.get_settings() info = image.info_xy(data_x, data_y, settings) # Are we reporting in data or FITS coordinates? off = self.settings.get('pixel_coords_offset', 0.0) info.x += off info.y += off except Exception as e: self.logger.warning( "Can't get info under the cursor: %s" % (str(e))) return # TODO: can this be made more efficient? chname = self.get_channel_name(viewer) channel = self.get_channel(chname) self.make_callback('field-info', channel, info) self.update_pending() return True
python
def _showxy(self, viewer, data_x, data_y): """Update the info from the last position recorded under the cursor. """ self._cursor_last_update = time.time() try: image = viewer.get_image() if (image is None) or not isinstance(image, BaseImage.BaseImage): # No compatible image loaded for this channel return settings = viewer.get_settings() info = image.info_xy(data_x, data_y, settings) # Are we reporting in data or FITS coordinates? off = self.settings.get('pixel_coords_offset', 0.0) info.x += off info.y += off except Exception as e: self.logger.warning( "Can't get info under the cursor: %s" % (str(e))) return # TODO: can this be made more efficient? chname = self.get_channel_name(viewer) channel = self.get_channel(chname) self.make_callback('field-info', channel, info) self.update_pending() return True
[ "def", "_showxy", "(", "self", ",", "viewer", ",", "data_x", ",", "data_y", ")", ":", "self", ".", "_cursor_last_update", "=", "time", ".", "time", "(", ")", "try", ":", "image", "=", "viewer", ".", "get_image", "(", ")", "if", "(", "image", "is", ...
Update the info from the last position recorded under the cursor.
[ "Update", "the", "info", "from", "the", "last", "position", "recorded", "under", "the", "cursor", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2577-L2607
train
24,768
ejeschke/ginga
ginga/rv/Control.py
GingaShell.motion_cb
def motion_cb(self, viewer, button, data_x, data_y): """Motion event in the channel viewer window. Show the pointing information under the cursor. """ self.showxy(viewer, data_x, data_y) return True
python
def motion_cb(self, viewer, button, data_x, data_y): """Motion event in the channel viewer window. Show the pointing information under the cursor. """ self.showxy(viewer, data_x, data_y) return True
[ "def", "motion_cb", "(", "self", ",", "viewer", ",", "button", ",", "data_x", ",", "data_y", ")", ":", "self", ".", "showxy", "(", "viewer", ",", "data_x", ",", "data_y", ")", "return", "True" ]
Motion event in the channel viewer window. Show the pointing information under the cursor.
[ "Motion", "event", "in", "the", "channel", "viewer", "window", ".", "Show", "the", "pointing", "information", "under", "the", "cursor", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2609-L2614
train
24,769
ejeschke/ginga
ginga/rv/Control.py
GingaShell.keypress
def keypress(self, viewer, event, data_x, data_y): """Key press event in a channel window.""" keyname = event.key chname = self.get_channel_name(viewer) self.logger.debug("key press (%s) in channel %s" % ( keyname, chname)) # TODO: keyboard accelerators to raise tabs need to be integrated into # the desktop object if keyname == 'Z': self.ds.raise_tab('Zoom') ## elif keyname == 'T': ## self.ds.raise_tab('Thumbs') elif keyname == 'I': self.ds.raise_tab('Info') elif keyname == 'H': self.ds.raise_tab('Header') elif keyname == 'C': self.ds.raise_tab('Contents') elif keyname == 'D': self.ds.raise_tab('Dialogs') elif keyname == 'F': self.build_fullscreen() elif keyname == 'f': self.toggle_fullscreen() elif keyname == 'm': self.maximize() elif keyname == '<': self.collapse_pane('left') elif keyname == '>': self.collapse_pane('right') elif keyname == 'n': self.next_channel() elif keyname == 'J': self.cycle_workspace_type() elif keyname == 'k': self.add_channel_auto() elif keyname == 'K': self.remove_channel_auto() elif keyname == 'f1': self.show_channel_names() ## elif keyname == 'escape': ## self.reset_viewer() elif keyname in ('up',): self.prev_img() elif keyname in ('down',): self.next_img() elif keyname in ('left',): self.prev_channel() elif keyname in ('right',): self.next_channel() return True
python
def keypress(self, viewer, event, data_x, data_y): """Key press event in a channel window.""" keyname = event.key chname = self.get_channel_name(viewer) self.logger.debug("key press (%s) in channel %s" % ( keyname, chname)) # TODO: keyboard accelerators to raise tabs need to be integrated into # the desktop object if keyname == 'Z': self.ds.raise_tab('Zoom') ## elif keyname == 'T': ## self.ds.raise_tab('Thumbs') elif keyname == 'I': self.ds.raise_tab('Info') elif keyname == 'H': self.ds.raise_tab('Header') elif keyname == 'C': self.ds.raise_tab('Contents') elif keyname == 'D': self.ds.raise_tab('Dialogs') elif keyname == 'F': self.build_fullscreen() elif keyname == 'f': self.toggle_fullscreen() elif keyname == 'm': self.maximize() elif keyname == '<': self.collapse_pane('left') elif keyname == '>': self.collapse_pane('right') elif keyname == 'n': self.next_channel() elif keyname == 'J': self.cycle_workspace_type() elif keyname == 'k': self.add_channel_auto() elif keyname == 'K': self.remove_channel_auto() elif keyname == 'f1': self.show_channel_names() ## elif keyname == 'escape': ## self.reset_viewer() elif keyname in ('up',): self.prev_img() elif keyname in ('down',): self.next_img() elif keyname in ('left',): self.prev_channel() elif keyname in ('right',): self.next_channel() return True
[ "def", "keypress", "(", "self", ",", "viewer", ",", "event", ",", "data_x", ",", "data_y", ")", ":", "keyname", "=", "event", ".", "key", "chname", "=", "self", ".", "get_channel_name", "(", "viewer", ")", "self", ".", "logger", ".", "debug", "(", "\...
Key press event in a channel window.
[ "Key", "press", "event", "in", "a", "channel", "window", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2616-L2666
train
24,770
ejeschke/ginga
ginga/rv/Control.py
GingaShell.show_channel_names
def show_channel_names(self): """Show each channel's name in its image viewer. Useful in 'grid' or 'stack' workspace type to identify which window is which. """ for name in self.get_channel_names(): channel = self.get_channel(name) channel.fitsimage.onscreen_message(name, delay=2.5)
python
def show_channel_names(self): """Show each channel's name in its image viewer. Useful in 'grid' or 'stack' workspace type to identify which window is which. """ for name in self.get_channel_names(): channel = self.get_channel(name) channel.fitsimage.onscreen_message(name, delay=2.5)
[ "def", "show_channel_names", "(", "self", ")", ":", "for", "name", "in", "self", ".", "get_channel_names", "(", ")", ":", "channel", "=", "self", ".", "get_channel", "(", "name", ")", "channel", ".", "fitsimage", ".", "onscreen_message", "(", "name", ",", ...
Show each channel's name in its image viewer. Useful in 'grid' or 'stack' workspace type to identify which window is which.
[ "Show", "each", "channel", "s", "name", "in", "its", "image", "viewer", ".", "Useful", "in", "grid", "or", "stack", "workspace", "type", "to", "identify", "which", "window", "is", "which", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L2703-L2710
train
24,771
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark._short_color_list
def _short_color_list(self): """Color list is too long. Discard variations with numbers.""" return [c for c in colors.get_colors() if not re.search(r'\d', c)]
python
def _short_color_list(self): """Color list is too long. Discard variations with numbers.""" return [c for c in colors.get_colors() if not re.search(r'\d', c)]
[ "def", "_short_color_list", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "colors", ".", "get_colors", "(", ")", "if", "not", "re", ".", "search", "(", "r'\\d'", ",", "c", ")", "]" ]
Color list is too long. Discard variations with numbers.
[ "Color", "list", "is", "too", "long", ".", "Discard", "variations", "with", "numbers", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L165-L167
train
24,772
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark._get_markobj
def _get_markobj(self, x, y, marktype, marksize, markcolor, markwidth): """Generate canvas object for given mark parameters.""" if marktype == 'circle': obj = self.dc.Circle( x=x, y=y, radius=marksize, color=markcolor, linewidth=markwidth) elif marktype in ('cross', 'plus'): obj = self.dc.Point( x=x, y=y, radius=marksize, color=markcolor, linewidth=markwidth, style=marktype) elif marktype == 'box': obj = self.dc.Box( x=x, y=y, xradius=marksize, yradius=marksize, color=markcolor, linewidth=markwidth) else: # point, marksize obj = self.dc.Box( x=x, y=y, xradius=1, yradius=1, color=markcolor, linewidth=markwidth, fill=True, fillcolor=markcolor) return obj
python
def _get_markobj(self, x, y, marktype, marksize, markcolor, markwidth): """Generate canvas object for given mark parameters.""" if marktype == 'circle': obj = self.dc.Circle( x=x, y=y, radius=marksize, color=markcolor, linewidth=markwidth) elif marktype in ('cross', 'plus'): obj = self.dc.Point( x=x, y=y, radius=marksize, color=markcolor, linewidth=markwidth, style=marktype) elif marktype == 'box': obj = self.dc.Box( x=x, y=y, xradius=marksize, yradius=marksize, color=markcolor, linewidth=markwidth) else: # point, marksize obj = self.dc.Box( x=x, y=y, xradius=1, yradius=1, color=markcolor, linewidth=markwidth, fill=True, fillcolor=markcolor) return obj
[ "def", "_get_markobj", "(", "self", ",", "x", ",", "y", ",", "marktype", ",", "marksize", ",", "markcolor", ",", "markwidth", ")", ":", "if", "marktype", "==", "'circle'", ":", "obj", "=", "self", ".", "dc", ".", "Circle", "(", "x", "=", "x", ",", ...
Generate canvas object for given mark parameters.
[ "Generate", "canvas", "object", "for", "given", "mark", "parameters", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L393-L411
train
24,773
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.clear_marking
def clear_marking(self): """Clear marking from image. This does not clear loaded coordinates from memory.""" if self.marktag: try: self.canvas.delete_object_by_tag(self.marktag, redraw=False) except Exception: pass if self.markhltag: try: self.canvas.delete_object_by_tag(self.markhltag, redraw=False) except Exception: pass self.treeview.clear() # Clear table too self.w.nshown.set_text('0') self.fitsimage.redraw()
python
def clear_marking(self): """Clear marking from image. This does not clear loaded coordinates from memory.""" if self.marktag: try: self.canvas.delete_object_by_tag(self.marktag, redraw=False) except Exception: pass if self.markhltag: try: self.canvas.delete_object_by_tag(self.markhltag, redraw=False) except Exception: pass self.treeview.clear() # Clear table too self.w.nshown.set_text('0') self.fitsimage.redraw()
[ "def", "clear_marking", "(", "self", ")", ":", "if", "self", ".", "marktag", ":", "try", ":", "self", ".", "canvas", ".", "delete_object_by_tag", "(", "self", ".", "marktag", ",", "redraw", "=", "False", ")", "except", "Exception", ":", "pass", "if", "...
Clear marking from image. This does not clear loaded coordinates from memory.
[ "Clear", "marking", "from", "image", ".", "This", "does", "not", "clear", "loaded", "coordinates", "from", "memory", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L413-L430
train
24,774
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.load_file
def load_file(self, filename): """Load coordinates file. Results are appended to previously loaded coordinates. This can be used to load one file per color. """ if not os.path.isfile(filename): return self.logger.info('Loading coordinates from {0}'.format(filename)) if filename.endswith('.fits'): fmt = 'fits' else: # Assume ASCII fmt = 'ascii' try: tab = Table.read(filename, format=fmt) except Exception as e: self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e))) return if self.use_radec: colname0 = self.settings.get('ra_colname', 'ra') colname1 = self.settings.get('dec_colname', 'dec') else: colname0 = self.settings.get('x_colname', 'x') colname1 = self.settings.get('y_colname', 'y') try: col_0 = tab[colname0] col_1 = tab[colname1] except Exception as e: self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e))) return nrows = len(col_0) dummy_col = [None] * nrows try: oldrows = int(self.w.ntotal.get_text()) except ValueError: oldrows = 0 self.w.ntotal.set_text(str(oldrows + nrows)) if self.use_radec: ra = self._convert_radec(col_0) dec = self._convert_radec(col_1) x = y = dummy_col else: ra = dec = dummy_col # X and Y always 0-indexed internally x = col_0.data - self.pixelstart y = col_1.data - self.pixelstart args = [ra, dec, x, y] # Load extra columns for colname in self.extra_columns: try: col = tab[colname].data except Exception as e: self.logger.error( '{0}: {1}'.format(e.__class__.__name__, str(e))) col = dummy_col args.append(col) # Use list to preserve order. Does not handle duplicates. key = (self.marktype, self.marksize, self.markcolor) self.coords_dict[key] += list(zip(*args)) self.redo()
python
def load_file(self, filename): """Load coordinates file. Results are appended to previously loaded coordinates. This can be used to load one file per color. """ if not os.path.isfile(filename): return self.logger.info('Loading coordinates from {0}'.format(filename)) if filename.endswith('.fits'): fmt = 'fits' else: # Assume ASCII fmt = 'ascii' try: tab = Table.read(filename, format=fmt) except Exception as e: self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e))) return if self.use_radec: colname0 = self.settings.get('ra_colname', 'ra') colname1 = self.settings.get('dec_colname', 'dec') else: colname0 = self.settings.get('x_colname', 'x') colname1 = self.settings.get('y_colname', 'y') try: col_0 = tab[colname0] col_1 = tab[colname1] except Exception as e: self.logger.error('{0}: {1}'.format(e.__class__.__name__, str(e))) return nrows = len(col_0) dummy_col = [None] * nrows try: oldrows = int(self.w.ntotal.get_text()) except ValueError: oldrows = 0 self.w.ntotal.set_text(str(oldrows + nrows)) if self.use_radec: ra = self._convert_radec(col_0) dec = self._convert_radec(col_1) x = y = dummy_col else: ra = dec = dummy_col # X and Y always 0-indexed internally x = col_0.data - self.pixelstart y = col_1.data - self.pixelstart args = [ra, dec, x, y] # Load extra columns for colname in self.extra_columns: try: col = tab[colname].data except Exception as e: self.logger.error( '{0}: {1}'.format(e.__class__.__name__, str(e))) col = dummy_col args.append(col) # Use list to preserve order. Does not handle duplicates. key = (self.marktype, self.marksize, self.markcolor) self.coords_dict[key] += list(zip(*args)) self.redo()
[ "def", "load_file", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "self", ".", "logger", ".", "info", "(", "'Loading coordinates from {0}'", ".", "format", "(", "filename", ")"...
Load coordinates file. Results are appended to previously loaded coordinates. This can be used to load one file per color.
[ "Load", "coordinates", "file", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L439-L514
train
24,775
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark._convert_radec
def _convert_radec(self, val): """Convert RA or DEC table column to degrees and extract data. Assume already in degrees if cannot convert. """ try: ans = val.to('deg') except Exception as e: self.logger.error('Cannot convert, assume already in degrees') ans = val.data else: ans = ans.value return ans
python
def _convert_radec(self, val): """Convert RA or DEC table column to degrees and extract data. Assume already in degrees if cannot convert. """ try: ans = val.to('deg') except Exception as e: self.logger.error('Cannot convert, assume already in degrees') ans = val.data else: ans = ans.value return ans
[ "def", "_convert_radec", "(", "self", ",", "val", ")", ":", "try", ":", "ans", "=", "val", ".", "to", "(", "'deg'", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "'Cannot convert, assume already in degrees'", ")", ...
Convert RA or DEC table column to degrees and extract data. Assume already in degrees if cannot convert.
[ "Convert", "RA", "or", "DEC", "table", "column", "to", "degrees", "and", "extract", "data", ".", "Assume", "already", "in", "degrees", "if", "cannot", "convert", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L526-L539
train
24,776
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.hl_table2canvas
def hl_table2canvas(self, w, res_dict): """Highlight marking on canvas when user click on table.""" objlist = [] width = self.markwidth + self._dwidth # Remove existing highlight if self.markhltag: try: self.canvas.delete_object_by_tag(self.markhltag, redraw=False) except Exception: pass # Display highlighted entries only in second table self.treeviewsel.set_tree(res_dict) for kstr, sub_dict in res_dict.items(): s = kstr.split(',') marktype = s[0] marksize = float(s[1]) markcolor = s[2] for bnch in sub_dict.values(): obj = self._get_markobj(bnch.X - self.pixelstart, bnch.Y - self.pixelstart, marktype, marksize, markcolor, width) objlist.append(obj) nsel = len(objlist) self.w.nselected.set_text(str(nsel)) # Draw on canvas if nsel > 0: self.markhltag = self.canvas.add(self.dc.CompoundObject(*objlist)) self.fitsimage.redraw()
python
def hl_table2canvas(self, w, res_dict): """Highlight marking on canvas when user click on table.""" objlist = [] width = self.markwidth + self._dwidth # Remove existing highlight if self.markhltag: try: self.canvas.delete_object_by_tag(self.markhltag, redraw=False) except Exception: pass # Display highlighted entries only in second table self.treeviewsel.set_tree(res_dict) for kstr, sub_dict in res_dict.items(): s = kstr.split(',') marktype = s[0] marksize = float(s[1]) markcolor = s[2] for bnch in sub_dict.values(): obj = self._get_markobj(bnch.X - self.pixelstart, bnch.Y - self.pixelstart, marktype, marksize, markcolor, width) objlist.append(obj) nsel = len(objlist) self.w.nselected.set_text(str(nsel)) # Draw on canvas if nsel > 0: self.markhltag = self.canvas.add(self.dc.CompoundObject(*objlist)) self.fitsimage.redraw()
[ "def", "hl_table2canvas", "(", "self", ",", "w", ",", "res_dict", ")", ":", "objlist", "=", "[", "]", "width", "=", "self", ".", "markwidth", "+", "self", ".", "_dwidth", "# Remove existing highlight", "if", "self", ".", "markhltag", ":", "try", ":", "se...
Highlight marking on canvas when user click on table.
[ "Highlight", "marking", "on", "canvas", "when", "user", "click", "on", "table", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L562-L596
train
24,777
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.hl_canvas2table_box
def hl_canvas2table_box(self, canvas, tag): """Highlight all markings inside user drawn box on table.""" self.treeview.clear_selection() # Remove existing box cobj = canvas.get_object_by_tag(tag) if cobj.kind != 'rectangle': return canvas.delete_object_by_tag(tag, redraw=False) # Remove existing highlight if self.markhltag: try: canvas.delete_object_by_tag(self.markhltag, redraw=True) except Exception: pass # Nothing to do if no markings are displayed try: obj = canvas.get_object_by_tag(self.marktag) except Exception: return if obj.kind != 'compound': return # Nothing to do if table has no data if (len(self._xarr) == 0 or len(self._yarr) == 0 or len(self._treepaths) == 0): return # Find markings inside box mask = cobj.contains_arr(self._xarr, self._yarr) for hlpath in self._treepaths[mask]: self._highlight_path(hlpath)
python
def hl_canvas2table_box(self, canvas, tag): """Highlight all markings inside user drawn box on table.""" self.treeview.clear_selection() # Remove existing box cobj = canvas.get_object_by_tag(tag) if cobj.kind != 'rectangle': return canvas.delete_object_by_tag(tag, redraw=False) # Remove existing highlight if self.markhltag: try: canvas.delete_object_by_tag(self.markhltag, redraw=True) except Exception: pass # Nothing to do if no markings are displayed try: obj = canvas.get_object_by_tag(self.marktag) except Exception: return if obj.kind != 'compound': return # Nothing to do if table has no data if (len(self._xarr) == 0 or len(self._yarr) == 0 or len(self._treepaths) == 0): return # Find markings inside box mask = cobj.contains_arr(self._xarr, self._yarr) for hlpath in self._treepaths[mask]: self._highlight_path(hlpath)
[ "def", "hl_canvas2table_box", "(", "self", ",", "canvas", ",", "tag", ")", ":", "self", ".", "treeview", ".", "clear_selection", "(", ")", "# Remove existing box", "cobj", "=", "canvas", ".", "get_object_by_tag", "(", "tag", ")", "if", "cobj", ".", "kind", ...
Highlight all markings inside user drawn box on table.
[ "Highlight", "all", "markings", "inside", "user", "drawn", "box", "on", "table", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L598-L633
train
24,778
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.hl_canvas2table
def hl_canvas2table(self, canvas, button, data_x, data_y): """Highlight marking on table when user click on canvas.""" self.treeview.clear_selection() # Remove existing highlight if self.markhltag: try: canvas.delete_object_by_tag(self.markhltag, redraw=True) except Exception: pass # Nothing to do if no markings are displayed try: obj = canvas.get_object_by_tag(self.marktag) except Exception: return if obj.kind != 'compound': return # Nothing to do if table has no data if (len(self._xarr) == 0 or len(self._yarr) == 0 or len(self._treepaths) == 0): return sr = 10 # self.settings.get('searchradius', 10) dx = data_x - self._xarr dy = data_y - self._yarr dr = np.sqrt(dx * dx + dy * dy) mask = dr <= sr for hlpath in self._treepaths[mask]: self._highlight_path(hlpath)
python
def hl_canvas2table(self, canvas, button, data_x, data_y): """Highlight marking on table when user click on canvas.""" self.treeview.clear_selection() # Remove existing highlight if self.markhltag: try: canvas.delete_object_by_tag(self.markhltag, redraw=True) except Exception: pass # Nothing to do if no markings are displayed try: obj = canvas.get_object_by_tag(self.marktag) except Exception: return if obj.kind != 'compound': return # Nothing to do if table has no data if (len(self._xarr) == 0 or len(self._yarr) == 0 or len(self._treepaths) == 0): return sr = 10 # self.settings.get('searchradius', 10) dx = data_x - self._xarr dy = data_y - self._yarr dr = np.sqrt(dx * dx + dy * dy) mask = dr <= sr for hlpath in self._treepaths[mask]: self._highlight_path(hlpath)
[ "def", "hl_canvas2table", "(", "self", ",", "canvas", ",", "button", ",", "data_x", ",", "data_y", ")", ":", "self", ".", "treeview", ".", "clear_selection", "(", ")", "# Remove existing highlight", "if", "self", ".", "markhltag", ":", "try", ":", "canvas", ...
Highlight marking on table when user click on canvas.
[ "Highlight", "marking", "on", "table", "when", "user", "click", "on", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L636-L668
train
24,779
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark._highlight_path
def _highlight_path(self, hlpath): """Highlight an entry in the table and associated marking.""" self.logger.debug('Highlighting {0}'.format(hlpath)) self.treeview.select_path(hlpath) # TODO: Does not work in Qt. This is known issue in Ginga. self.treeview.scroll_to_path(hlpath)
python
def _highlight_path(self, hlpath): """Highlight an entry in the table and associated marking.""" self.logger.debug('Highlighting {0}'.format(hlpath)) self.treeview.select_path(hlpath) # TODO: Does not work in Qt. This is known issue in Ginga. self.treeview.scroll_to_path(hlpath)
[ "def", "_highlight_path", "(", "self", ",", "hlpath", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Highlighting {0}'", ".", "format", "(", "hlpath", ")", ")", "self", ".", "treeview", ".", "select_path", "(", "hlpath", ")", "# TODO: Does not work in...
Highlight an entry in the table and associated marking.
[ "Highlight", "an", "entry", "in", "the", "table", "and", "associated", "marking", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L670-L676
train
24,780
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.set_marktype_cb
def set_marktype_cb(self, w, index): """Set type of marking.""" self.marktype = self._mark_options[index] # Mark size is not used for point if self.marktype != 'point': self.w.mark_size.set_enabled(True) else: self.w.mark_size.set_enabled(False)
python
def set_marktype_cb(self, w, index): """Set type of marking.""" self.marktype = self._mark_options[index] # Mark size is not used for point if self.marktype != 'point': self.w.mark_size.set_enabled(True) else: self.w.mark_size.set_enabled(False)
[ "def", "set_marktype_cb", "(", "self", ",", "w", ",", "index", ")", ":", "self", ".", "marktype", "=", "self", ".", "_mark_options", "[", "index", "]", "# Mark size is not used for point", "if", "self", ".", "marktype", "!=", "'point'", ":", "self", ".", "...
Set type of marking.
[ "Set", "type", "of", "marking", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L678-L686
train
24,781
ejeschke/ginga
ginga/rv/plugins/TVMark.py
TVMark.set_markwidth
def set_markwidth(self): """Set width of marking.""" try: sz = int(self.w.mark_width.get_text()) except ValueError: self.logger.error('Cannot set mark width') self.w.mark_width.set_text(str(self.markwidth)) else: self.markwidth = sz
python
def set_markwidth(self): """Set width of marking.""" try: sz = int(self.w.mark_width.get_text()) except ValueError: self.logger.error('Cannot set mark width') self.w.mark_width.set_text(str(self.markwidth)) else: self.markwidth = sz
[ "def", "set_markwidth", "(", "self", ")", ":", "try", ":", "sz", "=", "int", "(", "self", ".", "w", ".", "mark_width", ".", "get_text", "(", ")", ")", "except", "ValueError", ":", "self", ".", "logger", ".", "error", "(", "'Cannot set mark width'", ")"...
Set width of marking.
[ "Set", "width", "of", "marking", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L702-L710
train
24,782
ejeschke/ginga
ginga/rv/plugins/Header.py
Header.redo
def redo(self, channel, image): """This is called when image changes.""" self._image = None # Skip cache checking in set_header() info = channel.extdata._header_info self.set_header(info, image)
python
def redo(self, channel, image): """This is called when image changes.""" self._image = None # Skip cache checking in set_header() info = channel.extdata._header_info self.set_header(info, image)
[ "def", "redo", "(", "self", ",", "channel", ",", "image", ")", ":", "self", ".", "_image", "=", "None", "# Skip cache checking in set_header()", "info", "=", "channel", ".", "extdata", ".", "_header_info", "self", ".", "set_header", "(", "info", ",", "image"...
This is called when image changes.
[ "This", "is", "called", "when", "image", "changes", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Header.py#L225-L230
train
24,783
ejeschke/ginga
ginga/rv/plugins/Header.py
Header.blank
def blank(self, channel): """This is called when image is cleared.""" self._image = None info = channel.extdata._header_info info.table.clear()
python
def blank(self, channel): """This is called when image is cleared.""" self._image = None info = channel.extdata._header_info info.table.clear()
[ "def", "blank", "(", "self", ",", "channel", ")", ":", "self", ".", "_image", "=", "None", "info", "=", "channel", ".", "extdata", ".", "_header_info", "info", ".", "table", ".", "clear", "(", ")" ]
This is called when image is cleared.
[ "This", "is", "called", "when", "image", "is", "cleared", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Header.py#L232-L236
train
24,784
ejeschke/ginga
ginga/examples/gw/clocks.py
Clock.clock_resized_cb
def clock_resized_cb(self, viewer, width, height): """This method is called when an individual clock is resized. It deletes and reconstructs the placement of the text objects in the canvas. """ self.logger.info("resized canvas to %dx%d" % (width, height)) # add text objects to canvas self.canvas.delete_all_objects() Text = self.canvas.get_draw_class('text') x, y = 20, int(height * 0.55) # text object for the time self.time_txt = Text(x, y, text='', color=self.color, font=self.font, fontsize=self.largesize, coord='window') self.canvas.add(self.time_txt, tag='_time', redraw=False) # for supplementary info (date, timezone, etc) self.suppl_txt = Text(x, height - 10, text='', color=self.color, font=self.font, fontsize=self.smallsize, coord='window') self.canvas.add(self.suppl_txt, tag='_suppl', redraw=False) self.canvas.update_canvas(whence=3)
python
def clock_resized_cb(self, viewer, width, height): """This method is called when an individual clock is resized. It deletes and reconstructs the placement of the text objects in the canvas. """ self.logger.info("resized canvas to %dx%d" % (width, height)) # add text objects to canvas self.canvas.delete_all_objects() Text = self.canvas.get_draw_class('text') x, y = 20, int(height * 0.55) # text object for the time self.time_txt = Text(x, y, text='', color=self.color, font=self.font, fontsize=self.largesize, coord='window') self.canvas.add(self.time_txt, tag='_time', redraw=False) # for supplementary info (date, timezone, etc) self.suppl_txt = Text(x, height - 10, text='', color=self.color, font=self.font, fontsize=self.smallsize, coord='window') self.canvas.add(self.suppl_txt, tag='_suppl', redraw=False) self.canvas.update_canvas(whence=3)
[ "def", "clock_resized_cb", "(", "self", ",", "viewer", ",", "width", ",", "height", ")", ":", "self", ".", "logger", ".", "info", "(", "\"resized canvas to %dx%d\"", "%", "(", "width", ",", "height", ")", ")", "# add text objects to canvas", "self", ".", "ca...
This method is called when an individual clock is resized. It deletes and reconstructs the placement of the text objects in the canvas.
[ "This", "method", "is", "called", "when", "an", "individual", "clock", "is", "resized", ".", "It", "deletes", "and", "reconstructs", "the", "placement", "of", "the", "text", "objects", "in", "the", "canvas", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gw/clocks.py#L82-L106
train
24,785
ejeschke/ginga
ginga/examples/gw/clocks.py
Clock.update_clock
def update_clock(self, dt): """This method is called by the ClockApp whenever the timer fires to update the clock. `dt` is a timezone-aware datetime object. """ dt = dt.astimezone(self.tzinfo) fmt = "%H:%M" if self.show_seconds: fmt = "%H:%M:%S" self.time_txt.text = dt.strftime(fmt) suppl_text = "{0} {1}".format(dt.strftime("%Y-%m-%d"), self.timezone) self.suppl_txt.text = suppl_text self.viewer.redraw(whence=3)
python
def update_clock(self, dt): """This method is called by the ClockApp whenever the timer fires to update the clock. `dt` is a timezone-aware datetime object. """ dt = dt.astimezone(self.tzinfo) fmt = "%H:%M" if self.show_seconds: fmt = "%H:%M:%S" self.time_txt.text = dt.strftime(fmt) suppl_text = "{0} {1}".format(dt.strftime("%Y-%m-%d"), self.timezone) self.suppl_txt.text = suppl_text self.viewer.redraw(whence=3)
[ "def", "update_clock", "(", "self", ",", "dt", ")", ":", "dt", "=", "dt", ".", "astimezone", "(", "self", ".", "tzinfo", ")", "fmt", "=", "\"%H:%M\"", "if", "self", ".", "show_seconds", ":", "fmt", "=", "\"%H:%M:%S\"", "self", ".", "time_txt", ".", "...
This method is called by the ClockApp whenever the timer fires to update the clock. `dt` is a timezone-aware datetime object.
[ "This", "method", "is", "called", "by", "the", "ClockApp", "whenever", "the", "timer", "fires", "to", "update", "the", "clock", ".", "dt", "is", "a", "timezone", "-", "aware", "datetime", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gw/clocks.py#L108-L122
train
24,786
ejeschke/ginga
ginga/examples/gw/clocks.py
ClockApp.add_clock
def add_clock(self, timezone, color='lightgreen', show_seconds=None): """Add a clock to the grid. `timezone` is a string representing a valid timezone. """ if show_seconds is None: show_seconds = self.options.show_seconds clock = Clock(self.app, self.logger, timezone, color=color, font=self.options.font, show_seconds=show_seconds) clock.widget.cfg_expand(0x7, 0x7) num_clocks = len(self.clocks) cols = self.settings.get('columns') row = num_clocks // cols col = num_clocks % cols self.clocks[timezone] = clock self.grid.add_widget(clock.widget, row, col, stretch=1)
python
def add_clock(self, timezone, color='lightgreen', show_seconds=None): """Add a clock to the grid. `timezone` is a string representing a valid timezone. """ if show_seconds is None: show_seconds = self.options.show_seconds clock = Clock(self.app, self.logger, timezone, color=color, font=self.options.font, show_seconds=show_seconds) clock.widget.cfg_expand(0x7, 0x7) num_clocks = len(self.clocks) cols = self.settings.get('columns') row = num_clocks // cols col = num_clocks % cols self.clocks[timezone] = clock self.grid.add_widget(clock.widget, row, col, stretch=1)
[ "def", "add_clock", "(", "self", ",", "timezone", ",", "color", "=", "'lightgreen'", ",", "show_seconds", "=", "None", ")", ":", "if", "show_seconds", "is", "None", ":", "show_seconds", "=", "self", ".", "options", ".", "show_seconds", "clock", "=", "Clock...
Add a clock to the grid. `timezone` is a string representing a valid timezone.
[ "Add", "a", "clock", "to", "the", "grid", ".", "timezone", "is", "a", "string", "representing", "a", "valid", "timezone", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gw/clocks.py#L232-L249
train
24,787
ejeschke/ginga
ginga/examples/gw/clocks.py
ClockApp.timer_cb
def timer_cb(self, timer): """Timer callback. Update all our clocks.""" dt_now = datetime.utcnow().replace(tzinfo=pytz.utc) self.logger.debug("timer fired. utc time is '%s'" % (str(dt_now))) for clock in self.clocks.values(): clock.update_clock(dt_now) # update clocks approx every second timer.start(1.0)
python
def timer_cb(self, timer): """Timer callback. Update all our clocks.""" dt_now = datetime.utcnow().replace(tzinfo=pytz.utc) self.logger.debug("timer fired. utc time is '%s'" % (str(dt_now))) for clock in self.clocks.values(): clock.update_clock(dt_now) # update clocks approx every second timer.start(1.0)
[ "def", "timer_cb", "(", "self", ",", "timer", ")", ":", "dt_now", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "self", ".", "logger", ".", "debug", "(", "\"timer fired. utc time is '%s'\"", "%", ...
Timer callback. Update all our clocks.
[ "Timer", "callback", ".", "Update", "all", "our", "clocks", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gw/clocks.py#L251-L260
train
24,788
ejeschke/ginga
ginga/table/TableView.py
TableViewGw.set_table_cb
def set_table_cb(self, viewer, table): """Display the given table object.""" self.clear() tree_dict = OrderedDict() # Extract data as astropy table a_tab = table.get_data() # Fill masked values, if applicable try: a_tab = a_tab.filled() except Exception: # Just use original table pass # This is to get around table widget not sorting numbers properly i_fmt = '{{0:0{0}d}}'.format(len(str(len(a_tab)))) # Table header with units columns = [('Row', '_DISPLAY_ROW')] for c in a_tab.columns.values(): col_str = '{0:^s}\n{1:^s}'.format(c.name, str(c.unit)) columns.append((col_str, c.name)) self.widget.setup_table(columns, 1, '_DISPLAY_ROW') # Table contents for i, row in enumerate(a_tab, 1): bnch = Bunch.Bunch(zip(row.colnames, row.as_void())) i_str = i_fmt.format(i) bnch['_DISPLAY_ROW'] = i_str tree_dict[i_str] = bnch self.widget.set_tree(tree_dict) # Resize column widths n_rows = len(tree_dict) if n_rows < self.settings.get('max_rows_for_col_resize', 5000): self.widget.set_optimal_column_widths() self.logger.debug('Resized columns for {0} row(s)'.format(n_rows)) tablename = table.get('name', 'NoName') self.logger.debug('Displayed {0}'.format(tablename))
python
def set_table_cb(self, viewer, table): """Display the given table object.""" self.clear() tree_dict = OrderedDict() # Extract data as astropy table a_tab = table.get_data() # Fill masked values, if applicable try: a_tab = a_tab.filled() except Exception: # Just use original table pass # This is to get around table widget not sorting numbers properly i_fmt = '{{0:0{0}d}}'.format(len(str(len(a_tab)))) # Table header with units columns = [('Row', '_DISPLAY_ROW')] for c in a_tab.columns.values(): col_str = '{0:^s}\n{1:^s}'.format(c.name, str(c.unit)) columns.append((col_str, c.name)) self.widget.setup_table(columns, 1, '_DISPLAY_ROW') # Table contents for i, row in enumerate(a_tab, 1): bnch = Bunch.Bunch(zip(row.colnames, row.as_void())) i_str = i_fmt.format(i) bnch['_DISPLAY_ROW'] = i_str tree_dict[i_str] = bnch self.widget.set_tree(tree_dict) # Resize column widths n_rows = len(tree_dict) if n_rows < self.settings.get('max_rows_for_col_resize', 5000): self.widget.set_optimal_column_widths() self.logger.debug('Resized columns for {0} row(s)'.format(n_rows)) tablename = table.get('name', 'NoName') self.logger.debug('Displayed {0}'.format(tablename))
[ "def", "set_table_cb", "(", "self", ",", "viewer", ",", "table", ")", ":", "self", ".", "clear", "(", ")", "tree_dict", "=", "OrderedDict", "(", ")", "# Extract data as astropy table", "a_tab", "=", "table", ".", "get_data", "(", ")", "# Fill masked values, if...
Display the given table object.
[ "Display", "the", "given", "table", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/table/TableView.py#L118-L159
train
24,789
ejeschke/ginga
ginga/rv/plugins/ChangeHistory.py
ChangeHistory.build_gui
def build_gui(self, container): """This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. """ vbox, sw, self.orientation = Widgets.get_oriented_box(container) vbox.set_border_width(4) vbox.set_spacing(2) # create the Treeview always_expand = self.settings.get('always_expand', True) color_alternate = self.settings.get('color_alternate_rows', True) treeview = Widgets.TreeView(auto_expand=always_expand, sortable=True, use_alt_row_color=color_alternate) self.treeview = treeview treeview.setup_table(self.columns, 3, 'MODIFIED') treeview.set_column_width(0, self.settings.get('ts_colwidth', 250)) treeview.add_callback('selected', self.show_more) vbox.add_widget(treeview, stretch=1) fr = Widgets.Frame('Selected History') captions = (('Channel:', 'label', 'chname', 'llabel'), ('Image:', 'label', 'imname', 'llabel'), ('Timestamp:', 'label', 'modified', 'llabel')) w, b = Widgets.build_info(captions) self.w.update(b) b.chname.set_text('') b.chname.set_tooltip('Channel name') b.imname.set_text('') b.imname.set_tooltip('Image name') b.modified.set_text('') b.modified.set_tooltip('Timestamp (UTC)') captions = (('Description:-', 'llabel'), ('descrip', 'textarea')) w2, b = Widgets.build_info(captions) self.w.update(b) b.descrip.set_editable(False) b.descrip.set_wrap(True) b.descrip.set_text('') b.descrip.set_tooltip('Displays selected history entry') vbox2 = Widgets.VBox() vbox2.set_border_width(4) vbox2.add_widget(w) vbox2.add_widget(w2) fr.set_widget(vbox2, stretch=0) vbox.add_widget(fr, stretch=0) container.add_widget(vbox, stretch=1) btns = Widgets.HBox() btns.set_spacing(3) btn = Widgets.Button('Close') btn.add_callback('activated', lambda w: self.close()) btns.add_widget(btn, stretch=0) btn = Widgets.Button("Help") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) container.add_widget(btns, stretch=0) self.gui_up = True
python
def build_gui(self, container): """This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. """ vbox, sw, self.orientation = Widgets.get_oriented_box(container) vbox.set_border_width(4) vbox.set_spacing(2) # create the Treeview always_expand = self.settings.get('always_expand', True) color_alternate = self.settings.get('color_alternate_rows', True) treeview = Widgets.TreeView(auto_expand=always_expand, sortable=True, use_alt_row_color=color_alternate) self.treeview = treeview treeview.setup_table(self.columns, 3, 'MODIFIED') treeview.set_column_width(0, self.settings.get('ts_colwidth', 250)) treeview.add_callback('selected', self.show_more) vbox.add_widget(treeview, stretch=1) fr = Widgets.Frame('Selected History') captions = (('Channel:', 'label', 'chname', 'llabel'), ('Image:', 'label', 'imname', 'llabel'), ('Timestamp:', 'label', 'modified', 'llabel')) w, b = Widgets.build_info(captions) self.w.update(b) b.chname.set_text('') b.chname.set_tooltip('Channel name') b.imname.set_text('') b.imname.set_tooltip('Image name') b.modified.set_text('') b.modified.set_tooltip('Timestamp (UTC)') captions = (('Description:-', 'llabel'), ('descrip', 'textarea')) w2, b = Widgets.build_info(captions) self.w.update(b) b.descrip.set_editable(False) b.descrip.set_wrap(True) b.descrip.set_text('') b.descrip.set_tooltip('Displays selected history entry') vbox2 = Widgets.VBox() vbox2.set_border_width(4) vbox2.add_widget(w) vbox2.add_widget(w2) fr.set_widget(vbox2, stretch=0) vbox.add_widget(fr, stretch=0) container.add_widget(vbox, stretch=1) btns = Widgets.HBox() btns.set_spacing(3) btn = Widgets.Button('Close') btn.add_callback('activated', lambda w: self.close()) btns.add_widget(btn, stretch=0) btn = Widgets.Button("Help") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) container.add_widget(btns, stretch=0) self.gui_up = True
[ "def", "build_gui", "(", "self", ",", "container", ")", ":", "vbox", ",", "sw", ",", "self", ".", "orientation", "=", "Widgets", ".", "get_oriented_box", "(", "container", ")", "vbox", ".", "set_border_width", "(", "4", ")", "vbox", ".", "set_spacing", "...
This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed.
[ "This", "method", "is", "called", "when", "the", "plugin", "is", "invoked", ".", "It", "builds", "the", "GUI", "used", "by", "the", "plugin", "into", "the", "widget", "layout", "passed", "as", "container", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ChangeHistory.py#L75-L149
train
24,790
ejeschke/ginga
ginga/rv/plugins/ChangeHistory.py
ChangeHistory.redo
def redo(self, channel, image): """Add an entry with image modification info.""" chname = channel.name if image is None: # shouldn't happen, but let's play it safe return imname = image.get('name', 'none') iminfo = channel.get_image_info(imname) timestamp = iminfo.time_modified if timestamp is None: reason = iminfo.get('reason_modified', None) if reason is not None: self.fv.show_error( "{0} invoked 'modified' callback to ChangeHistory with a " "reason but without a timestamp. The plugin invoking the " "callback is no longer be compatible with Ginga. " "Please contact plugin developer to update the plugin " "to use self.fv.update_image_info() like Mosaic " "plugin.".format(imname)) # Image somehow lost its history self.remove_image_info_cb(self.fv, channel, iminfo) return self.add_entry(chname, iminfo)
python
def redo(self, channel, image): """Add an entry with image modification info.""" chname = channel.name if image is None: # shouldn't happen, but let's play it safe return imname = image.get('name', 'none') iminfo = channel.get_image_info(imname) timestamp = iminfo.time_modified if timestamp is None: reason = iminfo.get('reason_modified', None) if reason is not None: self.fv.show_error( "{0} invoked 'modified' callback to ChangeHistory with a " "reason but without a timestamp. The plugin invoking the " "callback is no longer be compatible with Ginga. " "Please contact plugin developer to update the plugin " "to use self.fv.update_image_info() like Mosaic " "plugin.".format(imname)) # Image somehow lost its history self.remove_image_info_cb(self.fv, channel, iminfo) return self.add_entry(chname, iminfo)
[ "def", "redo", "(", "self", ",", "channel", ",", "image", ")", ":", "chname", "=", "channel", ".", "name", "if", "image", "is", "None", ":", "# shouldn't happen, but let's play it safe", "return", "imname", "=", "image", ".", "get", "(", "'name'", ",", "'n...
Add an entry with image modification info.
[ "Add", "an", "entry", "with", "image", "modification", "info", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ChangeHistory.py#L181-L207
train
24,791
ejeschke/ginga
ginga/rv/plugins/ChangeHistory.py
ChangeHistory.remove_image_info_cb
def remove_image_info_cb(self, gshell, channel, iminfo): """Delete entries related to deleted image.""" chname = channel.name if chname not in self.name_dict: return fileDict = self.name_dict[chname] name = iminfo.name if name not in fileDict: return del fileDict[name] self.logger.debug('{0} removed from ChangeHistory'.format(name)) if not self.gui_up: return False self.clear_selected_history() self.recreate_toc()
python
def remove_image_info_cb(self, gshell, channel, iminfo): """Delete entries related to deleted image.""" chname = channel.name if chname not in self.name_dict: return fileDict = self.name_dict[chname] name = iminfo.name if name not in fileDict: return del fileDict[name] self.logger.debug('{0} removed from ChangeHistory'.format(name)) if not self.gui_up: return False self.clear_selected_history() self.recreate_toc()
[ "def", "remove_image_info_cb", "(", "self", ",", "gshell", ",", "channel", ",", "iminfo", ")", ":", "chname", "=", "channel", ".", "name", "if", "chname", "not", "in", "self", ".", "name_dict", ":", "return", "fileDict", "=", "self", ".", "name_dict", "[...
Delete entries related to deleted image.
[ "Delete", "entries", "related", "to", "deleted", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ChangeHistory.py#L238-L257
train
24,792
ejeschke/ginga
ginga/rv/plugins/ChangeHistory.py
ChangeHistory.add_image_info_cb
def add_image_info_cb(self, gshell, channel, iminfo): """Add entries related to an added image.""" timestamp = iminfo.time_modified if timestamp is None: # Not an image we are interested in tracking return self.add_entry(channel.name, iminfo)
python
def add_image_info_cb(self, gshell, channel, iminfo): """Add entries related to an added image.""" timestamp = iminfo.time_modified if timestamp is None: # Not an image we are interested in tracking return self.add_entry(channel.name, iminfo)
[ "def", "add_image_info_cb", "(", "self", ",", "gshell", ",", "channel", ",", "iminfo", ")", ":", "timestamp", "=", "iminfo", ".", "time_modified", "if", "timestamp", "is", "None", ":", "# Not an image we are interested in tracking", "return", "self", ".", "add_ent...
Add entries related to an added image.
[ "Add", "entries", "related", "to", "an", "added", "image", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/ChangeHistory.py#L259-L267
train
24,793
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
Thumbs.drag_drop_cb
def drag_drop_cb(self, viewer, urls): """Punt drag-drops to the ginga shell. """ channel = self.fv.get_current_channel() if channel is None: return self.fv.open_uris(urls, chname=channel.name, bulk_add=True) return True
python
def drag_drop_cb(self, viewer, urls): """Punt drag-drops to the ginga shell. """ channel = self.fv.get_current_channel() if channel is None: return self.fv.open_uris(urls, chname=channel.name, bulk_add=True) return True
[ "def", "drag_drop_cb", "(", "self", ",", "viewer", ",", "urls", ")", ":", "channel", "=", "self", ".", "fv", ".", "get_current_channel", "(", ")", "if", "channel", "is", "None", ":", "return", "self", ".", "fv", ".", "open_uris", "(", "urls", ",", "c...
Punt drag-drops to the ginga shell.
[ "Punt", "drag", "-", "drops", "to", "the", "ginga", "shell", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L223-L230
train
24,794
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
Thumbs.update_highlights
def update_highlights(self, old_highlight_set, new_highlight_set): """Unhighlight the thumbnails represented by `old_highlight_set` and highlight the ones represented by new_highlight_set. Both are sets of thumbkeys. """ with self.thmblock: un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # highlight new labels that should be bg = self.settings.get('label_bg_color', 'lightgreen') fg = self.settings.get('label_font_color', 'black') # unhighlight thumb labels that should NOT be highlighted any more for thumbkey in un_hilite_set: if thumbkey in self.thumb_dict: namelbl = self.thumb_dict[thumbkey].get('namelbl') namelbl.color = fg for thumbkey in re_hilite_set: if thumbkey in self.thumb_dict: namelbl = self.thumb_dict[thumbkey].get('namelbl') namelbl.color = bg if self.gui_up: self.c_view.redraw(whence=3)
python
def update_highlights(self, old_highlight_set, new_highlight_set): """Unhighlight the thumbnails represented by `old_highlight_set` and highlight the ones represented by new_highlight_set. Both are sets of thumbkeys. """ with self.thmblock: un_hilite_set = old_highlight_set - new_highlight_set re_hilite_set = new_highlight_set - old_highlight_set # highlight new labels that should be bg = self.settings.get('label_bg_color', 'lightgreen') fg = self.settings.get('label_font_color', 'black') # unhighlight thumb labels that should NOT be highlighted any more for thumbkey in un_hilite_set: if thumbkey in self.thumb_dict: namelbl = self.thumb_dict[thumbkey].get('namelbl') namelbl.color = fg for thumbkey in re_hilite_set: if thumbkey in self.thumb_dict: namelbl = self.thumb_dict[thumbkey].get('namelbl') namelbl.color = bg if self.gui_up: self.c_view.redraw(whence=3)
[ "def", "update_highlights", "(", "self", ",", "old_highlight_set", ",", "new_highlight_set", ")", ":", "with", "self", ".", "thmblock", ":", "un_hilite_set", "=", "old_highlight_set", "-", "new_highlight_set", "re_hilite_set", "=", "new_highlight_set", "-", "old_highl...
Unhighlight the thumbnails represented by `old_highlight_set` and highlight the ones represented by new_highlight_set. Both are sets of thumbkeys.
[ "Unhighlight", "the", "thumbnails", "represented", "by", "old_highlight_set", "and", "highlight", "the", "ones", "represented", "by", "new_highlight_set", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L483-L510
train
24,795
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
Thumbs.have_thumbnail
def have_thumbnail(self, fitsimage, image): """Returns True if we already have a thumbnail version of this image cached, False otherwise. """ chname = self.fv.get_channel_name(fitsimage) # Look up our version of the thumb idx = image.get('idx', None) path = image.get('path', None) if path is not None: path = os.path.abspath(path) name = iohelper.name_image_from_path(path, idx=idx) else: name = 'NoName' # get image name name = image.get('name', name) thumbkey = self.get_thumb_key(chname, name, path) with self.thmblock: return thumbkey in self.thumb_dict
python
def have_thumbnail(self, fitsimage, image): """Returns True if we already have a thumbnail version of this image cached, False otherwise. """ chname = self.fv.get_channel_name(fitsimage) # Look up our version of the thumb idx = image.get('idx', None) path = image.get('path', None) if path is not None: path = os.path.abspath(path) name = iohelper.name_image_from_path(path, idx=idx) else: name = 'NoName' # get image name name = image.get('name', name) thumbkey = self.get_thumb_key(chname, name, path) with self.thmblock: return thumbkey in self.thumb_dict
[ "def", "have_thumbnail", "(", "self", ",", "fitsimage", ",", "image", ")", ":", "chname", "=", "self", ".", "fv", ".", "get_channel_name", "(", "fitsimage", ")", "# Look up our version of the thumb", "idx", "=", "image", ".", "get", "(", "'idx'", ",", "None"...
Returns True if we already have a thumbnail version of this image cached, False otherwise.
[ "Returns", "True", "if", "we", "already", "have", "a", "thumbnail", "version", "of", "this", "image", "cached", "False", "otherwise", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L546-L566
train
24,796
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
Thumbs.auto_scroll
def auto_scroll(self, thumbkey): """Scroll the window to the thumb.""" if not self.gui_up: return # force scroll to bottom of thumbs, if checkbox is set scrollp = self.w.auto_scroll.get_state() if not scrollp: return bnch = self.thumb_dict[thumbkey] # override X parameter because we only want to scroll vertically pan_x, pan_y = self.c_view.get_pan() self.c_view.panset_xy(pan_x, bnch.image.y)
python
def auto_scroll(self, thumbkey): """Scroll the window to the thumb.""" if not self.gui_up: return # force scroll to bottom of thumbs, if checkbox is set scrollp = self.w.auto_scroll.get_state() if not scrollp: return bnch = self.thumb_dict[thumbkey] # override X parameter because we only want to scroll vertically pan_x, pan_y = self.c_view.get_pan() self.c_view.panset_xy(pan_x, bnch.image.y)
[ "def", "auto_scroll", "(", "self", ",", "thumbkey", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "# force scroll to bottom of thumbs, if checkbox is set", "scrollp", "=", "self", ".", "w", ".", "auto_scroll", ".", "get_state", "(", ")", "if", "...
Scroll the window to the thumb.
[ "Scroll", "the", "window", "to", "the", "thumb", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L1011-L1024
train
24,797
ejeschke/ginga
ginga/rv/plugins/Thumbs.py
Thumbs.clear_widget
def clear_widget(self): """ Clears the thumbnail display widget of all thumbnails, but does not remove them from the thumb_dict or thumb_list. """ if not self.gui_up: return canvas = self.c_view.get_canvas() canvas.delete_all_objects() self.c_view.redraw(whence=0)
python
def clear_widget(self): """ Clears the thumbnail display widget of all thumbnails, but does not remove them from the thumb_dict or thumb_list. """ if not self.gui_up: return canvas = self.c_view.get_canvas() canvas.delete_all_objects() self.c_view.redraw(whence=0)
[ "def", "clear_widget", "(", "self", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "canvas", "=", "self", ".", "c_view", ".", "get_canvas", "(", ")", "canvas", ".", "delete_all_objects", "(", ")", "self", ".", "c_view", ".", "redraw", "("...
Clears the thumbnail display widget of all thumbnails, but does not remove them from the thumb_dict or thumb_list.
[ "Clears", "the", "thumbnail", "display", "widget", "of", "all", "thumbnails", "but", "does", "not", "remove", "them", "from", "the", "thumb_dict", "or", "thumb_list", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Thumbs.py#L1026-L1035
train
24,798
ejeschke/ginga
ginga/AstroImage.py
AstroImage.load_nddata
def load_nddata(self, ndd, naxispath=None): """Load from an astropy.nddata.NDData object. """ self.clear_metadata() # Make a header based on any NDData metadata ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) if ndd.wcs is None: # no wcs in ndd obj--let's try to make one from the header self.wcs = wcsmod.WCS(logger=self.logger) self.wcs.load_header(ahdr) else: # already have a valid wcs in the ndd object # we assume it needs an astropy compatible wcs wcsinfo = wcsmod.get_wcs_class('astropy') self.wcs = wcsinfo.wrapper_class(logger=self.logger) self.wcs.load_nddata(ndd)
python
def load_nddata(self, ndd, naxispath=None): """Load from an astropy.nddata.NDData object. """ self.clear_metadata() # Make a header based on any NDData metadata ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) if ndd.wcs is None: # no wcs in ndd obj--let's try to make one from the header self.wcs = wcsmod.WCS(logger=self.logger) self.wcs.load_header(ahdr) else: # already have a valid wcs in the ndd object # we assume it needs an astropy compatible wcs wcsinfo = wcsmod.get_wcs_class('astropy') self.wcs = wcsinfo.wrapper_class(logger=self.logger) self.wcs.load_nddata(ndd)
[ "def", "load_nddata", "(", "self", ",", "ndd", ",", "naxispath", "=", "None", ")", ":", "self", ".", "clear_metadata", "(", ")", "# Make a header based on any NDData metadata", "ahdr", "=", "self", ".", "get_header", "(", ")", "ahdr", ".", "update", "(", "nd...
Load from an astropy.nddata.NDData object.
[ "Load", "from", "an", "astropy", ".", "nddata", ".", "NDData", "object", "." ]
a78c893ec6f37a837de851947e9bb4625c597915
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/AstroImage.py#L146-L166
train
24,799