id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
26,300 | ejeschke/ginga | ginga/web/pgw/ipg.py | BasicCanvasView.embed | def embed(self, width=600, height=650):
"""
Embed a viewer into a Jupyter notebook.
"""
from IPython.display import IFrame
return IFrame(self.url, width, height) | python | def embed(self, width=600, height=650):
from IPython.display import IFrame
return IFrame(self.url, width, height) | [
"def",
"embed",
"(",
"self",
",",
"width",
"=",
"600",
",",
"height",
"=",
"650",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"IFrame",
"return",
"IFrame",
"(",
"self",
".",
"url",
",",
"width",
",",
"height",
")"
] | Embed a viewer into a Jupyter notebook. | [
"Embed",
"a",
"viewer",
"into",
"a",
"Jupyter",
"notebook",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L62-L67 |
26,301 | ejeschke/ginga | ginga/web/pgw/ipg.py | BasicCanvasView.load_fits | def load_fits(self, filepath):
"""
Load a FITS file into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.load_file(filepath)
self.set_image(image) | python | def load_fits(self, filepath):
image = AstroImage.AstroImage(logger=self.logger)
image.load_file(filepath)
self.set_image(image) | [
"def",
"load_fits",
"(",
"self",
",",
"filepath",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"image",
".",
"load_file",
"(",
"filepath",
")",
"self",
".",
"set_image",
"(",
"image",
")"
] | Load a FITS file into the viewer. | [
"Load",
"a",
"FITS",
"file",
"into",
"the",
"viewer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L96-L103 |
26,302 | ejeschke/ginga | ginga/web/pgw/ipg.py | BasicCanvasView.load_hdu | def load_hdu(self, hdu):
"""
Load an HDU into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.load_hdu(hdu)
self.set_image(image) | python | def load_hdu(self, hdu):
image = AstroImage.AstroImage(logger=self.logger)
image.load_hdu(hdu)
self.set_image(image) | [
"def",
"load_hdu",
"(",
"self",
",",
"hdu",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"image",
".",
"load_hdu",
"(",
"hdu",
")",
"self",
".",
"set_image",
"(",
"image",
")"
] | Load an HDU into the viewer. | [
"Load",
"an",
"HDU",
"into",
"the",
"viewer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L107-L114 |
26,303 | ejeschke/ginga | ginga/web/pgw/ipg.py | BasicCanvasView.load_data | def load_data(self, data_np):
"""
Load raw numpy data into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.set_data(data_np)
self.set_image(image) | python | def load_data(self, data_np):
image = AstroImage.AstroImage(logger=self.logger)
image.set_data(data_np)
self.set_image(image) | [
"def",
"load_data",
"(",
"self",
",",
"data_np",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"image",
".",
"set_data",
"(",
"data_np",
")",
"self",
".",
"set_image",
"(",
"image",
")"
] | Load raw numpy data into the viewer. | [
"Load",
"raw",
"numpy",
"data",
"into",
"the",
"viewer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L116-L123 |
26,304 | ejeschke/ginga | ginga/web/pgw/ipg.py | BasicCanvasView.set_html5_canvas_format | def set_html5_canvas_format(self, fmt):
"""
Sets the format used for rendering to the HTML5 canvas.
'png' offers greater clarity, especially for small text, but
does not have as good of performance as 'jpeg'.
"""
fmt = fmt.lower()
if fmt not in ('jpeg', 'png'):
raise ValueError("Format must be one of {jpeg|png} not '%s'" % (
fmt))
settings = self.get_settings()
settings.set(html5_canvas_format=fmt) | python | def set_html5_canvas_format(self, fmt):
fmt = fmt.lower()
if fmt not in ('jpeg', 'png'):
raise ValueError("Format must be one of {jpeg|png} not '%s'" % (
fmt))
settings = self.get_settings()
settings.set(html5_canvas_format=fmt) | [
"def",
"set_html5_canvas_format",
"(",
"self",
",",
"fmt",
")",
":",
"fmt",
"=",
"fmt",
".",
"lower",
"(",
")",
"if",
"fmt",
"not",
"in",
"(",
"'jpeg'",
",",
"'png'",
")",
":",
"raise",
"ValueError",
"(",
"\"Format must be one of {jpeg|png} not '%s'\"",
"%",... | Sets the format used for rendering to the HTML5 canvas.
'png' offers greater clarity, especially for small text, but
does not have as good of performance as 'jpeg'. | [
"Sets",
"the",
"format",
"used",
"for",
"rendering",
"to",
"the",
"HTML5",
"canvas",
".",
"png",
"offers",
"greater",
"clarity",
"especially",
"for",
"small",
"text",
"but",
"does",
"not",
"have",
"as",
"good",
"of",
"performance",
"as",
"jpeg",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L143-L155 |
26,305 | ejeschke/ginga | ginga/web/pgw/ipg.py | EnhancedCanvasView.build_gui | def build_gui(self, container):
"""
This is responsible for building the viewer's UI. It should
place the UI in `container`.
"""
vbox = Widgets.VBox()
vbox.set_border_width(2)
vbox.set_spacing(1)
w = Viewers.GingaViewerWidget(viewer=self)
vbox.add_widget(w, stretch=1)
# set up to capture cursor movement for reading out coordinates
# coordinates reported in base 1 or 0?
self.pixel_base = 1.0
self.readout = Widgets.Label("")
vbox.add_widget(self.readout, stretch=0)
#self.set_callback('none-move', self.motion_cb)
self.set_callback('cursor-changed', self.motion_cb)
# need to put this in an hbox with an expanding label or the
# browser wants to resize the canvas, distorting it
hbox = Widgets.HBox()
hbox.add_widget(vbox, stretch=0)
hbox.add_widget(Widgets.Label(''), stretch=1)
container.set_widget(hbox) | python | def build_gui(self, container):
vbox = Widgets.VBox()
vbox.set_border_width(2)
vbox.set_spacing(1)
w = Viewers.GingaViewerWidget(viewer=self)
vbox.add_widget(w, stretch=1)
# set up to capture cursor movement for reading out coordinates
# coordinates reported in base 1 or 0?
self.pixel_base = 1.0
self.readout = Widgets.Label("")
vbox.add_widget(self.readout, stretch=0)
#self.set_callback('none-move', self.motion_cb)
self.set_callback('cursor-changed', self.motion_cb)
# need to put this in an hbox with an expanding label or the
# browser wants to resize the canvas, distorting it
hbox = Widgets.HBox()
hbox.add_widget(vbox, stretch=0)
hbox.add_widget(Widgets.Label(''), stretch=1)
container.set_widget(hbox) | [
"def",
"build_gui",
"(",
"self",
",",
"container",
")",
":",
"vbox",
"=",
"Widgets",
".",
"VBox",
"(",
")",
"vbox",
".",
"set_border_width",
"(",
"2",
")",
"vbox",
".",
"set_spacing",
"(",
"1",
")",
"w",
"=",
"Viewers",
".",
"GingaViewerWidget",
"(",
... | This is responsible for building the viewer's UI. It should
place the UI in `container`. | [
"This",
"is",
"responsible",
"for",
"building",
"the",
"viewer",
"s",
"UI",
".",
"It",
"should",
"place",
"the",
"UI",
"in",
"container",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L168-L197 |
26,306 | ejeschke/ginga | ginga/web/pgw/ipg.py | ViewerFactory.get_viewer | def get_viewer(self, v_id, viewer_class=None, width=512, height=512,
force_new=False):
"""
Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one.
"""
if not force_new:
try:
return self.viewers[v_id]
except KeyError:
pass
# create top level window
window = self.app.make_window("Viewer %s" % v_id, wid=v_id)
# We get back a record with information about the viewer
v_info = self.make_viewer(window, viewer_class=viewer_class,
width=width, height=height)
# Save it under this viewer id
self.viewers[v_id] = v_info
return v_info | python | def get_viewer(self, v_id, viewer_class=None, width=512, height=512,
force_new=False):
if not force_new:
try:
return self.viewers[v_id]
except KeyError:
pass
# create top level window
window = self.app.make_window("Viewer %s" % v_id, wid=v_id)
# We get back a record with information about the viewer
v_info = self.make_viewer(window, viewer_class=viewer_class,
width=width, height=height)
# Save it under this viewer id
self.viewers[v_id] = v_info
return v_info | [
"def",
"get_viewer",
"(",
"self",
",",
"v_id",
",",
"viewer_class",
"=",
"None",
",",
"width",
"=",
"512",
",",
"height",
"=",
"512",
",",
"force_new",
"=",
"False",
")",
":",
"if",
"not",
"force_new",
":",
"try",
":",
"return",
"self",
".",
"viewers... | Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one. | [
"Get",
"an",
"existing",
"viewer",
"by",
"viewer",
"id",
".",
"If",
"the",
"viewer",
"does",
"not",
"yet",
"exist",
"make",
"a",
"new",
"one",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L315-L336 |
26,307 | ejeschke/ginga | ginga/rv/plugins/Pick.py | Pick.detailxy | def detailxy(self, canvas, button, data_x, data_y):
"""Motion event in the pick fits window. Show the pointing
information under the cursor.
"""
if button == 0:
# TODO: we could track the focus changes to make this check
# more efficient
chviewer = self.fv.getfocus_viewer()
# Don't update global information if our chviewer isn't focused
if chviewer != self.fitsimage:
return True
# Add offsets from cutout
data_x = data_x + self.pick_x1
data_y = data_y + self.pick_y1
return self.fv.showxy(chviewer, data_x, data_y) | python | def detailxy(self, canvas, button, data_x, data_y):
if button == 0:
# TODO: we could track the focus changes to make this check
# more efficient
chviewer = self.fv.getfocus_viewer()
# Don't update global information if our chviewer isn't focused
if chviewer != self.fitsimage:
return True
# Add offsets from cutout
data_x = data_x + self.pick_x1
data_y = data_y + self.pick_y1
return self.fv.showxy(chviewer, data_x, data_y) | [
"def",
"detailxy",
"(",
"self",
",",
"canvas",
",",
"button",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"button",
"==",
"0",
":",
"# TODO: we could track the focus changes to make this check",
"# more efficient",
"chviewer",
"=",
"self",
".",
"fv",
".",
"get... | Motion event in the pick fits window. Show the pointing
information under the cursor. | [
"Motion",
"event",
"in",
"the",
"pick",
"fits",
"window",
".",
"Show",
"the",
"pointing",
"information",
"under",
"the",
"cursor",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Pick.py#L1855-L1871 |
26,308 | ejeschke/ginga | ginga/rv/main.py | reference_viewer | def reference_viewer(sys_argv):
"""Create reference viewer from command line."""
viewer = ReferenceViewer(layout=default_layout)
viewer.add_default_plugins()
viewer.add_separately_distributed_plugins()
# Parse command line options with optparse module
from optparse import OptionParser
usage = "usage: %prog [options] cmd [args]"
optprs = OptionParser(usage=usage,
version=('%%prog %s' % version.version))
viewer.add_default_options(optprs)
(options, args) = optprs.parse_args(sys_argv[1:])
if options.display:
os.environ['DISPLAY'] = options.display
# Are we debugging this?
if options.debug:
import pdb
pdb.run('viewer.main(options, args)')
# Are we profiling this?
elif options.profile:
import profile
print(("%s profile:" % sys_argv[0]))
profile.run('viewer.main(options, args)')
else:
viewer.main(options, args) | python | def reference_viewer(sys_argv):
viewer = ReferenceViewer(layout=default_layout)
viewer.add_default_plugins()
viewer.add_separately_distributed_plugins()
# Parse command line options with optparse module
from optparse import OptionParser
usage = "usage: %prog [options] cmd [args]"
optprs = OptionParser(usage=usage,
version=('%%prog %s' % version.version))
viewer.add_default_options(optprs)
(options, args) = optprs.parse_args(sys_argv[1:])
if options.display:
os.environ['DISPLAY'] = options.display
# Are we debugging this?
if options.debug:
import pdb
pdb.run('viewer.main(options, args)')
# Are we profiling this?
elif options.profile:
import profile
print(("%s profile:" % sys_argv[0]))
profile.run('viewer.main(options, args)')
else:
viewer.main(options, args) | [
"def",
"reference_viewer",
"(",
"sys_argv",
")",
":",
"viewer",
"=",
"ReferenceViewer",
"(",
"layout",
"=",
"default_layout",
")",
"viewer",
".",
"add_default_plugins",
"(",
")",
"viewer",
".",
"add_separately_distributed_plugins",
"(",
")",
"# Parse command line opti... | Create reference viewer from command line. | [
"Create",
"reference",
"viewer",
"from",
"command",
"line",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/main.py#L692-L725 |
26,309 | ejeschke/ginga | ginga/rv/main.py | ReferenceViewer.add_default_plugins | def add_default_plugins(self, except_global=[], except_local=[]):
"""
Add the ginga-distributed default set of plugins to the
reference viewer.
"""
# add default global plugins
for spec in plugins:
ptype = spec.get('ptype', 'local')
if ptype == 'global' and spec.module not in except_global:
self.add_plugin_spec(spec)
if ptype == 'local' and spec.module not in except_local:
self.add_plugin_spec(spec) | python | def add_default_plugins(self, except_global=[], except_local=[]):
# add default global plugins
for spec in plugins:
ptype = spec.get('ptype', 'local')
if ptype == 'global' and spec.module not in except_global:
self.add_plugin_spec(spec)
if ptype == 'local' and spec.module not in except_local:
self.add_plugin_spec(spec) | [
"def",
"add_default_plugins",
"(",
"self",
",",
"except_global",
"=",
"[",
"]",
",",
"except_local",
"=",
"[",
"]",
")",
":",
"# add default global plugins",
"for",
"spec",
"in",
"plugins",
":",
"ptype",
"=",
"spec",
".",
"get",
"(",
"'ptype'",
",",
"'loca... | Add the ginga-distributed default set of plugins to the
reference viewer. | [
"Add",
"the",
"ginga",
"-",
"distributed",
"default",
"set",
"of",
"plugins",
"to",
"the",
"reference",
"viewer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/main.py#L181-L193 |
26,310 | ejeschke/ginga | ginga/rv/main.py | ReferenceViewer.add_default_options | def add_default_options(self, optprs):
"""
Adds the default reference viewer startup options to an
OptionParser instance `optprs`.
"""
optprs.add_option("--bufsize", dest="bufsize", metavar="NUM",
type="int", default=10,
help="Buffer length to NUM")
optprs.add_option('-c', "--channels", dest="channels",
help="Specify list of channels to create")
optprs.add_option("--debug", dest="debug", default=False,
action="store_true",
help="Enter the pdb debugger on main()")
optprs.add_option("--disable-plugins", dest="disable_plugins",
metavar="NAMES",
help="Specify plugins that should be disabled")
optprs.add_option("--display", dest="display", metavar="HOST:N",
help="Use X display on HOST:N")
optprs.add_option("--fitspkg", dest="fitspkg", metavar="NAME",
default=None,
help="Prefer FITS I/O module NAME")
optprs.add_option("-g", "--geometry", dest="geometry",
default=None, metavar="GEOM",
help="X geometry for initial size and placement")
optprs.add_option("--modules", dest="modules", metavar="NAMES",
help="Specify additional modules to load")
optprs.add_option("--norestore", dest="norestore", default=False,
action="store_true",
help="Don't restore the GUI from a saved layout")
optprs.add_option("--nosplash", dest="nosplash", default=False,
action="store_true",
help="Don't display the splash screen")
optprs.add_option("--numthreads", dest="numthreads", type="int",
default=30, metavar="NUM",
help="Start NUM threads in thread pool")
optprs.add_option("--opencv", dest="opencv", default=False,
action="store_true",
help="Use OpenCv acceleration")
optprs.add_option("--opencl", dest="opencl", default=False,
action="store_true",
help="Use OpenCL acceleration")
optprs.add_option("--plugins", dest="plugins", metavar="NAMES",
help="Specify additional plugins to load")
optprs.add_option("--profile", dest="profile", action="store_true",
default=False,
help="Run the profiler on main()")
optprs.add_option("--sep", dest="separate_channels", default=False,
action="store_true",
help="Load files in separate channels")
optprs.add_option("-t", "--toolkit", dest="toolkit", metavar="NAME",
default=None,
help="Prefer GUI toolkit (gtk|qt)")
optprs.add_option("--wcspkg", dest="wcspkg", metavar="NAME",
default=None,
help="Prefer WCS module NAME")
log.addlogopts(optprs) | python | def add_default_options(self, optprs):
optprs.add_option("--bufsize", dest="bufsize", metavar="NUM",
type="int", default=10,
help="Buffer length to NUM")
optprs.add_option('-c', "--channels", dest="channels",
help="Specify list of channels to create")
optprs.add_option("--debug", dest="debug", default=False,
action="store_true",
help="Enter the pdb debugger on main()")
optprs.add_option("--disable-plugins", dest="disable_plugins",
metavar="NAMES",
help="Specify plugins that should be disabled")
optprs.add_option("--display", dest="display", metavar="HOST:N",
help="Use X display on HOST:N")
optprs.add_option("--fitspkg", dest="fitspkg", metavar="NAME",
default=None,
help="Prefer FITS I/O module NAME")
optprs.add_option("-g", "--geometry", dest="geometry",
default=None, metavar="GEOM",
help="X geometry for initial size and placement")
optprs.add_option("--modules", dest="modules", metavar="NAMES",
help="Specify additional modules to load")
optprs.add_option("--norestore", dest="norestore", default=False,
action="store_true",
help="Don't restore the GUI from a saved layout")
optprs.add_option("--nosplash", dest="nosplash", default=False,
action="store_true",
help="Don't display the splash screen")
optprs.add_option("--numthreads", dest="numthreads", type="int",
default=30, metavar="NUM",
help="Start NUM threads in thread pool")
optprs.add_option("--opencv", dest="opencv", default=False,
action="store_true",
help="Use OpenCv acceleration")
optprs.add_option("--opencl", dest="opencl", default=False,
action="store_true",
help="Use OpenCL acceleration")
optprs.add_option("--plugins", dest="plugins", metavar="NAMES",
help="Specify additional plugins to load")
optprs.add_option("--profile", dest="profile", action="store_true",
default=False,
help="Run the profiler on main()")
optprs.add_option("--sep", dest="separate_channels", default=False,
action="store_true",
help="Load files in separate channels")
optprs.add_option("-t", "--toolkit", dest="toolkit", metavar="NAME",
default=None,
help="Prefer GUI toolkit (gtk|qt)")
optprs.add_option("--wcspkg", dest="wcspkg", metavar="NAME",
default=None,
help="Prefer WCS module NAME")
log.addlogopts(optprs) | [
"def",
"add_default_options",
"(",
"self",
",",
"optprs",
")",
":",
"optprs",
".",
"add_option",
"(",
"\"--bufsize\"",
",",
"dest",
"=",
"\"bufsize\"",
",",
"metavar",
"=",
"\"NUM\"",
",",
"type",
"=",
"\"int\"",
",",
"default",
"=",
"10",
",",
"help",
"... | Adds the default reference viewer startup options to an
OptionParser instance `optprs`. | [
"Adds",
"the",
"default",
"reference",
"viewer",
"startup",
"options",
"to",
"an",
"OptionParser",
"instance",
"optprs",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/main.py#L219-L274 |
26,311 | ejeschke/ginga | ginga/gw/GwMain.py | GwMain.gui_call | def gui_call(self, method, *args, **kwdargs):
"""General method for synchronously calling into the GUI.
This waits until the method has completed before returning.
"""
my_id = thread.get_ident()
if my_id == self.gui_thread_id:
return method(*args, **kwdargs)
else:
future = self.gui_do(method, *args, **kwdargs)
return future.wait() | python | def gui_call(self, method, *args, **kwdargs):
my_id = thread.get_ident()
if my_id == self.gui_thread_id:
return method(*args, **kwdargs)
else:
future = self.gui_do(method, *args, **kwdargs)
return future.wait() | [
"def",
"gui_call",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwdargs",
")",
":",
"my_id",
"=",
"thread",
".",
"get_ident",
"(",
")",
"if",
"my_id",
"==",
"self",
".",
"gui_thread_id",
":",
"return",
"method",
"(",
"*",
"args",
"... | General method for synchronously calling into the GUI.
This waits until the method has completed before returning. | [
"General",
"method",
"for",
"synchronously",
"calling",
"into",
"the",
"GUI",
".",
"This",
"waits",
"until",
"the",
"method",
"has",
"completed",
"before",
"returning",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gw/GwMain.py#L170-L179 |
26,312 | ejeschke/ginga | ginga/rv/plugins/WBrowser.py | WBrowser.show_help | def show_help(self, plugin=None, no_url_callback=None):
"""See `~ginga.GingaPlugin` for usage of optional keywords."""
if not Widgets.has_webkit:
return
self.fv.nongui_do(self._download_doc, plugin=plugin,
no_url_callback=no_url_callback) | python | def show_help(self, plugin=None, no_url_callback=None):
if not Widgets.has_webkit:
return
self.fv.nongui_do(self._download_doc, plugin=plugin,
no_url_callback=no_url_callback) | [
"def",
"show_help",
"(",
"self",
",",
"plugin",
"=",
"None",
",",
"no_url_callback",
"=",
"None",
")",
":",
"if",
"not",
"Widgets",
".",
"has_webkit",
":",
"return",
"self",
".",
"fv",
".",
"nongui_do",
"(",
"self",
".",
"_download_doc",
",",
"plugin",
... | See `~ginga.GingaPlugin` for usage of optional keywords. | [
"See",
"~ginga",
".",
"GingaPlugin",
"for",
"usage",
"of",
"optional",
"keywords",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/WBrowser.py#L129-L135 |
26,313 | ejeschke/ginga | ginga/util/iqcalc.py | get_mean | def get_mean(data_np):
"""Calculate mean for valid values.
Parameters
----------
data_np : ndarray
Input array.
Returns
-------
result : float
Mean of array values that are finite.
If array contains no finite values, returns NaN.
"""
i = np.isfinite(data_np)
if not np.any(i):
return np.nan
return np.mean(data_np[i]) | python | def get_mean(data_np):
i = np.isfinite(data_np)
if not np.any(i):
return np.nan
return np.mean(data_np[i]) | [
"def",
"get_mean",
"(",
"data_np",
")",
":",
"i",
"=",
"np",
".",
"isfinite",
"(",
"data_np",
")",
"if",
"not",
"np",
".",
"any",
"(",
"i",
")",
":",
"return",
"np",
".",
"nan",
"return",
"np",
".",
"mean",
"(",
"data_np",
"[",
"i",
"]",
")"
] | Calculate mean for valid values.
Parameters
----------
data_np : ndarray
Input array.
Returns
-------
result : float
Mean of array values that are finite.
If array contains no finite values, returns NaN. | [
"Calculate",
"mean",
"for",
"valid",
"values",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iqcalc.py#L25-L43 |
26,314 | ejeschke/ginga | ginga/util/iqcalc.py | IQCalc.calc_fwhm_gaussian | def calc_fwhm_gaussian(self, arr1d, medv=None, gauss_fn=None):
"""FWHM calculation on a 1D array by using least square fitting of
a gaussian function on the data. arr1d is a 1D array cut in either
X or Y direction on the object.
"""
if gauss_fn is None:
gauss_fn = self.gaussian
N = len(arr1d)
X = np.array(list(range(N)))
Y = arr1d
# Fitting works more reliably if we do the following
# a. subtract sky background
if medv is None:
medv = get_median(Y)
Y = Y - medv
maxv = Y.max()
# b. clamp to 0..max (of the sky subtracted field)
Y = Y.clip(0, maxv)
# Fit a gaussian
p0 = [0, N - 1, maxv] # Inital guess
# Distance to the target function
errfunc = lambda p, x, y: gauss_fn(x, p) - y # noqa
# Least square fit to the gaussian
with self.lock:
# NOTE: without this mutex, optimize.leastsq causes a fatal error
# sometimes--it appears not to be thread safe.
# The error is:
# "SystemError: null argument to internal routine"
# "Fatal Python error: GC object already tracked"
p1, success = optimize.leastsq(errfunc, p0[:], args=(X, Y))
if not success:
raise IQCalcError("FWHM gaussian fitting failed")
mu, sdev, maxv = p1
self.logger.debug("mu=%f sdev=%f maxv=%f" % (mu, sdev, maxv))
# Now that we have the sdev from fitting, we can calculate FWHM
fwhm = 2.0 * np.sqrt(2.0 * np.log(2.0)) * sdev
# some routines choke on numpy values and need "pure" Python floats
# e.g. when marshalling through a remote procedure interface
fwhm = float(fwhm)
mu = float(mu)
sdev = float(sdev)
maxv = float(maxv)
res = Bunch.Bunch(fwhm=fwhm, mu=mu, sdev=sdev, maxv=maxv,
fit_fn=gauss_fn, fit_args=[mu, sdev, maxv])
return res | python | def calc_fwhm_gaussian(self, arr1d, medv=None, gauss_fn=None):
if gauss_fn is None:
gauss_fn = self.gaussian
N = len(arr1d)
X = np.array(list(range(N)))
Y = arr1d
# Fitting works more reliably if we do the following
# a. subtract sky background
if medv is None:
medv = get_median(Y)
Y = Y - medv
maxv = Y.max()
# b. clamp to 0..max (of the sky subtracted field)
Y = Y.clip(0, maxv)
# Fit a gaussian
p0 = [0, N - 1, maxv] # Inital guess
# Distance to the target function
errfunc = lambda p, x, y: gauss_fn(x, p) - y # noqa
# Least square fit to the gaussian
with self.lock:
# NOTE: without this mutex, optimize.leastsq causes a fatal error
# sometimes--it appears not to be thread safe.
# The error is:
# "SystemError: null argument to internal routine"
# "Fatal Python error: GC object already tracked"
p1, success = optimize.leastsq(errfunc, p0[:], args=(X, Y))
if not success:
raise IQCalcError("FWHM gaussian fitting failed")
mu, sdev, maxv = p1
self.logger.debug("mu=%f sdev=%f maxv=%f" % (mu, sdev, maxv))
# Now that we have the sdev from fitting, we can calculate FWHM
fwhm = 2.0 * np.sqrt(2.0 * np.log(2.0)) * sdev
# some routines choke on numpy values and need "pure" Python floats
# e.g. when marshalling through a remote procedure interface
fwhm = float(fwhm)
mu = float(mu)
sdev = float(sdev)
maxv = float(maxv)
res = Bunch.Bunch(fwhm=fwhm, mu=mu, sdev=sdev, maxv=maxv,
fit_fn=gauss_fn, fit_args=[mu, sdev, maxv])
return res | [
"def",
"calc_fwhm_gaussian",
"(",
"self",
",",
"arr1d",
",",
"medv",
"=",
"None",
",",
"gauss_fn",
"=",
"None",
")",
":",
"if",
"gauss_fn",
"is",
"None",
":",
"gauss_fn",
"=",
"self",
".",
"gaussian",
"N",
"=",
"len",
"(",
"arr1d",
")",
"X",
"=",
"... | FWHM calculation on a 1D array by using least square fitting of
a gaussian function on the data. arr1d is a 1D array cut in either
X or Y direction on the object. | [
"FWHM",
"calculation",
"on",
"a",
"1D",
"array",
"by",
"using",
"least",
"square",
"fitting",
"of",
"a",
"gaussian",
"function",
"on",
"the",
"data",
".",
"arr1d",
"is",
"a",
"1D",
"array",
"cut",
"in",
"either",
"X",
"or",
"Y",
"direction",
"on",
"the... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iqcalc.py#L85-L135 |
26,315 | ejeschke/ginga | ginga/util/iqcalc.py | IQCalc.calc_fwhm_moffat | def calc_fwhm_moffat(self, arr1d, medv=None, moffat_fn=None):
"""FWHM calculation on a 1D array by using least square fitting of
a Moffat function on the data. arr1d is a 1D array cut in either
X or Y direction on the object.
"""
if moffat_fn is None:
moffat_fn = self.moffat
N = len(arr1d)
X = np.array(list(range(N)))
Y = arr1d
# Fitting works more reliably if we do the following
# a. subtract sky background
if medv is None:
medv = get_median(Y)
Y = Y - medv
maxv = Y.max()
# b. clamp to 0..max (of the sky subtracted field)
Y = Y.clip(0, maxv)
# Fit a moffat
p0 = [0, N - 1, 2, maxv] # Inital guess
# Distance to the target function
errfunc = lambda p, x, y: moffat_fn(x, p) - y # noqa
# Least square fit to the gaussian
with self.lock:
# NOTE: without this mutex, optimize.leastsq causes a fatal error
# sometimes--it appears not to be thread safe.
# The error is:
# "SystemError: null argument to internal routine"
# "Fatal Python error: GC object already tracked"
p1, success = optimize.leastsq(errfunc, p0[:], args=(X, Y))
if not success:
raise IQCalcError("FWHM moffat fitting failed")
mu, width, power, maxv = p1
width = np.abs(width)
self.logger.debug("mu=%f width=%f power=%f maxv=%f" % (
mu, width, power, maxv))
fwhm = 2.0 * width * np.sqrt(2.0 ** (1.0 / power) - 1.0)
# some routines choke on numpy values and need "pure" Python floats
# e.g. when marshalling through a remote procedure interface
fwhm = float(fwhm)
mu = float(mu)
width = float(width)
power = float(power)
maxv = float(maxv)
res = Bunch.Bunch(fwhm=fwhm, mu=mu, width=width, power=power,
maxv=maxv, fit_fn=moffat_fn,
fit_args=[mu, width, power, maxv])
return res | python | def calc_fwhm_moffat(self, arr1d, medv=None, moffat_fn=None):
if moffat_fn is None:
moffat_fn = self.moffat
N = len(arr1d)
X = np.array(list(range(N)))
Y = arr1d
# Fitting works more reliably if we do the following
# a. subtract sky background
if medv is None:
medv = get_median(Y)
Y = Y - medv
maxv = Y.max()
# b. clamp to 0..max (of the sky subtracted field)
Y = Y.clip(0, maxv)
# Fit a moffat
p0 = [0, N - 1, 2, maxv] # Inital guess
# Distance to the target function
errfunc = lambda p, x, y: moffat_fn(x, p) - y # noqa
# Least square fit to the gaussian
with self.lock:
# NOTE: without this mutex, optimize.leastsq causes a fatal error
# sometimes--it appears not to be thread safe.
# The error is:
# "SystemError: null argument to internal routine"
# "Fatal Python error: GC object already tracked"
p1, success = optimize.leastsq(errfunc, p0[:], args=(X, Y))
if not success:
raise IQCalcError("FWHM moffat fitting failed")
mu, width, power, maxv = p1
width = np.abs(width)
self.logger.debug("mu=%f width=%f power=%f maxv=%f" % (
mu, width, power, maxv))
fwhm = 2.0 * width * np.sqrt(2.0 ** (1.0 / power) - 1.0)
# some routines choke on numpy values and need "pure" Python floats
# e.g. when marshalling through a remote procedure interface
fwhm = float(fwhm)
mu = float(mu)
width = float(width)
power = float(power)
maxv = float(maxv)
res = Bunch.Bunch(fwhm=fwhm, mu=mu, width=width, power=power,
maxv=maxv, fit_fn=moffat_fn,
fit_args=[mu, width, power, maxv])
return res | [
"def",
"calc_fwhm_moffat",
"(",
"self",
",",
"arr1d",
",",
"medv",
"=",
"None",
",",
"moffat_fn",
"=",
"None",
")",
":",
"if",
"moffat_fn",
"is",
"None",
":",
"moffat_fn",
"=",
"self",
".",
"moffat",
"N",
"=",
"len",
"(",
"arr1d",
")",
"X",
"=",
"n... | FWHM calculation on a 1D array by using least square fitting of
a Moffat function on the data. arr1d is a 1D array cut in either
X or Y direction on the object. | [
"FWHM",
"calculation",
"on",
"a",
"1D",
"array",
"by",
"using",
"least",
"square",
"fitting",
"of",
"a",
"Moffat",
"function",
"on",
"the",
"data",
".",
"arr1d",
"is",
"a",
"1D",
"array",
"cut",
"in",
"either",
"X",
"or",
"Y",
"direction",
"on",
"the",... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iqcalc.py#L144-L198 |
26,316 | ejeschke/ginga | ginga/misc/ModuleManager.py | my_import | def my_import(name, path=None):
"""Return imported module for the given name."""
# Documentation for importlib says this may be needed to pick up
# modules created after the program has started
if hasattr(importlib, 'invalidate_caches'):
# python 3.3+
importlib.invalidate_caches()
if path is not None:
directory, src_file = os.path.split(path)
# TODO: use the importlib.util machinery
sys.path.insert(0, directory)
try:
mod = importlib.import_module(name)
finally:
sys.path.pop(0)
else:
mod = importlib.import_module(name)
return mod | python | def my_import(name, path=None):
# Documentation for importlib says this may be needed to pick up
# modules created after the program has started
if hasattr(importlib, 'invalidate_caches'):
# python 3.3+
importlib.invalidate_caches()
if path is not None:
directory, src_file = os.path.split(path)
# TODO: use the importlib.util machinery
sys.path.insert(0, directory)
try:
mod = importlib.import_module(name)
finally:
sys.path.pop(0)
else:
mod = importlib.import_module(name)
return mod | [
"def",
"my_import",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"# Documentation for importlib says this may be needed to pick up",
"# modules created after the program has started",
"if",
"hasattr",
"(",
"importlib",
",",
"'invalidate_caches'",
")",
":",
"# python 3.3+"... | Return imported module for the given name. | [
"Return",
"imported",
"module",
"for",
"the",
"given",
"name",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/ModuleManager.py#L19-L41 |
26,317 | ejeschke/ginga | ginga/misc/ModuleManager.py | ModuleManager.get_module | def get_module(self, module_name):
"""Return loaded module from the given name."""
try:
return self.module[module_name]
except KeyError:
return sys.modules[module_name] | python | def get_module(self, module_name):
try:
return self.module[module_name]
except KeyError:
return sys.modules[module_name] | [
"def",
"get_module",
"(",
"self",
",",
"module_name",
")",
":",
"try",
":",
"return",
"self",
".",
"module",
"[",
"module_name",
"]",
"except",
"KeyError",
":",
"return",
"sys",
".",
"modules",
"[",
"module_name",
"]"
] | Return loaded module from the given name. | [
"Return",
"loaded",
"module",
"from",
"the",
"given",
"name",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/ModuleManager.py#L82-L88 |
26,318 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.parse_combo | def parse_combo(self, combo, modes_set, modifiers_set, pfx):
"""
Parse a string into a mode, a set of modifiers and a trigger.
"""
mode, mods, trigger = None, set([]), combo
if '+' in combo:
if combo.endswith('+'):
# special case: probably contains the keystroke '+'
trigger, combo = '+', combo[:-1]
if '+' in combo:
items = set(combo.split('+'))
else:
items = set(combo)
else:
# trigger is always specified last
items = combo.split('+')
trigger, items = items[-1], set(items[:-1])
if '*' in items:
items.remove('*')
# modifier wildcard
mods = '*'
else:
mods = items.intersection(modifiers_set)
mode = items.intersection(modes_set)
if len(mode) == 0:
mode = None
else:
mode = mode.pop()
if pfx is not None:
trigger = pfx + trigger
return (mode, mods, trigger) | python | def parse_combo(self, combo, modes_set, modifiers_set, pfx):
mode, mods, trigger = None, set([]), combo
if '+' in combo:
if combo.endswith('+'):
# special case: probably contains the keystroke '+'
trigger, combo = '+', combo[:-1]
if '+' in combo:
items = set(combo.split('+'))
else:
items = set(combo)
else:
# trigger is always specified last
items = combo.split('+')
trigger, items = items[-1], set(items[:-1])
if '*' in items:
items.remove('*')
# modifier wildcard
mods = '*'
else:
mods = items.intersection(modifiers_set)
mode = items.intersection(modes_set)
if len(mode) == 0:
mode = None
else:
mode = mode.pop()
if pfx is not None:
trigger = pfx + trigger
return (mode, mods, trigger) | [
"def",
"parse_combo",
"(",
"self",
",",
"combo",
",",
"modes_set",
",",
"modifiers_set",
",",
"pfx",
")",
":",
"mode",
",",
"mods",
",",
"trigger",
"=",
"None",
",",
"set",
"(",
"[",
"]",
")",
",",
"combo",
"if",
"'+'",
"in",
"combo",
":",
"if",
... | Parse a string into a mode, a set of modifiers and a trigger. | [
"Parse",
"a",
"string",
"into",
"a",
"mode",
"a",
"set",
"of",
"modifiers",
"and",
"a",
"trigger",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L272-L306 |
26,319 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.get_direction | def get_direction(self, direction, rev=False):
"""
Translate a direction in compass degrees into 'up' or 'down'.
"""
if (direction < 90.0) or (direction >= 270.0):
if not rev:
return 'up'
else:
return 'down'
elif (90.0 <= direction < 270.0):
if not rev:
return 'down'
else:
return 'up'
else:
return 'none' | python | def get_direction(self, direction, rev=False):
if (direction < 90.0) or (direction >= 270.0):
if not rev:
return 'up'
else:
return 'down'
elif (90.0 <= direction < 270.0):
if not rev:
return 'down'
else:
return 'up'
else:
return 'none' | [
"def",
"get_direction",
"(",
"self",
",",
"direction",
",",
"rev",
"=",
"False",
")",
":",
"if",
"(",
"direction",
"<",
"90.0",
")",
"or",
"(",
"direction",
">=",
"270.0",
")",
":",
"if",
"not",
"rev",
":",
"return",
"'up'",
"else",
":",
"return",
... | Translate a direction in compass degrees into 'up' or 'down'. | [
"Translate",
"a",
"direction",
"in",
"compass",
"degrees",
"into",
"up",
"or",
"down",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L706-L721 |
26,320 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.kp_pan_px_center | def kp_pan_px_center(self, viewer, event, data_x, data_y, msg=True):
"""This pans so that the cursor is over the center of the
current pixel."""
if not self.canpan:
return False
self.pan_center_px(viewer)
return True | python | def kp_pan_px_center(self, viewer, event, data_x, data_y, msg=True):
if not self.canpan:
return False
self.pan_center_px(viewer)
return True | [
"def",
"kp_pan_px_center",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canpan",
":",
"return",
"False",
"self",
".",
"pan_center_px",
"(",
"viewer",
")",
"return"... | This pans so that the cursor is over the center of the
current pixel. | [
"This",
"pans",
"so",
"that",
"the",
"cursor",
"is",
"over",
"the",
"center",
"of",
"the",
"current",
"pixel",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1214-L1220 |
26,321 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_zoom | def ms_zoom(self, viewer, event, data_x, data_y, msg=True):
"""Zoom the image by dragging the cursor left or right.
"""
if not self.canzoom:
return True
msg = self.settings.get('msg_zoom', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._zoom_xy(viewer, x, y)
elif event.state == 'down':
if msg:
viewer.onscreen_message("Zoom (drag mouse L-R)",
delay=1.0)
self._start_x, self._start_y = x, y
else:
viewer.onscreen_message(None)
return True | python | def ms_zoom(self, viewer, event, data_x, data_y, msg=True):
if not self.canzoom:
return True
msg = self.settings.get('msg_zoom', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._zoom_xy(viewer, x, y)
elif event.state == 'down':
if msg:
viewer.onscreen_message("Zoom (drag mouse L-R)",
delay=1.0)
self._start_x, self._start_y = x, y
else:
viewer.onscreen_message(None)
return True | [
"def",
"ms_zoom",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canzoom",
":",
"return",
"True",
"msg",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'msg_zoo... | Zoom the image by dragging the cursor left or right. | [
"Zoom",
"the",
"image",
"by",
"dragging",
"the",
"cursor",
"left",
"or",
"right",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1554-L1574 |
26,322 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_zoom_in | def ms_zoom_in(self, viewer, event, data_x, data_y, msg=False):
"""Zoom in one level by a mouse click.
"""
if not self.canzoom:
return True
if not (event.state == 'down'):
return True
with viewer.suppress_redraw:
viewer.panset_xy(data_x, data_y)
if self.settings.get('scroll_zoom_direct_scale', True):
zoom_accel = self.settings.get('scroll_zoom_acceleration', 1.0)
# change scale by 100%
amount = self._scale_adjust(2.0, 15.0, zoom_accel, max_limit=4.0)
self._scale_image(viewer, 0.0, amount, msg=msg)
else:
viewer.zoom_in()
if hasattr(viewer, 'center_cursor'):
viewer.center_cursor()
if msg:
viewer.onscreen_message(viewer.get_scale_text(),
delay=1.0)
return True | python | def ms_zoom_in(self, viewer, event, data_x, data_y, msg=False):
if not self.canzoom:
return True
if not (event.state == 'down'):
return True
with viewer.suppress_redraw:
viewer.panset_xy(data_x, data_y)
if self.settings.get('scroll_zoom_direct_scale', True):
zoom_accel = self.settings.get('scroll_zoom_acceleration', 1.0)
# change scale by 100%
amount = self._scale_adjust(2.0, 15.0, zoom_accel, max_limit=4.0)
self._scale_image(viewer, 0.0, amount, msg=msg)
else:
viewer.zoom_in()
if hasattr(viewer, 'center_cursor'):
viewer.center_cursor()
if msg:
viewer.onscreen_message(viewer.get_scale_text(),
delay=1.0)
return True | [
"def",
"ms_zoom_in",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"canzoom",
":",
"return",
"True",
"if",
"not",
"(",
"event",
".",
"state",
"==",
"'down'",
")... | Zoom in one level by a mouse click. | [
"Zoom",
"in",
"one",
"level",
"by",
"a",
"mouse",
"click",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1585-L1610 |
26,323 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_rotate | def ms_rotate(self, viewer, event, data_x, data_y, msg=True):
"""Rotate the image by dragging the cursor left or right.
"""
if not self.canrotate:
return True
msg = self.settings.get('msg_rotate', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._rotate_xy(viewer, x, y)
elif event.state == 'down':
if msg:
viewer.onscreen_message("Rotate (drag around center)",
delay=1.0)
self._start_x, self._start_y = x, y
self._start_rot = viewer.get_rotation()
else:
viewer.onscreen_message(None)
return True | python | def ms_rotate(self, viewer, event, data_x, data_y, msg=True):
if not self.canrotate:
return True
msg = self.settings.get('msg_rotate', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._rotate_xy(viewer, x, y)
elif event.state == 'down':
if msg:
viewer.onscreen_message("Rotate (drag around center)",
delay=1.0)
self._start_x, self._start_y = x, y
self._start_rot = viewer.get_rotation()
else:
viewer.onscreen_message(None)
return True | [
"def",
"ms_rotate",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canrotate",
":",
"return",
"True",
"msg",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'msg... | Rotate the image by dragging the cursor left or right. | [
"Rotate",
"the",
"image",
"by",
"dragging",
"the",
"cursor",
"left",
"or",
"right",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1641-L1662 |
26,324 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_contrast | def ms_contrast(self, viewer, event, data_x, data_y, msg=True):
"""Shift the colormap by dragging the cursor left or right.
Stretch the colormap by dragging the cursor up or down.
"""
if not self.cancmap:
return True
msg = self.settings.get('msg_contrast', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._tweak_colormap(viewer, x, y, 'preview')
elif event.state == 'down':
self._start_x, self._start_y = x, y
if msg:
viewer.onscreen_message(
"Shift and stretch colormap (drag mouse)", delay=1.0)
else:
viewer.onscreen_message(None)
return True | python | def ms_contrast(self, viewer, event, data_x, data_y, msg=True):
if not self.cancmap:
return True
msg = self.settings.get('msg_contrast', msg)
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._tweak_colormap(viewer, x, y, 'preview')
elif event.state == 'down':
self._start_x, self._start_y = x, y
if msg:
viewer.onscreen_message(
"Shift and stretch colormap (drag mouse)", delay=1.0)
else:
viewer.onscreen_message(None)
return True | [
"def",
"ms_contrast",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"cancmap",
":",
"return",
"True",
"msg",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'msg... | Shift the colormap by dragging the cursor left or right.
Stretch the colormap by dragging the cursor up or down. | [
"Shift",
"the",
"colormap",
"by",
"dragging",
"the",
"cursor",
"left",
"or",
"right",
".",
"Stretch",
"the",
"colormap",
"by",
"dragging",
"the",
"cursor",
"up",
"or",
"down",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1674-L1694 |
26,325 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_contrast_restore | def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):
"""An interactive way to restore the colormap contrast settings after
a warp operation.
"""
if self.cancmap and (event.state == 'down'):
self.restore_contrast(viewer, msg=msg)
return True | python | def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):
if self.cancmap and (event.state == 'down'):
self.restore_contrast(viewer, msg=msg)
return True | [
"def",
"ms_contrast_restore",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"cancmap",
"and",
"(",
"event",
".",
"state",
"==",
"'down'",
")",
":",
"self",
".",
"restore_... | An interactive way to restore the colormap contrast settings after
a warp operation. | [
"An",
"interactive",
"way",
"to",
"restore",
"the",
"colormap",
"contrast",
"settings",
"after",
"a",
"warp",
"operation",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1696-L1702 |
26,326 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_cmap_restore | def ms_cmap_restore(self, viewer, event, data_x, data_y, msg=True):
"""An interactive way to restore the colormap settings after
a rotate or invert operation.
"""
if self.cancmap and (event.state == 'down'):
self.restore_colormap(viewer, msg)
return True | python | def ms_cmap_restore(self, viewer, event, data_x, data_y, msg=True):
if self.cancmap and (event.state == 'down'):
self.restore_colormap(viewer, msg)
return True | [
"def",
"ms_cmap_restore",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"cancmap",
"and",
"(",
"event",
".",
"state",
"==",
"'down'",
")",
":",
"self",
".",
"restore_colo... | An interactive way to restore the colormap settings after
a rotate or invert operation. | [
"An",
"interactive",
"way",
"to",
"restore",
"the",
"colormap",
"settings",
"after",
"a",
"rotate",
"or",
"invert",
"operation",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1726-L1732 |
26,327 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_pan | def ms_pan(self, viewer, event, data_x, data_y):
"""A 'drag' or proportional pan, where the image is panned by
'dragging the canvas' up or down. The amount of the pan is
proportionate to the length of the drag.
"""
if not self.canpan:
return True
x, y = viewer.get_last_win_xy()
if event.state == 'move':
data_x, data_y = self.get_new_pan(viewer, x, y,
ptype=self._pantype)
viewer.panset_xy(data_x, data_y)
elif event.state == 'down':
self.pan_set_origin(viewer, x, y, data_x, data_y)
self.pan_start(viewer, ptype=2)
else:
self.pan_stop(viewer)
return True | python | def ms_pan(self, viewer, event, data_x, data_y):
if not self.canpan:
return True
x, y = viewer.get_last_win_xy()
if event.state == 'move':
data_x, data_y = self.get_new_pan(viewer, x, y,
ptype=self._pantype)
viewer.panset_xy(data_x, data_y)
elif event.state == 'down':
self.pan_set_origin(viewer, x, y, data_x, data_y)
self.pan_start(viewer, ptype=2)
else:
self.pan_stop(viewer)
return True | [
"def",
"ms_pan",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"not",
"self",
".",
"canpan",
":",
"return",
"True",
"x",
",",
"y",
"=",
"viewer",
".",
"get_last_win_xy",
"(",
")",
"if",
"event",
".",
"state... | A 'drag' or proportional pan, where the image is panned by
'dragging the canvas' up or down. The amount of the pan is
proportionate to the length of the drag. | [
"A",
"drag",
"or",
"proportional",
"pan",
"where",
"the",
"image",
"is",
"panned",
"by",
"dragging",
"the",
"canvas",
"up",
"or",
"down",
".",
"The",
"amount",
"of",
"the",
"pan",
"is",
"proportionate",
"to",
"the",
"length",
"of",
"the",
"drag",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1734-L1754 |
26,328 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_cutlo | def ms_cutlo(self, viewer, event, data_x, data_y):
"""An interactive way to set the low cut level.
"""
if not self.cancut:
return True
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._cutlow_xy(viewer, x, y)
elif event.state == 'down':
self._start_x, self._start_y = x, y
self._loval, self._hival = viewer.get_cut_levels()
else:
viewer.onscreen_message(None)
return True | python | def ms_cutlo(self, viewer, event, data_x, data_y):
if not self.cancut:
return True
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._cutlow_xy(viewer, x, y)
elif event.state == 'down':
self._start_x, self._start_y = x, y
self._loval, self._hival = viewer.get_cut_levels()
else:
viewer.onscreen_message(None)
return True | [
"def",
"ms_cutlo",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"not",
"self",
".",
"cancut",
":",
"return",
"True",
"x",
",",
"y",
"=",
"self",
".",
"get_win_xy",
"(",
"viewer",
")",
"if",
"event",
".",
... | An interactive way to set the low cut level. | [
"An",
"interactive",
"way",
"to",
"set",
"the",
"low",
"cut",
"level",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1777-L1794 |
26,329 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.ms_cutall | def ms_cutall(self, viewer, event, data_x, data_y):
"""An interactive way to set the low AND high cut levels.
"""
if not self.cancut:
return True
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._cutboth_xy(viewer, x, y)
elif event.state == 'down':
self._start_x, self._start_y = x, y
image = viewer.get_image()
#self._loval, self._hival = viewer.get_cut_levels()
self._loval, self._hival = viewer.autocuts.calc_cut_levels(image)
else:
viewer.onscreen_message(None)
return True | python | def ms_cutall(self, viewer, event, data_x, data_y):
if not self.cancut:
return True
x, y = self.get_win_xy(viewer)
if event.state == 'move':
self._cutboth_xy(viewer, x, y)
elif event.state == 'down':
self._start_x, self._start_y = x, y
image = viewer.get_image()
#self._loval, self._hival = viewer.get_cut_levels()
self._loval, self._hival = viewer.autocuts.calc_cut_levels(image)
else:
viewer.onscreen_message(None)
return True | [
"def",
"ms_cutall",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"not",
"self",
".",
"cancut",
":",
"return",
"True",
"x",
",",
"y",
"=",
"self",
".",
"get_win_xy",
"(",
"viewer",
")",
"if",
"event",
".",
... | An interactive way to set the low AND high cut levels. | [
"An",
"interactive",
"way",
"to",
"set",
"the",
"low",
"AND",
"high",
"cut",
"levels",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1815-L1834 |
26,330 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_cuts_coarse | def sc_cuts_coarse(self, viewer, event, msg=True):
"""Adjust cuts interactively by setting the low AND high cut
levels. This function adjusts it coarsely.
"""
if self.cancut:
# adjust the cut by 10% on each end
self._adjust_cuts(viewer, event.direction, 0.1, msg=msg)
return True | python | def sc_cuts_coarse(self, viewer, event, msg=True):
if self.cancut:
# adjust the cut by 10% on each end
self._adjust_cuts(viewer, event.direction, 0.1, msg=msg)
return True | [
"def",
"sc_cuts_coarse",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"cancut",
":",
"# adjust the cut by 10% on each end",
"self",
".",
"_adjust_cuts",
"(",
"viewer",
",",
"event",
".",
"direction",
",",
... | Adjust cuts interactively by setting the low AND high cut
levels. This function adjusts it coarsely. | [
"Adjust",
"cuts",
"interactively",
"by",
"setting",
"the",
"low",
"AND",
"high",
"cut",
"levels",
".",
"This",
"function",
"adjusts",
"it",
"coarsely",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1878-L1885 |
26,331 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_cuts_alg | def sc_cuts_alg(self, viewer, event, msg=True):
"""Adjust cuts algorithm interactively.
"""
if self.cancut:
direction = self.get_direction(event.direction)
self._cycle_cuts_alg(viewer, msg, direction=direction)
return True | python | def sc_cuts_alg(self, viewer, event, msg=True):
if self.cancut:
direction = self.get_direction(event.direction)
self._cycle_cuts_alg(viewer, msg, direction=direction)
return True | [
"def",
"sc_cuts_alg",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"cancut",
":",
"direction",
"=",
"self",
".",
"get_direction",
"(",
"event",
".",
"direction",
")",
"self",
".",
"_cycle_cuts_alg",
"(... | Adjust cuts algorithm interactively. | [
"Adjust",
"cuts",
"algorithm",
"interactively",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1896-L1902 |
26,332 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_zoom | def sc_zoom(self, viewer, event, msg=True):
"""Interactively zoom the image by scrolling motion.
This zooms by the zoom steps configured under Preferences.
"""
self._sc_zoom(viewer, event, msg=msg, origin=None)
return True | python | def sc_zoom(self, viewer, event, msg=True):
self._sc_zoom(viewer, event, msg=msg, origin=None)
return True | [
"def",
"sc_zoom",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"self",
".",
"_sc_zoom",
"(",
"viewer",
",",
"event",
",",
"msg",
"=",
"msg",
",",
"origin",
"=",
"None",
")",
"return",
"True"
] | Interactively zoom the image by scrolling motion.
This zooms by the zoom steps configured under Preferences. | [
"Interactively",
"zoom",
"the",
"image",
"by",
"scrolling",
"motion",
".",
"This",
"zooms",
"by",
"the",
"zoom",
"steps",
"configured",
"under",
"Preferences",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1952-L1957 |
26,333 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_zoom_coarse | def sc_zoom_coarse(self, viewer, event, msg=True):
"""Interactively zoom the image by scrolling motion.
This zooms by adjusting the scale in x and y coarsely.
"""
if not self.canzoom:
return True
zoom_accel = self.settings.get('scroll_zoom_acceleration', 1.0)
# change scale by 20%
amount = self._scale_adjust(1.2, event.amount, zoom_accel, max_limit=4.0)
self._scale_image(viewer, event.direction, amount, msg=msg)
return True | python | def sc_zoom_coarse(self, viewer, event, msg=True):
if not self.canzoom:
return True
zoom_accel = self.settings.get('scroll_zoom_acceleration', 1.0)
# change scale by 20%
amount = self._scale_adjust(1.2, event.amount, zoom_accel, max_limit=4.0)
self._scale_image(viewer, event.direction, amount, msg=msg)
return True | [
"def",
"sc_zoom_coarse",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canzoom",
":",
"return",
"True",
"zoom_accel",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'scroll_zoom_acceleration'",
"... | Interactively zoom the image by scrolling motion.
This zooms by adjusting the scale in x and y coarsely. | [
"Interactively",
"zoom",
"the",
"image",
"by",
"scrolling",
"motion",
".",
"This",
"zooms",
"by",
"adjusting",
"the",
"scale",
"in",
"x",
"and",
"y",
"coarsely",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1968-L1979 |
26,334 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_pan | def sc_pan(self, viewer, event, msg=True):
"""Interactively pan the image by scrolling motion.
"""
if not self.canpan:
return True
# User has "Pan Reverse" preference set?
rev = self.settings.get('pan_reverse', False)
direction = event.direction
if rev:
direction = math.fmod(direction + 180.0, 360.0)
pan_accel = self.settings.get('scroll_pan_acceleration', 1.0)
# Internal factor to adjust the panning speed so that user-adjustable
# scroll_pan_acceleration is normalized to 1.0 for "normal" speed
scr_pan_adj_factor = 1.4142135623730951
amount = (event.amount * scr_pan_adj_factor * pan_accel) / 360.0
self.pan_omni(viewer, direction, amount)
return True | python | def sc_pan(self, viewer, event, msg=True):
if not self.canpan:
return True
# User has "Pan Reverse" preference set?
rev = self.settings.get('pan_reverse', False)
direction = event.direction
if rev:
direction = math.fmod(direction + 180.0, 360.0)
pan_accel = self.settings.get('scroll_pan_acceleration', 1.0)
# Internal factor to adjust the panning speed so that user-adjustable
# scroll_pan_acceleration is normalized to 1.0 for "normal" speed
scr_pan_adj_factor = 1.4142135623730951
amount = (event.amount * scr_pan_adj_factor * pan_accel) / 360.0
self.pan_omni(viewer, direction, amount)
return True | [
"def",
"sc_pan",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"canpan",
":",
"return",
"True",
"# User has \"Pan Reverse\" preference set?",
"rev",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"... | Interactively pan the image by scrolling motion. | [
"Interactively",
"pan",
"the",
"image",
"by",
"scrolling",
"motion",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L1994-L2014 |
26,335 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_dist | def sc_dist(self, viewer, event, msg=True):
"""Interactively change the color distribution algorithm
by scrolling.
"""
direction = self.get_direction(event.direction)
self._cycle_dist(viewer, msg, direction=direction)
return True | python | def sc_dist(self, viewer, event, msg=True):
direction = self.get_direction(event.direction)
self._cycle_dist(viewer, msg, direction=direction)
return True | [
"def",
"sc_dist",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"direction",
"=",
"self",
".",
"get_direction",
"(",
"event",
".",
"direction",
")",
"self",
".",
"_cycle_dist",
"(",
"viewer",
",",
"msg",
",",
"direction",... | Interactively change the color distribution algorithm
by scrolling. | [
"Interactively",
"change",
"the",
"color",
"distribution",
"algorithm",
"by",
"scrolling",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2034-L2040 |
26,336 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_cmap | def sc_cmap(self, viewer, event, msg=True):
"""Interactively change the color map by scrolling.
"""
direction = self.get_direction(event.direction)
self._cycle_cmap(viewer, msg, direction=direction)
return True | python | def sc_cmap(self, viewer, event, msg=True):
direction = self.get_direction(event.direction)
self._cycle_cmap(viewer, msg, direction=direction)
return True | [
"def",
"sc_cmap",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"direction",
"=",
"self",
".",
"get_direction",
"(",
"event",
".",
"direction",
")",
"self",
".",
"_cycle_cmap",
"(",
"viewer",
",",
"msg",
",",
"direction",... | Interactively change the color map by scrolling. | [
"Interactively",
"change",
"the",
"color",
"map",
"by",
"scrolling",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2042-L2047 |
26,337 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.sc_imap | def sc_imap(self, viewer, event, msg=True):
"""Interactively change the intensity map by scrolling.
"""
direction = self.get_direction(event.direction)
self._cycle_imap(viewer, msg, direction=direction)
return True | python | def sc_imap(self, viewer, event, msg=True):
direction = self.get_direction(event.direction)
self._cycle_imap(viewer, msg, direction=direction)
return True | [
"def",
"sc_imap",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"direction",
"=",
"self",
".",
"get_direction",
"(",
"event",
".",
"direction",
")",
"self",
".",
"_cycle_imap",
"(",
"viewer",
",",
"msg",
",",
"direction",... | Interactively change the intensity map by scrolling. | [
"Interactively",
"change",
"the",
"intensity",
"map",
"by",
"scrolling",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2049-L2054 |
26,338 | ejeschke/ginga | ginga/Bindings.py | ImageViewBindings.pa_naxis | def pa_naxis(self, viewer, event, msg=True):
"""Interactively change the slice of the image in a data cube
by pan gesture.
"""
event = self._pa_synth_scroll_event(event)
if event.state != 'move':
return False
# TODO: be able to pick axis
axis = 2
direction = self.get_direction(event.direction)
return self._nav_naxis(viewer, axis, direction, msg=msg) | python | def pa_naxis(self, viewer, event, msg=True):
event = self._pa_synth_scroll_event(event)
if event.state != 'move':
return False
# TODO: be able to pick axis
axis = 2
direction = self.get_direction(event.direction)
return self._nav_naxis(viewer, axis, direction, msg=msg) | [
"def",
"pa_naxis",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"msg",
"=",
"True",
")",
":",
"event",
"=",
"self",
".",
"_pa_synth_scroll_event",
"(",
"event",
")",
"if",
"event",
".",
"state",
"!=",
"'move'",
":",
"return",
"False",
"# TODO: be able ... | Interactively change the slice of the image in a data cube
by pan gesture. | [
"Interactively",
"change",
"the",
"slice",
"of",
"the",
"image",
"in",
"a",
"data",
"cube",
"by",
"pan",
"gesture",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2269-L2281 |
26,339 | ejeschke/ginga | ginga/Bindings.py | BindingMapper.mode_key_down | def mode_key_down(self, viewer, keyname):
"""This method is called when a key is pressed and was not handled
by some other handler with precedence, such as a subcanvas.
"""
# Is this a mode key?
if keyname not in self.mode_map:
if (keyname not in self.mode_tbl) or (self._kbdmode != 'meta'):
# No
return False
bnch = self.mode_tbl[keyname]
else:
bnch = self.mode_map[keyname]
mode_name = bnch.name
self.logger.debug("cur mode='%s' mode pressed='%s'" % (
self._kbdmode, mode_name))
if mode_name == self._kbdmode:
# <== same key was pressed that started the mode we're in
# standard handling is to close the mode when we press the
# key again that started that mode
self.reset_mode(viewer)
return True
if self._delayed_reset:
# <== this shouldn't happen, but put here to reset handling
# of delayed_reset just in case (see cursor up handling)
self._delayed_reset = False
return True
if ((self._kbdmode in (None, 'meta')) or
(self._kbdmode_type != 'locked') or (mode_name == 'meta')):
if self._kbdmode is not None:
self.reset_mode(viewer)
# activate this mode
if self._kbdmode in (None, 'meta'):
mode_type = bnch.type
if mode_type is None:
mode_type = self._kbdmode_type_default
self.set_mode(mode_name, mode_type)
if bnch.msg is not None:
viewer.onscreen_message(bnch.msg)
return True
return False | python | def mode_key_down(self, viewer, keyname):
# Is this a mode key?
if keyname not in self.mode_map:
if (keyname not in self.mode_tbl) or (self._kbdmode != 'meta'):
# No
return False
bnch = self.mode_tbl[keyname]
else:
bnch = self.mode_map[keyname]
mode_name = bnch.name
self.logger.debug("cur mode='%s' mode pressed='%s'" % (
self._kbdmode, mode_name))
if mode_name == self._kbdmode:
# <== same key was pressed that started the mode we're in
# standard handling is to close the mode when we press the
# key again that started that mode
self.reset_mode(viewer)
return True
if self._delayed_reset:
# <== this shouldn't happen, but put here to reset handling
# of delayed_reset just in case (see cursor up handling)
self._delayed_reset = False
return True
if ((self._kbdmode in (None, 'meta')) or
(self._kbdmode_type != 'locked') or (mode_name == 'meta')):
if self._kbdmode is not None:
self.reset_mode(viewer)
# activate this mode
if self._kbdmode in (None, 'meta'):
mode_type = bnch.type
if mode_type is None:
mode_type = self._kbdmode_type_default
self.set_mode(mode_name, mode_type)
if bnch.msg is not None:
viewer.onscreen_message(bnch.msg)
return True
return False | [
"def",
"mode_key_down",
"(",
"self",
",",
"viewer",
",",
"keyname",
")",
":",
"# Is this a mode key?",
"if",
"keyname",
"not",
"in",
"self",
".",
"mode_map",
":",
"if",
"(",
"keyname",
"not",
"in",
"self",
".",
"mode_tbl",
")",
"or",
"(",
"self",
".",
... | This method is called when a key is pressed and was not handled
by some other handler with precedence, such as a subcanvas. | [
"This",
"method",
"is",
"called",
"when",
"a",
"key",
"is",
"pressed",
"and",
"was",
"not",
"handled",
"by",
"some",
"other",
"handler",
"with",
"precedence",
"such",
"as",
"a",
"subcanvas",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2658-L2704 |
26,340 | ejeschke/ginga | ginga/Bindings.py | BindingMapper.mode_key_up | def mode_key_up(self, viewer, keyname):
"""This method is called when a key is pressed in a mode and was
not handled by some other handler with precedence, such as a
subcanvas.
"""
# Is this a mode key?
if keyname not in self.mode_map:
# <== no
return False
bnch = self.mode_map[keyname]
if self._kbdmode == bnch.name:
# <-- the current mode key is being released
if bnch.type == 'held':
if self._button == 0:
# if no button is being held, then reset mode
self.reset_mode(viewer)
else:
self._delayed_reset = True
return True
return False | python | def mode_key_up(self, viewer, keyname):
# Is this a mode key?
if keyname not in self.mode_map:
# <== no
return False
bnch = self.mode_map[keyname]
if self._kbdmode == bnch.name:
# <-- the current mode key is being released
if bnch.type == 'held':
if self._button == 0:
# if no button is being held, then reset mode
self.reset_mode(viewer)
else:
self._delayed_reset = True
return True
return False | [
"def",
"mode_key_up",
"(",
"self",
",",
"viewer",
",",
"keyname",
")",
":",
"# Is this a mode key?",
"if",
"keyname",
"not",
"in",
"self",
".",
"mode_map",
":",
"# <== no",
"return",
"False",
"bnch",
"=",
"self",
".",
"mode_map",
"[",
"keyname",
"]",
"if",... | This method is called when a key is pressed in a mode and was
not handled by some other handler with precedence, such as a
subcanvas. | [
"This",
"method",
"is",
"called",
"when",
"a",
"key",
"is",
"pressed",
"in",
"a",
"mode",
"and",
"was",
"not",
"handled",
"by",
"some",
"other",
"handler",
"with",
"precedence",
"such",
"as",
"a",
"subcanvas",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/Bindings.py#L2706-L2727 |
26,341 | ejeschke/ginga | ginga/util/bezier.py | get_4pt_bezier | def get_4pt_bezier(steps, points):
"""Gets a series of bezier curve points with 1 set of 4
control points."""
for i in range(steps):
t = i / float(steps)
xloc = (math.pow(1 - t, 3) * points[0][0] +
3 * t * math.pow(1 - t, 2) * points[1][0] +
3 * (1 - t) * math.pow(t, 2) * points[2][0] +
math.pow(t, 3) * points[3][0])
yloc = (math.pow(1 - t, 3) * points[0][1] +
3 * t * math.pow(1 - t, 2) * points[1][1] +
3 * (1 - t) * math.pow(t, 2) * points[2][1] +
math.pow(t, 3) * points[3][1])
yield (xloc, yloc) | python | def get_4pt_bezier(steps, points):
for i in range(steps):
t = i / float(steps)
xloc = (math.pow(1 - t, 3) * points[0][0] +
3 * t * math.pow(1 - t, 2) * points[1][0] +
3 * (1 - t) * math.pow(t, 2) * points[2][0] +
math.pow(t, 3) * points[3][0])
yloc = (math.pow(1 - t, 3) * points[0][1] +
3 * t * math.pow(1 - t, 2) * points[1][1] +
3 * (1 - t) * math.pow(t, 2) * points[2][1] +
math.pow(t, 3) * points[3][1])
yield (xloc, yloc) | [
"def",
"get_4pt_bezier",
"(",
"steps",
",",
"points",
")",
":",
"for",
"i",
"in",
"range",
"(",
"steps",
")",
":",
"t",
"=",
"i",
"/",
"float",
"(",
"steps",
")",
"xloc",
"=",
"(",
"math",
".",
"pow",
"(",
"1",
"-",
"t",
",",
"3",
")",
"*",
... | Gets a series of bezier curve points with 1 set of 4
control points. | [
"Gets",
"a",
"series",
"of",
"bezier",
"curve",
"points",
"with",
"1",
"set",
"of",
"4",
"control",
"points",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/bezier.py#L19-L34 |
26,342 | ejeschke/ginga | ginga/util/bezier.py | get_bezier | def get_bezier(steps, points):
"""Gets a series of bezier curve points with any number of sets
of 4 control points."""
res = []
num_pts = len(points)
for i in range(0, num_pts + 1, 3):
if i + 4 < num_pts + 1:
res.extend(list(get_4pt_bezier(steps, points[i:i + 4])))
return res | python | def get_bezier(steps, points):
res = []
num_pts = len(points)
for i in range(0, num_pts + 1, 3):
if i + 4 < num_pts + 1:
res.extend(list(get_4pt_bezier(steps, points[i:i + 4])))
return res | [
"def",
"get_bezier",
"(",
"steps",
",",
"points",
")",
":",
"res",
"=",
"[",
"]",
"num_pts",
"=",
"len",
"(",
"points",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_pts",
"+",
"1",
",",
"3",
")",
":",
"if",
"i",
"+",
"4",
"<",
"num_pts... | Gets a series of bezier curve points with any number of sets
of 4 control points. | [
"Gets",
"a",
"series",
"of",
"bezier",
"curve",
"points",
"with",
"any",
"number",
"of",
"sets",
"of",
"4",
"control",
"points",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/bezier.py#L37-L45 |
26,343 | ejeschke/ginga | ginga/util/bezier.py | get_bezier_ellipse | def get_bezier_ellipse(x, y, xradius, yradius, kappa=0.5522848):
"""Get a set of 12 bezier control points necessary to form an
ellipse."""
xs, ys = x - xradius, y - yradius
ox, oy = xradius * kappa, yradius * kappa
xe, ye = x + xradius, y + yradius
pts = [(xs, y),
(xs, y - oy), (x - ox, ys), (x, ys),
(x + ox, ys), (xe, y - oy), (xe, y),
(xe, y + oy), (x + ox, ye), (x, ye),
(x - ox, ye), (xs, y + oy), (xs, y)]
return pts | python | def get_bezier_ellipse(x, y, xradius, yradius, kappa=0.5522848):
xs, ys = x - xradius, y - yradius
ox, oy = xradius * kappa, yradius * kappa
xe, ye = x + xradius, y + yradius
pts = [(xs, y),
(xs, y - oy), (x - ox, ys), (x, ys),
(x + ox, ys), (xe, y - oy), (xe, y),
(xe, y + oy), (x + ox, ye), (x, ye),
(x - ox, ye), (xs, y + oy), (xs, y)]
return pts | [
"def",
"get_bezier_ellipse",
"(",
"x",
",",
"y",
",",
"xradius",
",",
"yradius",
",",
"kappa",
"=",
"0.5522848",
")",
":",
"xs",
",",
"ys",
"=",
"x",
"-",
"xradius",
",",
"y",
"-",
"yradius",
"ox",
",",
"oy",
"=",
"xradius",
"*",
"kappa",
",",
"y... | Get a set of 12 bezier control points necessary to form an
ellipse. | [
"Get",
"a",
"set",
"of",
"12",
"bezier",
"control",
"points",
"necessary",
"to",
"form",
"an",
"ellipse",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/bezier.py#L48-L61 |
26,344 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.set_cmap_cb | def set_cmap_cb(self, w, index):
"""This callback is invoked when the user selects a new color
map from the preferences pane."""
name = cmap.get_names()[index]
self.t_.set(color_map=name) | python | def set_cmap_cb(self, w, index):
name = cmap.get_names()[index]
self.t_.set(color_map=name) | [
"def",
"set_cmap_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"name",
"=",
"cmap",
".",
"get_names",
"(",
")",
"[",
"index",
"]",
"self",
".",
"t_",
".",
"set",
"(",
"color_map",
"=",
"name",
")"
] | This callback is invoked when the user selects a new color
map from the preferences pane. | [
"This",
"callback",
"is",
"invoked",
"when",
"the",
"user",
"selects",
"a",
"new",
"color",
"map",
"from",
"the",
"preferences",
"pane",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L980-L984 |
26,345 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.set_imap_cb | def set_imap_cb(self, w, index):
"""This callback is invoked when the user selects a new intensity
map from the preferences pane."""
name = imap.get_names()[index]
self.t_.set(intensity_map=name) | python | def set_imap_cb(self, w, index):
name = imap.get_names()[index]
self.t_.set(intensity_map=name) | [
"def",
"set_imap_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"name",
"=",
"imap",
".",
"get_names",
"(",
")",
"[",
"index",
"]",
"self",
".",
"t_",
".",
"set",
"(",
"intensity_map",
"=",
"name",
")"
] | This callback is invoked when the user selects a new intensity
map from the preferences pane. | [
"This",
"callback",
"is",
"invoked",
"when",
"the",
"user",
"selects",
"a",
"new",
"intensity",
"map",
"from",
"the",
"preferences",
"pane",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L986-L990 |
26,346 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.set_calg_cb | def set_calg_cb(self, w, index):
"""This callback is invoked when the user selects a new color
hashing algorithm from the preferences pane."""
#index = w.get_index()
name = self.calg_names[index]
self.t_.set(color_algorithm=name) | python | def set_calg_cb(self, w, index):
#index = w.get_index()
name = self.calg_names[index]
self.t_.set(color_algorithm=name) | [
"def",
"set_calg_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"#index = w.get_index()",
"name",
"=",
"self",
".",
"calg_names",
"[",
"index",
"]",
"self",
".",
"t_",
".",
"set",
"(",
"color_algorithm",
"=",
"name",
")"
] | This callback is invoked when the user selects a new color
hashing algorithm from the preferences pane. | [
"This",
"callback",
"is",
"invoked",
"when",
"the",
"user",
"selects",
"a",
"new",
"color",
"hashing",
"algorithm",
"from",
"the",
"preferences",
"pane",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L992-L997 |
26,347 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.autocut_params_changed_cb | def autocut_params_changed_cb(self, paramObj, ac_obj):
"""This callback is called when the user changes the attributes of
an object via the paramSet.
"""
args, kwdargs = paramObj.get_params()
params = list(kwdargs.items())
self.t_.set(autocut_params=params) | python | def autocut_params_changed_cb(self, paramObj, ac_obj):
args, kwdargs = paramObj.get_params()
params = list(kwdargs.items())
self.t_.set(autocut_params=params) | [
"def",
"autocut_params_changed_cb",
"(",
"self",
",",
"paramObj",
",",
"ac_obj",
")",
":",
"args",
",",
"kwdargs",
"=",
"paramObj",
".",
"get_params",
"(",
")",
"params",
"=",
"list",
"(",
"kwdargs",
".",
"items",
"(",
")",
")",
"self",
".",
"t_",
".",... | This callback is called when the user changes the attributes of
an object via the paramSet. | [
"This",
"callback",
"is",
"called",
"when",
"the",
"user",
"changes",
"the",
"attributes",
"of",
"an",
"object",
"via",
"the",
"paramSet",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L1182-L1188 |
26,348 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.set_sort_cb | def set_sort_cb(self, w, index):
"""This callback is invoked when the user selects a new sort order
from the preferences pane."""
name = self.sort_options[index]
self.t_.set(sort_order=name) | python | def set_sort_cb(self, w, index):
name = self.sort_options[index]
self.t_.set(sort_order=name) | [
"def",
"set_sort_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"name",
"=",
"self",
".",
"sort_options",
"[",
"index",
"]",
"self",
".",
"t_",
".",
"set",
"(",
"sort_order",
"=",
"name",
")"
] | This callback is invoked when the user selects a new sort order
from the preferences pane. | [
"This",
"callback",
"is",
"invoked",
"when",
"the",
"user",
"selects",
"a",
"new",
"sort",
"order",
"from",
"the",
"preferences",
"pane",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L1254-L1258 |
26,349 | ejeschke/ginga | ginga/rv/plugins/Preferences.py | Preferences.set_scrollbars_cb | def set_scrollbars_cb(self, w, tf):
"""This callback is invoked when the user checks the 'Use Scrollbars'
box in the preferences pane."""
scrollbars = 'on' if tf else 'off'
self.t_.set(scrollbars=scrollbars) | python | def set_scrollbars_cb(self, w, tf):
scrollbars = 'on' if tf else 'off'
self.t_.set(scrollbars=scrollbars) | [
"def",
"set_scrollbars_cb",
"(",
"self",
",",
"w",
",",
"tf",
")",
":",
"scrollbars",
"=",
"'on'",
"if",
"tf",
"else",
"'off'",
"self",
".",
"t_",
".",
"set",
"(",
"scrollbars",
"=",
"scrollbars",
")"
] | This callback is invoked when the user checks the 'Use Scrollbars'
box in the preferences pane. | [
"This",
"callback",
"is",
"invoked",
"when",
"the",
"user",
"checks",
"the",
"Use",
"Scrollbars",
"box",
"in",
"the",
"preferences",
"pane",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Preferences.py#L1265-L1269 |
26,350 | ejeschke/ginga | ginga/rv/plugins/Info.py | Info.zoomset_cb | def zoomset_cb(self, setting, value, channel):
"""This callback is called when the main window is zoomed.
"""
if not self.gui_up:
return
info = channel.extdata._info_info
if info is None:
return
#scale_x, scale_y = fitsimage.get_scale_xy()
scale_x, scale_y = value
# Set text showing zoom factor (1X, 2X, etc.)
if scale_x == scale_y:
text = self.fv.scale2text(scale_x)
else:
textx = self.fv.scale2text(scale_x)
texty = self.fv.scale2text(scale_y)
text = "X: %s Y: %s" % (textx, texty)
info.winfo.zoom.set_text(text) | python | def zoomset_cb(self, setting, value, channel):
if not self.gui_up:
return
info = channel.extdata._info_info
if info is None:
return
#scale_x, scale_y = fitsimage.get_scale_xy()
scale_x, scale_y = value
# Set text showing zoom factor (1X, 2X, etc.)
if scale_x == scale_y:
text = self.fv.scale2text(scale_x)
else:
textx = self.fv.scale2text(scale_x)
texty = self.fv.scale2text(scale_y)
text = "X: %s Y: %s" % (textx, texty)
info.winfo.zoom.set_text(text) | [
"def",
"zoomset_cb",
"(",
"self",
",",
"setting",
",",
"value",
",",
"channel",
")",
":",
"if",
"not",
"self",
".",
"gui_up",
":",
"return",
"info",
"=",
"channel",
".",
"extdata",
".",
"_info_info",
"if",
"info",
"is",
"None",
":",
"return",
"#scale_x... | This callback is called when the main window is zoomed. | [
"This",
"callback",
"is",
"called",
"when",
"the",
"main",
"window",
"is",
"zoomed",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Info.py#L319-L337 |
26,351 | ejeschke/ginga | ginga/rv/plugins/MultiDim.py | MultiDim.redo | def redo(self):
"""Called when an image is set in the channel."""
image = self.channel.get_current_image()
if image is None:
return True
path = image.get('path', None)
if path is None:
self.fv.show_error(
"Cannot open image: no value for metadata key 'path'")
return
# TODO: How to properly reset GUI components?
# They are still showing info from prev FITS.
# No-op for ASDF
if path.endswith('asdf'):
return True
if path != self.img_path:
# <-- New file is being looked at
self.img_path = path
# close previous file opener, if any
if self.file_obj is not None:
try:
self.file_obj.close()
except Exception:
pass
self.file_obj = io_fits.get_fitsloader(logger=self.logger)
# TODO: specify 'readonly' somehow?
self.file_obj.open_file(path)
upper = len(self.file_obj) - 1
self.prep_hdu_menu(self.w.hdu, self.file_obj.hdu_info)
self.num_hdu = upper
self.logger.debug("there are %d hdus" % (upper + 1))
self.w.numhdu.set_text("%d" % (upper + 1))
self.w.hdu.set_enabled(len(self.file_obj) > 0)
name = image.get('name', iohelper.name_image_from_path(path))
idx = image.get('idx', None)
# remove index designation from root of name, if any
match = re.match(r'^(.+)\[(.+)\]$', name)
if match:
name = match.group(1)
self.name_pfx = name
htype = None
if idx is not None:
# set the HDU in the drop down if known
info = self.file_obj.hdu_db.get(idx, None)
if info is not None:
htype = info.htype.lower()
toc_ent = self._toc_fmt % info
self.w.hdu.show_text(toc_ent)
# rebuild the NAXIS controls, if necessary
# No two images in the same channel can have the same name.
# Here we keep track of the name to decide if we need to rebuild
if self.img_name != name:
self.img_name = name
dims = [0, 0]
data = image.get_data()
if data is None:
# <- empty data part to this HDU
self.logger.warning("Empty data part in HDU %s" % (str(idx)))
elif htype in ('bintablehdu', 'tablehdu',):
pass
elif htype not in ('imagehdu', 'primaryhdu', 'compimagehdu'):
self.logger.warning("HDU %s is not an image (%s)" % (
str(idx), htype))
else:
mddata = image.get_mddata()
if mddata is not None:
dims = list(mddata.shape)
dims.reverse()
self.build_naxis(dims, image) | python | def redo(self):
image = self.channel.get_current_image()
if image is None:
return True
path = image.get('path', None)
if path is None:
self.fv.show_error(
"Cannot open image: no value for metadata key 'path'")
return
# TODO: How to properly reset GUI components?
# They are still showing info from prev FITS.
# No-op for ASDF
if path.endswith('asdf'):
return True
if path != self.img_path:
# <-- New file is being looked at
self.img_path = path
# close previous file opener, if any
if self.file_obj is not None:
try:
self.file_obj.close()
except Exception:
pass
self.file_obj = io_fits.get_fitsloader(logger=self.logger)
# TODO: specify 'readonly' somehow?
self.file_obj.open_file(path)
upper = len(self.file_obj) - 1
self.prep_hdu_menu(self.w.hdu, self.file_obj.hdu_info)
self.num_hdu = upper
self.logger.debug("there are %d hdus" % (upper + 1))
self.w.numhdu.set_text("%d" % (upper + 1))
self.w.hdu.set_enabled(len(self.file_obj) > 0)
name = image.get('name', iohelper.name_image_from_path(path))
idx = image.get('idx', None)
# remove index designation from root of name, if any
match = re.match(r'^(.+)\[(.+)\]$', name)
if match:
name = match.group(1)
self.name_pfx = name
htype = None
if idx is not None:
# set the HDU in the drop down if known
info = self.file_obj.hdu_db.get(idx, None)
if info is not None:
htype = info.htype.lower()
toc_ent = self._toc_fmt % info
self.w.hdu.show_text(toc_ent)
# rebuild the NAXIS controls, if necessary
# No two images in the same channel can have the same name.
# Here we keep track of the name to decide if we need to rebuild
if self.img_name != name:
self.img_name = name
dims = [0, 0]
data = image.get_data()
if data is None:
# <- empty data part to this HDU
self.logger.warning("Empty data part in HDU %s" % (str(idx)))
elif htype in ('bintablehdu', 'tablehdu',):
pass
elif htype not in ('imagehdu', 'primaryhdu', 'compimagehdu'):
self.logger.warning("HDU %s is not an image (%s)" % (
str(idx), htype))
else:
mddata = image.get_mddata()
if mddata is not None:
dims = list(mddata.shape)
dims.reverse()
self.build_naxis(dims, image) | [
"def",
"redo",
"(",
"self",
")",
":",
"image",
"=",
"self",
".",
"channel",
".",
"get_current_image",
"(",
")",
"if",
"image",
"is",
"None",
":",
"return",
"True",
"path",
"=",
"image",
".",
"get",
"(",
"'path'",
",",
"None",
")",
"if",
"path",
"is... | Called when an image is set in the channel. | [
"Called",
"when",
"an",
"image",
"is",
"set",
"in",
"the",
"channel",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/MultiDim.py#L588-L671 |
26,352 | ejeschke/ginga | ginga/trcalc.py | reorder_image | def reorder_image(dst_order, src_arr, src_order):
"""Reorder src_arr, with order of color planes in src_order, as
dst_order.
"""
depth = src_arr.shape[2]
if depth != len(src_order):
raise ValueError("src_order (%s) does not match array depth (%d)" % (
src_order, depth))
bands = []
if dst_order == src_order:
return np.ascontiguousarray(src_arr)
elif 'A' not in dst_order or 'A' in src_order:
# <-- we don't have to add an alpha plane, just create a new view
idx = np.array([src_order.index(c) for c in dst_order])
return np.ascontiguousarray(src_arr[..., idx])
else:
# <-- dst order requires missing alpha channel
indexes = [src_order.index(c) for c in dst_order.replace('A', '')]
bands = [src_arr[..., idx, np.newaxis] for idx in indexes]
ht, wd = src_arr.shape[:2]
dst_type = src_arr.dtype
dst_max_val = np.iinfo(dst_type).max
alpha = np.full((ht, wd, 1), dst_max_val, dtype=dst_type)
bands.insert(dst_order.index('A'), alpha)
return np.concatenate(bands, axis=-1) | python | def reorder_image(dst_order, src_arr, src_order):
depth = src_arr.shape[2]
if depth != len(src_order):
raise ValueError("src_order (%s) does not match array depth (%d)" % (
src_order, depth))
bands = []
if dst_order == src_order:
return np.ascontiguousarray(src_arr)
elif 'A' not in dst_order or 'A' in src_order:
# <-- we don't have to add an alpha plane, just create a new view
idx = np.array([src_order.index(c) for c in dst_order])
return np.ascontiguousarray(src_arr[..., idx])
else:
# <-- dst order requires missing alpha channel
indexes = [src_order.index(c) for c in dst_order.replace('A', '')]
bands = [src_arr[..., idx, np.newaxis] for idx in indexes]
ht, wd = src_arr.shape[:2]
dst_type = src_arr.dtype
dst_max_val = np.iinfo(dst_type).max
alpha = np.full((ht, wd, 1), dst_max_val, dtype=dst_type)
bands.insert(dst_order.index('A'), alpha)
return np.concatenate(bands, axis=-1) | [
"def",
"reorder_image",
"(",
"dst_order",
",",
"src_arr",
",",
"src_order",
")",
":",
"depth",
"=",
"src_arr",
".",
"shape",
"[",
"2",
"]",
"if",
"depth",
"!=",
"len",
"(",
"src_order",
")",
":",
"raise",
"ValueError",
"(",
"\"src_order (%s) does not match a... | Reorder src_arr, with order of color planes in src_order, as
dst_order. | [
"Reorder",
"src_arr",
"with",
"order",
"of",
"color",
"planes",
"in",
"src_order",
"as",
"dst_order",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/trcalc.py#L845-L873 |
26,353 | ejeschke/ginga | ginga/trcalc.py | strip_z | def strip_z(pts):
"""Strips a Z component from `pts` if it is present."""
pts = np.asarray(pts)
if pts.shape[-1] > 2:
pts = np.asarray((pts.T[0], pts.T[1])).T
return pts | python | def strip_z(pts):
pts = np.asarray(pts)
if pts.shape[-1] > 2:
pts = np.asarray((pts.T[0], pts.T[1])).T
return pts | [
"def",
"strip_z",
"(",
"pts",
")",
":",
"pts",
"=",
"np",
".",
"asarray",
"(",
"pts",
")",
"if",
"pts",
".",
"shape",
"[",
"-",
"1",
"]",
">",
"2",
":",
"pts",
"=",
"np",
".",
"asarray",
"(",
"(",
"pts",
".",
"T",
"[",
"0",
"]",
",",
"pts... | Strips a Z component from `pts` if it is present. | [
"Strips",
"a",
"Z",
"component",
"from",
"pts",
"if",
"it",
"is",
"present",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/trcalc.py#L876-L881 |
26,354 | ejeschke/ginga | ginga/trcalc.py | get_bounds | def get_bounds(pts):
"""Return the minimum point and maximum point bounding a
set of points."""
pts_t = np.asarray(pts).T
return np.asarray(([np.min(_pts) for _pts in pts_t],
[np.max(_pts) for _pts in pts_t])) | python | def get_bounds(pts):
pts_t = np.asarray(pts).T
return np.asarray(([np.min(_pts) for _pts in pts_t],
[np.max(_pts) for _pts in pts_t])) | [
"def",
"get_bounds",
"(",
"pts",
")",
":",
"pts_t",
"=",
"np",
".",
"asarray",
"(",
"pts",
")",
".",
"T",
"return",
"np",
".",
"asarray",
"(",
"(",
"[",
"np",
".",
"min",
"(",
"_pts",
")",
"for",
"_pts",
"in",
"pts_t",
"]",
",",
"[",
"np",
".... | Return the minimum point and maximum point bounding a
set of points. | [
"Return",
"the",
"minimum",
"point",
"and",
"maximum",
"point",
"bounding",
"a",
"set",
"of",
"points",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/trcalc.py#L896-L901 |
26,355 | ejeschke/ginga | ginga/util/toolbox.py | trim_prefix | def trim_prefix(text, nchr):
"""Trim characters off of the beginnings of text lines.
Parameters
----------
text : str
The text to be trimmed, with newlines (\n) separating lines
nchr: int
The number of spaces to trim off the beginning of a line if
it starts with that many spaces
Returns
-------
text : str
The trimmed text
"""
res = []
for line in text.split('\n'):
if line.startswith(' ' * nchr):
line = line[nchr:]
res.append(line)
return '\n'.join(res) | python | def trim_prefix(text, nchr):
res = []
for line in text.split('\n'):
if line.startswith(' ' * nchr):
line = line[nchr:]
res.append(line)
return '\n'.join(res) | [
"def",
"trim_prefix",
"(",
"text",
",",
"nchr",
")",
":",
"res",
"=",
"[",
"]",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"' '",
"*",
"nchr",
")",
":",
"line",
"=",
"line",
"[",
"nc... | Trim characters off of the beginnings of text lines.
Parameters
----------
text : str
The text to be trimmed, with newlines (\n) separating lines
nchr: int
The number of spaces to trim off the beginning of a line if
it starts with that many spaces
Returns
-------
text : str
The trimmed text | [
"Trim",
"characters",
"off",
"of",
"the",
"beginnings",
"of",
"text",
"lines",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/toolbox.py#L107-L130 |
26,356 | ejeschke/ginga | ginga/mockw/ImageViewMock.py | ImageViewMock._get_color | def _get_color(self, r, g, b):
"""Convert red, green and blue values specified in floats with
range 0-1 to whatever the native widget color object is.
"""
clr = (r, g, b)
return clr | python | def _get_color(self, r, g, b):
clr = (r, g, b)
return clr | [
"def",
"_get_color",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"clr",
"=",
"(",
"r",
",",
"g",
",",
"b",
")",
"return",
"clr"
] | Convert red, green and blue values specified in floats with
range 0-1 to whatever the native widget color object is. | [
"Convert",
"red",
"green",
"and",
"blue",
"values",
"specified",
"in",
"floats",
"with",
"range",
"0",
"-",
"1",
"to",
"whatever",
"the",
"native",
"widget",
"color",
"object",
"is",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mockw/ImageViewMock.py#L191-L196 |
26,357 | ejeschke/ginga | ginga/mockw/ImageViewMock.py | ImageViewEvent.key_press_event | def key_press_event(self, widget, event):
"""
Called when a key is pressed and the window has the focus.
Adjust method signature as appropriate for callback.
"""
# get keyname or keycode and translate to ginga standard
# keyname =
# keycode =
keyname = '' # self.transkey(keyname, keycode)
self.logger.debug("key press event, key=%s" % (keyname))
return self.make_ui_callback('key-press', keyname) | python | def key_press_event(self, widget, event):
# get keyname or keycode and translate to ginga standard
# keyname =
# keycode =
keyname = '' # self.transkey(keyname, keycode)
self.logger.debug("key press event, key=%s" % (keyname))
return self.make_ui_callback('key-press', keyname) | [
"def",
"key_press_event",
"(",
"self",
",",
"widget",
",",
"event",
")",
":",
"# get keyname or keycode and translate to ginga standard",
"# keyname =",
"# keycode =",
"keyname",
"=",
"''",
"# self.transkey(keyname, keycode)",
"self",
".",
"logger",
".",
"debug",
"(",
"... | Called when a key is pressed and the window has the focus.
Adjust method signature as appropriate for callback. | [
"Called",
"when",
"a",
"key",
"is",
"pressed",
"and",
"the",
"window",
"has",
"the",
"focus",
".",
"Adjust",
"method",
"signature",
"as",
"appropriate",
"for",
"callback",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mockw/ImageViewMock.py#L309-L319 |
26,358 | ejeschke/ginga | ginga/mockw/ImageViewMock.py | ImageViewEvent.key_release_event | def key_release_event(self, widget, event):
"""
Called when a key is released after being pressed.
Adjust method signature as appropriate for callback.
"""
# get keyname or keycode and translate to ginga standard
# keyname =
# keycode =
keyname = '' # self.transkey(keyname, keycode)
self.logger.debug("key release event, key=%s" % (keyname))
return self.make_ui_callback('key-release', keyname) | python | def key_release_event(self, widget, event):
# get keyname or keycode and translate to ginga standard
# keyname =
# keycode =
keyname = '' # self.transkey(keyname, keycode)
self.logger.debug("key release event, key=%s" % (keyname))
return self.make_ui_callback('key-release', keyname) | [
"def",
"key_release_event",
"(",
"self",
",",
"widget",
",",
"event",
")",
":",
"# get keyname or keycode and translate to ginga standard",
"# keyname =",
"# keycode =",
"keyname",
"=",
"''",
"# self.transkey(keyname, keycode)",
"self",
".",
"logger",
".",
"debug",
"(",
... | Called when a key is released after being pressed.
Adjust method signature as appropriate for callback. | [
"Called",
"when",
"a",
"key",
"is",
"released",
"after",
"being",
"pressed",
".",
"Adjust",
"method",
"signature",
"as",
"appropriate",
"for",
"callback",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/mockw/ImageViewMock.py#L321-L331 |
26,359 | ejeschke/ginga | ginga/qtw/ImageViewQt.py | ScrolledView.resizeEvent | def resizeEvent(self, event):
"""Override from QAbstractScrollArea.
Resize the viewer widget when the viewport is resized."""
vp = self.viewport()
rect = vp.geometry()
x1, y1, x2, y2 = rect.getCoords()
width = x2 - x1 + 1
height = y2 - y1 + 1
self.v_w.resize(width, height) | python | def resizeEvent(self, event):
vp = self.viewport()
rect = vp.geometry()
x1, y1, x2, y2 = rect.getCoords()
width = x2 - x1 + 1
height = y2 - y1 + 1
self.v_w.resize(width, height) | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"vp",
"=",
"self",
".",
"viewport",
"(",
")",
"rect",
"=",
"vp",
".",
"geometry",
"(",
")",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"rect",
".",
"getCoords",
"(",
")",
"width",
"=",... | Override from QAbstractScrollArea.
Resize the viewer widget when the viewport is resized. | [
"Override",
"from",
"QAbstractScrollArea",
".",
"Resize",
"the",
"viewer",
"widget",
"when",
"the",
"viewport",
"is",
"resized",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/ImageViewQt.py#L879-L888 |
26,360 | ejeschke/ginga | ginga/qtw/ImageViewQt.py | ScrolledView.scrollContentsBy | def scrollContentsBy(self, dx, dy):
"""Override from QAbstractScrollArea.
Called when the scroll bars are adjusted by the user.
"""
if self._adjusting:
return
self._scrolling = True
try:
bd = self.viewer.get_bindings()
res = bd.calc_pan_pct(self.viewer, pad=self.pad)
if res is None:
return
pct_x, pct_y = res.pan_pct_x, res.pan_pct_y
# Only adjust pan setting for axes that have changed
if dx != 0:
hsb = self.horizontalScrollBar()
pos_x = float(hsb.value())
pct_x = pos_x / float(self.upper_h)
if dy != 0:
vsb = self.verticalScrollBar()
pos_y = float(vsb.value())
# invert Y pct because of orientation of scrollbar
pct_y = 1.0 - (pos_y / float(self.upper_v))
bd = self.viewer.get_bindings()
bd.pan_by_pct(self.viewer, pct_x, pct_y, pad=self.pad)
# This shouldn't be necessary, but seems to be
self.viewer.redraw(whence=0)
finally:
self._scrolling = False | python | def scrollContentsBy(self, dx, dy):
if self._adjusting:
return
self._scrolling = True
try:
bd = self.viewer.get_bindings()
res = bd.calc_pan_pct(self.viewer, pad=self.pad)
if res is None:
return
pct_x, pct_y = res.pan_pct_x, res.pan_pct_y
# Only adjust pan setting for axes that have changed
if dx != 0:
hsb = self.horizontalScrollBar()
pos_x = float(hsb.value())
pct_x = pos_x / float(self.upper_h)
if dy != 0:
vsb = self.verticalScrollBar()
pos_y = float(vsb.value())
# invert Y pct because of orientation of scrollbar
pct_y = 1.0 - (pos_y / float(self.upper_v))
bd = self.viewer.get_bindings()
bd.pan_by_pct(self.viewer, pct_x, pct_y, pad=self.pad)
# This shouldn't be necessary, but seems to be
self.viewer.redraw(whence=0)
finally:
self._scrolling = False | [
"def",
"scrollContentsBy",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"if",
"self",
".",
"_adjusting",
":",
"return",
"self",
".",
"_scrolling",
"=",
"True",
"try",
":",
"bd",
"=",
"self",
".",
"viewer",
".",
"get_bindings",
"(",
")",
"res",
"=",
... | Override from QAbstractScrollArea.
Called when the scroll bars are adjusted by the user. | [
"Override",
"from",
"QAbstractScrollArea",
".",
"Called",
"when",
"the",
"scroll",
"bars",
"are",
"adjusted",
"by",
"the",
"user",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/qtw/ImageViewQt.py#L927-L960 |
26,361 | ejeschke/ginga | ginga/canvas/transform.py | get_catalog | def get_catalog():
"""Returns a catalog of available transforms. These are used to
build chains for rendering with different back ends.
"""
tforms = {}
for name, value in list(globals().items()):
if name.endswith('Transform'):
tforms[name] = value
return Bunch.Bunch(tforms, caseless=True) | python | def get_catalog():
tforms = {}
for name, value in list(globals().items()):
if name.endswith('Transform'):
tforms[name] = value
return Bunch.Bunch(tforms, caseless=True) | [
"def",
"get_catalog",
"(",
")",
":",
"tforms",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"list",
"(",
"globals",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'Transform'",
")",
":",
"tforms",
"[",
"name... | Returns a catalog of available transforms. These are used to
build chains for rendering with different back ends. | [
"Returns",
"a",
"catalog",
"of",
"available",
"transforms",
".",
"These",
"are",
"used",
"to",
"build",
"chains",
"for",
"rendering",
"with",
"different",
"back",
"ends",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/transform.py#L553-L562 |
26,362 | ejeschke/ginga | ginga/util/dp.py | masktorgb | def masktorgb(mask, color='lightgreen', alpha=1.0):
"""Convert boolean mask to RGB image object for canvas overlay.
Parameters
----------
mask : ndarray
Boolean mask to overlay. 2D image only.
color : str
Color name accepted by Ginga.
alpha : float
Opacity. Unmasked data are always transparent.
Returns
-------
rgbobj : RGBImage
RGB image for canvas Image object.
Raises
------
ValueError
Invalid mask dimension.
"""
mask = np.asarray(mask)
if mask.ndim != 2:
raise ValueError('ndim={0} is not supported'.format(mask.ndim))
ht, wd = mask.shape
r, g, b = colors.lookup_color(color)
rgbobj = RGBImage(data_np=np.zeros((ht, wd, 4), dtype=np.uint8))
rc = rgbobj.get_slice('R')
gc = rgbobj.get_slice('G')
bc = rgbobj.get_slice('B')
ac = rgbobj.get_slice('A')
ac[:] = 0 # Transparent background
rc[mask] = int(r * 255)
gc[mask] = int(g * 255)
bc[mask] = int(b * 255)
ac[mask] = int(alpha * 255)
# For debugging
#rgbobj.save_as_file('ztmp_rgbobj.png')
return rgbobj | python | def masktorgb(mask, color='lightgreen', alpha=1.0):
mask = np.asarray(mask)
if mask.ndim != 2:
raise ValueError('ndim={0} is not supported'.format(mask.ndim))
ht, wd = mask.shape
r, g, b = colors.lookup_color(color)
rgbobj = RGBImage(data_np=np.zeros((ht, wd, 4), dtype=np.uint8))
rc = rgbobj.get_slice('R')
gc = rgbobj.get_slice('G')
bc = rgbobj.get_slice('B')
ac = rgbobj.get_slice('A')
ac[:] = 0 # Transparent background
rc[mask] = int(r * 255)
gc[mask] = int(g * 255)
bc[mask] = int(b * 255)
ac[mask] = int(alpha * 255)
# For debugging
#rgbobj.save_as_file('ztmp_rgbobj.png')
return rgbobj | [
"def",
"masktorgb",
"(",
"mask",
",",
"color",
"=",
"'lightgreen'",
",",
"alpha",
"=",
"1.0",
")",
":",
"mask",
"=",
"np",
".",
"asarray",
"(",
"mask",
")",
"if",
"mask",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'ndim={0} is not suppor... | Convert boolean mask to RGB image object for canvas overlay.
Parameters
----------
mask : ndarray
Boolean mask to overlay. 2D image only.
color : str
Color name accepted by Ginga.
alpha : float
Opacity. Unmasked data are always transparent.
Returns
-------
rgbobj : RGBImage
RGB image for canvas Image object.
Raises
------
ValueError
Invalid mask dimension. | [
"Convert",
"boolean",
"mask",
"to",
"RGB",
"image",
"object",
"for",
"canvas",
"overlay",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/dp.py#L206-L254 |
26,363 | ejeschke/ginga | ginga/doc/download_doc.py | _find_rtd_version | def _find_rtd_version():
"""Find closest RTD doc version."""
vstr = 'latest'
try:
import ginga
from bs4 import BeautifulSoup
except ImportError:
return vstr
# No active doc build before this release, just use latest.
if not minversion(ginga, '2.6.0'):
return vstr
# Get RTD download listing.
url = 'https://readthedocs.org/projects/ginga/downloads/'
with urllib.request.urlopen(url) as r:
soup = BeautifulSoup(r, 'html.parser')
# Compile a list of available HTML doc versions for download.
all_rtd_vernums = []
for link in soup.find_all('a'):
href = link.get('href')
if 'htmlzip' not in href:
continue
s = href.split('/')[-2]
if s.startswith('v'): # Ignore latest and stable
all_rtd_vernums.append(s)
all_rtd_vernums.sort(reverse=True)
# Find closest match.
ginga_ver = ginga.__version__
for rtd_ver in all_rtd_vernums:
if ginga_ver > rtd_ver[1:]: # Ignore "v" in comparison
break
else:
vstr = rtd_ver
return vstr | python | def _find_rtd_version():
vstr = 'latest'
try:
import ginga
from bs4 import BeautifulSoup
except ImportError:
return vstr
# No active doc build before this release, just use latest.
if not minversion(ginga, '2.6.0'):
return vstr
# Get RTD download listing.
url = 'https://readthedocs.org/projects/ginga/downloads/'
with urllib.request.urlopen(url) as r:
soup = BeautifulSoup(r, 'html.parser')
# Compile a list of available HTML doc versions for download.
all_rtd_vernums = []
for link in soup.find_all('a'):
href = link.get('href')
if 'htmlzip' not in href:
continue
s = href.split('/')[-2]
if s.startswith('v'): # Ignore latest and stable
all_rtd_vernums.append(s)
all_rtd_vernums.sort(reverse=True)
# Find closest match.
ginga_ver = ginga.__version__
for rtd_ver in all_rtd_vernums:
if ginga_ver > rtd_ver[1:]: # Ignore "v" in comparison
break
else:
vstr = rtd_ver
return vstr | [
"def",
"_find_rtd_version",
"(",
")",
":",
"vstr",
"=",
"'latest'",
"try",
":",
"import",
"ginga",
"from",
"bs4",
"import",
"BeautifulSoup",
"except",
"ImportError",
":",
"return",
"vstr",
"# No active doc build before this release, just use latest.",
"if",
"not",
"mi... | Find closest RTD doc version. | [
"Find",
"closest",
"RTD",
"doc",
"version",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L15-L52 |
26,364 | ejeschke/ginga | ginga/doc/download_doc.py | _download_rtd_zip | def _download_rtd_zip(rtd_version=None, **kwargs):
"""
Download and extract HTML ZIP from RTD to installed doc data path.
Download is skipped if content already exists.
Parameters
----------
rtd_version : str or `None`
RTD version to download; e.g., "latest", "stable", or "v2.6.0".
If not given, download closest match to software version.
kwargs : dict
Keywords for ``urlretrieve()``.
Returns
-------
index_html : str
Path to local "index.html".
"""
# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134
if not toolkit.family.startswith('qt'):
raise ValueError('Downloaded documentation not compatible with {} '
'UI toolkit browser'.format(toolkit.family))
if rtd_version is None:
rtd_version = _find_rtd_version()
data_path = os.path.dirname(
_find_pkg_data_path('help.html', package='ginga.doc'))
index_html = os.path.join(data_path, 'index.html')
# There is a previous download of documentation; Do nothing.
# There is no check if downloaded version is outdated; The idea is that
# this folder would be empty again when installing new version.
if os.path.isfile(index_html):
return index_html
url = ('https://readthedocs.org/projects/ginga/downloads/htmlzip/'
'{}/'.format(rtd_version))
local_path = urllib.request.urlretrieve(url, **kwargs)[0]
with zipfile.ZipFile(local_path, 'r') as zf:
zf.extractall(data_path)
# RTD makes an undesirable sub-directory, so move everything there
# up one level and delete it.
subdir = os.path.join(data_path, 'ginga-{}'.format(rtd_version))
for s in os.listdir(subdir):
src = os.path.join(subdir, s)
if os.path.isfile(src):
shutil.copy(src, data_path)
else: # directory
shutil.copytree(src, os.path.join(data_path, s))
shutil.rmtree(subdir)
if not os.path.isfile(index_html):
raise OSError(
'{} is missing; Ginga doc download failed'.format(index_html))
return index_html | python | def _download_rtd_zip(rtd_version=None, **kwargs):
# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134
if not toolkit.family.startswith('qt'):
raise ValueError('Downloaded documentation not compatible with {} '
'UI toolkit browser'.format(toolkit.family))
if rtd_version is None:
rtd_version = _find_rtd_version()
data_path = os.path.dirname(
_find_pkg_data_path('help.html', package='ginga.doc'))
index_html = os.path.join(data_path, 'index.html')
# There is a previous download of documentation; Do nothing.
# There is no check if downloaded version is outdated; The idea is that
# this folder would be empty again when installing new version.
if os.path.isfile(index_html):
return index_html
url = ('https://readthedocs.org/projects/ginga/downloads/htmlzip/'
'{}/'.format(rtd_version))
local_path = urllib.request.urlretrieve(url, **kwargs)[0]
with zipfile.ZipFile(local_path, 'r') as zf:
zf.extractall(data_path)
# RTD makes an undesirable sub-directory, so move everything there
# up one level and delete it.
subdir = os.path.join(data_path, 'ginga-{}'.format(rtd_version))
for s in os.listdir(subdir):
src = os.path.join(subdir, s)
if os.path.isfile(src):
shutil.copy(src, data_path)
else: # directory
shutil.copytree(src, os.path.join(data_path, s))
shutil.rmtree(subdir)
if not os.path.isfile(index_html):
raise OSError(
'{} is missing; Ginga doc download failed'.format(index_html))
return index_html | [
"def",
"_download_rtd_zip",
"(",
"rtd_version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134",
"if",
"not",
"toolkit",
".",
"family",
".",
"startswith",
"(",
"'qt'",
")",
":",
"raise",
"ValueErr... | Download and extract HTML ZIP from RTD to installed doc data path.
Download is skipped if content already exists.
Parameters
----------
rtd_version : str or `None`
RTD version to download; e.g., "latest", "stable", or "v2.6.0".
If not given, download closest match to software version.
kwargs : dict
Keywords for ``urlretrieve()``.
Returns
-------
index_html : str
Path to local "index.html". | [
"Download",
"and",
"extract",
"HTML",
"ZIP",
"from",
"RTD",
"to",
"installed",
"doc",
"data",
"path",
".",
"Download",
"is",
"skipped",
"if",
"content",
"already",
"exists",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L55-L115 |
26,365 | ejeschke/ginga | ginga/doc/download_doc.py | get_doc | def get_doc(logger=None, plugin=None, reporthook=None):
"""
Return URL to documentation. Attempt download if does not exist.
Parameters
----------
logger : obj or `None`
Ginga logger.
plugin : obj or `None`
Plugin object. If given, URL points to plugin doc directly.
If this function is called from within plugin class,
pass ``self`` here.
reporthook : callable or `None`
Report hook for ``urlretrieve()``.
Returns
-------
url : str or `None`
URL to local documentation, if available.
"""
from ginga.GingaPlugin import GlobalPlugin, LocalPlugin
if isinstance(plugin, GlobalPlugin):
plugin_page = 'plugins_global'
plugin_name = str(plugin)
elif isinstance(plugin, LocalPlugin):
plugin_page = 'plugins_local'
plugin_name = str(plugin)
else:
plugin_page = None
plugin_name = None
try:
index_html = _download_rtd_zip(reporthook=reporthook)
# Download failed, use online resource
except Exception as e:
url = 'https://ginga.readthedocs.io/en/latest/'
if plugin_name is not None:
if toolkit.family.startswith('qt'):
# This displays plugin docstring.
url = None
else:
# This redirects to online doc.
url += 'manual/{}/{}.html'.format(plugin_page, plugin_name)
if logger is not None:
logger.error(str(e))
# Use local resource
else:
pfx = 'file:'
url = '{}{}'.format(pfx, index_html)
# https://github.com/rtfd/readthedocs.org/issues/2803
if plugin_name is not None:
url += '#{}'.format(plugin_name)
return url | python | def get_doc(logger=None, plugin=None, reporthook=None):
from ginga.GingaPlugin import GlobalPlugin, LocalPlugin
if isinstance(plugin, GlobalPlugin):
plugin_page = 'plugins_global'
plugin_name = str(plugin)
elif isinstance(plugin, LocalPlugin):
plugin_page = 'plugins_local'
plugin_name = str(plugin)
else:
plugin_page = None
plugin_name = None
try:
index_html = _download_rtd_zip(reporthook=reporthook)
# Download failed, use online resource
except Exception as e:
url = 'https://ginga.readthedocs.io/en/latest/'
if plugin_name is not None:
if toolkit.family.startswith('qt'):
# This displays plugin docstring.
url = None
else:
# This redirects to online doc.
url += 'manual/{}/{}.html'.format(plugin_page, plugin_name)
if logger is not None:
logger.error(str(e))
# Use local resource
else:
pfx = 'file:'
url = '{}{}'.format(pfx, index_html)
# https://github.com/rtfd/readthedocs.org/issues/2803
if plugin_name is not None:
url += '#{}'.format(plugin_name)
return url | [
"def",
"get_doc",
"(",
"logger",
"=",
"None",
",",
"plugin",
"=",
"None",
",",
"reporthook",
"=",
"None",
")",
":",
"from",
"ginga",
".",
"GingaPlugin",
"import",
"GlobalPlugin",
",",
"LocalPlugin",
"if",
"isinstance",
"(",
"plugin",
",",
"GlobalPlugin",
"... | Return URL to documentation. Attempt download if does not exist.
Parameters
----------
logger : obj or `None`
Ginga logger.
plugin : obj or `None`
Plugin object. If given, URL points to plugin doc directly.
If this function is called from within plugin class,
pass ``self`` here.
reporthook : callable or `None`
Report hook for ``urlretrieve()``.
Returns
-------
url : str or `None`
URL to local documentation, if available. | [
"Return",
"URL",
"to",
"documentation",
".",
"Attempt",
"download",
"if",
"does",
"not",
"exist",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/doc/download_doc.py#L118-L180 |
26,366 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.redo | def redo(self, *args):
"""Generate listing of images that user can save."""
if not self.gui_up:
return
mod_only = self.w.modified_only.get_state()
treedict = Bunch.caselessDict()
self.treeview.clear()
self.w.status.set_text('')
channel = self.fv.get_channel(self.chname)
if channel is None:
return
# Only list modified images for saving. Scanning Datasrc is enough.
if mod_only:
all_keys = channel.datasrc.keys(sort='alpha')
# List all images in the channel.
else:
all_keys = channel.get_image_names()
# Extract info for listing and saving
for key in all_keys:
iminfo = channel.get_image_info(key)
path = iminfo.get('path')
idx = iminfo.get('idx')
t = iminfo.get('time_modified')
if path is None: # Special handling for generated buffer, eg mosaic
infile = key
is_fits = True
else:
infile = os.path.basename(path)
infile_ext = os.path.splitext(path)[1]
infile_ext = infile_ext.lower()
is_fits = False
if 'fit' in infile_ext:
is_fits = True
# Only list FITS files unless it is Ginga generated buffer
if not is_fits:
continue
# Only list modified buffers
if mod_only and t is None:
continue
# More than one ext modified, append to existing entry
if infile in treedict:
if t is not None:
treedict[infile].extlist.add(idx)
elist = sorted(treedict[infile].extlist)
treedict[infile].MODEXT = ';'.join(
map(self._format_extname, elist))
# Add new entry
else:
if t is None:
s = ''
extlist = set()
else:
s = self._format_extname(idx)
extlist = set([idx])
treedict[infile] = Bunch.Bunch(
IMAGE=infile, MODEXT=s, extlist=extlist, path=path)
self.treeview.set_tree(treedict)
# Resize column widths
n_rows = len(treedict)
if n_rows == 0:
self.w.status.set_text('Nothing available for saving')
elif n_rows < self.settings.get('max_rows_for_col_resize', 5000):
self.treeview.set_optimal_column_widths()
self.logger.debug('Resized columns for {0} row(s)'.format(n_rows)) | python | def redo(self, *args):
if not self.gui_up:
return
mod_only = self.w.modified_only.get_state()
treedict = Bunch.caselessDict()
self.treeview.clear()
self.w.status.set_text('')
channel = self.fv.get_channel(self.chname)
if channel is None:
return
# Only list modified images for saving. Scanning Datasrc is enough.
if mod_only:
all_keys = channel.datasrc.keys(sort='alpha')
# List all images in the channel.
else:
all_keys = channel.get_image_names()
# Extract info for listing and saving
for key in all_keys:
iminfo = channel.get_image_info(key)
path = iminfo.get('path')
idx = iminfo.get('idx')
t = iminfo.get('time_modified')
if path is None: # Special handling for generated buffer, eg mosaic
infile = key
is_fits = True
else:
infile = os.path.basename(path)
infile_ext = os.path.splitext(path)[1]
infile_ext = infile_ext.lower()
is_fits = False
if 'fit' in infile_ext:
is_fits = True
# Only list FITS files unless it is Ginga generated buffer
if not is_fits:
continue
# Only list modified buffers
if mod_only and t is None:
continue
# More than one ext modified, append to existing entry
if infile in treedict:
if t is not None:
treedict[infile].extlist.add(idx)
elist = sorted(treedict[infile].extlist)
treedict[infile].MODEXT = ';'.join(
map(self._format_extname, elist))
# Add new entry
else:
if t is None:
s = ''
extlist = set()
else:
s = self._format_extname(idx)
extlist = set([idx])
treedict[infile] = Bunch.Bunch(
IMAGE=infile, MODEXT=s, extlist=extlist, path=path)
self.treeview.set_tree(treedict)
# Resize column widths
n_rows = len(treedict)
if n_rows == 0:
self.w.status.set_text('Nothing available for saving')
elif n_rows < self.settings.get('max_rows_for_col_resize', 5000):
self.treeview.set_optimal_column_widths()
self.logger.debug('Resized columns for {0} row(s)'.format(n_rows)) | [
"def",
"redo",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"gui_up",
":",
"return",
"mod_only",
"=",
"self",
".",
"w",
".",
"modified_only",
".",
"get_state",
"(",
")",
"treedict",
"=",
"Bunch",
".",
"caselessDict",
"(",
")",
... | Generate listing of images that user can save. | [
"Generate",
"listing",
"of",
"images",
"that",
"user",
"can",
"save",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L181-L257 |
26,367 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.update_channels | def update_channels(self):
"""Update the GUI to reflect channels and image listing.
"""
if not self.gui_up:
return
self.logger.debug("channel configuration has changed--updating gui")
try:
channel = self.fv.get_channel(self.chname)
except KeyError:
channel = self.fv.get_channel_info()
if channel is None:
raise ValueError('No channel available')
self.chname = channel.name
w = self.w.channel_name
w.clear()
self.chnames = list(self.fv.get_channel_names())
#self.chnames.sort()
for chname in self.chnames:
w.append_text(chname)
# select the channel that is the current one
try:
i = self.chnames.index(channel.name)
except IndexError:
i = 0
self.w.channel_name.set_index(i)
# update the image listing
self.redo() | python | def update_channels(self):
if not self.gui_up:
return
self.logger.debug("channel configuration has changed--updating gui")
try:
channel = self.fv.get_channel(self.chname)
except KeyError:
channel = self.fv.get_channel_info()
if channel is None:
raise ValueError('No channel available')
self.chname = channel.name
w = self.w.channel_name
w.clear()
self.chnames = list(self.fv.get_channel_names())
#self.chnames.sort()
for chname in self.chnames:
w.append_text(chname)
# select the channel that is the current one
try:
i = self.chnames.index(channel.name)
except IndexError:
i = 0
self.w.channel_name.set_index(i)
# update the image listing
self.redo() | [
"def",
"update_channels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"gui_up",
":",
"return",
"self",
".",
"logger",
".",
"debug",
"(",
"\"channel configuration has changed--updating gui\"",
")",
"try",
":",
"channel",
"=",
"self",
".",
"fv",
".",
"get... | Update the GUI to reflect channels and image listing. | [
"Update",
"the",
"GUI",
"to",
"reflect",
"channels",
"and",
"image",
"listing",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L259-L293 |
26,368 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage._format_extname | def _format_extname(self, ext):
"""Pretty print given extension name and number tuple."""
if ext is None:
outs = ext
else:
outs = '{0},{1}'.format(ext[0], ext[1])
return outs | python | def _format_extname(self, ext):
if ext is None:
outs = ext
else:
outs = '{0},{1}'.format(ext[0], ext[1])
return outs | [
"def",
"_format_extname",
"(",
"self",
",",
"ext",
")",
":",
"if",
"ext",
"is",
"None",
":",
"outs",
"=",
"ext",
"else",
":",
"outs",
"=",
"'{0},{1}'",
".",
"format",
"(",
"ext",
"[",
"0",
"]",
",",
"ext",
"[",
"1",
"]",
")",
"return",
"outs"
] | Pretty print given extension name and number tuple. | [
"Pretty",
"print",
"given",
"extension",
"name",
"and",
"number",
"tuple",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L300-L306 |
26,369 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.browse_outdir | def browse_outdir(self):
"""Browse for output directory."""
self.dirsel.popup(
'Select directory', self.w.outdir.set_text, initialdir=self.outdir)
self.set_outdir() | python | def browse_outdir(self):
self.dirsel.popup(
'Select directory', self.w.outdir.set_text, initialdir=self.outdir)
self.set_outdir() | [
"def",
"browse_outdir",
"(",
"self",
")",
":",
"self",
".",
"dirsel",
".",
"popup",
"(",
"'Select directory'",
",",
"self",
".",
"w",
".",
"outdir",
".",
"set_text",
",",
"initialdir",
"=",
"self",
".",
"outdir",
")",
"self",
".",
"set_outdir",
"(",
")... | Browse for output directory. | [
"Browse",
"for",
"output",
"directory",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L308-L312 |
26,370 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.set_outdir | def set_outdir(self):
"""Set output directory."""
dirname = self.w.outdir.get_text()
if os.path.isdir(dirname):
self.outdir = dirname
self.logger.debug('Output directory set to {0}'.format(self.outdir))
else:
self.w.outdir.set_text(self.outdir)
self.logger.error('{0} is not a directory'.format(dirname)) | python | def set_outdir(self):
dirname = self.w.outdir.get_text()
if os.path.isdir(dirname):
self.outdir = dirname
self.logger.debug('Output directory set to {0}'.format(self.outdir))
else:
self.w.outdir.set_text(self.outdir)
self.logger.error('{0} is not a directory'.format(dirname)) | [
"def",
"set_outdir",
"(",
"self",
")",
":",
"dirname",
"=",
"self",
".",
"w",
".",
"outdir",
".",
"get_text",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"self",
".",
"outdir",
"=",
"dirname",
"self",
".",
"logger",
... | Set output directory. | [
"Set",
"output",
"directory",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L314-L322 |
26,371 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.set_suffix | def set_suffix(self):
"""Set output suffix."""
self.suffix = self.w.suffix.get_text()
self.logger.debug('Output suffix set to {0}'.format(self.suffix)) | python | def set_suffix(self):
self.suffix = self.w.suffix.get_text()
self.logger.debug('Output suffix set to {0}'.format(self.suffix)) | [
"def",
"set_suffix",
"(",
"self",
")",
":",
"self",
".",
"suffix",
"=",
"self",
".",
"w",
".",
"suffix",
".",
"get_text",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Output suffix set to {0}'",
".",
"format",
"(",
"self",
".",
"suffix",
")",
... | Set output suffix. | [
"Set",
"output",
"suffix",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L324-L327 |
26,372 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage._write_history | def _write_history(self, pfx, hdu, linechar=60, indentchar=2):
"""Write change history to given HDU header.
Limit each HISTORY line to given number of characters.
Subsequent lines of the same history will be indented.
"""
channel = self.fv.get_channel(self.chname)
if channel is None:
return
history_plgname = 'ChangeHistory'
try:
history_obj = self.fv.gpmon.getPlugin(history_plgname)
except Exception:
self.logger.error(
'{0} plugin is not loaded. No HISTORY will be written to '
'{1}.'.format(history_plgname, pfx))
return
if channel.name not in history_obj.name_dict:
self.logger.error(
'{0} channel not found in {1}. No HISTORY will be written to '
'{2}.'.format(channel.name, history_plgname, pfx))
return
file_dict = history_obj.name_dict[channel.name]
chistory = []
ind = ' ' * indentchar
# NOTE: List comprehension too slow!
for key in file_dict:
if not key.startswith(pfx):
continue
for bnch in file_dict[key].values():
chistory.append('{0} {1}'.format(bnch.MODIFIED, bnch.DESCRIP))
# Add each HISTORY prettily into header, sorted by timestamp
for s in sorted(chistory):
for i in range(0, len(s), linechar):
subs = s[i:i + linechar]
if i > 0:
subs = ind + subs.lstrip()
hdu.header.add_history(subs) | python | def _write_history(self, pfx, hdu, linechar=60, indentchar=2):
channel = self.fv.get_channel(self.chname)
if channel is None:
return
history_plgname = 'ChangeHistory'
try:
history_obj = self.fv.gpmon.getPlugin(history_plgname)
except Exception:
self.logger.error(
'{0} plugin is not loaded. No HISTORY will be written to '
'{1}.'.format(history_plgname, pfx))
return
if channel.name not in history_obj.name_dict:
self.logger.error(
'{0} channel not found in {1}. No HISTORY will be written to '
'{2}.'.format(channel.name, history_plgname, pfx))
return
file_dict = history_obj.name_dict[channel.name]
chistory = []
ind = ' ' * indentchar
# NOTE: List comprehension too slow!
for key in file_dict:
if not key.startswith(pfx):
continue
for bnch in file_dict[key].values():
chistory.append('{0} {1}'.format(bnch.MODIFIED, bnch.DESCRIP))
# Add each HISTORY prettily into header, sorted by timestamp
for s in sorted(chistory):
for i in range(0, len(s), linechar):
subs = s[i:i + linechar]
if i > 0:
subs = ind + subs.lstrip()
hdu.header.add_history(subs) | [
"def",
"_write_history",
"(",
"self",
",",
"pfx",
",",
"hdu",
",",
"linechar",
"=",
"60",
",",
"indentchar",
"=",
"2",
")",
":",
"channel",
"=",
"self",
".",
"fv",
".",
"get_channel",
"(",
"self",
".",
"chname",
")",
"if",
"channel",
"is",
"None",
... | Write change history to given HDU header.
Limit each HISTORY line to given number of characters.
Subsequent lines of the same history will be indented. | [
"Write",
"change",
"history",
"to",
"given",
"HDU",
"header",
".",
"Limit",
"each",
"HISTORY",
"line",
"to",
"given",
"number",
"of",
"characters",
".",
"Subsequent",
"lines",
"of",
"the",
"same",
"history",
"will",
"be",
"indented",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L329-L370 |
26,373 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage._write_header | def _write_header(self, image, hdu):
"""Write header from image object to given HDU."""
hduhdr = hdu.header
# Ginga image header object for the given extension only.
# Cannot use get_header() because that might also return PRI hdr.
ghdr = image.metadata['header']
for key in ghdr:
# Need this to avoid duplication because COMMENT is a weird field
if key.upper() == 'COMMENT':
continue
bnch = ghdr.get_card(key)
# Insert new keyword
if key not in hduhdr:
hduhdr[key] = (bnch.value, bnch.comment)
# Update existing keyword
elif hduhdr[key] != bnch.value:
hduhdr[key] = bnch.value | python | def _write_header(self, image, hdu):
hduhdr = hdu.header
# Ginga image header object for the given extension only.
# Cannot use get_header() because that might also return PRI hdr.
ghdr = image.metadata['header']
for key in ghdr:
# Need this to avoid duplication because COMMENT is a weird field
if key.upper() == 'COMMENT':
continue
bnch = ghdr.get_card(key)
# Insert new keyword
if key not in hduhdr:
hduhdr[key] = (bnch.value, bnch.comment)
# Update existing keyword
elif hduhdr[key] != bnch.value:
hduhdr[key] = bnch.value | [
"def",
"_write_header",
"(",
"self",
",",
"image",
",",
"hdu",
")",
":",
"hduhdr",
"=",
"hdu",
".",
"header",
"# Ginga image header object for the given extension only.",
"# Cannot use get_header() because that might also return PRI hdr.",
"ghdr",
"=",
"image",
".",
"metada... | Write header from image object to given HDU. | [
"Write",
"header",
"from",
"image",
"object",
"to",
"given",
"HDU",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L372-L393 |
26,374 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage._write_mef | def _write_mef(self, key, extlist, outfile):
"""Write out regular multi-extension FITS data."""
channel = self.fv.get_channel(self.chname)
with fits.open(outfile, mode='update') as pf:
# Process each modified data extension
for idx in extlist:
k = '{0}[{1}]'.format(key, self._format_extname(idx))
image = channel.datasrc[k]
# Insert data and header into output HDU
pf[idx].data = image.get_data()
self._write_header(image, pf[idx])
# Write history to PRIMARY
self._write_history(key, pf['PRIMARY']) | python | def _write_mef(self, key, extlist, outfile):
channel = self.fv.get_channel(self.chname)
with fits.open(outfile, mode='update') as pf:
# Process each modified data extension
for idx in extlist:
k = '{0}[{1}]'.format(key, self._format_extname(idx))
image = channel.datasrc[k]
# Insert data and header into output HDU
pf[idx].data = image.get_data()
self._write_header(image, pf[idx])
# Write history to PRIMARY
self._write_history(key, pf['PRIMARY']) | [
"def",
"_write_mef",
"(",
"self",
",",
"key",
",",
"extlist",
",",
"outfile",
")",
":",
"channel",
"=",
"self",
".",
"fv",
".",
"get_channel",
"(",
"self",
".",
"chname",
")",
"with",
"fits",
".",
"open",
"(",
"outfile",
",",
"mode",
"=",
"'update'",... | Write out regular multi-extension FITS data. | [
"Write",
"out",
"regular",
"multi",
"-",
"extension",
"FITS",
"data",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L424-L438 |
26,375 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.toggle_save_cb | def toggle_save_cb(self, w, res_dict):
"""Only enable saving if something is selected."""
if len(res_dict) > 0:
self.w.save.set_enabled(True)
else:
self.w.save.set_enabled(False) | python | def toggle_save_cb(self, w, res_dict):
if len(res_dict) > 0:
self.w.save.set_enabled(True)
else:
self.w.save.set_enabled(False) | [
"def",
"toggle_save_cb",
"(",
"self",
",",
"w",
",",
"res_dict",
")",
":",
"if",
"len",
"(",
"res_dict",
")",
">",
"0",
":",
"self",
".",
"w",
".",
"save",
".",
"set_enabled",
"(",
"True",
")",
"else",
":",
"self",
".",
"w",
".",
"save",
".",
"... | Only enable saving if something is selected. | [
"Only",
"enable",
"saving",
"if",
"something",
"is",
"selected",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L440-L445 |
26,376 | ejeschke/ginga | ginga/rv/plugins/SaveImage.py | SaveImage.save_images | def save_images(self):
"""Save selected images.
This uses Astropy FITS package to save the outputs no matter
what user chose to load the images.
"""
res_dict = self.treeview.get_selected()
clobber = self.settings.get('clobber', False)
self.treeview.clear_selection() # Automatically disables Save button
# If user gives empty string, no suffix.
if self.suffix:
sfx = '_' + self.suffix
else:
sfx = ''
# Also include channel name in suffix. This is useful if user likes to
# open the same image in multiple channels.
if self.settings.get('include_chname', True):
sfx += '_' + self.chname
# Process each selected file. Each can have multiple edited extensions.
for infile in res_dict:
f_pfx = os.path.splitext(infile)[0] # prefix
f_ext = '.fits' # Only FITS supported
oname = f_pfx + sfx + f_ext
outfile = os.path.join(self.outdir, oname)
self.w.status.set_text(
'Writing out {0} to {1} ...'.format(shorten_name(infile, 10),
shorten_name(oname, 10)))
self.logger.debug(
'Writing out {0} to {1} ...'.format(infile, oname))
if os.path.exists(outfile) and not clobber:
self.logger.error('{0} already exists'.format(outfile))
continue
bnch = res_dict[infile]
if bnch.path is None or not os.path.isfile(bnch.path):
self._write_mosaic(f_pfx, outfile)
else:
shutil.copyfile(bnch.path, outfile)
self._write_mef(f_pfx, bnch.extlist, outfile)
self.logger.info('{0} written'.format(outfile))
self.w.status.set_text('Saving done, see log') | python | def save_images(self):
res_dict = self.treeview.get_selected()
clobber = self.settings.get('clobber', False)
self.treeview.clear_selection() # Automatically disables Save button
# If user gives empty string, no suffix.
if self.suffix:
sfx = '_' + self.suffix
else:
sfx = ''
# Also include channel name in suffix. This is useful if user likes to
# open the same image in multiple channels.
if self.settings.get('include_chname', True):
sfx += '_' + self.chname
# Process each selected file. Each can have multiple edited extensions.
for infile in res_dict:
f_pfx = os.path.splitext(infile)[0] # prefix
f_ext = '.fits' # Only FITS supported
oname = f_pfx + sfx + f_ext
outfile = os.path.join(self.outdir, oname)
self.w.status.set_text(
'Writing out {0} to {1} ...'.format(shorten_name(infile, 10),
shorten_name(oname, 10)))
self.logger.debug(
'Writing out {0} to {1} ...'.format(infile, oname))
if os.path.exists(outfile) and not clobber:
self.logger.error('{0} already exists'.format(outfile))
continue
bnch = res_dict[infile]
if bnch.path is None or not os.path.isfile(bnch.path):
self._write_mosaic(f_pfx, outfile)
else:
shutil.copyfile(bnch.path, outfile)
self._write_mef(f_pfx, bnch.extlist, outfile)
self.logger.info('{0} written'.format(outfile))
self.w.status.set_text('Saving done, see log') | [
"def",
"save_images",
"(",
"self",
")",
":",
"res_dict",
"=",
"self",
".",
"treeview",
".",
"get_selected",
"(",
")",
"clobber",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'clobber'",
",",
"False",
")",
"self",
".",
"treeview",
".",
"clear_selection... | Save selected images.
This uses Astropy FITS package to save the outputs no matter
what user chose to load the images. | [
"Save",
"selected",
"images",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/SaveImage.py#L447-L496 |
26,377 | ejeschke/ginga | ginga/web/pgw/PgHelp.py | font_info | def font_info(font_str):
"""Extract font information from a font string, such as supplied to the
'font' argument to a widget.
"""
vals = font_str.split(';')
point_size, style, weight = 8, 'normal', 'normal'
family = vals[0]
if len(vals) > 1:
style = vals[1]
if len(vals) > 2:
weight = vals[2]
match = font_regex.match(family)
if match:
family, point_size = match.groups()
point_size = int(point_size)
return Bunch.Bunch(family=family, point_size=point_size,
style=style, weight=weight) | python | def font_info(font_str):
vals = font_str.split(';')
point_size, style, weight = 8, 'normal', 'normal'
family = vals[0]
if len(vals) > 1:
style = vals[1]
if len(vals) > 2:
weight = vals[2]
match = font_regex.match(family)
if match:
family, point_size = match.groups()
point_size = int(point_size)
return Bunch.Bunch(family=family, point_size=point_size,
style=style, weight=weight) | [
"def",
"font_info",
"(",
"font_str",
")",
":",
"vals",
"=",
"font_str",
".",
"split",
"(",
"';'",
")",
"point_size",
",",
"style",
",",
"weight",
"=",
"8",
",",
"'normal'",
",",
"'normal'",
"family",
"=",
"vals",
"[",
"0",
"]",
"if",
"len",
"(",
"v... | Extract font information from a font string, such as supplied to the
'font' argument to a widget. | [
"Extract",
"font",
"information",
"from",
"a",
"font",
"string",
"such",
"as",
"supplied",
"to",
"the",
"font",
"argument",
"to",
"a",
"widget",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/PgHelp.py#L259-L277 |
26,378 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.get_points | def get_points(self):
"""Get the set of points that is used to draw the object.
Points are returned in *data* coordinates.
"""
if hasattr(self, 'points'):
points = self.crdmap.to_data(self.points)
else:
points = []
return points | python | def get_points(self):
if hasattr(self, 'points'):
points = self.crdmap.to_data(self.points)
else:
points = []
return points | [
"def",
"get_points",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'points'",
")",
":",
"points",
"=",
"self",
".",
"crdmap",
".",
"to_data",
"(",
"self",
".",
"points",
")",
"else",
":",
"points",
"=",
"[",
"]",
"return",
"points"
] | Get the set of points that is used to draw the object.
Points are returned in *data* coordinates. | [
"Get",
"the",
"set",
"of",
"points",
"that",
"is",
"used",
"to",
"draw",
"the",
"object",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L226-L235 |
26,379 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.get_data_points | def get_data_points(self, points=None):
"""Points returned are in data coordinates."""
if points is None:
points = self.points
points = self.crdmap.to_data(points)
return points | python | def get_data_points(self, points=None):
if points is None:
points = self.points
points = self.crdmap.to_data(points)
return points | [
"def",
"get_data_points",
"(",
"self",
",",
"points",
"=",
"None",
")",
":",
"if",
"points",
"is",
"None",
":",
"points",
"=",
"self",
".",
"points",
"points",
"=",
"self",
".",
"crdmap",
".",
"to_data",
"(",
"points",
")",
"return",
"points"
] | Points returned are in data coordinates. | [
"Points",
"returned",
"are",
"in",
"data",
"coordinates",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L237-L242 |
26,380 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.set_data_points | def set_data_points(self, points):
"""
Input `points` must be in data coordinates, will be converted
to the coordinate space of the object and stored.
"""
self.points = np.asarray(self.crdmap.data_to(points)) | python | def set_data_points(self, points):
self.points = np.asarray(self.crdmap.data_to(points)) | [
"def",
"set_data_points",
"(",
"self",
",",
"points",
")",
":",
"self",
".",
"points",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"crdmap",
".",
"data_to",
"(",
"points",
")",
")"
] | Input `points` must be in data coordinates, will be converted
to the coordinate space of the object and stored. | [
"Input",
"points",
"must",
"be",
"in",
"data",
"coordinates",
"will",
"be",
"converted",
"to",
"the",
"coordinate",
"space",
"of",
"the",
"object",
"and",
"stored",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L244-L249 |
26,381 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.convert_mapper | def convert_mapper(self, tomap):
"""
Converts our object from using one coordinate map to another.
NOTE: In some cases this only approximately preserves the
equivalent point values when transforming between coordinate
spaces.
"""
frommap = self.crdmap
if frommap == tomap:
return
# mild hack to convert radii on objects that have them
if hasattr(self, 'radius'):
# get coordinates of a point radius away from center
# under current coordmap
x0, y0 = frommap.offset_pt((self.x, self.y), (self.radius, 0))
pts = frommap.to_data(((self.x, self.y), (x0, y0)))
pts = tomap.data_to(pts)
self.radius = np.fabs(pts[1][0] - pts[0][0])
elif hasattr(self, 'xradius'):
# similar to above case, but there are 2 radii
x0, y0 = frommap.offset_pt((self.x, self.y), (self.xradius,
self.yradius))
pts = frommap.to_data(((self.x, self.y), (x0, y0)))
pts = tomap.data_to(pts)
self.xradius = np.fabs(pts[1][0] - pts[0][0])
self.yradius = np.fabs(pts[1][1] - pts[0][1])
data_pts = self.get_data_points()
# set our map to the new map
self.crdmap = tomap
self.set_data_points(data_pts) | python | def convert_mapper(self, tomap):
frommap = self.crdmap
if frommap == tomap:
return
# mild hack to convert radii on objects that have them
if hasattr(self, 'radius'):
# get coordinates of a point radius away from center
# under current coordmap
x0, y0 = frommap.offset_pt((self.x, self.y), (self.radius, 0))
pts = frommap.to_data(((self.x, self.y), (x0, y0)))
pts = tomap.data_to(pts)
self.radius = np.fabs(pts[1][0] - pts[0][0])
elif hasattr(self, 'xradius'):
# similar to above case, but there are 2 radii
x0, y0 = frommap.offset_pt((self.x, self.y), (self.xradius,
self.yradius))
pts = frommap.to_data(((self.x, self.y), (x0, y0)))
pts = tomap.data_to(pts)
self.xradius = np.fabs(pts[1][0] - pts[0][0])
self.yradius = np.fabs(pts[1][1] - pts[0][1])
data_pts = self.get_data_points()
# set our map to the new map
self.crdmap = tomap
self.set_data_points(data_pts) | [
"def",
"convert_mapper",
"(",
"self",
",",
"tomap",
")",
":",
"frommap",
"=",
"self",
".",
"crdmap",
"if",
"frommap",
"==",
"tomap",
":",
"return",
"# mild hack to convert radii on objects that have them",
"if",
"hasattr",
"(",
"self",
",",
"'radius'",
")",
":",... | Converts our object from using one coordinate map to another.
NOTE: In some cases this only approximately preserves the
equivalent point values when transforming between coordinate
spaces. | [
"Converts",
"our",
"object",
"from",
"using",
"one",
"coordinate",
"map",
"to",
"another",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L341-L376 |
26,382 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.point_within_radius | def point_within_radius(self, points, pt, canvas_radius,
scales=(1.0, 1.0)):
"""Points `points` and point `pt` are in data coordinates.
Return True for points within the circle defined by
a center at point `pt` and within canvas_radius.
"""
scale_x, scale_y = scales
x, y = pt
a_arr, b_arr = np.asarray(points).T
dx = np.fabs(x - a_arr) * scale_x
dy = np.fabs(y - b_arr) * scale_y
new_radius = np.sqrt(dx**2 + dy**2)
res = (new_radius <= canvas_radius)
return res | python | def point_within_radius(self, points, pt, canvas_radius,
scales=(1.0, 1.0)):
scale_x, scale_y = scales
x, y = pt
a_arr, b_arr = np.asarray(points).T
dx = np.fabs(x - a_arr) * scale_x
dy = np.fabs(y - b_arr) * scale_y
new_radius = np.sqrt(dx**2 + dy**2)
res = (new_radius <= canvas_radius)
return res | [
"def",
"point_within_radius",
"(",
"self",
",",
"points",
",",
"pt",
",",
"canvas_radius",
",",
"scales",
"=",
"(",
"1.0",
",",
"1.0",
")",
")",
":",
"scale_x",
",",
"scale_y",
"=",
"scales",
"x",
",",
"y",
"=",
"pt",
"a_arr",
",",
"b_arr",
"=",
"n... | Points `points` and point `pt` are in data coordinates.
Return True for points within the circle defined by
a center at point `pt` and within canvas_radius. | [
"Points",
"points",
"and",
"point",
"pt",
"are",
"in",
"data",
"coordinates",
".",
"Return",
"True",
"for",
"points",
"within",
"the",
"circle",
"defined",
"by",
"a",
"center",
"at",
"point",
"pt",
"and",
"within",
"canvas_radius",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L378-L391 |
26,383 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.within_radius | def within_radius(self, viewer, points, pt, canvas_radius):
"""Points `points` and point `pt` are in data coordinates.
Return True for points within the circle defined by
a center at point `pt` and within canvas_radius.
The distance between points is scaled by the canvas scale.
"""
scales = viewer.get_scale_xy()
return self.point_within_radius(points, pt, canvas_radius,
scales) | python | def within_radius(self, viewer, points, pt, canvas_radius):
scales = viewer.get_scale_xy()
return self.point_within_radius(points, pt, canvas_radius,
scales) | [
"def",
"within_radius",
"(",
"self",
",",
"viewer",
",",
"points",
",",
"pt",
",",
"canvas_radius",
")",
":",
"scales",
"=",
"viewer",
".",
"get_scale_xy",
"(",
")",
"return",
"self",
".",
"point_within_radius",
"(",
"points",
",",
"pt",
",",
"canvas_radiu... | Points `points` and point `pt` are in data coordinates.
Return True for points within the circle defined by
a center at point `pt` and within canvas_radius.
The distance between points is scaled by the canvas scale. | [
"Points",
"points",
"and",
"point",
"pt",
"are",
"in",
"data",
"coordinates",
".",
"Return",
"True",
"for",
"points",
"within",
"the",
"circle",
"defined",
"by",
"a",
"center",
"at",
"point",
"pt",
"and",
"within",
"canvas_radius",
".",
"The",
"distance",
... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L393-L401 |
26,384 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.get_pt | def get_pt(self, viewer, points, pt, canvas_radius=None):
"""Takes an array of points `points` and a target point `pt`.
Returns the first index of the point that is within the
radius of the target point. If none of the points are within
the radius, returns None.
"""
if canvas_radius is None:
canvas_radius = self.cap_radius
if hasattr(self, 'rot_deg'):
# rotate point back to cartesian alignment for test
ctr_pt = self.get_center_pt()
pt = trcalc.rotate_coord(pt, [-self.rot_deg], ctr_pt)
res = self.within_radius(viewer, points, pt, canvas_radius)
return np.flatnonzero(res) | python | def get_pt(self, viewer, points, pt, canvas_radius=None):
if canvas_radius is None:
canvas_radius = self.cap_radius
if hasattr(self, 'rot_deg'):
# rotate point back to cartesian alignment for test
ctr_pt = self.get_center_pt()
pt = trcalc.rotate_coord(pt, [-self.rot_deg], ctr_pt)
res = self.within_radius(viewer, points, pt, canvas_radius)
return np.flatnonzero(res) | [
"def",
"get_pt",
"(",
"self",
",",
"viewer",
",",
"points",
",",
"pt",
",",
"canvas_radius",
"=",
"None",
")",
":",
"if",
"canvas_radius",
"is",
"None",
":",
"canvas_radius",
"=",
"self",
".",
"cap_radius",
"if",
"hasattr",
"(",
"self",
",",
"'rot_deg'",... | Takes an array of points `points` and a target point `pt`.
Returns the first index of the point that is within the
radius of the target point. If none of the points are within
the radius, returns None. | [
"Takes",
"an",
"array",
"of",
"points",
"points",
"and",
"a",
"target",
"point",
"pt",
".",
"Returns",
"the",
"first",
"index",
"of",
"the",
"point",
"that",
"is",
"within",
"the",
"radius",
"of",
"the",
"target",
"point",
".",
"If",
"none",
"of",
"the... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L403-L418 |
26,385 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.within_line | def within_line(self, viewer, points, p_start, p_stop, canvas_radius):
"""Points `points` and line endpoints `p_start`, `p_stop` are in
data coordinates.
Return True for points within the line defined by a line from
p_start to p_end and within `canvas_radius`.
The distance between points is scaled by the viewer's canvas scale.
"""
scale_x, scale_y = viewer.get_scale_xy()
new_radius = canvas_radius * 1.0 / min(scale_x, scale_y)
return self.point_within_line(points, p_start, p_stop, new_radius) | python | def within_line(self, viewer, points, p_start, p_stop, canvas_radius):
scale_x, scale_y = viewer.get_scale_xy()
new_radius = canvas_radius * 1.0 / min(scale_x, scale_y)
return self.point_within_line(points, p_start, p_stop, new_radius) | [
"def",
"within_line",
"(",
"self",
",",
"viewer",
",",
"points",
",",
"p_start",
",",
"p_stop",
",",
"canvas_radius",
")",
":",
"scale_x",
",",
"scale_y",
"=",
"viewer",
".",
"get_scale_xy",
"(",
")",
"new_radius",
"=",
"canvas_radius",
"*",
"1.0",
"/",
... | Points `points` and line endpoints `p_start`, `p_stop` are in
data coordinates.
Return True for points within the line defined by a line from
p_start to p_end and within `canvas_radius`.
The distance between points is scaled by the viewer's canvas scale. | [
"Points",
"points",
"and",
"line",
"endpoints",
"p_start",
"p_stop",
"are",
"in",
"data",
"coordinates",
".",
"Return",
"True",
"for",
"points",
"within",
"the",
"line",
"defined",
"by",
"a",
"line",
"from",
"p_start",
"to",
"p_end",
"and",
"within",
"canvas... | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L439-L449 |
26,386 | ejeschke/ginga | ginga/canvas/CanvasObject.py | CanvasObjectBase.get_bbox | def get_bbox(self, points=None):
"""
Get bounding box of this object.
Returns
-------
(p1, p2, p3, p4): a 4-tuple of the points in data coordinates,
beginning with the lower-left and proceeding counter-clockwise.
"""
if points is None:
x1, y1, x2, y2 = self.get_llur()
return ((x1, y1), (x1, y2), (x2, y2), (x2, y1))
else:
return trcalc.strip_z(trcalc.get_bounds(points)) | python | def get_bbox(self, points=None):
if points is None:
x1, y1, x2, y2 = self.get_llur()
return ((x1, y1), (x1, y2), (x2, y2), (x2, y1))
else:
return trcalc.strip_z(trcalc.get_bounds(points)) | [
"def",
"get_bbox",
"(",
"self",
",",
"points",
"=",
"None",
")",
":",
"if",
"points",
"is",
"None",
":",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"self",
".",
"get_llur",
"(",
")",
"return",
"(",
"(",
"x1",
",",
"y1",
")",
",",
"(",
"x1",
... | Get bounding box of this object.
Returns
-------
(p1, p2, p3, p4): a 4-tuple of the points in data coordinates,
beginning with the lower-left and proceeding counter-clockwise. | [
"Get",
"bounding",
"box",
"of",
"this",
"object",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/CanvasObject.py#L503-L516 |
26,387 | ejeschke/ginga | ginga/misc/Timer.py | TimerFactory.set | def set(self, time_sec, callback_fn, *args, **kwdargs):
"""Convenience function to create and set a timer.
Equivalent to:
timer = timer_factory.timer()
timer.set_callback('expired', callback_fn, *args, **kwdargs)
timer.set(time_sec)
"""
timer = self.timer()
timer.set_callback('expired', callback_fn, *args, **kwdargs)
timer.set(time_sec)
return timer | python | def set(self, time_sec, callback_fn, *args, **kwdargs):
timer = self.timer()
timer.set_callback('expired', callback_fn, *args, **kwdargs)
timer.set(time_sec)
return timer | [
"def",
"set",
"(",
"self",
",",
"time_sec",
",",
"callback_fn",
",",
"*",
"args",
",",
"*",
"*",
"kwdargs",
")",
":",
"timer",
"=",
"self",
".",
"timer",
"(",
")",
"timer",
".",
"set_callback",
"(",
"'expired'",
",",
"callback_fn",
",",
"*",
"args",
... | Convenience function to create and set a timer.
Equivalent to:
timer = timer_factory.timer()
timer.set_callback('expired', callback_fn, *args, **kwdargs)
timer.set(time_sec) | [
"Convenience",
"function",
"to",
"create",
"and",
"set",
"a",
"timer",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Timer.py#L29-L40 |
26,388 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_window_size | def set_window_size(self, width, height):
"""Report the size of the window to display the image.
**Callbacks**
Will call any callbacks registered for the ``'configure'`` event.
Callbacks should have a method signature of::
(viewer, width, height, ...)
.. note::
This is called by the subclass with ``width`` and ``height``
as soon as the actual dimensions of the allocated window are known.
Parameters
----------
width : int
The width of the window in pixels.
height : int
The height of the window in pixels.
"""
self._imgwin_wd = int(width)
self._imgwin_ht = int(height)
self._ctr_x = width // 2
self._ctr_y = height // 2
self.logger.debug("widget resized to %dx%d" % (width, height))
self.make_callback('configure', width, height)
self.redraw(whence=0) | python | def set_window_size(self, width, height):
self._imgwin_wd = int(width)
self._imgwin_ht = int(height)
self._ctr_x = width // 2
self._ctr_y = height // 2
self.logger.debug("widget resized to %dx%d" % (width, height))
self.make_callback('configure', width, height)
self.redraw(whence=0) | [
"def",
"set_window_size",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"self",
".",
"_imgwin_wd",
"=",
"int",
"(",
"width",
")",
"self",
".",
"_imgwin_ht",
"=",
"int",
"(",
"height",
")",
"self",
".",
"_ctr_x",
"=",
"width",
"//",
"2",
"self",... | Report the size of the window to display the image.
**Callbacks**
Will call any callbacks registered for the ``'configure'`` event.
Callbacks should have a method signature of::
(viewer, width, height, ...)
.. note::
This is called by the subclass with ``width`` and ``height``
as soon as the actual dimensions of the allocated window are known.
Parameters
----------
width : int
The width of the window in pixels.
height : int
The height of the window in pixels. | [
"Report",
"the",
"size",
"of",
"the",
"window",
"to",
"display",
"the",
"image",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L353-L384 |
26,389 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_renderer | def set_renderer(self, renderer):
"""Set and initialize the renderer used by this instance.
"""
self.renderer = renderer
width, height = self.get_window_size()
if width > 0 and height > 0:
renderer.resize((width, height)) | python | def set_renderer(self, renderer):
self.renderer = renderer
width, height = self.get_window_size()
if width > 0 and height > 0:
renderer.resize((width, height)) | [
"def",
"set_renderer",
"(",
"self",
",",
"renderer",
")",
":",
"self",
".",
"renderer",
"=",
"renderer",
"width",
",",
"height",
"=",
"self",
".",
"get_window_size",
"(",
")",
"if",
"width",
">",
"0",
"and",
"height",
">",
"0",
":",
"renderer",
".",
... | Set and initialize the renderer used by this instance. | [
"Set",
"and",
"initialize",
"the",
"renderer",
"used",
"by",
"this",
"instance",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L470-L476 |
26,390 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_canvas | def set_canvas(self, canvas, private_canvas=None):
"""Set the canvas object.
Parameters
----------
canvas : `~ginga.canvas.types.layer.DrawingCanvas`
Canvas object.
private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None`
Private canvas object. If not given, this is the same as ``canvas``.
"""
self.canvas = canvas
canvas.initialize(None, self, self.logger)
canvas.add_callback('modified', self.canvas_changed_cb)
canvas.set_surface(self)
canvas.ui_set_active(True)
self._imgobj = None
# private canvas set?
if private_canvas is not None:
self.private_canvas = private_canvas
if private_canvas != canvas:
private_canvas.set_surface(self)
private_canvas.ui_set_active(True)
private_canvas.add_callback('modified', self.canvas_changed_cb)
# sanity check that we have a private canvas, and if not,
# set it to the "advertised" canvas
if self.private_canvas is None:
self.private_canvas = canvas
# make sure private canvas has our non-private one added
if (self.private_canvas != self.canvas) and (
not self.private_canvas.has_object(canvas)):
self.private_canvas.add(canvas)
self.initialize_private_canvas(self.private_canvas) | python | def set_canvas(self, canvas, private_canvas=None):
self.canvas = canvas
canvas.initialize(None, self, self.logger)
canvas.add_callback('modified', self.canvas_changed_cb)
canvas.set_surface(self)
canvas.ui_set_active(True)
self._imgobj = None
# private canvas set?
if private_canvas is not None:
self.private_canvas = private_canvas
if private_canvas != canvas:
private_canvas.set_surface(self)
private_canvas.ui_set_active(True)
private_canvas.add_callback('modified', self.canvas_changed_cb)
# sanity check that we have a private canvas, and if not,
# set it to the "advertised" canvas
if self.private_canvas is None:
self.private_canvas = canvas
# make sure private canvas has our non-private one added
if (self.private_canvas != self.canvas) and (
not self.private_canvas.has_object(canvas)):
self.private_canvas.add(canvas)
self.initialize_private_canvas(self.private_canvas) | [
"def",
"set_canvas",
"(",
"self",
",",
"canvas",
",",
"private_canvas",
"=",
"None",
")",
":",
"self",
".",
"canvas",
"=",
"canvas",
"canvas",
".",
"initialize",
"(",
"None",
",",
"self",
",",
"self",
".",
"logger",
")",
"canvas",
".",
"add_callback",
... | Set the canvas object.
Parameters
----------
canvas : `~ginga.canvas.types.layer.DrawingCanvas`
Canvas object.
private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None`
Private canvas object. If not given, this is the same as ``canvas``. | [
"Set",
"the",
"canvas",
"object",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L489-L528 |
26,391 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.initialize_private_canvas | def initialize_private_canvas(self, private_canvas):
"""Initialize the private canvas used by this instance.
"""
if self.t_.get('show_pan_position', False):
self.show_pan_mark(True)
if self.t_.get('show_focus_indicator', False):
self.show_focus_indicator(True) | python | def initialize_private_canvas(self, private_canvas):
if self.t_.get('show_pan_position', False):
self.show_pan_mark(True)
if self.t_.get('show_focus_indicator', False):
self.show_focus_indicator(True) | [
"def",
"initialize_private_canvas",
"(",
"self",
",",
"private_canvas",
")",
":",
"if",
"self",
".",
"t_",
".",
"get",
"(",
"'show_pan_position'",
",",
"False",
")",
":",
"self",
".",
"show_pan_mark",
"(",
"True",
")",
"if",
"self",
".",
"t_",
".",
"get"... | Initialize the private canvas used by this instance. | [
"Initialize",
"the",
"private",
"canvas",
"used",
"by",
"this",
"instance",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L541-L548 |
26,392 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_rgbmap | def set_rgbmap(self, rgbmap):
"""Set RGB map object used by this instance.
It controls how the values in the image are mapped to color.
Parameters
----------
rgbmap : `~ginga.RGBMap.RGBMapper`
RGB map.
"""
self.rgbmap = rgbmap
t_ = rgbmap.get_settings()
t_.share_settings(self.t_, keylist=rgbmap.settings_keys)
rgbmap.add_callback('changed', self.rgbmap_cb)
self.redraw(whence=2) | python | def set_rgbmap(self, rgbmap):
self.rgbmap = rgbmap
t_ = rgbmap.get_settings()
t_.share_settings(self.t_, keylist=rgbmap.settings_keys)
rgbmap.add_callback('changed', self.rgbmap_cb)
self.redraw(whence=2) | [
"def",
"set_rgbmap",
"(",
"self",
",",
"rgbmap",
")",
":",
"self",
".",
"rgbmap",
"=",
"rgbmap",
"t_",
"=",
"rgbmap",
".",
"get_settings",
"(",
")",
"t_",
".",
"share_settings",
"(",
"self",
".",
"t_",
",",
"keylist",
"=",
"rgbmap",
".",
"settings_keys... | Set RGB map object used by this instance.
It controls how the values in the image are mapped to color.
Parameters
----------
rgbmap : `~ginga.RGBMap.RGBMapper`
RGB map. | [
"Set",
"RGB",
"map",
"object",
"used",
"by",
"this",
"instance",
".",
"It",
"controls",
"how",
"the",
"values",
"in",
"the",
"image",
"are",
"mapped",
"to",
"color",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L684-L698 |
26,393 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.get_image | def get_image(self):
"""Get the image currently being displayed.
Returns
-------
image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage`
Image object.
"""
if self._imgobj is not None:
# quick optomization
return self._imgobj.get_image()
canvas_img = self.get_canvas_image()
return canvas_img.get_image() | python | def get_image(self):
if self._imgobj is not None:
# quick optomization
return self._imgobj.get_image()
canvas_img = self.get_canvas_image()
return canvas_img.get_image() | [
"def",
"get_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_imgobj",
"is",
"not",
"None",
":",
"# quick optomization",
"return",
"self",
".",
"_imgobj",
".",
"get_image",
"(",
")",
"canvas_img",
"=",
"self",
".",
"get_canvas_image",
"(",
")",
"return",... | Get the image currently being displayed.
Returns
-------
image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage`
Image object. | [
"Get",
"the",
"image",
"currently",
"being",
"displayed",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L700-L714 |
26,394 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.get_canvas_image | def get_canvas_image(self):
"""Get canvas image object.
Returns
-------
imgobj : `~ginga.canvas.types.image.NormImage`
Normalized image sitting on the canvas.
"""
if self._imgobj is not None:
return self._imgobj
try:
# See if there is an image on the canvas
self._imgobj = self.canvas.get_object_by_tag(self._canvas_img_tag)
self._imgobj.add_callback('image-set', self._image_set_cb)
except KeyError:
# add a normalized image item to this canvas if we don't
# have one already--then just keep reusing it
NormImage = self.canvas.getDrawClass('normimage')
interp = self.t_.get('interpolation', 'basic')
# previous choice might not be available if preferences
# were saved when opencv was being used (and not used now)
# --if so, default to "basic"
if interp not in trcalc.interpolation_methods:
interp = 'basic'
self._imgobj = NormImage(0, 0, None, alpha=1.0,
interpolation=interp)
self._imgobj.add_callback('image-set', self._image_set_cb)
return self._imgobj | python | def get_canvas_image(self):
if self._imgobj is not None:
return self._imgobj
try:
# See if there is an image on the canvas
self._imgobj = self.canvas.get_object_by_tag(self._canvas_img_tag)
self._imgobj.add_callback('image-set', self._image_set_cb)
except KeyError:
# add a normalized image item to this canvas if we don't
# have one already--then just keep reusing it
NormImage = self.canvas.getDrawClass('normimage')
interp = self.t_.get('interpolation', 'basic')
# previous choice might not be available if preferences
# were saved when opencv was being used (and not used now)
# --if so, default to "basic"
if interp not in trcalc.interpolation_methods:
interp = 'basic'
self._imgobj = NormImage(0, 0, None, alpha=1.0,
interpolation=interp)
self._imgobj.add_callback('image-set', self._image_set_cb)
return self._imgobj | [
"def",
"get_canvas_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_imgobj",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_imgobj",
"try",
":",
"# See if there is an image on the canvas",
"self",
".",
"_imgobj",
"=",
"self",
".",
"canvas",
".",
"get_... | Get canvas image object.
Returns
-------
imgobj : `~ginga.canvas.types.image.NormImage`
Normalized image sitting on the canvas. | [
"Get",
"canvas",
"image",
"object",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L716-L749 |
26,395 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_image | def set_image(self, image, add_to_canvas=True):
"""Set an image to be displayed.
If there is no error, the ``'image-unset'`` and ``'image-set'``
callbacks will be invoked.
Parameters
----------
image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage`
Image object.
add_to_canvas : bool
Add image to canvas.
"""
if not isinstance(image, BaseImage.BaseImage):
raise ValueError("Wrong type of object to load: %s" % (
str(type(image))))
canvas_img = self.get_canvas_image()
old_image = canvas_img.get_image()
self.make_callback('image-unset', old_image)
with self.suppress_redraw:
# this line should force the callback of _image_set_cb()
canvas_img.set_image(image)
if add_to_canvas:
try:
self.canvas.get_object_by_tag(self._canvas_img_tag)
except KeyError:
self.canvas.add(canvas_img, tag=self._canvas_img_tag)
#self.logger.debug("adding image to canvas %s" % self.canvas)
# move image to bottom of layers
self.canvas.lower_object(canvas_img) | python | def set_image(self, image, add_to_canvas=True):
if not isinstance(image, BaseImage.BaseImage):
raise ValueError("Wrong type of object to load: %s" % (
str(type(image))))
canvas_img = self.get_canvas_image()
old_image = canvas_img.get_image()
self.make_callback('image-unset', old_image)
with self.suppress_redraw:
# this line should force the callback of _image_set_cb()
canvas_img.set_image(image)
if add_to_canvas:
try:
self.canvas.get_object_by_tag(self._canvas_img_tag)
except KeyError:
self.canvas.add(canvas_img, tag=self._canvas_img_tag)
#self.logger.debug("adding image to canvas %s" % self.canvas)
# move image to bottom of layers
self.canvas.lower_object(canvas_img) | [
"def",
"set_image",
"(",
"self",
",",
"image",
",",
"add_to_canvas",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"BaseImage",
".",
"BaseImage",
")",
":",
"raise",
"ValueError",
"(",
"\"Wrong type of object to load: %s\"",
"%",
"(",
"... | Set an image to be displayed.
If there is no error, the ``'image-unset'`` and ``'image-set'``
callbacks will be invoked.
Parameters
----------
image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage`
Image object.
add_to_canvas : bool
Add image to canvas. | [
"Set",
"an",
"image",
"to",
"be",
"displayed",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L751-L789 |
26,396 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.save_profile | def save_profile(self, **params):
"""Save the given parameters into profile settings.
Parameters
----------
params : dict
Keywords and values to be saved.
"""
image = self.get_image()
if (image is None):
return
profile = image.get('profile', None)
if profile is None:
# If image has no profile then create one
profile = Settings.SettingGroup()
image.set(profile=profile)
self.logger.debug("saving to image profile: params=%s" % (
str(params)))
profile.set(**params)
return profile | python | def save_profile(self, **params):
image = self.get_image()
if (image is None):
return
profile = image.get('profile', None)
if profile is None:
# If image has no profile then create one
profile = Settings.SettingGroup()
image.set(profile=profile)
self.logger.debug("saving to image profile: params=%s" % (
str(params)))
profile.set(**params)
return profile | [
"def",
"save_profile",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"image",
"=",
"self",
".",
"get_image",
"(",
")",
"if",
"(",
"image",
"is",
"None",
")",
":",
"return",
"profile",
"=",
"image",
".",
"get",
"(",
"'profile'",
",",
"None",
")",
... | Save the given parameters into profile settings.
Parameters
----------
params : dict
Keywords and values to be saved. | [
"Save",
"the",
"given",
"parameters",
"into",
"profile",
"settings",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L909-L931 |
26,397 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.set_data | def set_data(self, data, metadata=None):
"""Set an image to be displayed by providing raw data.
This is a convenience method for first constructing an image
with `~ginga.AstroImage.AstroImage` and then calling :meth:`set_image`.
Parameters
----------
data : ndarray
This should be at least a 2D Numpy array.
metadata : dict or `None`
Image metadata mapping keywords to their respective values.
"""
image = AstroImage.AstroImage(data, metadata=metadata,
logger=self.logger)
self.set_image(image) | python | def set_data(self, data, metadata=None):
image = AstroImage.AstroImage(data, metadata=metadata,
logger=self.logger)
self.set_image(image) | [
"def",
"set_data",
"(",
"self",
",",
"data",
",",
"metadata",
"=",
"None",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"data",
",",
"metadata",
"=",
"metadata",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"set_image",... | Set an image to be displayed by providing raw data.
This is a convenience method for first constructing an image
with `~ginga.AstroImage.AstroImage` and then calling :meth:`set_image`.
Parameters
----------
data : ndarray
This should be at least a 2D Numpy array.
metadata : dict or `None`
Image metadata mapping keywords to their respective values. | [
"Set",
"an",
"image",
"to",
"be",
"displayed",
"by",
"providing",
"raw",
"data",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L984-L1001 |
26,398 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.clear | def clear(self):
"""Clear the displayed image."""
self._imgobj = None
try:
# See if there is an image on the canvas
self.canvas.delete_object_by_tag(self._canvas_img_tag)
self.redraw()
except KeyError:
pass | python | def clear(self):
self._imgobj = None
try:
# See if there is an image on the canvas
self.canvas.delete_object_by_tag(self._canvas_img_tag)
self.redraw()
except KeyError:
pass | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_imgobj",
"=",
"None",
"try",
":",
"# See if there is an image on the canvas",
"self",
".",
"canvas",
".",
"delete_object_by_tag",
"(",
"self",
".",
"_canvas_img_tag",
")",
"self",
".",
"redraw",
"(",
")",
... | Clear the displayed image. | [
"Clear",
"the",
"displayed",
"image",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1003-L1011 |
26,399 | ejeschke/ginga | ginga/ImageView.py | ImageViewBase.redraw | def redraw(self, whence=0):
"""Redraw the canvas.
Parameters
----------
whence
See :meth:`get_rgb_object`.
"""
with self._defer_lock:
whence = min(self._defer_whence, whence)
if not self.defer_redraw:
if self._hold_redraw_cnt == 0:
self._defer_whence = self._defer_whence_reset
self.redraw_now(whence=whence)
else:
self._defer_whence = whence
return
elapsed = time.time() - self.time_last_redraw
# If there is no redraw scheduled, or we are overdue for one:
if (not self._defer_flag) or (elapsed > self.defer_lagtime):
# If more time than defer_lagtime has passed since the
# last redraw then just do the redraw immediately
if elapsed > self.defer_lagtime:
if self._hold_redraw_cnt > 0:
#self._defer_flag = True
self._defer_whence = whence
return
self._defer_whence = self._defer_whence_reset
self.logger.debug("lagtime expired--forced redraw")
self.redraw_now(whence=whence)
return
# Indicate that a redraw is necessary and record whence
self._defer_flag = True
self._defer_whence = whence
# schedule a redraw by the end of the defer_lagtime
secs = self.defer_lagtime - elapsed
self.logger.debug("defer redraw (whence=%.2f) in %.f sec" % (
whence, secs))
self.reschedule_redraw(secs)
else:
# A redraw is already scheduled. Just record whence.
self._defer_whence = whence
self.logger.debug("update whence=%.2f" % (whence)) | python | def redraw(self, whence=0):
with self._defer_lock:
whence = min(self._defer_whence, whence)
if not self.defer_redraw:
if self._hold_redraw_cnt == 0:
self._defer_whence = self._defer_whence_reset
self.redraw_now(whence=whence)
else:
self._defer_whence = whence
return
elapsed = time.time() - self.time_last_redraw
# If there is no redraw scheduled, or we are overdue for one:
if (not self._defer_flag) or (elapsed > self.defer_lagtime):
# If more time than defer_lagtime has passed since the
# last redraw then just do the redraw immediately
if elapsed > self.defer_lagtime:
if self._hold_redraw_cnt > 0:
#self._defer_flag = True
self._defer_whence = whence
return
self._defer_whence = self._defer_whence_reset
self.logger.debug("lagtime expired--forced redraw")
self.redraw_now(whence=whence)
return
# Indicate that a redraw is necessary and record whence
self._defer_flag = True
self._defer_whence = whence
# schedule a redraw by the end of the defer_lagtime
secs = self.defer_lagtime - elapsed
self.logger.debug("defer redraw (whence=%.2f) in %.f sec" % (
whence, secs))
self.reschedule_redraw(secs)
else:
# A redraw is already scheduled. Just record whence.
self._defer_whence = whence
self.logger.debug("update whence=%.2f" % (whence)) | [
"def",
"redraw",
"(",
"self",
",",
"whence",
"=",
"0",
")",
":",
"with",
"self",
".",
"_defer_lock",
":",
"whence",
"=",
"min",
"(",
"self",
".",
"_defer_whence",
",",
"whence",
")",
"if",
"not",
"self",
".",
"defer_redraw",
":",
"if",
"self",
".",
... | Redraw the canvas.
Parameters
----------
whence
See :meth:`get_rgb_object`. | [
"Redraw",
"the",
"canvas",
"."
] | a78c893ec6f37a837de851947e9bb4625c597915 | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1025-L1075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.