text
stringlengths
18
773k
def generate_results(cube, q): """ Generate the resulting records for this query, applying pagination. Values will be returned by their reference. """ if q._limit is not None and q._limit < 1: return rp = cube.engine.execute(q) while True: row = rp.fetchone() if row is None: ...
def apply(self, q, bindings, ordering, distinct=None): """ Sort on a set of field specifications of the type (ref, direction) in order of the submitted list. """ info = [] for (ref, direction) in self.parse(ordering): info.append((ref, direction)) table, column = ...
def copy(self, only=None): ''' Returns a deep copy with all of the numpy arrays copied If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied ''' if only is None: return Mesh(self) else: import copy m =...
def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. """ nargs = len(args) if nargs == 1: return args[0] vs = [a.v for a in args if a.v is not None] vcs = [a.vc for a in ar...
def getNewConnection(*args, **kargs): """ Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to connect on @param comm...
def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs): """ Create a new PySQLQuery Class @param PySQLConnectionObj: Connection Object representing your connection string @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit @author: N...
def cli(username, repository, path, password, deploy, env, clipboard, env_file): """Encrypt passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the pass...
def apply(self, q, bindings, fields, distinct=False): """ Define a set of fields to return for a non-aggregated query. """ info = [] group_by = None for field in self.parse(fields): for concept in self.cube.model.match(field): info.append(concept.ref) ...
def drag(self, NewPt): # //Mouse drag, calculate rotation (Point2fT Quat4fT) """ drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec """ X = 0 Y = 1 Z = 2 W = 3 self.m_EnVec = self._mapToSphere(NewPt) # //Compute the vector perpendicular t...
def create_cell_volumes(self): """Computes the volumes of the "cells" in the mesh. """ self.cell_volumes = numpy.array( [ abs( self.node_coords[cell["nodes"]][1] - self.node_coords[cell["nodes"]][0] ) ...
def create_control_volumes(self): """Compute the control volumes of all nodes in the mesh. """ self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float) for k, cell in enumerate(self.cells): node_ids = cell["nodes"] self.control_volumes[node_ids] += 0...
def create_rectangular_prism(origin, size): ''' Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array. ''' from lace.topology import quads_to_tris lower_base_plane = np.array([ # Lowe...
def create_triangular_prism(p1, p2, p3, height): ''' Return a Mesh which is a triangular prism whose base is the triangle p1, p2, p3. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. ''' from blmath.geometry import Plane base_plane = Plane.f...
def create_horizontal_plane(): ''' Creates a horizontal plane. ''' v = np.array([ [1., 0., 0.], [-1., 0., 0.], [0., 0., 1.], [0., 0., -1.] ]) f = [[0, 1, 2], [3, 1, 0]] return Mesh(v=v, f=f)
def match_ref(self, ref): """ Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label. """ if ref in self.refs: self._matched_ref = ref return True return False
def _physical_column(self, cube, column_name): """ Return the SQLAlchemy Column object matching a given, possibly qualified, column name (i.e.: 'table.column'). If no table is named, the fact table is assumed. """ table_name = self.model.fact_table_name if '.' in column_name: ...
def bind(self, cube): """ Map a model reference to an physical column in the database. """ table, column = self._physical_column(cube, self.column_name) column = column.label(self.matched_ref) column.quote = True return table, column
def add_new_source(self, source_token, stripe_js_response=None): """Add new source (for example: a new card) to the customer The new source will be automatically set as customer's default payment source. Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be u...
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True): """ Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if...
def save(self, force_retrieve=False, *args, **kwargs): """ Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe API or update the local object with data fetched from Stripe. """ stripe.api_key = stripe_settings.API_KEY ...
def get_signed_simplex_volumes(cells, pts): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1) return ...
def grp_start_len(a): """Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this routine returns the indices where the blocks of equal integers start and how long the blocks are. """ # https://stackoverflow.com/a/50394587/353337 m = numpy.concatenate([[True], a[:-1] != a[1:], [Tru...
def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej): """Computes the circumcenters of all given triangles. """ # The input argument are the dot products # # <e1, e2> # <e2, e0> # <e0, e1> # # of the edges # # e0: x1->x2, # e1: x2->x0, # e2: x0->x1....
def get_edge_mask(self, subdomain=None): """Get faces which are fully in subdomain. """ if subdomain is None: # https://stackoverflow.com/a/42392791/353337 return numpy.s_[:] if subdomain not in self.subdomains: self._mark_vertices(subdomain) ...
def get_face_mask(self, subdomain): """Get faces which are fully in subdomain. """ if subdomain is None: # https://stackoverflow.com/a/42392791/353337 return numpy.s_[:] if subdomain not in self.subdomains: self._mark_vertices(subdomain) # A ...
def _mark_vertices(self, subdomain): """Mark faces/edges which are fully in subdomain. """ if subdomain is None: is_inside = numpy.ones(len(self.node_coords), dtype=bool) else: is_inside = subdomain.is_inside(self.node_coords.T).T if subdomain.is_boun...
def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds): """Dump a yaml configuration as an OrderedDict.""" class OrderedDumper(Dumper): pass def dict_representer(dumper, data): return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) Or...
def _check_type(self, ref, value): """ Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if it doesn't match """ if isinstance(value, list): return [self._check_type(ref, val) for val in value] mod...
def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types): return 'integer' elif type(value) is datetime....
def apply(self, q, bindings, cuts): """ Apply a set of filters, which can be given as a set of tuples in the form (ref, operator, value), or as a string in query form. If it is ``None``, no filter will be applied. """ info = [] for (ref, operator, value) in self.parse(cuts): ...
def colors_like(color, arr, colormap=DEFAULT_COLORMAP): ''' Given an array of size NxM (usually Nx3), we accept color in the following ways: - A string color name. The accepted names are roughly what's in X11's rgb.txt - An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape - A list of values (N...
def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument ''' Color each vertex by its height above the floor point. axis: The axis to use. 0 means x, 1 means y, 2 means z. threshold: The top of the range. Points at and above this heigh...
def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP): ''' Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with known scale. ''' import numpy as np adjusted_weights = np.clip(weights, 0., max_weight) / max_w...
def quads_to_tris(quads): ''' Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array. ''' import numpy as np tris = np.empty((2 * len(quads), 3)) tris[0::2, :] = quads[:, [0, 1, 2]] tris[1::2, :] = quads[:, [0, 2, 3]] return tris
def all_faces_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' import numpy as np included_vertices = np.zeros(self.v.shape[0], dtype=bool) included_vertices[np.array(v_indices, dtype=np...
def vertex_indices_in_segments(self, segments, ret_face_indices=False): ''' Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns f...
def keep_segments(self, segments_to_keep, preserve_segmentation=True): ''' Keep the faces and vertices for given segments, discarding all others. When preserve_segmentation is false self.segm is discarded for speed. ''' v_ind, f_ind = self.vertex_indices_in_segments(segments_to_k...
def remove_segments(self, segments_to_remove): ''' Remove the faces and vertices for given segments, keeping all others. Args: segments_to_remove: a list of segnments whose vertices will be removed ''' v_ind = self.vertex_indices_in_segments(segments_to_remove) self....
def verts_in_common(self, segments): """ returns array of all vertex indices common to each segment in segments""" verts_by_segm = self.verts_by_segm return sorted(reduce(lambda s0, s1: s0.intersection(s1), [set(verts_by_segm[segm]) for segm in segments]))
def uniquified_mesh(self): """This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face, and hence has only one texture""" import numpy as np from lace.mesh import Mesh new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.arr...
def downsampled_mesh(self, step): """Returns a downsampled copy of this mesh. Args: step: the step size for the sampling Returns: a new, downsampled Mesh object. Raises: ValueError if this Mesh has faces. """ from lace.mesh import Me...
def keep_vertices(self, indices_to_keep, ret_kept_faces=False): ''' Keep the given vertices and discard the others, and any faces to which they may belong. If `ret_kept_faces` is `True`, return the original indices of the kept faces. Otherwise return `self` for chaining. ...
def create_from_mesh_and_lines(cls, mesh, lines): ''' Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or Lines objects. ''' mesh_with_lines = mesh.copy() mesh_with_lines.add_lines(lines) return mesh_with_l...
def add_lines(self, lines): ''' Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects. ''' import numpy as np if not lines: return v_lines = np.vstack([l.v for l in lines]) v_index_offset = np.cumsum([0] + [len(...
def vert_connectivity(self): """Returns a sparse matrix (of size #verts x #verts) where each nonzero element indicates a neighborhood relation. For example, if there is a nonzero element in position (15, 12), that means vertex 15 is connected by an edge to vertex 12.""" import nu...
def vert_opposites_per_edge(self): """Returns a dictionary from vertidx-pairs to opposites. For example, a key consist of [4, 5)] meaning the edge between vertices 4 and 5, and a value might be [10, 11] which are the indices of the vertices opposing this edge.""" result = {} ...
def faces_per_edge(self): """Returns an Ex2 array of adjacencies between faces, where each element in the array is a face index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np import scipy.sparse as sp from bl...
def vertices_per_edge(self): """Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np return np.asarray([vertices_in_co...
def get_vertices_to_edges_matrix(self, want_xyz=True): """Returns a matrix M, which if multiplied by vertices, gives back edges (so "e = M.dot(v)"). Note that this generates one edge per edge, *not* two edges per triangle. Args: want_xyz: if true, takes and returns xyz coord...
def remove_redundant_verts(self, eps=1e-10): """Given verts and faces, this remove colocated vertices""" import numpy as np from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module fshape = self.f.shape tree = cKDTree(self.v) close_pairs = list(tree.que...
def cardinality_class(self): """ Group the cardinality of the dimension into one of four buckets, from very small (less than 5) to very large (more than 1000). """ if self.cardinality: if self.cardinality > 1000: return 'high' if self.cardinality > 50: ...
def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name ''' write_mtl: When True and mesh has a texture, includes a mtllib reference in the .obj and writes a .mtl alongside. ''' import os import numpy as np...
def signed_cell_areas(self): """Signed area of a triangle in 2D. """ # http://mathworld.wolfram.com/TriangleArea.html assert ( self.node_coords.shape[1] == 2 ), "Signed areas only make sense for triangles in 2D." if self._signed_cell_areas is None: ...
def create_edges(self): """Set up edge-node and edge-cell relations. """ # Reshape into individual edges. # Sort the columns to make it possible for `unique()` to identify # individual edges. s = self.idx_hierarchy.shape a = numpy.sort(self.idx_hierarchy.reshape(s...
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. """ if self.edges is None: self.create_edges() num_edges = len(self.edges["nodes"]) counts = nump...
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 ) return self._cell_centroids
def _compute_integral_x(self): """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. """ # The integral of any linear function over a triangle is the average of # the values...
def _compute_surface_areas(self, cell_ids): """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. """ # Each of the three edges may contribute to...
def compute_curl(self, vector_field): """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; ...
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 the mesh using matplotlib. ...
def show_vertex(self, node_id, show_ce_ratio=True): """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 _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[..., cell_ids] = nds[self.local_idx] # update self.half_edge_c...
def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
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, encoding='UTF-8')
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 pycollada.") def create_material(dae): ...
def convert_units(self, from_units, to_units): ''' 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) ''' from blmath import units factor = units.factor( ...
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.v, axis=0) - np.min(self.v, axis=0)) if round(longest_dist / 1000) > 0: return 'mm' ...
def reorient(self, up, look): ''' 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 flip(self, axis=0, preserve_centroid=False): ''' 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. ''' self.v[:, axis] *= -1 if preserve_centr...
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)
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
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.geometry.apex import apex return apex(self.v, axis)
def first_blip(self, squash_axis, origin, initial_direction): ''' 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 encount...
def cut_across_axis(self, dim, minval=None, maxval=None): ''' 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,...
def cut_across_axis_by_percentile(self, dim, minpct=0, maxpct=100): ''' 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 vertice...
def cut_by_plane(self, plane, inverted=False): ''' 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...
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_2[:, 1], ...
def purge_items(app, env, docname): """ 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. """ keys = list(env.traceability_all_items.keys()) for key ...
def process_item_nodes(app, doctree, fromdocname): """ 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. """ env = app.builder.env all_items = sorted...
def update_available_item_relationships(app): """ 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 initial...
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'): env.traceability_all_items = {} update_available_i...
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_info['target']['refid'] if item_info['caption'] != '': caption = ', ' + item_info['caption'] else: ...
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
def are_related(env, source, target, relationships): """ 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 t...
def MeshViewer( titlebar='Mesh Viewer', static_meshes=None, static_lines=None, uid=None, autorecenter=True, keepalive=False, window_width=1280, window_height=960, snapshot_camera=None ): """Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string...
def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepalive=False, window_width=1280, window_height=960 ): """Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns:...
def on_drag(self, cursor_x, cursor_y): """ 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. """ from blmath.geometry.transform.rodrigues import as_rotation_matrix if...
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. """ self.isdragging = False if button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_UP: ...
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. # Luckily, we have the circumcenter-face distan...
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 v = self.ei_dot_ei * self.ce_ratios / 6.0 ...
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: disable=unused-variable,relative-import from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as...
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 isinstance(text, six.string_types): return int(text) else: ...
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 not exist: %r' % name, ...
def fact_pk(self): """ 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. """ keys = [c for c in self.fact_table.columns if c.primary_key] return keys[0]
def aggregate(self, aggregates=None, drilldowns=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """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...
def members(self, ref, cuts=None, order=None, page=None, page_size=None): """ List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned. """ def prep(cuts, ref, order, columns=None): q = s...
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. """ def prep(cuts, columns=None): q = select(columns=columns).select_from(self...
def compute_cardinalities(self): """ 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. """ for dimension in self.model.dimensions: result = self.members(dimension....
def restrict_joins(self, q, bindings): """ 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 re...
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, "")) if k in commands: ...