repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_edges_cells
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 = numpy.zeros(num_edges, dtype=int) fastfunc.add.at( counts, self.cells["edges"], numpy.ones(self.cells["edges"].shape, dtype=int), ) # <https://stackoverflow.com/a/50395231/353337> edges_flat = self.cells["edges"].flat idx_sort = numpy.argsort(edges_flat) idx_start, count = grp_start_len(edges_flat[idx_sort]) res1 = idx_sort[idx_start[count == 1]][:, numpy.newaxis] idx = idx_start[count == 2] res2 = numpy.column_stack([idx_sort[idx], idx_sort[idx + 1]]) self._edges_cells = [ [], # no edges with zero adjacent cells res1 // 3, res2 // 3, ] # self._edges_local = [ # [], # no edges with zero adjacent cells # res1 % 3, # res2 % 3, # ] # For each edge, store the number of adjacent cells plus the index into # the respective edge array. self._edge_gid_to_edge_list = numpy.empty((num_edges, 2), dtype=int) self._edge_gid_to_edge_list[:, 0] = count c1 = count == 1 l1 = numpy.sum(c1) self._edge_gid_to_edge_list[c1, 1] = numpy.arange(l1) c2 = count == 2 l2 = numpy.sum(c2) self._edge_gid_to_edge_list[c2, 1] = numpy.arange(l2) assert l1 + l2 == len(count) return
python
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 = numpy.zeros(num_edges, dtype=int) fastfunc.add.at( counts, self.cells["edges"], numpy.ones(self.cells["edges"].shape, dtype=int), ) # <https://stackoverflow.com/a/50395231/353337> edges_flat = self.cells["edges"].flat idx_sort = numpy.argsort(edges_flat) idx_start, count = grp_start_len(edges_flat[idx_sort]) res1 = idx_sort[idx_start[count == 1]][:, numpy.newaxis] idx = idx_start[count == 2] res2 = numpy.column_stack([idx_sort[idx], idx_sort[idx + 1]]) self._edges_cells = [ [], # no edges with zero adjacent cells res1 // 3, res2 // 3, ] # self._edges_local = [ # [], # no edges with zero adjacent cells # res1 % 3, # res2 % 3, # ] # For each edge, store the number of adjacent cells plus the index into # the respective edge array. self._edge_gid_to_edge_list = numpy.empty((num_edges, 2), dtype=int) self._edge_gid_to_edge_list[:, 0] = count c1 = count == 1 l1 = numpy.sum(c1) self._edge_gid_to_edge_list[c1, 1] = numpy.arange(l1) c2 = count == 2 l2 = numpy.sum(c2) self._edge_gid_to_edge_list[c2, 1] = numpy.arange(l2) assert l1 + l2 == len(count) return
[ "def", "_compute_edges_cells", "(", "self", ")", ":", "if", "self", ".", "edges", "is", "None", ":", "self", ".", "create_edges", "(", ")", "num_edges", "=", "len", "(", "self", ".", "edges", "[", "\"nodes\"", "]", ")", "counts", "=", "numpy", ".", "...
This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy.
[ "This", "creates", "interior", "edge", "-", ">", "cells", "relations", ".", "While", "it", "s", "not", "necessary", "for", "many", "applications", "it", "sometimes", "does", "come", "in", "handy", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L374-L420
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.cell_centroids
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
python
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", "cell_centroids", "(", "self", ")", ":", "if", "self", ".", "_cell_centroids", "is", "None", ":", "self", ".", "_cell_centroids", "=", "(", "numpy", ".", "sum", "(", "self", ".", "node_coords", "[", "self", ".", "cells", "[", "\"nodes\"", "]", "...
The centroids (barycenters) of all triangles.
[ "The", "centroids", "(", "barycenters", ")", "of", "all", "triangles", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L454-L461
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_integral_x
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 of the function in each of the three corners, times the # area of the triangle. right_triangle_vols = self.cell_partitions node_edges = self.idx_hierarchy corner = self.node_coords[node_edges] edge_midpoints = 0.5 * (corner[0] + corner[1]) cc = self.cell_circumcenters average = (corner + edge_midpoints[None] + cc[None, None]) / 3.0 contribs = right_triangle_vols[None, :, :, None] * average return node_edges, contribs
python
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 of the function in each of the three corners, times the # area of the triangle. right_triangle_vols = self.cell_partitions node_edges = self.idx_hierarchy corner = self.node_coords[node_edges] edge_midpoints = 0.5 * (corner[0] + corner[1]) cc = self.cell_circumcenters average = (corner + edge_midpoints[None] + cc[None, None]) / 3.0 contribs = right_triangle_vols[None, :, :, None] * average return node_edges, contribs
[ "def", "_compute_integral_x", "(", "self", ")", ":", "# The integral of any linear function over a triangle is the average of", "# the values of the function in each of the three corners, times the", "# area of the triangle.", "right_triangle_vols", "=", "self", ".", "cell_partitions", "...
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.
[ "Computes", "the", "integral", "of", "x" ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L512-L535
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_surface_areas
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 the surface areas of all # three vertices. Here, only the two adjacent nodes receive a # contribution, but other approaches (e.g., the flat cell corrector), # may contribute to all three nodes. cn = self.cells["nodes"][cell_ids] ids = numpy.stack([cn, cn, cn], axis=1) half_el = 0.5 * self.edge_lengths[..., cell_ids] zero = numpy.zeros([half_el.shape[1]]) vals = numpy.stack( [ numpy.column_stack([zero, half_el[0], half_el[0]]), numpy.column_stack([half_el[1], zero, half_el[1]]), numpy.column_stack([half_el[2], half_el[2], zero]), ], axis=1, ) return ids, vals
python
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 the surface areas of all # three vertices. Here, only the two adjacent nodes receive a # contribution, but other approaches (e.g., the flat cell corrector), # may contribute to all three nodes. cn = self.cells["nodes"][cell_ids] ids = numpy.stack([cn, cn, cn], axis=1) half_el = 0.5 * self.edge_lengths[..., cell_ids] zero = numpy.zeros([half_el.shape[1]]) vals = numpy.stack( [ numpy.column_stack([zero, half_el[0], half_el[0]]), numpy.column_stack([half_el[1], zero, half_el[1]]), numpy.column_stack([half_el[2], half_el[2], zero]), ], axis=1, ) return ids, vals
[ "def", "_compute_surface_areas", "(", "self", ",", "cell_ids", ")", ":", "# Each of the three edges may contribute to the surface areas of all", "# three vertices. Here, only the two adjacent nodes receive a", "# contribution, but other approaches (e.g., the flat cell corrector),", "# may cont...
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.
[ "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", "condi...
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L537-L560
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.compute_curl
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; see <https://en.wikipedia.org/wiki/Curl_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges. """ # Compute the projection of A on the edge at each edge midpoint. # Take the average of `vector_field` at the endpoints to get the # approximate value at the edge midpoint. A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0) # sum of <edge, A> for all three edges sum_edge_dot_A = numpy.einsum("ijk, ijk->j", self.half_edge_coords, A) # Get normalized vector orthogonal to triangle z = numpy.cross(self.half_edge_coords[0], self.half_edge_coords[1]) # Now compute # # curl = z / ||z|| * sum_edge_dot_A / |A|. # # Since ||z|| = 2*|A|, one can save a sqrt and do # # curl = z * sum_edge_dot_A * 0.5 / |A|^2. # curl = z * (0.5 * sum_edge_dot_A / self.cell_volumes ** 2)[..., None] return curl
python
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; see <https://en.wikipedia.org/wiki/Curl_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges. """ # Compute the projection of A on the edge at each edge midpoint. # Take the average of `vector_field` at the endpoints to get the # approximate value at the edge midpoint. A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0) # sum of <edge, A> for all three edges sum_edge_dot_A = numpy.einsum("ijk, ijk->j", self.half_edge_coords, A) # Get normalized vector orthogonal to triangle z = numpy.cross(self.half_edge_coords[0], self.half_edge_coords[1]) # Now compute # # curl = z / ||z|| * sum_edge_dot_A / |A|. # # Since ||z|| = 2*|A|, one can save a sqrt and do # # curl = z * sum_edge_dot_A * 0.5 / |A|^2. # curl = z * (0.5 * sum_edge_dot_A / self.cell_volumes ** 2)[..., None] return curl
[ "def", "compute_curl", "(", "self", ",", "vector_field", ")", ":", "# Compute the projection of A on the edge at each edge midpoint.", "# Take the average of `vector_field` at the endpoints to get the", "# approximate value at the edge midpoint.", "A", "=", "0.5", "*", "numpy", ".", ...
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_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges.
[ "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" ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L651-L682
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.plot
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. """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt from matplotlib.collections import LineCollection # from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca() # plt.axis("equal") if not show_axes: ax.set_axis_off() xmin = numpy.amin(self.node_coords[:, 0]) xmax = numpy.amax(self.node_coords[:, 0]) ymin = numpy.amin(self.node_coords[:, 1]) ymax = numpy.amax(self.node_coords[:, 1]) width = xmax - xmin xmin -= 0.1 * width xmax += 0.1 * width height = ymax - ymin ymin -= 0.1 * height ymax += 0.1 * height # ax.set_xlim(xmin, xmax) # ax.set_ylim(ymin, ymax) if self.edges is None: self.create_edges() # Get edges, cut off z-component. e = self.node_coords[self.edges["nodes"]][:, :, :2] # Plot regular edges, mark those with negative ce-ratio red. ce_ratios = self.ce_ratios_per_interior_edge pos = ce_ratios >= 0 is_pos = numpy.zeros(len(self.edges["nodes"]), dtype=bool) is_pos[self._edge_to_edge_gid[2][pos]] = True # Mark Delaunay-conforming boundary edges is_pos_boundary = self.ce_ratios[self.is_boundary_edge] >= 0 is_pos[self._edge_to_edge_gid[1][is_pos_boundary]] = True line_segments0 = LineCollection(e[is_pos], color=mesh_color) ax.add_collection(line_segments0) # line_segments1 = LineCollection(e[~is_pos], color=nondelaunay_edge_color) ax.add_collection(line_segments1) if show_coedges: # Connect all cell circumcenters with the edge midpoints cc = self.cell_circumcenters edge_midpoints = 0.5 * ( self.node_coords[self.edges["nodes"][:, 0]] + self.node_coords[self.edges["nodes"][:, 1]] ) # Plot connection of the circumcenter to the midpoint of all three # axes. a = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 0], :2]], axis=1 ) b = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 1], :2]], axis=1 ) c = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 2], :2]], axis=1 ) line_segments = LineCollection( numpy.concatenate([a, b, c]), color=comesh_color ) ax.add_collection(line_segments) if boundary_edge_color: e = self.node_coords[self.edges["nodes"][self.is_boundary_edge_individual]][ :, :, :2 ] line_segments1 = LineCollection(e, color=boundary_edge_color) ax.add_collection(line_segments1) if show_centroids: centroids = self.control_volume_centroids ax.plot( centroids[:, 0], centroids[:, 1], linestyle="", marker=".", color="#d62728", ) return fig
python
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. """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt from matplotlib.collections import LineCollection # from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca() # plt.axis("equal") if not show_axes: ax.set_axis_off() xmin = numpy.amin(self.node_coords[:, 0]) xmax = numpy.amax(self.node_coords[:, 0]) ymin = numpy.amin(self.node_coords[:, 1]) ymax = numpy.amax(self.node_coords[:, 1]) width = xmax - xmin xmin -= 0.1 * width xmax += 0.1 * width height = ymax - ymin ymin -= 0.1 * height ymax += 0.1 * height # ax.set_xlim(xmin, xmax) # ax.set_ylim(ymin, ymax) if self.edges is None: self.create_edges() # Get edges, cut off z-component. e = self.node_coords[self.edges["nodes"]][:, :, :2] # Plot regular edges, mark those with negative ce-ratio red. ce_ratios = self.ce_ratios_per_interior_edge pos = ce_ratios >= 0 is_pos = numpy.zeros(len(self.edges["nodes"]), dtype=bool) is_pos[self._edge_to_edge_gid[2][pos]] = True # Mark Delaunay-conforming boundary edges is_pos_boundary = self.ce_ratios[self.is_boundary_edge] >= 0 is_pos[self._edge_to_edge_gid[1][is_pos_boundary]] = True line_segments0 = LineCollection(e[is_pos], color=mesh_color) ax.add_collection(line_segments0) # line_segments1 = LineCollection(e[~is_pos], color=nondelaunay_edge_color) ax.add_collection(line_segments1) if show_coedges: # Connect all cell circumcenters with the edge midpoints cc = self.cell_circumcenters edge_midpoints = 0.5 * ( self.node_coords[self.edges["nodes"][:, 0]] + self.node_coords[self.edges["nodes"][:, 1]] ) # Plot connection of the circumcenter to the midpoint of all three # axes. a = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 0], :2]], axis=1 ) b = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 1], :2]], axis=1 ) c = numpy.stack( [cc[:, :2], edge_midpoints[self.cells["edges"][:, 2], :2]], axis=1 ) line_segments = LineCollection( numpy.concatenate([a, b, c]), color=comesh_color ) ax.add_collection(line_segments) if boundary_edge_color: e = self.node_coords[self.edges["nodes"][self.is_boundary_edge_individual]][ :, :, :2 ] line_segments1 = LineCollection(e, color=boundary_edge_color) ax.add_collection(line_segments1) if show_centroids: centroids = self.control_volume_centroids ax.plot( centroids[:, 0], centroids[:, 1], linestyle="", marker=".", color="#d62728", ) return fig
[ "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_col...
Show the mesh using matplotlib.
[ "Show", "the", "mesh", "using", "matplotlib", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L709-L813
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.show_vertex
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 """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt fig = plt.figure() ax = fig.gca() plt.axis("equal") # Find the edges that contain the vertex edge_gids = numpy.where((self.edges["nodes"] == node_id).any(axis=1))[0] # ... and plot them for node_ids in self.edges["nodes"][edge_gids]: x = self.node_coords[node_ids] ax.plot(x[:, 0], x[:, 1], "k") # Highlight ce_ratios. if show_ce_ratio: if self.cell_circumcenters is None: X = self.node_coords[self.cells["nodes"]] self.cell_circumcenters = self.compute_triangle_circumcenters( X, self.ei_dot_ei, self.ei_dot_ej ) # Find the cells that contain the vertex cell_ids = numpy.where((self.cells["nodes"] == node_id).any(axis=1))[0] for cell_id in cell_ids: for edge_gid in self.cells["edges"][cell_id]: if node_id not in self.edges["nodes"][edge_gid]: continue node_ids = self.edges["nodes"][edge_gid] edge_midpoint = 0.5 * ( self.node_coords[node_ids[0]] + self.node_coords[node_ids[1]] ) p = _column_stack(self.cell_circumcenters[cell_id], edge_midpoint) q = numpy.column_stack( [ self.cell_circumcenters[cell_id], edge_midpoint, self.node_coords[node_id], ] ) ax.fill(q[0], q[1], color="0.5") ax.plot(p[0], p[1], color="0.7") return
python
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 """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt fig = plt.figure() ax = fig.gca() plt.axis("equal") # Find the edges that contain the vertex edge_gids = numpy.where((self.edges["nodes"] == node_id).any(axis=1))[0] # ... and plot them for node_ids in self.edges["nodes"][edge_gids]: x = self.node_coords[node_ids] ax.plot(x[:, 0], x[:, 1], "k") # Highlight ce_ratios. if show_ce_ratio: if self.cell_circumcenters is None: X = self.node_coords[self.cells["nodes"]] self.cell_circumcenters = self.compute_triangle_circumcenters( X, self.ei_dot_ei, self.ei_dot_ej ) # Find the cells that contain the vertex cell_ids = numpy.where((self.cells["nodes"] == node_id).any(axis=1))[0] for cell_id in cell_ids: for edge_gid in self.cells["edges"][cell_id]: if node_id not in self.edges["nodes"][edge_gid]: continue node_ids = self.edges["nodes"][edge_gid] edge_midpoint = 0.5 * ( self.node_coords[node_ids[0]] + self.node_coords[node_ids[1]] ) p = _column_stack(self.cell_circumcenters[cell_id], edge_midpoint) q = numpy.column_stack( [ self.cell_circumcenters[cell_id], edge_midpoint, self.node_coords[node_id], ] ) ax.fill(q[0], q[1], color="0.5") ax.plot(p[0], p[1], color="0.7") return
[ "def", "show_vertex", "(", "self", ",", "node_id", ",", "show_ce_ratio", "=", "True", ")", ":", "# Importing matplotlib takes a while, so don't do that at the header.", "from", "matplotlib", "import", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")"...
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
[ "Plot", "the", "vicinity", "of", "a", "node", "and", "its", "ce_ratio", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L815-L867
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._update_cell_values
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_coords self.half_edge_coords[:, cell_ids, :] = numpy.moveaxis( self.node_coords[self.idx_hierarchy[1, ..., cell_ids]] - self.node_coords[self.idx_hierarchy[0, ..., cell_ids]], 0, 1, ) # update self.ei_dot_ej self.ei_dot_ej[:, cell_ids] = numpy.einsum( "ijk, ijk->ij", self.half_edge_coords[[1, 2, 0]][:, cell_ids], self.half_edge_coords[[2, 0, 1]][:, cell_ids], ) # update self.ei_dot_ei e = self.half_edge_coords[:, cell_ids] self.ei_dot_ei[:, cell_ids] = numpy.einsum("ijk, ijk->ij", e, e) # update cell_volumes, ce_ratios_per_half_edge cv = compute_tri_areas(self.ei_dot_ej[:, cell_ids]) ce = compute_ce_ratios(self.ei_dot_ej[:, cell_ids], cv) self.cell_volumes[cell_ids] = cv self.ce_ratios[:, cell_ids] = ce if self._interior_ce_ratios is not None: self._interior_ce_ratios[interior_edge_ids] = 0.0 edge_gids = self._edge_to_edge_gid[2][interior_edge_ids] adj_cells = self._edges_cells[2][interior_edge_ids] is0 = self.cells["edges"][adj_cells[:, 0]][:, 0] == edge_gids is1 = self.cells["edges"][adj_cells[:, 0]][:, 1] == edge_gids is2 = self.cells["edges"][adj_cells[:, 0]][:, 2] == edge_gids assert numpy.all( numpy.sum(numpy.column_stack([is0, is1, is2]), axis=1) == 1 ) # self._interior_ce_ratios[interior_edge_ids[is0]] += self.ce_ratios[ 0, adj_cells[is0, 0] ] self._interior_ce_ratios[interior_edge_ids[is1]] += self.ce_ratios[ 1, adj_cells[is1, 0] ] self._interior_ce_ratios[interior_edge_ids[is2]] += self.ce_ratios[ 2, adj_cells[is2, 0] ] is0 = self.cells["edges"][adj_cells[:, 1]][:, 0] == edge_gids is1 = self.cells["edges"][adj_cells[:, 1]][:, 1] == edge_gids is2 = self.cells["edges"][adj_cells[:, 1]][:, 2] == edge_gids assert numpy.all( numpy.sum(numpy.column_stack([is0, is1, is2]), axis=1) == 1 ) # self._interior_ce_ratios[interior_edge_ids[is0]] += self.ce_ratios[ 0, adj_cells[is0, 1] ] self._interior_ce_ratios[interior_edge_ids[is1]] += self.ce_ratios[ 1, adj_cells[is1, 1] ] self._interior_ce_ratios[interior_edge_ids[is2]] += self.ce_ratios[ 2, adj_cells[is2, 1] ] if self._signed_cell_areas is not None: # One could make p contiguous by adding a copy(), but that's not # really worth it here. p = self.node_coords[self.cells["nodes"][cell_ids]].T # <https://stackoverflow.com/q/50411583/353337> self._signed_cell_areas[cell_ids] = ( +p[0][2] * (p[1][0] - p[1][1]) + p[0][0] * (p[1][1] - p[1][2]) + p[0][1] * (p[1][2] - p[1][0]) ) / 2 # TODO update those values self._cell_centroids = None self._edge_lengths = None self._cell_circumcenters = None self._control_volumes = None self._cell_partitions = None self._cv_centroids = None self._surface_areas = None self.subdomains = {} return
python
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_coords self.half_edge_coords[:, cell_ids, :] = numpy.moveaxis( self.node_coords[self.idx_hierarchy[1, ..., cell_ids]] - self.node_coords[self.idx_hierarchy[0, ..., cell_ids]], 0, 1, ) # update self.ei_dot_ej self.ei_dot_ej[:, cell_ids] = numpy.einsum( "ijk, ijk->ij", self.half_edge_coords[[1, 2, 0]][:, cell_ids], self.half_edge_coords[[2, 0, 1]][:, cell_ids], ) # update self.ei_dot_ei e = self.half_edge_coords[:, cell_ids] self.ei_dot_ei[:, cell_ids] = numpy.einsum("ijk, ijk->ij", e, e) # update cell_volumes, ce_ratios_per_half_edge cv = compute_tri_areas(self.ei_dot_ej[:, cell_ids]) ce = compute_ce_ratios(self.ei_dot_ej[:, cell_ids], cv) self.cell_volumes[cell_ids] = cv self.ce_ratios[:, cell_ids] = ce if self._interior_ce_ratios is not None: self._interior_ce_ratios[interior_edge_ids] = 0.0 edge_gids = self._edge_to_edge_gid[2][interior_edge_ids] adj_cells = self._edges_cells[2][interior_edge_ids] is0 = self.cells["edges"][adj_cells[:, 0]][:, 0] == edge_gids is1 = self.cells["edges"][adj_cells[:, 0]][:, 1] == edge_gids is2 = self.cells["edges"][adj_cells[:, 0]][:, 2] == edge_gids assert numpy.all( numpy.sum(numpy.column_stack([is0, is1, is2]), axis=1) == 1 ) # self._interior_ce_ratios[interior_edge_ids[is0]] += self.ce_ratios[ 0, adj_cells[is0, 0] ] self._interior_ce_ratios[interior_edge_ids[is1]] += self.ce_ratios[ 1, adj_cells[is1, 0] ] self._interior_ce_ratios[interior_edge_ids[is2]] += self.ce_ratios[ 2, adj_cells[is2, 0] ] is0 = self.cells["edges"][adj_cells[:, 1]][:, 0] == edge_gids is1 = self.cells["edges"][adj_cells[:, 1]][:, 1] == edge_gids is2 = self.cells["edges"][adj_cells[:, 1]][:, 2] == edge_gids assert numpy.all( numpy.sum(numpy.column_stack([is0, is1, is2]), axis=1) == 1 ) # self._interior_ce_ratios[interior_edge_ids[is0]] += self.ce_ratios[ 0, adj_cells[is0, 1] ] self._interior_ce_ratios[interior_edge_ids[is1]] += self.ce_ratios[ 1, adj_cells[is1, 1] ] self._interior_ce_ratios[interior_edge_ids[is2]] += self.ce_ratios[ 2, adj_cells[is2, 1] ] if self._signed_cell_areas is not None: # One could make p contiguous by adding a copy(), but that's not # really worth it here. p = self.node_coords[self.cells["nodes"][cell_ids]].T # <https://stackoverflow.com/q/50411583/353337> self._signed_cell_areas[cell_ids] = ( +p[0][2] * (p[1][0] - p[1][1]) + p[0][0] * (p[1][1] - p[1][2]) + p[0][1] * (p[1][2] - p[1][0]) ) / 2 # TODO update those values self._cell_centroids = None self._edge_lengths = None self._cell_circumcenters = None self._control_volumes = None self._cell_partitions = None self._cv_centroids = None self._surface_areas = None self.subdomains = {} return
[ "def", "_update_cell_values", "(", "self", ",", "cell_ids", ",", "interior_edge_ids", ")", ":", "# update idx_hierarchy", "nds", "=", "self", ".", "cells", "[", "\"nodes\"", "]", "[", "cell_ids", "]", ".", "T", "self", ".", "idx_hierarchy", "[", "...", ",", ...
Updates all sorts of cell information for the given cell IDs.
[ "Updates", "all", "sorts", "of", "cell", "information", "for", "the", "given", "cell", "IDs", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L1042-L1133
bodylabs/lace
lace/serialization/dae.py
_dump
def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
python
def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
[ "def", "_dump", "(", "f", ",", "mesh", ")", ":", "dae", "=", "mesh_to_collada", "(", "mesh", ")", "dae", ".", "write", "(", "f", ".", "name", ")" ]
Writes a mesh to collada file format.
[ "Writes", "a", "mesh", "to", "collada", "file", "format", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L7-L12
bodylabs/lace
lace/serialization/dae.py
dumps
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')
python
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", "dumps", "(", "mesh", ")", ":", "from", "lxml", "import", "etree", "dae", "=", "mesh_to_collada", "(", "mesh", ")", "# Update the xmlnode.", "dae", ".", "save", "(", ")", "return", "etree", ".", "tostring", "(", "dae", ".", "xmlnode", ",", "encodi...
Generates a UTF-8 XML string containing the mesh, in collada format.
[ "Generates", "a", "UTF", "-", "8", "XML", "string", "containing", "the", "mesh", "in", "collada", "format", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L14-L25
bodylabs/lace
lace/serialization/dae.py
mesh_to_collada
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): from collada import material, scene effect = material.Effect("effect0", [], "phong", diffuse=(1, 1, 1), specular=(0, 0, 0), double_sided=True) mat = material.Material("material0", "mymaterial", effect) dae.effects.append(effect) dae.materials.append(mat) return scene.MaterialNode("materialref", mat, inputs=[]) def geometry_from_mesh(dae, mesh): from collada import source, geometry srcs = [] # v srcs.append(source.FloatSource("verts-array", mesh.v, ('X', 'Y', 'Z'))) input_list = source.InputList() input_list.addInput(0, 'VERTEX', "#verts-array") # vc if mesh.vc is not None: input_list.addInput(len(srcs), 'COLOR', "#color-array") srcs.append(source.FloatSource("color-array", mesh.vc[mesh.f.ravel()], ('X', 'Y', 'Z'))) # f geom = geometry.Geometry(str(mesh), "geometry0", "mymesh", srcs) indices = np.dstack([mesh.f for _ in srcs]).ravel() triset = geom.createTriangleSet(indices, input_list, "materialref") geom.primitives.append(triset) # e if mesh.e is not None: indices = np.dstack([mesh.e for _ in srcs]).ravel() lineset = geom.createLineSet(indices, input_list, "materialref") geom.primitives.append(lineset) dae.geometries.append(geom) return geom dae = Collada() geom = geometry_from_mesh(dae, mesh) node = scene.Node("node0", children=[scene.GeometryNode(geom, [create_material(dae)])]) myscene = scene.Scene("myscene", [node]) dae.scenes.append(myscene) dae.scene = myscene return dae
python
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): from collada import material, scene effect = material.Effect("effect0", [], "phong", diffuse=(1, 1, 1), specular=(0, 0, 0), double_sided=True) mat = material.Material("material0", "mymaterial", effect) dae.effects.append(effect) dae.materials.append(mat) return scene.MaterialNode("materialref", mat, inputs=[]) def geometry_from_mesh(dae, mesh): from collada import source, geometry srcs = [] # v srcs.append(source.FloatSource("verts-array", mesh.v, ('X', 'Y', 'Z'))) input_list = source.InputList() input_list.addInput(0, 'VERTEX', "#verts-array") # vc if mesh.vc is not None: input_list.addInput(len(srcs), 'COLOR', "#color-array") srcs.append(source.FloatSource("color-array", mesh.vc[mesh.f.ravel()], ('X', 'Y', 'Z'))) # f geom = geometry.Geometry(str(mesh), "geometry0", "mymesh", srcs) indices = np.dstack([mesh.f for _ in srcs]).ravel() triset = geom.createTriangleSet(indices, input_list, "materialref") geom.primitives.append(triset) # e if mesh.e is not None: indices = np.dstack([mesh.e for _ in srcs]).ravel() lineset = geom.createLineSet(indices, input_list, "materialref") geom.primitives.append(lineset) dae.geometries.append(geom) return geom dae = Collada() geom = geometry_from_mesh(dae, mesh) node = scene.Node("node0", children=[scene.GeometryNode(geom, [create_material(dae)])]) myscene = scene.Scene("myscene", [node]) dae.scenes.append(myscene) dae.scene = myscene return dae
[ "def", "mesh_to_collada", "(", "mesh", ")", ":", "import", "numpy", "as", "np", "try", ":", "from", "collada", "import", "Collada", ",", "scene", "except", "ImportError", ":", "raise", "ImportError", "(", "\"lace.serialization.dae.mesh_to_collade requires package pyco...
Supports per-vertex color, but nothing else.
[ "Supports", "per", "-", "vertex", "color", "but", "nothing", "else", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L27-L76
bodylabs/lace
lace/geometry.py
MeshMixin.convert_units
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( from_units=from_units, to_units=to_units, units_class='length' ) self.scale(factor)
python
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( from_units=from_units, to_units=to_units, units_class='length' ) self.scale(factor)
[ "def", "convert_units", "(", "self", ",", "from_units", ",", "to_units", ")", ":", "from", "blmath", "import", "units", "factor", "=", "units", ".", "factor", "(", "from_units", "=", "from_units", ",", "to_units", "=", "to_units", ",", "units_class", "=", ...
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)
[ "Convert", "the", "mesh", "from", "one", "set", "of", "units", "to", "another", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L34-L50
bodylabs/lace
lace/geometry.py
MeshMixin.predict_body_units
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' if round(longest_dist / 100) > 0: return 'cm' if round(longest_dist / 10) > 0: return 'dm' return 'm'
python
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' if round(longest_dist / 100) > 0: return 'cm' if round(longest_dist / 10) > 0: return 'dm' return 'm'
[ "def", "predict_body_units", "(", "self", ")", ":", "longest_dist", "=", "np", ".", "max", "(", "np", ".", "max", "(", "self", ".", "v", ",", "axis", "=", "0", ")", "-", "np", ".", "min", "(", "self", ".", "v", ",", "axis", "=", "0", ")", ")"...
There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned
[ "There", "is", "no", "prediction", "for", "united", "states", "unit", "system", ".", "This", "may", "fail", "when", "a", "mesh", "is", "not", "axis", "-", "aligned" ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L52-L64
bodylabs/lace
lace/geometry.py
MeshMixin.reorient
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). ''' from blmath.geometry.transform import rotation_from_up_and_look from blmath.numerics import as_numeric_array up = as_numeric_array(up, (3,)) look = as_numeric_array(look, (3,)) if self.v is not None: self.v = np.dot(rotation_from_up_and_look(up, look), self.v.T).T
python
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). ''' from blmath.geometry.transform import rotation_from_up_and_look from blmath.numerics import as_numeric_array up = as_numeric_array(up, (3,)) look = as_numeric_array(look, (3,)) if self.v is not None: self.v = np.dot(rotation_from_up_and_look(up, look), self.v.T).T
[ "def", "reorient", "(", "self", ",", "up", ",", "look", ")", ":", "from", "blmath", ".", "geometry", ".", "transform", "import", "rotation_from_up_and_look", "from", "blmath", ".", "numerics", "import", "as_numeric_array", "up", "=", "as_numeric_array", "(", "...
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).
[ "Reorient", "the", "mesh", "by", "specifying", "two", "vectors", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L80-L98
bodylabs/lace
lace/geometry.py
MeshMixin.flip
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_centroid: self.v[:, axis] -= 2 * self.centroid[0] self.flip_faces()
python
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_centroid: self.v[:, axis] -= 2 * self.centroid[0] self.flip_faces()
[ "def", "flip", "(", "self", ",", "axis", "=", "0", ",", "preserve_centroid", "=", "False", ")", ":", "self", ".", "v", "[", ":", ",", "axis", "]", "*=", "-", "1", "if", "preserve_centroid", ":", "self", ".", "v", "[", ":", ",", "axis", "]", "-=...
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.
[ "Flip", "the", "mesh", "across", "the", "given", "axis", ":", "0", "for", "x", "1", "for", "y", "2", "for", "z", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L100-L113
bodylabs/lace
lace/geometry.py
MeshMixin.centroid
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)
python
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", "centroid", "(", "self", ")", ":", "if", "self", ".", "v", "is", "None", ":", "raise", "ValueError", "(", "'Mesh has no vertices; centroid is not defined'", ")", "return", "np", ".", "mean", "(", "self", ".", "v", ",", "axis", "=", "0", ")" ]
Return the geometric center.
[ "Return", "the", "geometric", "center", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L119-L127
bodylabs/lace
lace/geometry.py
MeshMixin.floor_point
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
python
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", "floor_point", "(", "self", ")", ":", "floor_point", "=", "self", ".", "centroid", "# y to floor", "floor_point", "[", "1", "]", "=", "self", ".", "v", "[", ":", ",", "1", "]", ".", "min", "(", ")", "return", "floor_point" ]
Return the point on the floor that lies below the centroid.
[ "Return", "the", "point", "on", "the", "floor", "that", "lies", "below", "the", "centroid", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L133-L141
bodylabs/lace
lace/geometry.py
MeshMixin.apex
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)
python
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", "apex", "(", "self", ",", "axis", ")", ":", "from", "blmath", ".", "geometry", ".", "apex", "import", "apex", "return", "apex", "(", "self", ".", "v", ",", "axis", ")" ]
Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array.
[ "Find", "the", "most", "extreme", "vertex", "in", "the", "direction", "of", "the", "axis", "provided", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L167-L175
bodylabs/lace
lace/geometry.py
MeshMixin.first_blip
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 encountering the mesh, and return that vertex: like the first blip of the radar. The radar works as if on a point cloud: it sees sees only vertices, not edges. The ray sweeps clockwise and counterclockwise at the same time, and returns the first point it hits. If no intersection occurs within 90 degrees, return None. `initial_direction` need not be normalized. ''' from blmath.numerics import as_numeric_array origin = vx.reject_axis(as_numeric_array(origin, (3,)), axis=squash_axis, squash=True) initial_direction = vx.reject_axis(as_numeric_array(initial_direction, (3,)), axis=squash_axis, squash=True) vertices = vx.reject_axis(self.v, axis=squash_axis, squash=True) origin_to_mesh = vx.normalize(vertices - origin) cosines = vx.normalize(initial_direction).dot(origin_to_mesh.T).T index_of_first_blip = np.argmax(cosines) return self.v[index_of_first_blip]
python
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 encountering the mesh, and return that vertex: like the first blip of the radar. The radar works as if on a point cloud: it sees sees only vertices, not edges. The ray sweeps clockwise and counterclockwise at the same time, and returns the first point it hits. If no intersection occurs within 90 degrees, return None. `initial_direction` need not be normalized. ''' from blmath.numerics import as_numeric_array origin = vx.reject_axis(as_numeric_array(origin, (3,)), axis=squash_axis, squash=True) initial_direction = vx.reject_axis(as_numeric_array(initial_direction, (3,)), axis=squash_axis, squash=True) vertices = vx.reject_axis(self.v, axis=squash_axis, squash=True) origin_to_mesh = vx.normalize(vertices - origin) cosines = vx.normalize(initial_direction).dot(origin_to_mesh.T).T index_of_first_blip = np.argmax(cosines) return self.v[index_of_first_blip]
[ "def", "first_blip", "(", "self", ",", "squash_axis", ",", "origin", ",", "initial_direction", ")", ":", "from", "blmath", ".", "numerics", "import", "as_numeric_array", "origin", "=", "vx", ".", "reject_axis", "(", "as_numeric_array", "(", "origin", ",", "(",...
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. The radar works as if on a point cloud: it sees sees only vertices, not edges. The ray sweeps clockwise and counterclockwise at the same time, and returns the first point it hits. If no intersection occurs within 90 degrees, return None. `initial_direction` need not be normalized.
[ "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", ...
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L177-L204
bodylabs/lace
lace/geometry.py
MeshMixin.cut_across_axis
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, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices. ''' # vertex_mask keeps track of the vertices we want to keep. vertex_mask = np.ones((len(self.v),), dtype=bool) if minval is not None: predicate = self.v[:, dim] >= minval vertex_mask = np.logical_and(vertex_mask, predicate) if maxval is not None: predicate = self.v[:, dim] <= maxval vertex_mask = np.logical_and(vertex_mask, predicate) vertex_indices = np.flatnonzero(vertex_mask) self.keep_vertices(vertex_indices) return vertex_indices
python
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, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices. ''' # vertex_mask keeps track of the vertices we want to keep. vertex_mask = np.ones((len(self.v),), dtype=bool) if minval is not None: predicate = self.v[:, dim] >= minval vertex_mask = np.logical_and(vertex_mask, predicate) if maxval is not None: predicate = self.v[:, dim] <= maxval vertex_mask = np.logical_and(vertex_mask, predicate) vertex_indices = np.flatnonzero(vertex_mask) self.keep_vertices(vertex_indices) return vertex_indices
[ "def", "cut_across_axis", "(", "self", ",", "dim", ",", "minval", "=", "None", ",", "maxval", "=", "None", ")", ":", "# vertex_mask keeps track of the vertices we want to keep.", "vertex_mask", "=", "np", ".", "ones", "(", "(", "len", "(", "self", ".", "v", ...
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` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices.
[ "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", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L206-L233
bodylabs/lace
lace/geometry.py
MeshMixin.cut_across_axis_by_percentile
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 vertices, `dim` is 2, and `minpct` is 10, this method drops the 5,000 vertices which are furthest along the +z axis. See numpy.percentile Return the original indices of the kept vertices. ''' value_range = np.percentile(self.v[:, dim], (minpct, maxpct)) return self.cut_across_axis(dim, *value_range)
python
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 vertices, `dim` is 2, and `minpct` is 10, this method drops the 5,000 vertices which are furthest along the +z axis. See numpy.percentile Return the original indices of the kept vertices. ''' value_range = np.percentile(self.v[:, dim], (minpct, maxpct)) return self.cut_across_axis(dim, *value_range)
[ "def", "cut_across_axis_by_percentile", "(", "self", ",", "dim", ",", "minpct", "=", "0", ",", "maxpct", "=", "100", ")", ":", "value_range", "=", "np", ".", "percentile", "(", "self", ".", "v", "[", ":", ",", "dim", "]", ",", "(", "minpct", ",", "...
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 are furthest along the +z axis. See numpy.percentile Return the original indices of the kept vertices.
[ "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", ".", ")" ...
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L235-L251
bodylabs/lace
lace/geometry.py
MeshMixin.cut_by_plane
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 behind the plane instead. Return the original indices of the kept vertices. ''' vertices_to_keep = plane.points_in_front(self.v, inverted=inverted, ret_indices=True) self.keep_vertices(vertices_to_keep) return vertices_to_keep
python
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 behind the plane instead. Return the original indices of the kept vertices. ''' vertices_to_keep = plane.points_in_front(self.v, inverted=inverted, ret_indices=True) self.keep_vertices(vertices_to_keep) return vertices_to_keep
[ "def", "cut_by_plane", "(", "self", ",", "plane", ",", "inverted", "=", "False", ")", ":", "vertices_to_keep", "=", "plane", ".", "points_in_front", "(", "self", ".", "v", ",", "inverted", "=", "inverted", ",", "ret_indices", "=", "True", ")", "self", "....
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 the kept vertices.
[ "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", ")", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L253-L269
bodylabs/lace
lace/geometry.py
MeshMixin.surface_areas
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], e_1[:, 2]*e_2[:, 0] - e_1[:, 0]*e_2[:, 2], e_1[:, 0]*e_2[:, 1] - e_1[:, 1]*e_2[:, 0]]).T return (0.5)*((cross_products**2.).sum(axis=1)**0.5)
python
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], e_1[:, 2]*e_2[:, 0] - e_1[:, 0]*e_2[:, 2], e_1[:, 0]*e_2[:, 1] - e_1[:, 1]*e_2[:, 0]]).T return (0.5)*((cross_products**2.).sum(axis=1)**0.5)
[ "def", "surface_areas", "(", "self", ")", ":", "e_1", "=", "self", ".", "v", "[", "self", ".", "f", "[", ":", ",", "1", "]", "]", "-", "self", ".", "v", "[", "self", ".", "f", "[", ":", ",", "0", "]", "]", "e_2", "=", "self", ".", "v", ...
returns the surface area of each face
[ "returns", "the", "surface", "area", "of", "each", "face" ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L279-L290
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
purge_items
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 in keys: if env.traceability_all_items[key]['docname'] == docname: del env.traceability_all_items[key]
python
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 in keys: if env.traceability_all_items[key]['docname'] == docname: del env.traceability_all_items[key]
[ "def", "purge_items", "(", "app", ",", "env", ",", "docname", ")", ":", "keys", "=", "list", "(", "env", ".", "traceability_all_items", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "if", "env", ".", "traceability_all_items", "[", "key",...
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.
[ "Clean", "if", "existing", "item", "entries", "in", "traceability_all_items", "environment", "variable", "for", "all", "the", "source", "docs", "being", "purged", "." ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L212-L223
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
process_item_nodes
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(env.traceability_all_items, key=naturalsortkey) # Item matrix: # Create table with related items, printing their target references. # Only source and target items matching respective regexp shall be included for node in doctree.traverse(item_matrix): table = nodes.table() tgroup = nodes.tgroup() left_colspec = nodes.colspec(colwidth=5) right_colspec = nodes.colspec(colwidth=5) tgroup += [left_colspec, right_colspec] tgroup += nodes.thead('', nodes.row( '', nodes.entry('', nodes.paragraph('', 'Source')), nodes.entry('', nodes.paragraph('', 'Target')))) tbody = nodes.tbody() tgroup += tbody table += tgroup for source_item in all_items: if re.match(node['source'], source_item): row = nodes.row() left = nodes.entry() left += make_item_ref(app, env, fromdocname, env.traceability_all_items[source_item]) right = nodes.entry() for target_item in all_items: if (re.match(node['target'], target_item) and are_related( env, source_item, target_item, node['type'])): right += make_item_ref( app, env, fromdocname, env.traceability_all_items[target_item]) row += left row += right tbody += row node.replace_self(table) # Item list: # Create list with target references. Only items matching list regexp # shall be included for node in doctree.traverse(item_list): content = nodes.bullet_list() for item in all_items: if re.match(node['filter'], item): bullet_list_item = nodes.list_item() paragraph = nodes.paragraph() paragraph.append( make_item_ref(app, env, fromdocname, env.traceability_all_items[item])) bullet_list_item.append(paragraph) content.append(bullet_list_item) node.replace_self(content) # Resolve item cross references (from ``item`` role) for node in doctree.traverse(pending_item_xref): # Create a dummy reference to be used if target reference fails new_node = make_refnode(app.builder, fromdocname, fromdocname, 'ITEM_NOT_FOUND', node[0].deepcopy(), node['reftarget'] + '??') # If target exists, try to create the reference if node['reftarget'] in env.traceability_all_items: item_info = env.traceability_all_items[node['reftarget']] try: new_node = make_refnode(app.builder, fromdocname, item_info['docname'], item_info['target']['refid'], node[0].deepcopy(), node['reftarget']) except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass else: env.warn_node( 'Traceability: item %s not found' % node['reftarget'], node) node.replace_self(new_node)
python
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(env.traceability_all_items, key=naturalsortkey) # Item matrix: # Create table with related items, printing their target references. # Only source and target items matching respective regexp shall be included for node in doctree.traverse(item_matrix): table = nodes.table() tgroup = nodes.tgroup() left_colspec = nodes.colspec(colwidth=5) right_colspec = nodes.colspec(colwidth=5) tgroup += [left_colspec, right_colspec] tgroup += nodes.thead('', nodes.row( '', nodes.entry('', nodes.paragraph('', 'Source')), nodes.entry('', nodes.paragraph('', 'Target')))) tbody = nodes.tbody() tgroup += tbody table += tgroup for source_item in all_items: if re.match(node['source'], source_item): row = nodes.row() left = nodes.entry() left += make_item_ref(app, env, fromdocname, env.traceability_all_items[source_item]) right = nodes.entry() for target_item in all_items: if (re.match(node['target'], target_item) and are_related( env, source_item, target_item, node['type'])): right += make_item_ref( app, env, fromdocname, env.traceability_all_items[target_item]) row += left row += right tbody += row node.replace_self(table) # Item list: # Create list with target references. Only items matching list regexp # shall be included for node in doctree.traverse(item_list): content = nodes.bullet_list() for item in all_items: if re.match(node['filter'], item): bullet_list_item = nodes.list_item() paragraph = nodes.paragraph() paragraph.append( make_item_ref(app, env, fromdocname, env.traceability_all_items[item])) bullet_list_item.append(paragraph) content.append(bullet_list_item) node.replace_self(content) # Resolve item cross references (from ``item`` role) for node in doctree.traverse(pending_item_xref): # Create a dummy reference to be used if target reference fails new_node = make_refnode(app.builder, fromdocname, fromdocname, 'ITEM_NOT_FOUND', node[0].deepcopy(), node['reftarget'] + '??') # If target exists, try to create the reference if node['reftarget'] in env.traceability_all_items: item_info = env.traceability_all_items[node['reftarget']] try: new_node = make_refnode(app.builder, fromdocname, item_info['docname'], item_info['target']['refid'], node[0].deepcopy(), node['reftarget']) except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass else: env.warn_node( 'Traceability: item %s not found' % node['reftarget'], node) node.replace_self(new_node)
[ "def", "process_item_nodes", "(", "app", ",", "doctree", ",", "fromdocname", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "all_items", "=", "sorted", "(", "env", ".", "traceability_all_items", ",", "key", "=", "naturalsortkey", ")", "# Item matri...
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.
[ "This", "function", "should", "be", "triggered", "upon", "doctree", "-", "resolved", "event" ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L226-L319
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
update_available_item_relationships
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 initialization, before processing any directive. Function also sets an environment variable ``relationships`` with the full list of relationships (with reverse relationships also as keys) """ env = app.builder.env env.relationships = {} for rel in list(app.config.traceability_relationships.keys()): env.relationships[rel] = app.config.traceability_relationships[rel] env.relationships[app.config.traceability_relationships[rel]] = rel for rel in sorted(list(env.relationships.keys())): ItemDirective.option_spec[rel] = directives.unchanged
python
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 initialization, before processing any directive. Function also sets an environment variable ``relationships`` with the full list of relationships (with reverse relationships also as keys) """ env = app.builder.env env.relationships = {} for rel in list(app.config.traceability_relationships.keys()): env.relationships[rel] = app.config.traceability_relationships[rel] env.relationships[app.config.traceability_relationships[rel]] = rel for rel in sorted(list(env.relationships.keys())): ItemDirective.option_spec[rel] = directives.unchanged
[ "def", "update_available_item_relationships", "(", "app", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "env", ".", "relationships", "=", "{", "}", "for", "rel", "in", "list", "(", "app", ".", "config", ".", "traceability_relationships", ".", "k...
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. Function also sets an environment variable ``relationships`` with the full list of relationships (with reverse relationships also as keys)
[ "Update", "directive", "option_spec", "with", "custom", "relationships", "defined", "in", "configuration", "file", "traceability_relationships", "variable", ".", "Both", "keys", "(", "relationships", ")", "and", "values", "(", "reverse", "relationships", ")", "are", ...
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L322-L344
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
initialize_environment
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_item_relationships(app)
python
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_item_relationships(app)
[ "def", "initialize_environment", "(", "app", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "# Assure ``traceability_all_items`` will always be there.", "if", "not", "hasattr", "(", "env", ",", "'traceability_all_items'", ")", ":", "env", ".", "traceabilit...
Perform initializations needed before the build process starts.
[ "Perform", "initializations", "needed", "before", "the", "build", "process", "starts", "." ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L347-L357
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
make_item_ref
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: caption = '' para = nodes.paragraph() newnode = nodes.reference('', '') innernode = nodes.emphasis(id + caption, id + caption) newnode['refdocname'] = item_info['docname'] try: newnode['refuri'] = app.builder.get_relative_uri(fromdocname, item_info['docname']) newnode['refuri'] += '#' + id except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass newnode.append(innernode) para += newnode return para
python
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: caption = '' para = nodes.paragraph() newnode = nodes.reference('', '') innernode = nodes.emphasis(id + caption, id + caption) newnode['refdocname'] = item_info['docname'] try: newnode['refuri'] = app.builder.get_relative_uri(fromdocname, item_info['docname']) newnode['refuri'] += '#' + id except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass newnode.append(innernode) para += newnode return para
[ "def", "make_item_ref", "(", "app", ",", "env", ",", "fromdocname", ",", "item_info", ")", ":", "id", "=", "item_info", "[", "'target'", "]", "[", "'refid'", "]", "if", "item_info", "[", "'caption'", "]", "!=", "''", ":", "caption", "=", "', '", "+", ...
Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists.
[ "Creates", "a", "reference", "node", "for", "an", "item", "embedded", "in", "a", "paragraph", ".", "Reference", "text", "adds", "also", "a", "caption", "if", "it", "exists", "." ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L363-L390
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
naturalsortkey
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
python
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
[ "def", "naturalsortkey", "(", "s", ")", ":", "return", "[", "int", "(", "part", ")", "if", "part", ".", "isdigit", "(", ")", "else", "part", "for", "part", "in", "re", ".", "split", "(", "'([0-9]+)'", ",", "s", ")", "]" ]
Natural sort order
[ "Natural", "sort", "order" ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L393-L396
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
are_related
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 to be considered. """ if not relationships: relationships = list(env.relationships.keys()) for rel in relationships: if (target in env.traceability_all_items[source][rel] or source in env.traceability_all_items[target][env.relationships[rel]]): return True return False
python
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 to be considered. """ if not relationships: relationships = list(env.relationships.keys()) for rel in relationships: if (target in env.traceability_all_items[source][rel] or source in env.traceability_all_items[target][env.relationships[rel]]): return True return False
[ "def", "are_related", "(", "env", ",", "source", ",", "target", ",", "relationships", ")", ":", "if", "not", "relationships", ":", "relationships", "=", "list", "(", "env", ".", "relationships", ".", "keys", "(", ")", ")", "for", "rel", "in", "relationsh...
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.
[ "Returns", "True", "if", "source", "and", "target", "items", "are", "related", "according", "a", "list", "relationships", "of", "relationship", "types", ".", "False", "is", "returned", "otherwise" ]
train
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L399-L418
bodylabs/lace
lace/meshviewer.py
MeshViewer
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 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 static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=(1, 1), uid=uid, titlebar=titlebar, keepalive=keepalive, window_width=window_width, window_height=window_height ) result = mv.get_subwindows()[0][0] result.snapshot_camera = snapshot_camera if static_meshes: result.static_meshes = static_meshes if static_lines: result.static_lines = static_lines result.autorecenter = autorecenter return result
python
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 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 static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=(1, 1), uid=uid, titlebar=titlebar, keepalive=keepalive, window_width=window_width, window_height=window_height ) result = mv.get_subwindows()[0][0] result.snapshot_camera = snapshot_camera if static_meshes: result.static_meshes = static_meshes if static_lines: result.static_lines = static_lines result.autorecenter = autorecenter return result
[ "def", "MeshViewer", "(", "titlebar", "=", "'Mesh Viewer'", ",", "static_meshes", "=", "None", ",", "static_lines", "=", "None", ",", "uid", "=", "None", ",", "autorecenter", "=", "True", ",", "keepalive", "=", "False", ",", "window_width", "=", "1280", ",...
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 static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons.
[ "Allows", "visual", "inspection", "of", "geometric", "primitives", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L87-L120
bodylabs/lace
lace/meshviewer.py
MeshViewers
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: a list of lists of MeshViewer objects: one per window requested. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive, window_width=window_width, window_height=window_height ) return mv.get_subwindows()
python
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: a list of lists of MeshViewer objects: one per window requested. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive, window_width=window_width, window_height=window_height ) return mv.get_subwindows()
[ "def", "MeshViewers", "(", "shape", "=", "(", "1", ",", "1", ")", ",", "titlebar", "=", "\"Mesh Viewers\"", ",", "keepalive", "=", "False", ",", "window_width", "=", "1280", ",", "window_height", "=", "960", ")", ":", "if", "not", "test_for_opengl", "(",...
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.
[ "Allows", "subplot", "-", "style", "inspection", "of", "primitives", "in", "multiple", "subwindows", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L123-L140
bodylabs/lace
lace/meshviewer.py
MeshViewerRemote.on_drag
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 self.isdragging: mouse_pt = arcball.Point2fT(cursor_x, cursor_y) # Update End Vector And Get Rotation As Quaternion ThisQuat = self.arcball.drag(mouse_pt) # Convert Quaternion Into Matrix3fT self.thisrot = arcball.Matrix3fSetRotationFromQuat4f(ThisQuat) # Use correct Linear Algebra matrix multiplication C = A * B # Accumulate Last Rotation Into This One self.thisrot = arcball.Matrix3fMulMatrix3f(self.lastrot, self.thisrot) # make sure it is a rotation self.thisrot = as_rotation_matrix(self.thisrot) # Set Our Final Transform's Rotation From This One self.transform = arcball.Matrix4fSetRotationFromMatrix3f(self.transform, self.thisrot) glut.glutPostRedisplay() return
python
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 self.isdragging: mouse_pt = arcball.Point2fT(cursor_x, cursor_y) # Update End Vector And Get Rotation As Quaternion ThisQuat = self.arcball.drag(mouse_pt) # Convert Quaternion Into Matrix3fT self.thisrot = arcball.Matrix3fSetRotationFromQuat4f(ThisQuat) # Use correct Linear Algebra matrix multiplication C = A * B # Accumulate Last Rotation Into This One self.thisrot = arcball.Matrix3fMulMatrix3f(self.lastrot, self.thisrot) # make sure it is a rotation self.thisrot = as_rotation_matrix(self.thisrot) # Set Our Final Transform's Rotation From This One self.transform = arcball.Matrix4fSetRotationFromMatrix3f(self.transform, self.thisrot) glut.glutPostRedisplay() return
[ "def", "on_drag", "(", "self", ",", "cursor_x", ",", "cursor_y", ")", ":", "from", "blmath", ".", "geometry", ".", "transform", ".", "rodrigues", "import", "as_rotation_matrix", "if", "self", ".", "isdragging", ":", "mouse_pt", "=", "arcball", ".", "Point2fT...
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.
[ "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", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L805-L825
bodylabs/lace
lace/meshviewer.py
MeshViewerRemote.on_click
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: # Left button released self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One elif button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_DOWN: # Left button clicked down self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One self.isdragging = True # Prepare For Dragging mouse_pt = arcball.Point2fT(cursor_x, cursor_y) self.arcball.click(mouse_pt) # Update Start Vector And Prepare For Dragging elif button == glut.GLUT_RIGHT_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y) elif button == glut.GLUT_MIDDLE_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y, button='middle') glut.glutPostRedisplay()
python
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: # Left button released self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One elif button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_DOWN: # Left button clicked down self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One self.isdragging = True # Prepare For Dragging mouse_pt = arcball.Point2fT(cursor_x, cursor_y) self.arcball.click(mouse_pt) # Update Start Vector And Prepare For Dragging elif button == glut.GLUT_RIGHT_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y) elif button == glut.GLUT_MIDDLE_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y, button='middle') glut.glutPostRedisplay()
[ "def", "on_click", "(", "self", ",", "button", ",", "button_state", ",", "cursor_x", ",", "cursor_y", ")", ":", "self", ".", "isdragging", "=", "False", "if", "button", "==", "glut", ".", "GLUT_LEFT_BUTTON", "and", "button_state", "==", "glut", ".", "GLUT_...
Mouse button clicked. Glut calls this function when a mouse button is clicked or released.
[ "Mouse", "button", "clicked", ".", "Glut", "calls", "this", "function", "when", "a", "mouse", "button", "is", "clicked", "or", "released", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L840-L869
nschloe/meshplex
meshplex/mesh_tetra.py
MeshTetra._compute_cell_circumcenters
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 distances (cfd): # # CC = ( # + cfd[0] * face_area[0] / sum(cfd*face_area) * X[0] # + cfd[1] * face_area[1] / sum(cfd*face_area) * X[1] # + cfd[2] * face_area[2] / sum(cfd*face_area) * X[2] # + cfd[3] * face_area[3] / sum(cfd*face_area) * X[3] # ) # # (Compare with # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>.) # Because of # # cfd = zeta / (24.0 * face_areas) / self.cell_volumes[None] # # we have # # CC = sum_k (zeta[k] / sum(zeta) * X[k]). # alpha = self._zeta / numpy.sum(self._zeta, axis=0) self._circumcenters = numpy.sum( alpha[None].T * self.node_coords[self.cells["nodes"]], axis=1 ) return
python
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 distances (cfd): # # CC = ( # + cfd[0] * face_area[0] / sum(cfd*face_area) * X[0] # + cfd[1] * face_area[1] / sum(cfd*face_area) * X[1] # + cfd[2] * face_area[2] / sum(cfd*face_area) * X[2] # + cfd[3] * face_area[3] / sum(cfd*face_area) * X[3] # ) # # (Compare with # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>.) # Because of # # cfd = zeta / (24.0 * face_areas) / self.cell_volumes[None] # # we have # # CC = sum_k (zeta[k] / sum(zeta) * X[k]). # alpha = self._zeta / numpy.sum(self._zeta, axis=0) self._circumcenters = numpy.sum( alpha[None].T * self.node_coords[self.cells["nodes"]], axis=1 ) return
[ "def", "_compute_cell_circumcenters", "(", "self", ")", ":", "# Just like for triangular cells, tetrahedron circumcenters are most easily", "# computed with the quadrilateral coordinates available.", "# Luckily, we have the circumcenter-face distances (cfd):", "#", "# CC = (", "# + cfd...
Computes the center of the circumsphere of each cell.
[ "Computes", "the", "center", "of", "the", "circumsphere", "of", "each", "cell", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tetra.py#L187-L216
nschloe/meshplex
meshplex/mesh_tetra.py
MeshTetra.control_volumes
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 # Explicitly sum up contributions per cell first. Makes # numpy.add.at faster. # For every node k (range(4)), check for which edges k appears in # local_idx, and sum() up the v's from there. idx = self.local_idx vals = numpy.array( [ sum([v[i, j] for i, j in zip(*numpy.where(idx == k)[1:])]) for k in range(4) ] ).T # self._control_volumes = numpy.zeros(len(self.node_coords)) numpy.add.at(self._control_volumes, self.cells["nodes"], vals) return self._control_volumes
python
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 # Explicitly sum up contributions per cell first. Makes # numpy.add.at faster. # For every node k (range(4)), check for which edges k appears in # local_idx, and sum() up the v's from there. idx = self.local_idx vals = numpy.array( [ sum([v[i, j] for i, j in zip(*numpy.where(idx == k)[1:])]) for k in range(4) ] ).T # self._control_volumes = numpy.zeros(len(self.node_coords)) numpy.add.at(self._control_volumes, self.cells["nodes"], vals) return self._control_volumes
[ "def", "control_volumes", "(", "self", ")", ":", "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", ...
Compute the control volumes of all nodes in the mesh.
[ "Compute", "the", "control", "volumes", "of", "all", "nodes", "in", "the", "mesh", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tetra.py#L429-L450
nschloe/meshplex
meshplex/mesh_tetra.py
MeshTetra.show_edge
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 plt if "faces" not in self.cells: self.create_cell_face_relationships() if "edges" not in self.faces: self.create_face_edge_relationships() fig = plt.figure() ax = fig.gca(projection=Axes3D.name) plt.axis("equal") # find all faces with this edge adj_face_ids = numpy.where((self.faces["edges"] == edge_id).any(axis=1))[0] # find all cells with the faces # https://stackoverflow.com/a/38481969/353337 adj_cell_ids = numpy.where( numpy.in1d(self.cells["faces"], adj_face_ids) .reshape(self.cells["faces"].shape) .any(axis=1) )[0] # plot all those adjacent cells; first collect all edges adj_edge_ids = numpy.unique( [ adj_edge_id for adj_cell_id in adj_cell_ids for face_id in self.cells["faces"][adj_cell_id] for adj_edge_id in self.faces["edges"][face_id] ] ) col = "k" for adj_edge_id in adj_edge_ids: x = self.node_coords[self.edges["nodes"][adj_edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], col) # make clear which is edge_id x = self.node_coords[self.edges["nodes"][edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], color=col, linewidth=3.0) # connect the face circumcenters with the corresponding cell # circumcenters X = self.node_coords for cell_id in adj_cell_ids: cc = self._circumcenters[cell_id] # x = X[self.node_face_cells[..., [cell_id]]] face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei, self.ei_dot_ej) # draw the face circumcenters ax.plot( face_ccs[..., 0].flatten(), face_ccs[..., 1].flatten(), face_ccs[..., 2].flatten(), "go", ) # draw the connections # tet circumcenter---face circumcenter for face_cc in face_ccs: ax.plot( [cc[..., 0], face_cc[..., 0]], [cc[..., 1], face_cc[..., 1]], [cc[..., 2], face_cc[..., 2]], "b-", ) # draw the cell circumcenters cc = self._circumcenters[adj_cell_ids] ax.plot(cc[:, 0], cc[:, 1], cc[:, 2], "ro") return
python
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 plt if "faces" not in self.cells: self.create_cell_face_relationships() if "edges" not in self.faces: self.create_face_edge_relationships() fig = plt.figure() ax = fig.gca(projection=Axes3D.name) plt.axis("equal") # find all faces with this edge adj_face_ids = numpy.where((self.faces["edges"] == edge_id).any(axis=1))[0] # find all cells with the faces # https://stackoverflow.com/a/38481969/353337 adj_cell_ids = numpy.where( numpy.in1d(self.cells["faces"], adj_face_ids) .reshape(self.cells["faces"].shape) .any(axis=1) )[0] # plot all those adjacent cells; first collect all edges adj_edge_ids = numpy.unique( [ adj_edge_id for adj_cell_id in adj_cell_ids for face_id in self.cells["faces"][adj_cell_id] for adj_edge_id in self.faces["edges"][face_id] ] ) col = "k" for adj_edge_id in adj_edge_ids: x = self.node_coords[self.edges["nodes"][adj_edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], col) # make clear which is edge_id x = self.node_coords[self.edges["nodes"][edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], color=col, linewidth=3.0) # connect the face circumcenters with the corresponding cell # circumcenters X = self.node_coords for cell_id in adj_cell_ids: cc = self._circumcenters[cell_id] # x = X[self.node_face_cells[..., [cell_id]]] face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei, self.ei_dot_ej) # draw the face circumcenters ax.plot( face_ccs[..., 0].flatten(), face_ccs[..., 1].flatten(), face_ccs[..., 2].flatten(), "go", ) # draw the connections # tet circumcenter---face circumcenter for face_cc in face_ccs: ax.plot( [cc[..., 0], face_cc[..., 0]], [cc[..., 1], face_cc[..., 1]], [cc[..., 2], face_cc[..., 2]], "b-", ) # draw the cell circumcenters cc = self._circumcenters[adj_cell_ids] ax.plot(cc[:, 0], cc[:, 1], cc[:, 2], "ro") return
[ "def", "show_edge", "(", "self", ",", "edge_id", ")", ":", "# pylint: disable=unused-variable,relative-import", "from", "mpl_toolkits", ".", "mplot3d", "import", "Axes3D", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "\"faces\"", "not", "in", "self",...
Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int
[ "Displays", "edge", "with", "ce_ratio", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tetra.py#L504-L579
openspending/babbage
babbage/util.py
parse_int
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: return fallback except ValueError: return fallback
python
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: return fallback except ValueError: return fallback
[ "def", "parse_int", "(", "text", ",", "fallback", "=", "None", ")", ":", "try", ":", "if", "isinstance", "(", "text", ",", "six", ".", "integer_types", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "six", ".", "string_types", ")",...
Try to extract an integer from a string, return the fallback if that's not possible.
[ "Try", "to", "extract", "an", "integer", "from", "a", "string", "return", "the", "fallback", "if", "that", "s", "not", "possible", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/util.py#L7-L18
openspending/babbage
babbage/cube.py
Cube._load_table
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, table=name) table = Table(name, self.meta, autoload=True) self._tables[name] = table return table
python
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, table=name) table = Table(name, self.meta, autoload=True) self._tables[name] = table return table
[ "def", "_load_table", "(", "self", ",", "name", ")", ":", "table", "=", "self", ".", "_tables", ".", "get", "(", "name", ",", "None", ")", "if", "table", "is", "not", "None", ":", "return", "table", "if", "not", "self", ".", "engine", ".", "has_tab...
Reflect a given table from the database.
[ "Reflect", "a", "given", "table", "from", "the", "database", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L30-L40
openspending/babbage
babbage/cube.py
Cube.fact_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 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]
python
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", "fact_pk", "(", "self", ")", ":", "keys", "=", "[", "c", "for", "c", "in", "self", ".", "fact_table", ".", "columns", "if", "c", ".", "primary_key", "]", "return", "keys", "[", "0", "]" ]
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.
[ "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", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L43-L49
openspending/babbage
babbage/cube.py
Cube.aggregate
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 also be filtered and sorted. """ def prep(cuts, drilldowns=False, aggregates=False, columns=None): q = select(columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) attributes = None if drilldowns is not False: attributes, q, bindings = Drilldowns(self).apply( q, bindings, drilldowns ) if aggregates is not False: aggregates, q, bindings = Aggregates(self).apply( q, bindings, aggregates ) q = self.restrict_joins(q, bindings) return q, bindings, attributes, aggregates, cuts # Count count = count_results(self, prep(cuts, drilldowns=drilldowns, columns=[1])[0]) # Summary summary = first_result(self, prep(cuts, aggregates=aggregates)[0].limit(1)) # Results q, bindings, attributes, aggregates, cuts = \ prep(cuts, drilldowns=drilldowns, aggregates=aggregates) page, q = Pagination(self).apply(q, page, page_size, page_max) ordering, q, bindings = Ordering(self).apply(q, bindings, order) q = self.restrict_joins(q, bindings) cells = list(generate_results(self, q)) return { 'total_cell_count': count, 'cells': cells, 'summary': summary, 'cell': cuts, 'aggregates': aggregates, 'attributes': attributes, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
python
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 also be filtered and sorted. """ def prep(cuts, drilldowns=False, aggregates=False, columns=None): q = select(columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) attributes = None if drilldowns is not False: attributes, q, bindings = Drilldowns(self).apply( q, bindings, drilldowns ) if aggregates is not False: aggregates, q, bindings = Aggregates(self).apply( q, bindings, aggregates ) q = self.restrict_joins(q, bindings) return q, bindings, attributes, aggregates, cuts # Count count = count_results(self, prep(cuts, drilldowns=drilldowns, columns=[1])[0]) # Summary summary = first_result(self, prep(cuts, aggregates=aggregates)[0].limit(1)) # Results q, bindings, attributes, aggregates, cuts = \ prep(cuts, drilldowns=drilldowns, aggregates=aggregates) page, q = Pagination(self).apply(q, page, page_size, page_max) ordering, q, bindings = Ordering(self).apply(q, bindings, order) q = self.restrict_joins(q, bindings) cells = list(generate_results(self, q)) return { 'total_cell_count': count, 'cells': cells, 'summary': summary, 'cell': cuts, 'aggregates': aggregates, 'attributes': attributes, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
[ "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 also be filtered and sorted.
[ "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", ...
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L60-L117
openspending/babbage
babbage/cube.py
Cube.members
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 = select(columns=columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) fields, q, bindings = \ Fields(self).apply(q, bindings, ref, distinct=True) ordering, q, bindings = \ Ordering(self).apply(q, bindings, order, distinct=fields[0]) q = self.restrict_joins(q, bindings) return q, bindings, cuts, fields, ordering # Count count = count_results(self, prep(cuts, ref, order, [1])[0]) # Member list q, bindings, cuts, fields, ordering = prep(cuts, ref, order) page, q = Pagination(self).apply(q, page, page_size) q = self.restrict_joins(q, bindings) return { 'total_member_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
python
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 = select(columns=columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) fields, q, bindings = \ Fields(self).apply(q, bindings, ref, distinct=True) ordering, q, bindings = \ Ordering(self).apply(q, bindings, order, distinct=fields[0]) q = self.restrict_joins(q, bindings) return q, bindings, cuts, fields, ordering # Count count = count_results(self, prep(cuts, ref, order, [1])[0]) # Member list q, bindings, cuts, fields, ordering = prep(cuts, ref, order) page, q = Pagination(self).apply(q, page, page_size) q = self.restrict_joins(q, bindings) return { 'total_member_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
[ "def", "members", "(", "self", ",", "ref", ",", "cuts", "=", "None", ",", "order", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ")", ":", "def", "prep", "(", "cuts", ",", "ref", ",", "order", ",", "columns", "=", "None", ...
List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned.
[ "List", "all", "the", "distinct", "members", "of", "the", "given", "reference", "filtered", "and", "paginated", ".", "If", "the", "reference", "describes", "a", "dimension", "all", "attributes", "are", "returned", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L119-L149
openspending/babbage
babbage/cube.py
Cube.facts
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.fact_table) bindings = [] _, q, bindings = Cuts(self).apply(q, bindings, cuts) q = self.restrict_joins(q, bindings) return q, bindings # Count count = count_results(self, prep(cuts, [1])[0]) # Facts q, bindings = prep(cuts) fields, q, bindings = Fields(self).apply(q, bindings, fields) ordering, q, bindings = Ordering(self).apply(q, bindings, order) page, q = Pagination(self).apply(q, page, page_size, page_max) q = self.restrict_joins(q, bindings) return { 'total_fact_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
python
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.fact_table) bindings = [] _, q, bindings = Cuts(self).apply(q, bindings, cuts) q = self.restrict_joins(q, bindings) return q, bindings # Count count = count_results(self, prep(cuts, [1])[0]) # Facts q, bindings = prep(cuts) fields, q, bindings = Fields(self).apply(q, bindings, fields) ordering, q, bindings = Ordering(self).apply(q, bindings, order) page, q = Pagination(self).apply(q, page, page_size, page_max) q = self.restrict_joins(q, bindings) return { 'total_fact_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
[ "def", "facts", "(", "self", ",", "fields", "=", "None", ",", "cuts", "=", "None", ",", "order", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "page_max", "=", "None", ")", ":", "def", "prep", "(", "cuts", ",", "colum...
List all facts in the cube, returning only the specified references if these are specified.
[ "List", "all", "facts", "in", "the", "cube", "returning", "only", "the", "specified", "references", "if", "these", "are", "specified", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L151-L180
openspending/babbage
babbage/cube.py
Cube.compute_cardinalities
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.ref, page_size=0) dimension.spec['cardinality'] = result.get('total_member_count')
python
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.ref, page_size=0) dimension.spec['cardinality'] = result.get('total_member_count')
[ "def", "compute_cardinalities", "(", "self", ")", ":", "for", "dimension", "in", "self", ".", "model", ".", "dimensions", ":", "result", "=", "self", ".", "members", "(", "dimension", ".", "ref", ",", "page_size", "=", "0", ")", "dimension", ".", "spec",...
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.
[ "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", "comp...
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L182-L188
openspending/babbage
babbage/cube.py
Cube.restrict_joins
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 referenced, this ensures their returned rows are connected via the fact table. """ if len(q.froms) == 1: return q else: for binding in bindings: if binding.table == self.fact_table: continue concept = self.model[binding.ref] if isinstance(concept, Dimension): dimension = concept else: dimension = concept.dimension dimension_table, key_col = dimension.key_attribute.bind(self) if binding.table != dimension_table: raise BindingException('Attributes must be of same table as ' 'as their dimension key') join_column_name = dimension.join_column_name if isinstance(join_column_name, string_types): try: join_column = self.fact_table.columns[join_column_name] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name, dimension)) else: if not isinstance(join_column_name, list) or len(join_column_name) != 2: raise BindingException("Join column '%s' for %r should be either a string or a 2-tuple." % (join_column_name, dimension)) try: join_column = self.fact_table.columns[join_column_name[0]] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name[0], dimension)) try: key_col = dimension_table.columns[join_column_name[1]] except KeyError: raise BindingException("Join column '%s' for %r not in dimension table." % (dimension.join_column_name[1], dimension)) q = q.where(join_column == key_col) return q
python
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 referenced, this ensures their returned rows are connected via the fact table. """ if len(q.froms) == 1: return q else: for binding in bindings: if binding.table == self.fact_table: continue concept = self.model[binding.ref] if isinstance(concept, Dimension): dimension = concept else: dimension = concept.dimension dimension_table, key_col = dimension.key_attribute.bind(self) if binding.table != dimension_table: raise BindingException('Attributes must be of same table as ' 'as their dimension key') join_column_name = dimension.join_column_name if isinstance(join_column_name, string_types): try: join_column = self.fact_table.columns[join_column_name] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name, dimension)) else: if not isinstance(join_column_name, list) or len(join_column_name) != 2: raise BindingException("Join column '%s' for %r should be either a string or a 2-tuple." % (join_column_name, dimension)) try: join_column = self.fact_table.columns[join_column_name[0]] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name[0], dimension)) try: key_col = dimension_table.columns[join_column_name[1]] except KeyError: raise BindingException("Join column '%s' for %r not in dimension table." % (dimension.join_column_name[1], dimension)) q = q.where(join_column == key_col) return q
[ "def", "restrict_joins", "(", "self", ",", "q", ",", "bindings", ")", ":", "if", "len", "(", "q", ".", "froms", ")", "==", "1", ":", "return", "q", "else", ":", "for", "binding", "in", "bindings", ":", "if", "binding", ".", "table", "==", "self", ...
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 connected via the fact table.
[ "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", ...
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L190-L237
pinax/pinax-cli
pinaxcli/utils.py
order_manually
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: del commands[k] # Add commands not present in `order` above for k in commands: ordered.append(commands[k]) return ordered
python
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: del commands[k] # Add commands not present in `order` above for k in commands: ordered.append(commands[k]) return ordered
[ "def", "order_manually", "(", "sub_commands", ")", ":", "order", "=", "[", "\"start\"", ",", "\"projects\"", ",", "]", "ordered", "=", "[", "]", "commands", "=", "dict", "(", "zip", "(", "[", "cmd", "for", "cmd", "in", "sub_commands", "]", ",", "sub_co...
Order sub-commands for display
[ "Order", "sub", "-", "commands", "for", "display" ]
train
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/utils.py#L4-L21
pinax/pinax-cli
pinaxcli/utils.py
format_help
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(' start', bold=True))) help = help.replace(' apps', str(crayons.yellow(' apps', bold=True))) help = help.replace(' demos', str(crayons.yellow(' demos', bold=True))) help = help.replace(' projects', str(crayons.yellow(' projects', bold=True))) help = help.replace(' themes', str(crayons.yellow(' themes', bold=True))) help = help.replace(' tools', str(crayons.yellow(' tools', bold=True))) additional_help = \ """Usage Examples: Create new project based on Pinax 'account' starter project: $ {0} Create new project based on development version of 'blog' starter project $ {6} View all Pinax starter projects: $ {1} View all Pinax demo projects: $ {2} View all Pinax apps: $ {3} View all Pinax tools: $ {4} View all Pinax themes: $ {5} Commands:""".format( crayons.red('pinax start account my_project'), crayons.red('pinax projects'), crayons.red('pinax demos'), crayons.red('pinax apps'), crayons.red('pinax tools'), crayons.red('pinax themes'), crayons.red('pinax start --dev blog my_project') ) help = help.replace('Commands:', additional_help) return help
python
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(' start', bold=True))) help = help.replace(' apps', str(crayons.yellow(' apps', bold=True))) help = help.replace(' demos', str(crayons.yellow(' demos', bold=True))) help = help.replace(' projects', str(crayons.yellow(' projects', bold=True))) help = help.replace(' themes', str(crayons.yellow(' themes', bold=True))) help = help.replace(' tools', str(crayons.yellow(' tools', bold=True))) additional_help = \ """Usage Examples: Create new project based on Pinax 'account' starter project: $ {0} Create new project based on development version of 'blog' starter project $ {6} View all Pinax starter projects: $ {1} View all Pinax demo projects: $ {2} View all Pinax apps: $ {3} View all Pinax tools: $ {4} View all Pinax themes: $ {5} Commands:""".format( crayons.red('pinax start account my_project'), crayons.red('pinax projects'), crayons.red('pinax demos'), crayons.red('pinax apps'), crayons.red('pinax tools'), crayons.red('pinax themes'), crayons.red('pinax start --dev blog my_project') ) help = help.replace('Commands:', additional_help) return help
[ "def", "format_help", "(", "help", ")", ":", "help", "=", "help", ".", "replace", "(", "'Options:'", ",", "str", "(", "crayons", ".", "black", "(", "'Options:'", ",", "bold", "=", "True", ")", ")", ")", "help", "=", "help", ".", "replace", "(", "'U...
Format the help string.
[ "Format", "the", "help", "string", "." ]
train
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/utils.py#L24-L72
scopely-devops/details
details/__init__.py
load
def load(file): """ 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 """ fp = open(file) reader = csv.reader(fp) headers = next(reader) costs = Costs(headers) for line in reader: data = {} for i in range(0, len(headers)): data[headers[i]] = line[i] data['UnBlendedCost'] = decimal.Decimal(data['UnBlendedCost']) data['BlendedCost'] = decimal.Decimal(data['BlendedCost']) costs.add(data) fp.close() return costs
python
def load(file): """ 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 """ fp = open(file) reader = csv.reader(fp) headers = next(reader) costs = Costs(headers) for line in reader: data = {} for i in range(0, len(headers)): data[headers[i]] = line[i] data['UnBlendedCost'] = decimal.Decimal(data['UnBlendedCost']) data['BlendedCost'] = decimal.Decimal(data['BlendedCost']) costs.add(data) fp.close() return costs
[ "def", "load", "(", "file", ")", ":", "fp", "=", "open", "(", "file", ")", "reader", "=", "csv", ".", "reader", "(", "fp", ")", "headers", "=", "next", "(", "reader", ")", "costs", "=", "Costs", "(", "headers", ")", "for", "line", "in", "reader",...
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
[ "This", "function", "expects", "a", "path", "to", "a", "file", "containing", "a", "**", "Detailed", "billing", "report", "with", "resources", "and", "tags", "**", "report", "from", "AWS", "." ]
train
https://github.com/scopely-devops/details/blob/07f2fc7f27b29a6ddcda918abf6ae0882450319e/details/__init__.py#L19-L40
openspending/babbage
babbage/model/model.py
Model.concepts
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 self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dimension.attributes: yield attribute
python
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 self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dimension.attributes: yield attribute
[ "def", "concepts", "(", "self", ")", ":", "for", "measure", "in", "self", ".", "measures", ":", "yield", "measure", "for", "aggregate", "in", "self", ".", "aggregates", ":", "yield", "aggregate", "for", "dimension", "in", "self", ".", "dimensions", ":", ...
Return all existing concepts, i.e. dimensions, measures and attributes within the model.
[ "Return", "all", "existing", "concepts", "i", ".", "e", ".", "dimensions", "measures", "and", "attributes", "within", "the", "model", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/model.py#L60-L70
openspending/babbage
babbage/model/model.py
Model.match
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] if not isinstance(concept, Dimension): return [concept] return [a for a in concept.attributes] except KeyError: return []
python
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] if not isinstance(concept, Dimension): return [concept] return [a for a in concept.attributes] except KeyError: return []
[ "def", "match", "(", "self", ",", "ref", ")", ":", "try", ":", "concept", "=", "self", "[", "ref", "]", "if", "not", "isinstance", "(", "concept", ",", "Dimension", ")", ":", "return", "[", "concept", "]", "return", "[", "a", "for", "a", "in", "c...
Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself.
[ "Get", "all", "concepts", "matching", "this", "ref", ".", "For", "a", "dimension", "that", "is", "all", "its", "attributes", "but", "not", "the", "dimension", "itself", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/model.py#L72-L81
bodylabs/lace
lace/serialization/meshlab_pickedpoints.py
dumps
def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument ''' 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 ''' point_template = '<point x="%f" y="%f" z="%f" name="%s"/>\n' file_template = """ <!DOCTYPE PickedPoints> <PickedPoints> <DocumentData> <DateTime time="16:00:00" date="2014-12-31"/> <User name="bodylabs"/> <DataFileName name="%s"/> </DocumentData> %s </PickedPoints> """ from blmath.numerics import isnumericarray if not isinstance(obj, dict) or not all([isnumericarray(point) for point in obj.itervalues()]): raise ValueError('obj should be a dict of points') points = '\n'.join([point_template % (tuple(xyz) + (name,)) for name, xyz in obj.iteritems()]) return file_template % (mesh_filename, points)
python
def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument ''' 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 ''' point_template = '<point x="%f" y="%f" z="%f" name="%s"/>\n' file_template = """ <!DOCTYPE PickedPoints> <PickedPoints> <DocumentData> <DateTime time="16:00:00" date="2014-12-31"/> <User name="bodylabs"/> <DataFileName name="%s"/> </DocumentData> %s </PickedPoints> """ from blmath.numerics import isnumericarray if not isinstance(obj, dict) or not all([isnumericarray(point) for point in obj.itervalues()]): raise ValueError('obj should be a dict of points') points = '\n'.join([point_template % (tuple(xyz) + (name,)) for name, xyz in obj.iteritems()]) return file_template % (mesh_filename, points)
[ "def", "dumps", "(", "obj", ",", "mesh_filename", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "point_template", "=", "'<point x=\"%f\" y=\"%f\" z=\"%f\" name=\"%s\"/>\\n'", "file_template", "=", "\"\"\"\n <!D...
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
[ "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", ...
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/meshlab_pickedpoints.py#L31-L59
bodylabs/lace
lace/landmarks.py
MeshMixin.landm
def landm(self, val): ''' 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_xyz, given sequential integers as names) - pkl, json, yaml file containing either of the above dicts or arrays ''' import numpy as np if val is None: self._landm = None self._raw_landmarks = None elif isinstance(val, basestring): self.landm = load_landmarks(val) else: if not hasattr(val, 'keys'): val = {str(ii): v for ii, v in enumerate(val)} landm = {} landm_xyz = {} filtered_landmarks = [] for k, v in val.iteritems(): if isinstance(v, (int, long)): landm[k] = v elif len(v) == 3: if np.all(v == [0.0, 0.0, 0.0]): filtered_landmarks.append(k) landm_xyz[k] = v else: raise Exception("Can't parse landmark %s: %s" % (k, v)) if len(filtered_landmarks) > 0: import warnings warnings.warn("WARNING: the following landmarks are positioned at (0.0, 0.0, 0.0) and were ignored: %s" % ", ".join(filtered_landmarks)) # We preserve these and calculate everything seperately so that we can recompute_landmarks if v changes self._raw_landmarks = { 'landm': landm, 'landm_xyz': landm_xyz } self.recompute_landmarks()
python
def landm(self, val): ''' 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_xyz, given sequential integers as names) - pkl, json, yaml file containing either of the above dicts or arrays ''' import numpy as np if val is None: self._landm = None self._raw_landmarks = None elif isinstance(val, basestring): self.landm = load_landmarks(val) else: if not hasattr(val, 'keys'): val = {str(ii): v for ii, v in enumerate(val)} landm = {} landm_xyz = {} filtered_landmarks = [] for k, v in val.iteritems(): if isinstance(v, (int, long)): landm[k] = v elif len(v) == 3: if np.all(v == [0.0, 0.0, 0.0]): filtered_landmarks.append(k) landm_xyz[k] = v else: raise Exception("Can't parse landmark %s: %s" % (k, v)) if len(filtered_landmarks) > 0: import warnings warnings.warn("WARNING: the following landmarks are positioned at (0.0, 0.0, 0.0) and were ignored: %s" % ", ".join(filtered_landmarks)) # We preserve these and calculate everything seperately so that we can recompute_landmarks if v changes self._raw_landmarks = { 'landm': landm, 'landm_xyz': landm_xyz } self.recompute_landmarks()
[ "def", "landm", "(", "self", ",", "val", ")", ":", "import", "numpy", "as", "np", "if", "val", "is", "None", ":", "self", ".", "_landm", "=", "None", "self", ".", "_raw_landmarks", "=", "None", "elif", "isinstance", "(", "val", ",", "basestring", ")"...
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_xyz, given sequential integers as names) - pkl, json, yaml file containing either of the above dicts or arrays
[ "Sets", "landmarks", "given", "any", "of", ":", "-", "ppfile", "-", "ldmk", "file", "-", "dict", "of", "{", "name", ":", "inds", "}", "(", "i", ".", "e", ".", "mesh", ".", "landm", ")", "-", "dict", "of", "{", "name", ":", "xyz", "}", "(", "i...
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/landmarks.py#L92-L133
scopely-devops/details
details/costs.py
Costs.add
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. So ignore it. if lineitem['ProductName']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: self._blended_cost += lineitem['BlendedCost'] if lineitem['UnBlendedCost']: self._unblended_cost += lineitem['UnBlendedCost']
python
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. So ignore it. if lineitem['ProductName']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: self._blended_cost += lineitem['BlendedCost'] if lineitem['UnBlendedCost']: self._unblended_cost += lineitem['UnBlendedCost']
[ "def", "add", "(", "self", ",", "lineitem", ")", ":", "# 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. So ignore it.", "if", "lineitem", "[", "'ProductName'", "]", ":", "self",...
Add a line item record to this Costs object.
[ "Add", "a", "line", "item", "record", "to", "this", "Costs", "object", "." ]
train
https://github.com/scopely-devops/details/blob/07f2fc7f27b29a6ddcda918abf6ae0882450319e/details/costs.py#L73-L85
scopely-devops/details
details/costs.py
Costs.filter
def filter(self, filters): """ 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 that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``. """ subset = Costs(self._columns) filters = [(col, re.compile(regex)) for col, regex in filters] for lineitem in self._lineitems: for filter in filters: if filter[1].search(lineitem[filter[0]]) is None: continue subset.add(lineitem) return subset
python
def filter(self, filters): """ 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 that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``. """ subset = Costs(self._columns) filters = [(col, re.compile(regex)) for col, regex in filters] for lineitem in self._lineitems: for filter in filters: if filter[1].search(lineitem[filter[0]]) is None: continue subset.add(lineitem) return subset
[ "def", "filter", "(", "self", ",", "filters", ")", ":", "subset", "=", "Costs", "(", "self", ".", "_columns", ")", "filters", "=", "[", "(", "col", ",", "re", ".", "compile", "(", "regex", ")", ")", "for", "col", ",", "regex", "in", "filters", "]...
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 that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``.
[ "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", ...
train
https://github.com/scopely-devops/details/blob/07f2fc7f27b29a6ddcda918abf6ae0882450319e/details/costs.py#L95-L118
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.query
def query(self, query, args=None): """ 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 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() log.logger.debug('Running query "%s" with args "%s"', query, args) self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.lastInsertID = self.conn.connection.insert_id() self.rowcount = cursor.rowcount log.logger.debug('Query Resulted in %s affected rows, %s rows returned, %s last insert id', self.affectedRows, self.lastInsertID, self.rowcount) self.record = cursor.fetchall() self.conn.updateCheckTime() except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
python
def query(self, query, args=None): """ 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 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() log.logger.debug('Running query "%s" with args "%s"', query, args) self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.lastInsertID = self.conn.connection.insert_id() self.rowcount = cursor.rowcount log.logger.debug('Query Resulted in %s affected rows, %s rows returned, %s last insert id', self.affectedRows, self.lastInsertID, self.rowcount) self.record = cursor.fetchall() self.conn.updateCheckTime() except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
[ "def", "query", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "self", ".", "affectedRows", "=", "None", "self", ".", "lastError", "=", "None", "cursor", "=", "None", "try", ":", "try", ":", "self", ".", "_GetConnection", "(", ")", ...
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
[ "Execute", "the", "passed", "in", "query", "against", "the", "database" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L74-L114
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.queryOne
def queryOne(self, query, args=None): """ 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 must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.conn.updateCheckTime() while 1: row = cursor.fetchone() if row is None: break else: self.record = row yield row self.rowcount = cursor.rowcount except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: raise StopIteration
python
def queryOne(self, query, args=None): """ 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 must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.conn.updateCheckTime() while 1: row = cursor.fetchone() if row is None: break else: self.record = row yield row self.rowcount = cursor.rowcount except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: raise StopIteration
[ "def", "queryOne", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "self", ".", "affectedRows", "=", "None", "self", ".", "lastError", "=", "None", "cursor", "=", "None", "try", ":", "try", ":", "self", ".", "_GetConnection", "(", ")",...
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 must use %(key)s @author: Nick Verbeck @since: 5/12/2008
[ "Execute", "the", "passed", "in", "query", "against", "the", "database", ".", "Uses", "a", "Generator", "&", "fetchone", "to", "reduce", "your", "process", "memory", "size", "." ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L117-L158
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.queryMany
def queryMany(self, query, args): """ 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 """ self.lastError = None self.affectedRows = None self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.executemany(query, args) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
python
def queryMany(self, query, args): """ 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 """ self.lastError = None self.affectedRows = None self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.executemany(query, args) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
[ "def", "queryMany", "(", "self", ",", "query", ",", "args", ")", ":", "self", ".", "lastError", "=", "None", "self", ".", "affectedRows", "=", "None", "self", ".", "rowcount", "=", "None", "self", ".", "record", "=", "None", "cursor", "=", "None", "t...
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
[ "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", ...
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L161-L194
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.queryMulti
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 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execute query and store results cursor = self.conn.getCursor() for query in queries: self.conn.query = query if query.__class__ == [].__class__: self.affectedRows += cursor.execute(query[0], query[1]) else: self.affectedRows += cursor.execute(query) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
python
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 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execute query and store results cursor = self.conn.getCursor() for query in queries: self.conn.query = query if query.__class__ == [].__class__: self.affectedRows += cursor.execute(query[0], query[1]) else: self.affectedRows += cursor.execute(query) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
[ "def", "queryMulti", "(", "self", ",", "queries", ")", ":", "self", ".", "lastError", "=", "None", "self", ".", "affectedRows", "=", "0", "self", ".", "rowcount", "=", "None", "self", ".", "record", "=", "None", "cursor", "=", "None", "try", ":", "tr...
Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008
[ "Execute", "a", "series", "of", "Deletes", "Inserts", "&", "Updates", "in", "the", "Queires", "List" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L197-L231
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery._GetConnection
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 number of connections, #we wait 1 second and try again. #The Connection is returned locked to be thread safe while self.conn is None: self.conn = Pool().GetConnection(self.connInfo) if self.conn is not None: break else: time.sleep(1)
python
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 number of connections, #we wait 1 second and try again. #The Connection is returned locked to be thread safe while self.conn is None: self.conn = Pool().GetConnection(self.connInfo) if self.conn is not None: break else: time.sleep(1)
[ "def", "_GetConnection", "(", "self", ")", ":", "#Attempt to get a connection. If all connections are in use and we have reached the max number of connections,", "#we wait 1 second and try again.", "#The Connection is returned locked to be thread safe", "while", "self", ".", "conn", "is", ...
Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008
[ "Retieves", "a", "prelocked", "connection", "from", "the", "Pool" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L234-L249
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery._ReturnConnection
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.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
python
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.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
[ "def", "_ReturnConnection", "(", "self", ")", ":", "if", "self", ".", "conn", "is", "not", "None", ":", "if", "self", ".", "connInfo", ".", "commitOnEnd", "is", "True", "or", "self", ".", "commitOnEnd", "is", "True", ":", "self", ".", "conn", ".", "C...
Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008
[ "Returns", "a", "connection", "back", "to", "the", "pool" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L251-L263
openspending/babbage
babbage/model/aggregate.py
Aggregate.bind
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 function: column = getattr(func, self.function)(column) column = column.label(self.ref) column.quote = True return table, column
python
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 function: column = getattr(func, self.function)(column) column = column.label(self.ref) column.quote = True return table, column
[ "def", "bind", "(", "self", ",", "cube", ")", ":", "if", "self", ".", "measure", ":", "table", ",", "column", "=", "self", ".", "measure", ".", "bind", "(", "cube", ")", "else", ":", "table", ",", "column", "=", "cube", ".", "fact_table", ",", "c...
When one column needs to match, use the key.
[ "When", "one", "column", "needs", "to", "match", "use", "the", "key", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/aggregate.py#L22-L32
mandeep/Travis-Encrypt
travis/encrypt.py
retrieve_public_key
def retrieve_public_key(user_repo): """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, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given """ url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.split('/') raise InvalidCredentialsError("Either the username: '{}' or the repository: '{}' does not exist. Please enter a valid username or repository name. The username and repository name are both case sensitive." .format(username, repository))
python
def retrieve_public_key(user_repo): """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, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given """ url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.split('/') raise InvalidCredentialsError("Either the username: '{}' or the repository: '{}' does not exist. Please enter a valid username or repository name. The username and repository name are both case sensitive." .format(username, repository))
[ "def", "retrieve_public_key", "(", "user_repo", ")", ":", "url", "=", "'https://api.travis-ci.org/repos/{}/key'", ".", "format", "(", "user_repo", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "try", ":", "return", "response", ".", "json", "("...
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, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given
[ "Retrieve", "the", "public", "key", "from", "the", "Travis", "API", "." ]
train
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L21-L52
mandeep/Travis-Encrypt
travis/encrypt.py
encrypt_key
def encrypt_key(key, password): """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 then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None)) """ public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
python
def encrypt_key(key, password): """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 then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None)) """ public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
[ "def", "encrypt_key", "(", "key", ",", "password", ")", ":", "public_key", "=", "load_pem_public_key", "(", "key", ".", "encode", "(", ")", ",", "default_backend", "(", ")", ")", "encrypted_password", "=", "public_key", ".", "encrypt", "(", "password", ",", ...
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 then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None))
[ "Encrypt", "the", "password", "with", "the", "public", "key", "and", "return", "an", "ASCII", "representation", "." ]
train
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L55-L86
mandeep/Travis-Encrypt
travis/encrypt.py
dump_travis_configuration
def dump_travis_configuration(config, path): """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: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None """ with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
python
def dump_travis_configuration(config, path): """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: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None """ with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
[ "def", "dump_travis_configuration", "(", "config", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "config_file", ":", "ordered_dump", "(", "config", ",", "config_file", ",", "default_flow_style", "=", "False", ")" ]
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: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None
[ "Dump", "the", "travis", "configuration", "settings", "to", "the", "travis", ".", "yml", "file", "." ]
train
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L111-L130
bodylabs/lace
lace/texture.py
MeshMixin.load_texture
def load_texture(self, texture_version): ''' 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. ''' import numpy as np lowres_tex_template = 's3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_low_v%d.obj' % texture_version highres_tex_template = 's3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_high_v%d.obj' % texture_version from lace.mesh import Mesh from lace.cache import sc mesh_with_texture = Mesh(filename=sc(lowres_tex_template)) if not np.all(mesh_with_texture.f.shape == self.f.shape): mesh_with_texture = Mesh(filename=sc(highres_tex_template)) self.transfer_texture(mesh_with_texture)
python
def load_texture(self, texture_version): ''' 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. ''' import numpy as np lowres_tex_template = 's3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_low_v%d.obj' % texture_version highres_tex_template = 's3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_high_v%d.obj' % texture_version from lace.mesh import Mesh from lace.cache import sc mesh_with_texture = Mesh(filename=sc(lowres_tex_template)) if not np.all(mesh_with_texture.f.shape == self.f.shape): mesh_with_texture = Mesh(filename=sc(highres_tex_template)) self.transfer_texture(mesh_with_texture)
[ "def", "load_texture", "(", "self", ",", "texture_version", ")", ":", "import", "numpy", "as", "np", "lowres_tex_template", "=", "'s3://bodylabs-korper-assets/is/ps/shared/data/body/template/texture_coordinates/textured_template_low_v%d.obj'", "%", "texture_version", "highres_tex_t...
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.
[ "Expect", "a", "texture", "version", "number", "as", "an", "integer", "load", "the", "texture", "version", "from", "/", "is", "/", "ps", "/", "shared", "/", "data", "/", "body", "/", "template", "/", "texture_coordinates", "/", ".", "Currently", "there", ...
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/texture.py#L56-L69
pinax/pinax-cli
pinaxcli/cli.py
show_distribution_section
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(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Release".rjust(7), title)) click.echo("------- ---------------") section = latest_distribution[section_name] names = sorted(section.keys()) for name in names: click.echo("{} {}".format(section[name].rjust(7), name))
python
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(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Release".rjust(7), title)) click.echo("------- ---------------") section = latest_distribution[section_name] names = sorted(section.keys()) for name in names: click.echo("{} {}".format(section[name].rjust(7), name))
[ "def", "show_distribution_section", "(", "config", ",", "title", ",", "section_name", ")", ":", "payload", "=", "requests", ".", "get", "(", "config", ".", "apps_url", ")", ".", "json", "(", ")", "distributions", "=", "sorted", "(", "payload", ".", "keys",...
Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes".
[ "Obtain", "distribution", "data", "and", "display", "latest", "distribution", "section", "i", ".", "e", ".", "demos", "or", "apps", "or", "themes", "." ]
train
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/cli.py#L93-L106
pinax/pinax-cli
pinaxcli/cli.py
validate_django_compatible_with_python
def validate_django_compatible_with_python(): """ 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. """ python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
python
def validate_django_compatible_with_python(): """ 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. """ python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
[ "def", "validate_django_compatible_with_python", "(", ")", ":", "python_version", "=", "sys", ".", "version", "[", ":", "5", "]", "django_version", "=", "django", ".", "get_version", "(", ")", "if", "sys", ".", "version_info", "==", "(", "2", ",", "7", ")"...
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.
[ "Verify", "Django", "1", ".", "11", "is", "present", "if", "Python", "2", ".", "7", "is", "active" ]
train
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/cli.py#L158-L169
pinax/pinax-cli
pinaxcli/cli.py
PinaxGroup.list_commands
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)]
python
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)]
[ "def", "list_commands", "(", "self", ",", "ctx", ")", ":", "commands", "=", "super", "(", "PinaxGroup", ",", "self", ")", ".", "list_commands", "(", "ctx", ")", "return", "[", "cmd", "for", "cmd", "in", "order_manually", "(", "commands", ")", "]" ]
Override for showing commands in particular order
[ "Override", "for", "showing", "commands", "in", "particular", "order" ]
train
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/cli.py#L27-L30
bodylabs/lace
lace/lines.py
Lines.all_edges_with_verts
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) included_vertices[v_indices] = True edges_with_verts = included_vertices[self.e].all(axis=1) if as_boolean: return edges_with_verts return np.nonzero(edges_with_verts)[0]
python
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) included_vertices[v_indices] = True edges_with_verts = included_vertices[self.e].all(axis=1) if as_boolean: return edges_with_verts return np.nonzero(edges_with_verts)[0]
[ "def", "all_edges_with_verts", "(", "self", ",", "v_indices", ",", "as_boolean", "=", "False", ")", ":", "included_vertices", "=", "np", ".", "zeros", "(", "self", ".", "v", ".", "shape", "[", "0", "]", ",", "dtype", "=", "bool", ")", "included_vertices"...
returns all of the faces that contain at least one of the vertices in v_indices
[ "returns", "all", "of", "the", "faces", "that", "contain", "at", "least", "one", "of", "the", "vertices", "in", "v_indices" ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/lines.py#L58-L67
bodylabs/lace
lace/lines.py
Lines.keep_vertices
def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' 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. ''' if self.v is None: return initial_num_verts = self.v.shape[0] if self.e is not None: initial_num_edges = self.e.shape[0] e_indices_to_keep = self.all_edges_with_verts(indices_to_keep, as_boolean=True) self.v = self.v[indices_to_keep] if self.e is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) e_old_to_new = np.zeros(initial_num_edges, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.e = v_old_to_new[self.e[e_indices_to_keep]] e_old_to_new[e_indices_to_keep] = np.arange(self.e.shape[0], dtype=int) else: e_indices_to_keep = [] return np.nonzero(e_indices_to_keep)[0] if ret_kept_edges else self
python
def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' 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. ''' if self.v is None: return initial_num_verts = self.v.shape[0] if self.e is not None: initial_num_edges = self.e.shape[0] e_indices_to_keep = self.all_edges_with_verts(indices_to_keep, as_boolean=True) self.v = self.v[indices_to_keep] if self.e is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) e_old_to_new = np.zeros(initial_num_edges, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.e = v_old_to_new[self.e[e_indices_to_keep]] e_old_to_new[e_indices_to_keep] = np.arange(self.e.shape[0], dtype=int) else: e_indices_to_keep = [] return np.nonzero(e_indices_to_keep)[0] if ret_kept_edges else self
[ "def", "keep_vertices", "(", "self", ",", "indices_to_keep", ",", "ret_kept_edges", "=", "False", ")", ":", "if", "self", ".", "v", "is", "None", ":", "return", "initial_num_verts", "=", "self", ".", "v", ".", "shape", "[", "0", "]", "if", "self", ".",...
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.
[ "Keep", "the", "given", "vertices", "and", "discard", "the", "others", "and", "any", "edges", "to", "which", "they", "may", "belong", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/lines.py#L69-L99
nschloe/meshplex
meshplex/reader.py
read
def read(filename): """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 """ mesh = meshio.read(filename) # make sure to include the used nodes only if "tetra" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["tetra"]) return ( MeshTetra(points, cells), mesh.point_data, mesh.cell_data, mesh.field_data, ) elif "triangle" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["triangle"]) return ( MeshTri(points, cells), mesh.point_data, mesh.cell_data, mesh.field_data, ) else: raise RuntimeError("Unknown mesh type.")
python
def read(filename): """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 """ mesh = meshio.read(filename) # make sure to include the used nodes only if "tetra" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["tetra"]) return ( MeshTetra(points, cells), mesh.point_data, mesh.cell_data, mesh.field_data, ) elif "triangle" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["triangle"]) return ( MeshTri(points, cells), mesh.point_data, mesh.cell_data, mesh.field_data, ) else: raise RuntimeError("Unknown mesh type.")
[ "def", "read", "(", "filename", ")", ":", "mesh", "=", "meshio", ".", "read", "(", "filename", ")", "# make sure to include the used nodes only", "if", "\"tetra\"", "in", "mesh", ".", "cells", ":", "points", ",", "cells", "=", "_sanitize", "(", "mesh", ".", ...
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
[ "Reads", "an", "unstructured", "mesh", "with", "added", "data", "." ]
train
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/reader.py#L26-L57
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.lock
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
python
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
[ "def", "lock", "(", "self", ",", "block", "=", "True", ")", ":", "self", ".", "_locked", "=", "True", "return", "self", ".", "_lock", ".", "acquire", "(", "block", ")" ]
Lock connection from being used else where
[ "Lock", "connection", "from", "being", "used", "else", "where" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L117-L122
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.release
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
python
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "_locked", "is", "True", ":", "self", ".", "_locked", "=", "False", "self", ".", "_lock", ".", "release", "(", ")" ]
Release the connection lock
[ "Release", "the", "connection", "lock" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L124-L130
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.getCursor
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
python
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
[ "def", "getCursor", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "Connect", "(", ")", "return", "self", ".", "connection", ".", "cursor", "(", "MySQLdb", ".", "cursors", ".", "DictCursor", ")" ]
Get a Dictionary Cursor for executing queries
[ "Get", "a", "Dictionary", "Cursor", "for", "executing", "queries" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L138-L145
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.Connect
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.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() self._updateCheckTime()
python
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.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() self._updateCheckTime()
[ "def", "Connect", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "connection", "=", "MySQLdb", ".", "connect", "(", "*", "[", "]", ",", "*", "*", "self", ".", "connectionInfo", ".", "info", ")", "if", "self"...
Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008
[ "Creates", "a", "new", "physical", "connection", "to", "the", "database" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L153-L166
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.being
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
python
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
[ "def", "being", "(", "self", ")", ":", "try", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "lock", "(", ")", "c", "=", "self", ".", "getCursor", "(", ")", "c", ".", "execute", "(", "'BEGIN;'", ")", "c", ".", "clo...
Being a Transaction @author: Nick Verbeck @since: 5/14/2011
[ "Being", "a", "Transaction" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L207-L221
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.commit
def commit(self): """ 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 """ try: if self.connection is not None: self.connection.commit() self._updateCheckTime() self.release() except Exception, e: pass
python
def commit(self): """ 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 """ try: if self.connection is not None: self.connection.commit() self._updateCheckTime() self.release() except Exception, e: pass
[ "def", "commit", "(", "self", ")", ":", "try", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "connection", ".", "commit", "(", ")", "self", ".", "_updateCheckTime", "(", ")", "self", ".", "release", "(", ")", "except", ...
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
[ "Commit", "MySQL", "Transaction", "to", "database", ".", "MySQLDB", ":", "If", "the", "database", "and", "the", "tables", "support", "transactions", "this", "commits", "the", "current", "transaction", ";", "otherwise", "this", "method", "successfully", "does", "...
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L224-L240
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.rollback
def rollback(self): """ 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 """ try: if self.connection is not None: self.connection.rollback() self._updateCheckTime() self.release() except Exception, e: pass
python
def rollback(self): """ 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 """ try: if self.connection is not None: self.connection.rollback() self._updateCheckTime() self.release() except Exception, e: pass
[ "def", "rollback", "(", "self", ")", ":", "try", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "connection", ".", "rollback", "(", ")", "self", ".", "_updateCheckTime", "(", ")", "self", ".", "release", "(", ")", "excep...
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
[ "Rollback", "MySQL", "Transaction", "to", "database", ".", "MySQLDB", ":", "If", "the", "database", "and", "tables", "support", "transactions", "this", "rolls", "back", "(", "cancels", ")", "the", "current", "transaction", ";", "otherwise", "a", "NotSupportedErr...
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L243-L259
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.Close
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.connection = None except Exception, e: pass
python
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.connection = None except Exception, e: pass
[ "def", "Close", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "try", ":", "self", ".", "connection", ".", "commit", "(", ")", "self", ".", "connection", ".", "close", "(", ")", "self", ".", "connection", "=", "No...
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008
[ "Commits", "and", "closes", "the", "current", "connection" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L261-L274
openspending/babbage
babbage/api.py
configure_api
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'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
python
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'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
[ "def", "configure_api", "(", "app", ",", "manager", ")", ":", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "app", ".", "extensions", "=", "{", "}", "# pragma: nocover", "app", ".", "extensions", "[", "'babbage'", "]", "=", "manager"...
Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data.
[ "Configure", "the", "current", "Flask", "app", "with", "an", "instance", "of", "CubeManager", "that", "will", "be", "used", "to", "load", "and", "query", "data", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L16-L22
openspending/babbage
babbage/api.py
get_cube
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)
python
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)
[ "def", "get_cube", "(", "name", ")", ":", "manager", "=", "get_manager", "(", ")", "if", "not", "manager", ".", "has_cube", "(", "name", ")", ":", "raise", "NotFound", "(", "'No such cube: %r'", "%", "name", ")", "return", "manager", ".", "get_cube", "("...
Load the named cube from the current registered ``CubeManager``.
[ "Load", "the", "named", "cube", "from", "the", "current", "registered", "CubeManager", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L31-L36
openspending/babbage
babbage/api.py
jsonify
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, data) return Response(data, headers=headers, status=status, mimetype='application/json')
python
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, data) return Response(data, headers=headers, status=status, mimetype='application/json')
[ "def", "jsonify", "(", "obj", ",", "status", "=", "200", ",", "headers", "=", "None", ")", ":", "data", "=", "JSONEncoder", "(", ")", ".", "encode", "(", "obj", ")", "if", "'callback'", "in", "request", ".", "args", ":", "cb", "=", "request", ".", ...
Custom JSONificaton to support obj.to_dict protocol.
[ "Custom", "JSONificaton", "to", "support", "obj", ".", "to_dict", "protocol", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L57-L64
openspending/babbage
babbage/api.py
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 })
python
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 })
[ "def", "cubes", "(", ")", ":", "cubes", "=", "[", "]", "for", "cube", "in", "get_manager", "(", ")", ".", "list_cubes", "(", ")", ":", "cubes", ".", "append", "(", "{", "'name'", ":", "cube", "}", ")", "return", "jsonify", "(", "{", "'status'", "...
Get a listing of all publicly available cubes.
[ "Get", "a", "listing", "of", "all", "publicly", "available", "cubes", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L120-L130
openspending/babbage
babbage/api.py
aggregate
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'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' if request.args.get('format', '').lower() == 'csv': return create_csv_response(result['cells']) else: return jsonify(result)
python
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'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' if request.args.get('format', '').lower() == 'csv': return create_csv_response(result['cells']) else: return jsonify(result)
[ "def", "aggregate", "(", "name", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "aggregate", "(", "aggregates", "=", "request", ".", "args", ".", "get", "(", "'aggregates'", ")", ",", "drilldowns", "=", "request", ".",...
Perform an aggregation request.
[ "Perform", "an", "aggregation", "request", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L145-L159
openspending/babbage
babbage/api.py
facts
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'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
python
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'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
[ "def", "facts", "(", "name", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "facts", "(", "fields", "=", "request", ".", "args", ".", "get", "(", "'fields'", ")", ",", "cuts", "=", "request", ".", "args", ".", "g...
List the fact table entries in the current cube. This is the full materialized dataset.
[ "List", "the", "fact", "table", "entries", "in", "the", "current", "cube", ".", "This", "is", "the", "full", "materialized", "dataset", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L163-L173
openspending/babbage
babbage/api.py
members
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'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
python
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'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify(result)
[ "def", "members", "(", "name", ",", "ref", ")", ":", "cube", "=", "get_cube", "(", "name", ")", "result", "=", "cube", ".", "members", "(", "ref", ",", "cuts", "=", "request", ".", "args", ".", "get", "(", "'cut'", ")", ",", "order", "=", "reques...
List the members of a specific dimension or the distinct values of a given attribute.
[ "List", "the", "members", "of", "a", "specific", "dimension", "or", "the", "distinct", "values", "of", "a", "given", "attribute", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L177-L186
openspending/babbage
babbage/query/drilldowns.py
Drilldowns.apply
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(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Binding(table, attribute.ref)) q = q.column(column) q = q.group_by(column) return info, q, bindings
python
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(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Binding(table, attribute.ref)) q = q.column(column) q = q.group_by(column) return info, q, bindings
[ "def", "apply", "(", "self", ",", "q", ",", "bindings", ",", "drilldowns", ")", ":", "info", "=", "[", "]", "for", "drilldown", "in", "self", ".", "parse", "(", "drilldowns", ")", ":", "for", "attribute", "in", "self", ".", "cube", ".", "model", "....
Apply a set of grouping criteria and project them.
[ "Apply", "a", "set", "of", "grouping", "criteria", "and", "project", "them", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/drilldowns.py#L18-L28
openspending/babbage
babbage/validation.py
check_attribute_exists
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. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False label_attr = instance.get('label_attribute') if label_attr and label_attr not in attributes: return False return True
python
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. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False label_attr = instance.get('label_attribute') if label_attr and label_attr not in attributes: return False return True
[ "def", "check_attribute_exists", "(", "instance", ")", ":", "attributes", "=", "instance", ".", "get", "(", "'attributes'", ",", "{", "}", ")", ".", "keys", "(", ")", "if", "instance", ".", "get", "(", "'key_attribute'", ")", "not", "in", "attributes", "...
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", "dimension", "model", "to", "ensure", "that", "attributes", "given", "as", "the", "key", "and", "label", "attribute", "on", "the", "dimension", "exist", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L11-L20
openspending/babbage
babbage/validation.py
check_valid_hierarchies
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', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy in hierarchies: levels = set(hierarcy.get('levels', [])) if len(all_levels.intersection(levels)) > 0: # Dimension appears in two different hierarchies return False all_levels = all_levels.union(levels) if not dimensions.issuperset(levels): # Level which is not in a dimension return False return True
python
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', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy in hierarchies: levels = set(hierarcy.get('levels', [])) if len(all_levels.intersection(levels)) > 0: # Dimension appears in two different hierarchies return False all_levels = all_levels.union(levels) if not dimensions.issuperset(levels): # Level which is not in a dimension return False return True
[ "def", "check_valid_hierarchies", "(", "instance", ")", ":", "hierarchies", "=", "instance", ".", "get", "(", "'hierarchies'", ",", "{", "}", ")", ".", "values", "(", ")", "dimensions", "=", "set", "(", "instance", ".", "get", "(", "'dimensions'", ",", "...
Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions
[ "Additional", "check", "for", "the", "hierarchies", "model", "to", "ensure", "that", "levels", "given", "are", "pointing", "to", "actual", "dimensions" ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L24-L39
openspending/babbage
babbage/validation.py
load_validator
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) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
python
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) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
[ "def", "load_validator", "(", "name", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "SCHEMA_PATH", ",", "name", ")", ")", "as", "fh", ":", "schema", "=", "json", ".", "load", "(", "fh", ")", "Draft4Validator", ".", "check_schema...
Load the JSON Schema Draft 4 validator with the given name from the local schema directory.
[ "Load", "the", "JSON", "Schema", "Draft", "4", "validator", "with", "the", "given", "name", "from", "the", "local", "schema", "directory", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/validation.py#L42-L48
openspending/babbage
babbage/manager.py
CubeManager.get_cube
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_cube_model(name))
python
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_cube_model(name))
[ "def", "get_cube", "(", "self", ",", "name", ")", ":", "return", "Cube", "(", "self", ".", "get_engine", "(", ")", ",", "name", ",", "self", ".", "get_cube_model", "(", "name", ")", ")" ]
Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to.
[ "Given", "a", "cube", "name", "construct", "that", "cube", "and", "return", "it", ".", "Do", "not", "overwrite", "this", "method", "unless", "you", "need", "to", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/manager.py#L41-L44
openspending/babbage
babbage/manager.py
JSONCubeManager.list_cubes
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
python
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
[ "def", "list_cubes", "(", "self", ")", ":", "for", "file_name", "in", "os", ".", "listdir", "(", "self", ".", "directory", ")", ":", "if", "'.'", "in", "file_name", ":", "name", ",", "ext", "=", "file_name", ".", "rsplit", "(", "'.'", ",", "1", ")"...
List all available JSON files.
[ "List", "all", "available", "JSON", "files", "." ]
train
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/manager.py#L55-L61
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Terminate
def Terminate(self): """ 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 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed connections pass conn.release() except Exception: pass self.connections = {} finally: self.lock.release()
python
def Terminate(self): """ 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 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed connections pass conn.release() except Exception: pass self.connections = {} finally: self.lock.release()
[ "def", "Terminate", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "l...
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
[ "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", "." ...
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L42-L69
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Cleanup
def Cleanup(self): """ 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 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: open = conn.TestConnection(forceCheck=True) if open is True: conn.commit() else: #Remove the connection from the pool. Its dead better of recreating it. index = bucket.index(conn) del bucket[index] conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
python
def Cleanup(self): """ 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 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: open = conn.TestConnection(forceCheck=True) if open is True: conn.commit() else: #Remove the connection from the pool. Its dead better of recreating it. index = bucket.index(conn) del bucket[index] conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
[ "def", "Cleanup", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "loc...
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
[ "Cleanup", "Timed", "out", "connections", "Loop", "though", "all", "the", "connections", "and", "test", "if", "still", "active", ".", "If", "inactive", "close", "socket", "." ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L71-L100
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.Commit
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: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
python
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: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
[ "def", "Commit", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "lock...
Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008
[ "Commits", "all", "currently", "open", "connections" ]
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L102-L123
nerdynick/PySQLPool
src/PySQLPool/pool.py
Pool.GetConnection
def GetConnection(self, ConnectionObj): """ 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 @author: Nick Verbeck @since: 5/12/2008 """ key = ConnectionObj.getKey() connection = None if self.connections.has_key(key): connection = self._getConnectionFromPoolSet(key) if connection is None: self.lock.acquire() if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) self.lock.release() else: #Wait for a free connection. We maintain the lock on the pool so we are the 1st to get a connection. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() #Create new Connection Pool Set else: self.lock.acquire() #We do a double check now that its locked to be sure some other thread didn't create this while we may have been waiting. if not self.connections.has_key(key): self.connections[key] = [] if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) else: #A rare thing happened. So many threads created connections so fast we need to wait for a free one. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() return connection
python
def GetConnection(self, ConnectionObj): """ 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 @author: Nick Verbeck @since: 5/12/2008 """ key = ConnectionObj.getKey() connection = None if self.connections.has_key(key): connection = self._getConnectionFromPoolSet(key) if connection is None: self.lock.acquire() if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) self.lock.release() else: #Wait for a free connection. We maintain the lock on the pool so we are the 1st to get a connection. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() #Create new Connection Pool Set else: self.lock.acquire() #We do a double check now that its locked to be sure some other thread didn't create this while we may have been waiting. if not self.connections.has_key(key): self.connections[key] = [] if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self._createConnection(ConnectionObj) self.connections[key].append(connection) else: #A rare thing happened. So many threads created connections so fast we need to wait for a free one. while connection is None: connection = self._getConnectionFromPoolSet(key) self.lock.release() return connection
[ "def", "GetConnection", "(", "self", ",", "ConnectionObj", ")", ":", "key", "=", "ConnectionObj", ".", "getKey", "(", ")", "connection", "=", "None", "if", "self", ".", "connections", ".", "has_key", "(", "key", ")", ":", "connection", "=", "self", ".", ...
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 @author: Nick Verbeck @since: 5/12/2008
[ "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", ...
train
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/pool.py#L125-L174
bodylabs/lace
lace/color_names.py
main
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.match(r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*', line) if reg: r = int(reg.group(1)) / 255. g = int(reg.group(2)) / 255. b = int(reg.group(3)) / 255. d = reg.group(4) print "'%s' : np.array([%.2f, %.2f, %.2f])," % (d, r, g, b) line = fp.readline()
python
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.match(r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*', line) if reg: r = int(reg.group(1)) / 255. g = int(reg.group(2)) / 255. b = int(reg.group(3)) / 255. d = reg.group(4) print "'%s' : np.array([%.2f, %.2f, %.2f])," % (d, r, g, b) line = fp.readline()
[ "def", "main", "(", ")", ":", "import", "re", "with", "open", "(", "'rgb.txt'", ")", "as", "fp", ":", "line", "=", "fp", ".", "readline", "(", ")", "while", "line", ":", "reg", "=", "re", ".", "match", "(", "r'\\s*(\\d+)\\s*(\\d+)\\s*(\\d+)\\s*(\\w.*\\w)...
Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).
[ "Generates", "code", "for", "name_to_rgb", "dict", "assuming", "an", "rgb", ".", "txt", "file", "available", "(", "in", "X11", "format", ")", "." ]
train
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/color_names.py#L768-L781
bachya/regenmaschine
regenmaschine/stats.py
Stats.on_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')))
python
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')))
[ "async", "def", "on_date", "(", "self", ",", "date", ":", "datetime", ".", "date", ")", "->", "dict", ":", "return", "await", "self", ".", "_request", "(", "'get'", ",", "'dailystats/{0}'", ".", "format", "(", "date", ".", "strftime", "(", "'%Y-%m-%d'", ...
Get statistics for a certain date.
[ "Get", "statistics", "for", "a", "certain", "date", "." ]
train
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/stats.py#L13-L16
bachya/regenmaschine
regenmaschine/stats.py
Stats.upcoming
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' data = await self._request('get', endpoint) return data[key]
python
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' data = await self._request('get', endpoint) return data[key]
[ "async", "def", "upcoming", "(", "self", ",", "details", ":", "bool", "=", "False", ")", "->", "list", ":", "endpoint", "=", "'dailystats'", "key", "=", "'DailyStats'", "if", "details", ":", "endpoint", "+=", "'/details'", "key", "=", "'DailyStatsDetails'", ...
Return watering statistics for the next 6 days.
[ "Return", "watering", "statistics", "for", "the", "next", "6", "days", "." ]
train
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/stats.py#L18-L26
bachya/regenmaschine
example.py
main
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') print('Name: {0}'.format(controller.name)) print('MAC Address: {0}'.format(controller.mac)) print('API Version: {0}'.format(controller.api_version)) print( 'Software Version: {0}'.format( controller.software_version)) print( 'Hardware Version: {0}'.format( controller.hardware_version)) # Work with diagnostics: print() print('RAINMACHINE DIAGNOSTICS') data = await controller.diagnostics.current() print('Uptime: {0}'.format(data['uptime'])) print('Software Version: {0}'.format(data['softwareVersion'])) # Work with parsers: print() print('RAINMACHINE PARSERS') for parser in await controller.parsers.current(): print(parser['name']) # Work with programs: print() print('ALL PROGRAMS') for program in await controller.programs.all( include_inactive=True): print( 'Program #{0}: {1}'.format( program['uid'], program['name'])) print() print('PROGRAM BY ID') program_1 = await controller.programs.get(1) print( "Program 1's Start Time: {0}".format( program_1['startTime'])) print() print('NEXT RUN TIMES') for program in await controller.programs.next(): print( 'Program #{0}: {1}'.format( program['pid'], program['startTime'])) print() print('RUNNING PROGRAMS') for program in await controller.programs.running(): print('Program #{0}'.format(program['uid'])) print() print('STARTING PROGRAM #1') print(await controller.programs.start(1)) await asyncio.sleep(3) print() print('STOPPING PROGRAM #1') print(await controller.programs.stop(1)) # Work with provisioning: print() print('PROVISIONING INFO') name = await controller.provisioning.device_name print('Device Name: {0}'.format(name)) settings = await controller.provisioning.settings() print( 'Database Path: {0}'.format( settings['system']['databasePath'])) print( 'Station Name: {0}'.format( settings['location']['stationName'])) wifi = await controller.provisioning.wifi() print('IP Address: {0}'.format(wifi['ipAddress'])) # Work with restrictions: print() print('RESTRICTIONS') current = await controller.restrictions.current() print( 'Rain Delay Restrictions: {0}'.format( current['rainDelay'])) universal = await controller.restrictions.universal() print( 'Freeze Protect: {0}'.format( universal['freezeProtectEnabled'])) print('Hourly Restrictions:') for restriction in await controller.restrictions.hourly(): print(restriction['name']) raindelay = await controller.restrictions.raindelay() print( 'Rain Delay Counter: {0}'.format( raindelay['delayCounter'])) # Work with restrictions: print() print('STATS') today = await controller.stats.on_date( date=datetime.date.today()) print('Min for Today: {0}'.format(today['mint'])) for day in await controller.stats.upcoming(details=True): print('{0} Min: {1}'.format(day['day'], day['mint'])) # Work with watering: print() print('WATERING') for day in await controller.watering.log( date=datetime.date.today()): print( '{0} duration: {1}'.format( day['date'], day['realDuration'])) queue = await controller.watering.queue() print('Current Queue: {0}'.format(queue)) print('Runs:') for watering_run in await controller.watering.runs( date=datetime.date.today()): print( '{0} ({1})'.format( watering_run['dateTime'], watering_run['et0'])) print() print('PAUSING ALL WATERING FOR 30 SECONDS') print(await controller.watering.pause_all(30)) await asyncio.sleep(3) print() print('UNPAUSING WATERING') print(await controller.watering.unpause_all()) print() print('STOPPING ALL WATERING') print(await controller.watering.stop_all()) # Work with zones: print() print('ALL ACTIVE ZONES') for zone in await controller.zones.all(details=True): print( 'Zone #{0}: {1} (soil: {2})'.format( zone['uid'], zone['name'], zone['soil'])) print() print('ZONE BY ID') zone_1 = await controller.zones.get(1, details=True) print( "Zone 1's Name: {0} (soil: {1})".format( zone_1['name'], zone_1['soil'])) print() print('STARTING ZONE #1 FOR 3 SECONDS') print(await controller.zones.start(1, 3)) await asyncio.sleep(3) print() print('STOPPING ZONE #1') print(await controller.zones.stop(1)) except RainMachineError as err: print(err)
python
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') print('Name: {0}'.format(controller.name)) print('MAC Address: {0}'.format(controller.mac)) print('API Version: {0}'.format(controller.api_version)) print( 'Software Version: {0}'.format( controller.software_version)) print( 'Hardware Version: {0}'.format( controller.hardware_version)) # Work with diagnostics: print() print('RAINMACHINE DIAGNOSTICS') data = await controller.diagnostics.current() print('Uptime: {0}'.format(data['uptime'])) print('Software Version: {0}'.format(data['softwareVersion'])) # Work with parsers: print() print('RAINMACHINE PARSERS') for parser in await controller.parsers.current(): print(parser['name']) # Work with programs: print() print('ALL PROGRAMS') for program in await controller.programs.all( include_inactive=True): print( 'Program #{0}: {1}'.format( program['uid'], program['name'])) print() print('PROGRAM BY ID') program_1 = await controller.programs.get(1) print( "Program 1's Start Time: {0}".format( program_1['startTime'])) print() print('NEXT RUN TIMES') for program in await controller.programs.next(): print( 'Program #{0}: {1}'.format( program['pid'], program['startTime'])) print() print('RUNNING PROGRAMS') for program in await controller.programs.running(): print('Program #{0}'.format(program['uid'])) print() print('STARTING PROGRAM #1') print(await controller.programs.start(1)) await asyncio.sleep(3) print() print('STOPPING PROGRAM #1') print(await controller.programs.stop(1)) # Work with provisioning: print() print('PROVISIONING INFO') name = await controller.provisioning.device_name print('Device Name: {0}'.format(name)) settings = await controller.provisioning.settings() print( 'Database Path: {0}'.format( settings['system']['databasePath'])) print( 'Station Name: {0}'.format( settings['location']['stationName'])) wifi = await controller.provisioning.wifi() print('IP Address: {0}'.format(wifi['ipAddress'])) # Work with restrictions: print() print('RESTRICTIONS') current = await controller.restrictions.current() print( 'Rain Delay Restrictions: {0}'.format( current['rainDelay'])) universal = await controller.restrictions.universal() print( 'Freeze Protect: {0}'.format( universal['freezeProtectEnabled'])) print('Hourly Restrictions:') for restriction in await controller.restrictions.hourly(): print(restriction['name']) raindelay = await controller.restrictions.raindelay() print( 'Rain Delay Counter: {0}'.format( raindelay['delayCounter'])) # Work with restrictions: print() print('STATS') today = await controller.stats.on_date( date=datetime.date.today()) print('Min for Today: {0}'.format(today['mint'])) for day in await controller.stats.upcoming(details=True): print('{0} Min: {1}'.format(day['day'], day['mint'])) # Work with watering: print() print('WATERING') for day in await controller.watering.log( date=datetime.date.today()): print( '{0} duration: {1}'.format( day['date'], day['realDuration'])) queue = await controller.watering.queue() print('Current Queue: {0}'.format(queue)) print('Runs:') for watering_run in await controller.watering.runs( date=datetime.date.today()): print( '{0} ({1})'.format( watering_run['dateTime'], watering_run['et0'])) print() print('PAUSING ALL WATERING FOR 30 SECONDS') print(await controller.watering.pause_all(30)) await asyncio.sleep(3) print() print('UNPAUSING WATERING') print(await controller.watering.unpause_all()) print() print('STOPPING ALL WATERING') print(await controller.watering.stop_all()) # Work with zones: print() print('ALL ACTIVE ZONES') for zone in await controller.zones.all(details=True): print( 'Zone #{0}: {1} (soil: {2})'.format( zone['uid'], zone['name'], zone['soil'])) print() print('ZONE BY ID') zone_1 = await controller.zones.get(1, details=True) print( "Zone 1's Name: {0} (soil: {1})".format( zone_1['name'], zone_1['soil'])) print() print('STARTING ZONE #1 FOR 3 SECONDS') print(await controller.zones.start(1, 3)) await asyncio.sleep(3) print() print('STOPPING ZONE #1') print(await controller.zones.stop(1)) except RainMachineError as err: print(err)
[ "async", "def", "main", "(", ")", ":", "async", "with", "ClientSession", "(", ")", "as", "websession", ":", "try", ":", "client", "=", "Client", "(", "websession", ")", "await", "client", ".", "load_local", "(", "'<IP ADDRESS>'", ",", "'<PASSWORD>'", ",", ...
Run.
[ "Run", "." ]
train
https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/example.py#L12-L182