id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
236,600
vtkiorg/vtki
vtki/common.py
Common.arrows
def arrows(self): """ Returns a glyph representation of the active vector data as arrows. Arrows will be located at the points of the mesh and their size will be dependent on the length of the vector. Their direction will be the "direction" of the vector Returns ------- arrows : vtki.PolyData Active scalars represented as arrows. """ if self.active_vectors is None: return arrow = vtk.vtkArrowSource() arrow.Update() alg = vtk.vtkGlyph3D() alg.SetSourceData(arrow.GetOutput()) alg.SetOrient(True) alg.SetInputData(self) alg.SetVectorModeToUseVector() alg.SetScaleModeToScaleByVector() alg.Update() return vtki.wrap(alg.GetOutput())
python
def arrows(self): if self.active_vectors is None: return arrow = vtk.vtkArrowSource() arrow.Update() alg = vtk.vtkGlyph3D() alg.SetSourceData(arrow.GetOutput()) alg.SetOrient(True) alg.SetInputData(self) alg.SetVectorModeToUseVector() alg.SetScaleModeToScaleByVector() alg.Update() return vtki.wrap(alg.GetOutput())
[ "def", "arrows", "(", "self", ")", ":", "if", "self", ".", "active_vectors", "is", "None", ":", "return", "arrow", "=", "vtk", ".", "vtkArrowSource", "(", ")", "arrow", ".", "Update", "(", ")", "alg", "=", "vtk", ".", "vtkGlyph3D", "(", ")", "alg", ...
Returns a glyph representation of the active vector data as arrows. Arrows will be located at the points of the mesh and their size will be dependent on the length of the vector. Their direction will be the "direction" of the vector Returns ------- arrows : vtki.PolyData Active scalars represented as arrows.
[ "Returns", "a", "glyph", "representation", "of", "the", "active", "vector", "data", "as", "arrows", ".", "Arrows", "will", "be", "located", "at", "the", "points", "of", "the", "mesh", "and", "their", "size", "will", "be", "dependent", "on", "the", "length"...
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L128-L153
236,601
vtkiorg/vtki
vtki/common.py
Common.vectors
def vectors(self, array): """ Sets the active vector """ if array.ndim != 2: raise AssertionError('vector array must be a 2-dimensional array') elif array.shape[1] != 3: raise RuntimeError('vector array must be 3D') elif array.shape[0] != self.n_points: raise RuntimeError('Number of vectors be the same as the number of points') self.point_arrays[DEFAULT_VECTOR_KEY] = array self.active_vectors_name = DEFAULT_VECTOR_KEY
python
def vectors(self, array): if array.ndim != 2: raise AssertionError('vector array must be a 2-dimensional array') elif array.shape[1] != 3: raise RuntimeError('vector array must be 3D') elif array.shape[0] != self.n_points: raise RuntimeError('Number of vectors be the same as the number of points') self.point_arrays[DEFAULT_VECTOR_KEY] = array self.active_vectors_name = DEFAULT_VECTOR_KEY
[ "def", "vectors", "(", "self", ",", "array", ")", ":", "if", "array", ".", "ndim", "!=", "2", ":", "raise", "AssertionError", "(", "'vector array must be a 2-dimensional array'", ")", "elif", "array", ".", "shape", "[", "1", "]", "!=", "3", ":", "raise", ...
Sets the active vector
[ "Sets", "the", "active", "vector" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L161-L171
236,602
vtkiorg/vtki
vtki/common.py
Common.t_coords
def t_coords(self, t_coords): """Set the array to use as the texture coordinates""" if not isinstance(t_coords, np.ndarray): raise TypeError('Texture coordinates must be a numpy array') if t_coords.ndim != 2: raise AssertionError('Texture coordinates must be a 2-dimensional array') if t_coords.shape[0] != self.n_points: raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points)) if t_coords.shape[1] != 2: raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1])) if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0: raise AssertionError('Texture coordinates must be within (0, 1) range.') # convert the array vtkarr = numpy_to_vtk(t_coords) vtkarr.SetName('Texture Coordinates') self.GetPointData().SetTCoords(vtkarr) self.GetPointData().Modified() return
python
def t_coords(self, t_coords): if not isinstance(t_coords, np.ndarray): raise TypeError('Texture coordinates must be a numpy array') if t_coords.ndim != 2: raise AssertionError('Texture coordinates must be a 2-dimensional array') if t_coords.shape[0] != self.n_points: raise AssertionError('Number of texture coordinates ({}) must match number of points ({})'.format(t_coords.shape[0], self.n_points)) if t_coords.shape[1] != 2: raise AssertionError('Texture coordinates must only have 2 components, not ({})'.format(t_coords.shape[1])) if np.min(t_coords) < 0.0 or np.max(t_coords) > 1.0: raise AssertionError('Texture coordinates must be within (0, 1) range.') # convert the array vtkarr = numpy_to_vtk(t_coords) vtkarr.SetName('Texture Coordinates') self.GetPointData().SetTCoords(vtkarr) self.GetPointData().Modified() return
[ "def", "t_coords", "(", "self", ",", "t_coords", ")", ":", "if", "not", "isinstance", "(", "t_coords", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Texture coordinates must be a numpy array'", ")", "if", "t_coords", ".", "ndim", "!=", "2...
Set the array to use as the texture coordinates
[ "Set", "the", "array", "to", "use", "as", "the", "texture", "coordinates" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L181-L198
236,603
vtkiorg/vtki
vtki/common.py
Common._activate_texture
def _activate_texture(mesh, name): """Grab a texture and update the active texture coordinates. This makes sure to not destroy old texture coordinates Parameters ---------- name : str The name of the texture and texture coordinates to activate Return ------ vtk.vtkTexture : The active texture """ if name == True or isinstance(name, int): keys = list(mesh.textures.keys()) # Grab the first name availabe if True idx = 0 if not isinstance(name, int) or name == True else name if idx > len(keys): idx = 0 try: name = keys[idx] except IndexError: logging.warning('No textures associated with input mesh.') return None # Grab the texture object by name try: texture = mesh.textures[name] except KeyError: logging.warning('Texture ({}) not associated with this dataset'.format(name)) texture = None else: # Be sure to reset the tcoords if present # Grab old coordinates if name in mesh.scalar_names: old_tcoord = mesh.GetPointData().GetTCoords() mesh.GetPointData().SetTCoords(mesh.GetPointData().GetArray(name)) mesh.GetPointData().AddArray(old_tcoord) mesh.Modified() return texture
python
def _activate_texture(mesh, name): if name == True or isinstance(name, int): keys = list(mesh.textures.keys()) # Grab the first name availabe if True idx = 0 if not isinstance(name, int) or name == True else name if idx > len(keys): idx = 0 try: name = keys[idx] except IndexError: logging.warning('No textures associated with input mesh.') return None # Grab the texture object by name try: texture = mesh.textures[name] except KeyError: logging.warning('Texture ({}) not associated with this dataset'.format(name)) texture = None else: # Be sure to reset the tcoords if present # Grab old coordinates if name in mesh.scalar_names: old_tcoord = mesh.GetPointData().GetTCoords() mesh.GetPointData().SetTCoords(mesh.GetPointData().GetArray(name)) mesh.GetPointData().AddArray(old_tcoord) mesh.Modified() return texture
[ "def", "_activate_texture", "(", "mesh", ",", "name", ")", ":", "if", "name", "==", "True", "or", "isinstance", "(", "name", ",", "int", ")", ":", "keys", "=", "list", "(", "mesh", ".", "textures", ".", "keys", "(", ")", ")", "# Grab the first name ava...
Grab a texture and update the active texture coordinates. This makes sure to not destroy old texture coordinates Parameters ---------- name : str The name of the texture and texture coordinates to activate Return ------ vtk.vtkTexture : The active texture
[ "Grab", "a", "texture", "and", "update", "the", "active", "texture", "coordinates", ".", "This", "makes", "sure", "to", "not", "destroy", "old", "texture", "coordinates" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L210-L248
236,604
vtkiorg/vtki
vtki/common.py
Common.set_active_scalar
def set_active_scalar(self, name, preference='cell'): """Finds the scalar by name and appropriately sets it as active""" _, field = get_scalar(self, name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.GetPointData().SetActiveScalars(name) elif field == CELL_DATA_FIELD: self.GetCellData().SetActiveScalars(name) else: raise RuntimeError('Data field ({}) not useable'.format(field)) self._active_scalar_info = [field, name]
python
def set_active_scalar(self, name, preference='cell'): _, field = get_scalar(self, name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.GetPointData().SetActiveScalars(name) elif field == CELL_DATA_FIELD: self.GetCellData().SetActiveScalars(name) else: raise RuntimeError('Data field ({}) not useable'.format(field)) self._active_scalar_info = [field, name]
[ "def", "set_active_scalar", "(", "self", ",", "name", ",", "preference", "=", "'cell'", ")", ":", "_", ",", "field", "=", "get_scalar", "(", "self", ",", "name", ",", "preference", "=", "preference", ",", "info", "=", "True", ")", "if", "field", "==", ...
Finds the scalar by name and appropriately sets it as active
[ "Finds", "the", "scalar", "by", "name", "and", "appropriately", "sets", "it", "as", "active" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L250-L259
236,605
vtkiorg/vtki
vtki/common.py
Common.set_active_vectors
def set_active_vectors(self, name, preference='cell'): """Finds the vectors by name and appropriately sets it as active""" _, field = get_scalar(self, name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.GetPointData().SetActiveVectors(name) elif field == CELL_DATA_FIELD: self.GetCellData().SetActiveVectors(name) else: raise RuntimeError('Data field ({}) not useable'.format(field)) self._active_vectors_info = [field, name]
python
def set_active_vectors(self, name, preference='cell'): _, field = get_scalar(self, name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.GetPointData().SetActiveVectors(name) elif field == CELL_DATA_FIELD: self.GetCellData().SetActiveVectors(name) else: raise RuntimeError('Data field ({}) not useable'.format(field)) self._active_vectors_info = [field, name]
[ "def", "set_active_vectors", "(", "self", ",", "name", ",", "preference", "=", "'cell'", ")", ":", "_", ",", "field", "=", "get_scalar", "(", "self", ",", "name", ",", "preference", "=", "preference", ",", "info", "=", "True", ")", "if", "field", "==",...
Finds the vectors by name and appropriately sets it as active
[ "Finds", "the", "vectors", "by", "name", "and", "appropriately", "sets", "it", "as", "active" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L261-L270
236,606
vtkiorg/vtki
vtki/common.py
Common.rename_scalar
def rename_scalar(self, old_name, new_name, preference='cell'): """Changes array name by searching for the array then renaming it""" _, field = get_scalar(self, old_name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.point_arrays[new_name] = self.point_arrays.pop(old_name) elif field == CELL_DATA_FIELD: self.cell_arrays[new_name] = self.cell_arrays.pop(old_name) else: raise RuntimeError('Array not found.') if self.active_scalar_info[1] == old_name: self.set_active_scalar(new_name, preference=field)
python
def rename_scalar(self, old_name, new_name, preference='cell'): _, field = get_scalar(self, old_name, preference=preference, info=True) if field == POINT_DATA_FIELD: self.point_arrays[new_name] = self.point_arrays.pop(old_name) elif field == CELL_DATA_FIELD: self.cell_arrays[new_name] = self.cell_arrays.pop(old_name) else: raise RuntimeError('Array not found.') if self.active_scalar_info[1] == old_name: self.set_active_scalar(new_name, preference=field)
[ "def", "rename_scalar", "(", "self", ",", "old_name", ",", "new_name", ",", "preference", "=", "'cell'", ")", ":", "_", ",", "field", "=", "get_scalar", "(", "self", ",", "old_name", ",", "preference", "=", "preference", ",", "info", "=", "True", ")", ...
Changes array name by searching for the array then renaming it
[ "Changes", "array", "name", "by", "searching", "for", "the", "array", "then", "renaming", "it" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L272-L282
236,607
vtkiorg/vtki
vtki/common.py
Common.active_scalar
def active_scalar(self): """Returns the active scalar as an array""" field, name = self.active_scalar_info if name is None: return None if field == POINT_DATA_FIELD: return self._point_scalar(name) elif field == CELL_DATA_FIELD: return self._cell_scalar(name)
python
def active_scalar(self): field, name = self.active_scalar_info if name is None: return None if field == POINT_DATA_FIELD: return self._point_scalar(name) elif field == CELL_DATA_FIELD: return self._cell_scalar(name)
[ "def", "active_scalar", "(", "self", ")", ":", "field", ",", "name", "=", "self", ".", "active_scalar_info", "if", "name", "is", "None", ":", "return", "None", "if", "field", "==", "POINT_DATA_FIELD", ":", "return", "self", ".", "_point_scalar", "(", "name...
Returns the active scalar as an array
[ "Returns", "the", "active", "scalar", "as", "an", "array" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L285-L293
236,608
vtkiorg/vtki
vtki/common.py
Common._add_point_scalar
def _add_point_scalar(self, scalars, name, set_active=False, deep=True): """ Adds point scalars to the mesh Parameters ---------- scalars : numpy.ndarray Numpy array of scalars. Must match number of points. name : str Name of point scalars to add. set_active : bool, optional Sets the scalars to the active plotting scalars. Default False. deep : bool, optional Does not copy scalars when False. A reference to the scalars must be kept to avoid a segfault. """ if not isinstance(scalars, np.ndarray): raise TypeError('Input must be a numpy.ndarray') if scalars.shape[0] != self.n_points: raise Exception('Number of scalars must match the number of ' + 'points') # need to track which arrays are boolean as all boolean arrays # must be stored as uint8 if scalars.dtype == np.bool: scalars = scalars.view(np.uint8) if name not in self._point_bool_array_names: self._point_bool_array_names.append(name) if not scalars.flags.c_contiguous: scalars = np.ascontiguousarray(scalars) vtkarr = numpy_to_vtk(scalars, deep=deep) vtkarr.SetName(name) self.GetPointData().AddArray(vtkarr) if set_active or self.active_scalar_info[1] is None: self.GetPointData().SetActiveScalars(name) self._active_scalar_info = [POINT_DATA_FIELD, name]
python
def _add_point_scalar(self, scalars, name, set_active=False, deep=True): if not isinstance(scalars, np.ndarray): raise TypeError('Input must be a numpy.ndarray') if scalars.shape[0] != self.n_points: raise Exception('Number of scalars must match the number of ' + 'points') # need to track which arrays are boolean as all boolean arrays # must be stored as uint8 if scalars.dtype == np.bool: scalars = scalars.view(np.uint8) if name not in self._point_bool_array_names: self._point_bool_array_names.append(name) if not scalars.flags.c_contiguous: scalars = np.ascontiguousarray(scalars) vtkarr = numpy_to_vtk(scalars, deep=deep) vtkarr.SetName(name) self.GetPointData().AddArray(vtkarr) if set_active or self.active_scalar_info[1] is None: self.GetPointData().SetActiveScalars(name) self._active_scalar_info = [POINT_DATA_FIELD, name]
[ "def", "_add_point_scalar", "(", "self", ",", "scalars", ",", "name", ",", "set_active", "=", "False", ",", "deep", "=", "True", ")", ":", "if", "not", "isinstance", "(", "scalars", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Inpu...
Adds point scalars to the mesh Parameters ---------- scalars : numpy.ndarray Numpy array of scalars. Must match number of points. name : str Name of point scalars to add. set_active : bool, optional Sets the scalars to the active plotting scalars. Default False. deep : bool, optional Does not copy scalars when False. A reference to the scalars must be kept to avoid a segfault.
[ "Adds", "point", "scalars", "to", "the", "mesh" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L330-L372
236,609
vtkiorg/vtki
vtki/common.py
Common.points_to_double
def points_to_double(self): """ Makes points double precision """ if self.points.dtype != np.double: self.points = self.points.astype(np.double)
python
def points_to_double(self): if self.points.dtype != np.double: self.points = self.points.astype(np.double)
[ "def", "points_to_double", "(", "self", ")", ":", "if", "self", ".", "points", ".", "dtype", "!=", "np", ".", "double", ":", "self", ".", "points", "=", "self", ".", "points", ".", "astype", "(", "np", ".", "double", ")" ]
Makes points double precision
[ "Makes", "points", "double", "precision" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L374-L377
236,610
vtkiorg/vtki
vtki/common.py
Common.rotate_x
def rotate_x(self, angle): """ Rotates mesh about the x-axis. Parameters ---------- angle : float Angle in degrees to rotate about the x-axis. """ axis_rotation(self.points, angle, inplace=True, axis='x')
python
def rotate_x(self, angle): axis_rotation(self.points, angle, inplace=True, axis='x')
[ "def", "rotate_x", "(", "self", ",", "angle", ")", ":", "axis_rotation", "(", "self", ".", "points", ",", "angle", ",", "inplace", "=", "True", ",", "axis", "=", "'x'", ")" ]
Rotates mesh about the x-axis. Parameters ---------- angle : float Angle in degrees to rotate about the x-axis.
[ "Rotates", "mesh", "about", "the", "x", "-", "axis", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L379-L389
236,611
vtkiorg/vtki
vtki/common.py
Common.rotate_y
def rotate_y(self, angle): """ Rotates mesh about the y-axis. Parameters ---------- angle : float Angle in degrees to rotate about the y-axis. """ axis_rotation(self.points, angle, inplace=True, axis='y')
python
def rotate_y(self, angle): axis_rotation(self.points, angle, inplace=True, axis='y')
[ "def", "rotate_y", "(", "self", ",", "angle", ")", ":", "axis_rotation", "(", "self", ".", "points", ",", "angle", ",", "inplace", "=", "True", ",", "axis", "=", "'y'", ")" ]
Rotates mesh about the y-axis. Parameters ---------- angle : float Angle in degrees to rotate about the y-axis.
[ "Rotates", "mesh", "about", "the", "y", "-", "axis", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L391-L401
236,612
vtkiorg/vtki
vtki/common.py
Common.rotate_z
def rotate_z(self, angle): """ Rotates mesh about the z-axis. Parameters ---------- angle : float Angle in degrees to rotate about the z-axis. """ axis_rotation(self.points, angle, inplace=True, axis='z')
python
def rotate_z(self, angle): axis_rotation(self.points, angle, inplace=True, axis='z')
[ "def", "rotate_z", "(", "self", ",", "angle", ")", ":", "axis_rotation", "(", "self", ".", "points", ",", "angle", ",", "inplace", "=", "True", ",", "axis", "=", "'z'", ")" ]
Rotates mesh about the z-axis. Parameters ---------- angle : float Angle in degrees to rotate about the z-axis.
[ "Rotates", "mesh", "about", "the", "z", "-", "axis", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L403-L413
236,613
vtkiorg/vtki
vtki/common.py
Common.transform
def transform(self, trans): """ Compute a transformation in place using a 4x4 transform. Parameters ---------- trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray Accepts a vtk transformation object or a 4x4 transformation matrix. """ if isinstance(trans, vtk.vtkMatrix4x4): t = vtki.trans_from_matrix(trans) elif isinstance(trans, vtk.vtkTransform): t = vtki.trans_from_matrix(trans.GetMatrix()) elif isinstance(trans, np.ndarray): if trans.shape[0] != 4 or trans.shape[1] != 4: raise Exception('Transformation array must be 4x4') t = trans else: raise TypeError('Input transform must be either:\n' + '\tvtk.vtkMatrix4x4\n' + '\tvtk.vtkTransform\n' + '\t4x4 np.ndarray\n') x = (self.points*t[0, :3]).sum(1) + t[0, -1] y = (self.points*t[1, :3]).sum(1) + t[1, -1] z = (self.points*t[2, :3]).sum(1) + t[2, -1] # overwrite points self.points[:, 0] = x self.points[:, 1] = y self.points[:, 2] = z
python
def transform(self, trans): if isinstance(trans, vtk.vtkMatrix4x4): t = vtki.trans_from_matrix(trans) elif isinstance(trans, vtk.vtkTransform): t = vtki.trans_from_matrix(trans.GetMatrix()) elif isinstance(trans, np.ndarray): if trans.shape[0] != 4 or trans.shape[1] != 4: raise Exception('Transformation array must be 4x4') t = trans else: raise TypeError('Input transform must be either:\n' + '\tvtk.vtkMatrix4x4\n' + '\tvtk.vtkTransform\n' + '\t4x4 np.ndarray\n') x = (self.points*t[0, :3]).sum(1) + t[0, -1] y = (self.points*t[1, :3]).sum(1) + t[1, -1] z = (self.points*t[2, :3]).sum(1) + t[2, -1] # overwrite points self.points[:, 0] = x self.points[:, 1] = y self.points[:, 2] = z
[ "def", "transform", "(", "self", ",", "trans", ")", ":", "if", "isinstance", "(", "trans", ",", "vtk", ".", "vtkMatrix4x4", ")", ":", "t", "=", "vtki", ".", "trans_from_matrix", "(", "trans", ")", "elif", "isinstance", "(", "trans", ",", "vtk", ".", ...
Compute a transformation in place using a 4x4 transform. Parameters ---------- trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray Accepts a vtk transformation object or a 4x4 transformation matrix.
[ "Compute", "a", "transformation", "in", "place", "using", "a", "4x4", "transform", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L427-L458
236,614
vtkiorg/vtki
vtki/common.py
Common._cell_scalar
def _cell_scalar(self, name=None): """ Returns the cell scalars of a vtk object Parameters ---------- name : str Name of cell scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars """ if name is None: # use active scalar array field, name = self.active_scalar_info if field != CELL_DATA_FIELD: raise RuntimeError('Must specify an array to fetch.') vtkarr = self.GetCellData().GetArray(name) if vtkarr is None: raise AssertionError('({}) is not a cell scalar'.format(name)) # numpy does not support bit array data types if isinstance(vtkarr, vtk.vtkBitArray): vtkarr = vtk_bit_array_to_char(vtkarr) if name not in self._cell_bool_array_names: self._cell_bool_array_names.append(name) array = vtk_to_numpy(vtkarr) if array.dtype == np.uint8 and name in self._cell_bool_array_names: array = array.view(np.bool) return array
python
def _cell_scalar(self, name=None): if name is None: # use active scalar array field, name = self.active_scalar_info if field != CELL_DATA_FIELD: raise RuntimeError('Must specify an array to fetch.') vtkarr = self.GetCellData().GetArray(name) if vtkarr is None: raise AssertionError('({}) is not a cell scalar'.format(name)) # numpy does not support bit array data types if isinstance(vtkarr, vtk.vtkBitArray): vtkarr = vtk_bit_array_to_char(vtkarr) if name not in self._cell_bool_array_names: self._cell_bool_array_names.append(name) array = vtk_to_numpy(vtkarr) if array.dtype == np.uint8 and name in self._cell_bool_array_names: array = array.view(np.bool) return array
[ "def", "_cell_scalar", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "# use active scalar array", "field", ",", "name", "=", "self", ".", "active_scalar_info", "if", "field", "!=", "CELL_DATA_FIELD", ":", "raise", "Runtime...
Returns the cell scalars of a vtk object Parameters ---------- name : str Name of cell scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars
[ "Returns", "the", "cell", "scalars", "of", "a", "vtk", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L460-L494
236,615
vtkiorg/vtki
vtki/common.py
Common._add_cell_scalar
def _add_cell_scalar(self, scalars, name, set_active=False, deep=True): """ Adds cell scalars to the vtk object. Parameters ---------- scalars : numpy.ndarray Numpy array of scalars. Must match number of points. name : str Name of point scalars to add. set_active : bool, optional Sets the scalars to the active plotting scalars. Default False. deep : bool, optional Does not copy scalars when False. A reference to the scalars must be kept to avoid a segfault. """ if not isinstance(scalars, np.ndarray): raise TypeError('Input must be a numpy.ndarray') if scalars.shape[0] != self.n_cells: raise Exception('Number of scalars must match the number of cells (%d)' % self.n_cells) if not scalars.flags.c_contiguous: raise AssertionError('Array must be contigious') if scalars.dtype == np.bool: scalars = scalars.view(np.uint8) self._cell_bool_array_names.append(name) vtkarr = numpy_to_vtk(scalars, deep=deep) vtkarr.SetName(name) self.GetCellData().AddArray(vtkarr) if set_active or self.active_scalar_info[1] is None: self.GetCellData().SetActiveScalars(name) self._active_scalar_info = [CELL_DATA_FIELD, name]
python
def _add_cell_scalar(self, scalars, name, set_active=False, deep=True): if not isinstance(scalars, np.ndarray): raise TypeError('Input must be a numpy.ndarray') if scalars.shape[0] != self.n_cells: raise Exception('Number of scalars must match the number of cells (%d)' % self.n_cells) if not scalars.flags.c_contiguous: raise AssertionError('Array must be contigious') if scalars.dtype == np.bool: scalars = scalars.view(np.uint8) self._cell_bool_array_names.append(name) vtkarr = numpy_to_vtk(scalars, deep=deep) vtkarr.SetName(name) self.GetCellData().AddArray(vtkarr) if set_active or self.active_scalar_info[1] is None: self.GetCellData().SetActiveScalars(name) self._active_scalar_info = [CELL_DATA_FIELD, name]
[ "def", "_add_cell_scalar", "(", "self", ",", "scalars", ",", "name", ",", "set_active", "=", "False", ",", "deep", "=", "True", ")", ":", "if", "not", "isinstance", "(", "scalars", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Input...
Adds cell scalars to the vtk object. Parameters ---------- scalars : numpy.ndarray Numpy array of scalars. Must match number of points. name : str Name of point scalars to add. set_active : bool, optional Sets the scalars to the active plotting scalars. Default False. deep : bool, optional Does not copy scalars when False. A reference to the scalars must be kept to avoid a segfault.
[ "Adds", "cell", "scalars", "to", "the", "vtk", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L496-L534
236,616
vtkiorg/vtki
vtki/common.py
Common.copy_meta_from
def copy_meta_from(self, ido): """Copies vtki meta data onto this object from another object""" self._active_scalar_info = ido.active_scalar_info self._active_vectors_info = ido.active_vectors_info if hasattr(ido, '_textures'): self._textures = ido._textures
python
def copy_meta_from(self, ido): self._active_scalar_info = ido.active_scalar_info self._active_vectors_info = ido.active_vectors_info if hasattr(ido, '_textures'): self._textures = ido._textures
[ "def", "copy_meta_from", "(", "self", ",", "ido", ")", ":", "self", ".", "_active_scalar_info", "=", "ido", ".", "active_scalar_info", "self", ".", "_active_vectors_info", "=", "ido", ".", "active_vectors_info", "if", "hasattr", "(", "ido", ",", "'_textures'", ...
Copies vtki meta data onto this object from another object
[ "Copies", "vtki", "meta", "data", "onto", "this", "object", "from", "another", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L536-L541
236,617
vtkiorg/vtki
vtki/common.py
Common.copy
def copy(self, deep=True): """ Returns a copy of the object Parameters ---------- deep : bool, optional When True makes a full copy of the object. Returns ------- newobject : same as input Deep or shallow copy of the input. """ thistype = type(self) newobject = thistype() if deep: newobject.DeepCopy(self) else: newobject.ShallowCopy(self) newobject.copy_meta_from(self) return newobject
python
def copy(self, deep=True): thistype = type(self) newobject = thistype() if deep: newobject.DeepCopy(self) else: newobject.ShallowCopy(self) newobject.copy_meta_from(self) return newobject
[ "def", "copy", "(", "self", ",", "deep", "=", "True", ")", ":", "thistype", "=", "type", "(", "self", ")", "newobject", "=", "thistype", "(", ")", "if", "deep", ":", "newobject", ".", "DeepCopy", "(", "self", ")", "else", ":", "newobject", ".", "Sh...
Returns a copy of the object Parameters ---------- deep : bool, optional When True makes a full copy of the object. Returns ------- newobject : same as input Deep or shallow copy of the input.
[ "Returns", "a", "copy", "of", "the", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L543-L564
236,618
vtkiorg/vtki
vtki/common.py
Common.point_arrays
def point_arrays(self): """ Returns the all point arrays """ pdata = self.GetPointData() narr = pdata.GetNumberOfArrays() # Update data if necessary if hasattr(self, '_point_arrays'): keys = list(self._point_arrays.keys()) if narr == len(keys): if keys: if self._point_arrays[keys[0]].size == self.n_points: return self._point_arrays else: return self._point_arrays # dictionary with callbacks self._point_arrays = PointScalarsDict(self) for i in range(narr): name = pdata.GetArrayName(i) self._point_arrays[name] = self._point_scalar(name) self._point_arrays.enable_callback() return self._point_arrays
python
def point_arrays(self): pdata = self.GetPointData() narr = pdata.GetNumberOfArrays() # Update data if necessary if hasattr(self, '_point_arrays'): keys = list(self._point_arrays.keys()) if narr == len(keys): if keys: if self._point_arrays[keys[0]].size == self.n_points: return self._point_arrays else: return self._point_arrays # dictionary with callbacks self._point_arrays = PointScalarsDict(self) for i in range(narr): name = pdata.GetArrayName(i) self._point_arrays[name] = self._point_scalar(name) self._point_arrays.enable_callback() return self._point_arrays
[ "def", "point_arrays", "(", "self", ")", ":", "pdata", "=", "self", ".", "GetPointData", "(", ")", "narr", "=", "pdata", ".", "GetNumberOfArrays", "(", ")", "# Update data if necessary", "if", "hasattr", "(", "self", ",", "'_point_arrays'", ")", ":", "keys",...
Returns the all point arrays
[ "Returns", "the", "all", "point", "arrays" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L572-L595
236,619
vtkiorg/vtki
vtki/common.py
Common.cell_arrays
def cell_arrays(self): """ Returns the all cell arrays """ cdata = self.GetCellData() narr = cdata.GetNumberOfArrays() # Update data if necessary if hasattr(self, '_cell_arrays'): keys = list(self._cell_arrays.keys()) if narr == len(keys): if keys: if self._cell_arrays[keys[0]].size == self.n_cells: return self._cell_arrays else: return self._cell_arrays # dictionary with callbacks self._cell_arrays = CellScalarsDict(self) for i in range(narr): name = cdata.GetArrayName(i) self._cell_arrays[name] = self._cell_scalar(name) self._cell_arrays.enable_callback() return self._cell_arrays
python
def cell_arrays(self): cdata = self.GetCellData() narr = cdata.GetNumberOfArrays() # Update data if necessary if hasattr(self, '_cell_arrays'): keys = list(self._cell_arrays.keys()) if narr == len(keys): if keys: if self._cell_arrays[keys[0]].size == self.n_cells: return self._cell_arrays else: return self._cell_arrays # dictionary with callbacks self._cell_arrays = CellScalarsDict(self) for i in range(narr): name = cdata.GetArrayName(i) self._cell_arrays[name] = self._cell_scalar(name) self._cell_arrays.enable_callback() return self._cell_arrays
[ "def", "cell_arrays", "(", "self", ")", ":", "cdata", "=", "self", ".", "GetCellData", "(", ")", "narr", "=", "cdata", ".", "GetNumberOfArrays", "(", ")", "# Update data if necessary", "if", "hasattr", "(", "self", ",", "'_cell_arrays'", ")", ":", "keys", ...
Returns the all cell arrays
[ "Returns", "the", "all", "cell", "arrays" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L602-L625
236,620
vtkiorg/vtki
vtki/common.py
Common.get_data_range
def get_data_range(self, arr=None, preference='cell'): """Get the non-NaN min and max of a named scalar array Parameters ---------- arr : str, np.ndarray, optional The name of the array to get the range. If None, the active scalar is used preference : str, optional When scalars is specified, this is the perfered scalar type to search for in the dataset. Must be either ``'point'`` or ``'cell'`` """ if arr is None: # use active scalar array _, arr = self.active_scalar_info if isinstance(arr, str): arr = get_scalar(self, arr, preference=preference) # If array has no tuples return a NaN range if arr is None or arr.size == 0: return (np.nan, np.nan) # Use the array range return np.nanmin(arr), np.nanmax(arr)
python
def get_data_range(self, arr=None, preference='cell'): if arr is None: # use active scalar array _, arr = self.active_scalar_info if isinstance(arr, str): arr = get_scalar(self, arr, preference=preference) # If array has no tuples return a NaN range if arr is None or arr.size == 0: return (np.nan, np.nan) # Use the array range return np.nanmin(arr), np.nanmax(arr)
[ "def", "get_data_range", "(", "self", ",", "arr", "=", "None", ",", "preference", "=", "'cell'", ")", ":", "if", "arr", "is", "None", ":", "# use active scalar array", "_", ",", "arr", "=", "self", ".", "active_scalar_info", "if", "isinstance", "(", "arr",...
Get the non-NaN min and max of a named scalar array Parameters ---------- arr : str, np.ndarray, optional The name of the array to get the range. If None, the active scalar is used preference : str, optional When scalars is specified, this is the perfered scalar type to search for in the dataset. Must be either ``'point'`` or ``'cell'``
[ "Get", "the", "non", "-", "NaN", "min", "and", "max", "of", "a", "named", "scalar", "array" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L685-L708
236,621
vtkiorg/vtki
vtki/common.py
Common.scalar_names
def scalar_names(self): """A list of scalar names for the dataset. This makes sure to put the active scalar's name first in the list.""" names = [] for i in range(self.GetPointData().GetNumberOfArrays()): names.append(self.GetPointData().GetArrayName(i)) for i in range(self.GetCellData().GetNumberOfArrays()): names.append(self.GetCellData().GetArrayName(i)) try: names.remove(self.active_scalar_name) names.insert(0, self.active_scalar_name) except ValueError: pass return names
python
def scalar_names(self): names = [] for i in range(self.GetPointData().GetNumberOfArrays()): names.append(self.GetPointData().GetArrayName(i)) for i in range(self.GetCellData().GetNumberOfArrays()): names.append(self.GetCellData().GetArrayName(i)) try: names.remove(self.active_scalar_name) names.insert(0, self.active_scalar_name) except ValueError: pass return names
[ "def", "scalar_names", "(", "self", ")", ":", "names", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "GetPointData", "(", ")", ".", "GetNumberOfArrays", "(", ")", ")", ":", "names", ".", "append", "(", "self", ".", "GetPointData", "(", ...
A list of scalar names for the dataset. This makes sure to put the active scalar's name first in the list.
[ "A", "list", "of", "scalar", "names", "for", "the", "dataset", ".", "This", "makes", "sure", "to", "put", "the", "active", "scalar", "s", "name", "first", "in", "the", "list", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L749-L762
236,622
vtkiorg/vtki
vtki/common.py
Common.head
def head(self, display=True, html=None): """Return the header stats of this dataset. If in IPython, this will be formatted to HTML. Otherwise returns a console friendly string""" # Generate the output if html: fmt = "" # HTML version fmt += "\n" fmt += "<table>\n" fmt += "<tr><th>{}</th><th>Information</th></tr>\n".format(type(self).__name__) row = "<tr><td>{}</td><td>{}</td></tr>\n" # now make a call on the object to get its attributes as a list of len 2 tuples for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += row.format('N Scalars', self.n_scalars) fmt += "</table>\n" fmt += "\n" if display: from IPython.display import display, HTML display(HTML(fmt)) return return fmt # Otherwise return a string that is Python console friendly fmt = "{} ({})\n".format(type(self).__name__, hex(id(self))) # now make a call on the object to get its attributes as a list of len 2 tuples row = " {}:\t{}\n" for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += row.format('N Scalars', self.n_scalars) return fmt
python
def head(self, display=True, html=None): # Generate the output if html: fmt = "" # HTML version fmt += "\n" fmt += "<table>\n" fmt += "<tr><th>{}</th><th>Information</th></tr>\n".format(type(self).__name__) row = "<tr><td>{}</td><td>{}</td></tr>\n" # now make a call on the object to get its attributes as a list of len 2 tuples for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += row.format('N Scalars', self.n_scalars) fmt += "</table>\n" fmt += "\n" if display: from IPython.display import display, HTML display(HTML(fmt)) return return fmt # Otherwise return a string that is Python console friendly fmt = "{} ({})\n".format(type(self).__name__, hex(id(self))) # now make a call on the object to get its attributes as a list of len 2 tuples row = " {}:\t{}\n" for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += row.format('N Scalars', self.n_scalars) return fmt
[ "def", "head", "(", "self", ",", "display", "=", "True", ",", "html", "=", "None", ")", ":", "# Generate the output", "if", "html", ":", "fmt", "=", "\"\"", "# HTML version", "fmt", "+=", "\"\\n\"", "fmt", "+=", "\"<table>\\n\"", "fmt", "+=", "\"<tr><th>{}...
Return the header stats of this dataset. If in IPython, this will be formatted to HTML. Otherwise returns a console friendly string
[ "Return", "the", "header", "stats", "of", "this", "dataset", ".", "If", "in", "IPython", "this", "will", "be", "formatted", "to", "HTML", ".", "Otherwise", "returns", "a", "console", "friendly", "string" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L779-L814
236,623
vtkiorg/vtki
vtki/common.py
Common._repr_html_
def _repr_html_(self): """A pretty representation for Jupyter notebooks that includes header details and information about all scalar arrays""" fmt = "" if self.n_scalars > 0: fmt += "<table>" fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>" fmt += "<tr><td>" # Get the header info fmt += self.head(display=False, html=True) # Fill out scalar arrays if self.n_scalars > 0: fmt += "</td><td>" fmt += "\n" fmt += "<table>\n" row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n" fmt += row.format("Name", "Field", "Type", "Min", "Max") row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n" def format_array(key, field): """internal helper to foramt array information for printing""" arr = get_scalar(self, key) dl, dh = self.get_data_range(key) if key == self.active_scalar_info[1]: key = '<b>{}</b>'.format(key) return row.format(key, field, arr.dtype, dl, dh) for i in range(self.GetPointData().GetNumberOfArrays()): key = self.GetPointData().GetArrayName(i) fmt += format_array(key, field='Points') for i in range(self.GetCellData().GetNumberOfArrays()): key = self.GetCellData().GetArrayName(i) fmt += format_array(key, field='Cells') fmt += "</table>\n" fmt += "\n" fmt += "</td></tr> </table>" return fmt
python
def _repr_html_(self): fmt = "" if self.n_scalars > 0: fmt += "<table>" fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>" fmt += "<tr><td>" # Get the header info fmt += self.head(display=False, html=True) # Fill out scalar arrays if self.n_scalars > 0: fmt += "</td><td>" fmt += "\n" fmt += "<table>\n" row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n" fmt += row.format("Name", "Field", "Type", "Min", "Max") row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n" def format_array(key, field): """internal helper to foramt array information for printing""" arr = get_scalar(self, key) dl, dh = self.get_data_range(key) if key == self.active_scalar_info[1]: key = '<b>{}</b>'.format(key) return row.format(key, field, arr.dtype, dl, dh) for i in range(self.GetPointData().GetNumberOfArrays()): key = self.GetPointData().GetArrayName(i) fmt += format_array(key, field='Points') for i in range(self.GetCellData().GetNumberOfArrays()): key = self.GetCellData().GetArrayName(i) fmt += format_array(key, field='Cells') fmt += "</table>\n" fmt += "\n" fmt += "</td></tr> </table>" return fmt
[ "def", "_repr_html_", "(", "self", ")", ":", "fmt", "=", "\"\"", "if", "self", ".", "n_scalars", ">", "0", ":", "fmt", "+=", "\"<table>\"", "fmt", "+=", "\"<tr><th>Header</th><th>Data Arrays</th></tr>\"", "fmt", "+=", "\"<tr><td>\"", "# Get the header info", "fmt"...
A pretty representation for Jupyter notebooks that includes header details and information about all scalar arrays
[ "A", "pretty", "representation", "for", "Jupyter", "notebooks", "that", "includes", "header", "details", "and", "information", "about", "all", "scalar", "arrays" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L817-L853
236,624
vtkiorg/vtki
vtki/common.py
Common.overwrite
def overwrite(self, mesh): """ Overwrites this mesh inplace with the new mesh's geometries and data Parameters ---------- mesh : vtk.vtkDataSet The overwriting mesh. """ self.DeepCopy(mesh) if is_vtki_obj(mesh): self.copy_meta_from(mesh)
python
def overwrite(self, mesh): self.DeepCopy(mesh) if is_vtki_obj(mesh): self.copy_meta_from(mesh)
[ "def", "overwrite", "(", "self", ",", "mesh", ")", ":", "self", ".", "DeepCopy", "(", "mesh", ")", "if", "is_vtki_obj", "(", "mesh", ")", ":", "self", ".", "copy_meta_from", "(", "mesh", ")" ]
Overwrites this mesh inplace with the new mesh's geometries and data Parameters ---------- mesh : vtk.vtkDataSet The overwriting mesh.
[ "Overwrites", "this", "mesh", "inplace", "with", "the", "new", "mesh", "s", "geometries", "and", "data" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L864-L876
236,625
vtkiorg/vtki
vtki/common.py
_ScalarsDict.pop
def pop(self, key): """Get and remove an element by key name""" arr = dict.pop(self, key).copy() self.remover(key) return arr
python
def pop(self, key): arr = dict.pop(self, key).copy() self.remover(key) return arr
[ "def", "pop", "(", "self", ",", "key", ")", ":", "arr", "=", "dict", ".", "pop", "(", "self", ",", "key", ")", ".", "copy", "(", ")", "self", ".", "remover", "(", "key", ")", "return", "arr" ]
Get and remove an element by key name
[ "Get", "and", "remove", "an", "element", "by", "key", "name" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L901-L905
236,626
vtkiorg/vtki
vtki/common.py
_ScalarsDict.update
def update(self, data): """ Update this dictionary with th key-value pairs from a given dictionary """ if not isinstance(data, dict): raise TypeError('Data to update must be in a dictionary.') for k, v in data.items(): arr = np.array(v) try: self[k] = arr except TypeError: logging.warning("Values under key ({}) not supported by VTK".format(k)) return
python
def update(self, data): if not isinstance(data, dict): raise TypeError('Data to update must be in a dictionary.') for k, v in data.items(): arr = np.array(v) try: self[k] = arr except TypeError: logging.warning("Values under key ({}) not supported by VTK".format(k)) return
[ "def", "update", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Data to update must be in a dictionary.'", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ...
Update this dictionary with th key-value pairs from a given dictionary
[ "Update", "this", "dictionary", "with", "th", "key", "-", "value", "pairs", "from", "a", "given", "dictionary" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L907-L920
236,627
chardet/chardet
convert_language_model.py
convert_sbcs_model
def convert_sbcs_model(old_model, alphabet): """Create a SingleByteCharSetModel object representing the charset.""" # Setup tables necessary for computing transition frequencies for model char_to_order = {i: order for i, order in enumerate(old_model['char_to_order_map'])} pos_ratio = old_model['typical_positive_ratio'] keep_ascii_letters = old_model['keep_english_letter'] curr_model = SingleByteCharSetModel(charset_name=old_model['charset_name'], language=old_model['language'], char_to_order_map=char_to_order, # language_model is filled in later language_model=None, typical_positive_ratio=pos_ratio, keep_ascii_letters=keep_ascii_letters, alphabet=alphabet) return curr_model
python
def convert_sbcs_model(old_model, alphabet): # Setup tables necessary for computing transition frequencies for model char_to_order = {i: order for i, order in enumerate(old_model['char_to_order_map'])} pos_ratio = old_model['typical_positive_ratio'] keep_ascii_letters = old_model['keep_english_letter'] curr_model = SingleByteCharSetModel(charset_name=old_model['charset_name'], language=old_model['language'], char_to_order_map=char_to_order, # language_model is filled in later language_model=None, typical_positive_ratio=pos_ratio, keep_ascii_letters=keep_ascii_letters, alphabet=alphabet) return curr_model
[ "def", "convert_sbcs_model", "(", "old_model", ",", "alphabet", ")", ":", "# Setup tables necessary for computing transition frequencies for model", "char_to_order", "=", "{", "i", ":", "order", "for", "i", ",", "order", "in", "enumerate", "(", "old_model", "[", "'cha...
Create a SingleByteCharSetModel object representing the charset.
[ "Create", "a", "SingleByteCharSetModel", "object", "representing", "the", "charset", "." ]
b5194bf8250b7d180ac4edff51e09cab9d99febe
https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/convert_language_model.py#L57-L73
236,628
chardet/chardet
bench.py
get_py_impl
def get_py_impl(): """Return what kind of Python this is""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'PyPy' elif sys.platform.startswith('java'): pyimpl = 'Jython' elif sys.platform == 'cli': pyimpl = 'IronPython' else: pyimpl = 'CPython' return pyimpl
python
def get_py_impl(): if hasattr(sys, 'pypy_version_info'): pyimpl = 'PyPy' elif sys.platform.startswith('java'): pyimpl = 'Jython' elif sys.platform == 'cli': pyimpl = 'IronPython' else: pyimpl = 'CPython' return pyimpl
[ "def", "get_py_impl", "(", ")", ":", "if", "hasattr", "(", "sys", ",", "'pypy_version_info'", ")", ":", "pyimpl", "=", "'PyPy'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", ":", "pyimpl", "=", "'Jython'", "elif", "sys", ".", ...
Return what kind of Python this is
[ "Return", "what", "kind", "of", "Python", "this", "is" ]
b5194bf8250b7d180ac4edff51e09cab9d99febe
https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/bench.py#L36-L46
236,629
chardet/chardet
chardet/__init__.py
detect_all
def detect_all(byte_str): """ Detect all the possible encodings of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) detector.close() if detector._input_state == InputState.HIGH_BYTE: results = [] for prober in detector._charset_probers: if prober.get_confidence() > detector.MINIMUM_THRESHOLD: charset_name = prober.charset_name lower_charset_name = prober.charset_name.lower() # Use Windows encoding name instead of ISO-8859 if we saw any # extra Windows-specific bytes if lower_charset_name.startswith('iso-8859'): if detector._has_win_bytes: charset_name = detector.ISO_WIN_MAP.get(lower_charset_name, charset_name) results.append({ 'encoding': charset_name, 'confidence': prober.get_confidence() }) if len(results) > 0: return sorted(results, key=lambda result: -result['confidence']) return [detector.result]
python
def detect_all(byte_str): if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) detector.close() if detector._input_state == InputState.HIGH_BYTE: results = [] for prober in detector._charset_probers: if prober.get_confidence() > detector.MINIMUM_THRESHOLD: charset_name = prober.charset_name lower_charset_name = prober.charset_name.lower() # Use Windows encoding name instead of ISO-8859 if we saw any # extra Windows-specific bytes if lower_charset_name.startswith('iso-8859'): if detector._has_win_bytes: charset_name = detector.ISO_WIN_MAP.get(lower_charset_name, charset_name) results.append({ 'encoding': charset_name, 'confidence': prober.get_confidence() }) if len(results) > 0: return sorted(results, key=lambda result: -result['confidence']) return [detector.result]
[ "def", "detect_all", "(", "byte_str", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytearray", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Expected object of type bytes or bytearray, g...
Detect all the possible encodings of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
[ "Detect", "all", "the", "possible", "encodings", "of", "the", "given", "byte", "string", "." ]
b5194bf8250b7d180ac4edff51e09cab9d99febe
https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/chardet/__init__.py#L45-L82
236,630
sentinelsat/sentinelsat
sentinelsat/sentinel.py
geojson_to_wkt
def geojson_to_wkt(geojson_obj, feature_number=0, decimals=4): """Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries. In case of FeatureCollection, only one of the features is used (the first by default). 3D points are converted to 2D. Parameters ---------- geojson_obj : dict a GeoJSON object feature_number : int, optional Feature to extract polygon from (in case of MultiPolygon FeatureCollection), defaults to first Feature decimals : int, optional Number of decimal figures after point to round coordinate to. Defaults to 4 (about 10 meters). Returns ------- polygon coordinates string of comma separated coordinate tuples (lon, lat) to be used by SentinelAPI """ if 'coordinates' in geojson_obj: geometry = geojson_obj elif 'geometry' in geojson_obj: geometry = geojson_obj['geometry'] else: geometry = geojson_obj['features'][feature_number]['geometry'] def ensure_2d(geometry): if isinstance(geometry[0], (list, tuple)): return list(map(ensure_2d, geometry)) else: return geometry[:2] def check_bounds(geometry): if isinstance(geometry[0], (list, tuple)): return list(map(check_bounds, geometry)) else: if geometry[0] > 180 or geometry[0] < -180: raise ValueError('Longitude is out of bounds, check your JSON format or data') if geometry[1] > 90 or geometry[1] < -90: raise ValueError('Latitude is out of bounds, check your JSON format or data') # Discard z-coordinate, if it exists geometry['coordinates'] = ensure_2d(geometry['coordinates']) check_bounds(geometry['coordinates']) wkt = geomet.wkt.dumps(geometry, decimals=decimals) # Strip unnecessary spaces wkt = re.sub(r'(?<!\d) ', '', wkt) return wkt
python
def geojson_to_wkt(geojson_obj, feature_number=0, decimals=4): if 'coordinates' in geojson_obj: geometry = geojson_obj elif 'geometry' in geojson_obj: geometry = geojson_obj['geometry'] else: geometry = geojson_obj['features'][feature_number]['geometry'] def ensure_2d(geometry): if isinstance(geometry[0], (list, tuple)): return list(map(ensure_2d, geometry)) else: return geometry[:2] def check_bounds(geometry): if isinstance(geometry[0], (list, tuple)): return list(map(check_bounds, geometry)) else: if geometry[0] > 180 or geometry[0] < -180: raise ValueError('Longitude is out of bounds, check your JSON format or data') if geometry[1] > 90 or geometry[1] < -90: raise ValueError('Latitude is out of bounds, check your JSON format or data') # Discard z-coordinate, if it exists geometry['coordinates'] = ensure_2d(geometry['coordinates']) check_bounds(geometry['coordinates']) wkt = geomet.wkt.dumps(geometry, decimals=decimals) # Strip unnecessary spaces wkt = re.sub(r'(?<!\d) ', '', wkt) return wkt
[ "def", "geojson_to_wkt", "(", "geojson_obj", ",", "feature_number", "=", "0", ",", "decimals", "=", "4", ")", ":", "if", "'coordinates'", "in", "geojson_obj", ":", "geometry", "=", "geojson_obj", "elif", "'geometry'", "in", "geojson_obj", ":", "geometry", "=",...
Convert a GeoJSON object to Well-Known Text. Intended for use with OpenSearch queries. In case of FeatureCollection, only one of the features is used (the first by default). 3D points are converted to 2D. Parameters ---------- geojson_obj : dict a GeoJSON object feature_number : int, optional Feature to extract polygon from (in case of MultiPolygon FeatureCollection), defaults to first Feature decimals : int, optional Number of decimal figures after point to round coordinate to. Defaults to 4 (about 10 meters). Returns ------- polygon coordinates string of comma separated coordinate tuples (lon, lat) to be used by SentinelAPI
[ "Convert", "a", "GeoJSON", "object", "to", "Well", "-", "Known", "Text", ".", "Intended", "for", "use", "with", "OpenSearch", "queries", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L889-L940
236,631
sentinelsat/sentinelsat
sentinelsat/sentinel.py
_check_scihub_response
def _check_scihub_response(response, test_json=True): """Check that the response from server has status code 2xx and that the response is valid JSON. """ # Prevent requests from needing to guess the encoding # SciHub appears to be using UTF-8 in all of their responses response.encoding = 'utf-8' try: response.raise_for_status() if test_json: response.json() except (requests.HTTPError, ValueError): msg = "Invalid API response." try: msg = response.headers['cause-message'] except: try: msg = response.json()['error']['message']['value'] except: if not response.text.strip().startswith('{'): try: h = html2text.HTML2Text() h.ignore_images = True h.ignore_anchors = True msg = h.handle(response.text).strip() except: pass api_error = SentinelAPIError(msg, response) # Suppress "During handling of the above exception..." message # See PEP 409 api_error.__cause__ = None raise api_error
python
def _check_scihub_response(response, test_json=True): # Prevent requests from needing to guess the encoding # SciHub appears to be using UTF-8 in all of their responses response.encoding = 'utf-8' try: response.raise_for_status() if test_json: response.json() except (requests.HTTPError, ValueError): msg = "Invalid API response." try: msg = response.headers['cause-message'] except: try: msg = response.json()['error']['message']['value'] except: if not response.text.strip().startswith('{'): try: h = html2text.HTML2Text() h.ignore_images = True h.ignore_anchors = True msg = h.handle(response.text).strip() except: pass api_error = SentinelAPIError(msg, response) # Suppress "During handling of the above exception..." message # See PEP 409 api_error.__cause__ = None raise api_error
[ "def", "_check_scihub_response", "(", "response", ",", "test_json", "=", "True", ")", ":", "# Prevent requests from needing to guess the encoding", "# SciHub appears to be using UTF-8 in all of their responses", "response", ".", "encoding", "=", "'utf-8'", "try", ":", "response...
Check that the response from server has status code 2xx and that the response is valid JSON.
[ "Check", "that", "the", "response", "from", "server", "has", "status", "code", "2xx", "and", "that", "the", "response", "is", "valid", "JSON", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L997-L1027
236,632
sentinelsat/sentinelsat
sentinelsat/sentinel.py
_parse_odata_timestamp
def _parse_odata_timestamp(in_date): """Convert the timestamp received from OData JSON API to a datetime object. """ timestamp = int(in_date.replace('/Date(', '').replace(')/', '')) seconds = timestamp // 1000 ms = timestamp % 1000 return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms)
python
def _parse_odata_timestamp(in_date): timestamp = int(in_date.replace('/Date(', '').replace(')/', '')) seconds = timestamp // 1000 ms = timestamp % 1000 return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms)
[ "def", "_parse_odata_timestamp", "(", "in_date", ")", ":", "timestamp", "=", "int", "(", "in_date", ".", "replace", "(", "'/Date('", ",", "''", ")", ".", "replace", "(", "')/'", ",", "''", ")", ")", "seconds", "=", "timestamp", "//", "1000", "ms", "=",...
Convert the timestamp received from OData JSON API to a datetime object.
[ "Convert", "the", "timestamp", "received", "from", "OData", "JSON", "API", "to", "a", "datetime", "object", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L1066-L1072
236,633
sentinelsat/sentinelsat
sentinelsat/sentinel.py
_parse_opensearch_response
def _parse_opensearch_response(products): """Convert a query response to a dictionary. The resulting dictionary structure is {<product id>: {<property>: <value>}}. The property values are converted to their respective Python types unless `parse_values` is set to `False`. """ converters = {'date': _parse_iso_date, 'int': int, 'long': int, 'float': float, 'double': float} # Keep the string type by default default_converter = lambda x: x output = OrderedDict() for prod in products: product_dict = {} prod_id = prod['id'] output[prod_id] = product_dict for key in prod: if key == 'id': continue if isinstance(prod[key], string_types): product_dict[key] = prod[key] else: properties = prod[key] if isinstance(properties, dict): properties = [properties] if key == 'link': for p in properties: name = 'link' if 'rel' in p: name = 'link_' + p['rel'] product_dict[name] = p['href'] else: f = converters.get(key, default_converter) for p in properties: try: product_dict[p['name']] = f(p['content']) except KeyError: # Sentinel-3 has one element 'arr' # which violates the name:content convention product_dict[p['name']] = f(p['str']) return output
python
def _parse_opensearch_response(products): converters = {'date': _parse_iso_date, 'int': int, 'long': int, 'float': float, 'double': float} # Keep the string type by default default_converter = lambda x: x output = OrderedDict() for prod in products: product_dict = {} prod_id = prod['id'] output[prod_id] = product_dict for key in prod: if key == 'id': continue if isinstance(prod[key], string_types): product_dict[key] = prod[key] else: properties = prod[key] if isinstance(properties, dict): properties = [properties] if key == 'link': for p in properties: name = 'link' if 'rel' in p: name = 'link_' + p['rel'] product_dict[name] = p['href'] else: f = converters.get(key, default_converter) for p in properties: try: product_dict[p['name']] = f(p['content']) except KeyError: # Sentinel-3 has one element 'arr' # which violates the name:content convention product_dict[p['name']] = f(p['str']) return output
[ "def", "_parse_opensearch_response", "(", "products", ")", ":", "converters", "=", "{", "'date'", ":", "_parse_iso_date", ",", "'int'", ":", "int", ",", "'long'", ":", "int", ",", "'float'", ":", "float", ",", "'double'", ":", "float", "}", "# Keep the strin...
Convert a query response to a dictionary. The resulting dictionary structure is {<product id>: {<property>: <value>}}. The property values are converted to their respective Python types unless `parse_values` is set to `False`.
[ "Convert", "a", "query", "response", "to", "a", "dictionary", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L1075-L1116
236,634
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.query
def query(self, area=None, date=None, raw=None, area_relation='Intersects', order_by=None, limit=None, offset=0, **keywords): """Query the OpenSearch API with the coordinates of an area, a date interval and any other search keywords accepted by the API. Parameters ---------- area : str, optional The area of interest formatted as a Well-Known Text string. date : tuple of (str or datetime) or str, optional A time interval filter based on the Sensing Start Time of the products. Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW"). The timestamps can be either a Python datetime or a string in one of the following formats: - yyyyMMdd - yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601) - yyyy-MM-ddThh:mm:ssZ - NOW - NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.) - NOW+<n>DAY(S) - yyyy-MM-ddThh:mm:ssZ-<n>DAY(S) - NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be used as well. raw : str, optional Additional query text that will be appended to the query. area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional What relation to use for testing the AOI. Case insensitive. - Intersects: true if the AOI and the footprint intersect (default) - Contains: true if the AOI is inside the footprint - IsWithin: true if the footprint is inside the AOI order_by: str, optional A comma-separated list of fields to order by (on server side). Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively. Ascending order is used if prefix is omitted. Example: "cloudcoverpercentage, -beginposition". limit: int, optional Maximum number of products returned. Defaults to no limit. offset: int, optional The number of results to skip. Defaults to 0. **keywords Additional keywords can be used to specify other query parameters, e.g. `relativeorbitnumber=70`. See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch for a full list. Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`. `None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`. Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query. The time interval formats accepted by the `date` parameter can also be used with any other parameters that expect time intervals (that is: 'beginposition', 'endposition', 'date', 'creationdate', and 'ingestiondate'). Returns ------- dict[string, dict] Products returned by the query as a dictionary with the product ID as the key and the product's attributes (a dictionary) as the value. """ query = self.format_query(area, date, raw, area_relation, **keywords) self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s", order_by, limit, offset, query) formatted_order_by = _format_order_by(order_by) response, count = self._load_query(query, formatted_order_by, limit, offset) self.logger.info("Found %s products", count) return _parse_opensearch_response(response)
python
def query(self, area=None, date=None, raw=None, area_relation='Intersects', order_by=None, limit=None, offset=0, **keywords): query = self.format_query(area, date, raw, area_relation, **keywords) self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s", order_by, limit, offset, query) formatted_order_by = _format_order_by(order_by) response, count = self._load_query(query, formatted_order_by, limit, offset) self.logger.info("Found %s products", count) return _parse_opensearch_response(response)
[ "def", "query", "(", "self", ",", "area", "=", "None", ",", "date", "=", "None", ",", "raw", "=", "None", ",", "area_relation", "=", "'Intersects'", ",", "order_by", "=", "None", ",", "limit", "=", "None", ",", "offset", "=", "0", ",", "*", "*", ...
Query the OpenSearch API with the coordinates of an area, a date interval and any other search keywords accepted by the API. Parameters ---------- area : str, optional The area of interest formatted as a Well-Known Text string. date : tuple of (str or datetime) or str, optional A time interval filter based on the Sensing Start Time of the products. Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW"). The timestamps can be either a Python datetime or a string in one of the following formats: - yyyyMMdd - yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601) - yyyy-MM-ddThh:mm:ssZ - NOW - NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.) - NOW+<n>DAY(S) - yyyy-MM-ddThh:mm:ssZ-<n>DAY(S) - NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be used as well. raw : str, optional Additional query text that will be appended to the query. area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional What relation to use for testing the AOI. Case insensitive. - Intersects: true if the AOI and the footprint intersect (default) - Contains: true if the AOI is inside the footprint - IsWithin: true if the footprint is inside the AOI order_by: str, optional A comma-separated list of fields to order by (on server side). Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively. Ascending order is used if prefix is omitted. Example: "cloudcoverpercentage, -beginposition". limit: int, optional Maximum number of products returned. Defaults to no limit. offset: int, optional The number of results to skip. Defaults to 0. **keywords Additional keywords can be used to specify other query parameters, e.g. `relativeorbitnumber=70`. See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch for a full list. Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`. `None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`. Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query. The time interval formats accepted by the `date` parameter can also be used with any other parameters that expect time intervals (that is: 'beginposition', 'endposition', 'date', 'creationdate', and 'ingestiondate'). Returns ------- dict[string, dict] Products returned by the query as a dictionary with the product ID as the key and the product's attributes (a dictionary) as the value.
[ "Query", "the", "OpenSearch", "API", "with", "the", "coordinates", "of", "an", "area", "a", "date", "interval", "and", "any", "other", "search", "keywords", "accepted", "by", "the", "API", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L77-L149
236,635
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.format_query
def format_query(area=None, date=None, raw=None, area_relation='Intersects', **keywords): """Create a OpenSearch API query string. """ if area_relation.lower() not in {"intersects", "contains", "iswithin"}: raise ValueError("Incorrect AOI relation provided ({})".format(area_relation)) # Check for duplicate keywords kw_lower = set(x.lower() for x in keywords) if (len(kw_lower) != len(keywords) or (date is not None and 'beginposition' in kw_lower) or (area is not None and 'footprint' in kw_lower)): raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.") query_parts = [] if date is not None: keywords['beginPosition'] = date for attr, value in sorted(keywords.items()): # Escape spaces, where appropriate if isinstance(value, string_types): value = value.strip() if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']): value = re.sub(r'\s', r'\ ', value, re.M) # Handle date keywords # Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601 date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate'] if attr.lower() in date_attrs: # Automatically format date-type attributes if isinstance(value, string_types) and ' TO ' in value: # This is a string already formatted as a date interval, # e.g. '[NOW-1DAY TO NOW]' pass elif not isinstance(value, string_types) and len(value) == 2: value = (format_query_date(value[0]), format_query_date(value[1])) else: raise ValueError("Date-type query parameter '{}' expects a two-element tuple " "of str or datetime objects. Received {}".format(attr, value)) # Handle ranged values if isinstance(value, (list, tuple)): # Handle value ranges if len(value) == 2: # Allow None to be used as a unlimited bound value = ['*' if x is None else x for x in value] if all(x == '*' for x in value): continue value = '[{} TO {}]'.format(*value) else: raise ValueError("Invalid number of elements in list. Expected 2, received " "{}".format(len(value))) query_parts.append('{}:{}'.format(attr, value)) if raw: query_parts.append(raw) if area is not None: query_parts.append('footprint:"{}({})"'.format(area_relation, area)) return ' '.join(query_parts)
python
def format_query(area=None, date=None, raw=None, area_relation='Intersects', **keywords): if area_relation.lower() not in {"intersects", "contains", "iswithin"}: raise ValueError("Incorrect AOI relation provided ({})".format(area_relation)) # Check for duplicate keywords kw_lower = set(x.lower() for x in keywords) if (len(kw_lower) != len(keywords) or (date is not None and 'beginposition' in kw_lower) or (area is not None and 'footprint' in kw_lower)): raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.") query_parts = [] if date is not None: keywords['beginPosition'] = date for attr, value in sorted(keywords.items()): # Escape spaces, where appropriate if isinstance(value, string_types): value = value.strip() if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']): value = re.sub(r'\s', r'\ ', value, re.M) # Handle date keywords # Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601 date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate'] if attr.lower() in date_attrs: # Automatically format date-type attributes if isinstance(value, string_types) and ' TO ' in value: # This is a string already formatted as a date interval, # e.g. '[NOW-1DAY TO NOW]' pass elif not isinstance(value, string_types) and len(value) == 2: value = (format_query_date(value[0]), format_query_date(value[1])) else: raise ValueError("Date-type query parameter '{}' expects a two-element tuple " "of str or datetime objects. Received {}".format(attr, value)) # Handle ranged values if isinstance(value, (list, tuple)): # Handle value ranges if len(value) == 2: # Allow None to be used as a unlimited bound value = ['*' if x is None else x for x in value] if all(x == '*' for x in value): continue value = '[{} TO {}]'.format(*value) else: raise ValueError("Invalid number of elements in list. Expected 2, received " "{}".format(len(value))) query_parts.append('{}:{}'.format(attr, value)) if raw: query_parts.append(raw) if area is not None: query_parts.append('footprint:"{}({})"'.format(area_relation, area)) return ' '.join(query_parts)
[ "def", "format_query", "(", "area", "=", "None", ",", "date", "=", "None", ",", "raw", "=", "None", ",", "area_relation", "=", "'Intersects'", ",", "*", "*", "keywords", ")", ":", "if", "area_relation", ".", "lower", "(", ")", "not", "in", "{", "\"in...
Create a OpenSearch API query string.
[ "Create", "a", "OpenSearch", "API", "query", "string", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L152-L214
236,636
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.count
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords): """Get the number of products matching a query. Accepted parameters are identical to :meth:`SentinelAPI.query()`. This is a significantly more efficient alternative to doing `len(api.query())`, which can take minutes to run for queries matching thousands of products. Returns ------- int The number of products matching a query. """ for kw in ['order_by', 'limit', 'offset']: # Allow these function arguments to be included for compatibility with query(), # but ignore them. if kw in keywords: del keywords[kw] query = self.format_query(area, date, raw, area_relation, **keywords) _, total_count = self._load_query(query, limit=0) return total_count
python
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords): for kw in ['order_by', 'limit', 'offset']: # Allow these function arguments to be included for compatibility with query(), # but ignore them. if kw in keywords: del keywords[kw] query = self.format_query(area, date, raw, area_relation, **keywords) _, total_count = self._load_query(query, limit=0) return total_count
[ "def", "count", "(", "self", ",", "area", "=", "None", ",", "date", "=", "None", ",", "raw", "=", "None", ",", "area_relation", "=", "'Intersects'", ",", "*", "*", "keywords", ")", ":", "for", "kw", "in", "[", "'order_by'", ",", "'limit'", ",", "'o...
Get the number of products matching a query. Accepted parameters are identical to :meth:`SentinelAPI.query()`. This is a significantly more efficient alternative to doing `len(api.query())`, which can take minutes to run for queries matching thousands of products. Returns ------- int The number of products matching a query.
[ "Get", "the", "number", "of", "products", "matching", "a", "query", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L249-L269
236,637
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.to_geojson
def to_geojson(products): """Return the products from a query response as a GeoJSON with the values in their appropriate Python types. """ feature_list = [] for i, (product_id, props) in enumerate(products.items()): props = props.copy() props['id'] = product_id poly = geomet.wkt.loads(props['footprint']) del props['footprint'] del props['gmlfootprint'] # Fix "'datetime' is not JSON serializable" for k, v in props.items(): if isinstance(v, (date, datetime)): props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ') feature_list.append( geojson.Feature(geometry=poly, id=i, properties=props) ) return geojson.FeatureCollection(feature_list)
python
def to_geojson(products): feature_list = [] for i, (product_id, props) in enumerate(products.items()): props = props.copy() props['id'] = product_id poly = geomet.wkt.loads(props['footprint']) del props['footprint'] del props['gmlfootprint'] # Fix "'datetime' is not JSON serializable" for k, v in props.items(): if isinstance(v, (date, datetime)): props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ') feature_list.append( geojson.Feature(geometry=poly, id=i, properties=props) ) return geojson.FeatureCollection(feature_list)
[ "def", "to_geojson", "(", "products", ")", ":", "feature_list", "=", "[", "]", "for", "i", ",", "(", "product_id", ",", "props", ")", "in", "enumerate", "(", "products", ".", "items", "(", ")", ")", ":", "props", "=", "props", ".", "copy", "(", ")"...
Return the products from a query response as a GeoJSON with the values in their appropriate Python types.
[ "Return", "the", "products", "from", "a", "query", "response", "as", "a", "GeoJSON", "with", "the", "values", "in", "their", "appropriate", "Python", "types", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L340-L358
236,638
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.to_dataframe
def to_dataframe(products): """Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types. """ try: import pandas as pd except ImportError: raise ImportError("to_dataframe requires the optional dependency Pandas.") return pd.DataFrame.from_dict(products, orient='index')
python
def to_dataframe(products): try: import pandas as pd except ImportError: raise ImportError("to_dataframe requires the optional dependency Pandas.") return pd.DataFrame.from_dict(products, orient='index')
[ "def", "to_dataframe", "(", "products", ")", ":", "try", ":", "import", "pandas", "as", "pd", "except", "ImportError", ":", "raise", "ImportError", "(", "\"to_dataframe requires the optional dependency Pandas.\"", ")", "return", "pd", ".", "DataFrame", ".", "from_di...
Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types.
[ "Return", "the", "products", "from", "a", "query", "response", "as", "a", "Pandas", "DataFrame", "with", "the", "values", "in", "their", "appropriate", "Python", "types", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L361-L370
236,639
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.to_geodataframe
def to_geodataframe(products): """Return the products from a query response as a GeoPandas GeoDataFrame with the values in their appropriate Python types. """ try: import geopandas as gpd import shapely.wkt except ImportError: raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.") crs = {'init': 'epsg:4326'} # WGS84 if len(products) == 0: return gpd.GeoDataFrame(crs=crs) df = SentinelAPI.to_dataframe(products) geometry = [shapely.wkt.loads(fp) for fp in df['footprint']] # remove useless columns df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True) return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
python
def to_geodataframe(products): try: import geopandas as gpd import shapely.wkt except ImportError: raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.") crs = {'init': 'epsg:4326'} # WGS84 if len(products) == 0: return gpd.GeoDataFrame(crs=crs) df = SentinelAPI.to_dataframe(products) geometry = [shapely.wkt.loads(fp) for fp in df['footprint']] # remove useless columns df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True) return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
[ "def", "to_geodataframe", "(", "products", ")", ":", "try", ":", "import", "geopandas", "as", "gpd", "import", "shapely", ".", "wkt", "except", "ImportError", ":", "raise", "ImportError", "(", "\"to_geodataframe requires the optional dependencies GeoPandas and Shapely.\""...
Return the products from a query response as a GeoPandas GeoDataFrame with the values in their appropriate Python types.
[ "Return", "the", "products", "from", "a", "query", "response", "as", "a", "GeoPandas", "GeoDataFrame", "with", "the", "values", "in", "their", "appropriate", "Python", "types", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L373-L391
236,640
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.get_product_odata
def get_product_odata(self, id, full=False): """Access OData API to get info about a product. Returns a dict containing the id, title, size, md5sum, date, footprint and download url of the product. The date field corresponds to the Start ContentDate value. If `full` is set to True, then the full, detailed metadata of the product is returned in addition to the above. Parameters ---------- id : string The UUID of the product to query full : bool Whether to get the full metadata for the Product. False by default. Returns ------- dict[str, Any] A dictionary with an item for each metadata attribute Notes ----- For a full list of mappings between the OpenSearch (Solr) and OData attribute names see the following definition files: https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl """ url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id)) if full: url += '&$expand=Attributes' response = self.session.get(url, auth=self.session.auth, timeout=self.timeout) _check_scihub_response(response) values = _parse_odata_response(response.json()['d']) return values
python
def get_product_odata(self, id, full=False): url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id)) if full: url += '&$expand=Attributes' response = self.session.get(url, auth=self.session.auth, timeout=self.timeout) _check_scihub_response(response) values = _parse_odata_response(response.json()['d']) return values
[ "def", "get_product_odata", "(", "self", ",", "id", ",", "full", "=", "False", ")", ":", "url", "=", "urljoin", "(", "self", ".", "api_url", ",", "u\"odata/v1/Products('{}')?$format=json\"", ".", "format", "(", "id", ")", ")", "if", "full", ":", "url", "...
Access OData API to get info about a product. Returns a dict containing the id, title, size, md5sum, date, footprint and download url of the product. The date field corresponds to the Start ContentDate value. If `full` is set to True, then the full, detailed metadata of the product is returned in addition to the above. Parameters ---------- id : string The UUID of the product to query full : bool Whether to get the full metadata for the Product. False by default. Returns ------- dict[str, Any] A dictionary with an item for each metadata attribute Notes ----- For a full list of mappings between the OpenSearch (Solr) and OData attribute names see the following definition files: https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
[ "Access", "OData", "API", "to", "get", "info", "about", "a", "product", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L393-L429
236,641
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI._trigger_offline_retrieval
def _trigger_offline_retrieval(self, url): """ Triggers retrieval of an offline product Trying to download an offline product triggers its retrieval from the long term archive. The returned HTTP status code conveys whether this was successful. Parameters ---------- url : string URL for downloading the product Notes ----- https://scihub.copernicus.eu/userguide/LongTermArchive """ with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r: # check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes if r.status_code == 202: self.logger.info("Accepted for retrieval") elif r.status_code == 503: self.logger.error("Request not accepted") raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r) elif r.status_code == 403: self.logger.error("Requests exceed user quota") raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r) elif r.status_code == 500: # should not happen self.logger.error("Trying to download an offline product") raise SentinelAPILTAError('Trying to download an offline product', r) return r.status_code
python
def _trigger_offline_retrieval(self, url): with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r: # check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes if r.status_code == 202: self.logger.info("Accepted for retrieval") elif r.status_code == 503: self.logger.error("Request not accepted") raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r) elif r.status_code == 403: self.logger.error("Requests exceed user quota") raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r) elif r.status_code == 500: # should not happen self.logger.error("Trying to download an offline product") raise SentinelAPILTAError('Trying to download an offline product', r) return r.status_code
[ "def", "_trigger_offline_retrieval", "(", "self", ",", "url", ")", ":", "with", "self", ".", "session", ".", "get", "(", "url", ",", "auth", "=", "self", ".", "session", ".", "auth", ",", "timeout", "=", "self", ".", "timeout", ")", "as", "r", ":", ...
Triggers retrieval of an offline product Trying to download an offline product triggers its retrieval from the long term archive. The returned HTTP status code conveys whether this was successful. Parameters ---------- url : string URL for downloading the product Notes ----- https://scihub.copernicus.eu/userguide/LongTermArchive
[ "Triggers", "retrieval", "of", "an", "offline", "product" ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L431-L461
236,642
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.download
def download(self, id, directory_path='.', checksum=True): """Download a product. Uses the filename on the server for the downloaded file, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". Incomplete downloads are continued and complete files are skipped. Parameters ---------- id : string UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed' directory_path : string, optional Where the file will be downloaded checksum : bool, optional If True, verify the downloaded file's integrity by checking its MD5 checksum. Throws InvalidChecksumError if the checksum does not match. Defaults to True. Returns ------- product_info : dict Dictionary containing the product's info from get_product_info() as well as the path on disk. Raises ------ InvalidChecksumError If the MD5 checksum does not match the checksum on the server. """ product_info = self.get_product_odata(id) path = join(directory_path, product_info['title'] + '.zip') product_info['path'] = path product_info['downloaded_bytes'] = 0 self.logger.info('Downloading %s to %s', id, path) if exists(path): # We assume that the product has been downloaded and is complete return product_info # An incomplete download triggers the retrieval from the LTA if the product is not online if not product_info['Online']: self.logger.warning( 'Product %s is not online. Triggering retrieval from long term archive.', product_info['id']) self._trigger_offline_retrieval(product_info['url']) return product_info # Use a temporary file for downloading temp_path = path + '.incomplete' skip_download = False if exists(temp_path): if getsize(temp_path) > product_info['size']: self.logger.warning( "Existing incomplete file %s is larger than the expected final size" " (%s vs %s bytes). Deleting it.", str(temp_path), getsize(temp_path), product_info['size']) remove(temp_path) elif getsize(temp_path) == product_info['size']: if self._md5_compare(temp_path, product_info['md5']): skip_download = True else: # Log a warning since this should never happen self.logger.warning( "Existing incomplete file %s appears to be fully downloaded but " "its checksum is incorrect. Deleting it.", str(temp_path)) remove(temp_path) else: # continue downloading self.logger.info( "Download will resume from existing incomplete file %s.", temp_path) pass if not skip_download: # Store the number of downloaded bytes for unit tests product_info['downloaded_bytes'] = self._download( product_info['url'], temp_path, self.session, product_info['size']) # Check integrity with MD5 checksum if checksum is True: if not self._md5_compare(temp_path, product_info['md5']): remove(temp_path) raise InvalidChecksumError('File corrupt: checksums do not match') # Download successful, rename the temporary file to its proper name shutil.move(temp_path, path) return product_info
python
def download(self, id, directory_path='.', checksum=True): product_info = self.get_product_odata(id) path = join(directory_path, product_info['title'] + '.zip') product_info['path'] = path product_info['downloaded_bytes'] = 0 self.logger.info('Downloading %s to %s', id, path) if exists(path): # We assume that the product has been downloaded and is complete return product_info # An incomplete download triggers the retrieval from the LTA if the product is not online if not product_info['Online']: self.logger.warning( 'Product %s is not online. Triggering retrieval from long term archive.', product_info['id']) self._trigger_offline_retrieval(product_info['url']) return product_info # Use a temporary file for downloading temp_path = path + '.incomplete' skip_download = False if exists(temp_path): if getsize(temp_path) > product_info['size']: self.logger.warning( "Existing incomplete file %s is larger than the expected final size" " (%s vs %s bytes). Deleting it.", str(temp_path), getsize(temp_path), product_info['size']) remove(temp_path) elif getsize(temp_path) == product_info['size']: if self._md5_compare(temp_path, product_info['md5']): skip_download = True else: # Log a warning since this should never happen self.logger.warning( "Existing incomplete file %s appears to be fully downloaded but " "its checksum is incorrect. Deleting it.", str(temp_path)) remove(temp_path) else: # continue downloading self.logger.info( "Download will resume from existing incomplete file %s.", temp_path) pass if not skip_download: # Store the number of downloaded bytes for unit tests product_info['downloaded_bytes'] = self._download( product_info['url'], temp_path, self.session, product_info['size']) # Check integrity with MD5 checksum if checksum is True: if not self._md5_compare(temp_path, product_info['md5']): remove(temp_path) raise InvalidChecksumError('File corrupt: checksums do not match') # Download successful, rename the temporary file to its proper name shutil.move(temp_path, path) return product_info
[ "def", "download", "(", "self", ",", "id", ",", "directory_path", "=", "'.'", ",", "checksum", "=", "True", ")", ":", "product_info", "=", "self", ".", "get_product_odata", "(", "id", ")", "path", "=", "join", "(", "directory_path", ",", "product_info", ...
Download a product. Uses the filename on the server for the downloaded file, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". Incomplete downloads are continued and complete files are skipped. Parameters ---------- id : string UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed' directory_path : string, optional Where the file will be downloaded checksum : bool, optional If True, verify the downloaded file's integrity by checking its MD5 checksum. Throws InvalidChecksumError if the checksum does not match. Defaults to True. Returns ------- product_info : dict Dictionary containing the product's info from get_product_info() as well as the path on disk. Raises ------ InvalidChecksumError If the MD5 checksum does not match the checksum on the server.
[ "Download", "a", "product", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L463-L552
236,643
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.download_all
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True): """Download a list of products. Takes a list of product IDs as input. This means that the return value of query() can be passed directly to this method. File names on the server are used for the downloaded files, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". In case of interruptions or other exceptions, downloading will restart from where it left off. Downloading is attempted at most max_attempts times to avoid getting stuck with unrecoverable errors. Parameters ---------- products : list List of product IDs directory_path : string Directory where the downloaded files will be downloaded max_attempts : int, optional Number of allowed retries before giving up downloading a product. Defaults to 10. checksum : bool, optional If True, verify the downloaded files' integrity by checking its MD5 checksum. Throws InvalidChecksumError if the checksum does not match. Defaults to True. Raises ------ Raises the most recent downloading exception if all downloads failed. Returns ------- dict[string, dict] A dictionary containing the return value from download() for each successfully downloaded product. dict[string, dict] A dictionary containing the product information for products whose retrieval from the long term archive was successfully triggered. set[string] The list of products that failed to download. """ product_ids = list(products) self.logger.info("Will download %d products", len(product_ids)) return_values = OrderedDict() last_exception = None for i, product_id in enumerate(products): for attempt_num in range(max_attempts): try: product_info = self.download(product_id, directory_path, checksum) return_values[product_id] = product_info break except (KeyboardInterrupt, SystemExit): raise except InvalidChecksumError as e: last_exception = e self.logger.warning( "Invalid checksum. The downloaded file for '%s' is corrupted.", product_id) except SentinelAPILTAError as e: last_exception = e self.logger.exception("There was an error retrieving %s from the LTA", product_id) break except Exception as e: last_exception = e self.logger.exception("There was an error downloading %s", product_id) self.logger.info("%s/%s products downloaded", i + 1, len(product_ids)) failed = set(products) - set(return_values) # split up sucessfully processed products into downloaded and only triggered retrieval from the LTA triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False]) downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True]) if len(failed) == len(product_ids) and last_exception is not None: raise last_exception return downloaded, triggered, failed
python
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True): product_ids = list(products) self.logger.info("Will download %d products", len(product_ids)) return_values = OrderedDict() last_exception = None for i, product_id in enumerate(products): for attempt_num in range(max_attempts): try: product_info = self.download(product_id, directory_path, checksum) return_values[product_id] = product_info break except (KeyboardInterrupt, SystemExit): raise except InvalidChecksumError as e: last_exception = e self.logger.warning( "Invalid checksum. The downloaded file for '%s' is corrupted.", product_id) except SentinelAPILTAError as e: last_exception = e self.logger.exception("There was an error retrieving %s from the LTA", product_id) break except Exception as e: last_exception = e self.logger.exception("There was an error downloading %s", product_id) self.logger.info("%s/%s products downloaded", i + 1, len(product_ids)) failed = set(products) - set(return_values) # split up sucessfully processed products into downloaded and only triggered retrieval from the LTA triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False]) downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True]) if len(failed) == len(product_ids) and last_exception is not None: raise last_exception return downloaded, triggered, failed
[ "def", "download_all", "(", "self", ",", "products", ",", "directory_path", "=", "'.'", ",", "max_attempts", "=", "10", ",", "checksum", "=", "True", ")", ":", "product_ids", "=", "list", "(", "products", ")", "self", ".", "logger", ".", "info", "(", "...
Download a list of products. Takes a list of product IDs as input. This means that the return value of query() can be passed directly to this method. File names on the server are used for the downloaded files, e.g. "S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip". In case of interruptions or other exceptions, downloading will restart from where it left off. Downloading is attempted at most max_attempts times to avoid getting stuck with unrecoverable errors. Parameters ---------- products : list List of product IDs directory_path : string Directory where the downloaded files will be downloaded max_attempts : int, optional Number of allowed retries before giving up downloading a product. Defaults to 10. checksum : bool, optional If True, verify the downloaded files' integrity by checking its MD5 checksum. Throws InvalidChecksumError if the checksum does not match. Defaults to True. Raises ------ Raises the most recent downloading exception if all downloads failed. Returns ------- dict[string, dict] A dictionary containing the return value from download() for each successfully downloaded product. dict[string, dict] A dictionary containing the product information for products whose retrieval from the long term archive was successfully triggered. set[string] The list of products that failed to download.
[ "Download", "a", "list", "of", "products", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L554-L627
236,644
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.get_products_size
def get_products_size(products): """Return the total file size in GB of all products in the OpenSearch response.""" size_total = 0 for title, props in products.items(): size_product = props["size"] size_value = float(size_product.split(" ")[0]) size_unit = str(size_product.split(" ")[1]) if size_unit == "MB": size_value /= 1024. if size_unit == "KB": size_value /= 1024. * 1024. size_total += size_value return round(size_total, 2)
python
def get_products_size(products): size_total = 0 for title, props in products.items(): size_product = props["size"] size_value = float(size_product.split(" ")[0]) size_unit = str(size_product.split(" ")[1]) if size_unit == "MB": size_value /= 1024. if size_unit == "KB": size_value /= 1024. * 1024. size_total += size_value return round(size_total, 2)
[ "def", "get_products_size", "(", "products", ")", ":", "size_total", "=", "0", "for", "title", ",", "props", "in", "products", ".", "items", "(", ")", ":", "size_product", "=", "props", "[", "\"size\"", "]", "size_value", "=", "float", "(", "size_product",...
Return the total file size in GB of all products in the OpenSearch response.
[ "Return", "the", "total", "file", "size", "in", "GB", "of", "all", "products", "in", "the", "OpenSearch", "response", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L630-L642
236,645
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI.check_files
def check_files(self, paths=None, ids=None, directory=None, delete=False): """Verify the integrity of product files on disk. Integrity is checked by comparing the size and checksum of the file with the respective values on the server. The input can be a list of products to check or a list of IDs and a directory. In cases where multiple products with different IDs exist on the server for given product name, the file is considered to be correct if any of them matches the file size and checksum. A warning is logged in such situations. The corrupt products' OData info is included in the return value to make it easier to re-download the products, if necessary. Parameters ---------- paths : list[string] List of product file paths. ids : list[string] List of product IDs. directory : string Directory where the files are located, if checking based on product IDs. delete : bool Whether to delete corrupt products. Defaults to False. Returns ------- dict[str, list[dict]] A dictionary listing the invalid or missing files. The dictionary maps the corrupt file paths to a list of OData dictionaries of matching products on the server (as returned by :meth:`SentinelAPI.get_product_odata()`). """ if not ids and not paths: raise ValueError("Must provide either file paths or product IDs and a directory") if ids and not directory: raise ValueError("Directory value missing") paths = paths or [] ids = ids or [] def name_from_path(path): return splitext(basename(path))[0] # Get product IDs corresponding to the files on disk names = [] if paths: names = list(map(name_from_path, paths)) result = self._query_names(names) for product_dicts in result.values(): ids += list(product_dicts) names_from_paths = set(names) ids = set(ids) # Collect the OData information for each product # Product name -> list of matching odata dicts product_infos = defaultdict(list) for id in ids: odata = self.get_product_odata(id) name = odata['title'] product_infos[name].append(odata) # Collect if name not in names_from_paths: paths.append(join(directory, name + '.zip')) # Now go over the list of products and check them corrupt = {} for path in paths: name = name_from_path(path) if len(product_infos[name]) > 1: self.logger.warning("{} matches multiple products on server".format(path)) if not exists(path): # We will consider missing files as corrupt also self.logger.info("{} does not exist on disk".format(path)) corrupt[path] = product_infos[name] continue is_fine = False for product_info in product_infos[name]: if (getsize(path) == product_info['size'] and self._md5_compare(path, product_info['md5'])): is_fine = True break if not is_fine: self.logger.info("{} is corrupt".format(path)) corrupt[path] = product_infos[name] if delete: remove(path) return corrupt
python
def check_files(self, paths=None, ids=None, directory=None, delete=False): if not ids and not paths: raise ValueError("Must provide either file paths or product IDs and a directory") if ids and not directory: raise ValueError("Directory value missing") paths = paths or [] ids = ids or [] def name_from_path(path): return splitext(basename(path))[0] # Get product IDs corresponding to the files on disk names = [] if paths: names = list(map(name_from_path, paths)) result = self._query_names(names) for product_dicts in result.values(): ids += list(product_dicts) names_from_paths = set(names) ids = set(ids) # Collect the OData information for each product # Product name -> list of matching odata dicts product_infos = defaultdict(list) for id in ids: odata = self.get_product_odata(id) name = odata['title'] product_infos[name].append(odata) # Collect if name not in names_from_paths: paths.append(join(directory, name + '.zip')) # Now go over the list of products and check them corrupt = {} for path in paths: name = name_from_path(path) if len(product_infos[name]) > 1: self.logger.warning("{} matches multiple products on server".format(path)) if not exists(path): # We will consider missing files as corrupt also self.logger.info("{} does not exist on disk".format(path)) corrupt[path] = product_infos[name] continue is_fine = False for product_info in product_infos[name]: if (getsize(path) == product_info['size'] and self._md5_compare(path, product_info['md5'])): is_fine = True break if not is_fine: self.logger.info("{} is corrupt".format(path)) corrupt[path] = product_infos[name] if delete: remove(path) return corrupt
[ "def", "check_files", "(", "self", ",", "paths", "=", "None", ",", "ids", "=", "None", ",", "directory", "=", "None", ",", "delete", "=", "False", ")", ":", "if", "not", "ids", "and", "not", "paths", ":", "raise", "ValueError", "(", "\"Must provide eit...
Verify the integrity of product files on disk. Integrity is checked by comparing the size and checksum of the file with the respective values on the server. The input can be a list of products to check or a list of IDs and a directory. In cases where multiple products with different IDs exist on the server for given product name, the file is considered to be correct if any of them matches the file size and checksum. A warning is logged in such situations. The corrupt products' OData info is included in the return value to make it easier to re-download the products, if necessary. Parameters ---------- paths : list[string] List of product file paths. ids : list[string] List of product IDs. directory : string Directory where the files are located, if checking based on product IDs. delete : bool Whether to delete corrupt products. Defaults to False. Returns ------- dict[str, list[dict]] A dictionary listing the invalid or missing files. The dictionary maps the corrupt file paths to a list of OData dictionaries of matching products on the server (as returned by :meth:`SentinelAPI.get_product_odata()`).
[ "Verify", "the", "integrity", "of", "product", "files", "on", "disk", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L702-L793
236,646
sentinelsat/sentinelsat
sentinelsat/sentinel.py
SentinelAPI._md5_compare
def _md5_compare(self, file_path, checksum, block_size=2 ** 13): """Compare a given MD5 checksum with one calculated from a file.""" with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B", unit_scale=True)) as progress: md5 = hashlib.md5() with open(file_path, "rb") as f: while True: block_data = f.read(block_size) if not block_data: break md5.update(block_data) progress.update(len(block_data)) return md5.hexdigest().lower() == checksum.lower()
python
def _md5_compare(self, file_path, checksum, block_size=2 ** 13): with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B", unit_scale=True)) as progress: md5 = hashlib.md5() with open(file_path, "rb") as f: while True: block_data = f.read(block_size) if not block_data: break md5.update(block_data) progress.update(len(block_data)) return md5.hexdigest().lower() == checksum.lower()
[ "def", "_md5_compare", "(", "self", ",", "file_path", ",", "checksum", ",", "block_size", "=", "2", "**", "13", ")", ":", "with", "closing", "(", "self", ".", "_tqdm", "(", "desc", "=", "\"MD5 checksumming\"", ",", "total", "=", "getsize", "(", "file_pat...
Compare a given MD5 checksum with one calculated from a file.
[ "Compare", "a", "given", "MD5", "checksum", "with", "one", "calculated", "from", "a", "file", "." ]
eacfd79ff4e7e939147db9dfdd393c67d64eecaa
https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L795-L807
236,647
celery/django-celery
djcelery/managers.py
transaction_retry
def transaction_retry(max_retries=1): """Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times. """ def _outer(fun): @wraps(fun) def _inner(*args, **kwargs): _max_retries = kwargs.pop('exception_retry_count', max_retries) for retries in count(0): try: return fun(*args, **kwargs) except Exception: # pragma: no cover # Depending on the database backend used we can experience # various exceptions. E.g. psycopg2 raises an exception # if some operation breaks the transaction, so saving # the task result won't be possible until we rollback # the transaction. if retries >= _max_retries: raise try: rollback_unless_managed() except Exception: pass return _inner return _outer
python
def transaction_retry(max_retries=1): def _outer(fun): @wraps(fun) def _inner(*args, **kwargs): _max_retries = kwargs.pop('exception_retry_count', max_retries) for retries in count(0): try: return fun(*args, **kwargs) except Exception: # pragma: no cover # Depending on the database backend used we can experience # various exceptions. E.g. psycopg2 raises an exception # if some operation breaks the transaction, so saving # the task result won't be possible until we rollback # the transaction. if retries >= _max_retries: raise try: rollback_unless_managed() except Exception: pass return _inner return _outer
[ "def", "transaction_retry", "(", "max_retries", "=", "1", ")", ":", "def", "_outer", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "_inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_max_retries", "=", "kwargs", ".", "pop...
Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times.
[ "Decorator", "for", "methods", "doing", "database", "operations", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L31-L60
236,648
celery/django-celery
djcelery/managers.py
ResultManager.delete_expired
def delete_expired(self, expires): """Delete all expired taskset results.""" meta = self.model._meta with commit_on_success(): self.get_all_expired(expires).update(hidden=True) cursor = self.connection_for_write().cursor() cursor.execute( 'DELETE FROM {0.db_table} WHERE hidden=%s'.format(meta), (True, ), )
python
def delete_expired(self, expires): meta = self.model._meta with commit_on_success(): self.get_all_expired(expires).update(hidden=True) cursor = self.connection_for_write().cursor() cursor.execute( 'DELETE FROM {0.db_table} WHERE hidden=%s'.format(meta), (True, ), )
[ "def", "delete_expired", "(", "self", ",", "expires", ")", ":", "meta", "=", "self", ".", "model", ".", "_meta", "with", "commit_on_success", "(", ")", ":", "self", ".", "get_all_expired", "(", "expires", ")", ".", "update", "(", "hidden", "=", "True", ...
Delete all expired taskset results.
[ "Delete", "all", "expired", "taskset", "results", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L115-L124
236,649
celery/django-celery
djcelery/managers.py
TaskManager.get_task
def get_task(self, task_id): """Get task meta for task by ``task_id``. :keyword exception_retry_count: How many times to retry by transaction rollback on exception. This could theoretically happen in a race condition if another worker is trying to create the same task. The default is to retry once. """ try: return self.get(task_id=task_id) except self.model.DoesNotExist: if self._last_id == task_id: self.warn_if_repeatable_read() self._last_id = task_id return self.model(task_id=task_id)
python
def get_task(self, task_id): try: return self.get(task_id=task_id) except self.model.DoesNotExist: if self._last_id == task_id: self.warn_if_repeatable_read() self._last_id = task_id return self.model(task_id=task_id)
[ "def", "get_task", "(", "self", ",", "task_id", ")", ":", "try", ":", "return", "self", ".", "get", "(", "task_id", "=", "task_id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "if", "self", ".", "_last_id", "==", "task_id", ":", "s...
Get task meta for task by ``task_id``. :keyword exception_retry_count: How many times to retry by transaction rollback on exception. This could theoretically happen in a race condition if another worker is trying to create the same task. The default is to retry once.
[ "Get", "task", "meta", "for", "task", "by", "task_id", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L140-L155
236,650
celery/django-celery
djcelery/managers.py
TaskManager.store_result
def store_result(self, task_id, result, status, traceback=None, children=None): """Store the result and status of a task. :param task_id: task id :param result: The return value of the task, or an exception instance raised by the task. :param status: Task status. See :meth:`celery.result.AsyncResult.get_status` for a list of possible status values. :keyword traceback: The traceback at the point of exception (if the task failed). :keyword children: List of serialized results of subtasks of this task. :keyword exception_retry_count: How many times to retry by transaction rollback on exception. This could theoretically happen in a race condition if another worker is trying to create the same task. The default is to retry twice. """ return self.update_or_create(task_id=task_id, defaults={'status': status, 'result': result, 'traceback': traceback, 'meta': {'children': children}})
python
def store_result(self, task_id, result, status, traceback=None, children=None): return self.update_or_create(task_id=task_id, defaults={'status': status, 'result': result, 'traceback': traceback, 'meta': {'children': children}})
[ "def", "store_result", "(", "self", ",", "task_id", ",", "result", ",", "status", ",", "traceback", "=", "None", ",", "children", "=", "None", ")", ":", "return", "self", ".", "update_or_create", "(", "task_id", "=", "task_id", ",", "defaults", "=", "{",...
Store the result and status of a task. :param task_id: task id :param result: The return value of the task, or an exception instance raised by the task. :param status: Task status. See :meth:`celery.result.AsyncResult.get_status` for a list of possible status values. :keyword traceback: The traceback at the point of exception (if the task failed). :keyword children: List of serialized results of subtasks of this task. :keyword exception_retry_count: How many times to retry by transaction rollback on exception. This could theoretically happen in a race condition if another worker is trying to create the same task. The default is to retry twice.
[ "Store", "the", "result", "and", "status", "of", "a", "task", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L158-L187
236,651
celery/django-celery
djcelery/managers.py
TaskSetManager.restore_taskset
def restore_taskset(self, taskset_id): """Get the async result instance by taskset id.""" try: return self.get(taskset_id=taskset_id) except self.model.DoesNotExist: pass
python
def restore_taskset(self, taskset_id): try: return self.get(taskset_id=taskset_id) except self.model.DoesNotExist: pass
[ "def", "restore_taskset", "(", "self", ",", "taskset_id", ")", ":", "try", ":", "return", "self", ".", "get", "(", "taskset_id", "=", "taskset_id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "pass" ]
Get the async result instance by taskset id.
[ "Get", "the", "async", "result", "instance", "by", "taskset", "id", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L205-L210
236,652
celery/django-celery
djcelery/managers.py
TaskSetManager.delete_taskset
def delete_taskset(self, taskset_id): """Delete a saved taskset result.""" s = self.restore_taskset(taskset_id) if s: s.delete()
python
def delete_taskset(self, taskset_id): s = self.restore_taskset(taskset_id) if s: s.delete()
[ "def", "delete_taskset", "(", "self", ",", "taskset_id", ")", ":", "s", "=", "self", ".", "restore_taskset", "(", "taskset_id", ")", "if", "s", ":", "s", ".", "delete", "(", ")" ]
Delete a saved taskset result.
[ "Delete", "a", "saved", "taskset", "result", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L212-L216
236,653
celery/django-celery
djcelery/managers.py
TaskSetManager.store_result
def store_result(self, taskset_id, result): """Store the async result instance of a taskset. :param taskset_id: task set id :param result: The return value of the taskset """ return self.update_or_create(taskset_id=taskset_id, defaults={'result': result})
python
def store_result(self, taskset_id, result): return self.update_or_create(taskset_id=taskset_id, defaults={'result': result})
[ "def", "store_result", "(", "self", ",", "taskset_id", ",", "result", ")", ":", "return", "self", ".", "update_or_create", "(", "taskset_id", "=", "taskset_id", ",", "defaults", "=", "{", "'result'", ":", "result", "}", ")" ]
Store the async result instance of a taskset. :param taskset_id: task set id :param result: The return value of the taskset
[ "Store", "the", "async", "result", "instance", "of", "a", "taskset", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/managers.py#L219-L228
236,654
celery/django-celery
djcelery/backends/database.py
DatabaseBackend._store_result
def _store_result(self, task_id, result, status, traceback=None, request=None): """Store return value and status of an executed task.""" self.TaskModel._default_manager.store_result( task_id, result, status, traceback=traceback, children=self.current_task_children(request), ) return result
python
def _store_result(self, task_id, result, status, traceback=None, request=None): self.TaskModel._default_manager.store_result( task_id, result, status, traceback=traceback, children=self.current_task_children(request), ) return result
[ "def", "_store_result", "(", "self", ",", "task_id", ",", "result", ",", "status", ",", "traceback", "=", "None", ",", "request", "=", "None", ")", ":", "self", ".", "TaskModel", ".", "_default_manager", ".", "store_result", "(", "task_id", ",", "result", ...
Store return value and status of an executed task.
[ "Store", "return", "value", "and", "status", "of", "an", "executed", "task", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L28-L35
236,655
celery/django-celery
djcelery/backends/database.py
DatabaseBackend._save_group
def _save_group(self, group_id, result): """Store the result of an executed group.""" self.TaskSetModel._default_manager.store_result(group_id, result) return result
python
def _save_group(self, group_id, result): self.TaskSetModel._default_manager.store_result(group_id, result) return result
[ "def", "_save_group", "(", "self", ",", "group_id", ",", "result", ")", ":", "self", ".", "TaskSetModel", ".", "_default_manager", ".", "store_result", "(", "group_id", ",", "result", ")", "return", "result" ]
Store the result of an executed group.
[ "Store", "the", "result", "of", "an", "executed", "group", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L37-L40
236,656
celery/django-celery
djcelery/backends/database.py
DatabaseBackend._restore_group
def _restore_group(self, group_id): """Get group metadata for a group by id.""" meta = self.TaskSetModel._default_manager.restore_taskset(group_id) if meta: return meta.to_dict()
python
def _restore_group(self, group_id): meta = self.TaskSetModel._default_manager.restore_taskset(group_id) if meta: return meta.to_dict()
[ "def", "_restore_group", "(", "self", ",", "group_id", ")", ":", "meta", "=", "self", ".", "TaskSetModel", ".", "_default_manager", ".", "restore_taskset", "(", "group_id", ")", "if", "meta", ":", "return", "meta", ".", "to_dict", "(", ")" ]
Get group metadata for a group by id.
[ "Get", "group", "metadata", "for", "a", "group", "by", "id", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L46-L50
236,657
celery/django-celery
djcelery/backends/database.py
DatabaseBackend.cleanup
def cleanup(self): """Delete expired metadata.""" expires = maybe_timedelta(self.expires) for model in self.TaskModel, self.TaskSetModel: model._default_manager.delete_expired(expires)
python
def cleanup(self): expires = maybe_timedelta(self.expires) for model in self.TaskModel, self.TaskSetModel: model._default_manager.delete_expired(expires)
[ "def", "cleanup", "(", "self", ")", ":", "expires", "=", "maybe_timedelta", "(", "self", ".", "expires", ")", "for", "model", "in", "self", ".", "TaskModel", ",", "self", ".", "TaskSetModel", ":", "model", ".", "_default_manager", ".", "delete_expired", "(...
Delete expired metadata.
[ "Delete", "expired", "metadata", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/backends/database.py#L61-L65
236,658
celery/django-celery
djcelery/snapshot.py
Camera.handle_task
def handle_task(self, uuid_task, worker=None): """Handle snapshotted event.""" uuid, task = uuid_task if task.worker and task.worker.hostname: worker = self.handle_worker( (task.worker.hostname, task.worker), ) defaults = { 'name': task.name, 'args': task.args, 'kwargs': task.kwargs, 'eta': correct_awareness(maybe_iso8601(task.eta)), 'expires': correct_awareness(maybe_iso8601(task.expires)), 'state': task.state, 'tstamp': fromtimestamp(task.timestamp), 'result': task.result or task.exception, 'traceback': task.traceback, 'runtime': task.runtime, 'worker': worker } # Some fields are only stored in the RECEIVED event, # so we should remove these from default values, # so that they are not overwritten by subsequent states. [defaults.pop(attr, None) for attr in NOT_SAVED_ATTRIBUTES if defaults[attr] is None] return self.update_task(task.state, task_id=uuid, defaults=defaults)
python
def handle_task(self, uuid_task, worker=None): uuid, task = uuid_task if task.worker and task.worker.hostname: worker = self.handle_worker( (task.worker.hostname, task.worker), ) defaults = { 'name': task.name, 'args': task.args, 'kwargs': task.kwargs, 'eta': correct_awareness(maybe_iso8601(task.eta)), 'expires': correct_awareness(maybe_iso8601(task.expires)), 'state': task.state, 'tstamp': fromtimestamp(task.timestamp), 'result': task.result or task.exception, 'traceback': task.traceback, 'runtime': task.runtime, 'worker': worker } # Some fields are only stored in the RECEIVED event, # so we should remove these from default values, # so that they are not overwritten by subsequent states. [defaults.pop(attr, None) for attr in NOT_SAVED_ATTRIBUTES if defaults[attr] is None] return self.update_task(task.state, task_id=uuid, defaults=defaults)
[ "def", "handle_task", "(", "self", ",", "uuid_task", ",", "worker", "=", "None", ")", ":", "uuid", ",", "task", "=", "uuid_task", "if", "task", ".", "worker", "and", "task", ".", "worker", ".", "hostname", ":", "worker", "=", "self", ".", "handle_worke...
Handle snapshotted event.
[ "Handle", "snapshotted", "event", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/snapshot.py#L73-L100
236,659
celery/django-celery
djcelery/common.py
respect_language
def respect_language(language): """Context manager that changes the current translation language for all code inside the following block. Can e.g. be used inside tasks like this:: from celery import task from djcelery.common import respect_language @task def my_task(language=None): with respect_language(language): pass """ if language: prev = translation.get_language() translation.activate(language) try: yield finally: translation.activate(prev) else: yield
python
def respect_language(language): if language: prev = translation.get_language() translation.activate(language) try: yield finally: translation.activate(prev) else: yield
[ "def", "respect_language", "(", "language", ")", ":", "if", "language", ":", "prev", "=", "translation", ".", "get_language", "(", ")", "translation", ".", "activate", "(", "language", ")", "try", ":", "yield", "finally", ":", "translation", ".", "activate",...
Context manager that changes the current translation language for all code inside the following block. Can e.g. be used inside tasks like this:: from celery import task from djcelery.common import respect_language @task def my_task(language=None): with respect_language(language): pass
[ "Context", "manager", "that", "changes", "the", "current", "translation", "language", "for", "all", "code", "inside", "the", "following", "block", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/common.py#L10-L32
236,660
celery/django-celery
djcelery/loaders.py
autodiscover
def autodiscover(): """Include tasks for all applications in ``INSTALLED_APPS``.""" global _RACE_PROTECTION if _RACE_PROTECTION: return _RACE_PROTECTION = True try: return filter(None, [find_related_module(app, 'tasks') for app in settings.INSTALLED_APPS]) finally: _RACE_PROTECTION = False
python
def autodiscover(): global _RACE_PROTECTION if _RACE_PROTECTION: return _RACE_PROTECTION = True try: return filter(None, [find_related_module(app, 'tasks') for app in settings.INSTALLED_APPS]) finally: _RACE_PROTECTION = False
[ "def", "autodiscover", "(", ")", ":", "global", "_RACE_PROTECTION", "if", "_RACE_PROTECTION", ":", "return", "_RACE_PROTECTION", "=", "True", "try", ":", "return", "filter", "(", "None", ",", "[", "find_related_module", "(", "app", ",", "'tasks'", ")", "for", ...
Include tasks for all applications in ``INSTALLED_APPS``.
[ "Include", "tasks", "for", "all", "applications", "in", "INSTALLED_APPS", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L167-L178
236,661
celery/django-celery
djcelery/loaders.py
find_related_module
def find_related_module(app, related_name): """Given an application name and a module name, tries to find that module in the application.""" try: app_path = importlib.import_module(app).__path__ except ImportError as exc: warn('Autodiscover: Error importing %s.%s: %r' % ( app, related_name, exc, )) return except AttributeError: return try: f, _, _ = imp.find_module(related_name, app_path) # f is returned None when app_path is a module f and f.close() except ImportError: return return importlib.import_module('{0}.{1}'.format(app, related_name))
python
def find_related_module(app, related_name): try: app_path = importlib.import_module(app).__path__ except ImportError as exc: warn('Autodiscover: Error importing %s.%s: %r' % ( app, related_name, exc, )) return except AttributeError: return try: f, _, _ = imp.find_module(related_name, app_path) # f is returned None when app_path is a module f and f.close() except ImportError: return return importlib.import_module('{0}.{1}'.format(app, related_name))
[ "def", "find_related_module", "(", "app", ",", "related_name", ")", ":", "try", ":", "app_path", "=", "importlib", ".", "import_module", "(", "app", ")", ".", "__path__", "except", "ImportError", "as", "exc", ":", "warn", "(", "'Autodiscover: Error importing %s....
Given an application name and a module name, tries to find that module in the application.
[ "Given", "an", "application", "name", "and", "a", "module", "name", "tries", "to", "find", "that", "module", "in", "the", "application", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L181-L202
236,662
celery/django-celery
djcelery/loaders.py
DjangoLoader.read_configuration
def read_configuration(self): """Load configuration from Django settings.""" self.configured = True # Default backend needs to be the database backend for backward # compatibility. backend = (getattr(settings, 'CELERY_RESULT_BACKEND', None) or getattr(settings, 'CELERY_BACKEND', None)) if not backend: settings.CELERY_RESULT_BACKEND = 'database' return DictAttribute(settings)
python
def read_configuration(self): self.configured = True # Default backend needs to be the database backend for backward # compatibility. backend = (getattr(settings, 'CELERY_RESULT_BACKEND', None) or getattr(settings, 'CELERY_BACKEND', None)) if not backend: settings.CELERY_RESULT_BACKEND = 'database' return DictAttribute(settings)
[ "def", "read_configuration", "(", "self", ")", ":", "self", ".", "configured", "=", "True", "# Default backend needs to be the database backend for backward", "# compatibility.", "backend", "=", "(", "getattr", "(", "settings", ",", "'CELERY_RESULT_BACKEND'", ",", "None",...
Load configuration from Django settings.
[ "Load", "configuration", "from", "Django", "settings", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L57-L66
236,663
celery/django-celery
djcelery/loaders.py
DjangoLoader.on_task_init
def on_task_init(self, task_id, task): """Called before every task.""" try: is_eager = task.request.is_eager except AttributeError: is_eager = False if not is_eager: self.close_database()
python
def on_task_init(self, task_id, task): try: is_eager = task.request.is_eager except AttributeError: is_eager = False if not is_eager: self.close_database()
[ "def", "on_task_init", "(", "self", ",", "task_id", ",", "task", ")", ":", "try", ":", "is_eager", "=", "task", ".", "request", ".", "is_eager", "except", "AttributeError", ":", "is_eager", "=", "False", "if", "not", "is_eager", ":", "self", ".", "close_...
Called before every task.
[ "Called", "before", "every", "task", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/loaders.py#L110-L117
236,664
celery/django-celery
djcelery/humanize.py
naturaldate
def naturaldate(date, include_seconds=False): """Convert datetime into a human natural date string.""" if not date: return '' right_now = now() today = datetime(right_now.year, right_now.month, right_now.day, tzinfo=right_now.tzinfo) delta = right_now - date delta_midnight = today - date days = delta.days hours = delta.seconds // 3600 minutes = delta.seconds // 60 seconds = delta.seconds if days < 0: return _('just now') if days == 0: if hours == 0: if minutes > 0: return ungettext( _('{minutes} minute ago'), _('{minutes} minutes ago'), minutes ).format(minutes=minutes) else: if include_seconds and seconds: return ungettext( _('{seconds} second ago'), _('{seconds} seconds ago'), seconds ).format(seconds=seconds) return _('just now') else: return ungettext( _('{hours} hour ago'), _('{hours} hours ago'), hours ).format(hours=hours) if delta_midnight.days == 0: return _('yesterday at {time}').format(time=date.strftime('%H:%M')) count = 0 for chunk, pluralizefun in OLDER_CHUNKS: if days >= chunk: count = int(round((delta_midnight.days + 1) / chunk, 0)) fmt = pluralizefun(count) return fmt.format(num=count)
python
def naturaldate(date, include_seconds=False): if not date: return '' right_now = now() today = datetime(right_now.year, right_now.month, right_now.day, tzinfo=right_now.tzinfo) delta = right_now - date delta_midnight = today - date days = delta.days hours = delta.seconds // 3600 minutes = delta.seconds // 60 seconds = delta.seconds if days < 0: return _('just now') if days == 0: if hours == 0: if minutes > 0: return ungettext( _('{minutes} minute ago'), _('{minutes} minutes ago'), minutes ).format(minutes=minutes) else: if include_seconds and seconds: return ungettext( _('{seconds} second ago'), _('{seconds} seconds ago'), seconds ).format(seconds=seconds) return _('just now') else: return ungettext( _('{hours} hour ago'), _('{hours} hours ago'), hours ).format(hours=hours) if delta_midnight.days == 0: return _('yesterday at {time}').format(time=date.strftime('%H:%M')) count = 0 for chunk, pluralizefun in OLDER_CHUNKS: if days >= chunk: count = int(round((delta_midnight.days + 1) / chunk, 0)) fmt = pluralizefun(count) return fmt.format(num=count)
[ "def", "naturaldate", "(", "date", ",", "include_seconds", "=", "False", ")", ":", "if", "not", "date", ":", "return", "''", "right_now", "=", "now", "(", ")", "today", "=", "datetime", "(", "right_now", ".", "year", ",", "right_now", ".", "month", ","...
Convert datetime into a human natural date string.
[ "Convert", "datetime", "into", "a", "human", "natural", "date", "string", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/humanize.py#L38-L85
236,665
celery/django-celery
djcelery/views.py
apply
def apply(request, task_name): """View applying a task. **Note:** Please use this with caution. Preferably you shouldn't make this publicly accessible without ensuring your code is safe! """ try: task = tasks[task_name] except KeyError: raise Http404('apply: no such task') return task_view(task)(request)
python
def apply(request, task_name): try: task = tasks[task_name] except KeyError: raise Http404('apply: no such task') return task_view(task)(request)
[ "def", "apply", "(", "request", ",", "task_name", ")", ":", "try", ":", "task", "=", "tasks", "[", "task_name", "]", "except", "KeyError", ":", "raise", "Http404", "(", "'apply: no such task'", ")", "return", "task_view", "(", "task", ")", "(", "request", ...
View applying a task. **Note:** Please use this with caution. Preferably you shouldn't make this publicly accessible without ensuring your code is safe!
[ "View", "applying", "a", "task", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/views.py#L46-L57
236,666
celery/django-celery
djcelery/views.py
task_status
def task_status(request, task_id): """Returns task status and result in JSON format.""" result = AsyncResult(task_id) state, retval = result.state, result.result response_data = {'id': task_id, 'status': state, 'result': retval} if state in states.EXCEPTION_STATES: traceback = result.traceback response_data.update({'result': safe_repr(retval), 'exc': get_full_cls_name(retval.__class__), 'traceback': traceback}) return JsonResponse({'task': response_data})
python
def task_status(request, task_id): result = AsyncResult(task_id) state, retval = result.state, result.result response_data = {'id': task_id, 'status': state, 'result': retval} if state in states.EXCEPTION_STATES: traceback = result.traceback response_data.update({'result': safe_repr(retval), 'exc': get_full_cls_name(retval.__class__), 'traceback': traceback}) return JsonResponse({'task': response_data})
[ "def", "task_status", "(", "request", ",", "task_id", ")", ":", "result", "=", "AsyncResult", "(", "task_id", ")", "state", ",", "retval", "=", "result", ".", "state", ",", "result", ".", "result", "response_data", "=", "{", "'id'", ":", "task_id", ",", ...
Returns task status and result in JSON format.
[ "Returns", "task", "status", "and", "result", "in", "JSON", "format", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/views.py#L68-L78
236,667
celery/django-celery
djcelery/views.py
task_webhook
def task_webhook(fun): """Decorator turning a function into a task webhook. If an exception is raised within the function, the decorated function catches this and returns an error JSON response, otherwise it returns the result as a JSON response. Example: .. code-block:: python @task_webhook def add(request): x = int(request.GET['x']) y = int(request.GET['y']) return x + y def view(request): response = add(request) print(response.content) Gives:: "{'status': 'success', 'retval': 100}" """ @wraps(fun) def _inner(*args, **kwargs): try: retval = fun(*args, **kwargs) except Exception as exc: response = {'status': 'failure', 'reason': safe_repr(exc)} else: response = {'status': 'success', 'retval': retval} return JsonResponse(response) return _inner
python
def task_webhook(fun): @wraps(fun) def _inner(*args, **kwargs): try: retval = fun(*args, **kwargs) except Exception as exc: response = {'status': 'failure', 'reason': safe_repr(exc)} else: response = {'status': 'success', 'retval': retval} return JsonResponse(response) return _inner
[ "def", "task_webhook", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "_inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "retval", "=", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Excep...
Decorator turning a function into a task webhook. If an exception is raised within the function, the decorated function catches this and returns an error JSON response, otherwise it returns the result as a JSON response. Example: .. code-block:: python @task_webhook def add(request): x = int(request.GET['x']) y = int(request.GET['y']) return x + y def view(request): response = add(request) print(response.content) Gives:: "{'status': 'success', 'retval': 100}"
[ "Decorator", "turning", "a", "function", "into", "a", "task", "webhook", "." ]
5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef
https://github.com/celery/django-celery/blob/5d1ecb09c6304d22cc447c7c08fba0bd1febc2ef/djcelery/views.py#L86-L125
236,668
Guake/guake
guake/menus.py
mk_tab_context_menu
def mk_tab_context_menu(callback_object): """Create the context menu for a notebook tab """ # Store the menu in a temp variable in terminal so that popup() is happy. See: # https://stackoverflow.com/questions/28465956/ callback_object.context_menu = Gtk.Menu() menu = callback_object.context_menu mi1 = Gtk.MenuItem(_("New Tab")) mi1.connect("activate", callback_object.on_new_tab) menu.add(mi1) mi2 = Gtk.MenuItem(_("Rename")) mi2.connect("activate", callback_object.on_rename) menu.add(mi2) mi3 = Gtk.MenuItem(_("Close")) mi3.connect("activate", callback_object.on_close) menu.add(mi3) menu.show_all() return menu
python
def mk_tab_context_menu(callback_object): # Store the menu in a temp variable in terminal so that popup() is happy. See: # https://stackoverflow.com/questions/28465956/ callback_object.context_menu = Gtk.Menu() menu = callback_object.context_menu mi1 = Gtk.MenuItem(_("New Tab")) mi1.connect("activate", callback_object.on_new_tab) menu.add(mi1) mi2 = Gtk.MenuItem(_("Rename")) mi2.connect("activate", callback_object.on_rename) menu.add(mi2) mi3 = Gtk.MenuItem(_("Close")) mi3.connect("activate", callback_object.on_close) menu.add(mi3) menu.show_all() return menu
[ "def", "mk_tab_context_menu", "(", "callback_object", ")", ":", "# Store the menu in a temp variable in terminal so that popup() is happy. See:", "# https://stackoverflow.com/questions/28465956/", "callback_object", ".", "context_menu", "=", "Gtk", ".", "Menu", "(", ")", "menu", ...
Create the context menu for a notebook tab
[ "Create", "the", "context", "menu", "for", "a", "notebook", "tab" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/menus.py#L13-L30
236,669
Guake/guake
guake/menus.py
mk_notebook_context_menu
def mk_notebook_context_menu(callback_object): """Create the context menu for the notebook """ callback_object.context_menu = Gtk.Menu() menu = callback_object.context_menu mi = Gtk.MenuItem(_("New Tab")) mi.connect("activate", callback_object.on_new_tab) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.MenuItem(_("Save Tabs")) mi.connect("activate", callback_object.on_save_tabs) menu.add(mi) mi = Gtk.MenuItem(_("Restore Tabs")) mi.connect("activate", callback_object.on_restore_tabs_with_dialog) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.ImageMenuItem("gtk-preferences") mi.set_use_stock(True) mi.connect("activate", callback_object.on_show_preferences) menu.add(mi) mi = Gtk.ImageMenuItem("gtk-about") mi.set_use_stock(True) mi.connect("activate", callback_object.on_show_about) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.MenuItem(_("Quit")) mi.connect("activate", callback_object.on_quit) menu.add(mi) menu.show_all() return menu
python
def mk_notebook_context_menu(callback_object): callback_object.context_menu = Gtk.Menu() menu = callback_object.context_menu mi = Gtk.MenuItem(_("New Tab")) mi.connect("activate", callback_object.on_new_tab) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.MenuItem(_("Save Tabs")) mi.connect("activate", callback_object.on_save_tabs) menu.add(mi) mi = Gtk.MenuItem(_("Restore Tabs")) mi.connect("activate", callback_object.on_restore_tabs_with_dialog) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.ImageMenuItem("gtk-preferences") mi.set_use_stock(True) mi.connect("activate", callback_object.on_show_preferences) menu.add(mi) mi = Gtk.ImageMenuItem("gtk-about") mi.set_use_stock(True) mi.connect("activate", callback_object.on_show_about) menu.add(mi) menu.add(Gtk.SeparatorMenuItem()) mi = Gtk.MenuItem(_("Quit")) mi.connect("activate", callback_object.on_quit) menu.add(mi) menu.show_all() return menu
[ "def", "mk_notebook_context_menu", "(", "callback_object", ")", ":", "callback_object", ".", "context_menu", "=", "Gtk", ".", "Menu", "(", ")", "menu", "=", "callback_object", ".", "context_menu", "mi", "=", "Gtk", ".", "MenuItem", "(", "_", "(", "\"New Tab\""...
Create the context menu for the notebook
[ "Create", "the", "context", "menu", "for", "the", "notebook" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/menus.py#L33-L62
236,670
Guake/guake
guake/gsettings.py
GSettingHandler.ontop_toggled
def ontop_toggled(self, settings, key, user_data): """If the gconf var window_ontop be changed, this method will be called and will set the keep_above attribute in guake's main window. """ self.guake.window.set_keep_above(settings.get_boolean(key))
python
def ontop_toggled(self, settings, key, user_data): self.guake.window.set_keep_above(settings.get_boolean(key))
[ "def", "ontop_toggled", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "self", ".", "guake", ".", "window", ".", "set_keep_above", "(", "settings", ".", "get_boolean", "(", "key", ")", ")" ]
If the gconf var window_ontop be changed, this method will be called and will set the keep_above attribute in guake's main window.
[ "If", "the", "gconf", "var", "window_ontop", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "set", "the", "keep_above", "attribute", "in", "guake", "s", "main", "window", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L103-L108
236,671
Guake/guake
guake/gsettings.py
GSettingHandler.alignment_changed
def alignment_changed(self, settings, key, user_data): """If the gconf var window_halignment be changed, this method will be called and will call the move function in guake. """ RectCalculator.set_final_window_rect(self.settings, self.guake.window) self.guake.set_tab_position() self.guake.force_move_if_shown()
python
def alignment_changed(self, settings, key, user_data): RectCalculator.set_final_window_rect(self.settings, self.guake.window) self.guake.set_tab_position() self.guake.force_move_if_shown()
[ "def", "alignment_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "RectCalculator", ".", "set_final_window_rect", "(", "self", ".", "settings", ",", "self", ".", "guake", ".", "window", ")", "self", ".", "guake", ".", "set_t...
If the gconf var window_halignment be changed, this method will be called and will call the move function in guake.
[ "If", "the", "gconf", "var", "window_halignment", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "call", "the", "move", "function", "in", "guake", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L126-L132
236,672
Guake/guake
guake/gsettings.py
GSettingHandler.size_changed
def size_changed(self, settings, key, user_data): """If the gconf var window_height or window_width are changed, this method will be called and will call the resize function in guake. """ RectCalculator.set_final_window_rect(self.settings, self.guake.window)
python
def size_changed(self, settings, key, user_data): RectCalculator.set_final_window_rect(self.settings, self.guake.window)
[ "def", "size_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "RectCalculator", ".", "set_final_window_rect", "(", "self", ".", "settings", ",", "self", ".", "guake", ".", "window", ")" ]
If the gconf var window_height or window_width are changed, this method will be called and will call the resize function in guake.
[ "If", "the", "gconf", "var", "window_height", "or", "window_width", "are", "changed", "this", "method", "will", "be", "called", "and", "will", "call", "the", "resize", "function", "in", "guake", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L134-L139
236,673
Guake/guake
guake/gsettings.py
GSettingHandler.cursor_blink_mode_changed
def cursor_blink_mode_changed(self, settings, key, user_data): """Called when cursor blink mode settings has been changed """ for term in self.guake.notebook_manager.iter_terminals(): term.set_property("cursor-blink-mode", settings.get_int(key))
python
def cursor_blink_mode_changed(self, settings, key, user_data): for term in self.guake.notebook_manager.iter_terminals(): term.set_property("cursor-blink-mode", settings.get_int(key))
[ "def", "cursor_blink_mode_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "term", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "term", ".", "set_property", "(", "\"cursor-bl...
Called when cursor blink mode settings has been changed
[ "Called", "when", "cursor", "blink", "mode", "settings", "has", "been", "changed" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L141-L145
236,674
Guake/guake
guake/gsettings.py
GSettingHandler.history_size_changed
def history_size_changed(self, settings, key, user_data): """If the gconf var history_size be changed, this method will be called and will set the scrollback_lines property of all terminals open. """ lines = settings.get_int(key) for i in self.guake.notebook_manager.iter_terminals(): i.set_scrollback_lines(lines)
python
def history_size_changed(self, settings, key, user_data): lines = settings.get_int(key) for i in self.guake.notebook_manager.iter_terminals(): i.set_scrollback_lines(lines)
[ "def", "history_size_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "lines", "=", "settings", ".", "get_int", "(", "key", ")", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", "...
If the gconf var history_size be changed, this method will be called and will set the scrollback_lines property of all terminals open.
[ "If", "the", "gconf", "var", "history_size", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "set", "the", "scrollback_lines", "property", "of", "all", "terminals", "open", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L171-L178
236,675
Guake/guake
guake/gsettings.py
GSettingHandler.keystroke_output
def keystroke_output(self, settings, key, user_data): """If the gconf var scroll_output be changed, this method will be called and will set the scroll_on_output in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_scroll_on_output(settings.get_boolean(key))
python
def keystroke_output(self, settings, key, user_data): for i in self.guake.notebook_manager.iter_terminals(): i.set_scroll_on_output(settings.get_boolean(key))
[ "def", "keystroke_output", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "i", ".", "set_scroll_on_output", "(", "settings", ".", ...
If the gconf var scroll_output be changed, this method will be called and will set the scroll_on_output in all terminals open.
[ "If", "the", "gconf", "var", "scroll_output", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "set", "the", "scroll_on_output", "in", "all", "terminals", "open", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L188-L194
236,676
Guake/guake
guake/gsettings.py
GSettingHandler.keystroke_toggled
def keystroke_toggled(self, settings, key, user_data): """If the gconf var scroll_keystroke be changed, this method will be called and will set the scroll_on_keystroke in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_scroll_on_keystroke(settings.get_boolean(key))
python
def keystroke_toggled(self, settings, key, user_data): for i in self.guake.notebook_manager.iter_terminals(): i.set_scroll_on_keystroke(settings.get_boolean(key))
[ "def", "keystroke_toggled", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "i", ".", "set_scroll_on_keystroke", "(", "settings", "...
If the gconf var scroll_keystroke be changed, this method will be called and will set the scroll_on_keystroke in all terminals open.
[ "If", "the", "gconf", "var", "scroll_keystroke", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "set", "the", "scroll_on_keystroke", "in", "all", "terminals", "open", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L196-L202
236,677
Guake/guake
guake/gsettings.py
GSettingHandler.allow_bold_toggled
def allow_bold_toggled(self, settings, key, user_data): """If the gconf var allow_bold is changed, this method will be called and will change the VTE terminal o. displaying characters in bold font. """ for term in self.guake.notebook_manager.iter_terminals(): term.set_allow_bold(settings.get_boolean(key))
python
def allow_bold_toggled(self, settings, key, user_data): for term in self.guake.notebook_manager.iter_terminals(): term.set_allow_bold(settings.get_boolean(key))
[ "def", "allow_bold_toggled", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "term", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "term", ".", "set_allow_bold", "(", "settings", "."...
If the gconf var allow_bold is changed, this method will be called and will change the VTE terminal o. displaying characters in bold font.
[ "If", "the", "gconf", "var", "allow_bold", "is", "changed", "this", "method", "will", "be", "called", "and", "will", "change", "the", "VTE", "terminal", "o", ".", "displaying", "characters", "in", "bold", "font", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L226-L232
236,678
Guake/guake
guake/gsettings.py
GSettingHandler.bold_is_bright_toggled
def bold_is_bright_toggled(self, settings, key, user_data): """If the dconf var bold_is_bright is changed, this method will be called and will change the VTE terminal to toggle auto-brightened bold text. """ try: for term in self.guake.notebook_manager.iter_terminals(): term.set_bold_is_bright(settings.get_boolean(key)) except: # pylint: disable=bare-except log.error("set_bold_is_bright not supported by your version of VTE")
python
def bold_is_bright_toggled(self, settings, key, user_data): try: for term in self.guake.notebook_manager.iter_terminals(): term.set_bold_is_bright(settings.get_boolean(key)) except: # pylint: disable=bare-except log.error("set_bold_is_bright not supported by your version of VTE")
[ "def", "bold_is_bright_toggled", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "try", ":", "for", "term", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "term", ".", "set_bold_is_bright", ...
If the dconf var bold_is_bright is changed, this method will be called and will change the VTE terminal to toggle auto-brightened bold text.
[ "If", "the", "dconf", "var", "bold_is_bright", "is", "changed", "this", "method", "will", "be", "called", "and", "will", "change", "the", "VTE", "terminal", "to", "toggle", "auto", "-", "brightened", "bold", "text", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L234-L242
236,679
Guake/guake
guake/gsettings.py
GSettingHandler.palette_font_and_background_color_toggled
def palette_font_and_background_color_toggled(self, settings, key, user_data): """If the gconf var use_palette_font_and_background_color be changed, this method will be called and will change the font color and the background color to the color defined in the palette. """ self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette')
python
def palette_font_and_background_color_toggled(self, settings, key, user_data): self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette')
[ "def", "palette_font_and_background_color_toggled", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "self", ".", "settings", ".", "styleFont", ".", "triggerOnChangedValue", "(", "self", ".", "settings", ".", "styleFont", ",", "'palette'", "...
If the gconf var use_palette_font_and_background_color be changed, this method will be called and will change the font color and the background color to the color defined in the palette.
[ "If", "the", "gconf", "var", "use_palette_font_and_background_color", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "change", "the", "font", "color", "and", "the", "background", "color", "to", "the", "color", "defined", "in", "the", ...
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L244-L249
236,680
Guake/guake
guake/gsettings.py
GSettingHandler.backspace_changed
def backspace_changed(self, settings, key, user_data): """If the gconf var compat_backspace be changed, this method will be called and will change the binding configuration in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_backspace_binding(self.getEraseBinding(settings.get_string(key)))
python
def backspace_changed(self, settings, key, user_data): for i in self.guake.notebook_manager.iter_terminals(): i.set_backspace_binding(self.getEraseBinding(settings.get_string(key)))
[ "def", "backspace_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "i", ".", "set_backspace_binding", "(", "self", ".", ...
If the gconf var compat_backspace be changed, this method will be called and will change the binding configuration in all terminals open.
[ "If", "the", "gconf", "var", "compat_backspace", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "change", "the", "binding", "configuration", "in", "all", "terminals", "open", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L286-L292
236,681
Guake/guake
guake/gsettings.py
GSettingHandler.delete_changed
def delete_changed(self, settings, key, user_data): """If the gconf var compat_delete be changed, this method will be called and will change the binding configuration in all terminals open. """ for i in self.guake.notebook_manager.iter_terminals(): i.set_delete_binding(self.getEraseBinding(settings.get_string(key)))
python
def delete_changed(self, settings, key, user_data): for i in self.guake.notebook_manager.iter_terminals(): i.set_delete_binding(self.getEraseBinding(settings.get_string(key)))
[ "def", "delete_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "for", "i", "in", "self", ".", "guake", ".", "notebook_manager", ".", "iter_terminals", "(", ")", ":", "i", ".", "set_delete_binding", "(", "self", ".", "getEr...
If the gconf var compat_delete be changed, this method will be called and will change the binding configuration in all terminals open.
[ "If", "the", "gconf", "var", "compat_delete", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "change", "the", "binding", "configuration", "in", "all", "terminals", "open", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L294-L300
236,682
Guake/guake
guake/gsettings.py
GSettingHandler.max_tab_name_length_changed
def max_tab_name_length_changed(self, settings, key, user_data): """If the gconf var max_tab_name_length be changed, this method will be called and will set the tab name length limit. """ # avoid get window title before terminal is ready if self.guake.notebook_manager.get_current_notebook().get_current_terminal() is None: return # avoid get window title before terminal is ready if self.guake.notebook_manager.get_current_notebook().get_current_terminal( ).get_window_title() is None: return self.guake.recompute_tabs_titles()
python
def max_tab_name_length_changed(self, settings, key, user_data): # avoid get window title before terminal is ready if self.guake.notebook_manager.get_current_notebook().get_current_terminal() is None: return # avoid get window title before terminal is ready if self.guake.notebook_manager.get_current_notebook().get_current_terminal( ).get_window_title() is None: return self.guake.recompute_tabs_titles()
[ "def", "max_tab_name_length_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "# avoid get window title before terminal is ready", "if", "self", ".", "guake", ".", "notebook_manager", ".", "get_current_notebook", "(", ")", ".", "get_curre...
If the gconf var max_tab_name_length be changed, this method will be called and will set the tab name length limit.
[ "If", "the", "gconf", "var", "max_tab_name_length", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "set", "the", "tab", "name", "length", "limit", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L302-L315
236,683
Guake/guake
guake/gsettings.py
GSettingHandler.abbreviate_tab_names_changed
def abbreviate_tab_names_changed(self, settings, key, user_data): """If the gconf var abbreviate_tab_names be changed, this method will be called and will update tab names. """ abbreviate_tab_names = settings.get_boolean('abbreviate-tab-names') self.guake.abbreviate = abbreviate_tab_names self.guake.recompute_tabs_titles()
python
def abbreviate_tab_names_changed(self, settings, key, user_data): abbreviate_tab_names = settings.get_boolean('abbreviate-tab-names') self.guake.abbreviate = abbreviate_tab_names self.guake.recompute_tabs_titles()
[ "def", "abbreviate_tab_names_changed", "(", "self", ",", "settings", ",", "key", ",", "user_data", ")", ":", "abbreviate_tab_names", "=", "settings", ".", "get_boolean", "(", "'abbreviate-tab-names'", ")", "self", ".", "guake", ".", "abbreviate", "=", "abbreviate_...
If the gconf var abbreviate_tab_names be changed, this method will be called and will update tab names.
[ "If", "the", "gconf", "var", "abbreviate_tab_names", "be", "changed", "this", "method", "will", "be", "called", "and", "will", "update", "tab", "names", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L317-L323
236,684
Guake/guake
guake/keybindings.py
Keybindings.reload_accelerators
def reload_accelerators(self, *args): """Reassign an accel_group to guake main window and guake context menu and calls the load_accelerators method. """ if self.accel_group: self.guake.window.remove_accel_group(self.accel_group) self.accel_group = Gtk.AccelGroup() self.guake.window.add_accel_group(self.accel_group) self.load_accelerators()
python
def reload_accelerators(self, *args): if self.accel_group: self.guake.window.remove_accel_group(self.accel_group) self.accel_group = Gtk.AccelGroup() self.guake.window.add_accel_group(self.accel_group) self.load_accelerators()
[ "def", "reload_accelerators", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "accel_group", ":", "self", ".", "guake", ".", "window", ".", "remove_accel_group", "(", "self", ".", "accel_group", ")", "self", ".", "accel_group", "=", "Gtk", "....
Reassign an accel_group to guake main window and guake context menu and calls the load_accelerators method.
[ "Reassign", "an", "accel_group", "to", "guake", "main", "window", "and", "guake", "context", "menu", "and", "calls", "the", "load_accelerators", "method", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/keybindings.py#L104-L112
236,685
Guake/guake
guake/globals.py
bindtextdomain
def bindtextdomain(app_name, locale_dir=None): """ Bind the domain represented by app_name to the locale directory locale_dir. It has the effect of loading translations, enabling applications for different languages. app_name: a domain to look for translations, typically the name of an application. locale_dir: a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo If omitted or None, then the current binding for app_name is used. """ import locale from locale import gettext as _ log.info("Local binding for app '%s', local dir: %s", app_name, locale_dir) locale.bindtextdomain(app_name, locale_dir) locale.textdomain(app_name)
python
def bindtextdomain(app_name, locale_dir=None): import locale from locale import gettext as _ log.info("Local binding for app '%s', local dir: %s", app_name, locale_dir) locale.bindtextdomain(app_name, locale_dir) locale.textdomain(app_name)
[ "def", "bindtextdomain", "(", "app_name", ",", "locale_dir", "=", "None", ")", ":", "import", "locale", "from", "locale", "import", "gettext", "as", "_", "log", ".", "info", "(", "\"Local binding for app '%s', local dir: %s\"", ",", "app_name", ",", "locale_dir", ...
Bind the domain represented by app_name to the locale directory locale_dir. It has the effect of loading translations, enabling applications for different languages. app_name: a domain to look for translations, typically the name of an application. locale_dir: a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo If omitted or None, then the current binding for app_name is used.
[ "Bind", "the", "domain", "represented", "by", "app_name", "to", "the", "locale", "directory", "locale_dir", ".", "It", "has", "the", "effect", "of", "loading", "translations", "enabling", "applications", "for", "different", "languages", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/globals.py#L38-L58
236,686
Guake/guake
guake/prefs.py
setup_standalone_signals
def setup_standalone_signals(instance): """Called when prefs dialog is running in standalone mode. It makes the delete event of dialog and click on close button finish the application. """ window = instance.get_widget('config-window') window.connect('delete-event', Gtk.main_quit) # We need to block the execution of the already associated # callback before connecting the new handler. button = instance.get_widget('button1') button.handler_block_by_func(instance.gtk_widget_destroy) button.connect('clicked', Gtk.main_quit) return instance
python
def setup_standalone_signals(instance): window = instance.get_widget('config-window') window.connect('delete-event', Gtk.main_quit) # We need to block the execution of the already associated # callback before connecting the new handler. button = instance.get_widget('button1') button.handler_block_by_func(instance.gtk_widget_destroy) button.connect('clicked', Gtk.main_quit) return instance
[ "def", "setup_standalone_signals", "(", "instance", ")", ":", "window", "=", "instance", ".", "get_widget", "(", "'config-window'", ")", "window", ".", "connect", "(", "'delete-event'", ",", "Gtk", ".", "main_quit", ")", "# We need to block the execution of the alread...
Called when prefs dialog is running in standalone mode. It makes the delete event of dialog and click on close button finish the application.
[ "Called", "when", "prefs", "dialog", "is", "running", "in", "standalone", "mode", ".", "It", "makes", "the", "delete", "event", "of", "dialog", "and", "click", "on", "close", "button", "finish", "the", "application", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1490-L1504
236,687
Guake/guake
guake/prefs.py
PrefsCallbacks.on_default_shell_changed
def on_default_shell_changed(self, combo): """Changes the activity of default_shell in dconf """ citer = combo.get_active_iter() if not citer: return shell = combo.get_model().get_value(citer, 0) # we unset the value (restore to default) when user chooses to use # user shell as guake shell interpreter. if shell == USER_SHELL_VALUE: self.settings.general.reset('default-shell') else: self.settings.general.set_string('default-shell', shell)
python
def on_default_shell_changed(self, combo): citer = combo.get_active_iter() if not citer: return shell = combo.get_model().get_value(citer, 0) # we unset the value (restore to default) when user chooses to use # user shell as guake shell interpreter. if shell == USER_SHELL_VALUE: self.settings.general.reset('default-shell') else: self.settings.general.set_string('default-shell', shell)
[ "def", "on_default_shell_changed", "(", "self", ",", "combo", ")", ":", "citer", "=", "combo", ".", "get_active_iter", "(", ")", "if", "not", "citer", ":", "return", "shell", "=", "combo", ".", "get_model", "(", ")", ".", "get_value", "(", "citer", ",", ...
Changes the activity of default_shell in dconf
[ "Changes", "the", "activity", "of", "default_shell", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L368-L380
236,688
Guake/guake
guake/prefs.py
PrefsCallbacks.on_gtk_theme_name_changed
def on_gtk_theme_name_changed(self, combo): """Set the `gtk_theme_name' property in dconf """ citer = combo.get_active_iter() if not citer: return theme_name = combo.get_model().get_value(citer, 0) self.settings.general.set_string('gtk-theme-name', theme_name) select_gtk_theme(self.settings)
python
def on_gtk_theme_name_changed(self, combo): citer = combo.get_active_iter() if not citer: return theme_name = combo.get_model().get_value(citer, 0) self.settings.general.set_string('gtk-theme-name', theme_name) select_gtk_theme(self.settings)
[ "def", "on_gtk_theme_name_changed", "(", "self", ",", "combo", ")", ":", "citer", "=", "combo", ".", "get_active_iter", "(", ")", "if", "not", "citer", ":", "return", "theme_name", "=", "combo", ".", "get_model", "(", ")", ".", "get_value", "(", "citer", ...
Set the `gtk_theme_name' property in dconf
[ "Set", "the", "gtk_theme_name", "property", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L417-L425
236,689
Guake/guake
guake/prefs.py
PrefsCallbacks.on_gtk_prefer_dark_theme_toggled
def on_gtk_prefer_dark_theme_toggled(self, chk): """Set the `gtk_prefer_dark_theme' property in dconf """ self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active()) select_gtk_theme(self.settings)
python
def on_gtk_prefer_dark_theme_toggled(self, chk): self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active()) select_gtk_theme(self.settings)
[ "def", "on_gtk_prefer_dark_theme_toggled", "(", "self", ",", "chk", ")", ":", "self", ".", "settings", ".", "general", ".", "set_boolean", "(", "'gtk-prefer-dark-theme'", ",", "chk", ".", "get_active", "(", ")", ")", "select_gtk_theme", "(", "self", ".", "sett...
Set the `gtk_prefer_dark_theme' property in dconf
[ "Set", "the", "gtk_prefer_dark_theme", "property", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L427-L431
236,690
Guake/guake
guake/prefs.py
PrefsCallbacks.on_start_at_login_toggled
def on_start_at_login_toggled(self, chk): """Changes the activity of start_at_login in dconf """ self.settings.general.set_boolean('start-at-login', chk.get_active()) refresh_user_start(self.settings)
python
def on_start_at_login_toggled(self, chk): self.settings.general.set_boolean('start-at-login', chk.get_active()) refresh_user_start(self.settings)
[ "def", "on_start_at_login_toggled", "(", "self", ",", "chk", ")", ":", "self", ".", "settings", ".", "general", ".", "set_boolean", "(", "'start-at-login'", ",", "chk", ".", "get_active", "(", ")", ")", "refresh_user_start", "(", "self", ".", "settings", ")"...
Changes the activity of start_at_login in dconf
[ "Changes", "the", "activity", "of", "start_at_login", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L480-L484
236,691
Guake/guake
guake/prefs.py
PrefsCallbacks.on_max_tab_name_length_changed
def on_max_tab_name_length_changed(self, spin): """Changes the value of max_tab_name_length in dconf """ val = int(spin.get_value()) self.settings.general.set_int('max-tab-name-length', val) self.prefDlg.update_vte_subwidgets_states()
python
def on_max_tab_name_length_changed(self, spin): val = int(spin.get_value()) self.settings.general.set_int('max-tab-name-length', val) self.prefDlg.update_vte_subwidgets_states()
[ "def", "on_max_tab_name_length_changed", "(", "self", ",", "spin", ")", ":", "val", "=", "int", "(", "spin", ".", "get_value", "(", ")", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'max-tab-name-length'", ",", "val", ")", "self", ...
Changes the value of max_tab_name_length in dconf
[ "Changes", "the", "value", "of", "max_tab_name_length", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L501-L506
236,692
Guake/guake
guake/prefs.py
PrefsCallbacks.on_right_align_toggled
def on_right_align_toggled(self, chk): """set the horizontal alignment setting. """ v = chk.get_active() self.settings.general.set_int('window-halignment', 1 if v else 0)
python
def on_right_align_toggled(self, chk): v = chk.get_active() self.settings.general.set_int('window-halignment', 1 if v else 0)
[ "def", "on_right_align_toggled", "(", "self", ",", "chk", ")", ":", "v", "=", "chk", ".", "get_active", "(", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'window-halignment'", ",", "1", "if", "v", "else", "0", ")" ]
set the horizontal alignment setting.
[ "set", "the", "horizontal", "alignment", "setting", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L514-L518
236,693
Guake/guake
guake/prefs.py
PrefsCallbacks.on_bottom_align_toggled
def on_bottom_align_toggled(self, chk): """set the vertical alignment setting. """ v = chk.get_active() self.settings.general.set_int('window-valignment', ALIGN_BOTTOM if v else ALIGN_TOP)
python
def on_bottom_align_toggled(self, chk): v = chk.get_active() self.settings.general.set_int('window-valignment', ALIGN_BOTTOM if v else ALIGN_TOP)
[ "def", "on_bottom_align_toggled", "(", "self", ",", "chk", ")", ":", "v", "=", "chk", ".", "get_active", "(", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'window-valignment'", ",", "ALIGN_BOTTOM", "if", "v", "else", "ALIGN_TOP", ")"...
set the vertical alignment setting.
[ "set", "the", "vertical", "alignment", "setting", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L520-L524
236,694
Guake/guake
guake/prefs.py
PrefsCallbacks.on_display_n_changed
def on_display_n_changed(self, combo): """Set the destination display in dconf. """ i = combo.get_active_iter() if not i: return model = combo.get_model() first_item_path = model.get_path(model.get_iter_first()) if model.get_path(i) == first_item_path: val_int = ALWAYS_ON_PRIMARY else: val = model.get_value(i, 0) val_int = int(val.split()[0]) # extracts 1 from '1' or from '1 (primary)' self.settings.general.set_int('display-n', val_int)
python
def on_display_n_changed(self, combo): i = combo.get_active_iter() if not i: return model = combo.get_model() first_item_path = model.get_path(model.get_iter_first()) if model.get_path(i) == first_item_path: val_int = ALWAYS_ON_PRIMARY else: val = model.get_value(i, 0) val_int = int(val.split()[0]) # extracts 1 from '1' or from '1 (primary)' self.settings.general.set_int('display-n', val_int)
[ "def", "on_display_n_changed", "(", "self", ",", "combo", ")", ":", "i", "=", "combo", ".", "get_active_iter", "(", ")", "if", "not", "i", ":", "return", "model", "=", "combo", ".", "get_model", "(", ")", "first_item_path", "=", "model", ".", "get_path",...
Set the destination display in dconf.
[ "Set", "the", "destination", "display", "in", "dconf", "." ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L526-L542
236,695
Guake/guake
guake/prefs.py
PrefsCallbacks.on_window_height_value_changed
def on_window_height_value_changed(self, hscale): """Changes the value of window_height in dconf """ val = hscale.get_value() self.settings.general.set_int('window-height', int(val))
python
def on_window_height_value_changed(self, hscale): val = hscale.get_value() self.settings.general.set_int('window-height', int(val))
[ "def", "on_window_height_value_changed", "(", "self", ",", "hscale", ")", ":", "val", "=", "hscale", ".", "get_value", "(", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'window-height'", ",", "int", "(", "val", ")", ")" ]
Changes the value of window_height in dconf
[ "Changes", "the", "value", "of", "window_height", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L544-L548
236,696
Guake/guake
guake/prefs.py
PrefsCallbacks.on_window_width_value_changed
def on_window_width_value_changed(self, wscale): """Changes the value of window_width in dconf """ val = wscale.get_value() self.settings.general.set_int('window-width', int(val))
python
def on_window_width_value_changed(self, wscale): val = wscale.get_value() self.settings.general.set_int('window-width', int(val))
[ "def", "on_window_width_value_changed", "(", "self", ",", "wscale", ")", ":", "val", "=", "wscale", ".", "get_value", "(", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'window-width'", ",", "int", "(", "val", ")", ")" ]
Changes the value of window_width in dconf
[ "Changes", "the", "value", "of", "window_width", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L550-L554
236,697
Guake/guake
guake/prefs.py
PrefsCallbacks.on_window_halign_value_changed
def on_window_halign_value_changed(self, halign_button): """Changes the value of window_halignment in dconf """ which_align = { 'radiobutton_align_left': ALIGN_LEFT, 'radiobutton_align_right': ALIGN_RIGHT, 'radiobutton_align_center': ALIGN_CENTER } if halign_button.get_active(): self.settings.general.set_int( 'window-halignment', which_align[halign_button.get_name()] ) self.prefDlg.get_widget("window_horizontal_displacement").set_sensitive( which_align[halign_button.get_name()] != ALIGN_CENTER )
python
def on_window_halign_value_changed(self, halign_button): which_align = { 'radiobutton_align_left': ALIGN_LEFT, 'radiobutton_align_right': ALIGN_RIGHT, 'radiobutton_align_center': ALIGN_CENTER } if halign_button.get_active(): self.settings.general.set_int( 'window-halignment', which_align[halign_button.get_name()] ) self.prefDlg.get_widget("window_horizontal_displacement").set_sensitive( which_align[halign_button.get_name()] != ALIGN_CENTER )
[ "def", "on_window_halign_value_changed", "(", "self", ",", "halign_button", ")", ":", "which_align", "=", "{", "'radiobutton_align_left'", ":", "ALIGN_LEFT", ",", "'radiobutton_align_right'", ":", "ALIGN_RIGHT", ",", "'radiobutton_align_center'", ":", "ALIGN_CENTER", "}",...
Changes the value of window_halignment in dconf
[ "Changes", "the", "value", "of", "window_halignment", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L556-L570
236,698
Guake/guake
guake/prefs.py
PrefsCallbacks.on_history_size_value_changed
def on_history_size_value_changed(self, spin): """Changes the value of history_size in dconf """ val = int(spin.get_value()) self.settings.general.set_int('history-size', val) self._update_history_widgets()
python
def on_history_size_value_changed(self, spin): val = int(spin.get_value()) self.settings.general.set_int('history-size', val) self._update_history_widgets()
[ "def", "on_history_size_value_changed", "(", "self", ",", "spin", ")", ":", "val", "=", "int", "(", "spin", ".", "get_value", "(", ")", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'history-size'", ",", "val", ")", "self", ".", "...
Changes the value of history_size in dconf
[ "Changes", "the", "value", "of", "history_size", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L584-L589
236,699
Guake/guake
guake/prefs.py
PrefsCallbacks.on_transparency_value_changed
def on_transparency_value_changed(self, hscale): """Changes the value of background_transparency in dconf """ value = hscale.get_value() self.prefDlg.set_colors_from_settings() self.settings.styleBackground.set_int('transparency', MAX_TRANSPARENCY - int(value))
python
def on_transparency_value_changed(self, hscale): value = hscale.get_value() self.prefDlg.set_colors_from_settings() self.settings.styleBackground.set_int('transparency', MAX_TRANSPARENCY - int(value))
[ "def", "on_transparency_value_changed", "(", "self", ",", "hscale", ")", ":", "value", "=", "hscale", ".", "get_value", "(", ")", "self", ".", "prefDlg", ".", "set_colors_from_settings", "(", ")", "self", ".", "settings", ".", "styleBackground", ".", "set_int"...
Changes the value of background_transparency in dconf
[ "Changes", "the", "value", "of", "background_transparency", "in", "dconf" ]
4153ef38f9044cbed6494075fce80acd5809df2b
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L631-L636