repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
|
BaseCamera.view_changed
|
def view_changed(self):
""" Called when this camera is changes its view. Also called
when its associated with a viewbox.
"""
if self._resetting:
return # don't update anything while resetting (are in set_range)
if self._viewbox:
# Set range if necessary
if self._xlim is None:
args = self._set_range_args or ()
self.set_range(*args)
# Store default state if we have not set it yet
if self._default_state is None:
self.set_default_state()
# Do the actual update
self._update_transform()
|
python
|
def view_changed(self):
""" Called when this camera is changes its view. Also called
when its associated with a viewbox.
"""
if self._resetting:
return # don't update anything while resetting (are in set_range)
if self._viewbox:
# Set range if necessary
if self._xlim is None:
args = self._set_range_args or ()
self.set_range(*args)
# Store default state if we have not set it yet
if self._default_state is None:
self.set_default_state()
# Do the actual update
self._update_transform()
|
[
"def",
"view_changed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resetting",
":",
"return",
"# don't update anything while resetting (are in set_range)",
"if",
"self",
".",
"_viewbox",
":",
"# Set range if necessary",
"if",
"self",
".",
"_xlim",
"is",
"None",
":",
"args",
"=",
"self",
".",
"_set_range_args",
"or",
"(",
")",
"self",
".",
"set_range",
"(",
"*",
"args",
")",
"# Store default state if we have not set it yet",
"if",
"self",
".",
"_default_state",
"is",
"None",
":",
"self",
".",
"set_default_state",
"(",
")",
"# Do the actual update",
"self",
".",
"_update_transform",
"(",
")"
] |
Called when this camera is changes its view. Also called
when its associated with a viewbox.
|
[
"Called",
"when",
"this",
"camera",
"is",
"changes",
"its",
"view",
".",
"Also",
"called",
"when",
"its",
"associated",
"with",
"a",
"viewbox",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L365-L380
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
|
BaseCamera.on_canvas_change
|
def on_canvas_change(self, event):
"""Canvas change event handler
Parameters
----------
event : instance of Event
The event.
"""
# Connect key events from canvas to camera.
# TODO: canvas should keep track of a single node with keyboard focus.
if event.old is not None:
event.old.events.key_press.disconnect(self.viewbox_key_event)
event.old.events.key_release.disconnect(self.viewbox_key_event)
if event.new is not None:
event.new.events.key_press.connect(self.viewbox_key_event)
event.new.events.key_release.connect(self.viewbox_key_event)
|
python
|
def on_canvas_change(self, event):
"""Canvas change event handler
Parameters
----------
event : instance of Event
The event.
"""
# Connect key events from canvas to camera.
# TODO: canvas should keep track of a single node with keyboard focus.
if event.old is not None:
event.old.events.key_press.disconnect(self.viewbox_key_event)
event.old.events.key_release.disconnect(self.viewbox_key_event)
if event.new is not None:
event.new.events.key_press.connect(self.viewbox_key_event)
event.new.events.key_release.connect(self.viewbox_key_event)
|
[
"def",
"on_canvas_change",
"(",
"self",
",",
"event",
")",
":",
"# Connect key events from canvas to camera. ",
"# TODO: canvas should keep track of a single node with keyboard focus.",
"if",
"event",
".",
"old",
"is",
"not",
"None",
":",
"event",
".",
"old",
".",
"events",
".",
"key_press",
".",
"disconnect",
"(",
"self",
".",
"viewbox_key_event",
")",
"event",
".",
"old",
".",
"events",
".",
"key_release",
".",
"disconnect",
"(",
"self",
".",
"viewbox_key_event",
")",
"if",
"event",
".",
"new",
"is",
"not",
"None",
":",
"event",
".",
"new",
".",
"events",
".",
"key_press",
".",
"connect",
"(",
"self",
".",
"viewbox_key_event",
")",
"event",
".",
"new",
".",
"events",
".",
"key_release",
".",
"connect",
"(",
"self",
".",
"viewbox_key_event",
")"
] |
Canvas change event handler
Parameters
----------
event : instance of Event
The event.
|
[
"Canvas",
"change",
"event",
"handler"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L404-L419
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
|
BaseCamera._set_scene_transform
|
def _set_scene_transform(self, tr):
""" Called by subclasses to configure the viewbox scene transform.
"""
# todo: check whether transform has changed, connect to
# transform.changed event
pre_tr = self.pre_transform
if pre_tr is None:
self._scene_transform = tr
else:
self._transform_cache.roll()
self._scene_transform = self._transform_cache.get([pre_tr, tr])
# Mark the transform dynamic so that it will not be collapsed with
# others
self._scene_transform.dynamic = True
# Update scene
self._viewbox.scene.transform = self._scene_transform
self._viewbox.update()
# Apply same state to linked cameras, but prevent that camera
# to return the favor
for cam in self._linked_cameras:
if cam is self._linked_cameras_no_update:
continue
try:
cam._linked_cameras_no_update = self
cam.set_state(self.get_state())
finally:
cam._linked_cameras_no_update = None
|
python
|
def _set_scene_transform(self, tr):
""" Called by subclasses to configure the viewbox scene transform.
"""
# todo: check whether transform has changed, connect to
# transform.changed event
pre_tr = self.pre_transform
if pre_tr is None:
self._scene_transform = tr
else:
self._transform_cache.roll()
self._scene_transform = self._transform_cache.get([pre_tr, tr])
# Mark the transform dynamic so that it will not be collapsed with
# others
self._scene_transform.dynamic = True
# Update scene
self._viewbox.scene.transform = self._scene_transform
self._viewbox.update()
# Apply same state to linked cameras, but prevent that camera
# to return the favor
for cam in self._linked_cameras:
if cam is self._linked_cameras_no_update:
continue
try:
cam._linked_cameras_no_update = self
cam.set_state(self.get_state())
finally:
cam._linked_cameras_no_update = None
|
[
"def",
"_set_scene_transform",
"(",
"self",
",",
"tr",
")",
":",
"# todo: check whether transform has changed, connect to",
"# transform.changed event",
"pre_tr",
"=",
"self",
".",
"pre_transform",
"if",
"pre_tr",
"is",
"None",
":",
"self",
".",
"_scene_transform",
"=",
"tr",
"else",
":",
"self",
".",
"_transform_cache",
".",
"roll",
"(",
")",
"self",
".",
"_scene_transform",
"=",
"self",
".",
"_transform_cache",
".",
"get",
"(",
"[",
"pre_tr",
",",
"tr",
"]",
")",
"# Mark the transform dynamic so that it will not be collapsed with",
"# others ",
"self",
".",
"_scene_transform",
".",
"dynamic",
"=",
"True",
"# Update scene",
"self",
".",
"_viewbox",
".",
"scene",
".",
"transform",
"=",
"self",
".",
"_scene_transform",
"self",
".",
"_viewbox",
".",
"update",
"(",
")",
"# Apply same state to linked cameras, but prevent that camera",
"# to return the favor",
"for",
"cam",
"in",
"self",
".",
"_linked_cameras",
":",
"if",
"cam",
"is",
"self",
".",
"_linked_cameras_no_update",
":",
"continue",
"try",
":",
"cam",
".",
"_linked_cameras_no_update",
"=",
"self",
"cam",
".",
"set_state",
"(",
"self",
".",
"get_state",
"(",
")",
")",
"finally",
":",
"cam",
".",
"_linked_cameras_no_update",
"=",
"None"
] |
Called by subclasses to configure the viewbox scene transform.
|
[
"Called",
"by",
"subclasses",
"to",
"configure",
"the",
"viewbox",
"scene",
"transform",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L448-L477
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/app/backends/_qt.py
|
_set_config
|
def _set_config(c):
"""Set the OpenGL configuration"""
glformat = QGLFormat()
glformat.setRedBufferSize(c['red_size'])
glformat.setGreenBufferSize(c['green_size'])
glformat.setBlueBufferSize(c['blue_size'])
glformat.setAlphaBufferSize(c['alpha_size'])
if QT5_NEW_API:
# Qt5 >= 5.4.0 - below options automatically enabled if nonzero.
glformat.setSwapBehavior(glformat.DoubleBuffer if c['double_buffer']
else glformat.SingleBuffer)
else:
# Qt4 and Qt5 < 5.4.0 - buffers must be explicitly requested.
glformat.setAccum(False)
glformat.setRgba(True)
glformat.setDoubleBuffer(True if c['double_buffer'] else False)
glformat.setDepth(True if c['depth_size'] else False)
glformat.setStencil(True if c['stencil_size'] else False)
glformat.setSampleBuffers(True if c['samples'] else False)
glformat.setDepthBufferSize(c['depth_size'] if c['depth_size'] else 0)
glformat.setStencilBufferSize(c['stencil_size'] if c['stencil_size']
else 0)
glformat.setSamples(c['samples'] if c['samples'] else 0)
glformat.setStereo(c['stereo'])
return glformat
|
python
|
def _set_config(c):
"""Set the OpenGL configuration"""
glformat = QGLFormat()
glformat.setRedBufferSize(c['red_size'])
glformat.setGreenBufferSize(c['green_size'])
glformat.setBlueBufferSize(c['blue_size'])
glformat.setAlphaBufferSize(c['alpha_size'])
if QT5_NEW_API:
# Qt5 >= 5.4.0 - below options automatically enabled if nonzero.
glformat.setSwapBehavior(glformat.DoubleBuffer if c['double_buffer']
else glformat.SingleBuffer)
else:
# Qt4 and Qt5 < 5.4.0 - buffers must be explicitly requested.
glformat.setAccum(False)
glformat.setRgba(True)
glformat.setDoubleBuffer(True if c['double_buffer'] else False)
glformat.setDepth(True if c['depth_size'] else False)
glformat.setStencil(True if c['stencil_size'] else False)
glformat.setSampleBuffers(True if c['samples'] else False)
glformat.setDepthBufferSize(c['depth_size'] if c['depth_size'] else 0)
glformat.setStencilBufferSize(c['stencil_size'] if c['stencil_size']
else 0)
glformat.setSamples(c['samples'] if c['samples'] else 0)
glformat.setStereo(c['stereo'])
return glformat
|
[
"def",
"_set_config",
"(",
"c",
")",
":",
"glformat",
"=",
"QGLFormat",
"(",
")",
"glformat",
".",
"setRedBufferSize",
"(",
"c",
"[",
"'red_size'",
"]",
")",
"glformat",
".",
"setGreenBufferSize",
"(",
"c",
"[",
"'green_size'",
"]",
")",
"glformat",
".",
"setBlueBufferSize",
"(",
"c",
"[",
"'blue_size'",
"]",
")",
"glformat",
".",
"setAlphaBufferSize",
"(",
"c",
"[",
"'alpha_size'",
"]",
")",
"if",
"QT5_NEW_API",
":",
"# Qt5 >= 5.4.0 - below options automatically enabled if nonzero.",
"glformat",
".",
"setSwapBehavior",
"(",
"glformat",
".",
"DoubleBuffer",
"if",
"c",
"[",
"'double_buffer'",
"]",
"else",
"glformat",
".",
"SingleBuffer",
")",
"else",
":",
"# Qt4 and Qt5 < 5.4.0 - buffers must be explicitly requested.",
"glformat",
".",
"setAccum",
"(",
"False",
")",
"glformat",
".",
"setRgba",
"(",
"True",
")",
"glformat",
".",
"setDoubleBuffer",
"(",
"True",
"if",
"c",
"[",
"'double_buffer'",
"]",
"else",
"False",
")",
"glformat",
".",
"setDepth",
"(",
"True",
"if",
"c",
"[",
"'depth_size'",
"]",
"else",
"False",
")",
"glformat",
".",
"setStencil",
"(",
"True",
"if",
"c",
"[",
"'stencil_size'",
"]",
"else",
"False",
")",
"glformat",
".",
"setSampleBuffers",
"(",
"True",
"if",
"c",
"[",
"'samples'",
"]",
"else",
"False",
")",
"glformat",
".",
"setDepthBufferSize",
"(",
"c",
"[",
"'depth_size'",
"]",
"if",
"c",
"[",
"'depth_size'",
"]",
"else",
"0",
")",
"glformat",
".",
"setStencilBufferSize",
"(",
"c",
"[",
"'stencil_size'",
"]",
"if",
"c",
"[",
"'stencil_size'",
"]",
"else",
"0",
")",
"glformat",
".",
"setSamples",
"(",
"c",
"[",
"'samples'",
"]",
"if",
"c",
"[",
"'samples'",
"]",
"else",
"0",
")",
"glformat",
".",
"setStereo",
"(",
"c",
"[",
"'stereo'",
"]",
")",
"return",
"glformat"
] |
Set the OpenGL configuration
|
[
"Set",
"the",
"OpenGL",
"configuration"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/backends/_qt.py#L195-L219
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/app/backends/_qt.py
|
CanvasBackendEgl.get_window_id
|
def get_window_id(self):
""" Get the window id of a PySide Widget. Might also work for PyQt4.
"""
# Get Qt win id
winid = self.winId()
# On Linux this is it
if IS_RPI:
nw = (ctypes.c_int * 3)(winid, self.width(), self.height())
return ctypes.pointer(nw)
elif IS_LINUX:
return int(winid) # Is int on PySide, but sip.voidptr on PyQt
# Get window id from stupid capsule thingy
# http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://www.cnb
#logs.com/Shiren-Y/archive/2011/04/06/2007288.html&prev=/search%3Fq%3Dp
# yside%2Bdirectx%26client%3Dfirefox-a%26hs%3DIsJ%26rls%3Dorg.mozilla:n
#l:official%26channel%3Dfflb%26biw%3D1366%26bih%3D614
# Prepare
ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object,
ctypes.c_char_p]
# Extract handle from capsule thingy
name = ctypes.pythonapi.PyCapsule_GetName(winid)
handle = ctypes.pythonapi.PyCapsule_GetPointer(winid, name)
return handle
|
python
|
def get_window_id(self):
""" Get the window id of a PySide Widget. Might also work for PyQt4.
"""
# Get Qt win id
winid = self.winId()
# On Linux this is it
if IS_RPI:
nw = (ctypes.c_int * 3)(winid, self.width(), self.height())
return ctypes.pointer(nw)
elif IS_LINUX:
return int(winid) # Is int on PySide, but sip.voidptr on PyQt
# Get window id from stupid capsule thingy
# http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://www.cnb
#logs.com/Shiren-Y/archive/2011/04/06/2007288.html&prev=/search%3Fq%3Dp
# yside%2Bdirectx%26client%3Dfirefox-a%26hs%3DIsJ%26rls%3Dorg.mozilla:n
#l:official%26channel%3Dfflb%26biw%3D1366%26bih%3D614
# Prepare
ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object,
ctypes.c_char_p]
# Extract handle from capsule thingy
name = ctypes.pythonapi.PyCapsule_GetName(winid)
handle = ctypes.pythonapi.PyCapsule_GetPointer(winid, name)
return handle
|
[
"def",
"get_window_id",
"(",
"self",
")",
":",
"# Get Qt win id",
"winid",
"=",
"self",
".",
"winId",
"(",
")",
"# On Linux this is it",
"if",
"IS_RPI",
":",
"nw",
"=",
"(",
"ctypes",
".",
"c_int",
"*",
"3",
")",
"(",
"winid",
",",
"self",
".",
"width",
"(",
")",
",",
"self",
".",
"height",
"(",
")",
")",
"return",
"ctypes",
".",
"pointer",
"(",
"nw",
")",
"elif",
"IS_LINUX",
":",
"return",
"int",
"(",
"winid",
")",
"# Is int on PySide, but sip.voidptr on PyQt",
"# Get window id from stupid capsule thingy",
"# http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://www.cnb",
"#logs.com/Shiren-Y/archive/2011/04/06/2007288.html&prev=/search%3Fq%3Dp",
"# yside%2Bdirectx%26client%3Dfirefox-a%26hs%3DIsJ%26rls%3Dorg.mozilla:n",
"#l:official%26channel%3Dfflb%26biw%3D1366%26bih%3D614",
"# Prepare",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetName",
".",
"restype",
"=",
"ctypes",
".",
"c_char_p",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetName",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"py_object",
"]",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetPointer",
".",
"restype",
"=",
"ctypes",
".",
"c_void_p",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetPointer",
".",
"argtypes",
"=",
"[",
"ctypes",
".",
"py_object",
",",
"ctypes",
".",
"c_char_p",
"]",
"# Extract handle from capsule thingy",
"name",
"=",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetName",
"(",
"winid",
")",
"handle",
"=",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_GetPointer",
"(",
"winid",
",",
"name",
")",
"return",
"handle"
] |
Get the window id of a PySide Widget. Might also work for PyQt4.
|
[
"Get",
"the",
"window",
"id",
"of",
"a",
"PySide",
"Widget",
".",
"Might",
"also",
"work",
"for",
"PyQt4",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/backends/_qt.py#L576-L603
|
train
|
andim/scipydirect
|
doc/tutorialfig.py
|
obj
|
def obj(x):
"""Six-hump camelback function"""
x1 = x[0]
x2 = x[1]
f = (4 - 2.1*(x1*x1) + (x1*x1*x1*x1)/3.0)*(x1*x1) + x1*x2 + (-4 + 4*(x2*x2))*(x2*x2)
return f
|
python
|
def obj(x):
"""Six-hump camelback function"""
x1 = x[0]
x2 = x[1]
f = (4 - 2.1*(x1*x1) + (x1*x1*x1*x1)/3.0)*(x1*x1) + x1*x2 + (-4 + 4*(x2*x2))*(x2*x2)
return f
|
[
"def",
"obj",
"(",
"x",
")",
":",
"x1",
"=",
"x",
"[",
"0",
"]",
"x2",
"=",
"x",
"[",
"1",
"]",
"f",
"=",
"(",
"4",
"-",
"2.1",
"*",
"(",
"x1",
"*",
"x1",
")",
"+",
"(",
"x1",
"*",
"x1",
"*",
"x1",
"*",
"x1",
")",
"/",
"3.0",
")",
"*",
"(",
"x1",
"*",
"x1",
")",
"+",
"x1",
"*",
"x2",
"+",
"(",
"-",
"4",
"+",
"4",
"*",
"(",
"x2",
"*",
"x2",
")",
")",
"*",
"(",
"x2",
"*",
"x2",
")",
"return",
"f"
] |
Six-hump camelback function
|
[
"Six",
"-",
"hump",
"camelback",
"function"
] |
ad36ab19e6ad64054a1d2abd22f1c993fc4b87be
|
https://github.com/andim/scipydirect/blob/ad36ab19e6ad64054a1d2abd22f1c993fc4b87be/doc/tutorialfig.py#L9-L16
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/collections/path_collection.py
|
PathCollection
|
def PathCollection(mode="agg", *args, **kwargs):
"""
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash)
"""
if mode == "raw":
return RawPathCollection(*args, **kwargs)
elif mode == "agg+":
return AggPathCollection(*args, **kwargs)
return AggFastPathCollection(*args, **kwargs)
|
python
|
def PathCollection(mode="agg", *args, **kwargs):
"""
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash)
"""
if mode == "raw":
return RawPathCollection(*args, **kwargs)
elif mode == "agg+":
return AggPathCollection(*args, **kwargs)
return AggFastPathCollection(*args, **kwargs)
|
[
"def",
"PathCollection",
"(",
"mode",
"=",
"\"agg\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"==",
"\"raw\"",
":",
"return",
"RawPathCollection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"mode",
"==",
"\"agg+\"",
":",
"return",
"AggPathCollection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"AggFastPathCollection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash)
|
[
"mode",
":",
"string",
"-",
"raw",
"(",
"speed",
":",
"fastest",
"size",
":",
"small",
"output",
":",
"ugly",
"no",
"dash",
"no",
"thickness",
")",
"-",
"agg",
"(",
"speed",
":",
"medium",
"size",
":",
"medium",
"output",
":",
"nice",
"some",
"flaws",
"no",
"dash",
")",
"-",
"agg",
"+",
"(",
"speed",
":",
"slow",
"size",
":",
"big",
"output",
":",
"perfect",
"no",
"dash",
")"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/path_collection.py#L11-L24
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
STTransform.map
|
def map(self, coords):
"""Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
"""
m = np.empty(coords.shape)
m[:, :3] = (coords[:, :3] * self.scale[np.newaxis, :3] +
coords[:, 3:] * self.translate[np.newaxis, :3])
m[:, 3] = coords[:, 3]
return m
|
python
|
def map(self, coords):
"""Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
"""
m = np.empty(coords.shape)
m[:, :3] = (coords[:, :3] * self.scale[np.newaxis, :3] +
coords[:, 3:] * self.translate[np.newaxis, :3])
m[:, 3] = coords[:, 3]
return m
|
[
"def",
"map",
"(",
"self",
",",
"coords",
")",
":",
"m",
"=",
"np",
".",
"empty",
"(",
"coords",
".",
"shape",
")",
"m",
"[",
":",
",",
":",
"3",
"]",
"=",
"(",
"coords",
"[",
":",
",",
":",
"3",
"]",
"*",
"self",
".",
"scale",
"[",
"np",
".",
"newaxis",
",",
":",
"3",
"]",
"+",
"coords",
"[",
":",
",",
"3",
":",
"]",
"*",
"self",
".",
"translate",
"[",
"np",
".",
"newaxis",
",",
":",
"3",
"]",
")",
"m",
"[",
":",
",",
"3",
"]",
"=",
"coords",
"[",
":",
",",
"3",
"]",
"return",
"m"
] |
Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
|
[
"Map",
"coordinates"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L96-L113
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
STTransform.move
|
def move(self, move):
"""Change the translation of this transform by the amount given.
Parameters
----------
move : array-like
The values to be added to the current translation of the transform.
"""
move = as_vec4(move, default=(0, 0, 0, 0))
self.translate = self.translate + move
|
python
|
def move(self, move):
"""Change the translation of this transform by the amount given.
Parameters
----------
move : array-like
The values to be added to the current translation of the transform.
"""
move = as_vec4(move, default=(0, 0, 0, 0))
self.translate = self.translate + move
|
[
"def",
"move",
"(",
"self",
",",
"move",
")",
":",
"move",
"=",
"as_vec4",
"(",
"move",
",",
"default",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"self",
".",
"translate",
"=",
"self",
".",
"translate",
"+",
"move"
] |
Change the translation of this transform by the amount given.
Parameters
----------
move : array-like
The values to be added to the current translation of the transform.
|
[
"Change",
"the",
"translation",
"of",
"this",
"transform",
"by",
"the",
"amount",
"given",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L181-L190
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
STTransform.zoom
|
def zoom(self, zoom, center=(0, 0, 0), mapped=True):
"""Update the transform such that its scale factor is changed, but
the specified center point is left unchanged.
Parameters
----------
zoom : array-like
Values to multiply the transform's current scale
factors.
center : array-like
The center point around which the scaling will take place.
mapped : bool
Whether *center* is expressed in mapped coordinates (True) or
unmapped coordinates (False).
"""
zoom = as_vec4(zoom, default=(1, 1, 1, 1))
center = as_vec4(center, default=(0, 0, 0, 0))
scale = self.scale * zoom
if mapped:
trans = center - (center - self.translate) * zoom
else:
trans = self.scale * (1 - zoom) * center + self.translate
self._set_st(scale=scale, translate=trans)
|
python
|
def zoom(self, zoom, center=(0, 0, 0), mapped=True):
"""Update the transform such that its scale factor is changed, but
the specified center point is left unchanged.
Parameters
----------
zoom : array-like
Values to multiply the transform's current scale
factors.
center : array-like
The center point around which the scaling will take place.
mapped : bool
Whether *center* is expressed in mapped coordinates (True) or
unmapped coordinates (False).
"""
zoom = as_vec4(zoom, default=(1, 1, 1, 1))
center = as_vec4(center, default=(0, 0, 0, 0))
scale = self.scale * zoom
if mapped:
trans = center - (center - self.translate) * zoom
else:
trans = self.scale * (1 - zoom) * center + self.translate
self._set_st(scale=scale, translate=trans)
|
[
"def",
"zoom",
"(",
"self",
",",
"zoom",
",",
"center",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"mapped",
"=",
"True",
")",
":",
"zoom",
"=",
"as_vec4",
"(",
"zoom",
",",
"default",
"=",
"(",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
")",
"center",
"=",
"as_vec4",
"(",
"center",
",",
"default",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"scale",
"=",
"self",
".",
"scale",
"*",
"zoom",
"if",
"mapped",
":",
"trans",
"=",
"center",
"-",
"(",
"center",
"-",
"self",
".",
"translate",
")",
"*",
"zoom",
"else",
":",
"trans",
"=",
"self",
".",
"scale",
"*",
"(",
"1",
"-",
"zoom",
")",
"*",
"center",
"+",
"self",
".",
"translate",
"self",
".",
"_set_st",
"(",
"scale",
"=",
"scale",
",",
"translate",
"=",
"trans",
")"
] |
Update the transform such that its scale factor is changed, but
the specified center point is left unchanged.
Parameters
----------
zoom : array-like
Values to multiply the transform's current scale
factors.
center : array-like
The center point around which the scaling will take place.
mapped : bool
Whether *center* is expressed in mapped coordinates (True) or
unmapped coordinates (False).
|
[
"Update",
"the",
"transform",
"such",
"that",
"its",
"scale",
"factor",
"is",
"changed",
"but",
"the",
"specified",
"center",
"point",
"is",
"left",
"unchanged",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L192-L214
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
STTransform.from_mapping
|
def from_mapping(cls, x0, x1):
""" Create an STTransform from the given mapping
See `set_mapping` for details.
Parameters
----------
x0 : array-like
Start.
x1 : array-like
End.
Returns
-------
t : instance of STTransform
The transform.
"""
t = cls()
t.set_mapping(x0, x1)
return t
|
python
|
def from_mapping(cls, x0, x1):
""" Create an STTransform from the given mapping
See `set_mapping` for details.
Parameters
----------
x0 : array-like
Start.
x1 : array-like
End.
Returns
-------
t : instance of STTransform
The transform.
"""
t = cls()
t.set_mapping(x0, x1)
return t
|
[
"def",
"from_mapping",
"(",
"cls",
",",
"x0",
",",
"x1",
")",
":",
"t",
"=",
"cls",
"(",
")",
"t",
".",
"set_mapping",
"(",
"x0",
",",
"x1",
")",
"return",
"t"
] |
Create an STTransform from the given mapping
See `set_mapping` for details.
Parameters
----------
x0 : array-like
Start.
x1 : array-like
End.
Returns
-------
t : instance of STTransform
The transform.
|
[
"Create",
"an",
"STTransform",
"from",
"the",
"given",
"mapping"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L223-L242
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
STTransform.set_mapping
|
def set_mapping(self, x0, x1, update=True):
"""Configure this transform such that it maps points x0 => x1
Parameters
----------
x0 : array-like, shape (2, 2) or (2, 3)
Start location.
x1 : array-like, shape (2, 2) or (2, 3)
End location.
update : bool
If False, then the update event is not emitted.
Examples
--------
For example, if we wish to map the corners of a rectangle::
>>> p1 = [[0, 0], [200, 300]]
onto a unit cube::
>>> p2 = [[-1, -1], [1, 1]]
then we can generate the transform as follows::
>>> tr = STTransform()
>>> tr.set_mapping(p1, p2)
>>> assert tr.map(p1)[:,:2] == p2 # test
"""
# if args are Rect, convert to array first
if isinstance(x0, Rect):
x0 = x0._transform_in()[:3]
if isinstance(x1, Rect):
x1 = x1._transform_in()[:3]
x0 = np.asarray(x0)
x1 = np.asarray(x1)
if (x0.ndim != 2 or x0.shape[0] != 2 or x1.ndim != 2 or
x1.shape[0] != 2):
raise TypeError("set_mapping requires array inputs of shape "
"(2, N).")
denom = x0[1] - x0[0]
mask = denom == 0
denom[mask] = 1.0
s = (x1[1] - x1[0]) / denom
s[mask] = 1.0
s[x0[1] == x0[0]] = 1.0
t = x1[0] - s * x0[0]
s = as_vec4(s, default=(1, 1, 1, 1))
t = as_vec4(t, default=(0, 0, 0, 0))
self._set_st(scale=s, translate=t, update=update)
|
python
|
def set_mapping(self, x0, x1, update=True):
"""Configure this transform such that it maps points x0 => x1
Parameters
----------
x0 : array-like, shape (2, 2) or (2, 3)
Start location.
x1 : array-like, shape (2, 2) or (2, 3)
End location.
update : bool
If False, then the update event is not emitted.
Examples
--------
For example, if we wish to map the corners of a rectangle::
>>> p1 = [[0, 0], [200, 300]]
onto a unit cube::
>>> p2 = [[-1, -1], [1, 1]]
then we can generate the transform as follows::
>>> tr = STTransform()
>>> tr.set_mapping(p1, p2)
>>> assert tr.map(p1)[:,:2] == p2 # test
"""
# if args are Rect, convert to array first
if isinstance(x0, Rect):
x0 = x0._transform_in()[:3]
if isinstance(x1, Rect):
x1 = x1._transform_in()[:3]
x0 = np.asarray(x0)
x1 = np.asarray(x1)
if (x0.ndim != 2 or x0.shape[0] != 2 or x1.ndim != 2 or
x1.shape[0] != 2):
raise TypeError("set_mapping requires array inputs of shape "
"(2, N).")
denom = x0[1] - x0[0]
mask = denom == 0
denom[mask] = 1.0
s = (x1[1] - x1[0]) / denom
s[mask] = 1.0
s[x0[1] == x0[0]] = 1.0
t = x1[0] - s * x0[0]
s = as_vec4(s, default=(1, 1, 1, 1))
t = as_vec4(t, default=(0, 0, 0, 0))
self._set_st(scale=s, translate=t, update=update)
|
[
"def",
"set_mapping",
"(",
"self",
",",
"x0",
",",
"x1",
",",
"update",
"=",
"True",
")",
":",
"# if args are Rect, convert to array first",
"if",
"isinstance",
"(",
"x0",
",",
"Rect",
")",
":",
"x0",
"=",
"x0",
".",
"_transform_in",
"(",
")",
"[",
":",
"3",
"]",
"if",
"isinstance",
"(",
"x1",
",",
"Rect",
")",
":",
"x1",
"=",
"x1",
".",
"_transform_in",
"(",
")",
"[",
":",
"3",
"]",
"x0",
"=",
"np",
".",
"asarray",
"(",
"x0",
")",
"x1",
"=",
"np",
".",
"asarray",
"(",
"x1",
")",
"if",
"(",
"x0",
".",
"ndim",
"!=",
"2",
"or",
"x0",
".",
"shape",
"[",
"0",
"]",
"!=",
"2",
"or",
"x1",
".",
"ndim",
"!=",
"2",
"or",
"x1",
".",
"shape",
"[",
"0",
"]",
"!=",
"2",
")",
":",
"raise",
"TypeError",
"(",
"\"set_mapping requires array inputs of shape \"",
"\"(2, N).\"",
")",
"denom",
"=",
"x0",
"[",
"1",
"]",
"-",
"x0",
"[",
"0",
"]",
"mask",
"=",
"denom",
"==",
"0",
"denom",
"[",
"mask",
"]",
"=",
"1.0",
"s",
"=",
"(",
"x1",
"[",
"1",
"]",
"-",
"x1",
"[",
"0",
"]",
")",
"/",
"denom",
"s",
"[",
"mask",
"]",
"=",
"1.0",
"s",
"[",
"x0",
"[",
"1",
"]",
"==",
"x0",
"[",
"0",
"]",
"]",
"=",
"1.0",
"t",
"=",
"x1",
"[",
"0",
"]",
"-",
"s",
"*",
"x0",
"[",
"0",
"]",
"s",
"=",
"as_vec4",
"(",
"s",
",",
"default",
"=",
"(",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
")",
"t",
"=",
"as_vec4",
"(",
"t",
",",
"default",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"self",
".",
"_set_st",
"(",
"scale",
"=",
"s",
",",
"translate",
"=",
"t",
",",
"update",
"=",
"update",
")"
] |
Configure this transform such that it maps points x0 => x1
Parameters
----------
x0 : array-like, shape (2, 2) or (2, 3)
Start location.
x1 : array-like, shape (2, 2) or (2, 3)
End location.
update : bool
If False, then the update event is not emitted.
Examples
--------
For example, if we wish to map the corners of a rectangle::
>>> p1 = [[0, 0], [200, 300]]
onto a unit cube::
>>> p2 = [[-1, -1], [1, 1]]
then we can generate the transform as follows::
>>> tr = STTransform()
>>> tr.set_mapping(p1, p2)
>>> assert tr.map(p1)[:,:2] == p2 # test
|
[
"Configure",
"this",
"transform",
"such",
"that",
"it",
"maps",
"points",
"x0",
"=",
">",
"x1"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L244-L294
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.translate
|
def translate(self, pos):
"""
Translate the matrix
The translation is applied *after* the transformations already present
in the matrix.
Parameters
----------
pos : arrayndarray
Position to translate by.
"""
self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))
|
python
|
def translate(self, pos):
"""
Translate the matrix
The translation is applied *after* the transformations already present
in the matrix.
Parameters
----------
pos : arrayndarray
Position to translate by.
"""
self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))
|
[
"def",
"translate",
"(",
"self",
",",
"pos",
")",
":",
"self",
".",
"matrix",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"matrix",
",",
"transforms",
".",
"translate",
"(",
"pos",
"[",
"0",
",",
":",
"3",
"]",
")",
")"
] |
Translate the matrix
The translation is applied *after* the transformations already present
in the matrix.
Parameters
----------
pos : arrayndarray
Position to translate by.
|
[
"Translate",
"the",
"matrix"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L410-L422
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.scale
|
def scale(self, scale, center=None):
"""
Scale the matrix about a given origin.
The scaling is applied *after* the transformations already present
in the matrix.
Parameters
----------
scale : array-like
Scale factors along x, y and z axes.
center : array-like or None
The x, y and z coordinates to scale around. If None,
(0, 0, 0) will be used.
"""
scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3])
if center is not None:
center = as_vec4(center)[0, :3]
scale = np.dot(np.dot(transforms.translate(-center), scale),
transforms.translate(center))
self.matrix = np.dot(self.matrix, scale)
|
python
|
def scale(self, scale, center=None):
"""
Scale the matrix about a given origin.
The scaling is applied *after* the transformations already present
in the matrix.
Parameters
----------
scale : array-like
Scale factors along x, y and z axes.
center : array-like or None
The x, y and z coordinates to scale around. If None,
(0, 0, 0) will be used.
"""
scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3])
if center is not None:
center = as_vec4(center)[0, :3]
scale = np.dot(np.dot(transforms.translate(-center), scale),
transforms.translate(center))
self.matrix = np.dot(self.matrix, scale)
|
[
"def",
"scale",
"(",
"self",
",",
"scale",
",",
"center",
"=",
"None",
")",
":",
"scale",
"=",
"transforms",
".",
"scale",
"(",
"as_vec4",
"(",
"scale",
",",
"default",
"=",
"(",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
")",
"[",
"0",
",",
":",
"3",
"]",
")",
"if",
"center",
"is",
"not",
"None",
":",
"center",
"=",
"as_vec4",
"(",
"center",
")",
"[",
"0",
",",
":",
"3",
"]",
"scale",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"transforms",
".",
"translate",
"(",
"-",
"center",
")",
",",
"scale",
")",
",",
"transforms",
".",
"translate",
"(",
"center",
")",
")",
"self",
".",
"matrix",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"matrix",
",",
"scale",
")"
] |
Scale the matrix about a given origin.
The scaling is applied *after* the transformations already present
in the matrix.
Parameters
----------
scale : array-like
Scale factors along x, y and z axes.
center : array-like or None
The x, y and z coordinates to scale around. If None,
(0, 0, 0) will be used.
|
[
"Scale",
"the",
"matrix",
"about",
"a",
"given",
"origin",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L424-L444
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.rotate
|
def rotate(self, angle, axis):
"""
Rotate the matrix by some angle about a given axis.
The rotation is applied *after* the transformations already present
in the matrix.
Parameters
----------
angle : float
The angle of rotation, in degrees.
axis : array-like
The x, y and z coordinates of the axis vector to rotate around.
"""
self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))
|
python
|
def rotate(self, angle, axis):
"""
Rotate the matrix by some angle about a given axis.
The rotation is applied *after* the transformations already present
in the matrix.
Parameters
----------
angle : float
The angle of rotation, in degrees.
axis : array-like
The x, y and z coordinates of the axis vector to rotate around.
"""
self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))
|
[
"def",
"rotate",
"(",
"self",
",",
"angle",
",",
"axis",
")",
":",
"self",
".",
"matrix",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"matrix",
",",
"transforms",
".",
"rotate",
"(",
"angle",
",",
"axis",
")",
")"
] |
Rotate the matrix by some angle about a given axis.
The rotation is applied *after* the transformations already present
in the matrix.
Parameters
----------
angle : float
The angle of rotation, in degrees.
axis : array-like
The x, y and z coordinates of the axis vector to rotate around.
|
[
"Rotate",
"the",
"matrix",
"by",
"some",
"angle",
"about",
"a",
"given",
"axis",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L446-L460
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.set_mapping
|
def set_mapping(self, points1, points2):
""" Set to a 3D transformation matrix that maps points1 onto points2.
Parameters
----------
points1 : array-like, shape (4, 3)
Four starting 3D coordinates.
points2 : array-like, shape (4, 3)
Four ending 3D coordinates.
"""
# note: need to transpose because util.functions uses opposite
# of standard linear algebra order.
self.matrix = transforms.affine_map(points1, points2).T
|
python
|
def set_mapping(self, points1, points2):
""" Set to a 3D transformation matrix that maps points1 onto points2.
Parameters
----------
points1 : array-like, shape (4, 3)
Four starting 3D coordinates.
points2 : array-like, shape (4, 3)
Four ending 3D coordinates.
"""
# note: need to transpose because util.functions uses opposite
# of standard linear algebra order.
self.matrix = transforms.affine_map(points1, points2).T
|
[
"def",
"set_mapping",
"(",
"self",
",",
"points1",
",",
"points2",
")",
":",
"# note: need to transpose because util.functions uses opposite",
"# of standard linear algebra order.",
"self",
".",
"matrix",
"=",
"transforms",
".",
"affine_map",
"(",
"points1",
",",
"points2",
")",
".",
"T"
] |
Set to a 3D transformation matrix that maps points1 onto points2.
Parameters
----------
points1 : array-like, shape (4, 3)
Four starting 3D coordinates.
points2 : array-like, shape (4, 3)
Four ending 3D coordinates.
|
[
"Set",
"to",
"a",
"3D",
"transformation",
"matrix",
"that",
"maps",
"points1",
"onto",
"points2",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L462-L474
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.set_ortho
|
def set_ortho(self, l, r, b, t, n, f):
"""Set ortho transform
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
"""
self.matrix = transforms.ortho(l, r, b, t, n, f)
|
python
|
def set_ortho(self, l, r, b, t, n, f):
"""Set ortho transform
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
"""
self.matrix = transforms.ortho(l, r, b, t, n, f)
|
[
"def",
"set_ortho",
"(",
"self",
",",
"l",
",",
"r",
",",
"b",
",",
"t",
",",
"n",
",",
"f",
")",
":",
"self",
".",
"matrix",
"=",
"transforms",
".",
"ortho",
"(",
"l",
",",
"r",
",",
"b",
",",
"t",
",",
"n",
",",
"f",
")"
] |
Set ortho transform
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
|
[
"Set",
"ortho",
"transform"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L476-L494
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.set_perspective
|
def set_perspective(self, fov, aspect, near, far):
"""Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location.
"""
self.matrix = transforms.perspective(fov, aspect, near, far)
|
python
|
def set_perspective(self, fov, aspect, near, far):
"""Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location.
"""
self.matrix = transforms.perspective(fov, aspect, near, far)
|
[
"def",
"set_perspective",
"(",
"self",
",",
"fov",
",",
"aspect",
",",
"near",
",",
"far",
")",
":",
"self",
".",
"matrix",
"=",
"transforms",
".",
"perspective",
"(",
"fov",
",",
"aspect",
",",
"near",
",",
"far",
")"
] |
Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location.
|
[
"Set",
"the",
"perspective"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L516-L530
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py
|
MatrixTransform.set_frustum
|
def set_frustum(self, l, r, b, t, n, f):
"""Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
"""
self.matrix = transforms.frustum(l, r, b, t, n, f)
|
python
|
def set_frustum(self, l, r, b, t, n, f):
"""Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
"""
self.matrix = transforms.frustum(l, r, b, t, n, f)
|
[
"def",
"set_frustum",
"(",
"self",
",",
"l",
",",
"r",
",",
"b",
",",
"t",
",",
"n",
",",
"f",
")",
":",
"self",
".",
"matrix",
"=",
"transforms",
".",
"frustum",
"(",
"l",
",",
"r",
",",
"b",
",",
"t",
",",
"n",
",",
"f",
")"
] |
Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
Far.
|
[
"Set",
"the",
"frustum"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/linear.py#L532-L550
|
train
|
cds-astro/mocpy
|
mocpy/utils.py
|
log2_lut
|
def log2_lut(v):
"""
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for
computing the log2 of a 32 bit integer using a look up table
Parameters
----------
v : int
32 bit integer
Returns
-------
"""
res = np.zeros(v.shape, dtype=np.int32)
tt = v >> 16
tt_zero = (tt == 0)
tt_not_zero = ~tt_zero
t_h = tt >> 8
t_zero_h = (t_h == 0) & tt_not_zero
t_not_zero_h = ~t_zero_h & tt_not_zero
res[t_zero_h] = LogTable256[tt[t_zero_h]] + 16
res[t_not_zero_h] = LogTable256[t_h[t_not_zero_h]] + 24
t_l = v >> 8
t_zero_l = (t_l == 0) & tt_zero
t_not_zero_l = ~t_zero_l & tt_zero
res[t_zero_l] = LogTable256[v[t_zero_l]]
res[t_not_zero_l] = LogTable256[t_l[t_not_zero_l]] + 8
return res
|
python
|
def log2_lut(v):
"""
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for
computing the log2 of a 32 bit integer using a look up table
Parameters
----------
v : int
32 bit integer
Returns
-------
"""
res = np.zeros(v.shape, dtype=np.int32)
tt = v >> 16
tt_zero = (tt == 0)
tt_not_zero = ~tt_zero
t_h = tt >> 8
t_zero_h = (t_h == 0) & tt_not_zero
t_not_zero_h = ~t_zero_h & tt_not_zero
res[t_zero_h] = LogTable256[tt[t_zero_h]] + 16
res[t_not_zero_h] = LogTable256[t_h[t_not_zero_h]] + 24
t_l = v >> 8
t_zero_l = (t_l == 0) & tt_zero
t_not_zero_l = ~t_zero_l & tt_zero
res[t_zero_l] = LogTable256[v[t_zero_l]]
res[t_not_zero_l] = LogTable256[t_l[t_not_zero_l]] + 8
return res
|
[
"def",
"log2_lut",
"(",
"v",
")",
":",
"res",
"=",
"np",
".",
"zeros",
"(",
"v",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"tt",
"=",
"v",
">>",
"16",
"tt_zero",
"=",
"(",
"tt",
"==",
"0",
")",
"tt_not_zero",
"=",
"~",
"tt_zero",
"t_h",
"=",
"tt",
">>",
"8",
"t_zero_h",
"=",
"(",
"t_h",
"==",
"0",
")",
"&",
"tt_not_zero",
"t_not_zero_h",
"=",
"~",
"t_zero_h",
"&",
"tt_not_zero",
"res",
"[",
"t_zero_h",
"]",
"=",
"LogTable256",
"[",
"tt",
"[",
"t_zero_h",
"]",
"]",
"+",
"16",
"res",
"[",
"t_not_zero_h",
"]",
"=",
"LogTable256",
"[",
"t_h",
"[",
"t_not_zero_h",
"]",
"]",
"+",
"24",
"t_l",
"=",
"v",
">>",
"8",
"t_zero_l",
"=",
"(",
"t_l",
"==",
"0",
")",
"&",
"tt_zero",
"t_not_zero_l",
"=",
"~",
"t_zero_l",
"&",
"tt_zero",
"res",
"[",
"t_zero_l",
"]",
"=",
"LogTable256",
"[",
"v",
"[",
"t_zero_l",
"]",
"]",
"res",
"[",
"t_not_zero_l",
"]",
"=",
"LogTable256",
"[",
"t_l",
"[",
"t_not_zero_l",
"]",
"]",
"+",
"8",
"return",
"res"
] |
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for
computing the log2 of a 32 bit integer using a look up table
Parameters
----------
v : int
32 bit integer
Returns
-------
|
[
"See",
"this",
"algo",
"<https",
":",
"//",
"graphics",
".",
"stanford",
".",
"edu",
"/",
"~seander",
"/",
"bithacks",
".",
"html#IntegerLogLookup",
">",
"__",
"for",
"computing",
"the",
"log2",
"of",
"a",
"32",
"bit",
"integer",
"using",
"a",
"look",
"up",
"table"
] |
09472cabe537f6bfdb049eeea64d3ea57b391c21
|
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/utils.py#L27-L61
|
train
|
cds-astro/mocpy
|
mocpy/utils.py
|
uniq2orderipix_lut
|
def uniq2orderipix_lut(uniq):
"""
~30% faster than the method below
Parameters
----------
uniq
Returns
-------
"""
order = log2_lut(uniq >> 2) >> 1
ipix = uniq - (1 << (2 * (order + 1)))
return order, ipix
|
python
|
def uniq2orderipix_lut(uniq):
"""
~30% faster than the method below
Parameters
----------
uniq
Returns
-------
"""
order = log2_lut(uniq >> 2) >> 1
ipix = uniq - (1 << (2 * (order + 1)))
return order, ipix
|
[
"def",
"uniq2orderipix_lut",
"(",
"uniq",
")",
":",
"order",
"=",
"log2_lut",
"(",
"uniq",
">>",
"2",
")",
">>",
"1",
"ipix",
"=",
"uniq",
"-",
"(",
"1",
"<<",
"(",
"2",
"*",
"(",
"order",
"+",
"1",
")",
")",
")",
"return",
"order",
",",
"ipix"
] |
~30% faster than the method below
Parameters
----------
uniq
Returns
-------
|
[
"~30%",
"faster",
"than",
"the",
"method",
"below",
"Parameters",
"----------",
"uniq"
] |
09472cabe537f6bfdb049eeea64d3ea57b391c21
|
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/utils.py#L64-L77
|
train
|
cds-astro/mocpy
|
mocpy/utils.py
|
uniq2orderipix
|
def uniq2orderipix(uniq):
"""
convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple
"""
order = ((np.log2(uniq//4)) // 2)
order = order.astype(int)
ipix = uniq - 4 * (4**order)
return order, ipix
|
python
|
def uniq2orderipix(uniq):
"""
convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple
"""
order = ((np.log2(uniq//4)) // 2)
order = order.astype(int)
ipix = uniq - 4 * (4**order)
return order, ipix
|
[
"def",
"uniq2orderipix",
"(",
"uniq",
")",
":",
"order",
"=",
"(",
"(",
"np",
".",
"log2",
"(",
"uniq",
"//",
"4",
")",
")",
"//",
"2",
")",
"order",
"=",
"order",
".",
"astype",
"(",
"int",
")",
"ipix",
"=",
"uniq",
"-",
"4",
"*",
"(",
"4",
"**",
"order",
")",
"return",
"order",
",",
"ipix"
] |
convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple
|
[
"convert",
"a",
"HEALPix",
"pixel",
"coded",
"as",
"a",
"NUNIQ",
"number",
"to",
"a",
"(",
"norder",
"ipix",
")",
"tuple"
] |
09472cabe537f6bfdb049eeea64d3ea57b391c21
|
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/utils.py#L80-L89
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py
|
glBufferData
|
def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = None
else:
size = data.nbytes
GL.glBufferData(target, size, data, usage)
|
python
|
def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = None
else:
size = data.nbytes
GL.glBufferData(target, size, data, usage)
|
[
"def",
"glBufferData",
"(",
"target",
",",
"data",
",",
"usage",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"size",
"=",
"data",
"data",
"=",
"None",
"else",
":",
"size",
"=",
"data",
".",
"nbytes",
"GL",
".",
"glBufferData",
"(",
"target",
",",
"size",
",",
"data",
",",
"usage",
")"
] |
Data can be numpy array or the size of data to allocate.
|
[
"Data",
"can",
"be",
"numpy",
"array",
"or",
"the",
"size",
"of",
"data",
"to",
"allocate",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py#L22-L30
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/line_plot.py
|
LinePlotVisual.set_data
|
def set_data(self, data=None, **kwargs):
"""Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
"""
if data is None:
pos = None
else:
if isinstance(data, tuple):
pos = np.array(data).T.astype(np.float32)
else:
pos = np.atleast_1d(data).astype(np.float32)
if pos.ndim == 1:
pos = pos[:, np.newaxis]
elif pos.ndim > 2:
raise ValueError('data must have at most two dimensions')
if pos.size == 0:
pos = self._line.pos
# if both args and keywords are zero, then there is no
# point in calling this function.
if len(kwargs) == 0:
raise TypeError("neither line points nor line properties"
"are provided")
elif pos.shape[1] == 1:
x = np.arange(pos.shape[0], dtype=np.float32)[:, np.newaxis]
pos = np.concatenate((x, pos), axis=1)
# if args are empty, don't modify position
elif pos.shape[1] > 3:
raise TypeError("Too many coordinates given (%s; max is 3)."
% pos.shape[1])
# todo: have both sub-visuals share the same buffers.
line_kwargs = {}
for k in self._line_kwargs:
if k in kwargs:
k_ = self._kw_trans[k] if k in self._kw_trans else k
line_kwargs[k] = kwargs.pop(k_)
if pos is not None or len(line_kwargs) > 0:
self._line.set_data(pos=pos, **line_kwargs)
marker_kwargs = {}
for k in self._marker_kwargs:
if k in kwargs:
k_ = self._kw_trans[k] if k in self._kw_trans else k
marker_kwargs[k_] = kwargs.pop(k)
if pos is not None or len(marker_kwargs) > 0:
self._markers.set_data(pos=pos, **marker_kwargs)
if len(kwargs) > 0:
raise TypeError("Invalid keyword arguments: %s" % kwargs.keys())
|
python
|
def set_data(self, data=None, **kwargs):
"""Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
"""
if data is None:
pos = None
else:
if isinstance(data, tuple):
pos = np.array(data).T.astype(np.float32)
else:
pos = np.atleast_1d(data).astype(np.float32)
if pos.ndim == 1:
pos = pos[:, np.newaxis]
elif pos.ndim > 2:
raise ValueError('data must have at most two dimensions')
if pos.size == 0:
pos = self._line.pos
# if both args and keywords are zero, then there is no
# point in calling this function.
if len(kwargs) == 0:
raise TypeError("neither line points nor line properties"
"are provided")
elif pos.shape[1] == 1:
x = np.arange(pos.shape[0], dtype=np.float32)[:, np.newaxis]
pos = np.concatenate((x, pos), axis=1)
# if args are empty, don't modify position
elif pos.shape[1] > 3:
raise TypeError("Too many coordinates given (%s; max is 3)."
% pos.shape[1])
# todo: have both sub-visuals share the same buffers.
line_kwargs = {}
for k in self._line_kwargs:
if k in kwargs:
k_ = self._kw_trans[k] if k in self._kw_trans else k
line_kwargs[k] = kwargs.pop(k_)
if pos is not None or len(line_kwargs) > 0:
self._line.set_data(pos=pos, **line_kwargs)
marker_kwargs = {}
for k in self._marker_kwargs:
if k in kwargs:
k_ = self._kw_trans[k] if k in self._kw_trans else k
marker_kwargs[k_] = kwargs.pop(k)
if pos is not None or len(marker_kwargs) > 0:
self._markers.set_data(pos=pos, **marker_kwargs)
if len(kwargs) > 0:
raise TypeError("Invalid keyword arguments: %s" % kwargs.keys())
|
[
"def",
"set_data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"pos",
"=",
"None",
"else",
":",
"if",
"isinstance",
"(",
"data",
",",
"tuple",
")",
":",
"pos",
"=",
"np",
".",
"array",
"(",
"data",
")",
".",
"T",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"else",
":",
"pos",
"=",
"np",
".",
"atleast_1d",
"(",
"data",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"pos",
".",
"ndim",
"==",
"1",
":",
"pos",
"=",
"pos",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"elif",
"pos",
".",
"ndim",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'data must have at most two dimensions'",
")",
"if",
"pos",
".",
"size",
"==",
"0",
":",
"pos",
"=",
"self",
".",
"_line",
".",
"pos",
"# if both args and keywords are zero, then there is no",
"# point in calling this function.",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"\"neither line points nor line properties\"",
"\"are provided\"",
")",
"elif",
"pos",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"pos",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"pos",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"pos",
")",
",",
"axis",
"=",
"1",
")",
"# if args are empty, don't modify position",
"elif",
"pos",
".",
"shape",
"[",
"1",
"]",
">",
"3",
":",
"raise",
"TypeError",
"(",
"\"Too many coordinates given (%s; max is 3).\"",
"%",
"pos",
".",
"shape",
"[",
"1",
"]",
")",
"# todo: have both sub-visuals share the same buffers.",
"line_kwargs",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_line_kwargs",
":",
"if",
"k",
"in",
"kwargs",
":",
"k_",
"=",
"self",
".",
"_kw_trans",
"[",
"k",
"]",
"if",
"k",
"in",
"self",
".",
"_kw_trans",
"else",
"k",
"line_kwargs",
"[",
"k",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"k_",
")",
"if",
"pos",
"is",
"not",
"None",
"or",
"len",
"(",
"line_kwargs",
")",
">",
"0",
":",
"self",
".",
"_line",
".",
"set_data",
"(",
"pos",
"=",
"pos",
",",
"*",
"*",
"line_kwargs",
")",
"marker_kwargs",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_marker_kwargs",
":",
"if",
"k",
"in",
"kwargs",
":",
"k_",
"=",
"self",
".",
"_kw_trans",
"[",
"k",
"]",
"if",
"k",
"in",
"self",
".",
"_kw_trans",
"else",
"k",
"marker_kwargs",
"[",
"k_",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"k",
")",
"if",
"pos",
"is",
"not",
"None",
"or",
"len",
"(",
"marker_kwargs",
")",
">",
"0",
":",
"self",
".",
"_markers",
".",
"set_data",
"(",
"pos",
"=",
"pos",
",",
"*",
"*",
"marker_kwargs",
")",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
":",
"raise",
"TypeError",
"(",
"\"Invalid keyword arguments: %s\"",
"%",
"kwargs",
".",
"keys",
"(",
")",
")"
] |
Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
|
[
"Set",
"the",
"line",
"data"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/line_plot.py#L72-L128
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/infinite_line.py
|
InfiniteLineVisual.set_data
|
def set_data(self, pos=None, color=None):
"""Set the data
Parameters
----------
pos : float
Position of the line along the axis.
color : list, tuple, or array
The color to use when drawing the line. If an array is given, it
must be of shape (1, 4) and provide one rgba color per vertex.
"""
if pos is not None:
pos = float(pos)
xy = self._pos
if self._is_vertical:
xy[0, 0] = pos
xy[0, 1] = -1
xy[1, 0] = pos
xy[1, 1] = 1
else:
xy[0, 0] = -1
xy[0, 1] = pos
xy[1, 0] = 1
xy[1, 1] = pos
self._changed['pos'] = True
if color is not None:
color = np.array(color, dtype=np.float32)
if color.ndim != 1 or color.shape[0] != 4:
raise ValueError('color must be a 4 element float rgba tuple,'
' list or array')
self._color = color
self._changed['color'] = True
|
python
|
def set_data(self, pos=None, color=None):
"""Set the data
Parameters
----------
pos : float
Position of the line along the axis.
color : list, tuple, or array
The color to use when drawing the line. If an array is given, it
must be of shape (1, 4) and provide one rgba color per vertex.
"""
if pos is not None:
pos = float(pos)
xy = self._pos
if self._is_vertical:
xy[0, 0] = pos
xy[0, 1] = -1
xy[1, 0] = pos
xy[1, 1] = 1
else:
xy[0, 0] = -1
xy[0, 1] = pos
xy[1, 0] = 1
xy[1, 1] = pos
self._changed['pos'] = True
if color is not None:
color = np.array(color, dtype=np.float32)
if color.ndim != 1 or color.shape[0] != 4:
raise ValueError('color must be a 4 element float rgba tuple,'
' list or array')
self._color = color
self._changed['color'] = True
|
[
"def",
"set_data",
"(",
"self",
",",
"pos",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"pos",
"is",
"not",
"None",
":",
"pos",
"=",
"float",
"(",
"pos",
")",
"xy",
"=",
"self",
".",
"_pos",
"if",
"self",
".",
"_is_vertical",
":",
"xy",
"[",
"0",
",",
"0",
"]",
"=",
"pos",
"xy",
"[",
"0",
",",
"1",
"]",
"=",
"-",
"1",
"xy",
"[",
"1",
",",
"0",
"]",
"=",
"pos",
"xy",
"[",
"1",
",",
"1",
"]",
"=",
"1",
"else",
":",
"xy",
"[",
"0",
",",
"0",
"]",
"=",
"-",
"1",
"xy",
"[",
"0",
",",
"1",
"]",
"=",
"pos",
"xy",
"[",
"1",
",",
"0",
"]",
"=",
"1",
"xy",
"[",
"1",
",",
"1",
"]",
"=",
"pos",
"self",
".",
"_changed",
"[",
"'pos'",
"]",
"=",
"True",
"if",
"color",
"is",
"not",
"None",
":",
"color",
"=",
"np",
".",
"array",
"(",
"color",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"if",
"color",
".",
"ndim",
"!=",
"1",
"or",
"color",
".",
"shape",
"[",
"0",
"]",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"'color must be a 4 element float rgba tuple,'",
"' list or array'",
")",
"self",
".",
"_color",
"=",
"color",
"self",
".",
"_changed",
"[",
"'color'",
"]",
"=",
"True"
] |
Set the data
Parameters
----------
pos : float
Position of the line along the axis.
color : list, tuple, or array
The color to use when drawing the line. If an array is given, it
must be of shape (1, 4) and provide one rgba color per vertex.
|
[
"Set",
"the",
"data"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/infinite_line.py#L85-L117
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/infinite_line.py
|
InfiniteLineVisual._compute_bounds
|
def _compute_bounds(self, axis, view):
"""Return the (min, max) bounding values of this visual along *axis*
in the local coordinate system.
"""
is_vertical = self._is_vertical
pos = self._pos
if axis == 0 and is_vertical:
return (pos[0, 0], pos[0, 0])
elif axis == 1 and not is_vertical:
return (self._pos[0, 1], self._pos[0, 1])
return None
|
python
|
def _compute_bounds(self, axis, view):
"""Return the (min, max) bounding values of this visual along *axis*
in the local coordinate system.
"""
is_vertical = self._is_vertical
pos = self._pos
if axis == 0 and is_vertical:
return (pos[0, 0], pos[0, 0])
elif axis == 1 and not is_vertical:
return (self._pos[0, 1], self._pos[0, 1])
return None
|
[
"def",
"_compute_bounds",
"(",
"self",
",",
"axis",
",",
"view",
")",
":",
"is_vertical",
"=",
"self",
".",
"_is_vertical",
"pos",
"=",
"self",
".",
"_pos",
"if",
"axis",
"==",
"0",
"and",
"is_vertical",
":",
"return",
"(",
"pos",
"[",
"0",
",",
"0",
"]",
",",
"pos",
"[",
"0",
",",
"0",
"]",
")",
"elif",
"axis",
"==",
"1",
"and",
"not",
"is_vertical",
":",
"return",
"(",
"self",
".",
"_pos",
"[",
"0",
",",
"1",
"]",
",",
"self",
".",
"_pos",
"[",
"0",
",",
"1",
"]",
")",
"return",
"None"
] |
Return the (min, max) bounding values of this visual along *axis*
in the local coordinate system.
|
[
"Return",
"the",
"(",
"min",
"max",
")",
"bounding",
"values",
"of",
"this",
"visual",
"along",
"*",
"axis",
"*",
"in",
"the",
"local",
"coordinate",
"system",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/infinite_line.py#L130-L141
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/curves.py
|
curve3_bezier
|
def curve3_bezier(p1, p2, p3):
"""
Generate the vertices for a quadratic Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve4_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
points = []
_curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3)
dx, dy = points[0][0] - x1, points[0][1] - y1
if (dx * dx + dy * dy) > 1e-10:
points.insert(0, (x1, y1))
dx, dy = points[-1][0] - x3, points[-1][1] - y3
if (dx * dx + dy * dy) > 1e-10:
points.append((x3, y3))
return np.array(points).reshape(len(points), 2)
|
python
|
def curve3_bezier(p1, p2, p3):
"""
Generate the vertices for a quadratic Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve4_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
points = []
_curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3)
dx, dy = points[0][0] - x1, points[0][1] - y1
if (dx * dx + dy * dy) > 1e-10:
points.insert(0, (x1, y1))
dx, dy = points[-1][0] - x3, points[-1][1] - y3
if (dx * dx + dy * dy) > 1e-10:
points.append((x3, y3))
return np.array(points).reshape(len(points), 2)
|
[
"def",
"curve3_bezier",
"(",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"x1",
",",
"y1",
"=",
"p1",
"x2",
",",
"y2",
"=",
"p2",
"x3",
",",
"y3",
"=",
"p3",
"points",
"=",
"[",
"]",
"_curve3_recursive_bezier",
"(",
"points",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
")",
"dx",
",",
"dy",
"=",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"x1",
",",
"points",
"[",
"0",
"]",
"[",
"1",
"]",
"-",
"y1",
"if",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
">",
"1e-10",
":",
"points",
".",
"insert",
"(",
"0",
",",
"(",
"x1",
",",
"y1",
")",
")",
"dx",
",",
"dy",
"=",
"points",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"-",
"x3",
",",
"points",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"-",
"y3",
"if",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
">",
"1e-10",
":",
"points",
".",
"append",
"(",
"(",
"x3",
",",
"y3",
")",
")",
"return",
"np",
".",
"array",
"(",
"points",
")",
".",
"reshape",
"(",
"len",
"(",
"points",
")",
",",
"2",
")"
] |
Generate the vertices for a quadratic Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve4_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
|
[
"Generate",
"the",
"vertices",
"for",
"a",
"quadratic",
"Bezier",
"curve",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/curves.py#L302-L348
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/curves.py
|
curve4_bezier
|
def curve4_bezier(p1, p2, p3, p4):
"""
Generate the vertices for a third order Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the second curve point
p4 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve3_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
x4, y4 = p4
points = []
_curve4_recursive_bezier(points, x1, y1, x2, y2, x3, y3, x4, y4)
dx, dy = points[0][0] - x1, points[0][1] - y1
if (dx * dx + dy * dy) > 1e-10:
points.insert(0, (x1, y1))
dx, dy = points[-1][0] - x4, points[-1][1] - y4
if (dx * dx + dy * dy) > 1e-10:
points.append((x4, y4))
return np.array(points).reshape(len(points), 2)
|
python
|
def curve4_bezier(p1, p2, p3, p4):
"""
Generate the vertices for a third order Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the second curve point
p4 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve3_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
x4, y4 = p4
points = []
_curve4_recursive_bezier(points, x1, y1, x2, y2, x3, y3, x4, y4)
dx, dy = points[0][0] - x1, points[0][1] - y1
if (dx * dx + dy * dy) > 1e-10:
points.insert(0, (x1, y1))
dx, dy = points[-1][0] - x4, points[-1][1] - y4
if (dx * dx + dy * dy) > 1e-10:
points.append((x4, y4))
return np.array(points).reshape(len(points), 2)
|
[
"def",
"curve4_bezier",
"(",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
")",
":",
"x1",
",",
"y1",
"=",
"p1",
"x2",
",",
"y2",
"=",
"p2",
"x3",
",",
"y3",
"=",
"p3",
"x4",
",",
"y4",
"=",
"p4",
"points",
"=",
"[",
"]",
"_curve4_recursive_bezier",
"(",
"points",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"x4",
",",
"y4",
")",
"dx",
",",
"dy",
"=",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
"-",
"x1",
",",
"points",
"[",
"0",
"]",
"[",
"1",
"]",
"-",
"y1",
"if",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
">",
"1e-10",
":",
"points",
".",
"insert",
"(",
"0",
",",
"(",
"x1",
",",
"y1",
")",
")",
"dx",
",",
"dy",
"=",
"points",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"-",
"x4",
",",
"points",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"-",
"y4",
"if",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
">",
"1e-10",
":",
"points",
".",
"append",
"(",
"(",
"x4",
",",
"y4",
")",
")",
"return",
"np",
".",
"array",
"(",
"points",
")",
".",
"reshape",
"(",
"len",
"(",
"points",
")",
",",
"2",
")"
] |
Generate the vertices for a third order Bezier curve.
The vertices returned by this function can be passed to a LineVisual or
ArrowVisual.
Parameters
----------
p1 : array
2D coordinates of the start point
p2 : array
2D coordinates of the first curve point
p3 : array
2D coordinates of the second curve point
p4 : array
2D coordinates of the end point
Returns
-------
coords : list
Vertices for the Bezier curve.
See Also
--------
curve3_bezier
Notes
-----
For more information about Bezier curves please refer to the `Wikipedia`_
page.
.. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
|
[
"Generate",
"the",
"vertices",
"for",
"a",
"third",
"order",
"Bezier",
"curve",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/curves.py#L351-L399
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/text/_sdf.py
|
SDFRenderer.render_to_texture
|
def render_to_texture(self, data, texture, offset, size):
"""Render a SDF to a texture at a given offset and size
Parameters
----------
data : array
Must be 2D with type np.ubyte.
texture : instance of Texture2D
The texture to render to.
offset : tuple of int
Offset (x, y) to render to inside the texture.
size : tuple of int
Size (w, h) to render inside the texture.
"""
assert isinstance(texture, Texture2D)
set_state(blend=False, depth_test=False)
# calculate the negative half (within object)
orig_tex = Texture2D(255 - data, format='luminance',
wrapping='clamp_to_edge', interpolation='nearest')
edf_neg_tex = self._render_edf(orig_tex)
# calculate positive half (outside object)
orig_tex[:, :, 0] = data
edf_pos_tex = self._render_edf(orig_tex)
# render final product to output texture
self.program_insert['u_texture'] = orig_tex
self.program_insert['u_pos_texture'] = edf_pos_tex
self.program_insert['u_neg_texture'] = edf_neg_tex
self.fbo_to[-1].color_buffer = texture
with self.fbo_to[-1]:
set_viewport(tuple(offset) + tuple(size))
self.program_insert.draw('triangle_strip')
|
python
|
def render_to_texture(self, data, texture, offset, size):
"""Render a SDF to a texture at a given offset and size
Parameters
----------
data : array
Must be 2D with type np.ubyte.
texture : instance of Texture2D
The texture to render to.
offset : tuple of int
Offset (x, y) to render to inside the texture.
size : tuple of int
Size (w, h) to render inside the texture.
"""
assert isinstance(texture, Texture2D)
set_state(blend=False, depth_test=False)
# calculate the negative half (within object)
orig_tex = Texture2D(255 - data, format='luminance',
wrapping='clamp_to_edge', interpolation='nearest')
edf_neg_tex = self._render_edf(orig_tex)
# calculate positive half (outside object)
orig_tex[:, :, 0] = data
edf_pos_tex = self._render_edf(orig_tex)
# render final product to output texture
self.program_insert['u_texture'] = orig_tex
self.program_insert['u_pos_texture'] = edf_pos_tex
self.program_insert['u_neg_texture'] = edf_neg_tex
self.fbo_to[-1].color_buffer = texture
with self.fbo_to[-1]:
set_viewport(tuple(offset) + tuple(size))
self.program_insert.draw('triangle_strip')
|
[
"def",
"render_to_texture",
"(",
"self",
",",
"data",
",",
"texture",
",",
"offset",
",",
"size",
")",
":",
"assert",
"isinstance",
"(",
"texture",
",",
"Texture2D",
")",
"set_state",
"(",
"blend",
"=",
"False",
",",
"depth_test",
"=",
"False",
")",
"# calculate the negative half (within object)",
"orig_tex",
"=",
"Texture2D",
"(",
"255",
"-",
"data",
",",
"format",
"=",
"'luminance'",
",",
"wrapping",
"=",
"'clamp_to_edge'",
",",
"interpolation",
"=",
"'nearest'",
")",
"edf_neg_tex",
"=",
"self",
".",
"_render_edf",
"(",
"orig_tex",
")",
"# calculate positive half (outside object)",
"orig_tex",
"[",
":",
",",
":",
",",
"0",
"]",
"=",
"data",
"edf_pos_tex",
"=",
"self",
".",
"_render_edf",
"(",
"orig_tex",
")",
"# render final product to output texture",
"self",
".",
"program_insert",
"[",
"'u_texture'",
"]",
"=",
"orig_tex",
"self",
".",
"program_insert",
"[",
"'u_pos_texture'",
"]",
"=",
"edf_pos_tex",
"self",
".",
"program_insert",
"[",
"'u_neg_texture'",
"]",
"=",
"edf_neg_tex",
"self",
".",
"fbo_to",
"[",
"-",
"1",
"]",
".",
"color_buffer",
"=",
"texture",
"with",
"self",
".",
"fbo_to",
"[",
"-",
"1",
"]",
":",
"set_viewport",
"(",
"tuple",
"(",
"offset",
")",
"+",
"tuple",
"(",
"size",
")",
")",
"self",
".",
"program_insert",
".",
"draw",
"(",
"'triangle_strip'",
")"
] |
Render a SDF to a texture at a given offset and size
Parameters
----------
data : array
Must be 2D with type np.ubyte.
texture : instance of Texture2D
The texture to render to.
offset : tuple of int
Offset (x, y) to render to inside the texture.
size : tuple of int
Size (w, h) to render inside the texture.
|
[
"Render",
"a",
"SDF",
"to",
"a",
"texture",
"at",
"a",
"given",
"offset",
"and",
"size"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/text/_sdf.py#L252-L286
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/text/_sdf.py
|
SDFRenderer._render_edf
|
def _render_edf(self, orig_tex):
"""Render an EDF to a texture"""
# Set up the necessary textures
sdf_size = orig_tex.shape[:2]
comp_texs = []
for _ in range(2):
tex = Texture2D(sdf_size + (4,), format='rgba',
interpolation='nearest', wrapping='clamp_to_edge')
comp_texs.append(tex)
self.fbo_to[0].color_buffer = comp_texs[0]
self.fbo_to[1].color_buffer = comp_texs[1]
for program in self.programs[1:]: # program_seed does not need this
program['u_texh'], program['u_texw'] = sdf_size
# Do the rendering
last_rend = 0
with self.fbo_to[last_rend]:
set_viewport(0, 0, sdf_size[1], sdf_size[0])
self.program_seed['u_texture'] = orig_tex
self.program_seed.draw('triangle_strip')
stepsize = (np.array(sdf_size) // 2).max()
while stepsize > 0:
self.program_flood['u_step'] = stepsize
self.program_flood['u_texture'] = comp_texs[last_rend]
last_rend = 1 if last_rend == 0 else 0
with self.fbo_to[last_rend]:
set_viewport(0, 0, sdf_size[1], sdf_size[0])
self.program_flood.draw('triangle_strip')
stepsize //= 2
return comp_texs[last_rend]
|
python
|
def _render_edf(self, orig_tex):
"""Render an EDF to a texture"""
# Set up the necessary textures
sdf_size = orig_tex.shape[:2]
comp_texs = []
for _ in range(2):
tex = Texture2D(sdf_size + (4,), format='rgba',
interpolation='nearest', wrapping='clamp_to_edge')
comp_texs.append(tex)
self.fbo_to[0].color_buffer = comp_texs[0]
self.fbo_to[1].color_buffer = comp_texs[1]
for program in self.programs[1:]: # program_seed does not need this
program['u_texh'], program['u_texw'] = sdf_size
# Do the rendering
last_rend = 0
with self.fbo_to[last_rend]:
set_viewport(0, 0, sdf_size[1], sdf_size[0])
self.program_seed['u_texture'] = orig_tex
self.program_seed.draw('triangle_strip')
stepsize = (np.array(sdf_size) // 2).max()
while stepsize > 0:
self.program_flood['u_step'] = stepsize
self.program_flood['u_texture'] = comp_texs[last_rend]
last_rend = 1 if last_rend == 0 else 0
with self.fbo_to[last_rend]:
set_viewport(0, 0, sdf_size[1], sdf_size[0])
self.program_flood.draw('triangle_strip')
stepsize //= 2
return comp_texs[last_rend]
|
[
"def",
"_render_edf",
"(",
"self",
",",
"orig_tex",
")",
":",
"# Set up the necessary textures",
"sdf_size",
"=",
"orig_tex",
".",
"shape",
"[",
":",
"2",
"]",
"comp_texs",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"2",
")",
":",
"tex",
"=",
"Texture2D",
"(",
"sdf_size",
"+",
"(",
"4",
",",
")",
",",
"format",
"=",
"'rgba'",
",",
"interpolation",
"=",
"'nearest'",
",",
"wrapping",
"=",
"'clamp_to_edge'",
")",
"comp_texs",
".",
"append",
"(",
"tex",
")",
"self",
".",
"fbo_to",
"[",
"0",
"]",
".",
"color_buffer",
"=",
"comp_texs",
"[",
"0",
"]",
"self",
".",
"fbo_to",
"[",
"1",
"]",
".",
"color_buffer",
"=",
"comp_texs",
"[",
"1",
"]",
"for",
"program",
"in",
"self",
".",
"programs",
"[",
"1",
":",
"]",
":",
"# program_seed does not need this",
"program",
"[",
"'u_texh'",
"]",
",",
"program",
"[",
"'u_texw'",
"]",
"=",
"sdf_size",
"# Do the rendering",
"last_rend",
"=",
"0",
"with",
"self",
".",
"fbo_to",
"[",
"last_rend",
"]",
":",
"set_viewport",
"(",
"0",
",",
"0",
",",
"sdf_size",
"[",
"1",
"]",
",",
"sdf_size",
"[",
"0",
"]",
")",
"self",
".",
"program_seed",
"[",
"'u_texture'",
"]",
"=",
"orig_tex",
"self",
".",
"program_seed",
".",
"draw",
"(",
"'triangle_strip'",
")",
"stepsize",
"=",
"(",
"np",
".",
"array",
"(",
"sdf_size",
")",
"//",
"2",
")",
".",
"max",
"(",
")",
"while",
"stepsize",
">",
"0",
":",
"self",
".",
"program_flood",
"[",
"'u_step'",
"]",
"=",
"stepsize",
"self",
".",
"program_flood",
"[",
"'u_texture'",
"]",
"=",
"comp_texs",
"[",
"last_rend",
"]",
"last_rend",
"=",
"1",
"if",
"last_rend",
"==",
"0",
"else",
"0",
"with",
"self",
".",
"fbo_to",
"[",
"last_rend",
"]",
":",
"set_viewport",
"(",
"0",
",",
"0",
",",
"sdf_size",
"[",
"1",
"]",
",",
"sdf_size",
"[",
"0",
"]",
")",
"self",
".",
"program_flood",
".",
"draw",
"(",
"'triangle_strip'",
")",
"stepsize",
"//=",
"2",
"return",
"comp_texs",
"[",
"last_rend",
"]"
] |
Render an EDF to a texture
|
[
"Render",
"an",
"EDF",
"to",
"a",
"texture"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/text/_sdf.py#L288-L318
|
train
|
anjishnu/ask-alexa-pykit
|
ask/intent_schema.py
|
IntentSchema._add_intent_interactive
|
def _add_intent_interactive(self, intent_num=0):
'''
Interactively add a new intent to the intent schema object
'''
print ("Name of intent number : ", intent_num)
slot_type_mappings = load_builtin_slots()
intent_name = read_from_user(str)
print ("How many slots?")
num_slots = read_from_user(int)
slot_list = []
for i in range(num_slots):
print ("Slot name no.", i+1)
slot_name = read_from_user(str).strip()
print ("Slot type? Enter a number for AMAZON supported types below,"
"else enter a string for a Custom Slot")
print (json.dumps(slot_type_mappings, indent=True))
slot_type_str = read_from_user(str)
try: slot_type = slot_type_mappings[int(slot_type_str)]['name']
except: slot_type = slot_type_str
slot_list += [self.build_slot(slot_name, slot_type)]
self.add_intent(intent_name, slot_list)
|
python
|
def _add_intent_interactive(self, intent_num=0):
'''
Interactively add a new intent to the intent schema object
'''
print ("Name of intent number : ", intent_num)
slot_type_mappings = load_builtin_slots()
intent_name = read_from_user(str)
print ("How many slots?")
num_slots = read_from_user(int)
slot_list = []
for i in range(num_slots):
print ("Slot name no.", i+1)
slot_name = read_from_user(str).strip()
print ("Slot type? Enter a number for AMAZON supported types below,"
"else enter a string for a Custom Slot")
print (json.dumps(slot_type_mappings, indent=True))
slot_type_str = read_from_user(str)
try: slot_type = slot_type_mappings[int(slot_type_str)]['name']
except: slot_type = slot_type_str
slot_list += [self.build_slot(slot_name, slot_type)]
self.add_intent(intent_name, slot_list)
|
[
"def",
"_add_intent_interactive",
"(",
"self",
",",
"intent_num",
"=",
"0",
")",
":",
"print",
"(",
"\"Name of intent number : \"",
",",
"intent_num",
")",
"slot_type_mappings",
"=",
"load_builtin_slots",
"(",
")",
"intent_name",
"=",
"read_from_user",
"(",
"str",
")",
"print",
"(",
"\"How many slots?\"",
")",
"num_slots",
"=",
"read_from_user",
"(",
"int",
")",
"slot_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_slots",
")",
":",
"print",
"(",
"\"Slot name no.\"",
",",
"i",
"+",
"1",
")",
"slot_name",
"=",
"read_from_user",
"(",
"str",
")",
".",
"strip",
"(",
")",
"print",
"(",
"\"Slot type? Enter a number for AMAZON supported types below,\"",
"\"else enter a string for a Custom Slot\"",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"slot_type_mappings",
",",
"indent",
"=",
"True",
")",
")",
"slot_type_str",
"=",
"read_from_user",
"(",
"str",
")",
"try",
":",
"slot_type",
"=",
"slot_type_mappings",
"[",
"int",
"(",
"slot_type_str",
")",
"]",
"[",
"'name'",
"]",
"except",
":",
"slot_type",
"=",
"slot_type_str",
"slot_list",
"+=",
"[",
"self",
".",
"build_slot",
"(",
"slot_name",
",",
"slot_type",
")",
"]",
"self",
".",
"add_intent",
"(",
"intent_name",
",",
"slot_list",
")"
] |
Interactively add a new intent to the intent schema object
|
[
"Interactively",
"add",
"a",
"new",
"intent",
"to",
"the",
"intent",
"schema",
"object"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/intent_schema.py#L65-L85
|
train
|
anjishnu/ask-alexa-pykit
|
ask/intent_schema.py
|
IntentSchema.from_filename
|
def from_filename(self, filename):
'''
Build an IntentSchema from a file path
creates a new intent schema if the file does not exist, throws an error if the file
exists but cannot be loaded as a JSON
'''
if os.path.exists(filename):
with open(filename) as fp:
return IntentSchema(json.load(fp, object_pairs_hook=OrderedDict))
else:
print ('File does not exist')
return IntentSchema()
|
python
|
def from_filename(self, filename):
'''
Build an IntentSchema from a file path
creates a new intent schema if the file does not exist, throws an error if the file
exists but cannot be loaded as a JSON
'''
if os.path.exists(filename):
with open(filename) as fp:
return IntentSchema(json.load(fp, object_pairs_hook=OrderedDict))
else:
print ('File does not exist')
return IntentSchema()
|
[
"def",
"from_filename",
"(",
"self",
",",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"return",
"IntentSchema",
"(",
"json",
".",
"load",
"(",
"fp",
",",
"object_pairs_hook",
"=",
"OrderedDict",
")",
")",
"else",
":",
"print",
"(",
"'File does not exist'",
")",
"return",
"IntentSchema",
"(",
")"
] |
Build an IntentSchema from a file path
creates a new intent schema if the file does not exist, throws an error if the file
exists but cannot be loaded as a JSON
|
[
"Build",
"an",
"IntentSchema",
"from",
"a",
"file",
"path",
"creates",
"a",
"new",
"intent",
"schema",
"if",
"the",
"file",
"does",
"not",
"exist",
"throws",
"an",
"error",
"if",
"the",
"file",
"exists",
"but",
"cannot",
"be",
"loaded",
"as",
"a",
"JSON"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/intent_schema.py#L89-L100
|
train
|
anjishnu/ask-alexa-pykit
|
examples/twitter/lambda_function.py
|
launch_request_handler
|
def launch_request_handler(request):
""" Annotate functions with @VoiceHandler so that they can be automatically mapped
to request types. Use the 'request_type' field to map them to non-intent requests """
user_id = request.access_token()
if user_id in twitter_cache.users():
user_cache = twitter_cache.get_user_state(user_id)
user_cache["amzn_id"]= request.user_id()
base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"])
print (user_cache)
if 'pending_action' in user_cache:
base_message += " You have one pending action . "
print ("Found pending action")
if 'description' in user_cache['pending_action']:
print ("Found description")
base_message += user_cache['pending_action']['description']
return r.create_response(base_message)
card = r.create_card(title="Please log into twitter", card_type="LinkAccount")
return r.create_response(message="Welcome to twitter, looks like you haven't logged in!"
" Log in via the alexa app.", card_obj=card,
end_session=True)
|
python
|
def launch_request_handler(request):
""" Annotate functions with @VoiceHandler so that they can be automatically mapped
to request types. Use the 'request_type' field to map them to non-intent requests """
user_id = request.access_token()
if user_id in twitter_cache.users():
user_cache = twitter_cache.get_user_state(user_id)
user_cache["amzn_id"]= request.user_id()
base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"])
print (user_cache)
if 'pending_action' in user_cache:
base_message += " You have one pending action . "
print ("Found pending action")
if 'description' in user_cache['pending_action']:
print ("Found description")
base_message += user_cache['pending_action']['description']
return r.create_response(base_message)
card = r.create_card(title="Please log into twitter", card_type="LinkAccount")
return r.create_response(message="Welcome to twitter, looks like you haven't logged in!"
" Log in via the alexa app.", card_obj=card,
end_session=True)
|
[
"def",
"launch_request_handler",
"(",
"request",
")",
":",
"user_id",
"=",
"request",
".",
"access_token",
"(",
")",
"if",
"user_id",
"in",
"twitter_cache",
".",
"users",
"(",
")",
":",
"user_cache",
"=",
"twitter_cache",
".",
"get_user_state",
"(",
"user_id",
")",
"user_cache",
"[",
"\"amzn_id\"",
"]",
"=",
"request",
".",
"user_id",
"(",
")",
"base_message",
"=",
"\"Welcome to Twitter, {} . How may I help you today ?\"",
".",
"format",
"(",
"user_cache",
"[",
"\"screen_name\"",
"]",
")",
"print",
"(",
"user_cache",
")",
"if",
"'pending_action'",
"in",
"user_cache",
":",
"base_message",
"+=",
"\" You have one pending action . \"",
"print",
"(",
"\"Found pending action\"",
")",
"if",
"'description'",
"in",
"user_cache",
"[",
"'pending_action'",
"]",
":",
"print",
"(",
"\"Found description\"",
")",
"base_message",
"+=",
"user_cache",
"[",
"'pending_action'",
"]",
"[",
"'description'",
"]",
"return",
"r",
".",
"create_response",
"(",
"base_message",
")",
"card",
"=",
"r",
".",
"create_card",
"(",
"title",
"=",
"\"Please log into twitter\"",
",",
"card_type",
"=",
"\"LinkAccount\"",
")",
"return",
"r",
".",
"create_response",
"(",
"message",
"=",
"\"Welcome to twitter, looks like you haven't logged in!\"",
"\" Log in via the alexa app.\"",
",",
"card_obj",
"=",
"card",
",",
"end_session",
"=",
"True",
")"
] |
Annotate functions with @VoiceHandler so that they can be automatically mapped
to request types. Use the 'request_type' field to map them to non-intent requests
|
[
"Annotate",
"functions",
"with"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L23-L45
|
train
|
anjishnu/ask-alexa-pykit
|
examples/twitter/lambda_function.py
|
post_tweet_intent_handler
|
def post_tweet_intent_handler(request):
"""
Use the 'intent' field in the VoiceHandler to map to the respective intent.
"""
tweet = request.get_slot_value("Tweet")
tweet = tweet if tweet else ""
if tweet:
user_state = twitter_cache.get_user_state(request.access_token())
def action():
return post_tweet(request.access_token(), tweet)
message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(tweet)
user_state['pending_action'] = {"action" : action,
"description" : message}
return r.create_response(message=message, end_session=False)
else:
# No tweet could be disambiguated
message = " ".join(
[
"I'm sorry, I couldn't understand what you wanted to tweet .",
"Please prepend the message with either post or tweet ."
]
)
return alexa.create_response(message=message, end_session=False)
|
python
|
def post_tweet_intent_handler(request):
"""
Use the 'intent' field in the VoiceHandler to map to the respective intent.
"""
tweet = request.get_slot_value("Tweet")
tweet = tweet if tweet else ""
if tweet:
user_state = twitter_cache.get_user_state(request.access_token())
def action():
return post_tweet(request.access_token(), tweet)
message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(tweet)
user_state['pending_action'] = {"action" : action,
"description" : message}
return r.create_response(message=message, end_session=False)
else:
# No tweet could be disambiguated
message = " ".join(
[
"I'm sorry, I couldn't understand what you wanted to tweet .",
"Please prepend the message with either post or tweet ."
]
)
return alexa.create_response(message=message, end_session=False)
|
[
"def",
"post_tweet_intent_handler",
"(",
"request",
")",
":",
"tweet",
"=",
"request",
".",
"get_slot_value",
"(",
"\"Tweet\"",
")",
"tweet",
"=",
"tweet",
"if",
"tweet",
"else",
"\"\"",
"if",
"tweet",
":",
"user_state",
"=",
"twitter_cache",
".",
"get_user_state",
"(",
"request",
".",
"access_token",
"(",
")",
")",
"def",
"action",
"(",
")",
":",
"return",
"post_tweet",
"(",
"request",
".",
"access_token",
"(",
")",
",",
"tweet",
")",
"message",
"=",
"\"I am ready to post the tweet, {} ,\\n Please say yes to confirm or stop to cancel .\"",
".",
"format",
"(",
"tweet",
")",
"user_state",
"[",
"'pending_action'",
"]",
"=",
"{",
"\"action\"",
":",
"action",
",",
"\"description\"",
":",
"message",
"}",
"return",
"r",
".",
"create_response",
"(",
"message",
"=",
"message",
",",
"end_session",
"=",
"False",
")",
"else",
":",
"# No tweet could be disambiguated",
"message",
"=",
"\" \"",
".",
"join",
"(",
"[",
"\"I'm sorry, I couldn't understand what you wanted to tweet .\"",
",",
"\"Please prepend the message with either post or tweet .\"",
"]",
")",
"return",
"alexa",
".",
"create_response",
"(",
"message",
"=",
"message",
",",
"end_session",
"=",
"False",
")"
] |
Use the 'intent' field in the VoiceHandler to map to the respective intent.
|
[
"Use",
"the",
"intent",
"field",
"in",
"the",
"VoiceHandler",
"to",
"map",
"to",
"the",
"respective",
"intent",
"."
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L54-L77
|
train
|
anjishnu/ask-alexa-pykit
|
examples/twitter/lambda_function.py
|
tweet_list_handler
|
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):
""" This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
tweets = tweet_list_builder(request.access_token())
print (len(tweets), 'tweets found')
if tweets:
twitter_cache.initialize_user_queue(user_id=request.access_token(),
queue=tweets)
text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)
message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number."
return alexa.create_response(message=message,
end_session=False)
else:
return alexa.create_response(message="Sorry, no tweets found, please try something else",
end_session=False)
|
python
|
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):
""" This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
tweets = tweet_list_builder(request.access_token())
print (len(tweets), 'tweets found')
if tweets:
twitter_cache.initialize_user_queue(user_id=request.access_token(),
queue=tweets)
text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)
message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number."
return alexa.create_response(message=message,
end_session=False)
else:
return alexa.create_response(message="Sorry, no tweets found, please try something else",
end_session=False)
|
[
"def",
"tweet_list_handler",
"(",
"request",
",",
"tweet_list_builder",
",",
"msg_prefix",
"=",
"\"\"",
")",
":",
"# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say",
"tweets",
"=",
"tweet_list_builder",
"(",
"request",
".",
"access_token",
"(",
")",
")",
"print",
"(",
"len",
"(",
"tweets",
")",
",",
"'tweets found'",
")",
"if",
"tweets",
":",
"twitter_cache",
".",
"initialize_user_queue",
"(",
"user_id",
"=",
"request",
".",
"access_token",
"(",
")",
",",
"queue",
"=",
"tweets",
")",
"text_to_read_out",
"=",
"twitter_cache",
".",
"user_queue",
"(",
"request",
".",
"access_token",
"(",
")",
")",
".",
"read_out_next",
"(",
"MAX_RESPONSE_TWEETS",
")",
"message",
"=",
"msg_prefix",
"+",
"text_to_read_out",
"+",
"\", say 'next' to hear more, or reply to a tweet by number.\"",
"return",
"alexa",
".",
"create_response",
"(",
"message",
"=",
"message",
",",
"end_session",
"=",
"False",
")",
"else",
":",
"return",
"alexa",
".",
"create_response",
"(",
"message",
"=",
"\"Sorry, no tweets found, please try something else\"",
",",
"end_session",
"=",
"False",
")"
] |
This is a generic function to handle any intent that reads out a list of tweets
|
[
"This",
"is",
"a",
"generic",
"function",
"to",
"handle",
"any",
"intent",
"that",
"reads",
"out",
"a",
"list",
"of",
"tweets"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L137-L152
|
train
|
anjishnu/ask-alexa-pykit
|
examples/twitter/lambda_function.py
|
focused_on_tweet
|
def focused_on_tweet(request):
"""
Return index if focused on tweet False if couldn't
"""
slots = request.get_slot_map()
if "Index" in slots and slots["Index"]:
index = int(slots['Index'])
elif "Ordinal" in slots and slots["Index"]:
parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits]))
index = parse_ordinal(slots['Ordinal'])
else:
return False
index = index - 1 # Going from regular notation to CS notation
user_state = twitter_cache.get_user_state(request.access_token())
queue = user_state['user_queue'].queue()
if index < len(queue):
# Analyze tweet in queue
tweet_to_analyze = queue[index]
user_state['focus_tweet'] = tweet_to_analyze
return index + 1 # Returning to regular notation
twitter_cache.serialize()
return False
|
python
|
def focused_on_tweet(request):
"""
Return index if focused on tweet False if couldn't
"""
slots = request.get_slot_map()
if "Index" in slots and slots["Index"]:
index = int(slots['Index'])
elif "Ordinal" in slots and slots["Index"]:
parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits]))
index = parse_ordinal(slots['Ordinal'])
else:
return False
index = index - 1 # Going from regular notation to CS notation
user_state = twitter_cache.get_user_state(request.access_token())
queue = user_state['user_queue'].queue()
if index < len(queue):
# Analyze tweet in queue
tweet_to_analyze = queue[index]
user_state['focus_tweet'] = tweet_to_analyze
return index + 1 # Returning to regular notation
twitter_cache.serialize()
return False
|
[
"def",
"focused_on_tweet",
"(",
"request",
")",
":",
"slots",
"=",
"request",
".",
"get_slot_map",
"(",
")",
"if",
"\"Index\"",
"in",
"slots",
"and",
"slots",
"[",
"\"Index\"",
"]",
":",
"index",
"=",
"int",
"(",
"slots",
"[",
"'Index'",
"]",
")",
"elif",
"\"Ordinal\"",
"in",
"slots",
"and",
"slots",
"[",
"\"Index\"",
"]",
":",
"parse_ordinal",
"=",
"lambda",
"inp",
":",
"int",
"(",
"\"\"",
".",
"join",
"(",
"[",
"l",
"for",
"l",
"in",
"inp",
"if",
"l",
"in",
"string",
".",
"digits",
"]",
")",
")",
"index",
"=",
"parse_ordinal",
"(",
"slots",
"[",
"'Ordinal'",
"]",
")",
"else",
":",
"return",
"False",
"index",
"=",
"index",
"-",
"1",
"# Going from regular notation to CS notation",
"user_state",
"=",
"twitter_cache",
".",
"get_user_state",
"(",
"request",
".",
"access_token",
"(",
")",
")",
"queue",
"=",
"user_state",
"[",
"'user_queue'",
"]",
".",
"queue",
"(",
")",
"if",
"index",
"<",
"len",
"(",
"queue",
")",
":",
"# Analyze tweet in queue",
"tweet_to_analyze",
"=",
"queue",
"[",
"index",
"]",
"user_state",
"[",
"'focus_tweet'",
"]",
"=",
"tweet_to_analyze",
"return",
"index",
"+",
"1",
"# Returning to regular notation",
"twitter_cache",
".",
"serialize",
"(",
")",
"return",
"False"
] |
Return index if focused on tweet False if couldn't
|
[
"Return",
"index",
"if",
"focused",
"on",
"tweet",
"False",
"if",
"couldn",
"t"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L198-L221
|
train
|
anjishnu/ask-alexa-pykit
|
examples/twitter/lambda_function.py
|
next_intent_handler
|
def next_intent_handler(request):
"""
Takes care of things whenver the user says 'next'
"""
message = "Sorry, couldn't find anything in your next queue"
end_session = True
if True:
user_queue = twitter_cache.user_queue(request.access_token())
if not user_queue.is_finished():
message = user_queue.read_out_next(MAX_RESPONSE_TWEETS)
if not user_queue.is_finished():
end_session = False
message = message + ". Please, say 'next' if you want me to read out more. "
return alexa.create_response(message=message,
end_session=end_session)
|
python
|
def next_intent_handler(request):
"""
Takes care of things whenver the user says 'next'
"""
message = "Sorry, couldn't find anything in your next queue"
end_session = True
if True:
user_queue = twitter_cache.user_queue(request.access_token())
if not user_queue.is_finished():
message = user_queue.read_out_next(MAX_RESPONSE_TWEETS)
if not user_queue.is_finished():
end_session = False
message = message + ". Please, say 'next' if you want me to read out more. "
return alexa.create_response(message=message,
end_session=end_session)
|
[
"def",
"next_intent_handler",
"(",
"request",
")",
":",
"message",
"=",
"\"Sorry, couldn't find anything in your next queue\"",
"end_session",
"=",
"True",
"if",
"True",
":",
"user_queue",
"=",
"twitter_cache",
".",
"user_queue",
"(",
"request",
".",
"access_token",
"(",
")",
")",
"if",
"not",
"user_queue",
".",
"is_finished",
"(",
")",
":",
"message",
"=",
"user_queue",
".",
"read_out_next",
"(",
"MAX_RESPONSE_TWEETS",
")",
"if",
"not",
"user_queue",
".",
"is_finished",
"(",
")",
":",
"end_session",
"=",
"False",
"message",
"=",
"message",
"+",
"\". Please, say 'next' if you want me to read out more. \"",
"return",
"alexa",
".",
"create_response",
"(",
"message",
"=",
"message",
",",
"end_session",
"=",
"end_session",
")"
] |
Takes care of things whenver the user says 'next'
|
[
"Takes",
"care",
"of",
"things",
"whenver",
"the",
"user",
"says",
"next"
] |
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
|
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L322-L337
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/app/_default_app.py
|
use_app
|
def use_app(backend_name=None, call_reuse=True):
""" Get/create the default Application object
It is safe to call this function multiple times, as long as
backend_name is None or matches the already selected backend.
Parameters
----------
backend_name : str | None
The name of the backend application to use. If not specified, Vispy
tries to select a backend automatically. See ``vispy.use()`` for
details.
call_reuse : bool
Whether to call the backend's `reuse()` function (True by default).
Not implemented by default, but some backends need it. For example,
the notebook backends need to inject some JavaScript in a notebook as
soon as `use_app()` is called.
"""
global default_app
# If we already have a default_app, raise error or return
if default_app is not None:
names = default_app.backend_name.lower().replace('(', ' ').strip(') ')
names = [name for name in names.split(' ') if name]
if backend_name and backend_name.lower() not in names:
raise RuntimeError('Can only select a backend once, already using '
'%s.' % names)
else:
if call_reuse:
default_app.reuse()
return default_app # Current backend matches backend_name
# Create default app
default_app = Application(backend_name)
return default_app
|
python
|
def use_app(backend_name=None, call_reuse=True):
""" Get/create the default Application object
It is safe to call this function multiple times, as long as
backend_name is None or matches the already selected backend.
Parameters
----------
backend_name : str | None
The name of the backend application to use. If not specified, Vispy
tries to select a backend automatically. See ``vispy.use()`` for
details.
call_reuse : bool
Whether to call the backend's `reuse()` function (True by default).
Not implemented by default, but some backends need it. For example,
the notebook backends need to inject some JavaScript in a notebook as
soon as `use_app()` is called.
"""
global default_app
# If we already have a default_app, raise error or return
if default_app is not None:
names = default_app.backend_name.lower().replace('(', ' ').strip(') ')
names = [name for name in names.split(' ') if name]
if backend_name and backend_name.lower() not in names:
raise RuntimeError('Can only select a backend once, already using '
'%s.' % names)
else:
if call_reuse:
default_app.reuse()
return default_app # Current backend matches backend_name
# Create default app
default_app = Application(backend_name)
return default_app
|
[
"def",
"use_app",
"(",
"backend_name",
"=",
"None",
",",
"call_reuse",
"=",
"True",
")",
":",
"global",
"default_app",
"# If we already have a default_app, raise error or return",
"if",
"default_app",
"is",
"not",
"None",
":",
"names",
"=",
"default_app",
".",
"backend_name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'('",
",",
"' '",
")",
".",
"strip",
"(",
"') '",
")",
"names",
"=",
"[",
"name",
"for",
"name",
"in",
"names",
".",
"split",
"(",
"' '",
")",
"if",
"name",
"]",
"if",
"backend_name",
"and",
"backend_name",
".",
"lower",
"(",
")",
"not",
"in",
"names",
":",
"raise",
"RuntimeError",
"(",
"'Can only select a backend once, already using '",
"'%s.'",
"%",
"names",
")",
"else",
":",
"if",
"call_reuse",
":",
"default_app",
".",
"reuse",
"(",
")",
"return",
"default_app",
"# Current backend matches backend_name",
"# Create default app",
"default_app",
"=",
"Application",
"(",
"backend_name",
")",
"return",
"default_app"
] |
Get/create the default Application object
It is safe to call this function multiple times, as long as
backend_name is None or matches the already selected backend.
Parameters
----------
backend_name : str | None
The name of the backend application to use. If not specified, Vispy
tries to select a backend automatically. See ``vispy.use()`` for
details.
call_reuse : bool
Whether to call the backend's `reuse()` function (True by default).
Not implemented by default, but some backends need it. For example,
the notebook backends need to inject some JavaScript in a notebook as
soon as `use_app()` is called.
|
[
"Get",
"/",
"create",
"the",
"default",
"Application",
"object"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/_default_app.py#L13-L48
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py
|
glBufferData
|
def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = ctypes.c_voidp(0)
else:
if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
data = data.copy('C')
data_ = data
size = data_.nbytes
data = data_.ctypes.data
res = _lib.glBufferData(target, size, data, usage)
|
python
|
def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = ctypes.c_voidp(0)
else:
if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
data = data.copy('C')
data_ = data
size = data_.nbytes
data = data_.ctypes.data
res = _lib.glBufferData(target, size, data, usage)
|
[
"def",
"glBufferData",
"(",
"target",
",",
"data",
",",
"usage",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"size",
"=",
"data",
"data",
"=",
"ctypes",
".",
"c_voidp",
"(",
"0",
")",
"else",
":",
"if",
"not",
"data",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
"or",
"not",
"data",
".",
"flags",
"[",
"'ALIGNED'",
"]",
":",
"data",
"=",
"data",
".",
"copy",
"(",
"'C'",
")",
"data_",
"=",
"data",
"size",
"=",
"data_",
".",
"nbytes",
"data",
"=",
"data_",
".",
"ctypes",
".",
"data",
"res",
"=",
"_lib",
".",
"glBufferData",
"(",
"target",
",",
"size",
",",
"data",
",",
"usage",
")"
] |
Data can be numpy array or the size of data to allocate.
|
[
"Data",
"can",
"be",
"numpy",
"array",
"or",
"the",
"size",
"of",
"data",
"to",
"allocate",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py#L88-L100
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/mesh.py
|
MeshVisual.set_data
|
def set_data(self, vertices=None, faces=None, vertex_colors=None,
face_colors=None, color=None, meshdata=None):
"""Set the mesh data
Parameters
----------
vertices : array-like | None
The vertices.
faces : array-like | None
The faces.
vertex_colors : array-like | None
Colors to use for each vertex.
face_colors : array-like | None
Colors to use for each face.
color : instance of Color
The color to use.
meshdata : instance of MeshData | None
The meshdata.
"""
if meshdata is not None:
self._meshdata = meshdata
else:
self._meshdata = MeshData(vertices=vertices, faces=faces,
vertex_colors=vertex_colors,
face_colors=face_colors)
self._bounds = self._meshdata.get_bounds()
if color is not None:
self._color = Color(color)
self.mesh_data_changed()
|
python
|
def set_data(self, vertices=None, faces=None, vertex_colors=None,
face_colors=None, color=None, meshdata=None):
"""Set the mesh data
Parameters
----------
vertices : array-like | None
The vertices.
faces : array-like | None
The faces.
vertex_colors : array-like | None
Colors to use for each vertex.
face_colors : array-like | None
Colors to use for each face.
color : instance of Color
The color to use.
meshdata : instance of MeshData | None
The meshdata.
"""
if meshdata is not None:
self._meshdata = meshdata
else:
self._meshdata = MeshData(vertices=vertices, faces=faces,
vertex_colors=vertex_colors,
face_colors=face_colors)
self._bounds = self._meshdata.get_bounds()
if color is not None:
self._color = Color(color)
self.mesh_data_changed()
|
[
"def",
"set_data",
"(",
"self",
",",
"vertices",
"=",
"None",
",",
"faces",
"=",
"None",
",",
"vertex_colors",
"=",
"None",
",",
"face_colors",
"=",
"None",
",",
"color",
"=",
"None",
",",
"meshdata",
"=",
"None",
")",
":",
"if",
"meshdata",
"is",
"not",
"None",
":",
"self",
".",
"_meshdata",
"=",
"meshdata",
"else",
":",
"self",
".",
"_meshdata",
"=",
"MeshData",
"(",
"vertices",
"=",
"vertices",
",",
"faces",
"=",
"faces",
",",
"vertex_colors",
"=",
"vertex_colors",
",",
"face_colors",
"=",
"face_colors",
")",
"self",
".",
"_bounds",
"=",
"self",
".",
"_meshdata",
".",
"get_bounds",
"(",
")",
"if",
"color",
"is",
"not",
"None",
":",
"self",
".",
"_color",
"=",
"Color",
"(",
"color",
")",
"self",
".",
"mesh_data_changed",
"(",
")"
] |
Set the mesh data
Parameters
----------
vertices : array-like | None
The vertices.
faces : array-like | None
The faces.
vertex_colors : array-like | None
Colors to use for each vertex.
face_colors : array-like | None
Colors to use for each face.
color : instance of Color
The color to use.
meshdata : instance of MeshData | None
The meshdata.
|
[
"Set",
"the",
"mesh",
"data"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/mesh.py#L212-L240
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
BaseVisual.bounds
|
def bounds(self, axis, view=None):
"""Get the bounds of the Visual
Parameters
----------
axis : int
The axis.
view : instance of VisualView
The view to use.
"""
if view is None:
view = self
if axis not in self._vshare.bounds:
self._vshare.bounds[axis] = self._compute_bounds(axis, view)
return self._vshare.bounds[axis]
|
python
|
def bounds(self, axis, view=None):
"""Get the bounds of the Visual
Parameters
----------
axis : int
The axis.
view : instance of VisualView
The view to use.
"""
if view is None:
view = self
if axis not in self._vshare.bounds:
self._vshare.bounds[axis] = self._compute_bounds(axis, view)
return self._vshare.bounds[axis]
|
[
"def",
"bounds",
"(",
"self",
",",
"axis",
",",
"view",
"=",
"None",
")",
":",
"if",
"view",
"is",
"None",
":",
"view",
"=",
"self",
"if",
"axis",
"not",
"in",
"self",
".",
"_vshare",
".",
"bounds",
":",
"self",
".",
"_vshare",
".",
"bounds",
"[",
"axis",
"]",
"=",
"self",
".",
"_compute_bounds",
"(",
"axis",
",",
"view",
")",
"return",
"self",
".",
"_vshare",
".",
"bounds",
"[",
"axis",
"]"
] |
Get the bounds of the Visual
Parameters
----------
axis : int
The axis.
view : instance of VisualView
The view to use.
|
[
"Get",
"the",
"bounds",
"of",
"the",
"Visual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L238-L252
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
Visual.set_gl_state
|
def set_gl_state(self, preset=None, **kwargs):
"""Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
"""
self._vshare.gl_state = kwargs
self._vshare.gl_state['preset'] = preset
|
python
|
def set_gl_state(self, preset=None, **kwargs):
"""Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
"""
self._vshare.gl_state = kwargs
self._vshare.gl_state['preset'] = preset
|
[
"def",
"set_gl_state",
"(",
"self",
",",
"preset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_vshare",
".",
"gl_state",
"=",
"kwargs",
"self",
".",
"_vshare",
".",
"gl_state",
"[",
"'preset'",
"]",
"=",
"preset"
] |
Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
|
[
"Define",
"the",
"set",
"of",
"GL",
"state",
"parameters",
"to",
"use",
"when",
"drawing"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L338-L349
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
Visual.update_gl_state
|
def update_gl_state(self, *args, **kwargs):
"""Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
"""
if len(args) == 1:
self._vshare.gl_state['preset'] = args[0]
elif len(args) != 0:
raise TypeError("Only one positional argument allowed.")
self._vshare.gl_state.update(kwargs)
|
python
|
def update_gl_state(self, *args, **kwargs):
"""Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
"""
if len(args) == 1:
self._vshare.gl_state['preset'] = args[0]
elif len(args) != 0:
raise TypeError("Only one positional argument allowed.")
self._vshare.gl_state.update(kwargs)
|
[
"def",
"update_gl_state",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"self",
".",
"_vshare",
".",
"gl_state",
"[",
"'preset'",
"]",
"=",
"args",
"[",
"0",
"]",
"elif",
"len",
"(",
"args",
")",
"!=",
"0",
":",
"raise",
"TypeError",
"(",
"\"Only one positional argument allowed.\"",
")",
"self",
".",
"_vshare",
".",
"gl_state",
".",
"update",
"(",
"kwargs",
")"
] |
Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
|
[
"Modify",
"the",
"set",
"of",
"GL",
"state",
"parameters",
"to",
"use",
"when",
"drawing"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L351-L365
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
Visual._get_hook
|
def _get_hook(self, shader, name):
"""Return a FunctionChain that Filters may use to modify the program.
*shader* should be "frag" or "vert"
*name* should be "pre" or "post"
"""
assert name in ('pre', 'post')
key = (shader, name)
if key in self._hooks:
return self._hooks[key]
hook = StatementList()
if shader == 'vert':
self.view_program.vert[name] = hook
elif shader == 'frag':
self.view_program.frag[name] = hook
self._hooks[key] = hook
return hook
|
python
|
def _get_hook(self, shader, name):
"""Return a FunctionChain that Filters may use to modify the program.
*shader* should be "frag" or "vert"
*name* should be "pre" or "post"
"""
assert name in ('pre', 'post')
key = (shader, name)
if key in self._hooks:
return self._hooks[key]
hook = StatementList()
if shader == 'vert':
self.view_program.vert[name] = hook
elif shader == 'frag':
self.view_program.frag[name] = hook
self._hooks[key] = hook
return hook
|
[
"def",
"_get_hook",
"(",
"self",
",",
"shader",
",",
"name",
")",
":",
"assert",
"name",
"in",
"(",
"'pre'",
",",
"'post'",
")",
"key",
"=",
"(",
"shader",
",",
"name",
")",
"if",
"key",
"in",
"self",
".",
"_hooks",
":",
"return",
"self",
".",
"_hooks",
"[",
"key",
"]",
"hook",
"=",
"StatementList",
"(",
")",
"if",
"shader",
"==",
"'vert'",
":",
"self",
".",
"view_program",
".",
"vert",
"[",
"name",
"]",
"=",
"hook",
"elif",
"shader",
"==",
"'frag'",
":",
"self",
".",
"view_program",
".",
"frag",
"[",
"name",
"]",
"=",
"hook",
"self",
".",
"_hooks",
"[",
"key",
"]",
"=",
"hook",
"return",
"hook"
] |
Return a FunctionChain that Filters may use to modify the program.
*shader* should be "frag" or "vert"
*name* should be "pre" or "post"
|
[
"Return",
"a",
"FunctionChain",
"that",
"Filters",
"may",
"use",
"to",
"modify",
"the",
"program",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L448-L464
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
Visual.attach
|
def attach(self, filt, view=None):
"""Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
"""
if view is None:
self._vshare.filters.append(filt)
for view in self._vshare.views.keys():
filt._attach(view)
else:
view._filters.append(filt)
filt._attach(view)
|
python
|
def attach(self, filt, view=None):
"""Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
"""
if view is None:
self._vshare.filters.append(filt)
for view in self._vshare.views.keys():
filt._attach(view)
else:
view._filters.append(filt)
filt._attach(view)
|
[
"def",
"attach",
"(",
"self",
",",
"filt",
",",
"view",
"=",
"None",
")",
":",
"if",
"view",
"is",
"None",
":",
"self",
".",
"_vshare",
".",
"filters",
".",
"append",
"(",
"filt",
")",
"for",
"view",
"in",
"self",
".",
"_vshare",
".",
"views",
".",
"keys",
"(",
")",
":",
"filt",
".",
"_attach",
"(",
"view",
")",
"else",
":",
"view",
".",
"_filters",
".",
"append",
"(",
"filt",
")",
"filt",
".",
"_attach",
"(",
"view",
")"
] |
Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
|
[
"Attach",
"a",
"Filter",
"to",
"this",
"visual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L466-L484
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
Visual.detach
|
def detach(self, filt, view=None):
"""Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
"""
if view is None:
self._vshare.filters.remove(filt)
for view in self._vshare.views.keys():
filt._detach(view)
else:
view._filters.remove(filt)
filt._detach(view)
|
python
|
def detach(self, filt, view=None):
"""Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
"""
if view is None:
self._vshare.filters.remove(filt)
for view in self._vshare.views.keys():
filt._detach(view)
else:
view._filters.remove(filt)
filt._detach(view)
|
[
"def",
"detach",
"(",
"self",
",",
"filt",
",",
"view",
"=",
"None",
")",
":",
"if",
"view",
"is",
"None",
":",
"self",
".",
"_vshare",
".",
"filters",
".",
"remove",
"(",
"filt",
")",
"for",
"view",
"in",
"self",
".",
"_vshare",
".",
"views",
".",
"keys",
"(",
")",
":",
"filt",
".",
"_detach",
"(",
"view",
")",
"else",
":",
"view",
".",
"_filters",
".",
"remove",
"(",
"filt",
")",
"filt",
".",
"_detach",
"(",
"view",
")"
] |
Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
|
[
"Detach",
"a",
"filter",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L486-L502
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.add_subvisual
|
def add_subvisual(self, visual):
"""Add a subvisual
Parameters
----------
visual : instance of Visual
The visual to add.
"""
visual.transforms = self.transforms
visual._prepare_transforms(visual)
self._subvisuals.append(visual)
visual.events.update.connect(self._subv_update)
self.update()
|
python
|
def add_subvisual(self, visual):
"""Add a subvisual
Parameters
----------
visual : instance of Visual
The visual to add.
"""
visual.transforms = self.transforms
visual._prepare_transforms(visual)
self._subvisuals.append(visual)
visual.events.update.connect(self._subv_update)
self.update()
|
[
"def",
"add_subvisual",
"(",
"self",
",",
"visual",
")",
":",
"visual",
".",
"transforms",
"=",
"self",
".",
"transforms",
"visual",
".",
"_prepare_transforms",
"(",
"visual",
")",
"self",
".",
"_subvisuals",
".",
"append",
"(",
"visual",
")",
"visual",
".",
"events",
".",
"update",
".",
"connect",
"(",
"self",
".",
"_subv_update",
")",
"self",
".",
"update",
"(",
")"
] |
Add a subvisual
Parameters
----------
visual : instance of Visual
The visual to add.
|
[
"Add",
"a",
"subvisual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L544-L556
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.remove_subvisual
|
def remove_subvisual(self, visual):
"""Remove a subvisual
Parameters
----------
visual : instance of Visual
The visual to remove.
"""
visual.events.update.disconnect(self._subv_update)
self._subvisuals.remove(visual)
self.update()
|
python
|
def remove_subvisual(self, visual):
"""Remove a subvisual
Parameters
----------
visual : instance of Visual
The visual to remove.
"""
visual.events.update.disconnect(self._subv_update)
self._subvisuals.remove(visual)
self.update()
|
[
"def",
"remove_subvisual",
"(",
"self",
",",
"visual",
")",
":",
"visual",
".",
"events",
".",
"update",
".",
"disconnect",
"(",
"self",
".",
"_subv_update",
")",
"self",
".",
"_subvisuals",
".",
"remove",
"(",
"visual",
")",
"self",
".",
"update",
"(",
")"
] |
Remove a subvisual
Parameters
----------
visual : instance of Visual
The visual to remove.
|
[
"Remove",
"a",
"subvisual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L558-L568
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.draw
|
def draw(self):
"""Draw the visual
"""
if not self.visible:
return
if self._prepare_draw(view=self) is False:
return
for v in self._subvisuals:
if v.visible:
v.draw()
|
python
|
def draw(self):
"""Draw the visual
"""
if not self.visible:
return
if self._prepare_draw(view=self) is False:
return
for v in self._subvisuals:
if v.visible:
v.draw()
|
[
"def",
"draw",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"visible",
":",
"return",
"if",
"self",
".",
"_prepare_draw",
"(",
"view",
"=",
"self",
")",
"is",
"False",
":",
"return",
"for",
"v",
"in",
"self",
".",
"_subvisuals",
":",
"if",
"v",
".",
"visible",
":",
"v",
".",
"draw",
"(",
")"
] |
Draw the visual
|
[
"Draw",
"the",
"visual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L578-L588
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.set_gl_state
|
def set_gl_state(self, preset=None, **kwargs):
"""Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
"""
for v in self._subvisuals:
v.set_gl_state(preset=preset, **kwargs)
|
python
|
def set_gl_state(self, preset=None, **kwargs):
"""Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
"""
for v in self._subvisuals:
v.set_gl_state(preset=preset, **kwargs)
|
[
"def",
"set_gl_state",
"(",
"self",
",",
"preset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"v",
"in",
"self",
".",
"_subvisuals",
":",
"v",
".",
"set_gl_state",
"(",
"preset",
"=",
"preset",
",",
"*",
"*",
"kwargs",
")"
] |
Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
|
[
"Define",
"the",
"set",
"of",
"GL",
"state",
"parameters",
"to",
"use",
"when",
"drawing"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L597-L608
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.update_gl_state
|
def update_gl_state(self, *args, **kwargs):
"""Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
"""
for v in self._subvisuals:
v.update_gl_state(*args, **kwargs)
|
python
|
def update_gl_state(self, *args, **kwargs):
"""Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
"""
for v in self._subvisuals:
v.update_gl_state(*args, **kwargs)
|
[
"def",
"update_gl_state",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"v",
"in",
"self",
".",
"_subvisuals",
":",
"v",
".",
"update_gl_state",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments.
|
[
"Modify",
"the",
"set",
"of",
"GL",
"state",
"parameters",
"to",
"use",
"when",
"drawing"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L610-L621
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.attach
|
def attach(self, filt, view=None):
"""Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
"""
for v in self._subvisuals:
v.attach(filt, v)
|
python
|
def attach(self, filt, view=None):
"""Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
"""
for v in self._subvisuals:
v.attach(filt, v)
|
[
"def",
"attach",
"(",
"self",
",",
"filt",
",",
"view",
"=",
"None",
")",
":",
"for",
"v",
"in",
"self",
".",
"_subvisuals",
":",
"v",
".",
"attach",
"(",
"filt",
",",
"v",
")"
] |
Attach a Filter to this visual
Each filter modifies the appearance or behavior of the visual.
Parameters
----------
filt : object
The filter to attach.
view : instance of VisualView | None
The view to use.
|
[
"Attach",
"a",
"Filter",
"to",
"this",
"visual"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L623-L636
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/visual.py
|
CompoundVisual.detach
|
def detach(self, filt, view=None):
"""Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
"""
for v in self._subvisuals:
v.detach(filt, v)
|
python
|
def detach(self, filt, view=None):
"""Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
"""
for v in self._subvisuals:
v.detach(filt, v)
|
[
"def",
"detach",
"(",
"self",
",",
"filt",
",",
"view",
"=",
"None",
")",
":",
"for",
"v",
"in",
"self",
".",
"_subvisuals",
":",
"v",
".",
"detach",
"(",
"filt",
",",
"v",
")"
] |
Detach a filter.
Parameters
----------
filt : object
The filter to detach.
view : instance of VisualView | None
The view to use.
|
[
"Detach",
"a",
"filter",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L638-L649
|
train
|
federico123579/Trading212-API
|
tradingAPI/api.py
|
API.addMov
|
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
auto_margin=None, name_counter=None):
"""main function for placing movements
stop_limit = {'gain': [mode, value], 'loss': [mode, value]}"""
# ~ ARGS ~
if (not isinstance(product, type('')) or
(not isinstance(name_counter, type('')) and
name_counter is not None)):
raise ValueError('product and name_counter have to be a string')
if not isinstance(stop_limit, type({})) and stop_limit is not None:
raise ValueError('it has to be a dictionary')
# exclusive args
if quantity is not None and auto_margin is not None:
raise ValueError("quantity and auto_margin are exclusive")
elif quantity is None and auto_margin is None:
raise ValueError("need at least one quantity")
# ~ MAIN ~
# open new window
mov = self.new_mov(product)
mov.open()
mov.set_mode(mode)
# set quantity
if quantity is not None:
mov.set_quantity(quantity)
# for best performance in long times
try:
margin = mov.get_unit_value() * quantity
except TimeoutError:
mov.close()
logger.warning("market closed for %s" % mov.product)
return False
# auto_margin calculate quantity (how simple!)
elif auto_margin is not None:
unit_value = mov.get_unit_value()
mov.set_quantity(auto_margin * unit_value)
margin = auto_margin
# stop limit (how can be so simple!)
if stop_limit is not None:
mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
# confirm
try:
mov.confirm()
except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
logger.warning(e.err)
# resolve immediately
mov.set_quantity(e.quant)
mov.confirm()
except Exception:
logger.exception('undefined error in movement confirmation')
mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
f"with margin of {margin}")
mov_logger.debug(f"stop_limit: {stop_limit}")
|
python
|
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
auto_margin=None, name_counter=None):
"""main function for placing movements
stop_limit = {'gain': [mode, value], 'loss': [mode, value]}"""
# ~ ARGS ~
if (not isinstance(product, type('')) or
(not isinstance(name_counter, type('')) and
name_counter is not None)):
raise ValueError('product and name_counter have to be a string')
if not isinstance(stop_limit, type({})) and stop_limit is not None:
raise ValueError('it has to be a dictionary')
# exclusive args
if quantity is not None and auto_margin is not None:
raise ValueError("quantity and auto_margin are exclusive")
elif quantity is None and auto_margin is None:
raise ValueError("need at least one quantity")
# ~ MAIN ~
# open new window
mov = self.new_mov(product)
mov.open()
mov.set_mode(mode)
# set quantity
if quantity is not None:
mov.set_quantity(quantity)
# for best performance in long times
try:
margin = mov.get_unit_value() * quantity
except TimeoutError:
mov.close()
logger.warning("market closed for %s" % mov.product)
return False
# auto_margin calculate quantity (how simple!)
elif auto_margin is not None:
unit_value = mov.get_unit_value()
mov.set_quantity(auto_margin * unit_value)
margin = auto_margin
# stop limit (how can be so simple!)
if stop_limit is not None:
mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
# confirm
try:
mov.confirm()
except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
logger.warning(e.err)
# resolve immediately
mov.set_quantity(e.quant)
mov.confirm()
except Exception:
logger.exception('undefined error in movement confirmation')
mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
f"with margin of {margin}")
mov_logger.debug(f"stop_limit: {stop_limit}")
|
[
"def",
"addMov",
"(",
"self",
",",
"product",
",",
"quantity",
"=",
"None",
",",
"mode",
"=",
"\"buy\"",
",",
"stop_limit",
"=",
"None",
",",
"auto_margin",
"=",
"None",
",",
"name_counter",
"=",
"None",
")",
":",
"# ~ ARGS ~",
"if",
"(",
"not",
"isinstance",
"(",
"product",
",",
"type",
"(",
"''",
")",
")",
"or",
"(",
"not",
"isinstance",
"(",
"name_counter",
",",
"type",
"(",
"''",
")",
")",
"and",
"name_counter",
"is",
"not",
"None",
")",
")",
":",
"raise",
"ValueError",
"(",
"'product and name_counter have to be a string'",
")",
"if",
"not",
"isinstance",
"(",
"stop_limit",
",",
"type",
"(",
"{",
"}",
")",
")",
"and",
"stop_limit",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'it has to be a dictionary'",
")",
"# exclusive args",
"if",
"quantity",
"is",
"not",
"None",
"and",
"auto_margin",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"quantity and auto_margin are exclusive\"",
")",
"elif",
"quantity",
"is",
"None",
"and",
"auto_margin",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"need at least one quantity\"",
")",
"# ~ MAIN ~",
"# open new window",
"mov",
"=",
"self",
".",
"new_mov",
"(",
"product",
")",
"mov",
".",
"open",
"(",
")",
"mov",
".",
"set_mode",
"(",
"mode",
")",
"# set quantity",
"if",
"quantity",
"is",
"not",
"None",
":",
"mov",
".",
"set_quantity",
"(",
"quantity",
")",
"# for best performance in long times",
"try",
":",
"margin",
"=",
"mov",
".",
"get_unit_value",
"(",
")",
"*",
"quantity",
"except",
"TimeoutError",
":",
"mov",
".",
"close",
"(",
")",
"logger",
".",
"warning",
"(",
"\"market closed for %s\"",
"%",
"mov",
".",
"product",
")",
"return",
"False",
"# auto_margin calculate quantity (how simple!)",
"elif",
"auto_margin",
"is",
"not",
"None",
":",
"unit_value",
"=",
"mov",
".",
"get_unit_value",
"(",
")",
"mov",
".",
"set_quantity",
"(",
"auto_margin",
"*",
"unit_value",
")",
"margin",
"=",
"auto_margin",
"# stop limit (how can be so simple!)",
"if",
"stop_limit",
"is",
"not",
"None",
":",
"mov",
".",
"set_limit",
"(",
"'gain'",
",",
"stop_limit",
"[",
"'gain'",
"]",
"[",
"0",
"]",
",",
"stop_limit",
"[",
"'gain'",
"]",
"[",
"1",
"]",
")",
"mov",
".",
"set_limit",
"(",
"'loss'",
",",
"stop_limit",
"[",
"'loss'",
"]",
"[",
"0",
"]",
",",
"stop_limit",
"[",
"'loss'",
"]",
"[",
"1",
"]",
")",
"# confirm",
"try",
":",
"mov",
".",
"confirm",
"(",
")",
"except",
"(",
"exceptions",
".",
"MaxQuantLimit",
",",
"exceptions",
".",
"MinQuantLimit",
")",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"e",
".",
"err",
")",
"# resolve immediately",
"mov",
".",
"set_quantity",
"(",
"e",
".",
"quant",
")",
"mov",
".",
"confirm",
"(",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"'undefined error in movement confirmation'",
")",
"mov_logger",
".",
"info",
"(",
"f\"added {mov.product} movement of {mov.quantity} \"",
"+",
"f\"with margin of {margin}\"",
")",
"mov_logger",
".",
"debug",
"(",
"f\"stop_limit: {stop_limit}\"",
")"
] |
main function for placing movements
stop_limit = {'gain': [mode, value], 'loss': [mode, value]}
|
[
"main",
"function",
"for",
"placing",
"movements",
"stop_limit",
"=",
"{",
"gain",
":",
"[",
"mode",
"value",
"]",
"loss",
":",
"[",
"mode",
"value",
"]",
"}"
] |
0fab20b71a2348e72bbe76071b81f3692128851f
|
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/api.py#L20-L72
|
train
|
federico123579/Trading212-API
|
tradingAPI/api.py
|
API.checkPos
|
def checkPos(self):
"""check all positions"""
soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser')
poss = []
for label in soup.find_all("tr"):
pos_id = label['id']
# init an empty list
# check if it already exist
pos_list = [x for x in self.positions if x.id == pos_id]
if pos_list:
# and update it
pos = pos_list[0]
pos.update(label)
else:
pos = self.new_pos(label)
pos.get_gain()
poss.append(pos)
# remove old positions
self.positions.clear()
self.positions.extend(poss)
logger.debug("%d positions update" % len(poss))
return self.positions
|
python
|
def checkPos(self):
"""check all positions"""
soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser')
poss = []
for label in soup.find_all("tr"):
pos_id = label['id']
# init an empty list
# check if it already exist
pos_list = [x for x in self.positions if x.id == pos_id]
if pos_list:
# and update it
pos = pos_list[0]
pos.update(label)
else:
pos = self.new_pos(label)
pos.get_gain()
poss.append(pos)
# remove old positions
self.positions.clear()
self.positions.extend(poss)
logger.debug("%d positions update" % len(poss))
return self.positions
|
[
"def",
"checkPos",
"(",
"self",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"css1",
"(",
"path",
"[",
"'movs-table'",
"]",
")",
".",
"html",
",",
"'html.parser'",
")",
"poss",
"=",
"[",
"]",
"for",
"label",
"in",
"soup",
".",
"find_all",
"(",
"\"tr\"",
")",
":",
"pos_id",
"=",
"label",
"[",
"'id'",
"]",
"# init an empty list",
"# check if it already exist",
"pos_list",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"positions",
"if",
"x",
".",
"id",
"==",
"pos_id",
"]",
"if",
"pos_list",
":",
"# and update it",
"pos",
"=",
"pos_list",
"[",
"0",
"]",
"pos",
".",
"update",
"(",
"label",
")",
"else",
":",
"pos",
"=",
"self",
".",
"new_pos",
"(",
"label",
")",
"pos",
".",
"get_gain",
"(",
")",
"poss",
".",
"append",
"(",
"pos",
")",
"# remove old positions",
"self",
".",
"positions",
".",
"clear",
"(",
")",
"self",
".",
"positions",
".",
"extend",
"(",
"poss",
")",
"logger",
".",
"debug",
"(",
"\"%d positions update\"",
"%",
"len",
"(",
"poss",
")",
")",
"return",
"self",
".",
"positions"
] |
check all positions
|
[
"check",
"all",
"positions"
] |
0fab20b71a2348e72bbe76071b81f3692128851f
|
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/api.py#L76-L97
|
train
|
federico123579/Trading212-API
|
tradingAPI/api.py
|
API.checkStock
|
def checkStock(self):
"""check stocks in preference"""
if not self.preferences:
logger.debug("no preferences")
return None
soup = BeautifulSoup(
self.xpath(path['stock-table'])[0].html, "html.parser")
count = 0
# iterate through product in left panel
for product in soup.select("div.tradebox"):
prod_name = product.select("span.instrument-name")[0].text
stk_name = [x for x in self.preferences
if x.lower() in prod_name.lower()]
if not stk_name:
continue
name = prod_name
if not [x for x in self.stocks if x.product == name]:
self.stocks.append(Stock(name))
stock = [x for x in self.stocks if x.product == name][0]
if 'tradebox-market-closed' in product['class']:
stock.market = False
if not stock.market:
logger.debug("market closed for %s" % stock.product)
continue
sell_price = product.select("div.tradebox-price-sell")[0].text
buy_price = product.select("div.tradebox-price-buy")[0].text
sent = int(product.select(path['sent'])[0].text.strip('%')) / 100
stock.new_rec([sell_price, buy_price, sent])
count += 1
logger.debug(f"added %d stocks" % count)
return self.stocks
|
python
|
def checkStock(self):
"""check stocks in preference"""
if not self.preferences:
logger.debug("no preferences")
return None
soup = BeautifulSoup(
self.xpath(path['stock-table'])[0].html, "html.parser")
count = 0
# iterate through product in left panel
for product in soup.select("div.tradebox"):
prod_name = product.select("span.instrument-name")[0].text
stk_name = [x for x in self.preferences
if x.lower() in prod_name.lower()]
if not stk_name:
continue
name = prod_name
if not [x for x in self.stocks if x.product == name]:
self.stocks.append(Stock(name))
stock = [x for x in self.stocks if x.product == name][0]
if 'tradebox-market-closed' in product['class']:
stock.market = False
if not stock.market:
logger.debug("market closed for %s" % stock.product)
continue
sell_price = product.select("div.tradebox-price-sell")[0].text
buy_price = product.select("div.tradebox-price-buy")[0].text
sent = int(product.select(path['sent'])[0].text.strip('%')) / 100
stock.new_rec([sell_price, buy_price, sent])
count += 1
logger.debug(f"added %d stocks" % count)
return self.stocks
|
[
"def",
"checkStock",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"preferences",
":",
"logger",
".",
"debug",
"(",
"\"no preferences\"",
")",
"return",
"None",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"xpath",
"(",
"path",
"[",
"'stock-table'",
"]",
")",
"[",
"0",
"]",
".",
"html",
",",
"\"html.parser\"",
")",
"count",
"=",
"0",
"# iterate through product in left panel",
"for",
"product",
"in",
"soup",
".",
"select",
"(",
"\"div.tradebox\"",
")",
":",
"prod_name",
"=",
"product",
".",
"select",
"(",
"\"span.instrument-name\"",
")",
"[",
"0",
"]",
".",
"text",
"stk_name",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"preferences",
"if",
"x",
".",
"lower",
"(",
")",
"in",
"prod_name",
".",
"lower",
"(",
")",
"]",
"if",
"not",
"stk_name",
":",
"continue",
"name",
"=",
"prod_name",
"if",
"not",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"stocks",
"if",
"x",
".",
"product",
"==",
"name",
"]",
":",
"self",
".",
"stocks",
".",
"append",
"(",
"Stock",
"(",
"name",
")",
")",
"stock",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"stocks",
"if",
"x",
".",
"product",
"==",
"name",
"]",
"[",
"0",
"]",
"if",
"'tradebox-market-closed'",
"in",
"product",
"[",
"'class'",
"]",
":",
"stock",
".",
"market",
"=",
"False",
"if",
"not",
"stock",
".",
"market",
":",
"logger",
".",
"debug",
"(",
"\"market closed for %s\"",
"%",
"stock",
".",
"product",
")",
"continue",
"sell_price",
"=",
"product",
".",
"select",
"(",
"\"div.tradebox-price-sell\"",
")",
"[",
"0",
"]",
".",
"text",
"buy_price",
"=",
"product",
".",
"select",
"(",
"\"div.tradebox-price-buy\"",
")",
"[",
"0",
"]",
".",
"text",
"sent",
"=",
"int",
"(",
"product",
".",
"select",
"(",
"path",
"[",
"'sent'",
"]",
")",
"[",
"0",
"]",
".",
"text",
".",
"strip",
"(",
"'%'",
")",
")",
"/",
"100",
"stock",
".",
"new_rec",
"(",
"[",
"sell_price",
",",
"buy_price",
",",
"sent",
"]",
")",
"count",
"+=",
"1",
"logger",
".",
"debug",
"(",
"f\"added %d stocks\"",
"%",
"count",
")",
"return",
"self",
".",
"stocks"
] |
check stocks in preference
|
[
"check",
"stocks",
"in",
"preference"
] |
0fab20b71a2348e72bbe76071b81f3692128851f
|
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/api.py#L99-L129
|
train
|
federico123579/Trading212-API
|
tradingAPI/api.py
|
API.clearPrefs
|
def clearPrefs(self):
"""clear the left panel and preferences"""
self.preferences.clear()
tradebox_num = len(self.css('div.tradebox'))
for i in range(tradebox_num):
self.xpath(path['trade-box'])[0].right_click()
self.css1('div.item-trade-contextmenu-list-remove').click()
logger.info("cleared preferences")
|
python
|
def clearPrefs(self):
"""clear the left panel and preferences"""
self.preferences.clear()
tradebox_num = len(self.css('div.tradebox'))
for i in range(tradebox_num):
self.xpath(path['trade-box'])[0].right_click()
self.css1('div.item-trade-contextmenu-list-remove').click()
logger.info("cleared preferences")
|
[
"def",
"clearPrefs",
"(",
"self",
")",
":",
"self",
".",
"preferences",
".",
"clear",
"(",
")",
"tradebox_num",
"=",
"len",
"(",
"self",
".",
"css",
"(",
"'div.tradebox'",
")",
")",
"for",
"i",
"in",
"range",
"(",
"tradebox_num",
")",
":",
"self",
".",
"xpath",
"(",
"path",
"[",
"'trade-box'",
"]",
")",
"[",
"0",
"]",
".",
"right_click",
"(",
")",
"self",
".",
"css1",
"(",
"'div.item-trade-contextmenu-list-remove'",
")",
".",
"click",
"(",
")",
"logger",
".",
"info",
"(",
"\"cleared preferences\"",
")"
] |
clear the left panel and preferences
|
[
"clear",
"the",
"left",
"panel",
"and",
"preferences"
] |
0fab20b71a2348e72bbe76071b81f3692128851f
|
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/api.py#L134-L141
|
train
|
federico123579/Trading212-API
|
tradingAPI/api.py
|
API.addPrefs
|
def addPrefs(self, prefs=[]):
"""add preference in self.preferences"""
if len(prefs) == len(self.preferences) == 0:
logger.debug("no preferences")
return None
self.preferences.extend(prefs)
self.css1(path['search-btn']).click()
count = 0
for pref in self.preferences:
self.css1(path['search-pref']).fill(pref)
self.css1(path['pref-icon']).click()
btn = self.css1('div.add-to-watchlist-popup-item .icon-wrapper')
if not self.css1('svg', btn)['class'] is None:
btn.click()
count += 1
# remove window
self.css1(path['pref-icon']).click()
# close finally
self.css1(path['back-btn']).click()
self.css1(path['back-btn']).click()
logger.debug("updated %d preferences" % count)
return self.preferences
|
python
|
def addPrefs(self, prefs=[]):
"""add preference in self.preferences"""
if len(prefs) == len(self.preferences) == 0:
logger.debug("no preferences")
return None
self.preferences.extend(prefs)
self.css1(path['search-btn']).click()
count = 0
for pref in self.preferences:
self.css1(path['search-pref']).fill(pref)
self.css1(path['pref-icon']).click()
btn = self.css1('div.add-to-watchlist-popup-item .icon-wrapper')
if not self.css1('svg', btn)['class'] is None:
btn.click()
count += 1
# remove window
self.css1(path['pref-icon']).click()
# close finally
self.css1(path['back-btn']).click()
self.css1(path['back-btn']).click()
logger.debug("updated %d preferences" % count)
return self.preferences
|
[
"def",
"addPrefs",
"(",
"self",
",",
"prefs",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"prefs",
")",
"==",
"len",
"(",
"self",
".",
"preferences",
")",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"\"no preferences\"",
")",
"return",
"None",
"self",
".",
"preferences",
".",
"extend",
"(",
"prefs",
")",
"self",
".",
"css1",
"(",
"path",
"[",
"'search-btn'",
"]",
")",
".",
"click",
"(",
")",
"count",
"=",
"0",
"for",
"pref",
"in",
"self",
".",
"preferences",
":",
"self",
".",
"css1",
"(",
"path",
"[",
"'search-pref'",
"]",
")",
".",
"fill",
"(",
"pref",
")",
"self",
".",
"css1",
"(",
"path",
"[",
"'pref-icon'",
"]",
")",
".",
"click",
"(",
")",
"btn",
"=",
"self",
".",
"css1",
"(",
"'div.add-to-watchlist-popup-item .icon-wrapper'",
")",
"if",
"not",
"self",
".",
"css1",
"(",
"'svg'",
",",
"btn",
")",
"[",
"'class'",
"]",
"is",
"None",
":",
"btn",
".",
"click",
"(",
")",
"count",
"+=",
"1",
"# remove window",
"self",
".",
"css1",
"(",
"path",
"[",
"'pref-icon'",
"]",
")",
".",
"click",
"(",
")",
"# close finally",
"self",
".",
"css1",
"(",
"path",
"[",
"'back-btn'",
"]",
")",
".",
"click",
"(",
")",
"self",
".",
"css1",
"(",
"path",
"[",
"'back-btn'",
"]",
")",
".",
"click",
"(",
")",
"logger",
".",
"debug",
"(",
"\"updated %d preferences\"",
"%",
"count",
")",
"return",
"self",
".",
"preferences"
] |
add preference in self.preferences
|
[
"add",
"preference",
"in",
"self",
".",
"preferences"
] |
0fab20b71a2348e72bbe76071b81f3692128851f
|
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/api.py#L143-L164
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/util/fonts/_freetype.py
|
_load_glyph
|
def _load_glyph(f, char, glyphs_dict):
"""Load glyph from font into dict"""
from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
FT_LOAD_NO_AUTOHINT)
flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT
face = _load_font(f['face'], f['bold'], f['italic'])
face.set_char_size(f['size'] * 64)
# get the character of interest
face.load_char(char, flags)
bitmap = face.glyph.bitmap
width = face.glyph.bitmap.width
height = face.glyph.bitmap.rows
bitmap = np.array(bitmap.buffer)
w0 = bitmap.size // height if bitmap.size > 0 else 0
bitmap.shape = (height, w0)
bitmap = bitmap[:, :width].astype(np.ubyte)
left = face.glyph.bitmap_left
top = face.glyph.bitmap_top
advance = face.glyph.advance.x / 64.
glyph = dict(char=char, offset=(left, top), bitmap=bitmap,
advance=advance, kerning={})
glyphs_dict[char] = glyph
# Generate kerning
for other_char, other_glyph in glyphs_dict.items():
kerning = face.get_kerning(other_char, char)
glyph['kerning'][other_char] = kerning.x / 64.
kerning = face.get_kerning(char, other_char)
other_glyph['kerning'][char] = kerning.x / 64.
|
python
|
def _load_glyph(f, char, glyphs_dict):
"""Load glyph from font into dict"""
from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
FT_LOAD_NO_AUTOHINT)
flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT
face = _load_font(f['face'], f['bold'], f['italic'])
face.set_char_size(f['size'] * 64)
# get the character of interest
face.load_char(char, flags)
bitmap = face.glyph.bitmap
width = face.glyph.bitmap.width
height = face.glyph.bitmap.rows
bitmap = np.array(bitmap.buffer)
w0 = bitmap.size // height if bitmap.size > 0 else 0
bitmap.shape = (height, w0)
bitmap = bitmap[:, :width].astype(np.ubyte)
left = face.glyph.bitmap_left
top = face.glyph.bitmap_top
advance = face.glyph.advance.x / 64.
glyph = dict(char=char, offset=(left, top), bitmap=bitmap,
advance=advance, kerning={})
glyphs_dict[char] = glyph
# Generate kerning
for other_char, other_glyph in glyphs_dict.items():
kerning = face.get_kerning(other_char, char)
glyph['kerning'][other_char] = kerning.x / 64.
kerning = face.get_kerning(char, other_char)
other_glyph['kerning'][char] = kerning.x / 64.
|
[
"def",
"_load_glyph",
"(",
"f",
",",
"char",
",",
"glyphs_dict",
")",
":",
"from",
".",
".",
".",
"ext",
".",
"freetype",
"import",
"(",
"FT_LOAD_RENDER",
",",
"FT_LOAD_NO_HINTING",
",",
"FT_LOAD_NO_AUTOHINT",
")",
"flags",
"=",
"FT_LOAD_RENDER",
"|",
"FT_LOAD_NO_HINTING",
"|",
"FT_LOAD_NO_AUTOHINT",
"face",
"=",
"_load_font",
"(",
"f",
"[",
"'face'",
"]",
",",
"f",
"[",
"'bold'",
"]",
",",
"f",
"[",
"'italic'",
"]",
")",
"face",
".",
"set_char_size",
"(",
"f",
"[",
"'size'",
"]",
"*",
"64",
")",
"# get the character of interest",
"face",
".",
"load_char",
"(",
"char",
",",
"flags",
")",
"bitmap",
"=",
"face",
".",
"glyph",
".",
"bitmap",
"width",
"=",
"face",
".",
"glyph",
".",
"bitmap",
".",
"width",
"height",
"=",
"face",
".",
"glyph",
".",
"bitmap",
".",
"rows",
"bitmap",
"=",
"np",
".",
"array",
"(",
"bitmap",
".",
"buffer",
")",
"w0",
"=",
"bitmap",
".",
"size",
"//",
"height",
"if",
"bitmap",
".",
"size",
">",
"0",
"else",
"0",
"bitmap",
".",
"shape",
"=",
"(",
"height",
",",
"w0",
")",
"bitmap",
"=",
"bitmap",
"[",
":",
",",
":",
"width",
"]",
".",
"astype",
"(",
"np",
".",
"ubyte",
")",
"left",
"=",
"face",
".",
"glyph",
".",
"bitmap_left",
"top",
"=",
"face",
".",
"glyph",
".",
"bitmap_top",
"advance",
"=",
"face",
".",
"glyph",
".",
"advance",
".",
"x",
"/",
"64.",
"glyph",
"=",
"dict",
"(",
"char",
"=",
"char",
",",
"offset",
"=",
"(",
"left",
",",
"top",
")",
",",
"bitmap",
"=",
"bitmap",
",",
"advance",
"=",
"advance",
",",
"kerning",
"=",
"{",
"}",
")",
"glyphs_dict",
"[",
"char",
"]",
"=",
"glyph",
"# Generate kerning",
"for",
"other_char",
",",
"other_glyph",
"in",
"glyphs_dict",
".",
"items",
"(",
")",
":",
"kerning",
"=",
"face",
".",
"get_kerning",
"(",
"other_char",
",",
"char",
")",
"glyph",
"[",
"'kerning'",
"]",
"[",
"other_char",
"]",
"=",
"kerning",
".",
"x",
"/",
"64.",
"kerning",
"=",
"face",
".",
"get_kerning",
"(",
"char",
",",
"other_char",
")",
"other_glyph",
"[",
"'kerning'",
"]",
"[",
"char",
"]",
"=",
"kerning",
".",
"x",
"/",
"64."
] |
Load glyph from font into dict
|
[
"Load",
"glyph",
"from",
"font",
"into",
"dict"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fonts/_freetype.py#L45-L73
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/scene/visuals.py
|
VisualNode._set_clipper
|
def _set_clipper(self, node, clipper):
"""Assign a clipper that is inherited from a parent node.
If *clipper* is None, then remove any clippers for *node*.
"""
if node in self._clippers:
self.detach(self._clippers.pop(node))
if clipper is not None:
self.attach(clipper)
self._clippers[node] = clipper
|
python
|
def _set_clipper(self, node, clipper):
"""Assign a clipper that is inherited from a parent node.
If *clipper* is None, then remove any clippers for *node*.
"""
if node in self._clippers:
self.detach(self._clippers.pop(node))
if clipper is not None:
self.attach(clipper)
self._clippers[node] = clipper
|
[
"def",
"_set_clipper",
"(",
"self",
",",
"node",
",",
"clipper",
")",
":",
"if",
"node",
"in",
"self",
".",
"_clippers",
":",
"self",
".",
"detach",
"(",
"self",
".",
"_clippers",
".",
"pop",
"(",
"node",
")",
")",
"if",
"clipper",
"is",
"not",
"None",
":",
"self",
".",
"attach",
"(",
"clipper",
")",
"self",
".",
"_clippers",
"[",
"node",
"]",
"=",
"clipper"
] |
Assign a clipper that is inherited from a parent node.
If *clipper* is None, then remove any clippers for *node*.
|
[
"Assign",
"a",
"clipper",
"that",
"is",
"inherited",
"from",
"a",
"parent",
"node",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/visuals.py#L43-L52
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/scene/visuals.py
|
VisualNode._update_trsys
|
def _update_trsys(self, event):
"""Transform object(s) have changed for this Node; assign these to the
visual's TransformSystem.
"""
doc = self.document_node
scene = self.scene_node
root = self.root_node
self.transforms.visual_transform = self.node_transform(scene)
self.transforms.scene_transform = scene.node_transform(doc)
self.transforms.document_transform = doc.node_transform(root)
Node._update_trsys(self, event)
|
python
|
def _update_trsys(self, event):
"""Transform object(s) have changed for this Node; assign these to the
visual's TransformSystem.
"""
doc = self.document_node
scene = self.scene_node
root = self.root_node
self.transforms.visual_transform = self.node_transform(scene)
self.transforms.scene_transform = scene.node_transform(doc)
self.transforms.document_transform = doc.node_transform(root)
Node._update_trsys(self, event)
|
[
"def",
"_update_trsys",
"(",
"self",
",",
"event",
")",
":",
"doc",
"=",
"self",
".",
"document_node",
"scene",
"=",
"self",
".",
"scene_node",
"root",
"=",
"self",
".",
"root_node",
"self",
".",
"transforms",
".",
"visual_transform",
"=",
"self",
".",
"node_transform",
"(",
"scene",
")",
"self",
".",
"transforms",
".",
"scene_transform",
"=",
"scene",
".",
"node_transform",
"(",
"doc",
")",
"self",
".",
"transforms",
".",
"document_transform",
"=",
"doc",
".",
"node_transform",
"(",
"root",
")",
"Node",
".",
"_update_trsys",
"(",
"self",
",",
"event",
")"
] |
Transform object(s) have changed for this Node; assign these to the
visual's TransformSystem.
|
[
"Transform",
"object",
"(",
"s",
")",
"have",
"changed",
"for",
"this",
"Node",
";",
"assign",
"these",
"to",
"the",
"visual",
"s",
"TransformSystem",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/visuals.py#L71-L82
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
cfnumber_to_number
|
def cfnumber_to_number(cfnumber):
"""Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber)
cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16,
kCFNumberSInt32Type: c_int32,
kCFNumberSInt64Type: c_int64,
kCFNumberFloat32Type: c_float,
kCFNumberFloat64Type: c_double,
kCFNumberCharType: c_byte, kCFNumberShortType: c_short,
kCFNumberIntType: c_int, kCFNumberLongType: c_long,
kCFNumberLongLongType: c_longlong,
kCFNumberFloatType: c_float,
kCFNumberDoubleType: c_double,
kCFNumberCFIndexType: CFIndex,
kCFNumberCGFloatType: CGFloat}
if numeric_type in cfnum_to_ctype:
t = cfnum_to_ctype[numeric_type]
result = t()
if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)):
return result.value
else:
raise Exception(
'cfnumber_to_number: unhandled CFNumber type %d' % numeric_type)
|
python
|
def cfnumber_to_number(cfnumber):
"""Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber)
cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16,
kCFNumberSInt32Type: c_int32,
kCFNumberSInt64Type: c_int64,
kCFNumberFloat32Type: c_float,
kCFNumberFloat64Type: c_double,
kCFNumberCharType: c_byte, kCFNumberShortType: c_short,
kCFNumberIntType: c_int, kCFNumberLongType: c_long,
kCFNumberLongLongType: c_longlong,
kCFNumberFloatType: c_float,
kCFNumberDoubleType: c_double,
kCFNumberCFIndexType: CFIndex,
kCFNumberCGFloatType: CGFloat}
if numeric_type in cfnum_to_ctype:
t = cfnum_to_ctype[numeric_type]
result = t()
if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)):
return result.value
else:
raise Exception(
'cfnumber_to_number: unhandled CFNumber type %d' % numeric_type)
|
[
"def",
"cfnumber_to_number",
"(",
"cfnumber",
")",
":",
"numeric_type",
"=",
"cf",
".",
"CFNumberGetType",
"(",
"cfnumber",
")",
"cfnum_to_ctype",
"=",
"{",
"kCFNumberSInt8Type",
":",
"c_int8",
",",
"kCFNumberSInt16Type",
":",
"c_int16",
",",
"kCFNumberSInt32Type",
":",
"c_int32",
",",
"kCFNumberSInt64Type",
":",
"c_int64",
",",
"kCFNumberFloat32Type",
":",
"c_float",
",",
"kCFNumberFloat64Type",
":",
"c_double",
",",
"kCFNumberCharType",
":",
"c_byte",
",",
"kCFNumberShortType",
":",
"c_short",
",",
"kCFNumberIntType",
":",
"c_int",
",",
"kCFNumberLongType",
":",
"c_long",
",",
"kCFNumberLongLongType",
":",
"c_longlong",
",",
"kCFNumberFloatType",
":",
"c_float",
",",
"kCFNumberDoubleType",
":",
"c_double",
",",
"kCFNumberCFIndexType",
":",
"CFIndex",
",",
"kCFNumberCGFloatType",
":",
"CGFloat",
"}",
"if",
"numeric_type",
"in",
"cfnum_to_ctype",
":",
"t",
"=",
"cfnum_to_ctype",
"[",
"numeric_type",
"]",
"result",
"=",
"t",
"(",
")",
"if",
"cf",
".",
"CFNumberGetValue",
"(",
"cfnumber",
",",
"numeric_type",
",",
"byref",
"(",
"result",
")",
")",
":",
"return",
"result",
".",
"value",
"else",
":",
"raise",
"Exception",
"(",
"'cfnumber_to_number: unhandled CFNumber type %d'",
"%",
"numeric_type",
")"
] |
Convert CFNumber to python int or float.
|
[
"Convert",
"CFNumber",
"to",
"python",
"int",
"or",
"float",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1032-L1055
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
cftype_to_value
|
def cftype_to_value(cftype):
"""Convert a CFType into an equivalent python type.
The convertible CFTypes are taken from the known_cftypes
dictionary, which may be added to if another library implements
its own conversion methods."""
if not cftype:
return None
typeID = cf.CFGetTypeID(cftype)
if typeID in known_cftypes:
convert_function = known_cftypes[typeID]
return convert_function(cftype)
else:
return cftype
|
python
|
def cftype_to_value(cftype):
"""Convert a CFType into an equivalent python type.
The convertible CFTypes are taken from the known_cftypes
dictionary, which may be added to if another library implements
its own conversion methods."""
if not cftype:
return None
typeID = cf.CFGetTypeID(cftype)
if typeID in known_cftypes:
convert_function = known_cftypes[typeID]
return convert_function(cftype)
else:
return cftype
|
[
"def",
"cftype_to_value",
"(",
"cftype",
")",
":",
"if",
"not",
"cftype",
":",
"return",
"None",
"typeID",
"=",
"cf",
".",
"CFGetTypeID",
"(",
"cftype",
")",
"if",
"typeID",
"in",
"known_cftypes",
":",
"convert_function",
"=",
"known_cftypes",
"[",
"typeID",
"]",
"return",
"convert_function",
"(",
"cftype",
")",
"else",
":",
"return",
"cftype"
] |
Convert a CFType into an equivalent python type.
The convertible CFTypes are taken from the known_cftypes
dictionary, which may be added to if another library implements
its own conversion methods.
|
[
"Convert",
"a",
"CFType",
"into",
"an",
"equivalent",
"python",
"type",
".",
"The",
"convertible",
"CFTypes",
"are",
"taken",
"from",
"the",
"known_cftypes",
"dictionary",
"which",
"may",
"be",
"added",
"to",
"if",
"another",
"library",
"implements",
"its",
"own",
"conversion",
"methods",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1062-L1074
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
cfset_to_set
|
def cfset_to_set(cfset):
"""Convert CFSet to python set."""
count = cf.CFSetGetCount(cfset)
buffer = (c_void_p * count)()
cf.CFSetGetValues(cfset, byref(buffer))
return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
|
python
|
def cfset_to_set(cfset):
"""Convert CFSet to python set."""
count = cf.CFSetGetCount(cfset)
buffer = (c_void_p * count)()
cf.CFSetGetValues(cfset, byref(buffer))
return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
|
[
"def",
"cfset_to_set",
"(",
"cfset",
")",
":",
"count",
"=",
"cf",
".",
"CFSetGetCount",
"(",
"cfset",
")",
"buffer",
"=",
"(",
"c_void_p",
"*",
"count",
")",
"(",
")",
"cf",
".",
"CFSetGetValues",
"(",
"cfset",
",",
"byref",
"(",
"buffer",
")",
")",
"return",
"set",
"(",
"[",
"cftype_to_value",
"(",
"c_void_p",
"(",
"buffer",
"[",
"i",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
"]",
")"
] |
Convert CFSet to python set.
|
[
"Convert",
"CFSet",
"to",
"python",
"set",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1085-L1090
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
cfarray_to_list
|
def cfarray_to_list(cfarray):
"""Convert CFArray to python list."""
count = cf.CFArrayGetCount(cfarray)
return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i)))
for i in range(count)]
|
python
|
def cfarray_to_list(cfarray):
"""Convert CFArray to python list."""
count = cf.CFArrayGetCount(cfarray)
return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i)))
for i in range(count)]
|
[
"def",
"cfarray_to_list",
"(",
"cfarray",
")",
":",
"count",
"=",
"cf",
".",
"CFArrayGetCount",
"(",
"cfarray",
")",
"return",
"[",
"cftype_to_value",
"(",
"c_void_p",
"(",
"cf",
".",
"CFArrayGetValueAtIndex",
"(",
"cfarray",
",",
"i",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
"]"
] |
Convert CFArray to python list.
|
[
"Convert",
"CFArray",
"to",
"python",
"list",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1099-L1103
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
ObjCMethod.ctype_for_encoding
|
def ctype_for_encoding(self, encoding):
"""Return ctypes type for an encoded Objective-C type."""
if encoding in self.typecodes:
return self.typecodes[encoding]
elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
return POINTER(self.typecodes[encoding[1:]])
elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding,
NSZoneEncoding]:
return c_void_p
elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes:
return self.typecodes[encoding[1:]]
elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes:
return POINTER(self.typecodes[encoding[2:]])
else:
raise Exception('unknown encoding for %s: %s'
% (self.name, encoding))
|
python
|
def ctype_for_encoding(self, encoding):
"""Return ctypes type for an encoded Objective-C type."""
if encoding in self.typecodes:
return self.typecodes[encoding]
elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
return POINTER(self.typecodes[encoding[1:]])
elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding,
NSZoneEncoding]:
return c_void_p
elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes:
return self.typecodes[encoding[1:]]
elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes:
return POINTER(self.typecodes[encoding[2:]])
else:
raise Exception('unknown encoding for %s: %s'
% (self.name, encoding))
|
[
"def",
"ctype_for_encoding",
"(",
"self",
",",
"encoding",
")",
":",
"if",
"encoding",
"in",
"self",
".",
"typecodes",
":",
"return",
"self",
".",
"typecodes",
"[",
"encoding",
"]",
"elif",
"encoding",
"[",
"0",
":",
"1",
"]",
"==",
"b'^'",
"and",
"encoding",
"[",
"1",
":",
"]",
"in",
"self",
".",
"typecodes",
":",
"return",
"POINTER",
"(",
"self",
".",
"typecodes",
"[",
"encoding",
"[",
"1",
":",
"]",
"]",
")",
"elif",
"encoding",
"[",
"0",
":",
"1",
"]",
"==",
"b'^'",
"and",
"encoding",
"[",
"1",
":",
"]",
"in",
"[",
"CGImageEncoding",
",",
"NSZoneEncoding",
"]",
":",
"return",
"c_void_p",
"elif",
"encoding",
"[",
"0",
":",
"1",
"]",
"==",
"b'r'",
"and",
"encoding",
"[",
"1",
":",
"]",
"in",
"self",
".",
"typecodes",
":",
"return",
"self",
".",
"typecodes",
"[",
"encoding",
"[",
"1",
":",
"]",
"]",
"elif",
"encoding",
"[",
"0",
":",
"2",
"]",
"==",
"b'r^'",
"and",
"encoding",
"[",
"2",
":",
"]",
"in",
"self",
".",
"typecodes",
":",
"return",
"POINTER",
"(",
"self",
".",
"typecodes",
"[",
"encoding",
"[",
"2",
":",
"]",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"'unknown encoding for %s: %s'",
"%",
"(",
"self",
".",
"name",
",",
"encoding",
")",
")"
] |
Return ctypes type for an encoded Objective-C type.
|
[
"Return",
"ctypes",
"type",
"for",
"an",
"encoded",
"Objective",
"-",
"C",
"type",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L595-L610
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
|
ObjCSubclass.classmethod
|
def classmethod(self, encoding):
"""Function decorator for class methods."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
def decorator(f):
def objc_class_method(objc_cls, objc_cmd, *args):
py_cls = ObjCClass(objc_cls)
py_cls.objc_cmd = objc_cmd
args = convert_method_arguments(encoding, args)
result = f(py_cls, *args)
if isinstance(result, ObjCClass):
result = result.ptr.value
elif isinstance(result, ObjCInstance):
result = result.ptr.value
return result
name = f.__name__.replace('_', ':')
self.add_class_method(objc_class_method, name, encoding)
return objc_class_method
return decorator
|
python
|
def classmethod(self, encoding):
"""Function decorator for class methods."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
def decorator(f):
def objc_class_method(objc_cls, objc_cmd, *args):
py_cls = ObjCClass(objc_cls)
py_cls.objc_cmd = objc_cmd
args = convert_method_arguments(encoding, args)
result = f(py_cls, *args)
if isinstance(result, ObjCClass):
result = result.ptr.value
elif isinstance(result, ObjCInstance):
result = result.ptr.value
return result
name = f.__name__.replace('_', ':')
self.add_class_method(objc_class_method, name, encoding)
return objc_class_method
return decorator
|
[
"def",
"classmethod",
"(",
"self",
",",
"encoding",
")",
":",
"# Add encodings for hidden self and cmd arguments.",
"encoding",
"=",
"ensure_bytes",
"(",
"encoding",
")",
"typecodes",
"=",
"parse_type_encoding",
"(",
"encoding",
")",
"typecodes",
".",
"insert",
"(",
"1",
",",
"b'@:'",
")",
"encoding",
"=",
"b''",
".",
"join",
"(",
"typecodes",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"objc_class_method",
"(",
"objc_cls",
",",
"objc_cmd",
",",
"*",
"args",
")",
":",
"py_cls",
"=",
"ObjCClass",
"(",
"objc_cls",
")",
"py_cls",
".",
"objc_cmd",
"=",
"objc_cmd",
"args",
"=",
"convert_method_arguments",
"(",
"encoding",
",",
"args",
")",
"result",
"=",
"f",
"(",
"py_cls",
",",
"*",
"args",
")",
"if",
"isinstance",
"(",
"result",
",",
"ObjCClass",
")",
":",
"result",
"=",
"result",
".",
"ptr",
".",
"value",
"elif",
"isinstance",
"(",
"result",
",",
"ObjCInstance",
")",
":",
"result",
"=",
"result",
".",
"ptr",
".",
"value",
"return",
"result",
"name",
"=",
"f",
".",
"__name__",
".",
"replace",
"(",
"'_'",
",",
"':'",
")",
"self",
".",
"add_class_method",
"(",
"objc_class_method",
",",
"name",
",",
"encoding",
")",
"return",
"objc_class_method",
"return",
"decorator"
] |
Function decorator for class methods.
|
[
"Function",
"decorator",
"for",
"class",
"methods",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L864-L886
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/collections/agg_segment_collection.py
|
AggSegmentCollection.append
|
def append(self, P0, P1, itemsize=None, **kwargs):
"""
Append a new set of segments to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices positions of the path(s) to be added
itemsize: int or None
Size of an individual path
caps : list, array or 2-tuple
Path start /end cap
color : list, array or 4-tuple
Path color
linewidth : list, array or float
Path linewidth
antialias : list, array or float
Path antialias area
"""
itemsize = itemsize or 1
itemcount = len(P0) // itemsize
V = np.empty(itemcount, dtype=self.vtype)
# Apply default values on vertices
for name in self.vtype.names:
if name not in ['collection_index', 'P0', 'P1', 'index']:
V[name] = kwargs.get(name, self._defaults[name])
V['P0'] = P0
V['P1'] = P1
V = V.repeat(4, axis=0)
V['index'] = np.resize([0, 1, 2, 3], 4 * itemcount * itemsize)
I = np.ones((itemcount, 6), dtype=int)
I[:] = 0, 1, 2, 0, 2, 3
I[:] += 4 * np.arange(itemcount)[:, np.newaxis]
I = I.ravel()
# Uniforms
if self.utype:
U = np.zeros(itemcount, dtype=self.utype)
for name in self.utype.names:
if name not in ["__unused__"]:
U[name] = kwargs.get(name, self._defaults[name])
else:
U = None
Collection.append(
self, vertices=V, uniforms=U, indices=I, itemsize=4 * itemcount)
|
python
|
def append(self, P0, P1, itemsize=None, **kwargs):
"""
Append a new set of segments to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices positions of the path(s) to be added
itemsize: int or None
Size of an individual path
caps : list, array or 2-tuple
Path start /end cap
color : list, array or 4-tuple
Path color
linewidth : list, array or float
Path linewidth
antialias : list, array or float
Path antialias area
"""
itemsize = itemsize or 1
itemcount = len(P0) // itemsize
V = np.empty(itemcount, dtype=self.vtype)
# Apply default values on vertices
for name in self.vtype.names:
if name not in ['collection_index', 'P0', 'P1', 'index']:
V[name] = kwargs.get(name, self._defaults[name])
V['P0'] = P0
V['P1'] = P1
V = V.repeat(4, axis=0)
V['index'] = np.resize([0, 1, 2, 3], 4 * itemcount * itemsize)
I = np.ones((itemcount, 6), dtype=int)
I[:] = 0, 1, 2, 0, 2, 3
I[:] += 4 * np.arange(itemcount)[:, np.newaxis]
I = I.ravel()
# Uniforms
if self.utype:
U = np.zeros(itemcount, dtype=self.utype)
for name in self.utype.names:
if name not in ["__unused__"]:
U[name] = kwargs.get(name, self._defaults[name])
else:
U = None
Collection.append(
self, vertices=V, uniforms=U, indices=I, itemsize=4 * itemcount)
|
[
"def",
"append",
"(",
"self",
",",
"P0",
",",
"P1",
",",
"itemsize",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"itemsize",
"=",
"itemsize",
"or",
"1",
"itemcount",
"=",
"len",
"(",
"P0",
")",
"//",
"itemsize",
"V",
"=",
"np",
".",
"empty",
"(",
"itemcount",
",",
"dtype",
"=",
"self",
".",
"vtype",
")",
"# Apply default values on vertices",
"for",
"name",
"in",
"self",
".",
"vtype",
".",
"names",
":",
"if",
"name",
"not",
"in",
"[",
"'collection_index'",
",",
"'P0'",
",",
"'P1'",
",",
"'index'",
"]",
":",
"V",
"[",
"name",
"]",
"=",
"kwargs",
".",
"get",
"(",
"name",
",",
"self",
".",
"_defaults",
"[",
"name",
"]",
")",
"V",
"[",
"'P0'",
"]",
"=",
"P0",
"V",
"[",
"'P1'",
"]",
"=",
"P1",
"V",
"=",
"V",
".",
"repeat",
"(",
"4",
",",
"axis",
"=",
"0",
")",
"V",
"[",
"'index'",
"]",
"=",
"np",
".",
"resize",
"(",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
",",
"4",
"*",
"itemcount",
"*",
"itemsize",
")",
"I",
"=",
"np",
".",
"ones",
"(",
"(",
"itemcount",
",",
"6",
")",
",",
"dtype",
"=",
"int",
")",
"I",
"[",
":",
"]",
"=",
"0",
",",
"1",
",",
"2",
",",
"0",
",",
"2",
",",
"3",
"I",
"[",
":",
"]",
"+=",
"4",
"*",
"np",
".",
"arange",
"(",
"itemcount",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"I",
"=",
"I",
".",
"ravel",
"(",
")",
"# Uniforms",
"if",
"self",
".",
"utype",
":",
"U",
"=",
"np",
".",
"zeros",
"(",
"itemcount",
",",
"dtype",
"=",
"self",
".",
"utype",
")",
"for",
"name",
"in",
"self",
".",
"utype",
".",
"names",
":",
"if",
"name",
"not",
"in",
"[",
"\"__unused__\"",
"]",
":",
"U",
"[",
"name",
"]",
"=",
"kwargs",
".",
"get",
"(",
"name",
",",
"self",
".",
"_defaults",
"[",
"name",
"]",
")",
"else",
":",
"U",
"=",
"None",
"Collection",
".",
"append",
"(",
"self",
",",
"vertices",
"=",
"V",
",",
"uniforms",
"=",
"U",
",",
"indices",
"=",
"I",
",",
"itemsize",
"=",
"4",
"*",
"itemcount",
")"
] |
Append a new set of segments to the collection.
For kwargs argument, n is the number of vertices (local) or the number
of item (shared)
Parameters
----------
P : np.array
Vertices positions of the path(s) to be added
itemsize: int or None
Size of an individual path
caps : list, array or 2-tuple
Path start /end cap
color : list, array or 4-tuple
Path color
linewidth : list, array or float
Path linewidth
antialias : list, array or float
Path antialias area
|
[
"Append",
"a",
"new",
"set",
"of",
"segments",
"to",
"the",
"collection",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/agg_segment_collection.py#L88-L147
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/volume/shaders.py
|
get_frag_shader
|
def get_frag_shader(volumes, clipped=False, n_volume_max=5):
"""
Get the fragment shader code - we use the shader_program object to determine
which layers are enabled and therefore what to include in the shader code.
"""
declarations = ""
before_loop = ""
in_loop = ""
after_loop = ""
for index in range(n_volume_max):
declarations += "uniform $sampler_type u_volumetex_{0:d};\n".format(index)
before_loop += "dummy = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)
declarations += "uniform $sampler_type dummy1;\n"
declarations += "float dummy;\n"
for label in sorted(volumes):
index = volumes[label]['index']
# Global declarations
declarations += "uniform float u_weight_{0:d};\n".format(index)
declarations += "uniform int u_enabled_{0:d};\n".format(index)
# Declarations before the raytracing loop
before_loop += "float max_val_{0:d} = 0;\n".format(index)
# Calculation inside the main raytracing loop
in_loop += "if(u_enabled_{0:d} == 1) {{\n\n".format(index)
if clipped:
in_loop += ("if(loc.r > u_clip_min.r && loc.r < u_clip_max.r &&\n"
" loc.g > u_clip_min.g && loc.g < u_clip_max.g &&\n"
" loc.b > u_clip_min.b && loc.b < u_clip_max.b) {\n\n")
in_loop += "// Sample texture for layer {0}\n".format(label)
in_loop += "val = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)
if volumes[label].get('multiply') is not None:
index_other = volumes[volumes[label]['multiply']]['index']
in_loop += ("if (val != 0) {{ val *= $sample(u_volumetex_{0:d}, loc).g; }}\n"
.format(index_other))
in_loop += "max_val_{0:d} = max(val, max_val_{0:d});\n\n".format(index)
if clipped:
in_loop += "}\n\n"
in_loop += "}\n\n"
# Calculation after the main loop
after_loop += "// Compute final color for layer {0}\n".format(label)
after_loop += ("color = $cmap{0:d}(max_val_{0:d});\n"
"color.a *= u_weight_{0:d};\n"
"total_color += color.a * color;\n"
"max_alpha = max(color.a, max_alpha);\n"
"count += color.a;\n\n").format(index)
if not clipped:
before_loop += "\nfloat val3 = u_clip_min.g + u_clip_max.g;\n\n"
# Code esthetics
before_loop = indent(before_loop, " " * 4).strip()
in_loop = indent(in_loop, " " * 16).strip()
after_loop = indent(after_loop, " " * 4).strip()
return FRAG_SHADER.format(declarations=declarations,
before_loop=before_loop,
in_loop=in_loop,
after_loop=after_loop)
|
python
|
def get_frag_shader(volumes, clipped=False, n_volume_max=5):
"""
Get the fragment shader code - we use the shader_program object to determine
which layers are enabled and therefore what to include in the shader code.
"""
declarations = ""
before_loop = ""
in_loop = ""
after_loop = ""
for index in range(n_volume_max):
declarations += "uniform $sampler_type u_volumetex_{0:d};\n".format(index)
before_loop += "dummy = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)
declarations += "uniform $sampler_type dummy1;\n"
declarations += "float dummy;\n"
for label in sorted(volumes):
index = volumes[label]['index']
# Global declarations
declarations += "uniform float u_weight_{0:d};\n".format(index)
declarations += "uniform int u_enabled_{0:d};\n".format(index)
# Declarations before the raytracing loop
before_loop += "float max_val_{0:d} = 0;\n".format(index)
# Calculation inside the main raytracing loop
in_loop += "if(u_enabled_{0:d} == 1) {{\n\n".format(index)
if clipped:
in_loop += ("if(loc.r > u_clip_min.r && loc.r < u_clip_max.r &&\n"
" loc.g > u_clip_min.g && loc.g < u_clip_max.g &&\n"
" loc.b > u_clip_min.b && loc.b < u_clip_max.b) {\n\n")
in_loop += "// Sample texture for layer {0}\n".format(label)
in_loop += "val = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)
if volumes[label].get('multiply') is not None:
index_other = volumes[volumes[label]['multiply']]['index']
in_loop += ("if (val != 0) {{ val *= $sample(u_volumetex_{0:d}, loc).g; }}\n"
.format(index_other))
in_loop += "max_val_{0:d} = max(val, max_val_{0:d});\n\n".format(index)
if clipped:
in_loop += "}\n\n"
in_loop += "}\n\n"
# Calculation after the main loop
after_loop += "// Compute final color for layer {0}\n".format(label)
after_loop += ("color = $cmap{0:d}(max_val_{0:d});\n"
"color.a *= u_weight_{0:d};\n"
"total_color += color.a * color;\n"
"max_alpha = max(color.a, max_alpha);\n"
"count += color.a;\n\n").format(index)
if not clipped:
before_loop += "\nfloat val3 = u_clip_min.g + u_clip_max.g;\n\n"
# Code esthetics
before_loop = indent(before_loop, " " * 4).strip()
in_loop = indent(in_loop, " " * 16).strip()
after_loop = indent(after_loop, " " * 4).strip()
return FRAG_SHADER.format(declarations=declarations,
before_loop=before_loop,
in_loop=in_loop,
after_loop=after_loop)
|
[
"def",
"get_frag_shader",
"(",
"volumes",
",",
"clipped",
"=",
"False",
",",
"n_volume_max",
"=",
"5",
")",
":",
"declarations",
"=",
"\"\"",
"before_loop",
"=",
"\"\"",
"in_loop",
"=",
"\"\"",
"after_loop",
"=",
"\"\"",
"for",
"index",
"in",
"range",
"(",
"n_volume_max",
")",
":",
"declarations",
"+=",
"\"uniform $sampler_type u_volumetex_{0:d};\\n\"",
".",
"format",
"(",
"index",
")",
"before_loop",
"+=",
"\"dummy = $sample(u_volumetex_{0:d}, loc).g;\\n\"",
".",
"format",
"(",
"index",
")",
"declarations",
"+=",
"\"uniform $sampler_type dummy1;\\n\"",
"declarations",
"+=",
"\"float dummy;\\n\"",
"for",
"label",
"in",
"sorted",
"(",
"volumes",
")",
":",
"index",
"=",
"volumes",
"[",
"label",
"]",
"[",
"'index'",
"]",
"# Global declarations",
"declarations",
"+=",
"\"uniform float u_weight_{0:d};\\n\"",
".",
"format",
"(",
"index",
")",
"declarations",
"+=",
"\"uniform int u_enabled_{0:d};\\n\"",
".",
"format",
"(",
"index",
")",
"# Declarations before the raytracing loop",
"before_loop",
"+=",
"\"float max_val_{0:d} = 0;\\n\"",
".",
"format",
"(",
"index",
")",
"# Calculation inside the main raytracing loop",
"in_loop",
"+=",
"\"if(u_enabled_{0:d} == 1) {{\\n\\n\"",
".",
"format",
"(",
"index",
")",
"if",
"clipped",
":",
"in_loop",
"+=",
"(",
"\"if(loc.r > u_clip_min.r && loc.r < u_clip_max.r &&\\n\"",
"\" loc.g > u_clip_min.g && loc.g < u_clip_max.g &&\\n\"",
"\" loc.b > u_clip_min.b && loc.b < u_clip_max.b) {\\n\\n\"",
")",
"in_loop",
"+=",
"\"// Sample texture for layer {0}\\n\"",
".",
"format",
"(",
"label",
")",
"in_loop",
"+=",
"\"val = $sample(u_volumetex_{0:d}, loc).g;\\n\"",
".",
"format",
"(",
"index",
")",
"if",
"volumes",
"[",
"label",
"]",
".",
"get",
"(",
"'multiply'",
")",
"is",
"not",
"None",
":",
"index_other",
"=",
"volumes",
"[",
"volumes",
"[",
"label",
"]",
"[",
"'multiply'",
"]",
"]",
"[",
"'index'",
"]",
"in_loop",
"+=",
"(",
"\"if (val != 0) {{ val *= $sample(u_volumetex_{0:d}, loc).g; }}\\n\"",
".",
"format",
"(",
"index_other",
")",
")",
"in_loop",
"+=",
"\"max_val_{0:d} = max(val, max_val_{0:d});\\n\\n\"",
".",
"format",
"(",
"index",
")",
"if",
"clipped",
":",
"in_loop",
"+=",
"\"}\\n\\n\"",
"in_loop",
"+=",
"\"}\\n\\n\"",
"# Calculation after the main loop",
"after_loop",
"+=",
"\"// Compute final color for layer {0}\\n\"",
".",
"format",
"(",
"label",
")",
"after_loop",
"+=",
"(",
"\"color = $cmap{0:d}(max_val_{0:d});\\n\"",
"\"color.a *= u_weight_{0:d};\\n\"",
"\"total_color += color.a * color;\\n\"",
"\"max_alpha = max(color.a, max_alpha);\\n\"",
"\"count += color.a;\\n\\n\"",
")",
".",
"format",
"(",
"index",
")",
"if",
"not",
"clipped",
":",
"before_loop",
"+=",
"\"\\nfloat val3 = u_clip_min.g + u_clip_max.g;\\n\\n\"",
"# Code esthetics",
"before_loop",
"=",
"indent",
"(",
"before_loop",
",",
"\" \"",
"*",
"4",
")",
".",
"strip",
"(",
")",
"in_loop",
"=",
"indent",
"(",
"in_loop",
",",
"\" \"",
"*",
"16",
")",
".",
"strip",
"(",
")",
"after_loop",
"=",
"indent",
"(",
"after_loop",
",",
"\" \"",
"*",
"4",
")",
".",
"strip",
"(",
")",
"return",
"FRAG_SHADER",
".",
"format",
"(",
"declarations",
"=",
"declarations",
",",
"before_loop",
"=",
"before_loop",
",",
"in_loop",
"=",
"in_loop",
",",
"after_loop",
"=",
"after_loop",
")"
] |
Get the fragment shader code - we use the shader_program object to determine
which layers are enabled and therefore what to include in the shader code.
|
[
"Get",
"the",
"fragment",
"shader",
"code",
"-",
"we",
"use",
"the",
"shader_program",
"object",
"to",
"determine",
"which",
"layers",
"are",
"enabled",
"and",
"therefore",
"what",
"to",
"include",
"in",
"the",
"shader",
"code",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/volume/shaders.py#L207-L280
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/egl.py
|
eglGetDisplay
|
def eglGetDisplay(display=EGL_DEFAULT_DISPLAY):
""" Connect to the EGL display server.
"""
res = _lib.eglGetDisplay(display)
if not res or res == EGL_NO_DISPLAY:
raise RuntimeError('Could not create display')
return res
|
python
|
def eglGetDisplay(display=EGL_DEFAULT_DISPLAY):
""" Connect to the EGL display server.
"""
res = _lib.eglGetDisplay(display)
if not res or res == EGL_NO_DISPLAY:
raise RuntimeError('Could not create display')
return res
|
[
"def",
"eglGetDisplay",
"(",
"display",
"=",
"EGL_DEFAULT_DISPLAY",
")",
":",
"res",
"=",
"_lib",
".",
"eglGetDisplay",
"(",
"display",
")",
"if",
"not",
"res",
"or",
"res",
"==",
"EGL_NO_DISPLAY",
":",
"raise",
"RuntimeError",
"(",
"'Could not create display'",
")",
"return",
"res"
] |
Connect to the EGL display server.
|
[
"Connect",
"to",
"the",
"EGL",
"display",
"server",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/egl.py#L233-L239
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/egl.py
|
eglInitialize
|
def eglInitialize(display):
""" Initialize EGL and return EGL version tuple.
"""
majorVersion = (_c_int*1)()
minorVersion = (_c_int*1)()
res = _lib.eglInitialize(display, majorVersion, minorVersion)
if res == EGL_FALSE:
raise RuntimeError('Could not initialize')
return majorVersion[0], minorVersion[0]
|
python
|
def eglInitialize(display):
""" Initialize EGL and return EGL version tuple.
"""
majorVersion = (_c_int*1)()
minorVersion = (_c_int*1)()
res = _lib.eglInitialize(display, majorVersion, minorVersion)
if res == EGL_FALSE:
raise RuntimeError('Could not initialize')
return majorVersion[0], minorVersion[0]
|
[
"def",
"eglInitialize",
"(",
"display",
")",
":",
"majorVersion",
"=",
"(",
"_c_int",
"*",
"1",
")",
"(",
")",
"minorVersion",
"=",
"(",
"_c_int",
"*",
"1",
")",
"(",
")",
"res",
"=",
"_lib",
".",
"eglInitialize",
"(",
"display",
",",
"majorVersion",
",",
"minorVersion",
")",
"if",
"res",
"==",
"EGL_FALSE",
":",
"raise",
"RuntimeError",
"(",
"'Could not initialize'",
")",
"return",
"majorVersion",
"[",
"0",
"]",
",",
"minorVersion",
"[",
"0",
"]"
] |
Initialize EGL and return EGL version tuple.
|
[
"Initialize",
"EGL",
"and",
"return",
"EGL",
"version",
"tuple",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/egl.py#L242-L250
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/egl.py
|
eglQueryString
|
def eglQueryString(display, name):
""" Query string from display
"""
out = _lib.eglQueryString(display, name)
if not out:
raise RuntimeError('Could not query %s' % name)
return out
|
python
|
def eglQueryString(display, name):
""" Query string from display
"""
out = _lib.eglQueryString(display, name)
if not out:
raise RuntimeError('Could not query %s' % name)
return out
|
[
"def",
"eglQueryString",
"(",
"display",
",",
"name",
")",
":",
"out",
"=",
"_lib",
".",
"eglQueryString",
"(",
"display",
",",
"name",
")",
"if",
"not",
"out",
":",
"raise",
"RuntimeError",
"(",
"'Could not query %s'",
"%",
"name",
")",
"return",
"out"
] |
Query string from display
|
[
"Query",
"string",
"from",
"display"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/egl.py#L259-L265
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_edges
|
def get_edges(self, indexed=None):
"""Edges of the mesh
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 3) array of vertex indices,
two per edge in the mesh.
If indexed is 'faces', then return (Nf, 3, 2) array of vertex
indices with 3 edges per face, and two vertices per edge.
Returns
-------
edges : ndarray
The edges.
"""
if indexed is None:
if self._edges is None:
self._compute_edges(indexed=None)
return self._edges
elif indexed == 'faces':
if self._edges_indexed_by_faces is None:
self._compute_edges(indexed='faces')
return self._edges_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_edges(self, indexed=None):
"""Edges of the mesh
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 3) array of vertex indices,
two per edge in the mesh.
If indexed is 'faces', then return (Nf, 3, 2) array of vertex
indices with 3 edges per face, and two vertices per edge.
Returns
-------
edges : ndarray
The edges.
"""
if indexed is None:
if self._edges is None:
self._compute_edges(indexed=None)
return self._edges
elif indexed == 'faces':
if self._edges_indexed_by_faces is None:
self._compute_edges(indexed='faces')
return self._edges_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_edges",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"indexed",
"is",
"None",
":",
"if",
"self",
".",
"_edges",
"is",
"None",
":",
"self",
".",
"_compute_edges",
"(",
"indexed",
"=",
"None",
")",
"return",
"self",
".",
"_edges",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"self",
".",
"_edges_indexed_by_faces",
"is",
"None",
":",
"self",
".",
"_compute_edges",
"(",
"indexed",
"=",
"'faces'",
")",
"return",
"self",
".",
"_edges_indexed_by_faces",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Edges of the mesh
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 3) array of vertex indices,
two per edge in the mesh.
If indexed is 'faces', then return (Nf, 3, 2) array of vertex
indices with 3 edges per face, and two vertices per edge.
Returns
-------
edges : ndarray
The edges.
|
[
"Edges",
"of",
"the",
"mesh",
"Parameters",
"----------",
"indexed",
":",
"str",
"|",
"None",
"If",
"indexed",
"is",
"None",
"return",
"(",
"Nf",
"3",
")",
"array",
"of",
"vertex",
"indices",
"two",
"per",
"edge",
"in",
"the",
"mesh",
".",
"If",
"indexed",
"is",
"faces",
"then",
"return",
"(",
"Nf",
"3",
"2",
")",
"array",
"of",
"vertex",
"indices",
"with",
"3",
"edges",
"per",
"face",
"and",
"two",
"vertices",
"per",
"edge",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L122-L148
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.set_faces
|
def set_faces(self, faces):
"""Set the faces
Parameters
----------
faces : ndarray
(Nf, 3) array of faces. Each row in the array contains
three indices into the vertex array, specifying the three corners
of a triangular face.
"""
self._faces = faces
self._edges = None
self._edges_indexed_by_faces = None
self._vertex_faces = None
self._vertices_indexed_by_faces = None
self.reset_normals()
self._vertex_colors_indexed_by_faces = None
self._face_colors_indexed_by_faces = None
|
python
|
def set_faces(self, faces):
"""Set the faces
Parameters
----------
faces : ndarray
(Nf, 3) array of faces. Each row in the array contains
three indices into the vertex array, specifying the three corners
of a triangular face.
"""
self._faces = faces
self._edges = None
self._edges_indexed_by_faces = None
self._vertex_faces = None
self._vertices_indexed_by_faces = None
self.reset_normals()
self._vertex_colors_indexed_by_faces = None
self._face_colors_indexed_by_faces = None
|
[
"def",
"set_faces",
"(",
"self",
",",
"faces",
")",
":",
"self",
".",
"_faces",
"=",
"faces",
"self",
".",
"_edges",
"=",
"None",
"self",
".",
"_edges_indexed_by_faces",
"=",
"None",
"self",
".",
"_vertex_faces",
"=",
"None",
"self",
".",
"_vertices_indexed_by_faces",
"=",
"None",
"self",
".",
"reset_normals",
"(",
")",
"self",
".",
"_vertex_colors_indexed_by_faces",
"=",
"None",
"self",
".",
"_face_colors_indexed_by_faces",
"=",
"None"
] |
Set the faces
Parameters
----------
faces : ndarray
(Nf, 3) array of faces. Each row in the array contains
three indices into the vertex array, specifying the three corners
of a triangular face.
|
[
"Set",
"the",
"faces"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L150-L167
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_vertices
|
def get_vertices(self, indexed=None):
"""Get the vertices
Parameters
----------
indexed : str | None
If Note, return an array (N,3) of the positions of vertices in
the mesh. By default, each unique vertex appears only once.
If indexed is 'faces', then the array will instead contain three
vertices per face in the mesh (and a single vertex may appear more
than once in the array).
Returns
-------
vertices : ndarray
The vertices.
"""
if indexed is None:
if (self._vertices is None and
self._vertices_indexed_by_faces is not None):
self._compute_unindexed_vertices()
return self._vertices
elif indexed == 'faces':
if (self._vertices_indexed_by_faces is None and
self._vertices is not None):
self._vertices_indexed_by_faces = \
self._vertices[self.get_faces()]
return self._vertices_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_vertices(self, indexed=None):
"""Get the vertices
Parameters
----------
indexed : str | None
If Note, return an array (N,3) of the positions of vertices in
the mesh. By default, each unique vertex appears only once.
If indexed is 'faces', then the array will instead contain three
vertices per face in the mesh (and a single vertex may appear more
than once in the array).
Returns
-------
vertices : ndarray
The vertices.
"""
if indexed is None:
if (self._vertices is None and
self._vertices_indexed_by_faces is not None):
self._compute_unindexed_vertices()
return self._vertices
elif indexed == 'faces':
if (self._vertices_indexed_by_faces is None and
self._vertices is not None):
self._vertices_indexed_by_faces = \
self._vertices[self.get_faces()]
return self._vertices_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_vertices",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"indexed",
"is",
"None",
":",
"if",
"(",
"self",
".",
"_vertices",
"is",
"None",
"and",
"self",
".",
"_vertices_indexed_by_faces",
"is",
"not",
"None",
")",
":",
"self",
".",
"_compute_unindexed_vertices",
"(",
")",
"return",
"self",
".",
"_vertices",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"(",
"self",
".",
"_vertices_indexed_by_faces",
"is",
"None",
"and",
"self",
".",
"_vertices",
"is",
"not",
"None",
")",
":",
"self",
".",
"_vertices_indexed_by_faces",
"=",
"self",
".",
"_vertices",
"[",
"self",
".",
"get_faces",
"(",
")",
"]",
"return",
"self",
".",
"_vertices_indexed_by_faces",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Get the vertices
Parameters
----------
indexed : str | None
If Note, return an array (N,3) of the positions of vertices in
the mesh. By default, each unique vertex appears only once.
If indexed is 'faces', then the array will instead contain three
vertices per face in the mesh (and a single vertex may appear more
than once in the array).
Returns
-------
vertices : ndarray
The vertices.
|
[
"Get",
"the",
"vertices"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L169-L198
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_bounds
|
def get_bounds(self):
"""Get the mesh bounds
Returns
-------
bounds : list
A list of tuples of mesh bounds.
"""
if self._vertices_indexed_by_faces is not None:
v = self._vertices_indexed_by_faces
elif self._vertices is not None:
v = self._vertices
else:
return None
bounds = [(v[:, ax].min(), v[:, ax].max()) for ax in range(v.shape[1])]
return bounds
|
python
|
def get_bounds(self):
"""Get the mesh bounds
Returns
-------
bounds : list
A list of tuples of mesh bounds.
"""
if self._vertices_indexed_by_faces is not None:
v = self._vertices_indexed_by_faces
elif self._vertices is not None:
v = self._vertices
else:
return None
bounds = [(v[:, ax].min(), v[:, ax].max()) for ax in range(v.shape[1])]
return bounds
|
[
"def",
"get_bounds",
"(",
"self",
")",
":",
"if",
"self",
".",
"_vertices_indexed_by_faces",
"is",
"not",
"None",
":",
"v",
"=",
"self",
".",
"_vertices_indexed_by_faces",
"elif",
"self",
".",
"_vertices",
"is",
"not",
"None",
":",
"v",
"=",
"self",
".",
"_vertices",
"else",
":",
"return",
"None",
"bounds",
"=",
"[",
"(",
"v",
"[",
":",
",",
"ax",
"]",
".",
"min",
"(",
")",
",",
"v",
"[",
":",
",",
"ax",
"]",
".",
"max",
"(",
")",
")",
"for",
"ax",
"in",
"range",
"(",
"v",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"return",
"bounds"
] |
Get the mesh bounds
Returns
-------
bounds : list
A list of tuples of mesh bounds.
|
[
"Get",
"the",
"mesh",
"bounds"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L200-L215
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.set_vertices
|
def set_vertices(self, verts=None, indexed=None, reset_normals=True):
"""Set the mesh vertices
Parameters
----------
verts : ndarray | None
The array (Nv, 3) of vertex coordinates.
indexed : str | None
If indexed=='faces', then the data must have shape (Nf, 3, 3) and
is assumed to be already indexed as a list of faces. This will
cause any pre-existing normal vectors to be cleared unless
reset_normals=False.
reset_normals : bool
If True, reset the normals.
"""
if indexed is None:
if verts is not None:
self._vertices = verts
self._vertices_indexed_by_faces = None
elif indexed == 'faces':
self._vertices = None
if verts is not None:
self._vertices_indexed_by_faces = verts
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
if reset_normals:
self.reset_normals()
|
python
|
def set_vertices(self, verts=None, indexed=None, reset_normals=True):
"""Set the mesh vertices
Parameters
----------
verts : ndarray | None
The array (Nv, 3) of vertex coordinates.
indexed : str | None
If indexed=='faces', then the data must have shape (Nf, 3, 3) and
is assumed to be already indexed as a list of faces. This will
cause any pre-existing normal vectors to be cleared unless
reset_normals=False.
reset_normals : bool
If True, reset the normals.
"""
if indexed is None:
if verts is not None:
self._vertices = verts
self._vertices_indexed_by_faces = None
elif indexed == 'faces':
self._vertices = None
if verts is not None:
self._vertices_indexed_by_faces = verts
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
if reset_normals:
self.reset_normals()
|
[
"def",
"set_vertices",
"(",
"self",
",",
"verts",
"=",
"None",
",",
"indexed",
"=",
"None",
",",
"reset_normals",
"=",
"True",
")",
":",
"if",
"indexed",
"is",
"None",
":",
"if",
"verts",
"is",
"not",
"None",
":",
"self",
".",
"_vertices",
"=",
"verts",
"self",
".",
"_vertices_indexed_by_faces",
"=",
"None",
"elif",
"indexed",
"==",
"'faces'",
":",
"self",
".",
"_vertices",
"=",
"None",
"if",
"verts",
"is",
"not",
"None",
":",
"self",
".",
"_vertices_indexed_by_faces",
"=",
"verts",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")",
"if",
"reset_normals",
":",
"self",
".",
"reset_normals",
"(",
")"
] |
Set the mesh vertices
Parameters
----------
verts : ndarray | None
The array (Nv, 3) of vertex coordinates.
indexed : str | None
If indexed=='faces', then the data must have shape (Nf, 3, 3) and
is assumed to be already indexed as a list of faces. This will
cause any pre-existing normal vectors to be cleared unless
reset_normals=False.
reset_normals : bool
If True, reset the normals.
|
[
"Set",
"the",
"mesh",
"vertices"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L217-L244
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.has_vertex_color
|
def has_vertex_color(self):
"""Return True if this data set has vertex color information"""
for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces,
self._vertex_colors_indexed_by_edges):
if v is not None:
return True
return False
|
python
|
def has_vertex_color(self):
"""Return True if this data set has vertex color information"""
for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces,
self._vertex_colors_indexed_by_edges):
if v is not None:
return True
return False
|
[
"def",
"has_vertex_color",
"(",
"self",
")",
":",
"for",
"v",
"in",
"(",
"self",
".",
"_vertex_colors",
",",
"self",
".",
"_vertex_colors_indexed_by_faces",
",",
"self",
".",
"_vertex_colors_indexed_by_edges",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] |
Return True if this data set has vertex color information
|
[
"Return",
"True",
"if",
"this",
"data",
"set",
"has",
"vertex",
"color",
"information"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L260-L266
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.has_face_color
|
def has_face_color(self):
"""Return True if this data set has face color information"""
for v in (self._face_colors, self._face_colors_indexed_by_faces,
self._face_colors_indexed_by_edges):
if v is not None:
return True
return False
|
python
|
def has_face_color(self):
"""Return True if this data set has face color information"""
for v in (self._face_colors, self._face_colors_indexed_by_faces,
self._face_colors_indexed_by_edges):
if v is not None:
return True
return False
|
[
"def",
"has_face_color",
"(",
"self",
")",
":",
"for",
"v",
"in",
"(",
"self",
".",
"_face_colors",
",",
"self",
".",
"_face_colors_indexed_by_faces",
",",
"self",
".",
"_face_colors_indexed_by_edges",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"False"
] |
Return True if this data set has face color information
|
[
"Return",
"True",
"if",
"this",
"data",
"set",
"has",
"face",
"color",
"information"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L268-L274
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_face_normals
|
def get_face_normals(self, indexed=None):
"""Get face normals
Parameters
----------
indexed : str | None
If None, return an array (Nf, 3) of normal vectors for each face.
If 'faces', then instead return an indexed array (Nf, 3, 3)
(this is just the same array with each vector copied three times).
Returns
-------
normals : ndarray
The normals.
"""
if self._face_normals is None:
v = self.get_vertices(indexed='faces')
self._face_normals = np.cross(v[:, 1] - v[:, 0],
v[:, 2] - v[:, 0])
if indexed is None:
return self._face_normals
elif indexed == 'faces':
if self._face_normals_indexed_by_faces is None:
norms = np.empty((self._face_normals.shape[0], 3, 3),
dtype=np.float32)
norms[:] = self._face_normals[:, np.newaxis, :]
self._face_normals_indexed_by_faces = norms
return self._face_normals_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_face_normals(self, indexed=None):
"""Get face normals
Parameters
----------
indexed : str | None
If None, return an array (Nf, 3) of normal vectors for each face.
If 'faces', then instead return an indexed array (Nf, 3, 3)
(this is just the same array with each vector copied three times).
Returns
-------
normals : ndarray
The normals.
"""
if self._face_normals is None:
v = self.get_vertices(indexed='faces')
self._face_normals = np.cross(v[:, 1] - v[:, 0],
v[:, 2] - v[:, 0])
if indexed is None:
return self._face_normals
elif indexed == 'faces':
if self._face_normals_indexed_by_faces is None:
norms = np.empty((self._face_normals.shape[0], 3, 3),
dtype=np.float32)
norms[:] = self._face_normals[:, np.newaxis, :]
self._face_normals_indexed_by_faces = norms
return self._face_normals_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_face_normals",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"self",
".",
"_face_normals",
"is",
"None",
":",
"v",
"=",
"self",
".",
"get_vertices",
"(",
"indexed",
"=",
"'faces'",
")",
"self",
".",
"_face_normals",
"=",
"np",
".",
"cross",
"(",
"v",
"[",
":",
",",
"1",
"]",
"-",
"v",
"[",
":",
",",
"0",
"]",
",",
"v",
"[",
":",
",",
"2",
"]",
"-",
"v",
"[",
":",
",",
"0",
"]",
")",
"if",
"indexed",
"is",
"None",
":",
"return",
"self",
".",
"_face_normals",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"self",
".",
"_face_normals_indexed_by_faces",
"is",
"None",
":",
"norms",
"=",
"np",
".",
"empty",
"(",
"(",
"self",
".",
"_face_normals",
".",
"shape",
"[",
"0",
"]",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"norms",
"[",
":",
"]",
"=",
"self",
".",
"_face_normals",
"[",
":",
",",
"np",
".",
"newaxis",
",",
":",
"]",
"self",
".",
"_face_normals_indexed_by_faces",
"=",
"norms",
"return",
"self",
".",
"_face_normals_indexed_by_faces",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Get face normals
Parameters
----------
indexed : str | None
If None, return an array (Nf, 3) of normal vectors for each face.
If 'faces', then instead return an indexed array (Nf, 3, 3)
(this is just the same array with each vector copied three times).
Returns
-------
normals : ndarray
The normals.
|
[
"Get",
"face",
"normals"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L276-L306
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_vertex_normals
|
def get_vertex_normals(self, indexed=None):
"""Get vertex normals
Parameters
----------
indexed : str | None
If None, return an (N, 3) array of normal vectors with one entry
per unique vertex in the mesh. If indexed is 'faces', then the
array will contain three normal vectors per face (and some
vertices may be repeated).
Returns
-------
normals : ndarray
The normals.
"""
if self._vertex_normals is None:
faceNorms = self.get_face_normals()
vertFaces = self.get_vertex_faces()
self._vertex_normals = np.empty(self._vertices.shape,
dtype=np.float32)
for vindex in xrange(self._vertices.shape[0]):
faces = vertFaces[vindex]
if len(faces) == 0:
self._vertex_normals[vindex] = (0, 0, 0)
continue
norms = faceNorms[faces] # get all face normals
norm = norms.sum(axis=0) # sum normals
renorm = (norm**2).sum()**0.5
if renorm > 0:
norm /= renorm
self._vertex_normals[vindex] = norm
if indexed is None:
return self._vertex_normals
elif indexed == 'faces':
return self._vertex_normals[self.get_faces()]
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_vertex_normals(self, indexed=None):
"""Get vertex normals
Parameters
----------
indexed : str | None
If None, return an (N, 3) array of normal vectors with one entry
per unique vertex in the mesh. If indexed is 'faces', then the
array will contain three normal vectors per face (and some
vertices may be repeated).
Returns
-------
normals : ndarray
The normals.
"""
if self._vertex_normals is None:
faceNorms = self.get_face_normals()
vertFaces = self.get_vertex_faces()
self._vertex_normals = np.empty(self._vertices.shape,
dtype=np.float32)
for vindex in xrange(self._vertices.shape[0]):
faces = vertFaces[vindex]
if len(faces) == 0:
self._vertex_normals[vindex] = (0, 0, 0)
continue
norms = faceNorms[faces] # get all face normals
norm = norms.sum(axis=0) # sum normals
renorm = (norm**2).sum()**0.5
if renorm > 0:
norm /= renorm
self._vertex_normals[vindex] = norm
if indexed is None:
return self._vertex_normals
elif indexed == 'faces':
return self._vertex_normals[self.get_faces()]
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_vertex_normals",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"self",
".",
"_vertex_normals",
"is",
"None",
":",
"faceNorms",
"=",
"self",
".",
"get_face_normals",
"(",
")",
"vertFaces",
"=",
"self",
".",
"get_vertex_faces",
"(",
")",
"self",
".",
"_vertex_normals",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"_vertices",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"vindex",
"in",
"xrange",
"(",
"self",
".",
"_vertices",
".",
"shape",
"[",
"0",
"]",
")",
":",
"faces",
"=",
"vertFaces",
"[",
"vindex",
"]",
"if",
"len",
"(",
"faces",
")",
"==",
"0",
":",
"self",
".",
"_vertex_normals",
"[",
"vindex",
"]",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"continue",
"norms",
"=",
"faceNorms",
"[",
"faces",
"]",
"# get all face normals",
"norm",
"=",
"norms",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"# sum normals",
"renorm",
"=",
"(",
"norm",
"**",
"2",
")",
".",
"sum",
"(",
")",
"**",
"0.5",
"if",
"renorm",
">",
"0",
":",
"norm",
"/=",
"renorm",
"self",
".",
"_vertex_normals",
"[",
"vindex",
"]",
"=",
"norm",
"if",
"indexed",
"is",
"None",
":",
"return",
"self",
".",
"_vertex_normals",
"elif",
"indexed",
"==",
"'faces'",
":",
"return",
"self",
".",
"_vertex_normals",
"[",
"self",
".",
"get_faces",
"(",
")",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Get vertex normals
Parameters
----------
indexed : str | None
If None, return an (N, 3) array of normal vectors with one entry
per unique vertex in the mesh. If indexed is 'faces', then the
array will contain three normal vectors per face (and some
vertices may be repeated).
Returns
-------
normals : ndarray
The normals.
|
[
"Get",
"vertex",
"normals"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L308-L346
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_vertex_colors
|
def get_vertex_colors(self, indexed=None):
"""Get vertex colors
Parameters
----------
indexed : str | None
If None, return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
Returns
-------
colors : ndarray
The vertex colors.
"""
if indexed is None:
return self._vertex_colors
elif indexed == 'faces':
if self._vertex_colors_indexed_by_faces is None:
self._vertex_colors_indexed_by_faces = \
self._vertex_colors[self.get_faces()]
return self._vertex_colors_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_vertex_colors(self, indexed=None):
"""Get vertex colors
Parameters
----------
indexed : str | None
If None, return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
Returns
-------
colors : ndarray
The vertex colors.
"""
if indexed is None:
return self._vertex_colors
elif indexed == 'faces':
if self._vertex_colors_indexed_by_faces is None:
self._vertex_colors_indexed_by_faces = \
self._vertex_colors[self.get_faces()]
return self._vertex_colors_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_vertex_colors",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"indexed",
"is",
"None",
":",
"return",
"self",
".",
"_vertex_colors",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"self",
".",
"_vertex_colors_indexed_by_faces",
"is",
"None",
":",
"self",
".",
"_vertex_colors_indexed_by_faces",
"=",
"self",
".",
"_vertex_colors",
"[",
"self",
".",
"get_faces",
"(",
")",
"]",
"return",
"self",
".",
"_vertex_colors_indexed_by_faces",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Get vertex colors
Parameters
----------
indexed : str | None
If None, return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
Returns
-------
colors : ndarray
The vertex colors.
|
[
"Get",
"vertex",
"colors"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L348-L371
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.set_vertex_colors
|
def set_vertex_colors(self, colors, indexed=None):
"""Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
"""
colors = _fix_colors(np.asarray(colors))
if indexed is None:
if colors.ndim != 2:
raise ValueError('colors must be 2D if indexed is None')
if colors.shape[0] != self.n_vertices:
raise ValueError('incorrect number of colors %s, expected %s'
% (colors.shape[0], self.n_vertices))
self._vertex_colors = colors
self._vertex_colors_indexed_by_faces = None
elif indexed == 'faces':
if colors.ndim != 3:
raise ValueError('colors must be 3D if indexed is "faces"')
if colors.shape[0] != self.n_faces:
raise ValueError('incorrect number of faces')
self._vertex_colors = None
self._vertex_colors_indexed_by_faces = colors
else:
raise ValueError('indexed must be None or "faces"')
|
python
|
def set_vertex_colors(self, colors, indexed=None):
"""Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
"""
colors = _fix_colors(np.asarray(colors))
if indexed is None:
if colors.ndim != 2:
raise ValueError('colors must be 2D if indexed is None')
if colors.shape[0] != self.n_vertices:
raise ValueError('incorrect number of colors %s, expected %s'
% (colors.shape[0], self.n_vertices))
self._vertex_colors = colors
self._vertex_colors_indexed_by_faces = None
elif indexed == 'faces':
if colors.ndim != 3:
raise ValueError('colors must be 3D if indexed is "faces"')
if colors.shape[0] != self.n_faces:
raise ValueError('incorrect number of faces')
self._vertex_colors = None
self._vertex_colors_indexed_by_faces = colors
else:
raise ValueError('indexed must be None or "faces"')
|
[
"def",
"set_vertex_colors",
"(",
"self",
",",
"colors",
",",
"indexed",
"=",
"None",
")",
":",
"colors",
"=",
"_fix_colors",
"(",
"np",
".",
"asarray",
"(",
"colors",
")",
")",
"if",
"indexed",
"is",
"None",
":",
"if",
"colors",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'colors must be 2D if indexed is None'",
")",
"if",
"colors",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"n_vertices",
":",
"raise",
"ValueError",
"(",
"'incorrect number of colors %s, expected %s'",
"%",
"(",
"colors",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"n_vertices",
")",
")",
"self",
".",
"_vertex_colors",
"=",
"colors",
"self",
".",
"_vertex_colors_indexed_by_faces",
"=",
"None",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"colors",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'colors must be 3D if indexed is \"faces\"'",
")",
"if",
"colors",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"n_faces",
":",
"raise",
"ValueError",
"(",
"'incorrect number of faces'",
")",
"self",
".",
"_vertex_colors",
"=",
"None",
"self",
".",
"_vertex_colors_indexed_by_faces",
"=",
"colors",
"else",
":",
"raise",
"ValueError",
"(",
"'indexed must be None or \"faces\"'",
")"
] |
Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
|
[
"Set",
"the",
"vertex",
"color",
"array"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L373-L401
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_face_colors
|
def get_face_colors(self, indexed=None):
"""Get the face colors
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 4) array of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
Returns
-------
colors : ndarray
The colors.
"""
if indexed is None:
return self._face_colors
elif indexed == 'faces':
if (self._face_colors_indexed_by_faces is None and
self._face_colors is not None):
Nf = self._face_colors.shape[0]
self._face_colors_indexed_by_faces = \
np.empty((Nf, 3, 4), dtype=self._face_colors.dtype)
self._face_colors_indexed_by_faces[:] = \
self._face_colors.reshape(Nf, 1, 4)
return self._face_colors_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
python
|
def get_face_colors(self, indexed=None):
"""Get the face colors
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 4) array of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
Returns
-------
colors : ndarray
The colors.
"""
if indexed is None:
return self._face_colors
elif indexed == 'faces':
if (self._face_colors_indexed_by_faces is None and
self._face_colors is not None):
Nf = self._face_colors.shape[0]
self._face_colors_indexed_by_faces = \
np.empty((Nf, 3, 4), dtype=self._face_colors.dtype)
self._face_colors_indexed_by_faces[:] = \
self._face_colors.reshape(Nf, 1, 4)
return self._face_colors_indexed_by_faces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
|
[
"def",
"get_face_colors",
"(",
"self",
",",
"indexed",
"=",
"None",
")",
":",
"if",
"indexed",
"is",
"None",
":",
"return",
"self",
".",
"_face_colors",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"(",
"self",
".",
"_face_colors_indexed_by_faces",
"is",
"None",
"and",
"self",
".",
"_face_colors",
"is",
"not",
"None",
")",
":",
"Nf",
"=",
"self",
".",
"_face_colors",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"_face_colors_indexed_by_faces",
"=",
"np",
".",
"empty",
"(",
"(",
"Nf",
",",
"3",
",",
"4",
")",
",",
"dtype",
"=",
"self",
".",
"_face_colors",
".",
"dtype",
")",
"self",
".",
"_face_colors_indexed_by_faces",
"[",
":",
"]",
"=",
"self",
".",
"_face_colors",
".",
"reshape",
"(",
"Nf",
",",
"1",
",",
"4",
")",
"return",
"self",
".",
"_face_colors_indexed_by_faces",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid indexing mode. Accepts: None, 'faces'\"",
")"
] |
Get the face colors
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 4) array of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
Returns
-------
colors : ndarray
The colors.
|
[
"Get",
"the",
"face",
"colors"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L403-L431
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.set_face_colors
|
def set_face_colors(self, colors, indexed=None):
"""Set the face color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nf, 4) (indexed by face),
or shape (Nf, 3, 4) (face colors indexed by faces).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
"""
colors = _fix_colors(colors)
if colors.shape[0] != self.n_faces:
raise ValueError('incorrect number of colors %s, expected %s'
% (colors.shape[0], self.n_faces))
if indexed is None:
if colors.ndim != 2:
raise ValueError('colors must be 2D if indexed is None')
self._face_colors = colors
self._face_colors_indexed_by_faces = None
elif indexed == 'faces':
if colors.ndim != 3:
raise ValueError('colors must be 3D if indexed is "faces"')
self._face_colors = None
self._face_colors_indexed_by_faces = colors
else:
raise ValueError('indexed must be None or "faces"')
|
python
|
def set_face_colors(self, colors, indexed=None):
"""Set the face color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nf, 4) (indexed by face),
or shape (Nf, 3, 4) (face colors indexed by faces).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
"""
colors = _fix_colors(colors)
if colors.shape[0] != self.n_faces:
raise ValueError('incorrect number of colors %s, expected %s'
% (colors.shape[0], self.n_faces))
if indexed is None:
if colors.ndim != 2:
raise ValueError('colors must be 2D if indexed is None')
self._face_colors = colors
self._face_colors_indexed_by_faces = None
elif indexed == 'faces':
if colors.ndim != 3:
raise ValueError('colors must be 3D if indexed is "faces"')
self._face_colors = None
self._face_colors_indexed_by_faces = colors
else:
raise ValueError('indexed must be None or "faces"')
|
[
"def",
"set_face_colors",
"(",
"self",
",",
"colors",
",",
"indexed",
"=",
"None",
")",
":",
"colors",
"=",
"_fix_colors",
"(",
"colors",
")",
"if",
"colors",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"n_faces",
":",
"raise",
"ValueError",
"(",
"'incorrect number of colors %s, expected %s'",
"%",
"(",
"colors",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"n_faces",
")",
")",
"if",
"indexed",
"is",
"None",
":",
"if",
"colors",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'colors must be 2D if indexed is None'",
")",
"self",
".",
"_face_colors",
"=",
"colors",
"self",
".",
"_face_colors_indexed_by_faces",
"=",
"None",
"elif",
"indexed",
"==",
"'faces'",
":",
"if",
"colors",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'colors must be 3D if indexed is \"faces\"'",
")",
"self",
".",
"_face_colors",
"=",
"None",
"self",
".",
"_face_colors_indexed_by_faces",
"=",
"colors",
"else",
":",
"raise",
"ValueError",
"(",
"'indexed must be None or \"faces\"'",
")"
] |
Set the face color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nf, 4) (indexed by face),
or shape (Nf, 3, 4) (face colors indexed by faces).
indexed : str | None
Should be 'faces' if colors are indexed by faces.
|
[
"Set",
"the",
"face",
"color",
"array"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L433-L459
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.n_faces
|
def n_faces(self):
"""The number of faces in the mesh"""
if self._faces is not None:
return self._faces.shape[0]
elif self._vertices_indexed_by_faces is not None:
return self._vertices_indexed_by_faces.shape[0]
|
python
|
def n_faces(self):
"""The number of faces in the mesh"""
if self._faces is not None:
return self._faces.shape[0]
elif self._vertices_indexed_by_faces is not None:
return self._vertices_indexed_by_faces.shape[0]
|
[
"def",
"n_faces",
"(",
"self",
")",
":",
"if",
"self",
".",
"_faces",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_faces",
".",
"shape",
"[",
"0",
"]",
"elif",
"self",
".",
"_vertices_indexed_by_faces",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_vertices_indexed_by_faces",
".",
"shape",
"[",
"0",
"]"
] |
The number of faces in the mesh
|
[
"The",
"number",
"of",
"faces",
"in",
"the",
"mesh"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L462-L467
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.get_vertex_faces
|
def get_vertex_faces(self):
"""
List mapping each vertex index to a list of face indices that use it.
"""
if self._vertex_faces is None:
self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))]
for i in xrange(self._faces.shape[0]):
face = self._faces[i]
for ind in face:
self._vertex_faces[ind].append(i)
return self._vertex_faces
|
python
|
def get_vertex_faces(self):
"""
List mapping each vertex index to a list of face indices that use it.
"""
if self._vertex_faces is None:
self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))]
for i in xrange(self._faces.shape[0]):
face = self._faces[i]
for ind in face:
self._vertex_faces[ind].append(i)
return self._vertex_faces
|
[
"def",
"get_vertex_faces",
"(",
"self",
")",
":",
"if",
"self",
".",
"_vertex_faces",
"is",
"None",
":",
"self",
".",
"_vertex_faces",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"get_vertices",
"(",
")",
")",
")",
"]",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"_faces",
".",
"shape",
"[",
"0",
"]",
")",
":",
"face",
"=",
"self",
".",
"_faces",
"[",
"i",
"]",
"for",
"ind",
"in",
"face",
":",
"self",
".",
"_vertex_faces",
"[",
"ind",
"]",
".",
"append",
"(",
"i",
")",
"return",
"self",
".",
"_vertex_faces"
] |
List mapping each vertex index to a list of face indices that use it.
|
[
"List",
"mapping",
"each",
"vertex",
"index",
"to",
"a",
"list",
"of",
"face",
"indices",
"that",
"use",
"it",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L510-L520
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.save
|
def save(self):
"""Serialize this mesh to a string appropriate for disk storage
Returns
-------
state : dict
The state.
"""
import pickle
if self._faces is not None:
names = ['_vertices', '_faces']
else:
names = ['_vertices_indexed_by_faces']
if self._vertex_colors is not None:
names.append('_vertex_colors')
elif self._vertex_colors_indexed_by_faces is not None:
names.append('_vertex_colors_indexed_by_faces')
if self._face_colors is not None:
names.append('_face_colors')
elif self._face_colors_indexed_by_faces is not None:
names.append('_face_colors_indexed_by_faces')
state = dict([(n, getattr(self, n)) for n in names])
return pickle.dumps(state)
|
python
|
def save(self):
"""Serialize this mesh to a string appropriate for disk storage
Returns
-------
state : dict
The state.
"""
import pickle
if self._faces is not None:
names = ['_vertices', '_faces']
else:
names = ['_vertices_indexed_by_faces']
if self._vertex_colors is not None:
names.append('_vertex_colors')
elif self._vertex_colors_indexed_by_faces is not None:
names.append('_vertex_colors_indexed_by_faces')
if self._face_colors is not None:
names.append('_face_colors')
elif self._face_colors_indexed_by_faces is not None:
names.append('_face_colors_indexed_by_faces')
state = dict([(n, getattr(self, n)) for n in names])
return pickle.dumps(state)
|
[
"def",
"save",
"(",
"self",
")",
":",
"import",
"pickle",
"if",
"self",
".",
"_faces",
"is",
"not",
"None",
":",
"names",
"=",
"[",
"'_vertices'",
",",
"'_faces'",
"]",
"else",
":",
"names",
"=",
"[",
"'_vertices_indexed_by_faces'",
"]",
"if",
"self",
".",
"_vertex_colors",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"'_vertex_colors'",
")",
"elif",
"self",
".",
"_vertex_colors_indexed_by_faces",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"'_vertex_colors_indexed_by_faces'",
")",
"if",
"self",
".",
"_face_colors",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"'_face_colors'",
")",
"elif",
"self",
".",
"_face_colors_indexed_by_faces",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"'_face_colors_indexed_by_faces'",
")",
"state",
"=",
"dict",
"(",
"[",
"(",
"n",
",",
"getattr",
"(",
"self",
",",
"n",
")",
")",
"for",
"n",
"in",
"names",
"]",
")",
"return",
"pickle",
".",
"dumps",
"(",
"state",
")"
] |
Serialize this mesh to a string appropriate for disk storage
Returns
-------
state : dict
The state.
|
[
"Serialize",
"this",
"mesh",
"to",
"a",
"string",
"appropriate",
"for",
"disk",
"storage"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L558-L583
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/geometry/meshdata.py
|
MeshData.restore
|
def restore(self, state):
"""Restore the state of a mesh previously saved using save()
Parameters
----------
state : dict
The previous state.
"""
import pickle
state = pickle.loads(state)
for k in state:
if isinstance(state[k], list):
state[k] = np.array(state[k])
setattr(self, k, state[k])
|
python
|
def restore(self, state):
"""Restore the state of a mesh previously saved using save()
Parameters
----------
state : dict
The previous state.
"""
import pickle
state = pickle.loads(state)
for k in state:
if isinstance(state[k], list):
state[k] = np.array(state[k])
setattr(self, k, state[k])
|
[
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"import",
"pickle",
"state",
"=",
"pickle",
".",
"loads",
"(",
"state",
")",
"for",
"k",
"in",
"state",
":",
"if",
"isinstance",
"(",
"state",
"[",
"k",
"]",
",",
"list",
")",
":",
"state",
"[",
"k",
"]",
"=",
"np",
".",
"array",
"(",
"state",
"[",
"k",
"]",
")",
"setattr",
"(",
"self",
",",
"k",
",",
"state",
"[",
"k",
"]",
")"
] |
Restore the state of a mesh previously saved using save()
Parameters
----------
state : dict
The previous state.
|
[
"Restore",
"the",
"state",
"of",
"a",
"mesh",
"previously",
"saved",
"using",
"save",
"()"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/meshdata.py#L585-L598
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/cubehelix.py
|
cubehelix
|
def cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256.,
minSat=1.2, maxSat=1.2, minLight=0., maxLight=1.,
**kwargs):
"""
A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://adsabs.harvard.edu/abs/2011arXiv1108.5083G
User can adjust all parameters of the cubehelix algorithm.
This enables much greater flexibility in choosing color maps, while
always ensuring the color map scales in intensity from black
to white. A few simple examples:
Default color map settings produce the standard "cubehelix".
Create color map in only blues by setting rot=0 and start=0.
Create reverse (white to black) backwards through the rainbow once
by setting rot=1 and reverse=True.
Parameters
----------
start : scalar, optional
Sets the starting position in the color space. 0=blue, 1=red,
2=green. Defaults to 0.5.
rot : scalar, optional
The number of rotations through the rainbow. Can be positive
or negative, indicating direction of rainbow. Negative values
correspond to Blue->Red direction. Defaults to -1.5
gamma : scalar, optional
The gamma correction for intensity. Defaults to 1.0
reverse : boolean, optional
Set to True to reverse the color map. Will go from black to
white. Good for density plots where shade~density. Defaults to False
nlev : scalar, optional
Defines the number of discrete levels to render colors at.
Defaults to 256.
sat : scalar, optional
The saturation intensity factor. Defaults to 1.2
NOTE: this was formerly known as "hue" parameter
minSat : scalar, optional
Sets the minimum-level saturation. Defaults to 1.2
maxSat : scalar, optional
Sets the maximum-level saturation. Defaults to 1.2
startHue : scalar, optional
Sets the starting color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in start parameter
endHue : scalar, optional
Sets the ending color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in rot parameter
minLight : scalar, optional
Sets the minimum lightness value. Defaults to 0.
maxLight : scalar, optional
Sets the maximum lightness value. Defaults to 1.
Returns
-------
data : ndarray, shape (N, 3)
Control points.
"""
# override start and rot if startHue and endHue are set
if kwargs is not None:
if 'startHue' in kwargs:
start = (kwargs.get('startHue') / 360. - 1.) * 3.
if 'endHue' in kwargs:
rot = kwargs.get('endHue') / 360. - start / 3. - 1.
if 'sat' in kwargs:
minSat = kwargs.get('sat')
maxSat = kwargs.get('sat')
# set up the parameters
fract = np.linspace(minLight, maxLight, nlev)
angle = 2.0 * pi * (start / 3.0 + rot * fract + 1.)
fract = fract**gamma
satar = np.linspace(minSat, maxSat, nlev)
amp = satar * fract * (1. - fract) / 2.
# compute the RGB vectors according to main equations
red = fract + amp * (-0.14861 * np.cos(angle) + 1.78277 * np.sin(angle))
grn = fract + amp * (-0.29227 * np.cos(angle) - 0.90649 * np.sin(angle))
blu = fract + amp * (1.97294 * np.cos(angle))
# find where RBB are outside the range [0,1], clip
red[np.where((red > 1.))] = 1.
grn[np.where((grn > 1.))] = 1.
blu[np.where((blu > 1.))] = 1.
red[np.where((red < 0.))] = 0.
grn[np.where((grn < 0.))] = 0.
blu[np.where((blu < 0.))] = 0.
# optional color reverse
if reverse is True:
red = red[::-1]
blu = blu[::-1]
grn = grn[::-1]
return np.array((red, grn, blu)).T
|
python
|
def cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256.,
minSat=1.2, maxSat=1.2, minLight=0., maxLight=1.,
**kwargs):
"""
A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://adsabs.harvard.edu/abs/2011arXiv1108.5083G
User can adjust all parameters of the cubehelix algorithm.
This enables much greater flexibility in choosing color maps, while
always ensuring the color map scales in intensity from black
to white. A few simple examples:
Default color map settings produce the standard "cubehelix".
Create color map in only blues by setting rot=0 and start=0.
Create reverse (white to black) backwards through the rainbow once
by setting rot=1 and reverse=True.
Parameters
----------
start : scalar, optional
Sets the starting position in the color space. 0=blue, 1=red,
2=green. Defaults to 0.5.
rot : scalar, optional
The number of rotations through the rainbow. Can be positive
or negative, indicating direction of rainbow. Negative values
correspond to Blue->Red direction. Defaults to -1.5
gamma : scalar, optional
The gamma correction for intensity. Defaults to 1.0
reverse : boolean, optional
Set to True to reverse the color map. Will go from black to
white. Good for density plots where shade~density. Defaults to False
nlev : scalar, optional
Defines the number of discrete levels to render colors at.
Defaults to 256.
sat : scalar, optional
The saturation intensity factor. Defaults to 1.2
NOTE: this was formerly known as "hue" parameter
minSat : scalar, optional
Sets the minimum-level saturation. Defaults to 1.2
maxSat : scalar, optional
Sets the maximum-level saturation. Defaults to 1.2
startHue : scalar, optional
Sets the starting color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in start parameter
endHue : scalar, optional
Sets the ending color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in rot parameter
minLight : scalar, optional
Sets the minimum lightness value. Defaults to 0.
maxLight : scalar, optional
Sets the maximum lightness value. Defaults to 1.
Returns
-------
data : ndarray, shape (N, 3)
Control points.
"""
# override start and rot if startHue and endHue are set
if kwargs is not None:
if 'startHue' in kwargs:
start = (kwargs.get('startHue') / 360. - 1.) * 3.
if 'endHue' in kwargs:
rot = kwargs.get('endHue') / 360. - start / 3. - 1.
if 'sat' in kwargs:
minSat = kwargs.get('sat')
maxSat = kwargs.get('sat')
# set up the parameters
fract = np.linspace(minLight, maxLight, nlev)
angle = 2.0 * pi * (start / 3.0 + rot * fract + 1.)
fract = fract**gamma
satar = np.linspace(minSat, maxSat, nlev)
amp = satar * fract * (1. - fract) / 2.
# compute the RGB vectors according to main equations
red = fract + amp * (-0.14861 * np.cos(angle) + 1.78277 * np.sin(angle))
grn = fract + amp * (-0.29227 * np.cos(angle) - 0.90649 * np.sin(angle))
blu = fract + amp * (1.97294 * np.cos(angle))
# find where RBB are outside the range [0,1], clip
red[np.where((red > 1.))] = 1.
grn[np.where((grn > 1.))] = 1.
blu[np.where((blu > 1.))] = 1.
red[np.where((red < 0.))] = 0.
grn[np.where((grn < 0.))] = 0.
blu[np.where((blu < 0.))] = 0.
# optional color reverse
if reverse is True:
red = red[::-1]
blu = blu[::-1]
grn = grn[::-1]
return np.array((red, grn, blu)).T
|
[
"def",
"cubehelix",
"(",
"start",
"=",
"0.5",
",",
"rot",
"=",
"1",
",",
"gamma",
"=",
"1.0",
",",
"reverse",
"=",
"True",
",",
"nlev",
"=",
"256.",
",",
"minSat",
"=",
"1.2",
",",
"maxSat",
"=",
"1.2",
",",
"minLight",
"=",
"0.",
",",
"maxLight",
"=",
"1.",
",",
"*",
"*",
"kwargs",
")",
":",
"# override start and rot if startHue and endHue are set",
"if",
"kwargs",
"is",
"not",
"None",
":",
"if",
"'startHue'",
"in",
"kwargs",
":",
"start",
"=",
"(",
"kwargs",
".",
"get",
"(",
"'startHue'",
")",
"/",
"360.",
"-",
"1.",
")",
"*",
"3.",
"if",
"'endHue'",
"in",
"kwargs",
":",
"rot",
"=",
"kwargs",
".",
"get",
"(",
"'endHue'",
")",
"/",
"360.",
"-",
"start",
"/",
"3.",
"-",
"1.",
"if",
"'sat'",
"in",
"kwargs",
":",
"minSat",
"=",
"kwargs",
".",
"get",
"(",
"'sat'",
")",
"maxSat",
"=",
"kwargs",
".",
"get",
"(",
"'sat'",
")",
"# set up the parameters",
"fract",
"=",
"np",
".",
"linspace",
"(",
"minLight",
",",
"maxLight",
",",
"nlev",
")",
"angle",
"=",
"2.0",
"*",
"pi",
"*",
"(",
"start",
"/",
"3.0",
"+",
"rot",
"*",
"fract",
"+",
"1.",
")",
"fract",
"=",
"fract",
"**",
"gamma",
"satar",
"=",
"np",
".",
"linspace",
"(",
"minSat",
",",
"maxSat",
",",
"nlev",
")",
"amp",
"=",
"satar",
"*",
"fract",
"*",
"(",
"1.",
"-",
"fract",
")",
"/",
"2.",
"# compute the RGB vectors according to main equations",
"red",
"=",
"fract",
"+",
"amp",
"*",
"(",
"-",
"0.14861",
"*",
"np",
".",
"cos",
"(",
"angle",
")",
"+",
"1.78277",
"*",
"np",
".",
"sin",
"(",
"angle",
")",
")",
"grn",
"=",
"fract",
"+",
"amp",
"*",
"(",
"-",
"0.29227",
"*",
"np",
".",
"cos",
"(",
"angle",
")",
"-",
"0.90649",
"*",
"np",
".",
"sin",
"(",
"angle",
")",
")",
"blu",
"=",
"fract",
"+",
"amp",
"*",
"(",
"1.97294",
"*",
"np",
".",
"cos",
"(",
"angle",
")",
")",
"# find where RBB are outside the range [0,1], clip",
"red",
"[",
"np",
".",
"where",
"(",
"(",
"red",
">",
"1.",
")",
")",
"]",
"=",
"1.",
"grn",
"[",
"np",
".",
"where",
"(",
"(",
"grn",
">",
"1.",
")",
")",
"]",
"=",
"1.",
"blu",
"[",
"np",
".",
"where",
"(",
"(",
"blu",
">",
"1.",
")",
")",
"]",
"=",
"1.",
"red",
"[",
"np",
".",
"where",
"(",
"(",
"red",
"<",
"0.",
")",
")",
"]",
"=",
"0.",
"grn",
"[",
"np",
".",
"where",
"(",
"(",
"grn",
"<",
"0.",
")",
")",
"]",
"=",
"0.",
"blu",
"[",
"np",
".",
"where",
"(",
"(",
"blu",
"<",
"0.",
")",
")",
"]",
"=",
"0.",
"# optional color reverse",
"if",
"reverse",
"is",
"True",
":",
"red",
"=",
"red",
"[",
":",
":",
"-",
"1",
"]",
"blu",
"=",
"blu",
"[",
":",
":",
"-",
"1",
"]",
"grn",
"=",
"grn",
"[",
":",
":",
"-",
"1",
"]",
"return",
"np",
".",
"array",
"(",
"(",
"red",
",",
"grn",
",",
"blu",
")",
")",
".",
"T"
] |
A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://adsabs.harvard.edu/abs/2011arXiv1108.5083G
User can adjust all parameters of the cubehelix algorithm.
This enables much greater flexibility in choosing color maps, while
always ensuring the color map scales in intensity from black
to white. A few simple examples:
Default color map settings produce the standard "cubehelix".
Create color map in only blues by setting rot=0 and start=0.
Create reverse (white to black) backwards through the rainbow once
by setting rot=1 and reverse=True.
Parameters
----------
start : scalar, optional
Sets the starting position in the color space. 0=blue, 1=red,
2=green. Defaults to 0.5.
rot : scalar, optional
The number of rotations through the rainbow. Can be positive
or negative, indicating direction of rainbow. Negative values
correspond to Blue->Red direction. Defaults to -1.5
gamma : scalar, optional
The gamma correction for intensity. Defaults to 1.0
reverse : boolean, optional
Set to True to reverse the color map. Will go from black to
white. Good for density plots where shade~density. Defaults to False
nlev : scalar, optional
Defines the number of discrete levels to render colors at.
Defaults to 256.
sat : scalar, optional
The saturation intensity factor. Defaults to 1.2
NOTE: this was formerly known as "hue" parameter
minSat : scalar, optional
Sets the minimum-level saturation. Defaults to 1.2
maxSat : scalar, optional
Sets the maximum-level saturation. Defaults to 1.2
startHue : scalar, optional
Sets the starting color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in start parameter
endHue : scalar, optional
Sets the ending color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in rot parameter
minLight : scalar, optional
Sets the minimum lightness value. Defaults to 0.
maxLight : scalar, optional
Sets the maximum lightness value. Defaults to 1.
Returns
-------
data : ndarray, shape (N, 3)
Control points.
|
[
"A",
"full",
"implementation",
"of",
"Dave",
"Green",
"s",
"cubehelix",
"for",
"Matplotlib",
".",
"Based",
"on",
"the",
"FORTRAN",
"77",
"code",
"provided",
"in",
"D",
".",
"A",
".",
"Green",
"2011",
"BASI",
"39",
"289",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cubehelix.py#L35-L138
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
color_to_hex
|
def color_to_hex(color):
"""Convert matplotlib color code to hex color code"""
if color is None or colorConverter.to_rgba(color)[3] == 0:
return 'none'
else:
rgb = colorConverter.to_rgb(color)
return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
|
python
|
def color_to_hex(color):
"""Convert matplotlib color code to hex color code"""
if color is None or colorConverter.to_rgba(color)[3] == 0:
return 'none'
else:
rgb = colorConverter.to_rgb(color)
return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
|
[
"def",
"color_to_hex",
"(",
"color",
")",
":",
"if",
"color",
"is",
"None",
"or",
"colorConverter",
".",
"to_rgba",
"(",
"color",
")",
"[",
"3",
"]",
"==",
"0",
":",
"return",
"'none'",
"else",
":",
"rgb",
"=",
"colorConverter",
".",
"to_rgb",
"(",
"color",
")",
"return",
"'#{0:02X}{1:02X}{2:02X}'",
".",
"format",
"(",
"*",
"(",
"int",
"(",
"255",
"*",
"c",
")",
"for",
"c",
"in",
"rgb",
")",
")"
] |
Convert matplotlib color code to hex color code
|
[
"Convert",
"matplotlib",
"color",
"code",
"to",
"hex",
"color",
"code"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L21-L27
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
_many_to_one
|
def _many_to_one(input_dict):
"""Convert a many-to-one mapping to a one-to-one mapping"""
return dict((key, val)
for keys, val in input_dict.items()
for key in keys)
|
python
|
def _many_to_one(input_dict):
"""Convert a many-to-one mapping to a one-to-one mapping"""
return dict((key, val)
for keys, val in input_dict.items()
for key in keys)
|
[
"def",
"_many_to_one",
"(",
"input_dict",
")",
":",
"return",
"dict",
"(",
"(",
"key",
",",
"val",
")",
"for",
"keys",
",",
"val",
"in",
"input_dict",
".",
"items",
"(",
")",
"for",
"key",
"in",
"keys",
")"
] |
Convert a many-to-one mapping to a one-to-one mapping
|
[
"Convert",
"a",
"many",
"-",
"to",
"-",
"one",
"mapping",
"to",
"a",
"one",
"-",
"to",
"-",
"one",
"mapping"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L30-L34
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_dasharray
|
def get_dasharray(obj):
"""Get an SVG dash array for the given matplotlib linestyle
Parameters
----------
obj : matplotlib object
The matplotlib line or path object, which must have a get_linestyle()
method which returns a valid matplotlib line code
Returns
-------
dasharray : string
The HTML/SVG dasharray code associated with the object.
"""
if obj.__dict__.get('_dashSeq', None) is not None:
return ','.join(map(str, obj._dashSeq))
else:
ls = obj.get_linestyle()
dasharray = LINESTYLES.get(ls, 'not found')
if dasharray == 'not found':
warnings.warn("line style '{0}' not understood: "
"defaulting to solid line.".format(ls))
dasharray = LINESTYLES['solid']
return dasharray
|
python
|
def get_dasharray(obj):
"""Get an SVG dash array for the given matplotlib linestyle
Parameters
----------
obj : matplotlib object
The matplotlib line or path object, which must have a get_linestyle()
method which returns a valid matplotlib line code
Returns
-------
dasharray : string
The HTML/SVG dasharray code associated with the object.
"""
if obj.__dict__.get('_dashSeq', None) is not None:
return ','.join(map(str, obj._dashSeq))
else:
ls = obj.get_linestyle()
dasharray = LINESTYLES.get(ls, 'not found')
if dasharray == 'not found':
warnings.warn("line style '{0}' not understood: "
"defaulting to solid line.".format(ls))
dasharray = LINESTYLES['solid']
return dasharray
|
[
"def",
"get_dasharray",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"__dict__",
".",
"get",
"(",
"'_dashSeq'",
",",
"None",
")",
"is",
"not",
"None",
":",
"return",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"obj",
".",
"_dashSeq",
")",
")",
"else",
":",
"ls",
"=",
"obj",
".",
"get_linestyle",
"(",
")",
"dasharray",
"=",
"LINESTYLES",
".",
"get",
"(",
"ls",
",",
"'not found'",
")",
"if",
"dasharray",
"==",
"'not found'",
":",
"warnings",
".",
"warn",
"(",
"\"line style '{0}' not understood: \"",
"\"defaulting to solid line.\"",
".",
"format",
"(",
"ls",
")",
")",
"dasharray",
"=",
"LINESTYLES",
"[",
"'solid'",
"]",
"return",
"dasharray"
] |
Get an SVG dash array for the given matplotlib linestyle
Parameters
----------
obj : matplotlib object
The matplotlib line or path object, which must have a get_linestyle()
method which returns a valid matplotlib line code
Returns
-------
dasharray : string
The HTML/SVG dasharray code associated with the object.
|
[
"Get",
"an",
"SVG",
"dash",
"array",
"for",
"the",
"given",
"matplotlib",
"linestyle"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L43-L66
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
SVG_path
|
def SVG_path(path, transform=None, simplify=False):
"""Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
-------
vertices : array
The shape (M, 2) array of vertices of the Path. Note that some Path
codes require multiple vertices, so the length of these vertices may
be longer than the list of path codes.
path_codes : list
A length N list of single-character path codes, N <= M. Each code is
a single character, in ['L','M','S','C','Z']. See the standard SVG
path specification for a description of these.
"""
if transform is not None:
path = path.transformed(transform)
vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],
PATH_DICT[path_code])
for (vertices, path_code)
in path.iter_segments(simplify=simplify)]
if not vc_tuples:
# empty path is a special case
return np.zeros((0, 2)), []
else:
vertices, codes = zip(*vc_tuples)
vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)
return vertices, list(codes)
|
python
|
def SVG_path(path, transform=None, simplify=False):
"""Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
-------
vertices : array
The shape (M, 2) array of vertices of the Path. Note that some Path
codes require multiple vertices, so the length of these vertices may
be longer than the list of path codes.
path_codes : list
A length N list of single-character path codes, N <= M. Each code is
a single character, in ['L','M','S','C','Z']. See the standard SVG
path specification for a description of these.
"""
if transform is not None:
path = path.transformed(transform)
vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],
PATH_DICT[path_code])
for (vertices, path_code)
in path.iter_segments(simplify=simplify)]
if not vc_tuples:
# empty path is a special case
return np.zeros((0, 2)), []
else:
vertices, codes = zip(*vc_tuples)
vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)
return vertices, list(codes)
|
[
"def",
"SVG_path",
"(",
"path",
",",
"transform",
"=",
"None",
",",
"simplify",
"=",
"False",
")",
":",
"if",
"transform",
"is",
"not",
"None",
":",
"path",
"=",
"path",
".",
"transformed",
"(",
"transform",
")",
"vc_tuples",
"=",
"[",
"(",
"vertices",
"if",
"path_code",
"!=",
"Path",
".",
"CLOSEPOLY",
"else",
"[",
"]",
",",
"PATH_DICT",
"[",
"path_code",
"]",
")",
"for",
"(",
"vertices",
",",
"path_code",
")",
"in",
"path",
".",
"iter_segments",
"(",
"simplify",
"=",
"simplify",
")",
"]",
"if",
"not",
"vc_tuples",
":",
"# empty path is a special case",
"return",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"2",
")",
")",
",",
"[",
"]",
"else",
":",
"vertices",
",",
"codes",
"=",
"zip",
"(",
"*",
"vc_tuples",
")",
"vertices",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"vertices",
")",
")",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"2",
")",
"return",
"vertices",
",",
"list",
"(",
"codes",
")"
] |
Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
-------
vertices : array
The shape (M, 2) array of vertices of the Path. Note that some Path
codes require multiple vertices, so the length of these vertices may
be longer than the list of path codes.
path_codes : list
A length N list of single-character path codes, N <= M. Each code is
a single character, in ['L','M','S','C','Z']. See the standard SVG
path specification for a description of these.
|
[
"Construct",
"the",
"vertices",
"and",
"SVG",
"codes",
"for",
"the",
"path"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L76-L111
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_path_style
|
def get_path_style(path, fill=True):
"""Get the style dictionary for matplotlib path objects"""
style = {}
style['alpha'] = path.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['edgecolor'] = color_to_hex(path.get_edgecolor())
if fill:
style['facecolor'] = color_to_hex(path.get_facecolor())
else:
style['facecolor'] = 'none'
style['edgewidth'] = path.get_linewidth()
style['dasharray'] = get_dasharray(path)
style['zorder'] = path.get_zorder()
return style
|
python
|
def get_path_style(path, fill=True):
"""Get the style dictionary for matplotlib path objects"""
style = {}
style['alpha'] = path.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['edgecolor'] = color_to_hex(path.get_edgecolor())
if fill:
style['facecolor'] = color_to_hex(path.get_facecolor())
else:
style['facecolor'] = 'none'
style['edgewidth'] = path.get_linewidth()
style['dasharray'] = get_dasharray(path)
style['zorder'] = path.get_zorder()
return style
|
[
"def",
"get_path_style",
"(",
"path",
",",
"fill",
"=",
"True",
")",
":",
"style",
"=",
"{",
"}",
"style",
"[",
"'alpha'",
"]",
"=",
"path",
".",
"get_alpha",
"(",
")",
"if",
"style",
"[",
"'alpha'",
"]",
"is",
"None",
":",
"style",
"[",
"'alpha'",
"]",
"=",
"1",
"style",
"[",
"'edgecolor'",
"]",
"=",
"color_to_hex",
"(",
"path",
".",
"get_edgecolor",
"(",
")",
")",
"if",
"fill",
":",
"style",
"[",
"'facecolor'",
"]",
"=",
"color_to_hex",
"(",
"path",
".",
"get_facecolor",
"(",
")",
")",
"else",
":",
"style",
"[",
"'facecolor'",
"]",
"=",
"'none'",
"style",
"[",
"'edgewidth'",
"]",
"=",
"path",
".",
"get_linewidth",
"(",
")",
"style",
"[",
"'dasharray'",
"]",
"=",
"get_dasharray",
"(",
"path",
")",
"style",
"[",
"'zorder'",
"]",
"=",
"path",
".",
"get_zorder",
"(",
")",
"return",
"style"
] |
Get the style dictionary for matplotlib path objects
|
[
"Get",
"the",
"style",
"dictionary",
"for",
"matplotlib",
"path",
"objects"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L114-L128
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_line_style
|
def get_line_style(line):
"""Get the style dictionary for matplotlib line objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['color'] = color_to_hex(line.get_color())
style['linewidth'] = line.get_linewidth()
style['dasharray'] = get_dasharray(line)
style['zorder'] = line.get_zorder()
return style
|
python
|
def get_line_style(line):
"""Get the style dictionary for matplotlib line objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['color'] = color_to_hex(line.get_color())
style['linewidth'] = line.get_linewidth()
style['dasharray'] = get_dasharray(line)
style['zorder'] = line.get_zorder()
return style
|
[
"def",
"get_line_style",
"(",
"line",
")",
":",
"style",
"=",
"{",
"}",
"style",
"[",
"'alpha'",
"]",
"=",
"line",
".",
"get_alpha",
"(",
")",
"if",
"style",
"[",
"'alpha'",
"]",
"is",
"None",
":",
"style",
"[",
"'alpha'",
"]",
"=",
"1",
"style",
"[",
"'color'",
"]",
"=",
"color_to_hex",
"(",
"line",
".",
"get_color",
"(",
")",
")",
"style",
"[",
"'linewidth'",
"]",
"=",
"line",
".",
"get_linewidth",
"(",
")",
"style",
"[",
"'dasharray'",
"]",
"=",
"get_dasharray",
"(",
"line",
")",
"style",
"[",
"'zorder'",
"]",
"=",
"line",
".",
"get_zorder",
"(",
")",
"return",
"style"
] |
Get the style dictionary for matplotlib line objects
|
[
"Get",
"the",
"style",
"dictionary",
"for",
"matplotlib",
"line",
"objects"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L131-L141
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_marker_style
|
def get_marker_style(line):
"""Get the style dictionary for matplotlib marker objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['facecolor'] = color_to_hex(line.get_markerfacecolor())
style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
style['edgewidth'] = line.get_markeredgewidth()
style['marker'] = line.get_marker()
markerstyle = MarkerStyle(line.get_marker())
markersize = line.get_markersize()
markertransform = (markerstyle.get_transform() +
Affine2D().scale(markersize, -markersize))
style['markerpath'] = SVG_path(markerstyle.get_path(),
markertransform)
style['markersize'] = markersize
style['zorder'] = line.get_zorder()
return style
|
python
|
def get_marker_style(line):
"""Get the style dictionary for matplotlib marker objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['facecolor'] = color_to_hex(line.get_markerfacecolor())
style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
style['edgewidth'] = line.get_markeredgewidth()
style['marker'] = line.get_marker()
markerstyle = MarkerStyle(line.get_marker())
markersize = line.get_markersize()
markertransform = (markerstyle.get_transform() +
Affine2D().scale(markersize, -markersize))
style['markerpath'] = SVG_path(markerstyle.get_path(),
markertransform)
style['markersize'] = markersize
style['zorder'] = line.get_zorder()
return style
|
[
"def",
"get_marker_style",
"(",
"line",
")",
":",
"style",
"=",
"{",
"}",
"style",
"[",
"'alpha'",
"]",
"=",
"line",
".",
"get_alpha",
"(",
")",
"if",
"style",
"[",
"'alpha'",
"]",
"is",
"None",
":",
"style",
"[",
"'alpha'",
"]",
"=",
"1",
"style",
"[",
"'facecolor'",
"]",
"=",
"color_to_hex",
"(",
"line",
".",
"get_markerfacecolor",
"(",
")",
")",
"style",
"[",
"'edgecolor'",
"]",
"=",
"color_to_hex",
"(",
"line",
".",
"get_markeredgecolor",
"(",
")",
")",
"style",
"[",
"'edgewidth'",
"]",
"=",
"line",
".",
"get_markeredgewidth",
"(",
")",
"style",
"[",
"'marker'",
"]",
"=",
"line",
".",
"get_marker",
"(",
")",
"markerstyle",
"=",
"MarkerStyle",
"(",
"line",
".",
"get_marker",
"(",
")",
")",
"markersize",
"=",
"line",
".",
"get_markersize",
"(",
")",
"markertransform",
"=",
"(",
"markerstyle",
".",
"get_transform",
"(",
")",
"+",
"Affine2D",
"(",
")",
".",
"scale",
"(",
"markersize",
",",
"-",
"markersize",
")",
")",
"style",
"[",
"'markerpath'",
"]",
"=",
"SVG_path",
"(",
"markerstyle",
".",
"get_path",
"(",
")",
",",
"markertransform",
")",
"style",
"[",
"'markersize'",
"]",
"=",
"markersize",
"style",
"[",
"'zorder'",
"]",
"=",
"line",
".",
"get_zorder",
"(",
")",
"return",
"style"
] |
Get the style dictionary for matplotlib marker objects
|
[
"Get",
"the",
"style",
"dictionary",
"for",
"matplotlib",
"marker",
"objects"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L144-L164
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_text_style
|
def get_text_style(text):
"""Return the text style dict for a text instance"""
style = {}
style['alpha'] = text.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['fontsize'] = text.get_size()
style['color'] = color_to_hex(text.get_color())
style['halign'] = text.get_horizontalalignment() # left, center, right
style['valign'] = text.get_verticalalignment() # baseline, center, top
style['malign'] = text._multialignment # text alignment when '\n' in text
style['rotation'] = text.get_rotation()
style['zorder'] = text.get_zorder()
return style
|
python
|
def get_text_style(text):
"""Return the text style dict for a text instance"""
style = {}
style['alpha'] = text.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['fontsize'] = text.get_size()
style['color'] = color_to_hex(text.get_color())
style['halign'] = text.get_horizontalalignment() # left, center, right
style['valign'] = text.get_verticalalignment() # baseline, center, top
style['malign'] = text._multialignment # text alignment when '\n' in text
style['rotation'] = text.get_rotation()
style['zorder'] = text.get_zorder()
return style
|
[
"def",
"get_text_style",
"(",
"text",
")",
":",
"style",
"=",
"{",
"}",
"style",
"[",
"'alpha'",
"]",
"=",
"text",
".",
"get_alpha",
"(",
")",
"if",
"style",
"[",
"'alpha'",
"]",
"is",
"None",
":",
"style",
"[",
"'alpha'",
"]",
"=",
"1",
"style",
"[",
"'fontsize'",
"]",
"=",
"text",
".",
"get_size",
"(",
")",
"style",
"[",
"'color'",
"]",
"=",
"color_to_hex",
"(",
"text",
".",
"get_color",
"(",
")",
")",
"style",
"[",
"'halign'",
"]",
"=",
"text",
".",
"get_horizontalalignment",
"(",
")",
"# left, center, right",
"style",
"[",
"'valign'",
"]",
"=",
"text",
".",
"get_verticalalignment",
"(",
")",
"# baseline, center, top",
"style",
"[",
"'malign'",
"]",
"=",
"text",
".",
"_multialignment",
"# text alignment when '\\n' in text",
"style",
"[",
"'rotation'",
"]",
"=",
"text",
".",
"get_rotation",
"(",
")",
"style",
"[",
"'zorder'",
"]",
"=",
"text",
".",
"get_zorder",
"(",
")",
"return",
"style"
] |
Return the text style dict for a text instance
|
[
"Return",
"the",
"text",
"style",
"dict",
"for",
"a",
"text",
"instance"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L167-L180
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
get_axis_properties
|
def get_axis_properties(axis):
"""Return the property dictionary for a matplotlib.Axis instance"""
props = {}
label1On = axis._major_tick_kw.get('label1On', True)
if isinstance(axis, matplotlib.axis.XAxis):
if label1On:
props['position'] = "bottom"
else:
props['position'] = "top"
elif isinstance(axis, matplotlib.axis.YAxis):
if label1On:
props['position'] = "left"
else:
props['position'] = "right"
else:
raise ValueError("{0} should be an Axis instance".format(axis))
# Use tick values if appropriate
locator = axis.get_major_locator()
props['nticks'] = len(locator())
if isinstance(locator, ticker.FixedLocator):
props['tickvalues'] = list(locator())
else:
props['tickvalues'] = None
# Find tick formats
formatter = axis.get_major_formatter()
if isinstance(formatter, ticker.NullFormatter):
props['tickformat'] = ""
elif isinstance(formatter, ticker.FixedFormatter):
props['tickformat'] = list(formatter.seq)
elif not any(label.get_visible() for label in axis.get_ticklabels()):
props['tickformat'] = ""
else:
props['tickformat'] = None
# Get axis scale
props['scale'] = axis.get_scale()
# Get major tick label size (assumes that's all we really care about!)
labels = axis.get_ticklabels()
if labels:
props['fontsize'] = labels[0].get_fontsize()
else:
props['fontsize'] = None
# Get associated grid
props['grid'] = get_grid_style(axis)
return props
|
python
|
def get_axis_properties(axis):
"""Return the property dictionary for a matplotlib.Axis instance"""
props = {}
label1On = axis._major_tick_kw.get('label1On', True)
if isinstance(axis, matplotlib.axis.XAxis):
if label1On:
props['position'] = "bottom"
else:
props['position'] = "top"
elif isinstance(axis, matplotlib.axis.YAxis):
if label1On:
props['position'] = "left"
else:
props['position'] = "right"
else:
raise ValueError("{0} should be an Axis instance".format(axis))
# Use tick values if appropriate
locator = axis.get_major_locator()
props['nticks'] = len(locator())
if isinstance(locator, ticker.FixedLocator):
props['tickvalues'] = list(locator())
else:
props['tickvalues'] = None
# Find tick formats
formatter = axis.get_major_formatter()
if isinstance(formatter, ticker.NullFormatter):
props['tickformat'] = ""
elif isinstance(formatter, ticker.FixedFormatter):
props['tickformat'] = list(formatter.seq)
elif not any(label.get_visible() for label in axis.get_ticklabels()):
props['tickformat'] = ""
else:
props['tickformat'] = None
# Get axis scale
props['scale'] = axis.get_scale()
# Get major tick label size (assumes that's all we really care about!)
labels = axis.get_ticklabels()
if labels:
props['fontsize'] = labels[0].get_fontsize()
else:
props['fontsize'] = None
# Get associated grid
props['grid'] = get_grid_style(axis)
return props
|
[
"def",
"get_axis_properties",
"(",
"axis",
")",
":",
"props",
"=",
"{",
"}",
"label1On",
"=",
"axis",
".",
"_major_tick_kw",
".",
"get",
"(",
"'label1On'",
",",
"True",
")",
"if",
"isinstance",
"(",
"axis",
",",
"matplotlib",
".",
"axis",
".",
"XAxis",
")",
":",
"if",
"label1On",
":",
"props",
"[",
"'position'",
"]",
"=",
"\"bottom\"",
"else",
":",
"props",
"[",
"'position'",
"]",
"=",
"\"top\"",
"elif",
"isinstance",
"(",
"axis",
",",
"matplotlib",
".",
"axis",
".",
"YAxis",
")",
":",
"if",
"label1On",
":",
"props",
"[",
"'position'",
"]",
"=",
"\"left\"",
"else",
":",
"props",
"[",
"'position'",
"]",
"=",
"\"right\"",
"else",
":",
"raise",
"ValueError",
"(",
"\"{0} should be an Axis instance\"",
".",
"format",
"(",
"axis",
")",
")",
"# Use tick values if appropriate",
"locator",
"=",
"axis",
".",
"get_major_locator",
"(",
")",
"props",
"[",
"'nticks'",
"]",
"=",
"len",
"(",
"locator",
"(",
")",
")",
"if",
"isinstance",
"(",
"locator",
",",
"ticker",
".",
"FixedLocator",
")",
":",
"props",
"[",
"'tickvalues'",
"]",
"=",
"list",
"(",
"locator",
"(",
")",
")",
"else",
":",
"props",
"[",
"'tickvalues'",
"]",
"=",
"None",
"# Find tick formats",
"formatter",
"=",
"axis",
".",
"get_major_formatter",
"(",
")",
"if",
"isinstance",
"(",
"formatter",
",",
"ticker",
".",
"NullFormatter",
")",
":",
"props",
"[",
"'tickformat'",
"]",
"=",
"\"\"",
"elif",
"isinstance",
"(",
"formatter",
",",
"ticker",
".",
"FixedFormatter",
")",
":",
"props",
"[",
"'tickformat'",
"]",
"=",
"list",
"(",
"formatter",
".",
"seq",
")",
"elif",
"not",
"any",
"(",
"label",
".",
"get_visible",
"(",
")",
"for",
"label",
"in",
"axis",
".",
"get_ticklabels",
"(",
")",
")",
":",
"props",
"[",
"'tickformat'",
"]",
"=",
"\"\"",
"else",
":",
"props",
"[",
"'tickformat'",
"]",
"=",
"None",
"# Get axis scale",
"props",
"[",
"'scale'",
"]",
"=",
"axis",
".",
"get_scale",
"(",
")",
"# Get major tick label size (assumes that's all we really care about!)",
"labels",
"=",
"axis",
".",
"get_ticklabels",
"(",
")",
"if",
"labels",
":",
"props",
"[",
"'fontsize'",
"]",
"=",
"labels",
"[",
"0",
"]",
".",
"get_fontsize",
"(",
")",
"else",
":",
"props",
"[",
"'fontsize'",
"]",
"=",
"None",
"# Get associated grid",
"props",
"[",
"'grid'",
"]",
"=",
"get_grid_style",
"(",
"axis",
")",
"return",
"props"
] |
Return the property dictionary for a matplotlib.Axis instance
|
[
"Return",
"the",
"property",
"dictionary",
"for",
"a",
"matplotlib",
".",
"Axis",
"instance"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L183-L233
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py
|
iter_all_children
|
def iter_all_children(obj, skipContainers=False):
"""
Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned.
"""
if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
for child in obj.get_children():
if not skipContainers:
yield child
# could use `yield from` in python 3...
for grandchild in iter_all_children(child, skipContainers):
yield grandchild
else:
yield obj
|
python
|
def iter_all_children(obj, skipContainers=False):
"""
Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned.
"""
if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
for child in obj.get_children():
if not skipContainers:
yield child
# could use `yield from` in python 3...
for grandchild in iter_all_children(child, skipContainers):
yield grandchild
else:
yield obj
|
[
"def",
"iter_all_children",
"(",
"obj",
",",
"skipContainers",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_children'",
")",
"and",
"len",
"(",
"obj",
".",
"get_children",
"(",
")",
")",
">",
"0",
":",
"for",
"child",
"in",
"obj",
".",
"get_children",
"(",
")",
":",
"if",
"not",
"skipContainers",
":",
"yield",
"child",
"# could use `yield from` in python 3...",
"for",
"grandchild",
"in",
"iter_all_children",
"(",
"child",
",",
"skipContainers",
")",
":",
"yield",
"grandchild",
"else",
":",
"yield",
"obj"
] |
Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned.
|
[
"Returns",
"an",
"iterator",
"over",
"all",
"childen",
"and",
"nested",
"children",
"using",
"obj",
"s",
"get_children",
"()",
"method"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/mplutils.py#L304-L319
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.