INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Set the data
def set_data(self, pos=None, color=None): """Set the data Parameters ---------- pos : float Position of the line along the axis. color : list, tuple, or array The color to use when drawing the line. If an array is given, it must be of shape (1...
Return the ( min max ) bounding values of this visual along * axis * in the local coordinate system.
def _compute_bounds(self, axis, view): """Return the (min, max) bounding values of this visual along *axis* in the local coordinate system. """ is_vertical = self._is_vertical pos = self._pos if axis == 0 and is_vertical: return (pos[0, 0], pos[0, 0]) ...
Generate the vertices for a quadratic Bezier curve.
def curve3_bezier(p1, p2, p3): """ Generate the vertices for a quadratic Bezier curve. The vertices returned by this function can be passed to a LineVisual or ArrowVisual. Parameters ---------- p1 : array 2D coordinates of the start point p2 : array 2D coordinates of th...
Generate the vertices for a third order Bezier curve.
def curve4_bezier(p1, p2, p3, p4): """ Generate the vertices for a third order Bezier curve. The vertices returned by this function can be passed to a LineVisual or ArrowVisual. Parameters ---------- p1 : array 2D coordinates of the start point p2 : array 2D coordinates...
Render a SDF to a texture at a given offset and size
def render_to_texture(self, data, texture, offset, size): """Render a SDF to a texture at a given offset and size Parameters ---------- data : array Must be 2D with type np.ubyte. texture : instance of Texture2D The texture to render to. offset : ...
Render an EDF to a texture
def _render_edf(self, orig_tex): """Render an EDF to a texture""" # Set up the necessary textures sdf_size = orig_tex.shape[:2] comp_texs = [] for _ in range(2): tex = Texture2D(sdf_size + (4,), format='rgba', interpolation='nearest', wrap...
Interactively add a new intent to the intent schema object
def _add_intent_interactive(self, intent_num=0): ''' Interactively add a new intent to the intent schema object ''' print ("Name of intent number : ", intent_num) slot_type_mappings = load_builtin_slots() intent_name = read_from_user(str) print ("How many...
Build an IntentSchema from a file path creates a new intent schema if the file does not exist throws an error if the file exists but cannot be loaded as a JSON
def from_filename(self, filename): ''' Build an IntentSchema from a file path creates a new intent schema if the file does not exist, throws an error if the file exists but cannot be loaded as a JSON ''' if os.path.exists(filename): with open(filename) as fp:...
Annotate functions with
def launch_request_handler(request): """ Annotate functions with @VoiceHandler so that they can be automatically mapped to request types. Use the 'request_type' field to map them to non-intent requests """ user_id = request.access_token() if user_id in twitter_cache.users(): user_cache = twit...
Use the intent field in the VoiceHandler to map to the respective intent.
def post_tweet_intent_handler(request): """ Use the 'intent' field in the VoiceHandler to map to the respective intent. """ tweet = request.get_slot_value("Tweet") tweet = tweet if tweet else "" if tweet: user_state = twitter_cache.get_user_state(request.access_token()) def a...
This is a generic function to handle any intent that reads out a list of tweets
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""): """ This is a generic function to handle any intent that reads out a list of tweets""" # tweet_list_builder is a function that takes a unique identifier and returns a list of things to say tweets = tweet_list_builder(request.access_token()...
Return index if focused on tweet False if couldn t
def focused_on_tweet(request): """ Return index if focused on tweet False if couldn't """ slots = request.get_slot_map() if "Index" in slots and slots["Index"]: index = int(slots['Index']) elif "Ordinal" in slots and slots["Index"]: parse_ordinal = lambda inp : int("".join([l fo...
Takes care of things whenver the user says next
def next_intent_handler(request): """ Takes care of things whenver the user says 'next' """ message = "Sorry, couldn't find anything in your next queue" end_session = True if True: user_queue = twitter_cache.user_queue(request.access_token()) if not user_queue.is_finished(): ...
Get/ create the default Application object
def use_app(backend_name=None, call_reuse=True): """ Get/create the default Application object It is safe to call this function multiple times, as long as backend_name is None or matches the already selected backend. Parameters ---------- backend_name : str | None The name of the backe...
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...
Set the mesh data
def set_data(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=None, meshdata=None): """Set the mesh data Parameters ---------- vertices : array-like | None The vertices. faces : array-like | None The faces. ...
Get the bounds of the Visual
def bounds(self, axis, view=None): """Get the bounds of the Visual Parameters ---------- axis : int The axis. view : instance of VisualView The view to use. """ if view is None: view = self if axis not in self._vshare.b...
Define the set of GL state parameters to use when drawing
def set_gl_state(self, preset=None, **kwargs): """Define the set of GL state parameters to use when drawing Parameters ---------- preset : str Preset to use. **kwargs : dict Keyword arguments to `gloo.set_state`. """ self._vshare.gl_state ...
Modify the set of GL state parameters to use when drawing
def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. """ if len(args) == 1: self._vshare.gl_st...
Return a FunctionChain that Filters may use to modify the program.
def _get_hook(self, shader, name): """Return a FunctionChain that Filters may use to modify the program. *shader* should be "frag" or "vert" *name* should be "pre" or "post" """ assert name in ('pre', 'post') key = (shader, name) if key in self._hooks: ...
Attach a Filter to this visual
def attach(self, filt, view=None): """Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. ...
Detach a filter.
def detach(self, filt, view=None): """Detach a filter. Parameters ---------- filt : object The filter to detach. view : instance of VisualView | None The view to use. """ if view is None: self._vshare.filters.remove(filt) ...
Add a subvisual
def add_subvisual(self, visual): """Add a subvisual Parameters ---------- visual : instance of Visual The visual to add. """ visual.transforms = self.transforms visual._prepare_transforms(visual) self._subvisuals.append(visual) visual....
Remove a subvisual
def remove_subvisual(self, visual): """Remove a subvisual Parameters ---------- visual : instance of Visual The visual to remove. """ visual.events.update.disconnect(self._subv_update) self._subvisuals.remove(visual) self.update()
Draw the visual
def draw(self): """Draw the visual """ if not self.visible: return if self._prepare_draw(view=self) is False: return for v in self._subvisuals: if v.visible: v.draw()
Define the set of GL state parameters to use when drawing
def set_gl_state(self, preset=None, **kwargs): """Define the set of GL state parameters to use when drawing Parameters ---------- preset : str Preset to use. **kwargs : dict Keyword arguments to `gloo.set_state`. """ for v in self._subvisu...
Modify the set of GL state parameters to use when drawing
def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. """ for v in self._subvisuals: v.update_g...
Attach a Filter to this visual
def attach(self, filt, view=None): """Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. ...
Detach a filter.
def detach(self, filt, view=None): """Detach a filter. Parameters ---------- filt : object The filter to detach. view : instance of VisualView | None The view to use. """ for v in self._subvisuals: v.detach(filt, v)
main function for placing movements stop_limit = { gain: [ mode value ] loss: [ mode value ] }
def addMov(self, product, quantity=None, mode="buy", stop_limit=None, auto_margin=None, name_counter=None): """main function for placing movements stop_limit = {'gain': [mode, value], 'loss': [mode, value]}""" # ~ ARGS ~ if (not isinstance(product, type('')) or ...
check all positions
def checkPos(self): """check all positions""" soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser') poss = [] for label in soup.find_all("tr"): pos_id = label['id'] # init an empty list # check if it already exist pos_list...
check stocks in preference
def checkStock(self): """check stocks in preference""" if not self.preferences: logger.debug("no preferences") return None soup = BeautifulSoup( self.xpath(path['stock-table'])[0].html, "html.parser") count = 0 # iterate through product in left...
clear the left panel and preferences
def clearPrefs(self): """clear the left panel and preferences""" self.preferences.clear() tradebox_num = len(self.css('div.tradebox')) for i in range(tradebox_num): self.xpath(path['trade-box'])[0].right_click() self.css1('div.item-trade-contextmenu-list-remove')....
add preference in self. preferences
def addPrefs(self, prefs=[]): """add preference in self.preferences""" if len(prefs) == len(self.preferences) == 0: logger.debug("no preferences") return None self.preferences.extend(prefs) self.css1(path['search-btn']).click() count = 0 for pref i...
Load glyph from font into dict
def _load_glyph(f, char, glyphs_dict): """Load glyph from font into dict""" from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING, FT_LOAD_NO_AUTOHINT) flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT face = _load_font(f['face'], f['bold'], f['...
Assign a clipper that is inherited from a parent node.
def _set_clipper(self, node, clipper): """Assign a clipper that is inherited from a parent node. If *clipper* is None, then remove any clippers for *node*. """ if node in self._clippers: self.detach(self._clippers.pop(node)) if clipper is not None: self.a...
Transform object ( s ) have changed for this Node ; assign these to the visual s TransformSystem.
def _update_trsys(self, event): """Transform object(s) have changed for this Node; assign these to the visual's TransformSystem. """ doc = self.document_node scene = self.scene_node root = self.root_node self.transforms.visual_transform = self.node_transform(scene...
Convert CFNumber to python int or float.
def cfnumber_to_number(cfnumber): """Convert CFNumber to python int or float.""" numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, kCFNumberSInt64Type: c_int64, ...
Convert a CFType into an equivalent python type. The convertible CFTypes are taken from the known_cftypes dictionary which may be added to if another library implements its own conversion methods.
def cftype_to_value(cftype): """Convert a CFType into an equivalent python type. The convertible CFTypes are taken from the known_cftypes dictionary, which may be added to if another library implements its own conversion methods.""" if not cftype: return None typeID = cf.CFGetTypeID(cfty...
Convert CFSet to python set.
def cfset_to_set(cfset): """Convert CFSet to python set.""" count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
Convert CFArray to python list.
def cfarray_to_list(cfarray): """Convert CFArray to python list.""" count = cf.CFArrayGetCount(cfarray) return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i))) for i in range(count)]
Return ctypes type for an encoded Objective - C type.
def ctype_for_encoding(self, encoding): """Return ctypes type for an encoded Objective-C type.""" if encoding in self.typecodes: return self.typecodes[encoding] elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes: return POINTER(self.typecodes[encoding[1:]]) ...
Function decorator for class methods.
def classmethod(self, encoding): """Function decorator for class methods.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) d...
Append a new set of segments to the collection.
def append(self, P0, P1, itemsize=None, **kwargs): """ Append a new set of segments to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices positions of t...
Get the fragment shader code - we use the shader_program object to determine which layers are enabled and therefore what to include in the shader code.
def get_frag_shader(volumes, clipped=False, n_volume_max=5): """ Get the fragment shader code - we use the shader_program object to determine which layers are enabled and therefore what to include in the shader code. """ declarations = "" before_loop = "" in_loop = "" after_loop = "" ...
Connect to the EGL display server.
def eglGetDisplay(display=EGL_DEFAULT_DISPLAY): """ Connect to the EGL display server. """ res = _lib.eglGetDisplay(display) if not res or res == EGL_NO_DISPLAY: raise RuntimeError('Could not create display') return res
Initialize EGL and return EGL version tuple.
def eglInitialize(display): """ Initialize EGL and return EGL version tuple. """ majorVersion = (_c_int*1)() minorVersion = (_c_int*1)() res = _lib.eglInitialize(display, majorVersion, minorVersion) if res == EGL_FALSE: raise RuntimeError('Could not initialize') return majorVersion[0...
Query string from display
def eglQueryString(display, name): """ Query string from display """ out = _lib.eglQueryString(display, name) if not out: raise RuntimeError('Could not query %s' % name) return out
Edges of the mesh Parameters ---------- indexed: str | None If indexed is None return ( Nf 3 ) array of vertex indices two per edge in the mesh. If indexed is faces then return ( Nf 3 2 ) array of vertex indices with 3 edges per face and two vertices per edge.
def get_edges(self, indexed=None): """Edges of the mesh Parameters ---------- indexed : str | None If indexed is None, return (Nf, 3) array of vertex indices, two per edge in the mesh. If indexed is 'faces', then return (Nf, 3, 2) array of vertex...
Set the faces
def set_faces(self, faces): """Set the faces Parameters ---------- faces : ndarray (Nf, 3) array of faces. Each row in the array contains three indices into the vertex array, specifying the three corners of a triangular face. """ self....
Get the vertices
def get_vertices(self, indexed=None): """Get the vertices Parameters ---------- indexed : str | None If Note, return an array (N,3) of the positions of vertices in the mesh. By default, each unique vertex appears only once. If indexed is 'faces', then...
Get the mesh bounds
def get_bounds(self): """Get the mesh bounds Returns ------- bounds : list A list of tuples of mesh bounds. """ if self._vertices_indexed_by_faces is not None: v = self._vertices_indexed_by_faces elif self._vertices is not None: ...
Set the mesh vertices
def set_vertices(self, verts=None, indexed=None, reset_normals=True): """Set the mesh vertices Parameters ---------- verts : ndarray | None The array (Nv, 3) of vertex coordinates. indexed : str | None If indexed=='faces', then the data must have shape (N...
Return True if this data set has vertex color information
def has_vertex_color(self): """Return True if this data set has vertex color information""" for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces, self._vertex_colors_indexed_by_edges): if v is not None: return True return False
Return True if this data set has face color information
def has_face_color(self): """Return True if this data set has face color information""" for v in (self._face_colors, self._face_colors_indexed_by_faces, self._face_colors_indexed_by_edges): if v is not None: return True return False
Get face normals
def get_face_normals(self, indexed=None): """Get face normals Parameters ---------- indexed : str | None If None, return an array (Nf, 3) of normal vectors for each face. If 'faces', then instead return an indexed array (Nf, 3, 3) (this is just the sa...
Get vertex normals
def get_vertex_normals(self, indexed=None): """Get vertex normals Parameters ---------- indexed : str | None If None, return an (N, 3) array of normal vectors with one entry per unique vertex in the mesh. If indexed is 'faces', then the array will con...
Get vertex colors
def get_vertex_colors(self, indexed=None): """Get vertex colors Parameters ---------- indexed : str | None If None, return an array (Nv, 4) of vertex colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4). Returns ...
Set the vertex color array
def set_vertex_colors(self, colors, indexed=None): """Set the vertex color array Parameters ---------- colors : array Array of colors. Must have shape (Nv, 4) (indexing by vertex) or shape (Nf, 3, 4) (vertices indexed by face). indexed : str | None ...
Get the face colors
def get_face_colors(self, indexed=None): """Get the face colors Parameters ---------- indexed : str | None If indexed is None, return (Nf, 4) array of face colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4) (note this is jus...
Set the face color array
def set_face_colors(self, colors, indexed=None): """Set the face color array Parameters ---------- colors : array Array of colors. Must have shape (Nf, 4) (indexed by face), or shape (Nf, 3, 4) (face colors indexed by faces). indexed : str | None ...
The number of faces in the mesh
def n_faces(self): """The number of faces in the mesh""" if self._faces is not None: return self._faces.shape[0] elif self._vertices_indexed_by_faces is not None: return self._vertices_indexed_by_faces.shape[0]
List mapping each vertex index to a list of face indices that use it.
def get_vertex_faces(self): """ List mapping each vertex index to a list of face indices that use it. """ if self._vertex_faces is None: self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))] for i in xrange(self._faces.shape[0]): face...
Serialize this mesh to a string appropriate for disk storage
def save(self): """Serialize this mesh to a string appropriate for disk storage Returns ------- state : dict The state. """ import pickle if self._faces is not None: names = ['_vertices', '_faces'] else: names = ['_vert...
Restore the state of a mesh previously saved using save ()
def restore(self, state): """Restore the state of a mesh previously saved using save() Parameters ---------- state : dict The previous state. """ import pickle state = pickle.loads(state) for k in state: if isinstance(state[k], lis...
A full implementation of Dave Green s cubehelix for Matplotlib. Based on the FORTRAN 77 code provided in D. A. Green 2011 BASI 39 289.
def cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256., minSat=1.2, maxSat=1.2, minLight=0., maxLight=1., **kwargs): """ A full implementation of Dave Green's "cubehelix" for Matplotlib. Based on the FORTRAN 77 code provided in D.A. Green, 2011, BASI, 39, 289. http://a...
Convert matplotlib color code to hex color code
def color_to_hex(color): """Convert matplotlib color code to hex color code""" if color is None or colorConverter.to_rgba(color)[3] == 0: return 'none' else: rgb = colorConverter.to_rgb(color) return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
Convert a many - to - one mapping to a one - to - one mapping
def _many_to_one(input_dict): """Convert a many-to-one mapping to a one-to-one mapping""" return dict((key, val) for keys, val in input_dict.items() for key in keys)
Get an SVG dash array for the given matplotlib linestyle
def get_dasharray(obj): """Get an SVG dash array for the given matplotlib linestyle Parameters ---------- obj : matplotlib object The matplotlib line or path object, which must have a get_linestyle() method which returns a valid matplotlib line code Returns ------- dasharra...
Construct the vertices and SVG codes for the path
def SVG_path(path, transform=None, simplify=False): """Construct the vertices and SVG codes for the path Parameters ---------- path : matplotlib.Path object transform : matplotlib transform (optional) if specified, the path will be transformed before computing the output. Returns ...
Get the style dictionary for matplotlib path objects
def get_path_style(path, fill=True): """Get the style dictionary for matplotlib path objects""" style = {} style['alpha'] = path.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['edgecolor'] = color_to_hex(path.get_edgecolor()) if fill: style['facecolor'] = color_t...
Get the style dictionary for matplotlib line objects
def get_line_style(line): """Get the style dictionary for matplotlib line objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['color'] = color_to_hex(line.get_color()) style['linewidth'] = line.get_linewidth() style['dasharray']...
Get the style dictionary for matplotlib marker objects
def get_marker_style(line): """Get the style dictionary for matplotlib marker objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['facecolor'] = color_to_hex(line.get_markerfacecolor()) style['edgecolor'] = color_to_hex(line.get_ma...
Return the text style dict for a text instance
def get_text_style(text): """Return the text style dict for a text instance""" style = {} style['alpha'] = text.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['fontsize'] = text.get_size() style['color'] = color_to_hex(text.get_color()) style['halign'] = text.get_hor...
Return the property dictionary for a matplotlib. Axis instance
def get_axis_properties(axis): """Return the property dictionary for a matplotlib.Axis instance""" props = {} label1On = axis._major_tick_kw.get('label1On', True) if isinstance(axis, matplotlib.axis.XAxis): if label1On: props['position'] = "bottom" else: props['p...
Returns an iterator over all childen and nested children using obj s get_children () method
def iter_all_children(obj, skipContainers=False): """ Returns an iterator over all childen and nested children using obj's get_children() method if skipContainers is true, only childless objects are returned. """ if hasattr(obj, 'get_children') and len(obj.get_children()) > 0: for child...
Convert a matplotlib image to a base64 png representation
def image_to_base64(image): """ Convert a matplotlib image to a base64 png representation Parameters ---------- image : matplotlib image object The image to be converted. Returns ------- image_base64 : string The UTF8-encoded base64 string representation of the png imag...
Activate the IPython hook for VisPy. If the app is not specified the default is used.
def set_interactive(enabled=True, app=None): """Activate the IPython hook for VisPy. If the app is not specified, the default is used. """ if enabled: inputhook_manager.enable_gui('vispy', app) else: inputhook_manager.disable_gui()
Resize buffers only if necessary
def _resize_buffers(self, font_scale): """Resize buffers only if necessary""" new_sizes = (font_scale,) + self.size if new_sizes == self._current_sizes: # don't need resize return self._n_rows = int(max(self.size[1] / (self._char_height * font_...
Clear the console
def clear(self): """Clear the console""" if hasattr(self, '_bytes_012'): self._bytes_012.fill(0) self._bytes_345.fill(0) self._text_lines = [] * self._n_rows self._pending_writes = []
Write text and scroll
def write(self, text='', wrap=True): """Write text and scroll Parameters ---------- text : str Text to write. ``''`` can be used for a blank line, as a newline is automatically added to the end of each line. wrap : str If True, long messages w...
Do any pending text writes
def _do_pending_writes(self): """Do any pending text writes""" for text, wrap in self._pending_writes: # truncate in case of *really* long messages text = text[-self._n_cols*self._n_rows:] text = text.split('\n') text = [t if len(t) > 0 else '' for t in te...
Insert text into bytes buffers
def _insert_text_buf(self, line, idx): """Insert text into bytes buffers""" self._bytes_012[idx] = 0 self._bytes_345[idx] = 0 # Crop text if necessary I = np.array([ord(c) - 32 for c in line[:self._n_cols]]) I = np.clip(I, 0, len(__font_6x8__)-1) if len(I) > 0: ...
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 replace str1 with
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 ...
find all template variables in self. _code excluding the function name.
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: contin...
Return code with new name expressions and replacements applied.
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 ...
Return * code * with indentation and leading/ trailing blank lines removed.
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()) ...
Create a new ChainFunction and attach to $var.
def add_chain(self, var): """ Create a new ChainFunction and attach to $var. """ chain = FunctionChain(var, []) self._chains[var] = chain self[var] = chain
Append a new function to the end of this 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()
Insert a new function into the chain at * index *.
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()
Remove a function from the chain.
def remove(self, function, update=True): """ Remove a function from the chain. """ self._funcs.remove(function) self._remove_dep(function) if update: self._update()
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.
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 ...
Remove an item from the list.
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)
Return an array ( Nf 3 ) of vertex indexes three per triangular face in the mesh.
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 ...
Return an array ( Nf 3 ) of vertices.
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 an array of vertex indexes representing the convex hull.
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: ...
Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull.
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...
Locate a filename into the shader library.
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): re...
Retrieve code from the given filename.
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()
try many times as in times with sleep time
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) ...