code
stringlengths
1
18.2k
def replace(self, str1, str2): """ Set verbatim code replacement It is strongly recommended to use function['$foo'] = 'bar' where possible because template variables are less likely to changed than the code itself in future versions of vispy. Parameters ---------- str1 : str String to replace str2 : str String to repla...
def _parse_template_vars(self): """ find all template variables in self._code, excluding the function name. """ template_vars = set() for var in parsing.find_template_variables(self._code): var = var.lstrip('$') if var == self.name: continue if var in ('pre', 'post'): raise ValueError('GLSL uses reserved template varia...
def _get_replaced_code(self, names): """ Return code, with new name, expressions, and replacements applied. """ code = self._code # Modify name fname = names[self] code = code.replace(" " + self.name + "(", " " + fname + "(") # Apply string replacements first -- these may contain $placeholders for key, val in self._rep...
function # Collect post lines post_lines = [] for key, val in self._assignments.items(): if isinstance(key, Variable): key = names[key] if isinstance(val, ShaderObject): val = val.expression(names) line = ' %s = %s;' % (key, val) post_lines.append(line) # Add a default $post placeholder if needed if 'post' in self._exp...
+ '\n' code = code.rpartition('}') code = code[0] + post_text + code[1] + code[2] # Add a default $pre placeholder if needed if 'pre' in self._expressions: m = re.search(fname + r'\s*\([^{]*\)\s*{', code) if m is None: raise RuntimeError("Cound not find beginning of function '%s'" % fname) ind = m.span()[1] code = code...
in self._expressions.items(): val = val.expression(names) search = r'\$' + key + r'($|[^a-zA-Z0-9_])' code = re.sub(search, val+r'\1', code) # Done if '$' in code: v = parsing.find_template_variables(code) logger.warning('Unsubstituted placeholders in code: %s\n' ' replacements made: %s', v, list(self._expressions.keys...
def _clean_code(self, code): """ Return *code* with indentation and leading/trailing blank lines removed. """ lines = code.split("\n") min_indent = 100 for line in lines: if line.strip() != "": indent = len(line) - len(line.lstrip()) min_indent = min(indent, min_indent) if min_indent > 0: lines = [line[min_indent:] for...
def add_chain(self, var): """ Create a new ChainFunction and attach to $var. """ chain = FunctionChain(var, []) self._chains[var] = chain self[var] = chain
def append(self, function, update=True): """ Append a new function to the end of this chain. """ self._funcs.append(function) self._add_dep(function) if update: self._update()
def insert(self, index, function, update=True): """ Insert a new function into the chain at *index*. """ self._funcs.insert(index, function) self._add_dep(function) if update: self._update()
def remove(self, function, update=True): """ Remove a function from the chain. """ self._funcs.remove(function) self._remove_dep(function) if update: self._update()
def add(self, item, position=5): """Add an item to the list unless it is already present. If the item is an expression, then a semicolon will be appended to it in the final compiled code. """ if item in self.items: return self.items[item] = position self._add_dep(item) self.order = None self.changed(code_changed=True)
def remove(self, item): """Remove an item from the list. """ self.items.pop(item) self._remove_dep(item) self.order = None self.changed(code_changed=True)
def faces(self): """Return an array (Nf, 3) of vertex indexes, three per triangular face in the mesh. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.trian...
def vertices(self): """Return an array (Nf, 3) of vertices. If only faces exist, the function computes the vertices and returns them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.triangulate() return self._vertices
def convex_hull(self): """Return an array of vertex indexes representing the convex hull. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. """ if self._faces is None: if self._vertices is None: return None self.triangulate() ret...
def triangulate(self): """ Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull. """ npts = self._vertices.shape[0] if np.any(self._vertices[0] != self._vertices[1]): # start != end, so edges must wrap around to beginning. edges = np.empty((npts, 2), dtype=np.uint32) edg...
no wrapping required. edges = np.empty((npts-1, 2), dtype=np.uint32) edges[:, 0] = np.arange(npts) edges[:, 1] = edges[:, 0] + 1 tri = Triangulation(self._vertices, edges) tri.triangulate() return tri.pts, tri.tris
def find(name): """Locate a filename into the shader library.""" if op.exists(name): return name path = op.dirname(__file__) or '.' paths = [path] + config['include_path'] for path in paths: filename = op.abspath(op.join(path, name)) if op.exists(filename): return filename for d in os.listdir(path): fullpath = op.abspa...
def get(name): """Retrieve code from the given filename.""" filename = find(name) if filename is None: raise RuntimeError('Could not find %s' % name) with open(filename) as fid: return fid.read()
def expect(func, args, times=7, sleep_t=0.5): """try many times as in times with sleep time""" while times > 0: try: return func(*args) except Exception as e: times -= 1 logger.debug("expect failed - attempts left: %d" % times) time.sleep(sleep_t) if times == 0: raise exceptions.BaseExc(e)
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: logger = logging.getLogger('tradingAPI.utils.num') l...
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)
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 ValueError() if api is not None: if name is None: logg...
mov is not None: mov._check_open() # find in the collection try: logger.debug(len(Glob().theCollector.collection)) pip = Glob().theCollector.collection['pip'] if name is not None: pip_res = pip[name] elif mov is not None: pip_res = pip[mov.product] logger.debug("pip found in the collection") return pip_res except KeyEr...
while time.time() < timeout: records.append(mov.get_price()) time.sleep(0.5) # find variation for interval in intervals: _check_price(interval) if min(records) == max(records): logger.debug("no variation in %d seconds" % interval) if interval == intervals[-1]: raise TimeoutError("no variation") else: break # find longe...
get pip pip = get_number_unit(best_price) Glob().pipHandler.add_val({mov.product: pip}) return pip
def itemsize(self): """ Individual item sizes """ return self._items[:self._count, 1] - self._items[:self._count, 0]
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)
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 __array__ method returns an array, or any (nested) sequence. itemsize: int or 1-D ar...
size N. If such partition is not possible, an error is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. """ if not self._sizeable: raise AttributeError("List is ...
# noqa itemsize = [len(l) for l in data] data = [item for sublist in data for item in sublist] data = np.array(data, copy=False).ravel() size = data.size # Check item size and get item number if itemsize is not None: if isinstance(itemsize, int): if (size % itemsize) != 0: raise ValueError("Cannot partition data as req...
* (size // _count) else: _itemsize = np.array(itemsize, copy=False) _count = len(itemsize) if _itemsize.sum() != size: raise ValueError("Cannot partition data as requested") else: _count = 1 # Check if data array is big enough and resize it if necessary if self._size + size >= self._data.size: capacity = int(2 ** np.ce...
and resize it if necessary if self._count + _count >= len(self._items): capacity = int(2 ** np.ceil(np.log2(self._count + _count))) self._items = np.resize(self._items, (capacity, 2)) # Check index if index < 0: index += len(self) if index < 0 or index > len(self): raise IndexError("List insertion index out of range") ...
Move data Z = self._data[dstart:self._size] self._data[dstart + size:self._size + size] = Z # Update moved items I = self._items[istart:self._count] + size self._items[istart + _count:self._count + _count] = I # Appending else: dstart = self._size istart = self._count # Only one item (faster) if _count == 1: # Store da...
= dstart self._items[istart][1] = dstart + size self._count += 1 # Several items else: # Store data dstop = dstart + size self._data[dstart:dstop] = data self._size += size # Store items items = np.ones((_count, 2), int) * dstart C = _itemsize.cumsum() items[1:, 0] += C[:-1] items[0:, 1] += C istop = istart + _count se...
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: int or 1-D array If `itemsize is an integer, N, the array will be divided i...
is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. """ self.insert(len(self), data, itemsize)
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 ): """ Solve an optimization problem using the DIRECT (Dividing Rectangles) algorithm. It can be used to solve general nonlinear programming pro...
and lower bounds), :math:`f(x)` is the objective function. Parameters ---------- func : objective function called as `func(x, *args)`; does not need to be defined everywhere, raise an Exception where function is not defined bounds : array-like ``(min, max)`` pairs for each element in ``x``, defining the bounds on that ...
float Ensures sufficient decrease in function value when a new potentially optimal interval is chosen. maxf : integer Approximate upper bound on objective function evaluations. .. note:: Maximal allowed value is 90000 see documentation of Fortran library. maxT : integer Maximum number of iterations. .. note:: Maximal a...
or modified DIRECT algorithm. Possible values: * ``algmethod=0`` - use the original DIRECT algorithm * ``algmethod=1`` - use the modified DIRECT-l algorithm fglobal : float Function value of the global optimum. If this value is not known set this to a very large negative value. fglper : float Terminate the optimization...
volper : float Terminate the optimization once the volume of a hyperrectangle is less than volper percent of the original hyperrectangel. sigmaper : float Terminate the optimization once the measure of the hyperrectangle is less than sigmaper. Returns ------- res : OptimizeResult The optimization result represented as ...
optimizer exited successfully and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. """ if bounds is None: l = np.zeros(nvar, dtype=np.float64) u = np.ones(nvar, dtype=np.float64) else: bounds = np.asarray(bounds) l = bounds[:, 0] u = bounds[:, 1] def ...
required by the Fortran library. Returns the function value and a flag indicating whether function is defined. If function is not defined return np.nan """ try: return func(x, *args), 0 except: return np.nan, 1 # # Dummy values so that the python wrapper will comply with the required # signature of the fortran library....
= np.ones([0, 40], dtype=np.uint8) # # Call the DIRECT algorithm # x, fun, ierror = direct( _objective_wrap, eps, maxf, maxT, l, u, algmethod, 'dummylogfile', fglobal, fglper, volper, sigmaper, iidata, ddata, cdata, disp ) return OptimizeResult(x=x,fun=fun, status=ierror, success=ierror>0, message=SUCCESS_MESSAGES[ierr...
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() except AttributeError: pass # not present on XP dc = user32....
gdi32.GetDeviceCaps(dc, VERTRES) user32.ReleaseDC(None, dc) return (h_res/float(h_size) + v_res/float(v_size)) * 0.5 * 25.4
def build_if_needed(self): """ Reset shader source if necesssary. """ if self._need_build: self._build() self._need_build = False self.update_variables()
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: curvefn = lambda x: x def map(n): r...
/ (b - a) out = curvefn(r) * (d - c) + c if not normfn: return out return normfn(out) return map
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._linked_view: return if self._linked_view is not None: self._linked_view.scene.tran...
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: self.axis.domain = (p1[0], p2[0])
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_pos = event.pos[:2] if event.type == 'mouse_wheel': # wheel rolled; adjust the magnifi...
event.delta[1] m = m if m > 1 else 1 self.mag_target = m else: # send everything _except_ wheel events to the superclass super(MagnifyCamera, self).viewbox_mouse_event(event) # start the timer to smoothly modify the transform properties. if not self.timer.running: self.timer.start() self._update_transform()
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**(-k * event.dt) c = np.array(self.mag.center) c1 = c * s + self.mouse_pos *...
very small, then it is safe to stop the timer. if (np.all(np.abs((c - c1) / c1) < 1e-5) and (np.abs(np.log(m / self.mag.mag)) < 1e-3)): self.timer.stop() self.mag.center = c1 self.mag.mag = m self._update_transform()
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 try...
nativefunc(target, size, data, usage)
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)
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 indices : numpy array An array whose dtype is compatible with self.idtype ...
N, the array will be divided into elements of size N. If such partition is not possible, an error is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. """ # Verti...
vsize = self._vertices_list.size # No itemsize given # ----------------- if itemsize is None: index = 0 count = 1 # Uniform itemsize (int) # ---------------------- elif isinstance(itemsize, int): count = len(vertices) / itemsize index = np.repeat(np.arange(count), itemsize) # Individual itemsize (array) # -------------...
+ len(self) self._vertices_list.append(vertices, itemsize) # Indices # ----------------------------- if self.itype is not None: # No indices given (-> automatic generation) if indices is None: indices = vsize + np.arange(len(vertices)) self._indices_list.append(indices, itemsize) # Indices given # FIXME: variables indi...
* np.repeat(np.arange(count), len(indices))) # noqa else: raise ValueError("Indices not compatible with items") self._indices_list.append(I, len(indices)) # Uniforms # ----------------------------- if self.utype: if uniforms is None: uniforms = np.zeros(count, dtype=self.utype) else: uniforms = np.array(uniforms).astyp...
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 // int(count) rows = max(1, int(math.ceil(size / floa...
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: self._indices_buffer.delete() self._indices_buffer = IndexBuffer(...
self._compute_texture_shape(size) # shape[2] = float count is only used in vertex shader code texture = texture.reshape(shape[0], shape[1], 4) self._uniforms_texture = Texture2D(texture) self._uniforms_texture.data = texture self._uniforms_texture.interpolation = 'nearest' if len(self._programs): for program in self._p...
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 available layouts. *args Positional arguments wh...
callable generator which will calculate the graph layout """ if name not in _layout_map: raise KeyError("Graph layout '%s' not found. Should be one of %s" % (name, AVAILABLE_LAYOUTS)) layout = _layout_map[name] if inspect.isclass(layout): layout = layout(*args, **kwargs) return layout
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['state'] = {} rec['state']['values'] = rec.p...
for prop in sorted(properties, key=state.update_priority, reverse=True): value = layer.pop(prop) value = context.object(value) if isinstance(value, six.string_types) and value == 'fixed': value = 'Fixed' if isinstance(value, six.string_types) and value == 'linear': value = 'Linear' setattr(state, prop, value) context.r...
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.MULTILINE | re.DOTALL) def d...
None: return "" # so we will return empty to remove the comment else: # otherwise, we will return the 1st group return match.group(1) # captured quoted-string return regex.sub(do_replace, code)
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(filename) path = glsl.find(filename) if not path: ...
of "%s" ---\n' % filename return text return '' # Limit recursion to depth 10 for i in range(10): if re.search(regex, code): code = re.sub(regex, replace, code) else: break return code
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 Parameters ---------- widget : Widget | None The Widget to add. New...
int The row in which to add the widget (0 is the topmost row) col : int The column in which to add the widget (0 is the leftmost column) row_span : int The number of rows to be occupied by this widget. Default is 1. col_span : int The number of columns to be occupied by this widget. Default is 1. **kwargs :
dict parameters sent to the new Widget that is constructed if widget is None Notes ----- The widget's parent is automatically set to this grid, and all other parent(s) are removed. """ if row is None: row = self._next_cell[0] if col is None: col = self._next_cell[1] if widget is None: widget = Widget(**kwargs) else: if...
_row = self._cells.setdefault(row, {}) _row[col] = widget self._grid_widgets[self._n_added] = (row, col, row_span, col_span, widget) self._n_added += 1 widget.parent = self self._next_cell = [row, col+col_span] widget._var_w = Variable("w-(row: %s | col: %s)" % (row, col)) widget._var_h = Variable("h-(row: %s | col: %s...
want it to actually *take it up*, ratio wise. # otherwise, it will never *use* the extra rows and columns, # thereby collapsing the extras to 0. stretch = list(widget.stretch) stretch[0] = col_span if stretch[0] is None else stretch[0] stretch[1] = row_span if stretch[1] is None else stretch[1] widget.stretch = stretch...
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() if val[-1] != widget) self._need_solver_recreate = True
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 The number of columns to be occupied by this widget. """ row = None col = None...
if w == widget: row = r col = c break if row is None or col is None: raise ValueError("%s not found in grid" % widget) self.remove_widget(widget) self.add_widget(widget, row, col, row_span, col_span) self._need_solver_recreate = True
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 column in which to add the widget (0 is the leftmost column) row_span : int The number of ...
this widget. Default is 1. col_span : int The number of columns to be occupied by this widget. Default is 1. **kwargs : dict Keyword arguments to pass to the new `Grid`. """ from .grid import Grid grid = Grid(**kwargs) return self.add_widget(grid, row, col, row_span, col_span)
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 The column in which to add the widget (0 is the leftmost column) row_span : int The number ...
this widget. Default is 1. col_span : int The number of columns to be occupied by this widget. Default is 1. **kwargs : dict Keyword arguments to pass to `ViewBox`. """ from .viewbox import ViewBox view = ViewBox(**kwargs) return self.add_widget(view, row, col, row_span, col_span)
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_WEIGHT, bold) fontconfig.FcPatte...
FC_FAMILY, 0, byref(value)) if(value.u.s != face): warnings.warn('Could not find face match "%s", falling back to "%s"' % (face, value.u.s)) result = fontconfig.FcPatternGet(match, FC_FILE, 0, byref(value)) if result != 0: raise RuntimeError('No filename or FT face for "%s"' % face) fname = value.u.s return fname.decod...
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
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[0].f_lineno) func = record[3] cls = record[0...
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 these are for convenience and are equ...
same as 'WARNING'. match : str | None String to match. Only those messages that both contain a substring that regexp matches ``'match'`` (and the ``verbose`` level) will be displayed. return_old : bool If True, return the old verbosity level and old match. Notes ----- If ``verbose=='debug'``, then the ``vispy`` method ...
useful for debugging. If ``verbose=='debug'`` or ``match is not None``, then a small performance overhead is added. Thus it is suggested to only use these options when performance is not crucial. See also -------- vispy.util.use_log_level """ # This method is responsible for setting properties of the handler and # form...
log messages is only available # via the context handler (use_log_level), so that configuration is # done by the context handler itself. if isinstance(verbose, bool): verbose = 'info' if verbose else 'warning' if isinstance(verbose, string_types): verbose = verbose.lower() if verbose not in logging_types: raise ValueEr...
old_verbose = logger.level old_match = _lh._vispy_set_match(match) logger.setLevel(verbose) if verbose <= logging.DEBUG: _lf._vispy_set_prepend(True) else: _lf._vispy_set_prepend(False) out = None if return_old: out = (old_verbose, old_match) return out
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 exception was caught. Pa...
to ignore, prior to the point where the exception was caught. The default is 2. """ stack = "".join(traceback.format_stack()[:-tb_skip]) tb = traceback.format_exception(*sys.exc_info()) msg = tb[0] # "Traceback (most recent call last):" msg += stack msg += " << caught exception here: >>\n" msg += "".join(tb[1:]).rstrip...
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 = {} registry = obj._vispy_err_registry if cb_event ...