text
stringlengths
81
112k
This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy. def _compute_edges_cells(self): """This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy. ...
The centroids (barycenters) of all triangles. def cell_centroids(self): """The centroids (barycenters) of all triangles. """ if self._cell_centroids is None: self._cell_centroids = ( numpy.sum(self.node_coords[self.cells["nodes"]], axis=1) / 3.0 ) ...
Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by a node, an edge midpoint, and a circumcenter. def _compute_integral_x(self): """Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by...
For each edge, one half of the the edge goes to each of the end points. Used for Neumann boundary conditions if on the boundary of the mesh and transition conditions if in the interior. def _compute_surface_areas(self, cell_ids): """For each edge, one half of the the edge goes to each of the en...
Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; see <https://en.wikipedia.org/wiki/Curl_(mathema...
Show the mesh using matplotlib. def plot( self, show_coedges=True, show_centroids=True, mesh_color="k", nondelaunay_edge_color="#d62728", # mpl 2.0 default red boundary_edge_color=None, comesh_color=(0.8, 0.8, 0.8), show_axes=True, ): """Show...
Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional def show_vertex(self, node_id, show_ce_ratio=True): """Plot...
Updates all sorts of cell information for the given cell IDs. def _update_cell_values(self, cell_ids, interior_edge_ids): """Updates all sorts of cell information for the given cell IDs. """ # update idx_hierarchy nds = self.cells["nodes"][cell_ids].T self.idx_hierarchy[..., cel...
Writes a mesh to collada file format. def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
Generates a UTF-8 XML string containing the mesh, in collada format. def dumps(mesh): ''' Generates a UTF-8 XML string containing the mesh, in collada format. ''' from lxml import etree dae = mesh_to_collada(mesh) # Update the xmlnode. dae.save() return etree.tostring(dae.xmlnode, en...
Supports per-vertex color, but nothing else. def mesh_to_collada(mesh): ''' Supports per-vertex color, but nothing else. ''' import numpy as np try: from collada import Collada, scene except ImportError: raise ImportError("lace.serialization.dae.mesh_to_collade requires package ...
Convert the mesh from one set of units to another. These calls are equivalent: - mesh.convert_units(from_units='cm', to_units='m') - mesh.scale(.01) def convert_units(self, from_units, to_units): ''' Convert the mesh from one set of units to another. These calls are e...
There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned def predict_body_units(self): ''' There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned ''' longest_dist = np.max(np.max(self...
Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera). def reorient(self, up, look): ''' Reorient ...
Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z. When `preserve_centroid` is True, translate after flipping to preserve the location of the centroid. def flip(self, axis=0, preserve_centroid=False): ''' Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z. ...
Return the geometric center. def centroid(self): ''' Return the geometric center. ''' if self.v is None: raise ValueError('Mesh has no vertices; centroid is not defined') return np.mean(self.v, axis=0)
Return the point on the floor that lies below the centroid. def floor_point(self): ''' Return the point on the floor that lies below the centroid. ''' floor_point = self.centroid # y to floor floor_point[1] = self.v[:, 1].min() return floor_point
Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array. def apex(self, axis): ''' Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array. ''' from blmath.geomet...
Flatten the mesh to the plane, dropping the dimension identified by `squash_axis`: 0 for x, 1 for y, 2 for z. Cast a ray from `origin`, pointing along `initial_direction`. Sweep the ray, like a radar, until encountering the mesh, and return that vertex: like the first blip of the radar. ...
Cut the mesh by a plane, discarding vertices that lie behind that plane. Or cut the mesh by two parallel planes, discarding vertices that lie outside them. The region to keep is defined by an axis of perpendicularity, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` ...
Like cut_across_axis, except the subset of vertices is constrained by percentile of the data along a given axis instead of specific values. (See numpy.percentile.) For example, if the mesh has 50,000 vertices, `dim` is 2, and `minpct` is 10, this method drops the 5,000 vertices which ar...
Like cut_across_axis, but works with an arbitrary plane. Keeps vertices that lie in front of the plane (i.e. in the direction of the plane normal). inverted: When `True`, invert the logic, to keep the vertices that lie behind the plane instead. Return the original indices of ...
returns the surface area of each face def surface_areas(self): ''' returns the surface area of each face ''' e_1 = self.v[self.f[:, 1]] - self.v[self.f[:, 0]] e_2 = self.v[self.f[:, 2]] - self.v[self.f[:, 0]] cross_products = np.array([e_1[:, 1]*e_2[:, 2] - e_1[:, 2]*e_...
Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event. def purge_items(app, env, docname): """ Clean, if existing, ``item`` entries in ``traceability_all_items`` ...
This function should be triggered upon ``doctree-resolved event`` Replace all item_list nodes with a list of the collected items. Augment each item with a backlink to the original location. def process_item_nodes(app, doctree, fromdocname): """ This function should be triggered upon ``doctree-resolved...
Update directive option_spec with custom relationships defined in configuration file ``traceability_relationships`` variable. Both keys (relationships) and values (reverse relationships) are added. This handler should be called upon builder initialization, before processing any directive. Functio...
Perform initializations needed before the build process starts. def initialize_environment(app): """ Perform initializations needed before the build process starts. """ env = app.builder.env # Assure ``traceability_all_items`` will always be there. if not hasattr(env, 'traceability_all_items')...
Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. def make_item_ref(app, env, fromdocname, item_info): """ Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. """ id = item...
Natural sort order def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
Returns ``True`` if ``source`` and ``target`` items are related according a list, ``relationships``, of relationship types. ``False`` is returned otherwise If the list of relationship types is empty, all available relationship types are to be considered. def are_related(env, source, target, relationsh...
Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string printed in the window titlebar dynamic_meshes: list of Mesh objects to be displayed static_meshes: list of Mesh objects to be displayed dynamic_lines: list of Lines objects to be displayed ...
Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns: a list of lists of MeshViewer objects: one per window requested. def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepa...
Mouse cursor is moving Glut calls this function (when mouse button is down) and pases the mouse cursor postion in window coords as the mouse moves. def on_drag(self, cursor_x, cursor_y): """ Mouse cursor is moving Glut calls this function (when mouse button is down) ...
Mouse button clicked. Glut calls this function when a mouse button is clicked or released. def on_click(self, button, button_state, cursor_x, cursor_y): """ Mouse button clicked. Glut calls this function when a mouse button is clicked or released. """ ...
Computes the center of the circumsphere of each cell. def _compute_cell_circumcenters(self): """Computes the center of the circumsphere of each cell. """ # Just like for triangular cells, tetrahedron circumcenters are most easily # computed with the quadrilateral coordinates available. ...
Compute the control volumes of all nodes in the mesh. def control_volumes(self): """Compute the control volumes of all nodes in the mesh. """ if self._control_volumes is None: # 1/3. * (0.5 * edge_length) * covolume # = 1/6 * edge_length**2 * ce_ratio_edge_ratio ...
Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int def show_edge(self, edge_id): """Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int """ # pylint: disabl...
Try to extract an integer from a string, return the fallback if that's not possible. def parse_int(text, fallback=None): """ Try to extract an integer from a string, return the fallback if that's not possible. """ try: if isinstance(text, six.integer_types): return text elif...
Reflect a given table from the database. def _load_table(self, name): """ Reflect a given table from the database. """ table = self._tables.get(name, None) if table is not None: return table if not self.engine.has_table(name): raise BindingException('Table does n...
Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk. def fact_pk(self): """ Try to determine the primary key of the fact table for use in fact table counting. If more than one colu...
Main aggregation function. This is used to compute a given set of aggregates, grouped by a given set of drilldown dimensions (i.e. dividers). The query can also be filtered and sorted. def aggregate(self, aggregates=None, drilldowns=None, cuts=None, order=None, page=None, page_size=No...
List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned. def members(self, ref, cuts=None, order=None, page=None, page_size=None): """ List all the distinct members of the given reference, filtered and ...
List all facts in the cube, returning only the specified references if these are specified. def facts(self, fields=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """ List all facts in the cube, returning only the specified references if these are specified...
This will count the number of distinct values for each dimension in the dataset and add that count to the model so that it can be used as a hint by UI components. def compute_cardinalities(self): """ This will count the number of distinct values for each dimension in the dataset and add...
Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are referenced, this ensures their returned rows are conn...
Order sub-commands for display def order_manually(sub_commands): """Order sub-commands for display""" order = [ "start", "projects", ] ordered = [] commands = dict(zip([cmd for cmd in sub_commands], sub_commands)) for k in order: ordered.append(commands.get(k, "")) ...
Format the help string. def format_help(help): """Format the help string.""" help = help.replace('Options:', str(crayons.black('Options:', bold=True))) help = help.replace('Usage: pinax', str('Usage: {0}'.format(crayons.black('pinax', bold=True)))) help = help.replace(' start', str(crayons.green(' ...
This function expects a path to a file containing a **Detailed billing report with resources and tags** report from AWS. It returns a ``Costs`` object containing all of the lineitems from that detailed billing report def load(file): """ This function expects a path to a file containing a *...
Return all existing concepts, i.e. dimensions, measures and attributes within the model. def concepts(self): """ Return all existing concepts, i.e. dimensions, measures and attributes within the model. """ for measure in self.measures: yield measure for aggregate in ...
Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref...
obj: A dictionary mapping names to a 3-dimension array. mesh_filename: If provided, this value is included in the <DataFileName> attribute, which Meshlab doesn't seem to use. TODO Maybe reconstruct this using xml.etree def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argumen...
Sets landmarks given any of: - ppfile - ldmk file - dict of {name:inds} (i.e. mesh.landm) - dict of {name:xyz} (i.e. mesh.landm_xyz) - Nx1 array or list of ints (treated as landm, given sequential integers as names) - Nx3 array or list of floats (treated as landm_xy...
Add a line item record to this Costs object. def add(self, lineitem): """ Add a line item record to this Costs object. """ # Check for a ProductName in the lineitem. # If its not there, it is a subtotal line and including it # will throw the total cost calculation off. ...
Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the regular expression matches the value in th...
Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008 def que...
Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query m...
Executes a series of the same Insert Statments Each tuple in the args list will be applied to the query and executed. This is the equivilant of MySQLDB.cursor.executemany() @author: Nick Verbeck @since: 9/7/2008 def queryMany(self, query, args): """ Executes a series of the same Insert Statments ...
Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 ...
Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008 def _GetConnection(self): """ Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008 """ #Attempt to get a connection. If all connections are in use and we have reached the max numbe...
Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 def _ReturnConnection(self): """ Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 """ if self.conn is not None: if self.connInfo.commitOnEnd is True or self.commitOnEnd is True: self.co...
When one column needs to match, use the key. def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation functi...
Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being returned from the Travis API as PKCS8 encoded, th...
Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPublicKey. The encrypted password is t...
Dump the travis configuration settings to the travis.yml file. The configuration settings from the travis.yml will be dumped with ordering preserved. Thus, when a password is added to the travis.yml file, a diff will show that only the password was added. Parameters ---------- config: collecti...
Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiable. def load_texture(self, texture_version): ''' Expect a texture version number as an integer, load the texture ...
Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". def show_distribution_section(config, title, section_name): """ Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". """ payload = requests.get(...
Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible. def validate_django_compatible_with_python(): ...
Override for showing commands in particular order def list_commands(self, ctx): """Override for showing commands in particular order""" commands = super(PinaxGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
returns all of the faces that contain at least one of the vertices in v_indices def all_edges_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' included_vertices = np.zeros(self.v.shape[0], dtype=bool) ...
Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of the kept edges. Otherwise return `self` for chaining. def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' Keep ...
Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data. :returns point_data: Point data read from file. :type point_data: dict :returns field_data: Field data read from file. :type field_data: dict def r...
Lock connection from being used else where def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
Release the connection lock def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
Get a Dictionary Cursor for executing queries def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 def Connect(self): """ Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInf...
Being a Transaction @author: Nick Verbeck @since: 5/14/2011 def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
Commit MySQL Transaction to database. MySQLDB: If the database and the tables support transactions, this commits the current transaction; otherwise this method successfully does nothing. @author: Nick Verbeck @since: 5/12/2008 def commit(self): """ Commit MySQL Transaction to database. MySQLDB: If...
Rollback MySQL Transaction to database. MySQLDB: If the database and tables support transactions, this rolls back (cancels) the current transaction; otherwise a NotSupportedError is raised. @author: Nick Verbeck @since: 5/12/2008 def rollback(self): """ Rollback MySQL Transaction to database. MySQ...
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 def Close(self): """ Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is not None: try: self.connection.commit() self.connection.close() self.co...
Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data. def configure_api(app, manager): """ Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data. """ if not hasattr(app, 'extensions'): ...
Load the named cube from the current registered ``CubeManager``. def get_cube(name): """ Load the named cube from the current registered ``CubeManager``. """ manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
Custom JSONificaton to support obj.to_dict protocol. def jsonify(obj, status=200, headers=None): """ Custom JSONificaton to support obj.to_dict protocol. """ data = JSONEncoder().encode(obj) if 'callback' in request.args: cb = request.args.get('callback') data = '%s && %s(%s)' % (cb, cb, da...
Get a listing of all publicly available cubes. def cubes(): """ Get a listing of all publicly available cubes. """ cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
Perform an aggregation request. def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'...
List the fact table entries in the current cube. This is the full materialized dataset. def facts(name): """ List the fact table entries in the current cube. This is the full materialized dataset. """ cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), ...
List the members of a specific dimension or the distinct values of a given attribute. def members(name, ref): """ List the members of a specific dimension or the distinct values of a given attribute. """ cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), ...
Apply a set of grouping criteria and project them. def apply(self, q, bindings, drilldowns): """ Apply a set of grouping criteria and project them. """ info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(a...
Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ ...
Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions def check_valid_hierarchies(instance): """ Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions """ hierarchies = instance.get('hierarchies', {}...
Load the JSON Schema Draft 4 validator with the given name from the local schema directory. def load_validator(name): """ Load the JSON Schema Draft 4 validator with the given name from the local schema directory. """ with open(os.path.join(SCHEMA_PATH, name)) as fh: schema = json.load(fh) ...
Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. def get_cube(self, name): """ Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. """ return Cube(self.get_engine(), name, self.get_c...
List all available JSON files. def list_cubes(self): """ List all available JSON files. """ for file_name in os.listdir(self.directory): if '.' in file_name: name, ext = file_name.rsplit('.', 1) if ext.lower() == 'json': yield name
Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008 def Terminate(self): """ Close all open connections Loop though all the connections and ...
Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009 def Cleanup(self): """ Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @a...
Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: co...
Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnection Object representing your connection string @...
Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format). def main(): """ Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).""" import re with open('rgb.txt') as fp: line = fp.readline() while line: reg = re.ma...
Get statistics for a certain date. async def on_date(self, date: datetime.date) -> dict: """Get statistics for a certain date.""" return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
Return watering statistics for the next 6 days. async def upcoming(self, details: bool = False) -> list: """Return watering statistics for the next 6 days.""" endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' ...
Run. async def main(): """Run.""" async with ClientSession() as websession: try: client = Client(websession) await client.load_local('<IP ADDRESS>', '<PASSWORD>', websession) for controller in client.controllers.values(): print('CLIENT INFORMATION') ...