sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _assign_uid(self, sid): """ Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object """ self._uid = ru.generate_id( 'pipeline.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid) for stage in sel...
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object
entailment
def _pass_uid(self): """ Purpose: Pass current Pipeline's uid to all Stages. :argument: List of Stage objects (optional) """ for stage in self._stages: stage.parent_pipeline['uid'] = self._uid stage.parent_pipeline['name'] = self._name stage....
Purpose: Pass current Pipeline's uid to all Stages. :argument: List of Stage objects (optional)
entailment
def hexdump(src, length=16, sep='.'): """ Hexdump function by sbz and 7h3rAm on Github: (https://gist.github.com/7h3rAm/5603718). :param src: Source, the string to be shown in hexadecimal format :param length: Number of hex characters to print in one row :param sep: Unprintable characters repres...
Hexdump function by sbz and 7h3rAm on Github: (https://gist.github.com/7h3rAm/5603718). :param src: Source, the string to be shown in hexadecimal format :param length: Number of hex characters to print in one row :param sep: Unprintable characters representation :return:
entailment
def xym(source_id, srcdir, dstdir, strict=False, strict_examples=False, debug_level=0, add_line_refs=False, force_revision_pyang=False, force_revision_regexp=False): """ Extracts YANG model from an IETF RFC or draft text file. This is the main (external) API entry for the module. :param add_lin...
Extracts YANG model from an IETF RFC or draft text file. This is the main (external) API entry for the module. :param add_line_refs: :param source_id: identifier (file name or URL) of a draft or RFC file containing one or more YANG models :param srcdir: If source_id points to a file, the opt...
entailment
def warning(self, s): """ Prints out a warning message to stderr. :param s: The warning string to print :return: None """ print(" WARNING: '%s', %s" % (self.src_id, s), file=sys.stderr)
Prints out a warning message to stderr. :param s: The warning string to print :return: None
entailment
def error(self, s): """ Prints out an error message to stderr. :param s: The error string to print :return: None """ print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr)
Prints out an error message to stderr. :param s: The error string to print :return: None
entailment
def remove_leading_spaces(self, input_model): """ This function is a part of the model post-processing pipeline. It removes leading spaces from an extracted module; depending on the formatting of the draft/rfc text, may have multiple spaces prepended to each line. The function a...
This function is a part of the model post-processing pipeline. It removes leading spaces from an extracted module; depending on the formatting of the draft/rfc text, may have multiple spaces prepended to each line. The function also determines the length of the longest line in the modul...
entailment
def add_line_references(self, input_model): """ This function is a part of the model post-processing pipeline. For each line in the module, it adds a reference to the line number in the original draft/RFC from where the module line was extracted. :param input_model: The YANG mode...
This function is a part of the model post-processing pipeline. For each line in the module, it adds a reference to the line number in the original draft/RFC from where the module line was extracted. :param input_model: The YANG model to be processed :return: Modified YANG model, where li...
entailment
def remove_extra_empty_lines(self, input_model): """ Removes superfluous newlines from a YANG model that was extracted from a draft or RFC text. Newlines are removed whenever 2 or more consecutive empty lines are found in the model. This function is a part of the model post-proce...
Removes superfluous newlines from a YANG model that was extracted from a draft or RFC text. Newlines are removed whenever 2 or more consecutive empty lines are found in the model. This function is a part of the model post-processing pipeline. :param input_model: The YANG model to be proc...
entailment
def post_process_model(self, input_model, add_line_refs): """ This function defines the order and execution logic for actions that are performed in the model post-processing pipeline. :param input_model: The YANG model to be processed in the pipeline :param add_line_refs: Flag th...
This function defines the order and execution logic for actions that are performed in the model post-processing pipeline. :param input_model: The YANG model to be processed in the pipeline :param add_line_refs: Flag that controls whether line number references should be added to the ...
entailment
def write_model_to_file(self, mdl, fn): """ Write a YANG model that was extracted from a source identifier (URL or source .txt file) to a .yang destination file :param mdl: YANG model, as a list of lines :param fn: Name of the YANG model file :return: """ ...
Write a YANG model that was extracted from a source identifier (URL or source .txt file) to a .yang destination file :param mdl: YANG model, as a list of lines :param fn: Name of the YANG model file :return:
entailment
def debug_print_line(self, i, level, line): """ Debug print of the currently parsed line :param i: The line number of the line that is being currently parsed :param level: Parser level :param line: the line that is currently being parsed :return: None """ ...
Debug print of the currently parsed line :param i: The line number of the line that is being currently parsed :param level: Parser level :param line: the line that is currently being parsed :return: None
entailment
def debug_print_strip_msg(self, i, line): """ Debug print indicating that an empty line is being skipped :param i: The line number of the line that is being currently parsed :param line: the parsed line :return: None """ if self.debug_level == 2: print...
Debug print indicating that an empty line is being skipped :param i: The line number of the line that is being currently parsed :param line: the parsed line :return: None
entailment
def strip_empty_lines_forward(self, content, i): """ Skip over empty lines :param content: parsed text :param i: current parsed line :return: number of skipped lined """ while i < len(content): line = content[i].strip(' \r\n\t\f') if line !...
Skip over empty lines :param content: parsed text :param i: current parsed line :return: number of skipped lined
entailment
def strip_empty_lines_backward(self, model, max_lines_to_strip): """ Strips empty lines preceding the line that is currently being parsed. This fucntion is called when the parser encounters a Footer. :param model: lines that were added to the model up to this point :param line_nu...
Strips empty lines preceding the line that is currently being parsed. This fucntion is called when the parser encounters a Footer. :param model: lines that were added to the model up to this point :param line_num: the number of teh line being parsed :param max_lines_to_strip: max number ...
entailment
def extract_yang_model(self, content): """ Extracts one or more YANG models from an RFC or draft text string in which the models are specified. The function skips over page formatting (Page Headers and Footers) and performs basic YANG module syntax checking. In strict mode, the f...
Extracts one or more YANG models from an RFC or draft text string in which the models are specified. The function skips over page formatting (Page Headers and Footers) and performs basic YANG module syntax checking. In strict mode, the function also enforces the <CODE BEGINS> / <CODE END...
entailment
def auto_retry(fun): """Decorator for retrying method calls, based on instance parameters.""" @functools.wraps(fun) def decorated(instance, *args, **kwargs): """Wrapper around a decorated function.""" cfg = instance._retry_config remaining_tries = cfg.retry_attempts current_...
Decorator for retrying method calls, based on instance parameters.
entailment
def extract_pattern(fmt): """Extracts used strings from a %(foo)s pattern.""" class FakeDict(object): def __init__(self): self.seen_keys = set() def __getitem__(self, key): self.seen_keys.add(key) return '' def keys(self): return self.see...
Extracts used strings from a %(foo)s pattern.
entailment
def iso_mesh_line(vertices, tris, vertex_data, levels): """Generate an isocurve from vertex data in a surface mesh. Parameters ---------- vertices : ndarray, shape (Nv, 3) Vertex coordinates. tris : ndarray, shape (Nf, 3) Indices of triangular element into the vertices array. ve...
Generate an isocurve from vertex data in a surface mesh. Parameters ---------- vertices : ndarray, shape (Nv, 3) Vertex coordinates. tris : ndarray, shape (Nf, 3) Indices of triangular element into the vertices array. vertex_data : ndarray, shape (Nv,) data at vertex. le...
entailment
def set_data(self, vertices=None, tris=None, data=None): """Set the data Parameters ---------- vertices : ndarray, shape (Nv, 3) | None Vertex coordinates. tris : ndarray, shape (Nf, 3) | None Indices into the vertex array. data : ndarray, shape (...
Set the data Parameters ---------- vertices : ndarray, shape (Nv, 3) | None Vertex coordinates. tris : ndarray, shape (Nf, 3) | None Indices into the vertex array. data : ndarray, shape (Nv,) | None scalar at vertices
entailment
def set_color(self, color): """Set the color Parameters ---------- color : instance of Color The color to use. """ if color is not None: self._color_lev = color self._need_color_update = True self.update()
Set the color Parameters ---------- color : instance of Color The color to use.
entailment
def _compute_iso_color(self): """ compute LineVisual color from level index and corresponding level color """ level_color = [] colors = self._lc for i, index in enumerate(self._li): level_color.append(np.zeros((index, 4)) + colors[i]) self._cl = np.vst...
compute LineVisual color from level index and corresponding level color
entailment
def remove(self): """ Remove the layer artist for good """ self._multivol.deallocate(self.id) ARRAY_CACHE.pop(self.id, None) PIXEL_CACHE.pop(self.id, None)
Remove the layer artist for good
entailment
def _inject(): """ Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API. """ # Get namespaces NS = globals() GLNS = _GL.__dict__ # Get names that we use in our API used_names = [] used_names.extend([names[0] ...
Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API.
entailment
def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) if fh is not None and pa...
Alternative to `imp.find_module` that can also search in subpackages.
entailment
def triangulate(vertices): """Triangulate a set of vertices Parameters ---------- vertices : array-like The vertices. Returns ------- vertices : array-like The vertices. tringles : array-like The triangles. """ n = len(vertices) vertices = np.asarray...
Triangulate a set of vertices Parameters ---------- vertices : array-like The vertices. Returns ------- vertices : array-like The vertices. tringles : array-like The triangles.
entailment
def triangulate(self): """Do the triangulation """ self._initialize() pts = self.pts front = self._front ## Begin sweep (sec. 3.4) for i in range(3, pts.shape[0]): pi = pts[i] #debug("========== New point %d: %s ==========...
Do the triangulation
entailment
def _edge_event(self, i, j): """ Force edge (i, j) to be present in mesh. This works by removing intersected triangles and filling holes up to the cutting edge. """ front_index = self._front.index(i) #debug(" == edge event ==") front = self._fro...
Force edge (i, j) to be present in mesh. This works by removing intersected triangles and filling holes up to the cutting edge.
entailment
def _find_cut_triangle(self, edge): """ Return the triangle that has edge[0] as one of its vertices and is bisected by edge. Return None if no triangle is found. """ edges = [] # opposite edge for each triangle attached to edge[0] for tri in self.tris: ...
Return the triangle that has edge[0] as one of its vertices and is bisected by edge. Return None if no triangle is found.
entailment
def _edge_in_front(self, edge): """ Return the index where *edge* appears in the current front. If the edge is not in the front, return -1 """ e = (list(edge), list(edge)[::-1]) for i in range(len(self._front)-1): if self._front[i:i+2] in e: return i ...
Return the index where *edge* appears in the current front. If the edge is not in the front, return -1
entailment
def _edge_opposite_point(self, tri, i): """ Given a triangle, return the edge that is opposite point i. Vertexes are returned in the same orientation as in tri. """ ind = tri.index(i) return (tri[(ind+1) % 3], tri[(ind+2) % 3])
Given a triangle, return the edge that is opposite point i. Vertexes are returned in the same orientation as in tri.
entailment
def _adjacent_tri(self, edge, i): """ Given a triangle formed by edge and i, return the triangle that shares edge. *i* may be either a point or the entire triangle. """ if not np.isscalar(i): i = [x for x in i if x not in edge][0] try: pt1 = self....
Given a triangle formed by edge and i, return the triangle that shares edge. *i* may be either a point or the entire triangle.
entailment
def _tri_from_edge(self, edge): """Return the only tri that contains *edge*. If two tris share this edge, raise an exception. """ edge = tuple(edge) p1 = self._edges_lookup.get(edge, None) p2 = self._edges_lookup.get(edge[::-1], None) if p1 is None: if...
Return the only tri that contains *edge*. If two tris share this edge, raise an exception.
entailment
def _edges_in_tri_except(self, tri, edge): """Return the edges in *tri*, excluding *edge*. """ edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)] try: edges.remove(tuple(edge)) except ValueError: edges.remove(tuple(edge[::-1])) return edges
Return the edges in *tri*, excluding *edge*.
entailment
def _edge_below_front(self, edge, front_index): """Return True if *edge* is below the current front. One of the points in *edge* must be _on_ the front, at *front_index*. """ f0 = self._front[front_index-1] f1 = self._front[front_index+1] return (self._orientati...
Return True if *edge* is below the current front. One of the points in *edge* must be _on_ the front, at *front_index*.
entailment
def _intersected_edge(self, edges, cut_edge): """ Given a list of *edges*, return the first that is intersected by *cut_edge*. """ for edge in edges: if self._edges_intersect(edge, cut_edge): return edge
Given a list of *edges*, return the first that is intersected by *cut_edge*.
entailment
def _find_edge_intersections(self): """ Return a dictionary containing, for each edge in self.edges, a list of the positions at which the edge should be split. """ edges = self.pts[self.edges] cuts = {} # { edge: [(intercept, point), ...], ... } for i in range(ed...
Return a dictionary containing, for each edge in self.edges, a list of the positions at which the edge should be split.
entailment
def _projection(self, a, b, c): """Return projection of (a,b) onto (a,c) Arguments are point locations, not indexes. """ ab = b - a ac = c - a return a + ((ab*ac).sum() / (ac*ac).sum()) * ac
Return projection of (a,b) onto (a,c) Arguments are point locations, not indexes.
entailment
def _edges_intersect(self, edge1, edge2): """ Return 1 if edges intersect completely (endpoints excluded) """ h12 = self._intersect_edge_arrays(self.pts[np.array(edge1)], self.pts[np.array(edge2)]) h21 = self._intersect_edge_arrays(self....
Return 1 if edges intersect completely (endpoints excluded)
entailment
def _intersection_matrix(self, lines): """ Return a 2D array of intercepts such that intercepts[i, j] is the intercept of lines[i] onto lines[j]. *lines* must be an array of point locations with shape (N, 2, 2), where the axes are (lines, points_per_line, xy_per_point)....
Return a 2D array of intercepts such that intercepts[i, j] is the intercept of lines[i] onto lines[j]. *lines* must be an array of point locations with shape (N, 2, 2), where the axes are (lines, points_per_line, xy_per_point). The intercept is described in intersect_e...
entailment
def _intersect_edge_arrays(self, lines1, lines2): """Return the intercepts of all lines defined in *lines1* as they intersect all lines in *lines2*. Arguments are of shape (..., 2, 2), where axes are: 0: number of lines 1: two points per line 2: x,y pa...
Return the intercepts of all lines defined in *lines1* as they intersect all lines in *lines2*. Arguments are of shape (..., 2, 2), where axes are: 0: number of lines 1: two points per line 2: x,y pair per point Lines are compared elementwise across t...
entailment
def _orientation(self, edge, point): """ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. """ v1 = self.pts[point] - self.pts[edge[0]] v2 = self.pts[edge[1]] - self.pts[edge[0]] c = np.cross(v1, v2) # positive i...
Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel.
entailment
def load_ipython_extension(ipython): """ Entry point of the IPython extension Parameters ---------- IPython : IPython interpreter An instance of the IPython interpreter that is handed over to the extension """ import IPython # don't continue if IPython version is < 3.0 ...
Entry point of the IPython extension Parameters ---------- IPython : IPython interpreter An instance of the IPython interpreter that is handed over to the extension
entailment
def _load_webgl_backend(ipython): """ Load the webgl backend for the IPython notebook""" from .. import app app_instance = app.use_app("ipynb_webgl") if app_instance.backend_name == "ipynb_webgl": ipython.write("Vispy IPython module has loaded successfully") else: # TODO: Improve t...
Load the webgl backend for the IPython notebook
entailment
def draw(self, mode=None): """ Draw collection """ if self._need_update: self._update() program = self._programs[0] mode = mode or self._mode if self._indices_list is not None: program.draw(mode, self._indices_buffer) else: program.d...
Draw collection
entailment
def gaussian_filter(data, sigma): """ Drop-in replacement for scipy.ndimage.gaussian_filter. (note: results are only approximately equal to the output of gaussian_filter) """ if np.isscalar(sigma): sigma = (sigma,) * data.ndim baseline = data.mean() filtered = data - baseline ...
Drop-in replacement for scipy.ndimage.gaussian_filter. (note: results are only approximately equal to the output of gaussian_filter)
entailment
def translate(offset, dtype=None): """Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix descr...
Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the translation.
entailment
def scale(s, dtype=None): """Non-uniform scaling along the x, y, and z axes Parameters ---------- s : array-like, shape (3,) Scaling in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing ...
Non-uniform scaling along the x, y, and z axes Parameters ---------- s : array-like, shape (3,) Scaling in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the scaling.
entailment
def rotate(angle, axis, dtype=None): """The 3x3 rotation matrix for rotation about a vector. Parameters ---------- angle : float The angle of rotation, in degrees. axis : ndarray The x, y, z coordinates of the axis direction vector. """ angle = np.radians(angle) assert l...
The 3x3 rotation matrix for rotation about a vector. Parameters ---------- angle : float The angle of rotation, in degrees. axis : ndarray The x, y, z coordinates of the axis direction vector.
entailment
def perspective(fovy, aspect, znear, zfar): """Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float ...
Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float Far coordinate of the field of view. Returns...
entailment
def affine_map(points1, points2): """ Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, shape (4, 3). """ A = np.ones((4, 4)) A[:, :3] = points1 B = np.ones((4, 4)) B[:, :3] = points2 # solve 3 sets of linear equat...
Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, shape (4, 3).
entailment
def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._new_msg("< Exiting %s, total time: %0....
Add a final message; flush the message list if no parent profiler.
entailment
def _init(): """ Create global Config object, parse command flags """ global config, _data_path, _allowed_config_keys app_dir = _get_vispy_app_dir() if app_dir is not None: _data_path = op.join(app_dir, 'data') _test_data_path = op.join(app_dir, 'test_data') else: _data_...
Create global Config object, parse command flags
entailment
def _parse_command_line_arguments(): """ Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy namespace. """ global config # Get command line args for vispy argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',...
Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy namespace.
entailment
def _get_vispy_app_dir(): """Helper to get the default directory for storing vispy data""" # Define default user directory user_dir = os.path.expanduser('~') # Get system app data dir path = None if sys.platform.startswith('win'): path1, path2 = os.getenv('LOCALAPPDATA'), os.getenv('APP...
Helper to get the default directory for storing vispy data
entailment
def _get_config_fname(): """Helper for the vispy config file""" directory = _get_vispy_app_dir() if directory is None: return None fname = op.join(directory, 'vispy.json') if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None: fname = op.join(_TempDir(), 'vispy.json') retu...
Helper for the vispy config file
entailment
def _load_config(): """Helper to load prefs from ~/.vispy/vispy.json""" fname = _get_config_fname() if fname is None or not op.isfile(fname): return dict() with open(fname, 'r') as fid: config = json.load(fid) return config
Helper to load prefs from ~/.vispy/vispy.json
entailment
def save_config(**kwargs): """Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/value pairs to save to the config file. """ if kwargs == {}: kwargs = config._config current_config = _load_config() current_config.update(**...
Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/value pairs to save to the config file.
entailment
def set_data_dir(directory=None, create=False, save=False): """Set vispy data download directory Parameters ---------- directory : str | None The directory to use. create : bool If True, create directory if it doesn't exist. save : bool If True, save the configuration to...
Set vispy data download directory Parameters ---------- directory : str | None The directory to use. create : bool If True, create directory if it doesn't exist. save : bool If True, save the configuration to the vispy config.
entailment
def _enable_profiling(): """ Start profiling and register callback to print stats when the program exits. """ import cProfile import atexit global _profiler _profiler = cProfile.Profile() _profiler.enable() atexit.register(_profile_atexit)
Start profiling and register callback to print stats when the program exits.
entailment
def sys_info(fname=None, overwrite=False): """Get relevant system and debugging information Parameters ---------- fname : str | None Filename to dump info to. Use None to simply print. overwrite : bool If True, overwrite file (if it exists). Returns ------- out : str ...
Get relevant system and debugging information Parameters ---------- fname : str | None Filename to dump info to. Use None to simply print. overwrite : bool If True, overwrite file (if it exists). Returns ------- out : str The system information as a string.
entailment
def compact(vertices, indices, tolerance=1e-3): """ Compact vertices and indices within given tolerance """ # Transform vertices into a structured array for np.unique to work n = len(vertices) V = np.zeros(n, dtype=[("pos", np.float32, 3)]) V["pos"][:, 0] = vertices[:, 0] V["pos"][:, 1] = verti...
Compact vertices and indices within given tolerance
entailment
def normals(vertices, indices): """ Compute normals over a triangulated surface Parameters ---------- vertices : ndarray (n,3) triangles vertices indices : ndarray (p,3) triangles indices """ # Compact similar vertices vertices, indices, mapping = compact(vertices...
Compute normals over a triangulated surface Parameters ---------- vertices : ndarray (n,3) triangles vertices indices : ndarray (p,3) triangles indices
entailment
def create_native(self): """ Create the native widget if not already done so. If the widget is already created, this function does nothing. """ if self._backend is not None: return # Make sure that the app is active assert self._app.native # Instantiat...
Create the native widget if not already done so. If the widget is already created, this function does nothing.
entailment
def connect(self, fun): """ Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- ...
Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- fun : callable T...
entailment
def size(self): """ The size of canvas/window """ size = self._backend._vispy_get_size() return (size[0] // self._px_scale, size[1] // self._px_scale)
The size of canvas/window
entailment
def show(self, visible=True, run=False): """Show or hide the canvas Parameters ---------- visible : bool Make the canvas visible. run : bool Run the backend event loop. """ self._backend._vispy_set_visible(visible) if run: ...
Show or hide the canvas Parameters ---------- visible : bool Make the canvas visible. run : bool Run the backend event loop.
entailment
def close(self): """Close the canvas Notes ----- This will usually destroy the GL context. For Qt, the context (and widget) will be destroyed only if the widget is top-level. To avoid having the widget destroyed (more like standard Qt behavior), consider making t...
Close the canvas Notes ----- This will usually destroy the GL context. For Qt, the context (and widget) will be destroyed only if the widget is top-level. To avoid having the widget destroyed (more like standard Qt behavior), consider making the widget a sub-widget.
entailment
def _update_fps(self, event): """Update the fps after every window""" self._frame_count += 1 diff = time() - self._basetime if (diff > self._fps_window): self._fps = self._frame_count / diff self._basetime = time() self._frame_count = 0 sel...
Update the fps after every window
entailment
def measure_fps(self, window=1, callback='%1.1f FPS'): """Measure the current FPS Sets the update window, connects the draw event to update_fps and sets the callback function. Parameters ---------- window : float The time-window (in seconds) to calculate FPS...
Measure the current FPS Sets the update window, connects the draw event to update_fps and sets the callback function. Parameters ---------- window : float The time-window (in seconds) to calculate FPS. Default 1.0. callback : function | str The f...
entailment
def render(self): """ Render the canvas to an offscreen buffer and return the image array. Returns ------- image : array Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the upper-left corner of the rendered region. """ ...
Render the canvas to an offscreen buffer and return the image array. Returns ------- image : array Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the upper-left corner of the rendered region.
entailment
def drag_events(self): """ Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation. """ if not self.is_dragging: return None event = self events = [] while True: # mouse_press ev...
Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation.
entailment
def trail(self): """ Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation. Returns None if there is no current drag operation. """ events = self.drag_events() if events is None: return None trail = np.empty(...
Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation. Returns None if there is no current drag operation.
entailment
def width_min(self, width_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget """ if width_min is None: self._width_limits[0] = 0 return width_min = float(wi...
Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget
entailment
def width_max(self, width_max): """Set the maximum width of the widget. Parameters ---------- width_max: None | float the maximum width of the widget. if None, maximum width is unbounded """ if width_max is None: self._width_limits[1] ...
Set the maximum width of the widget. Parameters ---------- width_max: None | float the maximum width of the widget. if None, maximum width is unbounded
entailment
def height_min(self, height_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget """ if height_min is None: self._height_limits[0] = 0 return height_min = floa...
Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget
entailment
def height_max(self, height_max): """Set the maximum height of the widget. Parameters ---------- height_max: None | float the maximum height of the widget. if None, maximum height is unbounded """ if height_max is None: self._height_li...
Set the maximum height of the widget. Parameters ---------- height_max: None | float the maximum height of the widget. if None, maximum height is unbounded
entailment
def inner_rect(self): """The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing sub-widgets outside this rectangle. """ m = self.margin + self._border_width + self.padding if not self.border_color.is_blank: ...
The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing sub-widgets outside this rectangle.
entailment
def _update_clipper(self): """Called whenever the clipper for this widget may need to be updated. """ if self.clip_children and self._clipper is None: self._clipper = Clipper() elif not self.clip_children: self._clipper = None if self._clipper is None: ...
Called whenever the clipper for this widget may need to be updated.
entailment
def _update_line(self): """ Update border line to match new shape """ w = self._border_width m = self.margin # border is drawn within the boundaries of the widget: # # size = (8, 7) margin=2 # internal rect = (3, 3, 2, 1) # ........ # ...........
Update border line to match new shape
entailment
def add_widget(self, widget): """ Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget :...
Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget : instance of Widget The widget to add....
entailment
def add_grid(self, *args, **kwargs): """ Create a new Grid and add it as a child widget. All arguments are given to Grid(). """ from .grid import Grid grid = Grid(*args, **kwargs) return self.add_widget(grid)
Create a new Grid and add it as a child widget. All arguments are given to Grid().
entailment
def add_view(self, *args, **kwargs): """ Create a new ViewBox and add it as a child widget. All arguments are given to ViewBox(). """ from .viewbox import ViewBox view = ViewBox(*args, **kwargs) return self.add_widget(view)
Create a new ViewBox and add it as a child widget. All arguments are given to ViewBox().
entailment
def remove_widget(self, widget): """ Remove a Widget as a managed child of this Widget. Parameters ---------- widget : instance of Widget The widget to remove. """ self._widgets.remove(widget) widget.parent = None self._update_child_wi...
Remove a Widget as a managed child of this Widget. Parameters ---------- widget : instance of Widget The widget to remove.
entailment
def pack_unit(value): """Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ pack = np.zeros(value.shape + (4,), dtype=np.ubyte) for i in range(4): value, pack[..., i] = np.modf(value * 256.) return pack
Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel
entailment
def pack_ieee(value): """Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ return np.fromstring(value.tostring(), np.ubyte).reshape((value.shape + (4,)))
Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel
entailment
def load_spatial_filters(packed=True): """Load spatial-filters kernel Parameters ---------- packed : bool Whether or not the data should be in "packed" representation for use in GLSL code. Returns ------- kernel : array 16x1024x4 (packed float in rgba) or 16...
Load spatial-filters kernel Parameters ---------- packed : bool Whether or not the data should be in "packed" representation for use in GLSL code. Returns ------- kernel : array 16x1024x4 (packed float in rgba) or 16x1024 (unpacked float) 16 interpolatio...
entailment
def list_fonts(): """List system fonts Returns ------- fonts : list of str List of system fonts. """ vals = _list_fonts() for font in _vispy_fonts: vals += [font] if font not in vals else [] vals = sorted(vals, key=lambda s: s.lower()) return vals
List system fonts Returns ------- fonts : list of str List of system fonts.
entailment
def timeout(limit, handler): """A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example...
A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example: >>>def timeout_handler(limit, ...
entailment
def _process_backend_kwargs(self, kwargs): """ Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments do not violate the backend capabilities. """ # Verify given argument with capability of the backend app = self....
Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments do not violate the backend capabilities.
entailment
def _set_range(self, init): """ Reset the view. """ #PerspectiveCamera._set_range(self, init) # Stop moving self._speed *= 0.0 # Get window size (and store factor now to sync with resizing) w, h = self._viewbox.size w, h = float(w), float(h) # ...
Reset the view.
entailment
def on_timer(self, event): """Timer event handler Parameters ---------- event : instance of Event The event. """ # Set relative speed and acceleration rel_speed = event.dt rel_acc = 0.1 # Get what's forward pf, pr, pl, pu = s...
Timer event handler Parameters ---------- event : instance of Event The event.
entailment
def viewbox_key_event(self, event): """ViewBox key event handler Parameters ---------- event : instance of Event The event. """ PerspectiveCamera.viewbox_key_event(self, event) if event.handled or not self.interactive: return # E...
ViewBox key event handler Parameters ---------- event : instance of Event The event.
entailment
def viewbox_mouse_event(self, event): """ViewBox mouse event handler Parameters ---------- event : instance of Event The event. """ PerspectiveCamera.viewbox_mouse_event(self, event) if event.handled or not self.interactive: return ...
ViewBox mouse event handler Parameters ---------- event : instance of Event The event.
entailment
def _stdin_ready_posix(): """Return True if there's something to read on stdin (posix version).""" infds, outfds, erfds = select.select([sys.stdin],[],[],0) return bool(infds)
Return True if there's something to read on stdin (posix version).
entailment
def set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one.""" # On platforms with 'readline' support, it's all too likely to # have a KeyboardInterrupt signal delivered *even before* an # initial ``try:`` clause in the callback can be executed, so ...
Set PyOS_InputHook to callback and return the previous one.
entailment
def clear_inputhook(self, app=None): """Set PyOS_InputHook to NULL and return the previous one. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` metho...
Set PyOS_InputHook to NULL and return the previous one. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` methods. But the actual value of the param...
entailment
def clear_app_refs(self, gui=None): """Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themsel...
Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themselves. This method is provided to clear ...
entailment
def register(self, toolkitname, *aliases): """Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass :class:`I...
Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass :class:`InputHookBase`. :: ...
entailment
def enable_gui(self, gui=None, app=None): """Switch amongst GUI input hooks by name. This is a higher level method than :meth:`set_inputhook` - it uses the GUI name to look up a registered object which enables the input hook for that GUI. Parameters ---------- g...
Switch amongst GUI input hooks by name. This is a higher level method than :meth:`set_inputhook` - it uses the GUI name to look up a registered object which enables the input hook for that GUI. Parameters ---------- gui : optional, string or None If None (or '...
entailment