INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
convert a string to float
def num(string): """convert a string to float""" if not isinstance(string, type('')): raise ValueError(type('')) try: string = re.sub('[^a-zA-Z0-9\.\-]', '', string) number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string) return float(number[0]) except Exception as e: ...
get the unit of number
def get_number_unit(number): """get the unit of number""" n = str(float(number)) mult, submult = n.split('.') if float(submult) != 0: unit = '0.' + (len(submult)-1)*'0' + '1' return float(unit) else: return float(1)
get value of pip
def get_pip(mov=None, api=None, name=None): """get value of pip""" # ~ check args if mov is None and api is None: logger.error("need at least one of those") raise ValueError() elif mov is not None and api is not None: logger.error("mov and api are exclusive") raise ValueE...
Individual item sizes
def itemsize(self): """ Individual item sizes """ return self._items[:self._count, 1] - self._items[:self._count, 0]
Set current capacity of the underlying array
def reserve(self, capacity): """ Set current capacity of the underlying array""" if capacity >= self._data.size: capacity = int(2 ** np.ceil(np.log2(capacity))) self._data = np.resize(self._data, capacity)
Insert data before index
def insert(self, index, data, itemsize=None): """ Insert data before index Parameters ---------- index : int Index before which data will be inserted. data : array_like An array, any object exposing the array interface, an object whose __arr...
Append data to the end.
def append(self, data, itemsize=None): """ Append data to the end. Parameters ---------- data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. itemsize: ...
Solve an optimization problem using the DIRECT ( Dividing Rectangles ) algorithm. It can be used to solve general nonlinear programming problems of the form:.. math:: \ min_ { x \ in R^n } f ( x ) subject to.. math:: x_L \ leq x \ leq x_U Where: math: x are the optimization variables ( with upper and lower bounds ): ma...
def minimize(func, bounds=None, nvar=None, args=(), disp=False, eps=1e-4, maxf=20000, maxT=6000, algmethod=0, fglobal=-1e100, fglper=0.01, volper=-1.0, sigmaper=-1.0, **kwargs ): ...
Get screen DPI from the OS
def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen. """ try: user32.SetProcessDPIAware(...
Reset shader source if necesssary.
def build_if_needed(self): """ Reset shader source if necesssary. """ if self._need_build: self._build() self._need_build = False self.update_variables()
Returns a function that maps a number n from range ( a b ) onto a range ( c d ). If no curvefn is given linear mapping will be used. Optionally a normalisation function normfn can be provided to transform output.
def nmap(a, b, c, d, curvefn=None, normfn=None): """ Returns a function that maps a number n from range (a, b) onto a range (c, d). If no curvefn is given, linear mapping will be used. Optionally a normalisation function normfn can be provided to transform output. """ if not curvefn: cur...
Link this axis to a ViewBox
def link_view(self, view): """Link this axis to a ViewBox This makes it so that the axis's domain always matches the visible range in the ViewBox. Parameters ---------- view : instance of ViewBox The ViewBox to link. """ if view is self._link...
Linked view transform has changed ; update ticks.
def _view_changed(self, event=None): """Linked view transform has changed; update ticks. """ tr = self.node_transform(self._linked_view.scene) p1, p2 = tr.map(self._axis_ends()) if self.orientation in ('left', 'right'): self.axis.domain = (p1[1], p2[1]) else: ...
ViewBox mouse event handler
def viewbox_mouse_event(self, event): """ViewBox mouse event handler Parameters ---------- event : instance of Event The mouse event. """ # When the attached ViewBox reseives a mouse event, it is sent to the # camera here. self.mouse_...
Timer event handler
def on_timer(self, event=None): """Timer event handler Parameters ---------- event : instance of Event The timer event. """ # Smoothly update center and magnification properties of the transform k = np.clip(100. / self.mag.mag, 10, 100) s = 10...
Data can be numpy array or the size of data to allocate.
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') d...
Return next power of 2 greater than or equal to n
def next_power_of_2(n): """ Return next power of 2 greater than or equal to n """ n -= 1 # greater than OR EQUAL TO n shift = 1 while (n + 1) & n: # n+1 is not a power of 2 yet n |= n >> shift shift *= 2 return max(4, n + 1)
Parameters ----------
def append(self, vertices, uniforms=None, indices=None, itemsize=None): """ Parameters ---------- vertices : numpy array An array whose dtype is compatible with self.vdtype uniforms: numpy array An array whose dtype is compatible with self.utype ...
Compute uniform texture shape
def _compute_texture_shape(self, size=1): """ Compute uniform texture shape """ # We should use this line but we may not have a GL context yet # linesize = gl.glGetInteger(gl.GL_MAX_TEXTURE_SIZE) linesize = 1024 count = self._uniforms_float_count cols = 4 * linesize // i...
Update vertex buffers & texture
def _update(self): """ Update vertex buffers & texture """ if self._vertices_buffer is not None: self._vertices_buffer.delete() self._vertices_buffer = VertexBuffer(self._vertices_list.data) if self.itype is not None: if self._indices_buffer is not None: ...
Retrieve a graph layout
def get_layout(name, *args, **kwargs): """ Retrieve a graph layout Some graph layouts accept extra options. Please refer to their documentation for more information. Parameters ---------- name : string The name of the layout. The variable `AVAILABLE_LAYOUTS` contains all av...
Given viewer session information make sure the session information is compatible with the current version of the viewers and if not update the session information in - place.
def update_viewer_state(rec, context): """ Given viewer session information, make sure the session information is compatible with the current version of the viewers, and if not, update the session information in-place. """ if '_protocol' not in rec: rec.pop('properties') rec['...
Remove C - style comment from GLSL code string.
def remove_comments(code): """Remove C-style comment from GLSL code string.""" pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*\n)" # first group captures quoted strings (double or single) # second group captures comments (//single-line or /* multi-line */) regex = re.compile(pattern, re.MULTILI...
Merge all includes recursively.
def merge_includes(code): """Merge all includes recursively.""" pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"' regex = re.compile(pattern) includes = [] def replace(match): filename = match.group("filename") if filename not in includes: includes.append...
Add a new widget to this grid. This will cause other widgets in the grid to be resized to make room for the new widget. Can be used to replace a widget as well
def add_widget(self, widget=None, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Add a new widget to this grid. This will cause other widgets in the grid to be resized to make room for the new widget. Can be used to replace a widget as well Paramet...
Remove a widget from this grid
def remove_widget(self, widget): """Remove a widget from this grid Parameters ---------- widget : Widget The Widget to remove """ self._grid_widgets = dict((key, val) for (key, val) in self._grid_widgets.items() ...
Resize a widget in the grid to new dimensions.
def resize_widget(self, widget, row_span, col_span): """Resize a widget in the grid to new dimensions. Parameters ---------- widget : Widget The widget to resize row_span : int The number of rows to be occupied by this widget. col_span : int ...
Create a new Grid and add it as a child widget.
def add_grid(self, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Create a new Grid and add it as a child widget. Parameters ---------- row : int The row in which to add the widget (0 is the topmost row) col : int The ...
Create a new ViewBox and add it as a child widget.
def add_view(self, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Create a new ViewBox and add it as a child widget. Parameters ---------- row : int The row in which to add the widget (0 is the topmost row) col : int T...
Find font
def find_font(face, bold, italic): """Find font""" bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN face = face.encode('utf8') fontconfig.FcInit() pattern = fontconfig.FcPatternCreate() fontconfig.FcPatternAddInteger(pattern, FC_WEIG...
List system fonts
def _list_fonts(): """List system fonts""" stdout_, stderr = run_subprocess(['fc-list', ':scalable=true', 'family']) vals = [v.split(',')[0] for v in stdout_.strip().splitlines(False)] return vals
Helper to get vispy calling function from the stack
def _get_vispy_caller(): """Helper to get vispy calling function from the stack""" records = inspect.stack() # first few records are vispy-based logging calls for record in records[5:]: module = record[0].f_globals['__name__'] if module.startswith('vispy'): line = str(record[...
Convenience function for setting the logging level
def set_log_level(verbose, match=None, return_old=False): """Convenience function for setting the logging level Parameters ---------- verbose : bool, str, int, or None The verbosity of messages to print. If a str, it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that thes...
Send an exception and traceback to the logger. This function is used in cases where an exception is handled safely but nevertheless should generate a descriptive error message. An extra line is inserted into the stack trace indicating where the exception was caught. Parameters ---------- level: str See set_log_level fo...
def log_exception(level='warning', tb_skip=2): """ Send an exception and traceback to the logger. This function is used in cases where an exception is handled safely but nevertheless should generate a descriptive error message. An extra line is inserted into the stack trace indicating where the...
Helper for prining errors in callbacks
def _handle_exception(ignore_callback_errors, print_callback_errors, obj, cb_event=None, node=None): """Helper for prining errors in callbacks See EventEmitter._invoke_callback for a use example. """ if not hasattr(obj, '_vispy_err_registry'): obj._vispy_err_registry = {} ...
Serialize a NumPy array.
def _serialize_buffer(buffer, array_serialization=None): """Serialize a NumPy array.""" if array_serialization == 'binary': # WARNING: in NumPy 1.9, tostring() has been renamed to tobytes() # but tostring() is still here for now for backward compatibility. return buffer.ravel().tostring(...
Log message emitter that optionally matches and/ or records
def _vispy_emit_match_andor_record(self, record): """Log message emitter that optionally matches and/or records""" test = record.getMessage() match = self._vispy_match if (match is None or re.search(match, test) or re.search(match, _get_vispy_caller())): if se...
Convert * obj * to a new ShaderObject. If the output is a Variable with no name then set its name using * ref *.
def create(self, obj, ref=None): """ Convert *obj* to a new ShaderObject. If the output is a Variable with no name, then set its name using *ref*. """ if isinstance(ref, Variable): ref = ref.name elif isinstance(ref, string_types) and ref.startswith('gl_'): ...
Return all dependencies required to use this object. The last item in the list is * self *.
def dependencies(self, sort=False): """ Return all dependencies required to use this object. The last item in the list is *self*. """ alldeps = [] if sort: def key(obj): # sort deps such that we get functions, variables, self. if not i...
Increment the reference count for * dep *. If this is a new dependency then connect to its * changed * event.
def _add_dep(self, dep): """ Increment the reference count for *dep*. If this is a new dependency, then connect to its *changed* event. """ if dep in self._deps: self._deps[dep] += 1 else: self._deps[dep] = 1 dep._dependents[self] = None
Decrement the reference count for * dep *. If the reference count reaches 0 then the dependency is removed and its * changed * event is disconnected.
def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed and its *changed* event is disconnected. """ refcount = self._deps[dep] if refcount == 1: self._deps.pop(dep) ...
Called when a dependency s expression has changed.
def _dep_changed(self, dep, code_changed=False, value_changed=False): """ Called when a dependency's expression has changed. """ self.changed(code_changed, value_changed)
Inform dependents that this shaderobject has changed.
def changed(self, code_changed=False, value_changed=False): """Inform dependents that this shaderobject has changed. """ for d in self._dependents: d._dep_changed(self, code_changed=code_changed, value_changed=value_changed)
The great missing equivalence function: Guaranteed evaluation to a single bool value.
def eq(a, b): """ The great missing equivalence function: Guaranteed evaluation to a single bool value. """ if a is b: return True if a is None or b is None: return True if a is None and b is None else False try: e = a == b except ValueError: return False ...
Zoom in ( or out ) at the given center
def zoom(self, factor, center=None): """ Zoom in (or out) at the given center Parameters ---------- factor : float or tuple Fraction by which the scene should be zoomed (e.g. a factor of 2 causes the scene to appear twice as large). center : tuple of 2-4 ...
Pan the view.
def pan(self, *pan): """Pan the view. Parameters ---------- *pan : length-2 sequence The distance to pan the view, in the coordinate system of the scene. """ if len(pan) == 1: pan = pan[0] self.rect = self.rect + pan
The SubScene received a mouse event ; update transform accordingly.
def viewbox_mouse_event(self, event): """ The SubScene received a mouse event; update transform accordingly. Parameters ---------- event : instance of Event The event. """ if event.handled or not self.interactive: return #...
Set the volume data.
def set_data(self, vol, clim=None): """ Set the volume data. Parameters ---------- vol : ndarray The 3D volume. clim : tuple | None Colormap limits to use. None will use the min and max values. """ # Check volume if not isinstance...
Create and set positions and texture coords from the given shape We have six faces with 1 quad ( 2 triangles ) each resulting in 6 * 2 * 3 = 36 vertices in total.
def _create_vertex_data(self): """ Create and set positions and texture coords from the given shape We have six faces with 1 quad (2 triangles) each, resulting in 6*2*3 = 36 vertices in total. """ shape = self._vol_shape # Get corner coordinates. The -0....
Set the data
def set_data(self, pos=None, color=None): """Set the data Parameters ---------- pos : list, tuple or numpy array Bounds of the region along the axis. len(pos) must be >=2. color : list, tuple, or array The color to use when drawing the line. It must have ...
This method is called immediately before each draw.
def _prepare_draw(self, view=None): """This method is called immediately before each draw. The *view* argument indicates which view is about to be drawn. """ if self._changed['pos']: self.pos_buf.set_data(self._pos) self._changed['pos'] = False if self....
Repopulate cache
def refresh_cache(self, cat_id): ''' Repopulate cache ''' self.cache[cat_id] = most_recent_25_posts_by_category(cat_id) self.last_refresh[cat_id] = datetime.now() print ('Cache refresh at...', str(self.last_refresh[cat_id]))
Merge overlapping intervals.
def _merge_intervals(self, min_depth): """ Merge overlapping intervals. This method is called only once in the constructor. """ def add_interval(ret, start, stop): if min_depth is not None: shift = 2 * (29 - min_depth) mask = (int(1) <...
Return the union between self and another_is.
def union(self, another_is): """ Return the union between self and ``another_is``. Parameters ---------- another_is : `IntervalSet` an IntervalSet object. Returns ------- interval : `IntervalSet` the union of self with ``another_is...
Convert an IntervalSet using the NESTED numbering scheme to an IntervalSet containing UNIQ numbers for HEALPix cells.
def to_nuniq_interval_set(cls, nested_is): """ Convert an IntervalSet using the NESTED numbering scheme to an IntervalSet containing UNIQ numbers for HEALPix cells. Parameters ---------- nested_is : `IntervalSet` IntervalSet object storing HEALPix cells as [i...
Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix cells following the NESTED numbering scheme.
def from_nuniq_interval_set(cls, nuniq_is): """ Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix cells following the NESTED numbering scheme. Parameters ---------- nuniq_is : `IntervalSet` IntervalSet object storing HEA...
Merge two lists of intervals according to the boolean function op
def merge(a_intervals, b_intervals, op): """ Merge two lists of intervals according to the boolean function op ``a_intervals`` and ``b_intervals`` need to be sorted and consistent (no overlapping intervals). This operation keeps the resulting interval set consistent. Parameters...
Delete the object from GPU memory.
def delete(self): """ Delete the object from GPU memory. Note that the GPU object will also be deleted when this gloo object is about to be deleted. However, sometimes you want to explicitly delete the GPU object explicitly. """ # We only allow the object from being del...
Set the data
def set_data(self, image): """Set the data Parameters ---------- image : array-like The image data. """ data = np.asarray(image) if self._data is None or self._data.shape != data.shape: self._need_vertex_update = True self._data = ...
Rebuild the _data_lookup_fn using different interpolations within the shader
def _build_interpolation(self): """Rebuild the _data_lookup_fn using different interpolations within the shader """ interpolation = self._interpolation self._data_lookup_fn = self._interpolation_fun[interpolation] self.shared_program.frag['get_data'] = self._data_lookup_f...
Rebuild the vertex buffers used for rendering the image when using the subdivide method.
def _build_vertex_data(self): """Rebuild the vertex buffers used for rendering the image when using the subdivide method. """ grid = self._grid w = 1.0 / grid[1] h = 1.0 / grid[0] quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0], [0, 0, 0...
Decide which method to use for * view * and configure it accordingly.
def _update_method(self, view): """Decide which method to use for *view* and configure it accordingly. """ method = self._method if method == 'auto': if view.transforms.get_transform().Linear: method = 'subdivide' else: method = 'im...
Append a new set of vertices to the collection.
def append(self, P, closed=False, itemsize=None, **kwargs): """ Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices posit...
Given a path P return the baked vertices as they should be copied in the collection if the path has already been appended.
def bake(self, P, key='curr', closed=False, itemsize=None): """ Given a path P, return the baked vertices as they should be copied in the collection if the path has already been appended. Example: -------- paths.append(P) P *= 2 paths['prev'][0] = bake(P...
Draw collection
def draw(self, mode="triangle_strip"): """ Draw collection """ gl.glDepthMask(gl.GL_FALSE) Collection.draw(self, mode) gl.glDepthMask(gl.GL_TRUE)
Stop all timers in a canvas.
def _stop_timers(canvas): """Stop all timers in a canvas.""" for attr in dir(canvas): try: attr_obj = getattr(canvas, attr) except NotImplementedError: # This try/except is needed because canvas.position raises # an error (it is not implemented in this backend...
Print stack trace from call that didn t originate from here
def _last_stack_str(): """Print stack trace from call that didn't originate from here""" stack = extract_stack() for s in stack[::-1]: if op.join('vispy', 'gloo', 'buffer.py') not in __file__: break return format_list([s])[0]
Set a sub - region of the buffer ( deferred operation ).
def set_subdata(self, data, offset=0, copy=False): """ Set a sub-region of the buffer (deferred operation). Parameters ---------- data : ndarray Data to be uploaded offset: int Offset in buffer where to start copying data (in bytes) copy: bool ...
Set data in the buffer ( deferred operation ).
def set_data(self, data, copy=False): """ Set data in the buffer (deferred operation). This completely resets the size and contents of the buffer. Parameters ---------- data : ndarray Data to be uploaded copy: bool Since the operation is deferred...
Resize this buffer ( deferred operation ). Parameters ---------- size: int New buffer size in bytes.
def resize_bytes(self, size): """ Resize this buffer (deferred operation). Parameters ---------- size : int New buffer size in bytes. """ self._nbytes = size self._glir.command('SIZE', self._id, size) # Invalidate any view on this buf...
Set a sub - region of the buffer ( deferred operation ).
def set_subdata(self, data, offset=0, copy=False, **kwargs): """ Set a sub-region of the buffer (deferred operation). Parameters ---------- data : ndarray Data to be uploaded offset: int Offset in buffer where to start copying data (in bytes) cop...
Set data ( deferred operation )
def set_data(self, data, copy=False, **kwargs): """ Set data (deferred operation) Parameters ---------- data : ndarray Data to be uploaded copy: bool Since the operation is deferred, data may change before data is actually uploaded to GPU memo...
GLSL declaration strings required for a variable to hold this data.
def glsl_type(self): """ GLSL declaration strings required for a variable to hold this data. """ if self.dtype is None: return None dtshape = self.dtype[0].shape n = dtshape[0] if dtshape else 1 if n > 1: dtype = 'vec%d' % n else: ...
Resize the buffer ( in - place deferred operation )
def resize_bytes(self, size): """ Resize the buffer (in-place, deferred operation) Parameters ---------- size : integer New buffer size in bytes Notes ----- This clears any pending operations. """ Buffer.resize_bytes(self, size) ...
Compile all code and return a dict { name: code } where the keys are determined by the keyword arguments passed to __init__ ().
def compile(self, pretty=True): """ Compile all code and return a dict {name: code} where the keys are determined by the keyword arguments passed to __init__(). Parameters ---------- pretty : bool If True, use a slower method to mangle object names. This produces ...
Rename all objects quickly to guaranteed - unique names using the id () of each object.
def _rename_objects_fast(self): """ Rename all objects quickly to guaranteed-unique names using the id() of each object. This produces mostly unreadable GLSL, but is about 10x faster to compile. """ for shader_name, deps in self._shader_deps.items(): for dep ...
Rename all objects like name_1 to avoid conflicts. Objects are only renamed if necessary.
def _rename_objects_pretty(self): """ Rename all objects like "name_1" to avoid conflicts. Objects are only renamed if necessary. This method produces more readable GLSL, but is rather slow. """ # # 1. For each object, add its static names to the global namespace ...
Return True if * name * is available for * obj * in * shaders *.
def _name_available(self, obj, name, shaders): """ Return True if *name* is available for *obj* in *shaders*. """ if name in self._global_ns: return False shaders = self.shaders if self._is_global(obj) else shaders for shader in shaders: if name in self._s...
Assign * name * to * obj * in * shaders *.
def _assign_name(self, obj, name, shaders): """ Assign *name* to *obj* in *shaders*. """ if self._is_global(obj): assert name not in self._global_ns self._global_ns[name] = obj else: for shader in shaders: ns = self._shader_ns[shader] ...
Rebuilds the shaders and repositions the objects that are used internally by the ColorBarVisual
def _update(self): """Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual """ x, y = self._pos halfw, halfh = self._halfdim # test that width and height are non-zero if halfw <= 0: raise ValueError("hal...
Rebuilds the shaders and repositions the objects that are used internally by the ColorBarVisual
def _update(self): """Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual """ self._colorbar.halfdim = self._halfdim self._border.halfdim = self._halfdim self._label.text = self._label_str self._ticks[0].text = str(...
updates the positions of the colorbars and labels
def _update_positions(self): """ updates the positions of the colorbars and labels """ self._colorbar.pos = self._pos self._border.pos = self._pos if self._orientation == "right" or self._orientation == "left": self._label.rotation = -90 x, y = self...
Calculate the text centeritions given the ColorBar parameters.
def _calc_positions(center, halfdim, border_width, orientation, transforms): """ Calculate the text centeritions given the ColorBar parameters. Note ---- This is static because in principle, this function does not need access to the state ...
The size of the ColorBar
def size(self): """ The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar """ (halfw, halfh) = self._halfdim if self.orientation in ["top",...
Add pseudo fields ( e. g non - displayed fields ) to the display.
def add_pseudo_fields(self): """Add 'pseudo' fields (e.g non-displayed fields) to the display.""" fields = [] if self.backlight_on != enums.BACKLIGHT_ON_NEVER: fields.append( display_fields.BacklightPseudoField(ref='0', backlight_rule=self.backlight_on) ) ...
Return a new Rect padded ( smaller ) by padding on all sides
def padded(self, padding): """Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. """ return Rect(pos=...
Return a Rect covering the same area but with height and width guaranteed to be positive.
def normalized(self): """Return a Rect covering the same area, but with height and width guaranteed to be positive.""" return Rect(pos=(min(self.left, self.right), min(self.top, self.bottom)), size=(abs(self.width), abs(self.height)))
Return a Rect with the same bounds but with axes inverted
def flipped(self, x=False, y=True): """Return a Rect with the same bounds but with axes inverted Parameters ---------- x : bool Flip the X axis. y : bool Flip the Y axis. Returns ------- rect : instance of Rect The fli...
Return array of coordinates that can be mapped by Transform classes.
def _transform_in(self): """Return array of coordinates that can be mapped by Transform classes.""" return np.array([ [self.left, self.bottom, 0, 1], [self.right, self.top, 0, 1]])
Automatically configure the TransformSystem:
def configure(self, viewport=None, fbo_size=None, fbo_rect=None, canvas=None): """Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the log...
Physical resolution of the document coordinate system ( dots per inch ).
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi
Return a transform mapping between any two coordinate systems. Parameters ---------- map_from: str The starting coordinate system to map from. Must be one of: visual scene document canvas framebuffer or render. map_to: str The ending coordinate system to map to. Must be one of: visual scene document canvas framebuffer ...
def get_transform(self, map_from='visual', map_to='render'): """Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas...
Helper to calculate the delta position
def _calculate_delta_pos(adjacency_arr, pos, t, optimal): """Helper to calculate the delta position""" # XXX eventually this should be refactored for the sparse case to only # do the necessary pairwise distances delta = pos[:, np.newaxis, :] - pos # Distance between points distance2 = (delta*de...
You can insert arbitrary business logic code here
def get_recipe_intent_handler(request): """ You can insert arbitrary business logic code here """ # Get variables like userId, slots, intent name etc from the 'Request' object ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object. if ingredient == ...
Set the usage options for vispy
def use(app=None, gl=None): """ Set the usage options for vispy Specify what app backend and GL backend to use. Parameters ---------- app : str The app backend to use (case insensitive). Standard backends: * 'PyQt4': use Qt widget toolkit via PyQt4. * 'PyQt5': use Q...
Run command using subprocess. Popen
def run_subprocess(command, return_code=False, **kwargs): """Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to ...
Start the timer.
def start(self, interval=None, iterations=None): """Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self.interval will be used. If *iterations* is specified, the timer will stop after emitting that number of events. If un...
Stop the timer.
def stop(self): """Stop the timer.""" self._backend._vispy_stop() self._running = False self.events.stop(type='timer_stop')
Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order.
def _best_res_pixels(self): """ Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray` The array of HEALPix at ``max_order`` """ factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self...
Returns a boolean mask array of the positions lying inside ( or outside ) the MOC instance.
def contains(self, ra, dec, keep_inside=True): """ Returns a boolean mask array of the positions lying inside (or outside) the MOC instance. Parameters ---------- ra : `astropy.units.Quantity` Right ascension array dec : `astropy.units.Quantity` D...