hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
⌀
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
8bf1b3dd29ef891853dda3b945b3c0dcb868433b
richpsharp/raster_calculations
realized_pollination.py
[ "Apache-2.0" ]
Python
create_flat_radial_convolution_mask
null
def create_flat_radial_convolution_mask( pixel_size_degree, radius_meters, kernel_filepath): """Create a radial mask to sample pixels in convolution filter. Parameters: pixel_size_degree (float): size of pixel in degrees. radius_meters (float): desired size of radial mask in meter...
Create a radial mask to sample pixels in convolution filter. Parameters: pixel_size_degree (float): size of pixel in degrees. radius_meters (float): desired size of radial mask in meters. Returns: A 2D numpy array that can be used in a convolution to aggregate a raster ...
Create a radial mask to sample pixels in convolution filter.
[ "Create", "a", "radial", "mask", "to", "sample", "pixels", "in", "convolution", "filter", "." ]
def create_flat_radial_convolution_mask( pixel_size_degree, radius_meters, kernel_filepath): degree_len_0 = 110574 degree_len_60 = 111412 pixel_size_m = pixel_size_degree * (degree_len_0 + degree_len_60) / 2.0 pixel_radius = numpy.ceil(radius_meters / pixel_size_m) n_pixels = (int(pixel_...
[ "def", "create_flat_radial_convolution_mask", "(", "pixel_size_degree", ",", "radius_meters", ",", "kernel_filepath", ")", ":", "degree_len_0", "=", "110574", "degree_len_60", "=", "111412", "pixel_size_m", "=", "pixel_size_degree", "*", "(", "degree_len_0", "+", "degre...
Create a radial mask to sample pixels in convolution filter.
[ "Create", "a", "radial", "mask", "to", "sample", "pixels", "in", "convolution", "filter", "." ]
[ "\"\"\"Create a radial mask to sample pixels in convolution filter.\r\n\r\n Parameters:\r\n pixel_size_degree (float): size of pixel in degrees.\r\n radius_meters (float): desired size of radial mask in meters.\r\n\r\n Returns:\r\n A 2D numpy array that can be used in a convolution to agg...
[ { "param": "pixel_size_degree", "type": null }, { "param": "radius_meters", "type": null }, { "param": "kernel_filepath", "type": null } ]
{ "returns": [ { "docstring": "A 2D numpy array that can be used in a convolution to aggregate a\nraster while accounting for partial coverage of the circle on the\nedges of the pixel.", "docstring_tokens": [ "A", "2D", "numpy", "array", "that", "can", ...
bc319ea9b32385052f50a3e46e8149c489611d80
richpsharp/raster_calculations
country_percentile_linear_interp_cdf_database_querier.py
[ "Apache-2.0" ]
Python
linear_interpolate_cdf
<not_specific>
def linear_interpolate_cdf(base_cdf): """Linear interpolate regions of straight lines in the CDF. Parameters: base_cdf (list): n elements of non-decreasing order. Returns: list of length base_cdf where consecutive elements of straight lines are linearly interpolated between the lef...
Linear interpolate regions of straight lines in the CDF. Parameters: base_cdf (list): n elements of non-decreasing order. Returns: list of length base_cdf where consecutive elements of straight lines are linearly interpolated between the left and right sides.
Linear interpolate regions of straight lines in the CDF.
[ "Linear", "interpolate", "regions", "of", "straight", "lines", "in", "the", "CDF", "." ]
def linear_interpolate_cdf(base_cdf): target_cdf = list(base_cdf) index = 0 left_val = 0 while index < len(base_cdf)-1: if base_cdf[index] == base_cdf[index+1]: offset = index+1 while (offset < len(base_cdf)-1 and base_cdf[offset] == base_cdf[offset+1])...
[ "def", "linear_interpolate_cdf", "(", "base_cdf", ")", ":", "target_cdf", "=", "list", "(", "base_cdf", ")", "index", "=", "0", "left_val", "=", "0", "while", "index", "<", "len", "(", "base_cdf", ")", "-", "1", ":", "if", "base_cdf", "[", "index", "]"...
Linear interpolate regions of straight lines in the CDF.
[ "Linear", "interpolate", "regions", "of", "straight", "lines", "in", "the", "CDF", "." ]
[ "\"\"\"Linear interpolate regions of straight lines in the CDF.\n\n Parameters:\n base_cdf (list): n elements of non-decreasing order.\n\n Returns:\n list of length base_cdf where consecutive elements of straight lines\n are linearly interpolated between the left and right sides.\n\n \...
[ { "param": "base_cdf", "type": null } ]
{ "returns": [ { "docstring": "list of length base_cdf where consecutive elements of straight lines\nare linearly interpolated between the left and right sides.", "docstring_tokens": [ "list", "of", "length", "base_cdf", "where", "consecutive", "...
b6f92e709b1f66cccb18806401c4c322da0b932e
richpsharp/raster_calculations
normalize_by_geometry.py
[ "Apache-2.0" ]
Python
normalize_by_polygon
null
def normalize_by_polygon( raster_path, vector_path, percentile, clamp_range, workspace_dir, target_path): """Normalize a raster locally by regions defined by vector. Parameters: raster_path (str): path to base raster to aggregate over. vector_path (str): path to a vector ...
Normalize a raster locally by regions defined by vector. Parameters: raster_path (str): path to base raster to aggregate over. vector_path (str): path to a vector that defines local regions to normalize over. Any pixels outside of these polygons will be set to nodata. ...
Normalize a raster locally by regions defined by vector.
[ "Normalize", "a", "raster", "locally", "by", "regions", "defined", "by", "vector", "." ]
def normalize_by_polygon( raster_path, vector_path, percentile, clamp_range, workspace_dir, target_path): base_dir = os.path.dirname(target_path) for dir_path in [base_dir, workspace_dir]: try: os.makedirs(dir_path) except OSError: pass vector = ogr.Op...
[ "def", "normalize_by_polygon", "(", "raster_path", ",", "vector_path", ",", "percentile", ",", "clamp_range", ",", "workspace_dir", ",", "target_path", ")", ":", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "target_path", ")", "for", "dir_path", "i...
Normalize a raster locally by regions defined by vector.
[ "Normalize", "a", "raster", "locally", "by", "regions", "defined", "by", "vector", "." ]
[ "\"\"\"Normalize a raster locally by regions defined by vector.\r\n\r\n Parameters:\r\n raster_path (str): path to base raster to aggregate over.\r\n vector_path (str): path to a vector that defines local regions to\r\n normalize over. Any pixels outside of these polygons will be set\r\n...
[ { "param": "raster_path", "type": null }, { "param": "vector_path", "type": null }, { "param": "percentile", "type": null }, { "param": "clamp_range", "type": null }, { "param": "workspace_dir", "type": null }, { "param": "target_path", "type": nul...
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": "path to base raster to aggregate over.", "docstring_tokens": [ "p...
b6f92e709b1f66cccb18806401c4c322da0b932e
richpsharp/raster_calculations
normalize_by_geometry.py
[ "Apache-2.0" ]
Python
clip_and_mask_raster
null
def clip_and_mask_raster( raster_path, vector_path, fid, target_mask_path): """Clip raster to feature and then mask by geometry. Parameters: raster_path (str): path to raster to clip. vector_path (str): path to vector that contains feature `fid`. fid (int): feature ID to ...
Clip raster to feature and then mask by geometry. Parameters: raster_path (str): path to raster to clip. vector_path (str): path to vector that contains feature `fid`. fid (int): feature ID to use as the clipping feature. target_mask_path (str): raster is created as 0, 1, boun...
Clip raster to feature and then mask by geometry.
[ "Clip", "raster", "to", "feature", "and", "then", "mask", "by", "geometry", "." ]
def clip_and_mask_raster( raster_path, vector_path, fid, target_mask_path): vector = gdal.OpenEx(vector_path, gdal.OF_VECTOR) layer = vector.GetLayer() feature = layer.GetFeature(fid) geometry_ref = feature.GetGeometryRef() geometry = shapely.wkb.loads(geometry_ref.ExportToWkb()) base_di...
[ "def", "clip_and_mask_raster", "(", "raster_path", ",", "vector_path", ",", "fid", ",", "target_mask_path", ")", ":", "vector", "=", "gdal", ".", "OpenEx", "(", "vector_path", ",", "gdal", ".", "OF_VECTOR", ")", "layer", "=", "vector", ".", "GetLayer", "(", ...
Clip raster to feature and then mask by geometry.
[ "Clip", "raster", "to", "feature", "and", "then", "mask", "by", "geometry", "." ]
[ "\"\"\"Clip raster to feature and then mask by geometry.\r\n\r\n Parameters:\r\n raster_path (str): path to raster to clip.\r\n vector_path (str): path to vector that contains feature `fid`.\r\n fid (int): feature ID to use as the clipping feature.\r\n target_mask_path (str): raster i...
[ { "param": "raster_path", "type": null }, { "param": "vector_path", "type": null }, { "param": "fid", "type": null }, { "param": "target_mask_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": "path to raster to clip.", "docstring_tokens": [ "path", "...
b6f92e709b1f66cccb18806401c4c322da0b932e
richpsharp/raster_calculations
normalize_by_geometry.py
[ "Apache-2.0" ]
Python
calculate_percentile
null
def calculate_percentile( raster_path, percentiles_list, workspace_dir, result_pickle_path): """Calculate the percentile cutoffs of a given raster. Store in json. Parameters: raster_path (str): path to raster to calculate over. percentiles_list (list): sorted list of increasing pe...
Calculate the percentile cutoffs of a given raster. Store in json. Parameters: raster_path (str): path to raster to calculate over. percentiles_list (list): sorted list of increasing percentile cutoffs to calculate. workspace_dir (str): path to a directory where this funct...
Calculate the percentile cutoffs of a given raster. Store in json.
[ "Calculate", "the", "percentile", "cutoffs", "of", "a", "given", "raster", ".", "Store", "in", "json", "." ]
def calculate_percentile( raster_path, percentiles_list, workspace_dir, result_pickle_path): churn_dir = tempfile.mkdtemp(dir=workspace_dir) LOGGER.debug('processing percentiles for %s', raster_path) heap_size = 2**28 ffi_buffer_size = 2**10 percentile_values_list = pygeoprocessing.raster_ba...
[ "def", "calculate_percentile", "(", "raster_path", ",", "percentiles_list", ",", "workspace_dir", ",", "result_pickle_path", ")", ":", "churn_dir", "=", "tempfile", ".", "mkdtemp", "(", "dir", "=", "workspace_dir", ")", "LOGGER", ".", "debug", "(", "'processing pe...
Calculate the percentile cutoffs of a given raster.
[ "Calculate", "the", "percentile", "cutoffs", "of", "a", "given", "raster", "." ]
[ "\"\"\"Calculate the percentile cutoffs of a given raster. Store in json.\r\n\r\n Parameters:\r\n raster_path (str): path to raster to calculate over.\r\n percentiles_list (list): sorted list of increasing percentile\r\n cutoffs to calculate.\r\n workspace_dir (str): path to a dir...
[ { "param": "raster_path", "type": null }, { "param": "percentiles_list", "type": null }, { "param": "workspace_dir", "type": null }, { "param": "result_pickle_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": "path to raster to calculate over.", "docstring_tokens": [ "path",...
b948283562b4addf84aef90abbea964dc528cb8f
richpsharp/raster_calculations
raster_stats.py
[ "Apache-2.0" ]
Python
_area_of_pixel
<not_specific>
def _area_of_pixel(pixel_size, center_lat): """Calculate m^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Args: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this ...
Calculate m^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Args: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this value +/- half the `pixel-size` must not exceed 90/...
Calculate m^2 area of a wgs84 square pixel.
[ "Calculate", "m^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
def _area_of_pixel(pixel_size, center_lat): a = 6378137 b = 6356752.3142 e = math.sqrt(1 - (b/a)**2) area_list = [] for f in [center_lat+pixel_size/2, center_lat-pixel_size/2]: zm = 1 - e*math.sin(math.radians(f)) zp = 1 + e*math.sin(math.radians(f)) area_list.append( ...
[ "def", "_area_of_pixel", "(", "pixel_size", ",", "center_lat", ")", ":", "a", "=", "6378137", "b", "=", "6356752.3142", "e", "=", "math", ".", "sqrt", "(", "1", "-", "(", "b", "/", "a", ")", "**", "2", ")", "area_list", "=", "[", "]", "for", "f",...
Calculate m^2 area of a wgs84 square pixel.
[ "Calculate", "m^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
[ "\"\"\"Calculate m^2 area of a wgs84 square pixel.\n\n Adapted from: https://gis.stackexchange.com/a/127327/2397\n\n Args:\n pixel_size (float): length of side of pixel in degrees.\n center_lat (float): latitude of the center of the pixel. Note this\n value +/- half the `pixel-size` m...
[ { "param": "pixel_size", "type": null }, { "param": "center_lat", "type": null } ]
{ "returns": [ { "docstring": "Area of square pixel of side length `pixel_size` centered at\n`center_lat` in m^2.", "docstring_tokens": [ "Area", "of", "square", "pixel", "of", "side", "length", "`", "pixel_size", "`", ...
644ac86ba3df5e91aec95279ee5046928e726df5
richpsharp/raster_calculations
align_to_mask.py
[ "Apache-2.0" ]
Python
warp_raster
null
def warp_raster(base_raster_path, mask_raster_path, resample_mode, target_raster_path): """Warp raster to exemplar's bounding box, cell size, and projection.""" base_projection_wkt = geoprocessing.get_raster_info( base_raster_path)['projection_wkt'] if base_projection_wkt is None: # assume i...
Warp raster to exemplar's bounding box, cell size, and projection.
Warp raster to exemplar's bounding box, cell size, and projection.
[ "Warp", "raster", "to", "exemplar", "'", "s", "bounding", "box", "cell", "size", "and", "projection", "." ]
def warp_raster(base_raster_path, mask_raster_path, resample_mode, target_raster_path): base_projection_wkt = geoprocessing.get_raster_info( base_raster_path)['projection_wkt'] if base_projection_wkt is None: LOGGER.warn( f'{base_raster_path} has undefined projection, assuming WGS84'...
[ "def", "warp_raster", "(", "base_raster_path", ",", "mask_raster_path", ",", "resample_mode", ",", "target_raster_path", ")", ":", "base_projection_wkt", "=", "geoprocessing", ".", "get_raster_info", "(", "base_raster_path", ")", "[", "'projection_wkt'", "]", "if", "b...
Warp raster to exemplar's bounding box, cell size, and projection.
[ "Warp", "raster", "to", "exemplar", "'", "s", "bounding", "box", "cell", "size", "and", "projection", "." ]
[ "\"\"\"Warp raster to exemplar's bounding box, cell size, and projection.\"\"\"", "# assume its wgs84 if not defined" ]
[ { "param": "base_raster_path", "type": null }, { "param": "mask_raster_path", "type": null }, { "param": "resample_mode", "type": null }, { "param": "target_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mask_raster_path", "type": null, "docstring": null, ...
644ac86ba3df5e91aec95279ee5046928e726df5
richpsharp/raster_calculations
align_to_mask.py
[ "Apache-2.0" ]
Python
copy_and_rehash_final_file
null
def copy_and_rehash_final_file(base_raster_path, target_dir): """Copy base to target and replace hash with current hash.""" target_md5_free_path = os.path.join( target_dir, re.sub('(.*)md5_[0-9a-f]+_(.*)', r"\1\2", os.path.basename( base_raster_path))) shutil.copyfile(base_raster...
Copy base to target and replace hash with current hash.
Copy base to target and replace hash with current hash.
[ "Copy", "base", "to", "target", "and", "replace", "hash", "with", "current", "hash", "." ]
def copy_and_rehash_final_file(base_raster_path, target_dir): target_md5_free_path = os.path.join( target_dir, re.sub('(.*)md5_[0-9a-f]+_(.*)', r"\1\2", os.path.basename( base_raster_path))) shutil.copyfile(base_raster_path, target_md5_free_path) try: ecoshard.hash_file(t...
[ "def", "copy_and_rehash_final_file", "(", "base_raster_path", ",", "target_dir", ")", ":", "target_md5_free_path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "re", ".", "sub", "(", "'(.*)md5_[0-9a-f]+_(.*)'", ",", "r\"\\1\\2\"", ",", "os", ".",...
Copy base to target and replace hash with current hash.
[ "Copy", "base", "to", "target", "and", "replace", "hash", "with", "current", "hash", "." ]
[ "\"\"\"Copy base to target and replace hash with current hash.\"\"\"" ]
[ { "param": "base_raster_path", "type": null }, { "param": "target_dir", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "target_dir", "type": null, "docstring": null, "do...
644ac86ba3df5e91aec95279ee5046928e726df5
richpsharp/raster_calculations
align_to_mask.py
[ "Apache-2.0" ]
Python
mask_raster
<not_specific>
def mask_raster(base_raster_path, mask_raster_path, target_raster_path): """Mask base by mask setting nodata to nodata otherwise passthrough.""" mask_nodata = geoprocessing.get_raster_info( mask_raster_path)['nodata'][0] base_raster_info = geoprocessing.get_raster_info(base_raster_path) base_nod...
Mask base by mask setting nodata to nodata otherwise passthrough.
Mask base by mask setting nodata to nodata otherwise passthrough.
[ "Mask", "base", "by", "mask", "setting", "nodata", "to", "nodata", "otherwise", "passthrough", "." ]
def mask_raster(base_raster_path, mask_raster_path, target_raster_path): mask_nodata = geoprocessing.get_raster_info( mask_raster_path)['nodata'][0] base_raster_info = geoprocessing.get_raster_info(base_raster_path) base_nodata = base_raster_info['nodata'][0] def _mask_op(base_array, mask_array)...
[ "def", "mask_raster", "(", "base_raster_path", ",", "mask_raster_path", ",", "target_raster_path", ")", ":", "mask_nodata", "=", "geoprocessing", ".", "get_raster_info", "(", "mask_raster_path", ")", "[", "'nodata'", "]", "[", "0", "]", "base_raster_info", "=", "g...
Mask base by mask setting nodata to nodata otherwise passthrough.
[ "Mask", "base", "by", "mask", "setting", "nodata", "to", "nodata", "otherwise", "passthrough", "." ]
[ "\"\"\"Mask base by mask setting nodata to nodata otherwise passthrough.\"\"\"" ]
[ { "param": "base_raster_path", "type": null }, { "param": "mask_raster_path", "type": null }, { "param": "target_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mask_raster_path", "type": null, "docstring": null, ...
1ea91ca1b94bddb230eed45bbe918566bed8dca8
richpsharp/raster_calculations
mask_by_vector.py
[ "Apache-2.0" ]
Python
mask_raster
null
def mask_raster(base_raster_path, vector_mask_path, target_raster_path): """Mask base by vector to target.""" base_raster_info = geoprocessing.get_raster_info(base_raster_path) geoprocessing.new_raster_from_base( base_raster_path, target_raster_path, base_raster_info['datatype'], [base_raste...
Mask base by vector to target.
Mask base by vector to target.
[ "Mask", "base", "by", "vector", "to", "target", "." ]
def mask_raster(base_raster_path, vector_mask_path, target_raster_path): base_raster_info = geoprocessing.get_raster_info(base_raster_path) geoprocessing.new_raster_from_base( base_raster_path, target_raster_path, base_raster_info['datatype'], [base_raster_info['nodata'][0]]) geoprocessing.m...
[ "def", "mask_raster", "(", "base_raster_path", ",", "vector_mask_path", ",", "target_raster_path", ")", ":", "base_raster_info", "=", "geoprocessing", ".", "get_raster_info", "(", "base_raster_path", ")", "geoprocessing", ".", "new_raster_from_base", "(", "base_raster_pat...
Mask base by vector to target.
[ "Mask", "base", "by", "vector", "to", "target", "." ]
[ "\"\"\"Mask base by vector to target.\"\"\"" ]
[ { "param": "base_raster_path", "type": null }, { "param": "vector_mask_path", "type": null }, { "param": "target_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "vector_mask_path", "type": null, "docstring": null, ...
37c020f40356af5ac48e6f5853f7d3efdf73aeaf
richpsharp/raster_calculations
wgs84_to_ha.py
[ "Apache-2.0" ]
Python
area_of_pixel
<not_specific>
def area_of_pixel(pixel_size, center_lat): """Calculate m^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Args: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this ...
Calculate m^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Args: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this value +/- half the `pixel-size` must not exc...
Calculate m^2 area of a wgs84 square pixel.
[ "Calculate", "m^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
def area_of_pixel(pixel_size, center_lat): a = 6378137 b = 6356752.3142 e = math.sqrt(1 - (b/a)**2) area_list = [] for f in [center_lat+pixel_size/2, center_lat-pixel_size/2]: zm = 1 - e*math.sin(math.radians(f)) zp = 1 + e*math.sin(math.radians(f)) area_list.append( ...
[ "def", "area_of_pixel", "(", "pixel_size", ",", "center_lat", ")", ":", "a", "=", "6378137", "b", "=", "6356752.3142", "e", "=", "math", ".", "sqrt", "(", "1", "-", "(", "b", "/", "a", ")", "**", "2", ")", "area_list", "=", "[", "]", "for", "f", ...
Calculate m^2 area of a wgs84 square pixel.
[ "Calculate", "m^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
[ "\"\"\"Calculate m^2 area of a wgs84 square pixel.\r\n\r\n Adapted from: https://gis.stackexchange.com/a/127327/2397\r\n\r\n Args:\r\n pixel_size (float): length of side of pixel in degrees.\r\n center_lat (float): latitude of the center of the pixel. Note this\r\n value +/- half the ...
[ { "param": "pixel_size", "type": null }, { "param": "center_lat", "type": null } ]
{ "returns": [ { "docstring": "Area of square pixel of side length `pixel_size` centered at\n`center_lat` in m^2.", "docstring_tokens": [ "Area", "of", "square", "pixel", "of", "side", "length", "`", "pixel_size", "`", ...
37c020f40356af5ac48e6f5853f7d3efdf73aeaf
richpsharp/raster_calculations
wgs84_to_ha.py
[ "Apache-2.0" ]
Python
raster_to_area_raster
null
def raster_to_area_raster(base_raster_path, target_raster_path): """Convert base to a target raster of same shape with per area pixels.""" base_raster_info = pygeoprocessing.get_raster_info(base_raster_path) # create 1D array of pixel size vs. lat n_rows = base_raster_info['raster_size'][1] p...
Convert base to a target raster of same shape with per area pixels.
Convert base to a target raster of same shape with per area pixels.
[ "Convert", "base", "to", "a", "target", "raster", "of", "same", "shape", "with", "per", "area", "pixels", "." ]
def raster_to_area_raster(base_raster_path, target_raster_path): base_raster_info = pygeoprocessing.get_raster_info(base_raster_path) n_rows = base_raster_info['raster_size'][1] pixel_height = abs(base_raster_info['geotransform'][5]) miny = base_raster_info['bounding_box'][1] + pixel_height/2 maxy =...
[ "def", "raster_to_area_raster", "(", "base_raster_path", ",", "target_raster_path", ")", ":", "base_raster_info", "=", "pygeoprocessing", ".", "get_raster_info", "(", "base_raster_path", ")", "n_rows", "=", "base_raster_info", "[", "'raster_size'", "]", "[", "1", "]",...
Convert base to a target raster of same shape with per area pixels.
[ "Convert", "base", "to", "a", "target", "raster", "of", "same", "shape", "with", "per", "area", "pixels", "." ]
[ "\"\"\"Convert base to a target raster of same shape with per area pixels.\"\"\"", "# create 1D array of pixel size vs. lat\r", "# the / 2 is to get in the center of the pixel\r" ]
[ { "param": "base_raster_path", "type": null }, { "param": "target_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "target_raster_path", "type": null, "docstring": null, ...
6ac51e3d7305cd7c0449cb085f4d9c27855509e9
richpsharp/raster_calculations
percentile_cdf_pipeline.py
[ "Apache-2.0" ]
Python
calculate_percentile
null
def calculate_percentile( raster_path, percentiles_list, workspace_dir, result_pickle_path): """Calculate the percentile cutoffs of a given raster. Store in json. Parameters: raster_path (str): path to raster to calculate over. percentiles_list (list): sorted list of increasing pe...
Calculate the percentile cutoffs of a given raster. Store in json. Parameters: raster_path (str): path to raster to calculate over. percentiles_list (list): sorted list of increasing percentile cutoffs to calculate. workspace_dir (str): path to a directory where this funct...
Calculate the percentile cutoffs of a given raster. Store in json.
[ "Calculate", "the", "percentile", "cutoffs", "of", "a", "given", "raster", ".", "Store", "in", "json", "." ]
def calculate_percentile( raster_path, percentiles_list, workspace_dir, result_pickle_path): churn_dir = tempfile.mkdtemp(dir=workspace_dir) LOGGER.debug('processing percentiles for %s', raster_path) heap_size = 2**28 ffi_buffer_size = 2**10 result_dict = { 'percentiles_list': percen...
[ "def", "calculate_percentile", "(", "raster_path", ",", "percentiles_list", ",", "workspace_dir", ",", "result_pickle_path", ")", ":", "churn_dir", "=", "tempfile", ".", "mkdtemp", "(", "dir", "=", "workspace_dir", ")", "LOGGER", ".", "debug", "(", "'processing pe...
Calculate the percentile cutoffs of a given raster.
[ "Calculate", "the", "percentile", "cutoffs", "of", "a", "given", "raster", "." ]
[ "\"\"\"Calculate the percentile cutoffs of a given raster. Store in json.\r\n\r\n Parameters:\r\n raster_path (str): path to raster to calculate over.\r\n percentiles_list (list): sorted list of increasing percentile\r\n cutoffs to calculate.\r\n workspace_dir (str): path to a dir...
[ { "param": "raster_path", "type": null }, { "param": "percentiles_list", "type": null }, { "param": "workspace_dir", "type": null }, { "param": "result_pickle_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": "path to raster to calculate over.", "docstring_tokens": [ "path",...
eb33d43a1b207d06862e4e97ce71b69184dc3722
richpsharp/raster_calculations
cumulative_density_function_per_country_agbc_for_rachel.py
[ "Apache-2.0" ]
Python
extract_feature
null
def extract_feature( vector_path, feature_id, projection_wkt, target_vector_path, target_complete_token_path): """Make a local projection of a single feature in a vector. Parameters: vector_path (str): base vector in WGS84 coordinates. feature_id (int): FID for the featur...
Make a local projection of a single feature in a vector. Parameters: vector_path (str): base vector in WGS84 coordinates. feature_id (int): FID for the feature to extract. projection_wkt (str): projection wkt code to project feature to. target_gpkg_vector_path (str): path to n...
Make a local projection of a single feature in a vector.
[ "Make", "a", "local", "projection", "of", "a", "single", "feature", "in", "a", "vector", "." ]
def extract_feature( vector_path, feature_id, projection_wkt, target_vector_path, target_complete_token_path): base_vector = gdal.OpenEx(vector_path, gdal.OF_VECTOR) base_layer = base_vector.GetLayer() feature = base_layer.GetFeature(feature_id) geom = feature.GetGeometryRef() epsg_s...
[ "def", "extract_feature", "(", "vector_path", ",", "feature_id", ",", "projection_wkt", ",", "target_vector_path", ",", "target_complete_token_path", ")", ":", "base_vector", "=", "gdal", ".", "OpenEx", "(", "vector_path", ",", "gdal", ".", "OF_VECTOR", ")", "base...
Make a local projection of a single feature in a vector.
[ "Make", "a", "local", "projection", "of", "a", "single", "feature", "in", "a", "vector", "." ]
[ "\"\"\"Make a local projection of a single feature in a vector.\r\n\r\n Parameters:\r\n vector_path (str): base vector in WGS84 coordinates.\r\n feature_id (int): FID for the feature to extract.\r\n projection_wkt (str): projection wkt code to project feature to.\r\n target_gpkg_vecto...
[ { "param": "vector_path", "type": null }, { "param": "feature_id", "type": null }, { "param": "projection_wkt", "type": null }, { "param": "target_vector_path", "type": null }, { "param": "target_complete_token_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "vector_path", "type": null, "docstring": "base vector in WGS84 coordinates.", "docstring_tokens": [ "base",...
87b60c24dbfbdc29abfb007d0d89893acc2cf5a6
richpsharp/raster_calculations
cumulative_density_function_global.py
[ "Apache-2.0" ]
Python
calculate_percentiles
null
def calculate_percentiles( raster_path, percentile_list, target_percentile_pickle_path): """Calculate percentiles and save to a pickle file. Parameters: raster_path (str): path to raster. percentile_list (list): list of increasing order percentile thresholds between t...
Calculate percentiles and save to a pickle file. Parameters: raster_path (str): path to raster. percentile_list (list): list of increasing order percentile thresholds between the ranges 0-100. target_percentile_pickle_path (str): the result of the percentile f...
Calculate percentiles and save to a pickle file.
[ "Calculate", "percentiles", "and", "save", "to", "a", "pickle", "file", "." ]
def calculate_percentiles( raster_path, percentile_list, target_percentile_pickle_path): working_dir = os.path.dirname(target_percentile_pickle_path) heapfile_dir = tempfile.mkdtemp(dir=working_dir) percentile_values = pygeoprocessing.raster_band_percentile( (raster_path, 1), heapfile_dir, p...
[ "def", "calculate_percentiles", "(", "raster_path", ",", "percentile_list", ",", "target_percentile_pickle_path", ")", ":", "working_dir", "=", "os", ".", "path", ".", "dirname", "(", "target_percentile_pickle_path", ")", "heapfile_dir", "=", "tempfile", ".", "mkdtemp...
Calculate percentiles and save to a pickle file.
[ "Calculate", "percentiles", "and", "save", "to", "a", "pickle", "file", "." ]
[ "\"\"\"Calculate percentiles and save to a pickle file.\r\n\r\n Parameters:\r\n raster_path (str): path to raster.\r\n percentile_list (list): list of increasing order percentile thresholds\r\n between the ranges 0-100.\r\n target_percentile_pickle_path (str): the result of the pe...
[ { "param": "raster_path", "type": null }, { "param": "percentile_list", "type": null }, { "param": "target_percentile_pickle_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": "path to raster.", "docstring_tokens": [ "path", "to", ...
87b60c24dbfbdc29abfb007d0d89893acc2cf5a6
richpsharp/raster_calculations
cumulative_density_function_global.py
[ "Apache-2.0" ]
Python
extract_feature
null
def extract_feature( vector_path, feature_id, projection_wkt, target_vector_path, target_complete_token_path): """Make a local projection of a single feature in a vector. Parameters: vector_path (str): base vector in WGS84 coordinates. feature_id (int): FID for the featur...
Make a local projection of a single feature in a vector. Parameters: vector_path (str): base vector in WGS84 coordinates. feature_id (int): FID for the feature to extract. projection_wkt (str): projection wkt code to project feature to. target_gpkg_vector_path (str): path to n...
Make a local projection of a single feature in a vector.
[ "Make", "a", "local", "projection", "of", "a", "single", "feature", "in", "a", "vector", "." ]
def extract_feature( vector_path, feature_id, projection_wkt, target_vector_path, target_complete_token_path): base_vector = gdal.OpenEx(vector_path, gdal.OF_VECTOR) base_layer = base_vector.GetLayer() feature = base_layer.GetFeature(feature_id) geom = feature.GetGeometryRef() epsg_s...
[ "def", "extract_feature", "(", "vector_path", ",", "feature_id", ",", "projection_wkt", ",", "target_vector_path", ",", "target_complete_token_path", ")", ":", "base_vector", "=", "gdal", ".", "OpenEx", "(", "vector_path", ",", "gdal", ".", "OF_VECTOR", ")", "base...
Make a local projection of a single feature in a vector.
[ "Make", "a", "local", "projection", "of", "a", "single", "feature", "in", "a", "vector", "." ]
[ "\"\"\"Make a local projection of a single feature in a vector.\r\n\r\n Parameters:\r\n vector_path (str): base vector in WGS84 coordinates.\r\n feature_id (int): FID for the feature to extract.\r\n projection_wkt (str): projection wkt code to project feature to.\r\n target_gpkg_vecto...
[ { "param": "vector_path", "type": null }, { "param": "feature_id", "type": null }, { "param": "projection_wkt", "type": null }, { "param": "target_vector_path", "type": null }, { "param": "target_complete_token_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "vector_path", "type": null, "docstring": "base vector in WGS84 coordinates.", "docstring_tokens": [ "base",...
c19aa5f9ee9c9d27fad7631e5c42dca2bfb9da6a
richpsharp/raster_calculations
divide_raster_by_area_of_wgs84_pixel.py
[ "Apache-2.0" ]
Python
area_of_pixel_km2
<not_specific>
def area_of_pixel_km2(pixel_size, center_lat): """Calculate km^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Parameters: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this ...
Calculate km^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Parameters: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this value +/- half the `pixel-size` must not exc...
Calculate km^2 area of a wgs84 square pixel.
[ "Calculate", "km^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
def area_of_pixel_km2(pixel_size, center_lat): a = 6378137 b = 6356752.3142 e = math.sqrt(1 - (b/a)**2) area_list = [] for f in [center_lat+pixel_size/2, center_lat-pixel_size/2]: zm = 1 - e*math.sin(math.radians(f)) zp = 1 + e*math.sin(math.radians(f)) area_list.append( ...
[ "def", "area_of_pixel_km2", "(", "pixel_size", ",", "center_lat", ")", ":", "a", "=", "6378137", "b", "=", "6356752.3142", "e", "=", "math", ".", "sqrt", "(", "1", "-", "(", "b", "/", "a", ")", "**", "2", ")", "area_list", "=", "[", "]", "for", "...
Calculate km^2 area of a wgs84 square pixel.
[ "Calculate", "km^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
[ "\"\"\"Calculate km^2 area of a wgs84 square pixel.\n\n Adapted from: https://gis.stackexchange.com/a/127327/2397\n\n Parameters:\n pixel_size (float): length of side of pixel in degrees.\n center_lat (float): latitude of the center of the pixel. Note this\n value +/- half the `pixel-...
[ { "param": "pixel_size", "type": null }, { "param": "center_lat", "type": null } ]
{ "returns": [ { "docstring": "Area of square pixel of side length `pixel_size` centered at\n`center_lat` in km^2.", "docstring_tokens": [ "Area", "of", "square", "pixel", "of", "side", "length", "`", "pixel_size", "`", ...
5b9cc7d7c0db30611940331bd707b03638096755
richpsharp/raster_calculations
potential_pollination.py
[ "Apache-2.0" ]
Python
create_radial_convolution_mask
null
def create_radial_convolution_mask( pixel_size_degree, radius_meters, kernel_filepath): """Create a radial mask to sample pixels in convolution filter. Parameters: pixel_size_degree (float): size of pixel in degrees. radius_meters (float): desired size of radial mask in meters. ...
Create a radial mask to sample pixels in convolution filter. Parameters: pixel_size_degree (float): size of pixel in degrees. radius_meters (float): desired size of radial mask in meters. Returns: A 2D numpy array that can be used in a convolution to aggregate a raster ...
Create a radial mask to sample pixels in convolution filter.
[ "Create", "a", "radial", "mask", "to", "sample", "pixels", "in", "convolution", "filter", "." ]
def create_radial_convolution_mask( pixel_size_degree, radius_meters, kernel_filepath): degree_len_0 = 110574 degree_len_60 = 111412 pixel_size_m = pixel_size_degree * (degree_len_0 + degree_len_60) / 2.0 pixel_radius = numpy.ceil(radius_meters / pixel_size_m) n_pixels = (int(pixel_radiu...
[ "def", "create_radial_convolution_mask", "(", "pixel_size_degree", ",", "radius_meters", ",", "kernel_filepath", ")", ":", "degree_len_0", "=", "110574", "degree_len_60", "=", "111412", "pixel_size_m", "=", "pixel_size_degree", "*", "(", "degree_len_0", "+", "degree_len...
Create a radial mask to sample pixels in convolution filter.
[ "Create", "a", "radial", "mask", "to", "sample", "pixels", "in", "convolution", "filter", "." ]
[ "\"\"\"Create a radial mask to sample pixels in convolution filter.\r\n\r\n Parameters:\r\n pixel_size_degree (float): size of pixel in degrees.\r\n radius_meters (float): desired size of radial mask in meters.\r\n\r\n Returns:\r\n A 2D numpy array that can be used in a convolution to agg...
[ { "param": "pixel_size_degree", "type": null }, { "param": "radius_meters", "type": null }, { "param": "kernel_filepath", "type": null } ]
{ "returns": [ { "docstring": "A 2D numpy array that can be used in a convolution to aggregate a\nraster while accounting for partial coverage of the circle on the\nedges of the pixel.", "docstring_tokens": [ "A", "2D", "numpy", "array", "that", "can", ...
4d5b21a7611b1e89c32a23be8b0aa3ac8c6a2dde
richpsharp/raster_calculations
fill_lat_lng_nodata.py
[ "Apache-2.0" ]
Python
fill_by_convolution
null
def fill_by_convolution( base_raster_path, convolve_radius, target_filled_raster_path): """Clip and fill. Clip the base raster data to the bounding box then fill any noodata holes with a weighted distance convolution. Args: base_raster_path (str): path to base raster convolve_r...
Clip and fill. Clip the base raster data to the bounding box then fill any noodata holes with a weighted distance convolution. Args: base_raster_path (str): path to base raster convolve_radius (float): maximum convolution distance kernel in projected units of base. targ...
Clip and fill. Clip the base raster data to the bounding box then fill any noodata holes with a weighted distance convolution.
[ "Clip", "and", "fill", ".", "Clip", "the", "base", "raster", "data", "to", "the", "bounding", "box", "then", "fill", "any", "noodata", "holes", "with", "a", "weighted", "distance", "convolution", "." ]
def fill_by_convolution( base_raster_path, convolve_radius, target_filled_raster_path): try: LOGGER.info(f'filling {base_raster_path}') working_dir = os.path.join( os.path.dirname(target_filled_raster_path), os.path.basename(os.path.splitext(target_filled_raster_path)...
[ "def", "fill_by_convolution", "(", "base_raster_path", ",", "convolve_radius", ",", "target_filled_raster_path", ")", ":", "try", ":", "LOGGER", ".", "info", "(", "f'filling {base_raster_path}'", ")", "working_dir", "=", "os", ".", "path", ".", "join", "(", "os", ...
Clip and fill.
[ "Clip", "and", "fill", "." ]
[ "\"\"\"Clip and fill.\n\n Clip the base raster data to the bounding box then fill any noodata\n holes with a weighted distance convolution.\n\n Args:\n base_raster_path (str): path to base raster\n convolve_radius (float): maximum convolution distance kernel in\n projected units of...
[ { "param": "base_raster_path", "type": null }, { "param": "convolve_radius", "type": null }, { "param": "target_filled_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": "path to base raster", "docstring_tokens": [ "path", "to", "base", "raster" ], "default": null, "is_optional": false }, { ...
4d5b21a7611b1e89c32a23be8b0aa3ac8c6a2dde
richpsharp/raster_calculations
fill_lat_lng_nodata.py
[ "Apache-2.0" ]
Python
_mask_valid_op
<not_specific>
def _mask_valid_op(base_array, nodata): """Convert valid to True nodata/invalid to False.""" if nodata is not None: valid_mask = ~numpy.isclose(base_array, nodata) else: valid_mask = numpy.ones(base_array.shape, dtype=numpy.bool) valid_mask &= numpy.isfinite(base_array) return valid_...
Convert valid to True nodata/invalid to False.
Convert valid to True nodata/invalid to False.
[ "Convert", "valid", "to", "True", "nodata", "/", "invalid", "to", "False", "." ]
def _mask_valid_op(base_array, nodata): if nodata is not None: valid_mask = ~numpy.isclose(base_array, nodata) else: valid_mask = numpy.ones(base_array.shape, dtype=numpy.bool) valid_mask &= numpy.isfinite(base_array) return valid_mask
[ "def", "_mask_valid_op", "(", "base_array", ",", "nodata", ")", ":", "if", "nodata", "is", "not", "None", ":", "valid_mask", "=", "~", "numpy", ".", "isclose", "(", "base_array", ",", "nodata", ")", "else", ":", "valid_mask", "=", "numpy", ".", "ones", ...
Convert valid to True nodata/invalid to False.
[ "Convert", "valid", "to", "True", "nodata", "/", "invalid", "to", "False", "." ]
[ "\"\"\"Convert valid to True nodata/invalid to False.\"\"\"" ]
[ { "param": "base_array", "type": null }, { "param": "nodata", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nodata", "type": null, "docstring": null, "docstring_to...
4d5b21a7611b1e89c32a23be8b0aa3ac8c6a2dde
richpsharp/raster_calculations
fill_lat_lng_nodata.py
[ "Apache-2.0" ]
Python
sanitize_raster
null
def sanitize_raster(base_raster_path, target_raster_path): """Scrub base raster of any non-finite values to nodata. If noodata is None then scrub to 0. Args: base_raster_path (str): path to base raster target_raster_path (str): path to target raster Return: None. """ r...
Scrub base raster of any non-finite values to nodata. If noodata is None then scrub to 0. Args: base_raster_path (str): path to base raster target_raster_path (str): path to target raster Return: None.
Scrub base raster of any non-finite values to nodata. If noodata is None then scrub to 0.
[ "Scrub", "base", "raster", "of", "any", "non", "-", "finite", "values", "to", "nodata", ".", "If", "noodata", "is", "None", "then", "scrub", "to", "0", "." ]
def sanitize_raster(base_raster_path, target_raster_path): raster_info = pygeoprocessing.get_raster_info( base_raster_path) fill_value = raster_info['nodata'][0] if fill_value is None: fill_value = 0 pygeoprocessing.raster_calculator( [(base_raster_path, 1), (fill_value, 'raw')],...
[ "def", "sanitize_raster", "(", "base_raster_path", ",", "target_raster_path", ")", ":", "raster_info", "=", "pygeoprocessing", ".", "get_raster_info", "(", "base_raster_path", ")", "fill_value", "=", "raster_info", "[", "'nodata'", "]", "[", "0", "]", "if", "fill_...
Scrub base raster of any non-finite values to nodata.
[ "Scrub", "base", "raster", "of", "any", "non", "-", "finite", "values", "to", "nodata", "." ]
[ "\"\"\"Scrub base raster of any non-finite values to nodata.\n\n If noodata is None then scrub to 0.\n\n Args:\n base_raster_path (str): path to base raster\n target_raster_path (str): path to target raster\n\n Return:\n None.\n \"\"\"" ]
[ { "param": "base_raster_path", "type": null }, { "param": "target_raster_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster_path", "type": null, "docstring": "path to base raster", "docstring_tokens": [ "path", "to", "base", "raster" ], "default": null, "is_optional": false }, { ...
94f806f06724a19cb04e64eea4d0ea99e2299875
richpsharp/raster_calculations
zonal_stats_by_area.py
[ "Apache-2.0" ]
Python
_area_of_pixel_km2
<not_specific>
def _area_of_pixel_km2(pixel_size, center_lat): """Calculate km^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Parameters: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this ...
Calculate km^2 area of a wgs84 square pixel. Adapted from: https://gis.stackexchange.com/a/127327/2397 Parameters: pixel_size (float): length of side of pixel in degrees. center_lat (float): latitude of the center of the pixel. Note this value +/- half the `pixel-size` must not exc...
Calculate km^2 area of a wgs84 square pixel.
[ "Calculate", "km^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
def _area_of_pixel_km2(pixel_size, center_lat): a = 6378137 b = 6356752.3142 e = math.sqrt(1 - (b/a)**2) area_list = [] for f in [center_lat+pixel_size/2, center_lat-pixel_size/2]: zm = 1 - e*math.sin(math.radians(f)) zp = 1 + e*math.sin(math.radians(f)) area_list.append(...
[ "def", "_area_of_pixel_km2", "(", "pixel_size", ",", "center_lat", ")", ":", "a", "=", "6378137", "b", "=", "6356752.3142", "e", "=", "math", ".", "sqrt", "(", "1", "-", "(", "b", "/", "a", ")", "**", "2", ")", "area_list", "=", "[", "]", "for", ...
Calculate km^2 area of a wgs84 square pixel.
[ "Calculate", "km^2", "area", "of", "a", "wgs84", "square", "pixel", "." ]
[ "\"\"\"Calculate km^2 area of a wgs84 square pixel.\n\n Adapted from: https://gis.stackexchange.com/a/127327/2397\n\n Parameters:\n pixel_size (float): length of side of pixel in degrees.\n center_lat (float): latitude of the center of the pixel. Note this\n value +/- half the `pixel-...
[ { "param": "pixel_size", "type": null }, { "param": "center_lat", "type": null } ]
{ "returns": [ { "docstring": "Area of square pixel of side length `pixel_size` centered at\n`center_lat` in km^2.", "docstring_tokens": [ "Area", "of", "square", "pixel", "of", "side", "length", "`", "pixel_size", "`", ...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
country_nodata0_op
<not_specific>
def country_nodata0_op(base_array, nodata): """Convert base_array 0s to nodata.""" result = base_array.copy() result[base_array == 0] = nodata return result
Convert base_array 0s to nodata.
Convert base_array 0s to nodata.
[ "Convert", "base_array", "0s", "to", "nodata", "." ]
def country_nodata0_op(base_array, nodata): result = base_array.copy() result[base_array == 0] = nodata return result
[ "def", "country_nodata0_op", "(", "base_array", ",", "nodata", ")", ":", "result", "=", "base_array", ".", "copy", "(", ")", "result", "[", "base_array", "==", "0", "]", "=", "nodata", "return", "result" ]
Convert base_array 0s to nodata.
[ "Convert", "base_array", "0s", "to", "nodata", "." ]
[ "\"\"\"Convert base_array 0s to nodata.\"\"\"" ]
[ { "param": "base_array", "type": null }, { "param": "nodata", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nodata", "type": null, "docstring": null, "docstring_to...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
stitch_manager
<not_specific>
def stitch_manager( lock_map, cpu_semaphore, worker_pool, stitch_queue, raster_id_to_global_stitch_path_map): """Thread to manage jobs to fork off to stitch workers. Parameters: lock_map (dict): maps global raster paths to lock objects. cpu_semaphore (bounded semaphore): ...
Thread to manage jobs to fork off to stitch workers. Parameters: lock_map (dict): maps global raster paths to lock objects. cpu_semaphore (bounded semaphore): acquire this when sending a job the job should release it worker_pool (multiprocessing.Pool): send work to this po...
Thread to manage jobs to fork off to stitch workers.
[ "Thread", "to", "manage", "jobs", "to", "fork", "off", "to", "stitch", "workers", "." ]
def stitch_manager( lock_map, cpu_semaphore, worker_pool, stitch_queue, raster_id_to_global_stitch_path_map): while True: payload = stitch_queue.get() if payload == 'STOP': return LOGGER.debug('stitch manager got this payload: %s', str(payload)) local_tile...
[ "def", "stitch_manager", "(", "lock_map", ",", "cpu_semaphore", ",", "worker_pool", ",", "stitch_queue", ",", "raster_id_to_global_stitch_path_map", ")", ":", "while", "True", ":", "payload", "=", "stitch_queue", ".", "get", "(", ")", "if", "payload", "==", "'ST...
Thread to manage jobs to fork off to stitch workers.
[ "Thread", "to", "manage", "jobs", "to", "fork", "off", "to", "stitch", "workers", "." ]
[ "\"\"\"Thread to manage jobs to fork off to stitch workers.\r\n\r\n Parameters:\r\n lock_map (dict): maps global raster paths to lock objects.\r\n cpu_semaphore (bounded semaphore): acquire this when sending a job\r\n the job should release it\r\n worker_pool (multiprocessing.Pool...
[ { "param": "lock_map", "type": null }, { "param": "cpu_semaphore", "type": null }, { "param": "worker_pool", "type": null }, { "param": "stitch_queue", "type": null }, { "param": "raster_id_to_global_stitch_path_map", "type": null } ]
{ "returns": [ { "docstring": "None when 'STOP' comes through the stitch queue.", "docstring_tokens": [ "None", "when", "'", "STOP", "'", "comes", "through", "the", "stitch", "queue", "." ], "type": nul...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
create_status_database
null
def create_status_database(database_path): """Create a runtime status database if it doesn't exist. Parameters: database_path (str): path to database to create. raster_id_list (list): list of raster id strings that will be monitored for completion. country_id_list (li...
Create a runtime status database if it doesn't exist. Parameters: database_path (str): path to database to create. raster_id_list (list): list of raster id strings that will be monitored for completion. country_id_list (list): list of country ids to pair with the rasters. ...
Create a runtime status database if it doesn't exist.
[ "Create", "a", "runtime", "status", "database", "if", "it", "doesn", "'", "t", "exist", "." ]
def create_status_database(database_path): LOGGER.debug('launching create_status_database') create_database_sql = ( """ CREATE TABLE job_status ( raster_id TEXT NOT NULL, aggregate_vector_id TEXT NOT NULL, fieldname_id TEXT NOT NULL, feature_id TEX...
[ "def", "create_status_database", "(", "database_path", ")", ":", "LOGGER", ".", "debug", "(", "'launching create_status_database'", ")", "create_database_sql", "=", "(", "\"\"\"\r\n CREATE TABLE job_status (\r\n raster_id TEXT NOT NULL,\r\n aggregate_vector...
Create a runtime status database if it doesn't exist.
[ "Create", "a", "runtime", "status", "database", "if", "it", "doesn", "'", "t", "exist", "." ]
[ "\"\"\"Create a runtime status database if it doesn't exist.\r\n\r\n Parameters:\r\n database_path (str): path to database to create.\r\n raster_id_list (list): list of raster id strings that will be monitored\r\n for completion.\r\n country_id_list (list): list of country ids to ...
[ { "param": "database_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "database_path", "type": null, "docstring": "path to database to create.", "docstring_tokens": [ "path", ...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
extract_feature_checked
<not_specific>
def extract_feature_checked( align_lock, vector_path, field_name, field_value, base_raster_path, target_vector_path, target_raster_path): """Extract single feature into separate vector and check for no error. Do not do a transform since it's all wgs84. Parameters: align_loc...
Extract single feature into separate vector and check for no error. Do not do a transform since it's all wgs84. Parameters: align_lock (multiprocessing.Lock): lock to only allow one align at a time. vector_path (str): base vector in WGS84 coordinates. field_name (st...
Extract single feature into separate vector and check for no error. Do not do a transform since it's all wgs84.
[ "Extract", "single", "feature", "into", "separate", "vector", "and", "check", "for", "no", "error", ".", "Do", "not", "do", "a", "transform", "since", "it", "'", "s", "all", "wgs84", "." ]
def extract_feature_checked( align_lock, vector_path, field_name, field_value, base_raster_path, target_vector_path, target_raster_path): attempt_number = 0 if not os.path.exists(base_raster_path): raise ValueError("%s does not exist" % base_raster_path) while True: try: ...
[ "def", "extract_feature_checked", "(", "align_lock", ",", "vector_path", ",", "field_name", ",", "field_value", ",", "base_raster_path", ",", "target_vector_path", ",", "target_raster_path", ")", ":", "attempt_number", "=", "0", "if", "not", "os", ".", "path", "."...
Extract single feature into separate vector and check for no error.
[ "Extract", "single", "feature", "into", "separate", "vector", "and", "check", "for", "no", "error", "." ]
[ "\"\"\"Extract single feature into separate vector and check for no error.\r\n\r\n Do not do a transform since it's all wgs84.\r\n\r\n Parameters:\r\n align_lock (multiprocessing.Lock): lock to only allow one align at\r\n a time.\r\n vector_path (str): base vector in WGS84 coordinates...
[ { "param": "align_lock", "type": null }, { "param": "vector_path", "type": null }, { "param": "field_name", "type": null }, { "param": "field_value", "type": null }, { "param": "base_raster_path", "type": null }, { "param": "target_vector_path", "t...
{ "returns": [ { "docstring": "True if no error, False otherwise.", "docstring_tokens": [ "True", "if", "no", "error", "False", "otherwise", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "align...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
calculate_cdf
<not_specific>
def calculate_cdf(raster_path, percentile_list): """Calculate the CDF given its percentile list.""" cdf_array = [0.0] * len(percentile_list) nodata = pygeoprocessing.get_raster_info( raster_path)['nodata'][0] pixel_count = 0 for _, data_block in pygeoprocessing.iterblocks( ...
Calculate the CDF given its percentile list.
Calculate the CDF given its percentile list.
[ "Calculate", "the", "CDF", "given", "its", "percentile", "list", "." ]
def calculate_cdf(raster_path, percentile_list): cdf_array = [0.0] * len(percentile_list) nodata = pygeoprocessing.get_raster_info( raster_path)['nodata'][0] pixel_count = 0 for _, data_block in pygeoprocessing.iterblocks( (raster_path, 1)): nodata_mask = ~numpy.isclose(data_...
[ "def", "calculate_cdf", "(", "raster_path", ",", "percentile_list", ")", ":", "cdf_array", "=", "[", "0.0", "]", "*", "len", "(", "percentile_list", ")", "nodata", "=", "pygeoprocessing", ".", "get_raster_info", "(", "raster_path", ")", "[", "'nodata'", "]", ...
Calculate the CDF given its percentile list.
[ "Calculate", "the", "CDF", "given", "its", "percentile", "list", "." ]
[ "\"\"\"Calculate the CDF given its percentile list.\"\"\"" ]
[ { "param": "raster_path", "type": null }, { "param": "percentile_list", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "raster_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "percentile_list", "type": null, "docstring": null, "do...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
stitch_raster
null
def stitch_raster( lock_map, cpu_semaphore, payload, raster_id_to_global_stitch_path_map): """Stitch incoming country rasters into global raster. Parameters: lock_map (dict): maps global raster paths to locks so we don't cpu_semaphore (BoundedSemaphore): release this when stitch i...
Stitch incoming country rasters into global raster. Parameters: lock_map (dict): maps global raster paths to locks so we don't cpu_semaphore (BoundedSemaphore): release this when stitch is done payload (tuple): payloads come in as an alert that a sub raster is ready for st...
Stitch incoming country rasters into global raster.
[ "Stitch", "incoming", "country", "rasters", "into", "global", "raster", "." ]
def stitch_raster( lock_map, cpu_semaphore, payload, raster_id_to_global_stitch_path_map): local_tile_raster_path, raster_aggregate_nodata_id_tuple = payload global_stitch_raster_path = raster_id_to_global_stitch_path_map[ raster_aggregate_nodata_id_tuple] local_tile_info = pygeoprocessing.g...
[ "def", "stitch_raster", "(", "lock_map", ",", "cpu_semaphore", ",", "payload", ",", "raster_id_to_global_stitch_path_map", ")", ":", "local_tile_raster_path", ",", "raster_aggregate_nodata_id_tuple", "=", "payload", "global_stitch_raster_path", "=", "raster_id_to_global_stitch_...
Stitch incoming country rasters into global raster.
[ "Stitch", "incoming", "country", "rasters", "into", "global", "raster", "." ]
[ "\"\"\"Stitch incoming country rasters into global raster.\r\n\r\n Parameters:\r\n lock_map (dict): maps global raster paths to locks so we don't\r\n cpu_semaphore (BoundedSemaphore): release this when stitch is done\r\n payload (tuple): payloads come in as an alert that a sub raster\r\n ...
[ { "param": "lock_map", "type": null }, { "param": "cpu_semaphore", "type": null }, { "param": "payload", "type": null }, { "param": "raster_id_to_global_stitch_path_map", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lock_map", "type": null, "docstring": "maps global raster paths to locks so we don't", "docstring_tokens": [ "maps", "global", "raster", "paths", "to", "locks", "so", ...
e3d83cc9dc150f8d8d3f392da65caeb856faa694
richpsharp/raster_calculations
cumulative_density_function_per_country.py
[ "Apache-2.0" ]
Python
new_raster_from_base
null
def new_raster_from_base( base_raster, target_base_id, target_dir, target_datatype, target_nodata): """Create a new raster from base given the base id. This function is to make the function signature look different for each run. Parameters: base_raster, target_base_id,...
Create a new raster from base given the base id. This function is to make the function signature look different for each run. Parameters: base_raster, target_base_id, target_dir, target_datatype, target_nodata are the same as pygeoprocessing.new_raster_from_base. Returns: ...
Create a new raster from base given the base id. This function is to make the function signature look different for each run. None.
[ "Create", "a", "new", "raster", "from", "base", "given", "the", "base", "id", ".", "This", "function", "is", "to", "make", "the", "function", "signature", "look", "different", "for", "each", "run", ".", "None", "." ]
def new_raster_from_base( base_raster, target_base_id, target_dir, target_datatype, target_nodata): target_raster_path = os.path.join(target_dir, '%s.tif' % target_base_id) LOGGER.debug('making new raster %s', target_raster_path) pygeoprocessing.new_raster_from_base( base_raster, tar...
[ "def", "new_raster_from_base", "(", "base_raster", ",", "target_base_id", ",", "target_dir", ",", "target_datatype", ",", "target_nodata", ")", ":", "target_raster_path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'%s.tif'", "%", "target_base_id...
Create a new raster from base given the base id.
[ "Create", "a", "new", "raster", "from", "base", "given", "the", "base", "id", "." ]
[ "\"\"\"Create a new raster from base given the base id.\r\n\r\n This function is to make the function signature look different for each\r\n run.\r\n\r\n Parameters:\r\n base_raster, target_base_id, target_dir, target_datatype,\r\n target_nodata are the same as pygeoprocessing.new_raster_from_...
[ { "param": "base_raster", "type": null }, { "param": "target_base_id", "type": null }, { "param": "target_dir", "type": null }, { "param": "target_datatype", "type": null }, { "param": "target_nodata", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_raster", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "target_base_id", "type": null, "docstring": null, "doc...
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
mask_by_value_op
<not_specific>
def mask_by_value_op(array, value, nodata): """Return 1 where array==value 0 otherwise.""" result = numpy.empty_like(array) result[:] = 0 result[array == value] = 1 result[numpy.isclose(array, nodata)] = 2 return result
Return 1 where array==value 0 otherwise.
Return 1 where array==value 0 otherwise.
[ "Return", "1", "where", "array", "==", "value", "0", "otherwise", "." ]
def mask_by_value_op(array, value, nodata): result = numpy.empty_like(array) result[:] = 0 result[array == value] = 1 result[numpy.isclose(array, nodata)] = 2 return result
[ "def", "mask_by_value_op", "(", "array", ",", "value", ",", "nodata", ")", ":", "result", "=", "numpy", ".", "empty_like", "(", "array", ")", "result", "[", ":", "]", "=", "0", "result", "[", "array", "==", "value", "]", "=", "1", "result", "[", "n...
Return 1 where array==value 0 otherwise.
[ "Return", "1", "where", "array", "==", "value", "0", "otherwise", "." ]
[ "\"\"\"Return 1 where array==value 0 otherwise.\"\"\"" ]
[ { "param": "array", "type": null }, { "param": "value", "type": null }, { "param": "nodata", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": null, "docstring": null, "docstring_tokens":...
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
mask_by_inv_value_op
<not_specific>
def mask_by_inv_value_op(array, value, nodata): """Return 0 where array==value 1 otherwise.""" result = numpy.empty_like(array) result[:] = 0 result[array != value] = 1 result[numpy.isclose(array, nodata)] = 2 return result
Return 0 where array==value 1 otherwise.
Return 0 where array==value 1 otherwise.
[ "Return", "0", "where", "array", "==", "value", "1", "otherwise", "." ]
def mask_by_inv_value_op(array, value, nodata): result = numpy.empty_like(array) result[:] = 0 result[array != value] = 1 result[numpy.isclose(array, nodata)] = 2 return result
[ "def", "mask_by_inv_value_op", "(", "array", ",", "value", ",", "nodata", ")", ":", "result", "=", "numpy", ".", "empty_like", "(", "array", ")", "result", "[", ":", "]", "=", "0", "result", "[", "array", "!=", "value", "]", "=", "1", "result", "[", ...
Return 0 where array==value 1 otherwise.
[ "Return", "0", "where", "array", "==", "value", "1", "otherwise", "." ]
[ "\"\"\"Return 0 where array==value 1 otherwise.\"\"\"" ]
[ { "param": "array", "type": null }, { "param": "value", "type": null }, { "param": "nodata", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": null, "docstring": null, "docstring_tokens":...
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
download_and_unzip
null
def download_and_unzip(base_url, target_dir, done_token_path): """Download and unzip base_url to target_dir and write done token path.""" path_to_zip_file = os.path.join(target_dir, os.path.basename(base_url)) ecoshard.download_url( base_url, path_to_zip_file, skip_if_target_exists=False) zip_re...
Download and unzip base_url to target_dir and write done token path.
Download and unzip base_url to target_dir and write done token path.
[ "Download", "and", "unzip", "base_url", "to", "target_dir", "and", "write", "done", "token", "path", "." ]
def download_and_unzip(base_url, target_dir, done_token_path): path_to_zip_file = os.path.join(target_dir, os.path.basename(base_url)) ecoshard.download_url( base_url, path_to_zip_file, skip_if_target_exists=False) zip_ref = zipfile.ZipFile(path_to_zip_file, 'r') zip_ref.extractall(target_dir) ...
[ "def", "download_and_unzip", "(", "base_url", ",", "target_dir", ",", "done_token_path", ")", ":", "path_to_zip_file", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "os", ".", "path", ".", "basename", "(", "base_url", ")", ")", "ecoshard", "...
Download and unzip base_url to target_dir and write done token path.
[ "Download", "and", "unzip", "base_url", "to", "target_dir", "and", "write", "done", "token", "path", "." ]
[ "\"\"\"Download and unzip base_url to target_dir and write done token path.\"\"\"" ]
[ { "param": "base_url", "type": null }, { "param": "target_dir", "type": null }, { "param": "done_token_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "base_url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "target_dir", "type": null, "docstring": null, "docstring_...
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
length_of_degree
<not_specific>
def length_of_degree(lat): """Calculate the length of a degree in meters.""" m1 = 111132.92 m2 = -559.82 m3 = 1.175 m4 = -0.0023 p1 = 111412.84 p2 = -93.5 p3 = 0.118 lat_rad = lat * numpy.pi / 180 latlen = ( m1 + m2 * numpy.cos(2 * lat_rad) + m3 * numpy.cos(4 * lat_rad) +...
Calculate the length of a degree in meters.
Calculate the length of a degree in meters.
[ "Calculate", "the", "length", "of", "a", "degree", "in", "meters", "." ]
def length_of_degree(lat): m1 = 111132.92 m2 = -559.82 m3 = 1.175 m4 = -0.0023 p1 = 111412.84 p2 = -93.5 p3 = 0.118 lat_rad = lat * numpy.pi / 180 latlen = ( m1 + m2 * numpy.cos(2 * lat_rad) + m3 * numpy.cos(4 * lat_rad) + m4 * numpy.cos(6 * lat_rad)) longlen = ab...
[ "def", "length_of_degree", "(", "lat", ")", ":", "m1", "=", "111132.92", "m2", "=", "-", "559.82", "m3", "=", "1.175", "m4", "=", "-", "0.0023", "p1", "=", "111412.84", "p2", "=", "-", "93.5", "p3", "=", "0.118", "lat_rad", "=", "lat", "*", "numpy"...
Calculate the length of a degree in meters.
[ "Calculate", "the", "length", "of", "a", "degree", "in", "meters", "." ]
[ "\"\"\"Calculate the length of a degree in meters.\"\"\"" ]
[ { "param": "lat", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lat", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
hat_distance_kernel
null
def hat_distance_kernel(pixel_radius, kernel_filepath): """Create a raster-based 0, 1 kernel path. Parameters: pixel_radius (int): Radius of the kernel in pixels. kernel_filepath (string): The path to the file on disk where this kernel should be stored. If this file exists, it will...
Create a raster-based 0, 1 kernel path. Parameters: pixel_radius (int): Radius of the kernel in pixels. kernel_filepath (string): The path to the file on disk where this kernel should be stored. If this file exists, it will be overwritten. Returns: None
Create a raster-based 0, 1 kernel path.
[ "Create", "a", "raster", "-", "based", "0", "1", "kernel", "path", "." ]
def hat_distance_kernel(pixel_radius, kernel_filepath): kernel_size = int((pixel_radius)*2+1) driver = gdal.GetDriverByName('GTiff') kernel_dataset = driver.Create( kernel_filepath.encode('utf-8'), kernel_size, kernel_size, 1, gdal.GDT_Float32, options=[ 'BIGTIFF=IF_SAFER', 'TILE...
[ "def", "hat_distance_kernel", "(", "pixel_radius", ",", "kernel_filepath", ")", ":", "kernel_size", "=", "int", "(", "(", "pixel_radius", ")", "*", "2", "+", "1", ")", "driver", "=", "gdal", ".", "GetDriverByName", "(", "'GTiff'", ")", "kernel_dataset", "=",...
Create a raster-based 0, 1 kernel path.
[ "Create", "a", "raster", "-", "based", "0", "1", "kernel", "path", "." ]
[ "\"\"\"Create a raster-based 0, 1 kernel path.\n\n Parameters:\n pixel_radius (int): Radius of the kernel in pixels.\n kernel_filepath (string): The path to the file on disk where this\n kernel should be stored. If this file exists, it will be\n overwritten.\n\n Returns:\n...
[ { "param": "pixel_radius", "type": null }, { "param": "kernel_filepath", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "pixel_radius", "type": null, "docstring": "Radius of the kernel in pixels.", "docstring_tokens": [ "Radius"...
4d03ab4a1b84ae7ad11fc041084a5f12f929d0d7
richpsharp/raster_calculations
raster_stream_buffer.py
[ "Apache-2.0" ]
Python
linear_decay_kernel
null
def linear_decay_kernel(pixel_radius, kernel_filepath): """Create a raster-based linear decay kernel path. Parameters: pixel_radius (int): Radius of the kernel in pixels. kernel_filepath (string): The path to the file on disk where this kernel should be stored. If this file exists,...
Create a raster-based linear decay kernel path. Parameters: pixel_radius (int): Radius of the kernel in pixels. kernel_filepath (string): The path to the file on disk where this kernel should be stored. If this file exists, it will be overwritten. Returns: None...
Create a raster-based linear decay kernel path.
[ "Create", "a", "raster", "-", "based", "linear", "decay", "kernel", "path", "." ]
def linear_decay_kernel(pixel_radius, kernel_filepath): kernel_size = int((pixel_radius)*2+1) driver = gdal.GetDriverByName('GTiff') kernel_dataset = driver.Create( kernel_filepath.encode('utf-8'), kernel_size, kernel_size, 1, gdal.GDT_Float32, options=[ 'BIGTIFF=IF_SAFER', 'TILE...
[ "def", "linear_decay_kernel", "(", "pixel_radius", ",", "kernel_filepath", ")", ":", "kernel_size", "=", "int", "(", "(", "pixel_radius", ")", "*", "2", "+", "1", ")", "driver", "=", "gdal", ".", "GetDriverByName", "(", "'GTiff'", ")", "kernel_dataset", "=",...
Create a raster-based linear decay kernel path.
[ "Create", "a", "raster", "-", "based", "linear", "decay", "kernel", "path", "." ]
[ "\"\"\"Create a raster-based linear decay kernel path.\n\n Parameters:\n pixel_radius (int): Radius of the kernel in pixels.\n kernel_filepath (string): The path to the file on disk where this\n kernel should be stored. If this file exists, it will be\n overwritten.\n\n Re...
[ { "param": "pixel_radius", "type": null }, { "param": "kernel_filepath", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "pixel_radius", "type": null, "docstring": "Radius of the kernel in pixels.", "docstring_tokens": [ "Radius"...
5c5bed94245fbd6c5cf80444cb8da625da8ae87f
richpsharp/raster_calculations
area_of_mask.py
[ "Apache-2.0" ]
Python
mask_op
<not_specific>
def mask_op(mask_array, value_array): """Mask out value to 0 if mask array is not 1.""" result = numpy.copy(value_array) result[mask_array != 1] = 0.0 return result
Mask out value to 0 if mask array is not 1.
Mask out value to 0 if mask array is not 1.
[ "Mask", "out", "value", "to", "0", "if", "mask", "array", "is", "not", "1", "." ]
def mask_op(mask_array, value_array): result = numpy.copy(value_array) result[mask_array != 1] = 0.0 return result
[ "def", "mask_op", "(", "mask_array", ",", "value_array", ")", ":", "result", "=", "numpy", ".", "copy", "(", "value_array", ")", "result", "[", "mask_array", "!=", "1", "]", "=", "0.0", "return", "result" ]
Mask out value to 0 if mask array is not 1.
[ "Mask", "out", "value", "to", "0", "if", "mask", "array", "is", "not", "1", "." ]
[ "\"\"\"Mask out value to 0 if mask array is not 1.\"\"\"" ]
[ { "param": "mask_array", "type": null }, { "param": "value_array", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "mask_array", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value_array", "type": null, "docstring": null, "docstri...
b634e23b2d93a2130b57a94a567594e422b075b8
TsVV/Robinzon-problem
robinzon_env.py
[ "MIT" ]
Python
_get_reward
<not_specific>
def _get_reward(self): """ Reward is given for scoring a goal. """ if self.alive: if (self.boat == 0): return 100 elif (self.res_water >= 0): #and (self.res_food >= 0): return 1 else: return -1 else: ...
Reward is given for scoring a goal.
Reward is given for scoring a goal.
[ "Reward", "is", "given", "for", "scoring", "a", "goal", "." ]
def _get_reward(self): if self.alive: if (self.boat == 0): return 100 elif (self.res_water >= 0): return 1 else: return -1 else: return -1000
[ "def", "_get_reward", "(", "self", ")", ":", "if", "self", ".", "alive", ":", "if", "(", "self", ".", "boat", "==", "0", ")", ":", "return", "100", "elif", "(", "self", ".", "res_water", ">=", "0", ")", ":", "return", "1", "else", ":", "return", ...
Reward is given for scoring a goal.
[ "Reward", "is", "given", "for", "scoring", "a", "goal", "." ]
[ "\"\"\" Reward is given for scoring a goal. \"\"\"", "#and (self.res_food >= 0):" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e8c54d42b1dcdc79b5243b987d9d7d64f9c81405
ZeroIntensity/RoboCollab
api/schemas/collab.py
[ "MIT" ]
Python
save
str
def save(doc: Document, *args, **kwargs) -> str: """Function for commiting the collab.""" return Schema.save( doc, collabs, unhashed = list(doc.keys()), force = ['server'], *args, **kwargs )
Function for commiting the collab.
Function for commiting the collab.
[ "Function", "for", "commiting", "the", "collab", "." ]
def save(doc: Document, *args, **kwargs) -> str: return Schema.save( doc, collabs, unhashed = list(doc.keys()), force = ['server'], *args, **kwargs )
[ "def", "save", "(", "doc", ":", "Document", ",", "*", "args", ",", "**", "kwargs", ")", "->", "str", ":", "return", "Schema", ".", "save", "(", "doc", ",", "collabs", ",", "unhashed", "=", "list", "(", "doc", ".", "keys", "(", ")", ")", ",", "f...
Function for commiting the collab.
[ "Function", "for", "commiting", "the", "collab", "." ]
[ "\"\"\"Function for commiting the collab.\"\"\"" ]
[ { "param": "doc", "type": "Document" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "doc", "type": "Document", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e8c54d42b1dcdc79b5243b987d9d7d64f9c81405
ZeroIntensity/RoboCollab
api/schemas/collab.py
[ "MIT" ]
Python
collab_from
Collab
def collab_from(query: Union[CollabModel, CollabQuery]) -> Collab: """Function for getting a Collab object based on a query.""" q = dict(query) if not BaseCollab.exists(q): raise ValueError('Collab does not exist.') doc: Document = BaseCollab.find(q, unhash = True, remove_id = True) ...
Function for getting a Collab object based on a query.
Function for getting a Collab object based on a query.
[ "Function", "for", "getting", "a", "Collab", "object", "based", "on", "a", "query", "." ]
def collab_from(query: Union[CollabModel, CollabQuery]) -> Collab: q = dict(query) if not BaseCollab.exists(q): raise ValueError('Collab does not exist.') doc: Document = BaseCollab.find(q, unhash = True, remove_id = True) return Collab(**doc, create = False)
[ "def", "collab_from", "(", "query", ":", "Union", "[", "CollabModel", ",", "CollabQuery", "]", ")", "->", "Collab", ":", "q", "=", "dict", "(", "query", ")", "if", "not", "BaseCollab", ".", "exists", "(", "q", ")", ":", "raise", "ValueError", "(", "'...
Function for getting a Collab object based on a query.
[ "Function", "for", "getting", "a", "Collab", "object", "based", "on", "a", "query", "." ]
[ "\"\"\"Function for getting a Collab object based on a query.\"\"\"" ]
[ { "param": "query", "type": "Union[CollabModel, CollabQuery]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "query", "type": "Union[CollabModel, CollabQuery]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
dbe1c3562bbbcc15301124e50585391706f2b533
ZeroIntensity/RoboCollab
api/utils/response.py
[ "MIT" ]
Python
response
JSONResponse
def response(message: Any, status: int = 200, extra: dict = {}, bot_message = '') -> JSONResponse: """Function for generating a server response.""" resp: dict = { 'message': message, 'botmessage': bot_message or message, 'status': status, } resp.update(extra) retu...
Function for generating a server response.
Function for generating a server response.
[ "Function", "for", "generating", "a", "server", "response", "." ]
def response(message: Any, status: int = 200, extra: dict = {}, bot_message = '') -> JSONResponse: resp: dict = { 'message': message, 'botmessage': bot_message or message, 'status': status, } resp.update(extra) return JSONResponse(resp, status_code = status)
[ "def", "response", "(", "message", ":", "Any", ",", "status", ":", "int", "=", "200", ",", "extra", ":", "dict", "=", "{", "}", ",", "bot_message", "=", "''", ")", "->", "JSONResponse", ":", "resp", ":", "dict", "=", "{", "'message'", ":", "message...
Function for generating a server response.
[ "Function", "for", "generating", "a", "server", "response", "." ]
[ "\"\"\"Function for generating a server response.\"\"\"" ]
[ { "param": "message", "type": "Any" }, { "param": "status", "type": "int" }, { "param": "extra", "type": "dict" }, { "param": "bot_message", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "message", "type": "Any", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "status", "type": "int", "docstring": null, "docstring_tok...
645c64cda71c7f30c10d67161ff6f3060ffbad67
ZeroIntensity/RoboCollab
api/utils/capitalize.py
[ "MIT" ]
Python
capitalize
<not_specific>
def capitalize(data: str): """Function for capitalizing the input string.""" # zero!!!111! why not just use str.capitalize!!!! # something like "hard demon".capitalize() returns "Hard demon", while this function returns "Hard Demon" resp: str = '' for i in data.split(' '): resp += ...
Function for capitalizing the input string.
Function for capitalizing the input string.
[ "Function", "for", "capitalizing", "the", "input", "string", "." ]
def capitalize(data: str): resp: str = '' for i in data.split(' '): resp += i[0].upper() + i[1:] + ' ' return resp[:-1]
[ "def", "capitalize", "(", "data", ":", "str", ")", ":", "resp", ":", "str", "=", "''", "for", "i", "in", "data", ".", "split", "(", "' '", ")", ":", "resp", "+=", "i", "[", "0", "]", ".", "upper", "(", ")", "+", "i", "[", "1", ":", "]", "...
Function for capitalizing the input string.
[ "Function", "for", "capitalizing", "the", "input", "string", "." ]
[ "\"\"\"Function for capitalizing the input string.\"\"\"", "# zero!!!111! why not just use str.capitalize!!!!\r", "# something like \"hard demon\".capitalize() returns \"Hard demon\", while this function returns \"Hard Demon\"\r" ]
[ { "param": "data", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5217cc1d1fe4fe8b50a0ed03c59b5c2c7cd8e7a1
ZeroIntensity/RoboCollab
api/schemas/schema_base.py
[ "MIT" ]
Python
find
Union[Any, None]
def find( cls, data_filter: Document, ignore: List[str] = [], hashed: List[str] = [], collection: MongoCollection = None, unhash: bool = False, remove_id: bool = False ) -> Union[Any, None]: """Function for performing a database query on...
Function for performing a database query on a collab.
Function for performing a database query on a collab.
[ "Function", "for", "performing", "a", "database", "query", "on", "a", "collab", "." ]
def find( cls, data_filter: Document, ignore: List[str] = [], hashed: List[str] = [], collection: MongoCollection = None, unhash: bool = False, remove_id: bool = False ) -> Union[Any, None]: c = cls.collection or collection q = cls.valida...
[ "def", "find", "(", "cls", ",", "data_filter", ":", "Document", ",", "ignore", ":", "List", "[", "str", "]", "=", "[", "]", ",", "hashed", ":", "List", "[", "str", "]", "=", "[", "]", ",", "collection", ":", "MongoCollection", "=", "None", ",", "...
Function for performing a database query on a collab.
[ "Function", "for", "performing", "a", "database", "query", "on", "a", "collab", "." ]
[ "\"\"\"Function for performing a database query on a collab.\"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "data_filter", "type": "Document" }, { "param": "ignore", "type": "List[str]" }, { "param": "hashed", "type": "List[str]" }, { "param": "collection", "type": "MongoCollection" }, { "param": "unhash", "ty...
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data_filter", "type": "Document", "docstring": null, "docstrin...
5217cc1d1fe4fe8b50a0ed03c59b5c2c7cd8e7a1
ZeroIntensity/RoboCollab
api/schemas/schema_base.py
[ "MIT" ]
Python
exists
bool
def exists(cls, doc: Document, ignore: list = [], hashed: list = [], collection: MongoCollection = None) -> bool: """Function for checking if a document exists.""" c = cls.collection or collection q = cls.validate_query(doc, ignore, hashed) return bool(c.find_one(q))
Function for checking if a document exists.
Function for checking if a document exists.
[ "Function", "for", "checking", "if", "a", "document", "exists", "." ]
def exists(cls, doc: Document, ignore: list = [], hashed: list = [], collection: MongoCollection = None) -> bool: c = cls.collection or collection q = cls.validate_query(doc, ignore, hashed) return bool(c.find_one(q))
[ "def", "exists", "(", "cls", ",", "doc", ":", "Document", ",", "ignore", ":", "list", "=", "[", "]", ",", "hashed", ":", "list", "=", "[", "]", ",", "collection", ":", "MongoCollection", "=", "None", ")", "->", "bool", ":", "c", "=", "cls", ".", ...
Function for checking if a document exists.
[ "Function", "for", "checking", "if", "a", "document", "exists", "." ]
[ "\"\"\"Function for checking if a document exists.\"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "doc", "type": "Document" }, { "param": "ignore", "type": "list" }, { "param": "hashed", "type": "list" }, { "param": "collection", "type": "MongoCollection" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "doc", "type": "Document", "docstring": null, "docstring_tokens...
5217cc1d1fe4fe8b50a0ed03c59b5c2c7cd8e7a1
ZeroIntensity/RoboCollab
api/schemas/schema_base.py
[ "MIT" ]
Python
delete
None
def delete(cls, data_filter: Document, collection: MongoCollection = None) -> None: """Function for deleting a document.""" c = cls.collection or collection c.delete_one(data_filter)
Function for deleting a document.
Function for deleting a document.
[ "Function", "for", "deleting", "a", "document", "." ]
def delete(cls, data_filter: Document, collection: MongoCollection = None) -> None: c = cls.collection or collection c.delete_one(data_filter)
[ "def", "delete", "(", "cls", ",", "data_filter", ":", "Document", ",", "collection", ":", "MongoCollection", "=", "None", ")", "->", "None", ":", "c", "=", "cls", ".", "collection", "or", "collection", "c", ".", "delete_one", "(", "data_filter", ")" ]
Function for deleting a document.
[ "Function", "for", "deleting", "a", "document", "." ]
[ "\"\"\"Function for deleting a document.\"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "data_filter", "type": "Document" }, { "param": "collection", "type": "MongoCollection" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data_filter", "type": "Document", "docstring": null, "docstrin...
5217cc1d1fe4fe8b50a0ed03c59b5c2c7cd8e7a1
ZeroIntensity/RoboCollab
api/schemas/schema_base.py
[ "MIT" ]
Python
delete_many
None
def delete_many(cls, data_filter: Document, collection: MongoCollection = None) -> None: """Function for deleting multiple documents.""" c = cls.collection or collection c.delete_many(data_filter)
Function for deleting multiple documents.
Function for deleting multiple documents.
[ "Function", "for", "deleting", "multiple", "documents", "." ]
def delete_many(cls, data_filter: Document, collection: MongoCollection = None) -> None: c = cls.collection or collection c.delete_many(data_filter)
[ "def", "delete_many", "(", "cls", ",", "data_filter", ":", "Document", ",", "collection", ":", "MongoCollection", "=", "None", ")", "->", "None", ":", "c", "=", "cls", ".", "collection", "or", "collection", "c", ".", "delete_many", "(", "data_filter", ")" ...
Function for deleting multiple documents.
[ "Function", "for", "deleting", "multiple", "documents", "." ]
[ "\"\"\"Function for deleting multiple documents.\"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "data_filter", "type": "Document" }, { "param": "collection", "type": "MongoCollection" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data_filter", "type": "Document", "docstring": null, "docstrin...
5217cc1d1fe4fe8b50a0ed03c59b5c2c7cd8e7a1
ZeroIntensity/RoboCollab
api/schemas/schema_base.py
[ "MIT" ]
Python
push
None
def push(cls, data_filter: Document, key: Any, value: Any, collection: MongoCollection = None) -> None: """Function for pushing to a document.""" c = cls.collection or collection c.update(data_filter, {'$push': {key: value}})
Function for pushing to a document.
Function for pushing to a document.
[ "Function", "for", "pushing", "to", "a", "document", "." ]
def push(cls, data_filter: Document, key: Any, value: Any, collection: MongoCollection = None) -> None: c = cls.collection or collection c.update(data_filter, {'$push': {key: value}})
[ "def", "push", "(", "cls", ",", "data_filter", ":", "Document", ",", "key", ":", "Any", ",", "value", ":", "Any", ",", "collection", ":", "MongoCollection", "=", "None", ")", "->", "None", ":", "c", "=", "cls", ".", "collection", "or", "collection", ...
Function for pushing to a document.
[ "Function", "for", "pushing", "to", "a", "document", "." ]
[ "\"\"\"Function for pushing to a document.\"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "data_filter", "type": "Document" }, { "param": "key", "type": "Any" }, { "param": "value", "type": "Any" }, { "param": "collection", "type": "MongoCollection" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data_filter", "type": "Document", "docstring": null, "docstrin...
26eee65166a16f4c4e6f97af6773e7e67163e966
ZeroIntensity/RoboCollab
api/utils/encrypt.py
[ "MIT" ]
Python
validate_argon2
bool
def validate_argon2(encrypted_str: str, data: str) -> bool: """Function for validating an argon2 hash.""" try: return h.verify(encrypted_str, encrypt(data)) except VerifyMismatchError: return False
Function for validating an argon2 hash.
Function for validating an argon2 hash.
[ "Function", "for", "validating", "an", "argon2", "hash", "." ]
def validate_argon2(encrypted_str: str, data: str) -> bool: try: return h.verify(encrypted_str, encrypt(data)) except VerifyMismatchError: return False
[ "def", "validate_argon2", "(", "encrypted_str", ":", "str", ",", "data", ":", "str", ")", "->", "bool", ":", "try", ":", "return", "h", ".", "verify", "(", "encrypted_str", ",", "encrypt", "(", "data", ")", ")", "except", "VerifyMismatchError", ":", "ret...
Function for validating an argon2 hash.
[ "Function", "for", "validating", "an", "argon2", "hash", "." ]
[ "\"\"\"Function for validating an argon2 hash.\"\"\"" ]
[ { "param": "encrypted_str", "type": "str" }, { "param": "data", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "encrypted_str", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": "str", "docstring": null, "docstring...
9b0ca9874a76f998da5036fdecafe8d7bc80a769
MutantPlatypus/wavedrompy
wavedrom/tspan.py
[ "MIT" ]
Python
extract_element
<not_specific>
def extract_element(self, e): """Extract AttrDict from jsonml This function non-recursively extracts an AttrDict from jsonml. This AttrDict has the three elements tagname, attributes and element_list according to the jsonml specification. :param e: element as jsonml list/tuple ...
Extract AttrDict from jsonml This function non-recursively extracts an AttrDict from jsonml. This AttrDict has the three elements tagname, attributes and element_list according to the jsonml specification. :param e: element as jsonml list/tuple :return: AttrDict
Extract AttrDict from jsonml This function non-recursively extracts an AttrDict from jsonml. This AttrDict has the three elements tagname, attributes and element_list according to the jsonml specification.
[ "Extract", "AttrDict", "from", "jsonml", "This", "function", "non", "-", "recursively", "extracts", "an", "AttrDict", "from", "jsonml", ".", "This", "AttrDict", "has", "the", "three", "elements", "tagname", "attributes", "and", "element_list", "according", "to", ...
def extract_element(self, e): if not isinstance(e, (list, tuple)): raise ValueError("JsonML must be a list") if len(e) == 0: raise ValueError("JsonML cannot be an empty list") if not isinstance(e[0], string_types): raise ValueError("JsonML tagname must be stri...
[ "def", "extract_element", "(", "self", ",", "e", ")", ":", "if", "not", "isinstance", "(", "e", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"JsonML must be a list\"", ")", "if", "len", "(", "e", ")", "==", "0", ":", ...
Extract AttrDict from jsonml This function non-recursively extracts an AttrDict from jsonml.
[ "Extract", "AttrDict", "from", "jsonml", "This", "function", "non", "-", "recursively", "extracts", "an", "AttrDict", "from", "jsonml", "." ]
[ "\"\"\"Extract AttrDict from jsonml\n\n This function non-recursively extracts an AttrDict from jsonml.\n This AttrDict has the three elements tagname, attributes and\n element_list according to the jsonml specification.\n\n :param e: element as jsonml list/tuple\n :return: AttrDi...
[ { "param": "self", "type": null }, { "param": "e", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
eb8bb118f9f83c7549dcc1f5992f2d26361f7ad7
spetrosi/storage
library/blivet.py
[ "MIT" ]
Python
_get_blivet_volume
<not_specific>
def _get_blivet_volume(blivet_obj, volume, bpool=None): """ Return a BlivetVolume instance appropriate for the volume dict. """ global volume_defaults volume_type = volume.get('type', bpool._pool['type'] if bpool else volume_defaults['type']) if volume_type not in _BLIVET_VOLUME_TYPES: raise Bli...
Return a BlivetVolume instance appropriate for the volume dict.
Return a BlivetVolume instance appropriate for the volume dict.
[ "Return", "a", "BlivetVolume", "instance", "appropriate", "for", "the", "volume", "dict", "." ]
def _get_blivet_volume(blivet_obj, volume, bpool=None): global volume_defaults volume_type = volume.get('type', bpool._pool['type'] if bpool else volume_defaults['type']) if volume_type not in _BLIVET_VOLUME_TYPES: raise BlivetAnsibleError("Volume '%s' has unknown type '%s'" % (volume['name'], volum...
[ "def", "_get_blivet_volume", "(", "blivet_obj", ",", "volume", ",", "bpool", "=", "None", ")", ":", "global", "volume_defaults", "volume_type", "=", "volume", ".", "get", "(", "'type'", ",", "bpool", ".", "_pool", "[", "'type'", "]", "if", "bpool", "else",...
Return a BlivetVolume instance appropriate for the volume dict.
[ "Return", "a", "BlivetVolume", "instance", "appropriate", "for", "the", "volume", "dict", "." ]
[ "\"\"\" Return a BlivetVolume instance appropriate for the volume dict. \"\"\"" ]
[ { "param": "blivet_obj", "type": null }, { "param": "volume", "type": null }, { "param": "bpool", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "blivet_obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "volume", "type": null, "docstring": null, "docstring_to...
eb8bb118f9f83c7549dcc1f5992f2d26361f7ad7
spetrosi/storage
library/blivet.py
[ "MIT" ]
Python
manage
<not_specific>
def manage(self): """ Schedule actions to configure this pool according to the yaml input. """ global safe_mode # look up the device self._look_up_disks() self._look_up_device() self._apply_defaults() # schedule destroy if appropriate, including member type chang...
Schedule actions to configure this pool according to the yaml input.
Schedule actions to configure this pool according to the yaml input.
[ "Schedule", "actions", "to", "configure", "this", "pool", "according", "to", "the", "yaml", "input", "." ]
def manage(self): global safe_mode self._look_up_disks() self._look_up_device() self._apply_defaults() if not self.ultimately_present: self._manage_volumes() self._destroy() return elif self._member_management_is_destructive(): ...
[ "def", "manage", "(", "self", ")", ":", "global", "safe_mode", "self", ".", "_look_up_disks", "(", ")", "self", ".", "_look_up_device", "(", ")", "self", ".", "_apply_defaults", "(", ")", "if", "not", "self", ".", "ultimately_present", ":", "self", ".", ...
Schedule actions to configure this pool according to the yaml input.
[ "Schedule", "actions", "to", "configure", "this", "pool", "according", "to", "the", "yaml", "input", "." ]
[ "\"\"\" Schedule actions to configure this pool according to the yaml input. \"\"\"", "# look up the device", "# schedule destroy if appropriate, including member type change", "# schedule create if appropriate" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
eb8bb118f9f83c7549dcc1f5992f2d26361f7ad7
spetrosi/storage
library/blivet.py
[ "MIT" ]
Python
_get_blivet_pool
<not_specific>
def _get_blivet_pool(blivet_obj, pool): """ Return an appropriate BlivetPool instance for the pool dict. """ if 'type' not in pool: global pool_defaults pool['type'] = pool_defaults['type'] if pool['type'] not in _BLIVET_POOL_TYPES: raise BlivetAnsibleError("Pool '%s' has unknown ty...
Return an appropriate BlivetPool instance for the pool dict.
Return an appropriate BlivetPool instance for the pool dict.
[ "Return", "an", "appropriate", "BlivetPool", "instance", "for", "the", "pool", "dict", "." ]
def _get_blivet_pool(blivet_obj, pool): if 'type' not in pool: global pool_defaults pool['type'] = pool_defaults['type'] if pool['type'] not in _BLIVET_POOL_TYPES: raise BlivetAnsibleError("Pool '%s' has unknown type '%s'" % (pool['name'], pool['type'])) return _BLIVET_POOL_TYPES[poo...
[ "def", "_get_blivet_pool", "(", "blivet_obj", ",", "pool", ")", ":", "if", "'type'", "not", "in", "pool", ":", "global", "pool_defaults", "pool", "[", "'type'", "]", "=", "pool_defaults", "[", "'type'", "]", "if", "pool", "[", "'type'", "]", "not", "in",...
Return an appropriate BlivetPool instance for the pool dict.
[ "Return", "an", "appropriate", "BlivetPool", "instance", "for", "the", "pool", "dict", "." ]
[ "\"\"\" Return an appropriate BlivetPool instance for the pool dict. \"\"\"" ]
[ { "param": "blivet_obj", "type": null }, { "param": "pool", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "blivet_obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pool", "type": null, "docstring": null, "docstring_toke...
8eaaefe0e235f1f767185e45aa364e9fc3f1a712
GateMartin/p3d_camera_controller
camera.py
[ "MIT" ]
Python
destroy
null
def destroy(self): """ Destroy the camera behaviour (it won't be usable anymore) """ self.disable() self._input_state.delete() del self
Destroy the camera behaviour (it won't be usable anymore)
Destroy the camera behaviour (it won't be usable anymore)
[ "Destroy", "the", "camera", "behaviour", "(", "it", "won", "'", "t", "be", "usable", "anymore", ")" ]
def destroy(self): self.disable() self._input_state.delete() del self
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "disable", "(", ")", "self", ".", "_input_state", ".", "delete", "(", ")", "del", "self" ]
Destroy the camera behaviour (it won't be usable anymore)
[ "Destroy", "the", "camera", "behaviour", "(", "it", "won", "'", "t", "be", "usable", "anymore", ")" ]
[ "\"\"\"\r\n Destroy the camera behaviour (it won't be usable anymore)\r\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8eaaefe0e235f1f767185e45aa364e9fc3f1a712
GateMartin/p3d_camera_controller
camera.py
[ "MIT" ]
Python
disable
null
def disable(self): """ Disable the camera behaviour. Note: the behaviour is still usable, you can use setup() in order to activate it again. """ # Remove camera task from the showbase task manager self._showbase.taskMgr.remove("UpdateCameraTask" + str(self._instance...
Disable the camera behaviour. Note: the behaviour is still usable, you can use setup() in order to activate it again.
Disable the camera behaviour. Note: the behaviour is still usable, you can use setup() in order to activate it again.
[ "Disable", "the", "camera", "behaviour", ".", "Note", ":", "the", "behaviour", "is", "still", "usable", "you", "can", "use", "setup", "()", "in", "order", "to", "activate", "it", "again", "." ]
def disable(self): self._showbase.taskMgr.remove("UpdateCameraTask" + str(self._instance)) props = WindowProperties() props.setCursorHidden(False) self._showbase.win.requestProperties(props)
[ "def", "disable", "(", "self", ")", ":", "self", ".", "_showbase", ".", "taskMgr", ".", "remove", "(", "\"UpdateCameraTask\"", "+", "str", "(", "self", ".", "_instance", ")", ")", "props", "=", "WindowProperties", "(", ")", "props", ".", "setCursorHidden",...
Disable the camera behaviour.
[ "Disable", "the", "camera", "behaviour", "." ]
[ "\"\"\"\r\n Disable the camera behaviour.\r\n Note: the behaviour is still usable, you can use setup() in order to activate it again.\r\n \"\"\"", "# Remove camera task from the showbase task manager\r", "# Show the mouse\r" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8eaaefe0e235f1f767185e45aa364e9fc3f1a712
GateMartin/p3d_camera_controller
camera.py
[ "MIT" ]
Python
update
<not_specific>
def update(self, task): """ Task to update camera's position and rotation based on inputs. """ dt = globalClock.getDt() # Getting mouse position md = self._showbase.win.getPointer(0) x = md.getX() y = md.getY() center_x = self._showb...
Task to update camera's position and rotation based on inputs.
Task to update camera's position and rotation based on inputs.
[ "Task", "to", "update", "camera", "'", "s", "position", "and", "rotation", "based", "on", "inputs", "." ]
def update(self, task): dt = globalClock.getDt() md = self._showbase.win.getPointer(0) x = md.getX() y = md.getY() center_x = self._showbase.win.getXSize() // 2 center_y = self._showbase.win.getYSize() // 2 if self._showbase.win.movePointer(0, center_x, center_y):...
[ "def", "update", "(", "self", ",", "task", ")", ":", "dt", "=", "globalClock", ".", "getDt", "(", ")", "md", "=", "self", ".", "_showbase", ".", "win", ".", "getPointer", "(", "0", ")", "x", "=", "md", ".", "getX", "(", ")", "y", "=", "md", "...
Task to update camera's position and rotation based on inputs.
[ "Task", "to", "update", "camera", "'", "s", "position", "and", "rotation", "based", "on", "inputs", "." ]
[ "\"\"\"\r\n Task to update camera's position and rotation based on inputs.\r\n \"\"\"", "# Getting mouse position\r", "# Set camera rotation based on mouse position\r", "# Setting camera position based on inputs \r" ]
[ { "param": "self", "type": null }, { "param": "task", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task", "type": null, "docstring": null, "docstring_tokens": [...
dccca74e68469767422a4aca05ddd9fcf4234b88
santiagoTena05/TC1001S.100-202211
Python/paint.py
[ "MIT" ]
Python
circle
null
def circle(start, end): "Draw circle from start to end." up() goto(start.x, start.y) down() begin_fill() turtle.circle(hypot(end.x - start.x, end.y - start.y)) end_fill()
Draw circle from start to end.
Draw circle from start to end.
[ "Draw", "circle", "from", "start", "to", "end", "." ]
def circle(start, end): up() goto(start.x, start.y) down() begin_fill() turtle.circle(hypot(end.x - start.x, end.y - start.y)) end_fill()
[ "def", "circle", "(", "start", ",", "end", ")", ":", "up", "(", ")", "goto", "(", "start", ".", "x", ",", "start", ".", "y", ")", "down", "(", ")", "begin_fill", "(", ")", "turtle", ".", "circle", "(", "hypot", "(", "end", ".", "x", "-", "sta...
Draw circle from start to end.
[ "Draw", "circle", "from", "start", "to", "end", "." ]
[ "\"Draw circle from start to end.\"" ]
[ { "param": "start", "type": null }, { "param": "end", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "start", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end", "type": null, "docstring": null, "docstring_tokens": [...
dccca74e68469767422a4aca05ddd9fcf4234b88
santiagoTena05/TC1001S.100-202211
Python/paint.py
[ "MIT" ]
Python
rectangle
null
def rectangle(start, end): "Draw rectangle from start to end." up() goto(start.x, start.y) down() begin_fill() for count in range(2): forward(end.x - start.x) left(90) forward(end.y - start.y) left(90) end_fill()
Draw rectangle from start to end.
Draw rectangle from start to end.
[ "Draw", "rectangle", "from", "start", "to", "end", "." ]
def rectangle(start, end): up() goto(start.x, start.y) down() begin_fill() for count in range(2): forward(end.x - start.x) left(90) forward(end.y - start.y) left(90) end_fill()
[ "def", "rectangle", "(", "start", ",", "end", ")", ":", "up", "(", ")", "goto", "(", "start", ".", "x", ",", "start", ".", "y", ")", "down", "(", ")", "begin_fill", "(", ")", "for", "count", "in", "range", "(", "2", ")", ":", "forward", "(", ...
Draw rectangle from start to end.
[ "Draw", "rectangle", "from", "start", "to", "end", "." ]
[ "\"Draw rectangle from start to end.\"" ]
[ { "param": "start", "type": null }, { "param": "end", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "start", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end", "type": null, "docstring": null, "docstring_tokens": [...
dccca74e68469767422a4aca05ddd9fcf4234b88
santiagoTena05/TC1001S.100-202211
Python/paint.py
[ "MIT" ]
Python
triangle
null
def triangle(start, end): "Draw triangle from start to end." up() goto(start.x, start.y) down() begin_fill() for count in range(3): forward(end.x - start.x) left(120) end_fill()
Draw triangle from start to end.
Draw triangle from start to end.
[ "Draw", "triangle", "from", "start", "to", "end", "." ]
def triangle(start, end): up() goto(start.x, start.y) down() begin_fill() for count in range(3): forward(end.x - start.x) left(120) end_fill()
[ "def", "triangle", "(", "start", ",", "end", ")", ":", "up", "(", ")", "goto", "(", "start", ".", "x", ",", "start", ".", "y", ")", "down", "(", ")", "begin_fill", "(", ")", "for", "count", "in", "range", "(", "3", ")", ":", "forward", "(", "...
Draw triangle from start to end.
[ "Draw", "triangle", "from", "start", "to", "end", "." ]
[ "\"Draw triangle from start to end.\"" ]
[ { "param": "start", "type": null }, { "param": "end", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "start", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end", "type": null, "docstring": null, "docstring_tokens": [...
345cab82299edf7d40102f076e12949aff7d3c5a
santiagoTena05/TC1001S.100-202211
Python/snake.py
[ "MIT" ]
Python
move_food
null
def move_food(): "Move food one step in a random direction" direction = randrange(1, 4) if direction == 1: food.x = food.x - 10 if not inside(food): food.x = food.x + 10 elif direction == 2: food.x = food.x + 10 if not inside(food): food.x = food.x...
Move food one step in a random direction
Move food one step in a random direction
[ "Move", "food", "one", "step", "in", "a", "random", "direction" ]
def move_food(): direction = randrange(1, 4) if direction == 1: food.x = food.x - 10 if not inside(food): food.x = food.x + 10 elif direction == 2: food.x = food.x + 10 if not inside(food): food.x = food.x - 10 elif direction == 3: food.y =...
[ "def", "move_food", "(", ")", ":", "direction", "=", "randrange", "(", "1", ",", "4", ")", "if", "direction", "==", "1", ":", "food", ".", "x", "=", "food", ".", "x", "-", "10", "if", "not", "inside", "(", "food", ")", ":", "food", ".", "x", ...
Move food one step in a random direction
[ "Move", "food", "one", "step", "in", "a", "random", "direction" ]
[ "\"Move food one step in a random direction\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
345cab82299edf7d40102f076e12949aff7d3c5a
santiagoTena05/TC1001S.100-202211
Python/snake.py
[ "MIT" ]
Python
move
<not_specific>
def move(): "Move snake forward one segment." head = snake[-1].copy() head.move(aim) if not inside(head) or head in snake: square(head.x, head.y, 9, 'red') update() return snake.append(head) if head == food: print('Snake:', len(snake)) food.x = randrange...
Move snake forward one segment.
Move snake forward one segment.
[ "Move", "snake", "forward", "one", "segment", "." ]
def move(): head = snake[-1].copy() head.move(aim) if not inside(head) or head in snake: square(head.x, head.y, 9, 'red') update() return snake.append(head) if head == food: print('Snake:', len(snake)) food.x = randrange(-15, 15) * 10 food.y = randrang...
[ "def", "move", "(", ")", ":", "head", "=", "snake", "[", "-", "1", "]", ".", "copy", "(", ")", "head", ".", "move", "(", "aim", ")", "if", "not", "inside", "(", "head", ")", "or", "head", "in", "snake", ":", "square", "(", "head", ".", "x", ...
Move snake forward one segment.
[ "Move", "snake", "forward", "one", "segment", "." ]
[ "\"Move snake forward one segment.\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7877b1ded3169fd49557221ac7ef7b974abbfc7c
santiagoTena05/TC1001S.100-202211
Python/memory.py
[ "MIT" ]
Python
tap
null
def tap(x, y): "Update mark and hidden tiles based on tap." global clicks spot = index(x, y) mark = state['mark'] if mark is None or mark == spot or tiles[mark] != tiles[spot]: state['mark'] = spot clicks +=1 print("Guesses= {:d}".format((clicks))) else: hide[spo...
Update mark and hidden tiles based on tap.
Update mark and hidden tiles based on tap.
[ "Update", "mark", "and", "hidden", "tiles", "based", "on", "tap", "." ]
def tap(x, y): global clicks spot = index(x, y) mark = state['mark'] if mark is None or mark == spot or tiles[mark] != tiles[spot]: state['mark'] = spot clicks +=1 print("Guesses= {:d}".format((clicks))) else: hide[spot] = False hide[mark] = False stat...
[ "def", "tap", "(", "x", ",", "y", ")", ":", "global", "clicks", "spot", "=", "index", "(", "x", ",", "y", ")", "mark", "=", "state", "[", "'mark'", "]", "if", "mark", "is", "None", "or", "mark", "==", "spot", "or", "tiles", "[", "mark", "]", ...
Update mark and hidden tiles based on tap.
[ "Update", "mark", "and", "hidden", "tiles", "based", "on", "tap", "." ]
[ "\"Update mark and hidden tiles based on tap.\"" ]
[ { "param": "x", "type": null }, { "param": "y", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y", "type": null, "docstring": null, "docstring_tokens": [], ...
c7560facd3f576c446a3abdf33aec143517bcb6e
o19s/solr-grid-tuning
src/solr_grid_tuning/query_runner.py
[ "Apache-2.0" ]
Python
run_searches_with_parameters
List[Tuple[str, List[str]]]
def run_searches_with_parameters(self, base_query: SolrQuery, searches: List[str], parameter_combination: List[Tuple[str, Any]]) -> List[Tuple[str, List[str]]]: """Performs queries for each of the give...
Performs queries for each of the given searches for the given parameter combination
Performs queries for each of the given searches for the given parameter combination
[ "Performs", "queries", "for", "each", "of", "the", "given", "searches", "for", "the", "given", "parameter", "combination" ]
def run_searches_with_parameters(self, base_query: SolrQuery, searches: List[str], parameter_combination: List[Tuple[str, Any]]) -> List[Tuple[str, List[str]]]: query_params = (base_query.other_params ...
[ "def", "run_searches_with_parameters", "(", "self", ",", "base_query", ":", "SolrQuery", ",", "searches", ":", "List", "[", "str", "]", ",", "parameter_combination", ":", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ")", "->", "List", "[", "Tu...
Performs queries for each of the given searches for the given parameter combination
[ "Performs", "queries", "for", "each", "of", "the", "given", "searches", "for", "the", "given", "parameter", "combination" ]
[ "\"\"\"Performs queries for each of the given searches for the given parameter combination\n \"\"\"", "# join the existing params on the base query with the given parameter combination" ]
[ { "param": "self", "type": null }, { "param": "base_query", "type": "SolrQuery" }, { "param": "searches", "type": "List[str]" }, { "param": "parameter_combination", "type": "List[Tuple[str, Any]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "base_query", "type": "SolrQuery", "docstring": null, "docstri...
c7560facd3f576c446a3abdf33aec143517bcb6e
o19s/solr-grid-tuning
src/solr_grid_tuning/query_runner.py
[ "Apache-2.0" ]
Python
run_searches
List[Tuple[str, List[str]]]
def run_searches(self, base_query: SolrQuery, searches: List[str]) -> List[Tuple[str, List[str]]]: """Performs queries for each of the given searches by successively setting them on a base query """ results = [] for search in searches: ...
Performs queries for each of the given searches by successively setting them on a base query
Performs queries for each of the given searches by successively setting them on a base query
[ "Performs", "queries", "for", "each", "of", "the", "given", "searches", "by", "successively", "setting", "them", "on", "a", "base", "query" ]
def run_searches(self, base_query: SolrQuery, searches: List[str]) -> List[Tuple[str, List[str]]]: results = [] for search in searches: if self.query_field == 'q': query = dataclasses.replace(base_query, q=search) else: ...
[ "def", "run_searches", "(", "self", ",", "base_query", ":", "SolrQuery", ",", "searches", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Tuple", "[", "str", ",", "List", "[", "str", "]", "]", "]", ":", "results", "=", "[", "]", "for", "se...
Performs queries for each of the given searches by successively setting them on a base query
[ "Performs", "queries", "for", "each", "of", "the", "given", "searches", "by", "successively", "setting", "them", "on", "a", "base", "query" ]
[ "\"\"\"Performs queries for each of the given searches by successively setting them on a base query\n \"\"\"", "# set the actual search term, handle special case of the query parameter not being 'q'", "# run the query" ]
[ { "param": "self", "type": null }, { "param": "base_query", "type": "SolrQuery" }, { "param": "searches", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "base_query", "type": "SolrQuery", "docstring": null, "docstri...
c7560facd3f576c446a3abdf33aec143517bcb6e
o19s/solr-grid-tuning
src/solr_grid_tuning/query_runner.py
[ "Apache-2.0" ]
Python
run_query
List[str]
def run_query(self, query: SolrQuery, return_field="id") -> List[str]: """Run a single query and return the list of document ids """ print(f"Running request: {str(query)}") response = self.solr_client.query(query) if response["docs"] is not None and len(response["docs"]) > 0: ...
Run a single query and return the list of document ids
Run a single query and return the list of document ids
[ "Run", "a", "single", "query", "and", "return", "the", "list", "of", "document", "ids" ]
def run_query(self, query: SolrQuery, return_field="id") -> List[str]: print(f"Running request: {str(query)}") response = self.solr_client.query(query) if response["docs"] is not None and len(response["docs"]) > 0: return [doc[return_field] for doc in response["docs"]] else: ...
[ "def", "run_query", "(", "self", ",", "query", ":", "SolrQuery", ",", "return_field", "=", "\"id\"", ")", "->", "List", "[", "str", "]", ":", "print", "(", "f\"Running request: {str(query)}\"", ")", "response", "=", "self", ".", "solr_client", ".", "query", ...
Run a single query and return the list of document ids
[ "Run", "a", "single", "query", "and", "return", "the", "list", "of", "document", "ids" ]
[ "\"\"\"Run a single query and return the list of document ids\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "query", "type": "SolrQuery" }, { "param": "return_field", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "query", "type": "SolrQuery", "docstring": null, "docstring_to...
c6d112b12797e32091afa8e6418e6ac0d512125c
o19s/solr-grid-tuning
src/solr_grid_tuning/parameters.py
[ "Apache-2.0" ]
Python
weights_parameters
List[str]
def weights_parameters(fields: List[str], weights: List[float]) -> List[str]: """Generate Solr field weight combinations for given field values and weights e.g. for ["content", "title"] and [0.1, 1.0] it generates ["content^0.1 title^0.1", "content^0.1 title^1.0", "content^1.0 title0.1", "content^1.0 title^...
Generate Solr field weight combinations for given field values and weights e.g. for ["content", "title"] and [0.1, 1.0] it generates ["content^0.1 title^0.1", "content^0.1 title^1.0", "content^1.0 title0.1", "content^1.0 title^1.0"]
Generate Solr field weight combinations for given field values and weights e.g.
[ "Generate", "Solr", "field", "weight", "combinations", "for", "given", "field", "values", "and", "weights", "e", ".", "g", "." ]
def weights_parameters(fields: List[str], weights: List[float]) -> List[str]: fields_and_weights: List[List[str]] = [[f"{field}^{weight}" for weight in weights] for field in fields] return [" ".join(combination) for combination in itertools.product(*fields_and_weights)]
[ "def", "weights_parameters", "(", "fields", ":", "List", "[", "str", "]", ",", "weights", ":", "List", "[", "float", "]", ")", "->", "List", "[", "str", "]", ":", "fields_and_weights", ":", "List", "[", "List", "[", "str", "]", "]", "=", "[", "[", ...
Generate Solr field weight combinations for given field values and weights e.g.
[ "Generate", "Solr", "field", "weight", "combinations", "for", "given", "field", "values", "and", "weights", "e", ".", "g", "." ]
[ "\"\"\"Generate Solr field weight combinations for given field values and weights\n e.g. for [\"content\", \"title\"] and [0.1, 1.0] it generates\n [\"content^0.1 title^0.1\", \"content^0.1 title^1.0\", \"content^1.0 title0.1\", \"content^1.0 title^1.0\"]\n \"\"\"" ]
[ { "param": "fields", "type": "List[str]" }, { "param": "weights", "type": "List[float]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fields", "type": "List[str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "weights", "type": "List[float]", "docstring": null, ...
a49ffc1fffd497432a466624bb77cb12f4d6af11
mseng10/sphinx
tests/roots/test-root/autodoc_target.py
[ "BSD-2-Clause" ]
Python
_funky_classmethod
<not_specific>
def _funky_classmethod(name, b, c, d, docstring=None): """Generates a classmethod for a class from a template by filling out some arguments.""" def template(cls, a, b, c, d=4, e=5, f=6): return a, b, c, d, e, f from functools import partial function = partial(template, b=b, c=c, d=d) fun...
Generates a classmethod for a class from a template by filling out some arguments.
Generates a classmethod for a class from a template by filling out some arguments.
[ "Generates", "a", "classmethod", "for", "a", "class", "from", "a", "template", "by", "filling", "out", "some", "arguments", "." ]
def _funky_classmethod(name, b, c, d, docstring=None): def template(cls, a, b, c, d=4, e=5, f=6): return a, b, c, d, e, f from functools import partial function = partial(template, b=b, c=c, d=d) function.__name__ = name function.__doc__ = docstring return classmethod(function)
[ "def", "_funky_classmethod", "(", "name", ",", "b", ",", "c", ",", "d", ",", "docstring", "=", "None", ")", ":", "def", "template", "(", "cls", ",", "a", ",", "b", ",", "c", ",", "d", "=", "4", ",", "e", "=", "5", ",", "f", "=", "6", ")", ...
Generates a classmethod for a class from a template by filling out some arguments.
[ "Generates", "a", "classmethod", "for", "a", "class", "from", "a", "template", "by", "filling", "out", "some", "arguments", "." ]
[ "\"\"\"Generates a classmethod for a class from a template by filling out\n some arguments.\"\"\"" ]
[ { "param": "name", "type": null }, { "param": "b", "type": null }, { "param": "c", "type": null }, { "param": "d", "type": null }, { "param": "docstring", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "b", "type": null, "docstring": null, "docstring_tokens": [], ...
a49ffc1fffd497432a466624bb77cb12f4d6af11
mseng10/sphinx
tests/roots/test-root/autodoc_target.py
[ "BSD-2-Clause" ]
Python
meth2
null
def meth2(self): """First line, no signature Second line followed by indentation:: indented line """
First line, no signature Second line followed by indentation:: indented line
First line, no signature Second line followed by indentation:. indented line
[ "First", "line", "no", "signature", "Second", "line", "followed", "by", "indentation", ":", ".", "indented", "line" ]
def meth2(self):
[ "def", "meth2", "(", "self", ")", ":" ]
First line, no signature Second line followed by indentation::
[ "First", "line", "no", "signature", "Second", "line", "followed", "by", "indentation", "::" ]
[ "\"\"\"First line, no signature\n Second line followed by indentation::\n\n indented line\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a49ffc1fffd497432a466624bb77cb12f4d6af11
mseng10/sphinx
tests/roots/test-root/autodoc_target.py
[ "BSD-2-Clause" ]
Python
prop1
<not_specific>
def prop1(self): """DocstringSig.prop1(self) First line of docstring """ return 123
DocstringSig.prop1(self) First line of docstring
DocstringSig.prop1(self) First line of docstring
[ "DocstringSig", ".", "prop1", "(", "self", ")", "First", "line", "of", "docstring" ]
def prop1(self): return 123
[ "def", "prop1", "(", "self", ")", ":", "return", "123" ]
DocstringSig.prop1(self) First line of docstring
[ "DocstringSig", ".", "prop1", "(", "self", ")", "First", "line", "of", "docstring" ]
[ "\"\"\"DocstringSig.prop1(self)\n First line of docstring\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f714dedfb2fc55a060893bd7f928aefbca6e4e47
mseng10/sphinx
sphinx/ext/duration.py
[ "BSD-2-Clause" ]
Python
on_builder_inited
None
def on_builder_inited(app: Sphinx) -> None: """Initialize DurationDomain on bootstrap. This clears results of last build. """ domain = cast(DurationDomain, app.env.get_domain('duration')) domain.clear()
Initialize DurationDomain on bootstrap. This clears results of last build.
Initialize DurationDomain on bootstrap. This clears results of last build.
[ "Initialize", "DurationDomain", "on", "bootstrap", ".", "This", "clears", "results", "of", "last", "build", "." ]
def on_builder_inited(app: Sphinx) -> None: domain = cast(DurationDomain, app.env.get_domain('duration')) domain.clear()
[ "def", "on_builder_inited", "(", "app", ":", "Sphinx", ")", "->", "None", ":", "domain", "=", "cast", "(", "DurationDomain", ",", "app", ".", "env", ".", "get_domain", "(", "'duration'", ")", ")", "domain", ".", "clear", "(", ")" ]
Initialize DurationDomain on bootstrap.
[ "Initialize", "DurationDomain", "on", "bootstrap", "." ]
[ "\"\"\"Initialize DurationDomain on bootstrap.\n\n This clears results of last build.\n \"\"\"" ]
[ { "param": "app", "type": "Sphinx" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "app", "type": "Sphinx", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f714dedfb2fc55a060893bd7f928aefbca6e4e47
mseng10/sphinx
sphinx/ext/duration.py
[ "BSD-2-Clause" ]
Python
on_build_finished
None
def on_build_finished(app: Sphinx, error: Exception) -> None: """Display duration ranking on current build.""" domain = cast(DurationDomain, app.env.get_domain('duration')) durations = sorted(domain.reading_durations.items(), key=itemgetter(1), reverse=True) if not durations: return logger....
Display duration ranking on current build.
Display duration ranking on current build.
[ "Display", "duration", "ranking", "on", "current", "build", "." ]
def on_build_finished(app: Sphinx, error: Exception) -> None: domain = cast(DurationDomain, app.env.get_domain('duration')) durations = sorted(domain.reading_durations.items(), key=itemgetter(1), reverse=True) if not durations: return logger.info('') logger.info(__('====================== sl...
[ "def", "on_build_finished", "(", "app", ":", "Sphinx", ",", "error", ":", "Exception", ")", "->", "None", ":", "domain", "=", "cast", "(", "DurationDomain", ",", "app", ".", "env", ".", "get_domain", "(", "'duration'", ")", ")", "durations", "=", "sorted...
Display duration ranking on current build.
[ "Display", "duration", "ranking", "on", "current", "build", "." ]
[ "\"\"\"Display duration ranking on current build.\"\"\"" ]
[ { "param": "app", "type": "Sphinx" }, { "param": "error", "type": "Exception" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "app", "type": "Sphinx", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "error", "type": "Exception", "docstring": null, "docstring...
09381740979bb6b9c781853a6240fe8f8bca5085
mseng10/sphinx
utils/checks.py
[ "BSD-2-Clause" ]
Python
sphinx_has_header
<not_specific>
def sphinx_has_header(physical_line, filename, lines, line_number): """Check for correct headers. Make sure each Python file has a correct file header including copyright and license information. X101 invalid header found """ # we have a state machine of sorts so we need to start on line 1. Al...
Check for correct headers. Make sure each Python file has a correct file header including copyright and license information. X101 invalid header found
Check for correct headers. Make sure each Python file has a correct file header including copyright and license information. X101 invalid header found
[ "Check", "for", "correct", "headers", ".", "Make", "sure", "each", "Python", "file", "has", "a", "correct", "file", "header", "including", "copyright", "and", "license", "information", ".", "X101", "invalid", "header", "found" ]
def sphinx_has_header(physical_line, filename, lines, line_number): if line_number != 1 or len(lines) < 10: return [1] https://gitlab.com/pycqa/flake8/issues/347 if os.path.samefile(filename, './sphinx/util/smartypants.py'): return if the top-level package or not inside the package, ig...
[ "def", "sphinx_has_header", "(", "physical_line", ",", "filename", ",", "lines", ",", "line_number", ")", ":", "if", "line_number", "!=", "1", "or", "len", "(", "lines", ")", "<", "10", ":", "return", "if", "os", ".", "path", ".", "samefile", "(", "fil...
Check for correct headers.
[ "Check", "for", "correct", "headers", "." ]
[ "\"\"\"Check for correct headers.\n\n Make sure each Python file has a correct file header including\n copyright and license information.\n\n X101 invalid header found\n \"\"\"", "# we have a state machine of sorts so we need to start on line 1. Also,", "# there's no point checking really short file...
[ { "param": "physical_line", "type": null }, { "param": "filename", "type": null }, { "param": "lines", "type": null }, { "param": "line_number", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "physical_line", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstri...
cd8de918f8c33c9eddba03015d3f21bc944114c4
mseng10/sphinx
sphinx/environment/collectors/dependencies.py
[ "BSD-2-Clause" ]
Python
process_doc
None
def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: """Process docutils-generated dependency info.""" cwd = os.getcwd() frompath = path.join(path.normpath(app.srcdir), 'dummy') deps = doctree.settings.record_dependencies if not deps: return fo...
Process docutils-generated dependency info.
Process docutils-generated dependency info.
[ "Process", "docutils", "-", "generated", "dependency", "info", "." ]
def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: cwd = os.getcwd() frompath = path.join(path.normpath(app.srcdir), 'dummy') deps = doctree.settings.record_dependencies if not deps: return for dep in deps.list: if isinstance(dep, bytes):...
[ "def", "process_doc", "(", "self", ",", "app", ":", "Sphinx", ",", "doctree", ":", "nodes", ".", "document", ")", "->", "None", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "frompath", "=", "path", ".", "join", "(", "path", ".", "normpath", "(",...
Process docutils-generated dependency info.
[ "Process", "docutils", "-", "generated", "dependency", "info", "." ]
[ "\"\"\"Process docutils-generated dependency info.\"\"\"", "# the dependency path is relative to the working dir, so get", "# one relative to the srcdir" ]
[ { "param": "self", "type": null }, { "param": "app", "type": "Sphinx" }, { "param": "doctree", "type": "nodes.document" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "app", "type": "Sphinx", "docstring": null, "docstring_tokens"...
4db13c695c868e2ac5f7f323030ab91a30db18ff
mseng10/sphinx
sphinx/ext/autodoc/type_comment.py
[ "BSD-2-Clause" ]
Python
not_suppressed
bool
def not_suppressed(argtypes: List[ast.AST] = []) -> bool: """Check given *argtypes* is suppressed type_comment or not.""" if len(argtypes) == 0: # no argtypees return False elif len(argtypes) == 1 and ast_unparse(argtypes[0]) == "...": # suppressed # Note: To support multiple versions of p...
Check given *argtypes* is suppressed type_comment or not.
Check given *argtypes* is suppressed type_comment or not.
[ "Check", "given", "*", "argtypes", "*", "is", "suppressed", "type_comment", "or", "not", "." ]
def not_suppressed(argtypes: List[ast.AST] = []) -> bool: if len(argtypes) == 0: return False elif len(argtypes) == 1 and ast_unparse(argtypes[0]) == "...": return False else: return True
[ "def", "not_suppressed", "(", "argtypes", ":", "List", "[", "ast", ".", "AST", "]", "=", "[", "]", ")", "->", "bool", ":", "if", "len", "(", "argtypes", ")", "==", "0", ":", "return", "False", "elif", "len", "(", "argtypes", ")", "==", "1", "and"...
Check given *argtypes* is suppressed type_comment or not.
[ "Check", "given", "*", "argtypes", "*", "is", "suppressed", "type_comment", "or", "not", "." ]
[ "\"\"\"Check given *argtypes* is suppressed type_comment or not.\"\"\"", "# no argtypees", "# suppressed", "# Note: To support multiple versions of python, this uses ``ast_unparse()`` for", "# comparison with Ellipsis. Since 3.8, ast.Constant has been used to represent", "# Ellipsis node instead of ast.E...
[ { "param": "argtypes", "type": "List[ast.AST]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "argtypes", "type": "List[ast.AST]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4db13c695c868e2ac5f7f323030ab91a30db18ff
mseng10/sphinx
sphinx/ext/autodoc/type_comment.py
[ "BSD-2-Clause" ]
Python
signature_from_ast
Signature
def signature_from_ast(node: ast.FunctionDef, bound_method: bool, type_comment: ast.FunctionDef) -> Signature: """Return a Signature object for the given *node*. :param bound_method: Specify *node* is a bound method or not """ params = [] if hasattr(node.args, "posonlyargs"):...
Return a Signature object for the given *node*. :param bound_method: Specify *node* is a bound method or not
Return a Signature object for the given *node*.
[ "Return", "a", "Signature", "object", "for", "the", "given", "*", "node", "*", "." ]
def signature_from_ast(node: ast.FunctionDef, bound_method: bool, type_comment: ast.FunctionDef) -> Signature: params = [] if hasattr(node.args, "posonlyargs"): for arg in node.args.posonlyargs: param = Parameter(arg.arg, Parameter.POSITIONAL_ONLY, annotation=arg.t...
[ "def", "signature_from_ast", "(", "node", ":", "ast", ".", "FunctionDef", ",", "bound_method", ":", "bool", ",", "type_comment", ":", "ast", ".", "FunctionDef", ")", "->", "Signature", ":", "params", "=", "[", "]", "if", "hasattr", "(", "node", ".", "arg...
Return a Signature object for the given *node*.
[ "Return", "a", "Signature", "object", "for", "the", "given", "*", "node", "*", "." ]
[ "\"\"\"Return a Signature object for the given *node*.\n\n :param bound_method: Specify *node* is a bound method or not\n \"\"\"", "# for py38+", "# type: ignore", "# Remove first parameter when *obj* is bound_method", "# merge type_comment into signature", "# type: ignore", "# type: ignore" ]
[ { "param": "node", "type": "ast.FunctionDef" }, { "param": "bound_method", "type": "bool" }, { "param": "type_comment", "type": "ast.FunctionDef" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "node", "type": "ast.FunctionDef", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bound_method", "type": "bool", "docstring": "Specify *...
4db13c695c868e2ac5f7f323030ab91a30db18ff
mseng10/sphinx
sphinx/ext/autodoc/type_comment.py
[ "BSD-2-Clause" ]
Python
update_annotations_using_type_comments
None
def update_annotations_using_type_comments(app: Sphinx, obj: Any, bound_method: bool) -> None: """Update annotations info of *obj* using type_comments.""" try: type_sig = get_type_comment(obj, bound_method) if type_sig: sig = inspect.signature(obj, bound_method) for param...
Update annotations info of *obj* using type_comments.
Update annotations info of *obj* using type_comments.
[ "Update", "annotations", "info", "of", "*", "obj", "*", "using", "type_comments", "." ]
def update_annotations_using_type_comments(app: Sphinx, obj: Any, bound_method: bool) -> None: try: type_sig = get_type_comment(obj, bound_method) if type_sig: sig = inspect.signature(obj, bound_method) for param in sig.parameters.values(): if param.name not i...
[ "def", "update_annotations_using_type_comments", "(", "app", ":", "Sphinx", ",", "obj", ":", "Any", ",", "bound_method", ":", "bool", ")", "->", "None", ":", "try", ":", "type_sig", "=", "get_type_comment", "(", "obj", ",", "bound_method", ")", "if", "type_s...
Update annotations info of *obj* using type_comments.
[ "Update", "annotations", "info", "of", "*", "obj", "*", "using", "type_comments", "." ]
[ "\"\"\"Update annotations info of *obj* using type_comments.\"\"\"", "# failed to ast.unparse()" ]
[ { "param": "app", "type": "Sphinx" }, { "param": "obj", "type": "Any" }, { "param": "bound_method", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "app", "type": "Sphinx", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": "Any", "docstring": null, "docstring_tokens"...
f29562cd99b77a38e21f9f64ed85a665cb107252
Palem1988/pinnwand
pinnwand/command.py
[ "BSD-3-Clause" ]
Python
http
None
def http(port: int) -> None: """Run pinnwand's HTTP server.""" database.Base.metadata.create_all(database._engine) application = make_application() application.listen(port) tornado.ioloop.IOLoop.current().start()
Run pinnwand's HTTP server.
Run pinnwand's HTTP server.
[ "Run", "pinnwand", "'", "s", "HTTP", "server", "." ]
def http(port: int) -> None: database.Base.metadata.create_all(database._engine) application = make_application() application.listen(port) tornado.ioloop.IOLoop.current().start()
[ "def", "http", "(", "port", ":", "int", ")", "->", "None", ":", "database", ".", "Base", ".", "metadata", ".", "create_all", "(", "database", ".", "_engine", ")", "application", "=", "make_application", "(", ")", "application", ".", "listen", "(", "port"...
Run pinnwand's HTTP server.
[ "Run", "pinnwand", "'", "s", "HTTP", "server", "." ]
[ "\"\"\"Run pinnwand's HTTP server.\"\"\"" ]
[ { "param": "port", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "port", "type": "int", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f29562cd99b77a38e21f9f64ed85a665cb107252
Palem1988/pinnwand
pinnwand/command.py
[ "BSD-3-Clause" ]
Python
add
None
def add(lexer: str) -> None: """Add a paste to pinnwand's database from stdin.""" if lexer not in utility.list_languages(): log.error("add: unknown lexer") return paste = database.Paste( sys.stdin.read(), lexer=lexer, expiry=timedelta(days=1) ) with database.session() as se...
Add a paste to pinnwand's database from stdin.
Add a paste to pinnwand's database from stdin.
[ "Add", "a", "paste", "to", "pinnwand", "'", "s", "database", "from", "stdin", "." ]
def add(lexer: str) -> None: if lexer not in utility.list_languages(): log.error("add: unknown lexer") return paste = database.Paste( sys.stdin.read(), lexer=lexer, expiry=timedelta(days=1) ) with database.session() as session: session.add(paste) session.commit() ...
[ "def", "add", "(", "lexer", ":", "str", ")", "->", "None", ":", "if", "lexer", "not", "in", "utility", ".", "list_languages", "(", ")", ":", "log", ".", "error", "(", "\"add: unknown lexer\"", ")", "return", "paste", "=", "database", ".", "Paste", "(",...
Add a paste to pinnwand's database from stdin.
[ "Add", "a", "paste", "to", "pinnwand", "'", "s", "database", "from", "stdin", "." ]
[ "\"\"\"Add a paste to pinnwand's database from stdin.\"\"\"" ]
[ { "param": "lexer", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lexer", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f29562cd99b77a38e21f9f64ed85a665cb107252
Palem1988/pinnwand
pinnwand/command.py
[ "BSD-3-Clause" ]
Python
delete
None
def delete(paste: str) -> None: """Delete a paste from pinnwand's database.""" with database.session() as session: paste_object = ( session.query(database.Paste) .filter(database.Paste.paste_id == paste) .first() ) if not paste_object: log...
Delete a paste from pinnwand's database.
Delete a paste from pinnwand's database.
[ "Delete", "a", "paste", "from", "pinnwand", "'", "s", "database", "." ]
def delete(paste: str) -> None: with database.session() as session: paste_object = ( session.query(database.Paste) .filter(database.Paste.paste_id == paste) .first() ) if not paste_object: log.error("delete: unknown paste") return ...
[ "def", "delete", "(", "paste", ":", "str", ")", "->", "None", ":", "with", "database", ".", "session", "(", ")", "as", "session", ":", "paste_object", "=", "(", "session", ".", "query", "(", "database", ".", "Paste", ")", ".", "filter", "(", "databas...
Delete a paste from pinnwand's database.
[ "Delete", "a", "paste", "from", "pinnwand", "'", "s", "database", "." ]
[ "\"\"\"Delete a paste from pinnwand's database.\"\"\"" ]
[ { "param": "paste", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "paste", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f29562cd99b77a38e21f9f64ed85a665cb107252
Palem1988/pinnwand
pinnwand/command.py
[ "BSD-3-Clause" ]
Python
reap
None
def reap() -> None: """Delete all pastes that are past their expiry date in pinnwand's database.""" with database.session() as session: pastes = ( session.query(database.Paste) .filter(database.Paste.exp_date < datetime.now()) .all() ) for past...
Delete all pastes that are past their expiry date in pinnwand's database.
Delete all pastes that are past their expiry date in pinnwand's database.
[ "Delete", "all", "pastes", "that", "are", "past", "their", "expiry", "date", "in", "pinnwand", "'", "s", "database", "." ]
def reap() -> None: with database.session() as session: pastes = ( session.query(database.Paste) .filter(database.Paste.exp_date < datetime.now()) .all() ) for paste in pastes: session.delete(paste) session.commit() log.info("re...
[ "def", "reap", "(", ")", "->", "None", ":", "with", "database", ".", "session", "(", ")", "as", "session", ":", "pastes", "=", "(", "session", ".", "query", "(", "database", ".", "Paste", ")", ".", "filter", "(", "database", ".", "Paste", ".", "exp...
Delete all pastes that are past their expiry date in pinnwand's database.
[ "Delete", "all", "pastes", "that", "are", "past", "their", "expiry", "date", "in", "pinnwand", "'", "s", "database", "." ]
[ "\"\"\"Delete all pastes that are past their expiry date in pinnwand's\n database.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2c2cca51ba84f48777f24c812435a957fba132cb
MarcinOrlowski/dhunter
dhunter/core/args_base.py
[ "MIT" ]
Python
_get_tool_name
str
def _get_tool_name(self) -> str: """ Returns name of invoked utility. This string is only used when help string is going to be shown, so it mention the right name of package tool handling these options. :return: """ return Const.APP_NAME.lower()
Returns name of invoked utility. This string is only used when help string is going to be shown, so it mention the right name of package tool handling these options. :return:
Returns name of invoked utility. This string is only used when help string is going to be shown, so it mention the right name of package tool handling these options.
[ "Returns", "name", "of", "invoked", "utility", ".", "This", "string", "is", "only", "used", "when", "help", "string", "is", "going", "to", "be", "shown", "so", "it", "mention", "the", "right", "name", "of", "package", "tool", "handling", "these", "options"...
def _get_tool_name(self) -> str: return Const.APP_NAME.lower()
[ "def", "_get_tool_name", "(", "self", ")", "->", "str", ":", "return", "Const", ".", "APP_NAME", ".", "lower", "(", ")" ]
Returns name of invoked utility.
[ "Returns", "name", "of", "invoked", "utility", "." ]
[ "\"\"\"\n Returns name of invoked utility. This string is only used when help\n string is going to be shown, so it mention the right name of package tool\n handling these options.\n\n :return:\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
85d443dbb7dc60837cea72d50ab4335a4e95d308
MarcinOrlowski/dhunter
dhunter/core/hash_manager.py
[ "MIT" ]
Python
has_dirhash_for_path
bool
def has_dirhash_for_path(self, dir_path: str) -> bool: """Checks if we already have dirhash object in project file. :param dir_path: Path to look DirHash object for """ result = False if self._use_db: self.db_init() cursor: sqlite3.Cursor = self._db.curs...
Checks if we already have dirhash object in project file. :param dir_path: Path to look DirHash object for
Checks if we already have dirhash object in project file.
[ "Checks", "if", "we", "already", "have", "dirhash", "object", "in", "project", "file", "." ]
def has_dirhash_for_path(self, dir_path: str) -> bool: result = False if self._use_db: self.db_init() cursor: sqlite3.Cursor = self._db.cursor() cursor.execute('SELECT COUNT(`path`) AS `cnt` FROM `files` where `path` = ? LIMIT 1', (dir_path,)) if cursor.ro...
[ "def", "has_dirhash_for_path", "(", "self", ",", "dir_path", ":", "str", ")", "->", "bool", ":", "result", "=", "False", "if", "self", ".", "_use_db", ":", "self", ".", "db_init", "(", ")", "cursor", ":", "sqlite3", ".", "Cursor", "=", "self", ".", "...
Checks if we already have dirhash object in project file.
[ "Checks", "if", "we", "already", "have", "dirhash", "object", "in", "project", "file", "." ]
[ "\"\"\"Checks if we already have dirhash object in project file.\n\n :param dir_path: Path to look DirHash object for\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "dir_path", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dir_path", "type": "str", "docstring": "Path to look DirHash object...
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
load
None
def load(self) -> None: """Loads FileHashes from from flat file storage """ if not os.path.isdir(self._path): raise NotADirectoryError('"{name}" is not a directory'.format(name=self._path)) from .file_hash import FileHash # if we are forced to rehash all files, then...
Loads FileHashes from from flat file storage
Loads FileHashes from from flat file storage
[ "Loads", "FileHashes", "from", "from", "flat", "file", "storage" ]
def load(self) -> None: if not os.path.isdir(self._path): raise NotADirectoryError('"{name}" is not a directory'.format(name=self._path)) from .file_hash import FileHash if self._config.force_rehash: self._dirty = True return dirty = self._dirty ...
[ "def", "load", "(", "self", ")", "->", "None", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_path", ")", ":", "raise", "NotADirectoryError", "(", "'\"{name}\" is not a directory'", ".", "format", "(", "name", "=", "self", ".", ...
Loads FileHashes from from flat file storage
[ "Loads", "FileHashes", "from", "from", "flat", "file", "storage" ]
[ "\"\"\"Loads FileHashes from from flat file storage\n \"\"\"", "# if we are forced to rehash all files, then we pretend", "# there was no file to load...", "# we need to prevent dirty state as loading should not affect that flag at all", "# is header line read already?", "# we need to read cache me...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
save
bool
def save(self) -> bool: """Saves FileHash hashes into flat file storage """ if self._config.dont_save_dot_file: return True result = False if self._dirty: dot_file_name = os.path.join(self._path, Const.FILE_DOT_DHUNTER) with open(dot_file_nam...
Saves FileHash hashes into flat file storage
Saves FileHash hashes into flat file storage
[ "Saves", "FileHash", "hashes", "into", "flat", "file", "storage" ]
def save(self) -> bool: if self._config.dont_save_dot_file: return True result = False if self._dirty: dot_file_name = os.path.join(self._path, Const.FILE_DOT_DHUNTER) with open(dot_file_name, 'w') as fh: fh.write('# {name} hash cache {url}\n'....
[ "def", "save", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_config", ".", "dont_save_dot_file", ":", "return", "True", "result", "=", "False", "if", "self", ".", "_dirty", ":", "dot_file_name", "=", "os", ".", "path", ".", "join", "(", "...
Saves FileHash hashes into flat file storage
[ "Saves", "FileHash", "hashes", "into", "flat", "file", "storage" ]
[ "\"\"\"Saves FileHash hashes into flat file storage\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
add
None
def add(self, file_hash: FileHash) -> None: """Add FileHash to internal cache storage :raises ValueError """ if not isinstance(file_hash, FileHash): raise ValueError('Unsupported data type {type}'.format(type=type(file_hash))) # check if we have this hash entry in c...
Add FileHash to internal cache storage :raises ValueError
Add FileHash to internal cache storage :raises ValueError
[ "Add", "FileHash", "to", "internal", "cache", "storage", ":", "raises", "ValueError" ]
def add(self, file_hash: FileHash) -> None: if not isinstance(file_hash, FileHash): raise ValueError('Unsupported data type {type}'.format(type=type(file_hash))) if file_hash not in self._cache.values(): self._add_finalize(file_hash) elif file_hash.name in self._cache: ...
[ "def", "add", "(", "self", ",", "file_hash", ":", "FileHash", ")", "->", "None", ":", "if", "not", "isinstance", "(", "file_hash", ",", "FileHash", ")", ":", "raise", "ValueError", "(", "'Unsupported data type {type}'", ".", "format", "(", "type", "=", "ty...
Add FileHash to internal cache storage :raises ValueError
[ "Add", "FileHash", "to", "internal", "cache", "storage", ":", "raises", "ValueError" ]
[ "\"\"\"Add FileHash to internal cache storage\n\n :raises ValueError\n \"\"\"", "# check if we have this hash entry in cache already?", "# no, create new entry then", "# we do, so let's check if that is for this particular file state", "# seems it is not. Most likely underlying data changed,",...
[ { "param": "self", "type": null }, { "param": "file_hash", "type": "FileHash" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "file_hash", "type": "FileHash", "docstring": null, "docstring...
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
replace
bool
def replace(self, file_hash: FileHash) -> bool: """Replaces existing FileHash entry with new one or just adds new entry if no file_hash is cached yet. :returns indicating if FileHash was replaced (True), or just added (False) """ replaced = False if file_hash.name in self._cache:...
Replaces existing FileHash entry with new one or just adds new entry if no file_hash is cached yet. :returns indicating if FileHash was replaced (True), or just added (False)
Replaces existing FileHash entry with new one or just adds new entry if no file_hash is cached yet. :returns indicating if FileHash was replaced (True), or just added (False)
[ "Replaces", "existing", "FileHash", "entry", "with", "new", "one", "or", "just", "adds", "new", "entry", "if", "no", "file_hash", "is", "cached", "yet", ".", ":", "returns", "indicating", "if", "FileHash", "was", "replaced", "(", "True", ")", "or", "just",...
def replace(self, file_hash: FileHash) -> bool: replaced = False if file_hash.name in self._cache: del self._cache[file_hash.name] replaced = True self.add(file_hash) return replaced
[ "def", "replace", "(", "self", ",", "file_hash", ":", "FileHash", ")", "->", "bool", ":", "replaced", "=", "False", "if", "file_hash", ".", "name", "in", "self", ".", "_cache", ":", "del", "self", ".", "_cache", "[", "file_hash", ".", "name", "]", "r...
Replaces existing FileHash entry with new one or just adds new entry if no file_hash is cached yet.
[ "Replaces", "existing", "FileHash", "entry", "with", "new", "one", "or", "just", "adds", "new", "entry", "if", "no", "file_hash", "is", "cached", "yet", "." ]
[ "\"\"\"Replaces existing FileHash entry with new one or just adds new entry if no file_hash is cached yet.\n :returns indicating if FileHash was replaced (True), or just added (False)\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "file_hash", "type": "FileHash" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "file_hash", "type": "FileHash", "docstring": null, "docstring...
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
remove
bool
def remove(self, obj: os.DirEntry or FileHash or str) -> bool: """Removes cached entry based on of either DirEntry or FileHash data. Does nothing if object is not found """ if isinstance(obj, (FileHash, os.DirEntry)): return self.remove_by_name(obj.name) if isinstance(obj, st...
Removes cached entry based on of either DirEntry or FileHash data. Does nothing if object is not found
Removes cached entry based on of either DirEntry or FileHash data. Does nothing if object is not found
[ "Removes", "cached", "entry", "based", "on", "of", "either", "DirEntry", "or", "FileHash", "data", ".", "Does", "nothing", "if", "object", "is", "not", "found" ]
def remove(self, obj: os.DirEntry or FileHash or str) -> bool: if isinstance(obj, (FileHash, os.DirEntry)): return self.remove_by_name(obj.name) if isinstance(obj, str): return self.remove_by_name(obj) raise ValueError('Unsupported argument type "{}"'.format(type(obj)))
[ "def", "remove", "(", "self", ",", "obj", ":", "os", ".", "DirEntry", "or", "FileHash", "or", "str", ")", "->", "bool", ":", "if", "isinstance", "(", "obj", ",", "(", "FileHash", ",", "os", ".", "DirEntry", ")", ")", ":", "return", "self", ".", "...
Removes cached entry based on of either DirEntry or FileHash data.
[ "Removes", "cached", "entry", "based", "on", "of", "either", "DirEntry", "or", "FileHash", "data", "." ]
[ "\"\"\"Removes cached entry based on of either DirEntry or FileHash data. Does nothing if object is not found\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "obj", "type": "os.DirEntry or FileHash or str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": "os.DirEntry or FileHash or str", "docstring": null, ...
5ae35b599f8e3d915000b65a49610bda4140de14
MarcinOrlowski/dhunter
dhunter/core/file_hash_cache.py
[ "MIT" ]
Python
remove_by_name
bool
def remove_by_name(self, name: str) -> bool: """Removes cached file entry based on file name. Does nothing if object is not found """ result = False if name in self._cache: del self._cache[name] self._dirty = True result = True return result
Removes cached file entry based on file name. Does nothing if object is not found
Removes cached file entry based on file name. Does nothing if object is not found
[ "Removes", "cached", "file", "entry", "based", "on", "file", "name", ".", "Does", "nothing", "if", "object", "is", "not", "found" ]
def remove_by_name(self, name: str) -> bool: result = False if name in self._cache: del self._cache[name] self._dirty = True result = True return result
[ "def", "remove_by_name", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "result", "=", "False", "if", "name", "in", "self", ".", "_cache", ":", "del", "self", ".", "_cache", "[", "name", "]", "self", ".", "_dirty", "=", "True", "resu...
Removes cached file entry based on file name.
[ "Removes", "cached", "file", "entry", "based", "on", "file", "name", "." ]
[ "\"\"\"Removes cached file entry based on file name. Does nothing if object is not found\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "name", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "name", "type": "str", "docstring": null, "docstring_tokens": ...
9f6549a5713d217f33a21249520ee9a73260bc6f
MarcinOrlowski/dhunter
dhunter/util/util.py
[ "MIT" ]
Python
size_to_str
str
def size_to_str(size_in_bytes: int, suffix: str = 'B') -> str: """Formats length in bytes into human readable string. """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(size_in_bytes) < 1024.0: if unit == '': return '%d %s%s' % ...
Formats length in bytes into human readable string.
Formats length in bytes into human readable string.
[ "Formats", "length", "in", "bytes", "into", "human", "readable", "string", "." ]
def size_to_str(size_in_bytes: int, suffix: str = 'B') -> str: for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(size_in_bytes) < 1024.0: if unit == '': return '%d %s%s' % (size_in_bytes, unit, suffix) else: ret...
[ "def", "size_to_str", "(", "size_in_bytes", ":", "int", ",", "suffix", ":", "str", "=", "'B'", ")", "->", "str", ":", "for", "unit", "in", "[", "''", ",", "'Ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", ",", "'Pi'", ",", "'Ei'", ",", "'Zi'", "]", ...
Formats length in bytes into human readable string.
[ "Formats", "length", "in", "bytes", "into", "human", "readable", "string", "." ]
[ "\"\"\"Formats length in bytes into human readable string.\n \"\"\"" ]
[ { "param": "size_in_bytes", "type": "int" }, { "param": "suffix", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "size_in_bytes", "type": "int", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "suffix", "type": "str", "docstring": null, "docstri...
9f6549a5713d217f33a21249520ee9a73260bc6f
MarcinOrlowski/dhunter
dhunter/util/util.py
[ "MIT" ]
Python
size_to_int
int
def size_to_int(val: str) -> int: """Parses size string trying to get size as int from it. Supported formats: "123" => 123 "12k" => 12 * 1024 "12M" => 12 * 1024 * 1024 :param val: string representing sine :return: filesize :raise Raises Inva...
Parses size string trying to get size as int from it. Supported formats: "123" => 123 "12k" => 12 * 1024 "12M" => 12 * 1024 * 1024 :param val: string representing sine :return: filesize :raise Raises InvalidArgument if cannot parse string
Parses size string trying to get size as int from it. :param val: string representing sine :return: filesize :raise Raises InvalidArgument if cannot parse string
[ "Parses", "size", "string", "trying", "to", "get", "size", "as", "int", "from", "it", ".", ":", "param", "val", ":", "string", "representing", "sine", ":", "return", ":", "filesize", ":", "raise", "Raises", "InvalidArgument", "if", "cannot", "parse", "stri...
def size_to_int(val: str) -> int: import re val = val.strip().replace(' ', '').lower() match = re.match(r'^([0-9]+)([bkmgt]?)$', val) if match is None: raise ValueError('Unable to parse provided size string %r' % val) unit = match.group(2) if match.group(2) != '' else...
[ "def", "size_to_int", "(", "val", ":", "str", ")", "->", "int", ":", "import", "re", "val", "=", "val", ".", "strip", "(", ")", ".", "replace", "(", "' '", ",", "''", ")", ".", "lower", "(", ")", "match", "=", "re", ".", "match", "(", "r'^([0-9...
Parses size string trying to get size as int from it.
[ "Parses", "size", "string", "trying", "to", "get", "size", "as", "int", "from", "it", "." ]
[ "\"\"\"Parses size string trying to get size as int from it.\n\n Supported formats:\n \"123\" => 123\n \"12k\" => 12 * 1024\n \"12M\" => 12 * 1024 * 1024\n\n :param val: string representing sine\n :return: filesize\n\n :raise Raises InvalidArgument if can...
[ { "param": "val", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "val", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9f6549a5713d217f33a21249520ee9a73260bc6f
MarcinOrlowski/dhunter
dhunter/util/util.py
[ "MIT" ]
Python
md5
str
def md5(msg: str) -> str: """Calculates MD5 hashs for string argument. """ import hashlib if str is None: raise ValueError('Data do hash cannot be None') name_hash = hashlib.md5() name_hash.update(msg.encode('UTF-8')) # return name_hash.digest() ...
Calculates MD5 hashs for string argument.
Calculates MD5 hashs for string argument.
[ "Calculates", "MD5", "hashs", "for", "string", "argument", "." ]
def md5(msg: str) -> str: import hashlib if str is None: raise ValueError('Data do hash cannot be None') name_hash = hashlib.md5() name_hash.update(msg.encode('UTF-8')) return name_hash.hexdigest()
[ "def", "md5", "(", "msg", ":", "str", ")", "->", "str", ":", "import", "hashlib", "if", "str", "is", "None", ":", "raise", "ValueError", "(", "'Data do hash cannot be None'", ")", "name_hash", "=", "hashlib", ".", "md5", "(", ")", "name_hash", ".", "upda...
Calculates MD5 hashs for string argument.
[ "Calculates", "MD5", "hashs", "for", "string", "argument", "." ]
[ "\"\"\"Calculates MD5 hashs for string argument.\n \"\"\"", "# return name_hash.digest()" ]
[ { "param": "msg", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "msg", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9f6549a5713d217f33a21249520ee9a73260bc6f
MarcinOrlowski/dhunter
dhunter/util/util.py
[ "MIT" ]
Python
json_data_valid
bool
def json_data_valid(json_dict: dict, required_type: str, required_min_version: int) -> bool: """Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class """ result = False if Const.FIELD_TYPE in json_dict: if json_dict[Const.FIELD...
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
[ "Checks", "if", "given", "dict", "structure", "based", "on", "loaded", "JSON", "data", "matches", "requirements", "and", "is", "dump", "of", "our", "class" ]
def json_data_valid(json_dict: dict, required_type: str, required_min_version: int) -> bool: result = False if Const.FIELD_TYPE in json_dict: if json_dict[Const.FIELD_TYPE] == required_type: if Const.FIELD_VERSION in json_dict: if json_dict[Const.FIELD_VER...
[ "def", "json_data_valid", "(", "json_dict", ":", "dict", ",", "required_type", ":", "str", ",", "required_min_version", ":", "int", ")", "->", "bool", ":", "result", "=", "False", "if", "Const", ".", "FIELD_TYPE", "in", "json_dict", ":", "if", "json_dict", ...
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
[ "Checks", "if", "given", "dict", "structure", "based", "on", "loaded", "JSON", "data", "matches", "requirements", "and", "is", "dump", "of", "our", "class" ]
[ "\"\"\"Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class\n \"\"\"" ]
[ { "param": "json_dict", "type": "dict" }, { "param": "required_type", "type": "str" }, { "param": "required_min_version", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "json_dict", "type": "dict", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "required_type", "type": "str", "docstring": null, "doc...
3fbe0e18da21fea7d899a2a1b9142e50221c5402
MarcinOrlowski/dhunter
dhunter/core/filter.py
[ "MIT" ]
Python
_append_regexp
null
def _append_regexp(self, to: List[str], regexps: List[str] or None): """Appends new regexp rules to existing blacklists.""" if regexps: try: for pattern in regexps: re.compile(pattern) if pattern not in to: to.ap...
Appends new regexp rules to existing blacklists.
Appends new regexp rules to existing blacklists.
[ "Appends", "new", "regexp", "rules", "to", "existing", "blacklists", "." ]
def _append_regexp(self, to: List[str], regexps: List[str] or None): if regexps: try: for pattern in regexps: re.compile(pattern) if pattern not in to: to.append(pattern) except re.error: from...
[ "def", "_append_regexp", "(", "self", ",", "to", ":", "List", "[", "str", "]", ",", "regexps", ":", "List", "[", "str", "]", "or", "None", ")", ":", "if", "regexps", ":", "try", ":", "for", "pattern", "in", "regexps", ":", "re", ".", "compile", "...
Appends new regexp rules to existing blacklists.
[ "Appends", "new", "regexp", "rules", "to", "existing", "blacklists", "." ]
[ "\"\"\"Appends new regexp rules to existing blacklists.\"\"\"", "# noinspection PyUnboundLocalVariable" ]
[ { "param": "self", "type": null }, { "param": "to", "type": "List[str]" }, { "param": "regexps", "type": "List[str] or None" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "to", "type": "List[str]", "docstring": null, "docstring_token...
3fbe0e18da21fea7d899a2a1b9142e50221c5402
MarcinOrlowski/dhunter
dhunter/core/filter.py
[ "MIT" ]
Python
validate_file
bool
def validate_file(self, dir_entry: os.DirEntry) -> bool: """Validates given DirEntry. Returns False if entry should be completely ignored, or True if we want to keep it for further processing. Ignore all zero length files. There are usually there for a purpose like .dummy etc, so there ...
Validates given DirEntry. Returns False if entry should be completely ignored, or True if we want to keep it for further processing. Ignore all zero length files. There are usually there for a purpose like .dummy etc, so there can be tons of it with the same name even, so by default, ignore the...
Ignore all zero length files. There are usually there for a purpose like .dummy etc, so there can be tons of it with the same name even, so by default, ignore them completely. Also ignore all symlinks.
[ "Ignore", "all", "zero", "length", "files", ".", "There", "are", "usually", "there", "for", "a", "purpose", "like", ".", "dummy", "etc", "so", "there", "can", "be", "tons", "of", "it", "with", "the", "same", "name", "even", "so", "by", "default", "igno...
def validate_file(self, dir_entry: os.DirEntry) -> bool: from .log import Log if dir_entry.is_symlink(): Log.vv('{name}: It is the symbolic link. Skipping.'.format(name=dir_entry.name)) return False if not dir_entry.is_file(): Log.vv('{name}: This is not a fil...
[ "def", "validate_file", "(", "self", ",", "dir_entry", ":", "os", ".", "DirEntry", ")", "->", "bool", ":", "from", ".", "log", "import", "Log", "if", "dir_entry", ".", "is_symlink", "(", ")", ":", "Log", ".", "vv", "(", "'{name}: It is the symbolic link. S...
Validates given DirEntry.
[ "Validates", "given", "DirEntry", "." ]
[ "\"\"\"Validates given DirEntry. Returns False if entry should be completely ignored,\n or True if we want to keep it for further processing.\n\n Ignore all zero length files. There are usually there for a purpose like .dummy etc,\n so there can be tons of it with the same name even, so by defa...
[ { "param": "self", "type": null }, { "param": "dir_entry", "type": "os.DirEntry" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dir_entry", "type": "os.DirEntry", "docstring": null, "docstr...
3fbe0e18da21fea7d899a2a1b9142e50221c5402
MarcinOrlowski/dhunter
dhunter/core/filter.py
[ "MIT" ]
Python
validate_dir
bool
def validate_dir(self, path: str, no_log: bool = False, warn_on_symlink=False) -> bool: """Validates given path. Returns False if entry should be completely ignored, or True if keep it for further processing.""" from .log import Log if os.path.islink(path): msg = '{path} is...
Validates given path. Returns False if entry should be completely ignored, or True if keep it for further processing.
Validates given path. Returns False if entry should be completely ignored, or True if keep it for further processing.
[ "Validates", "given", "path", ".", "Returns", "False", "if", "entry", "should", "be", "completely", "ignored", "or", "True", "if", "keep", "it", "for", "further", "processing", "." ]
def validate_dir(self, path: str, no_log: bool = False, warn_on_symlink=False) -> bool: from .log import Log if os.path.islink(path): msg = '{path} is a symbolic link. Skipping.'.format(path=path) if warn_on_symlink: Log.w(msg, not no_log) else: ...
[ "def", "validate_dir", "(", "self", ",", "path", ":", "str", ",", "no_log", ":", "bool", "=", "False", ",", "warn_on_symlink", "=", "False", ")", "->", "bool", ":", "from", ".", "log", "import", "Log", "if", "os", ".", "path", ".", "islink", "(", "...
Validates given path.
[ "Validates", "given", "path", "." ]
[ "\"\"\"Validates given path. Returns False if entry should be completely ignored,\n or True if keep it for further processing.\"\"\"", "# if there's dot ignore file present in the folder we completely skip." ]
[ { "param": "self", "type": null }, { "param": "path", "type": "str" }, { "param": "no_log", "type": "bool" }, { "param": "warn_on_symlink", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": "str", "docstring": null, "docstring_tokens": ...
654569d4750f8c671c919f1def63c1bd9e70b403
MarcinOrlowski/dhunter
dhunter/core/dir_hash.py
[ "MIT" ]
Python
file_count
int
def file_count(self) -> int: """Returns number of files stored in cache :return: number of files stored in cache """ return len(self._file_hash_cache)
Returns number of files stored in cache :return: number of files stored in cache
Returns number of files stored in cache
[ "Returns", "number", "of", "files", "stored", "in", "cache" ]
def file_count(self) -> int: return len(self._file_hash_cache)
[ "def", "file_count", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "_file_hash_cache", ")" ]
Returns number of files stored in cache
[ "Returns", "number", "of", "files", "stored", "in", "cache" ]
[ "\"\"\"Returns number of files stored in cache\n\n :return: number of files stored in cache\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "number of files stored in cache", "docstring_tokens": [ "number", "of", "files", "stored", "in", "cache" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": n...
654569d4750f8c671c919f1def63c1bd9e70b403
MarcinOrlowski/dhunter
dhunter/core/dir_hash.py
[ "MIT" ]
Python
total_file_size
int
def total_file_size(self) -> int: """Returns total file size of all cached files :return: total file size of all cached files """ return self._file_hash_cache.total_file_size
Returns total file size of all cached files :return: total file size of all cached files
Returns total file size of all cached files
[ "Returns", "total", "file", "size", "of", "all", "cached", "files" ]
def total_file_size(self) -> int: return self._file_hash_cache.total_file_size
[ "def", "total_file_size", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_file_hash_cache", ".", "total_file_size" ]
Returns total file size of all cached files
[ "Returns", "total", "file", "size", "of", "all", "cached", "files" ]
[ "\"\"\"Returns total file size of all cached files\n\n :return: total file size of all cached files\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "total file size of all cached files", "docstring_tokens": [ "total", "file", "size", "of", "all", "cached", "files" ], "type": null } ], "raises": [], "params": [ { "identifier": "sel...
654569d4750f8c671c919f1def63c1bd9e70b403
MarcinOrlowski/dhunter
dhunter/core/dir_hash.py
[ "MIT" ]
Python
from_json
None
def from_json(self, json_string) -> None: """Populates instance of FileHash with data from JSON object string :param str json_string: """ self.__dict__ = json.loads(json_string) self._file_hash_cache = FileHashCache(self.path, self._config)
Populates instance of FileHash with data from JSON object string :param str json_string:
Populates instance of FileHash with data from JSON object string
[ "Populates", "instance", "of", "FileHash", "with", "data", "from", "JSON", "object", "string" ]
def from_json(self, json_string) -> None: self.__dict__ = json.loads(json_string) self._file_hash_cache = FileHashCache(self.path, self._config)
[ "def", "from_json", "(", "self", ",", "json_string", ")", "->", "None", ":", "self", ".", "__dict__", "=", "json", ".", "loads", "(", "json_string", ")", "self", ".", "_file_hash_cache", "=", "FileHashCache", "(", "self", ".", "path", ",", "self", ".", ...
Populates instance of FileHash with data from JSON object string
[ "Populates", "instance", "of", "FileHash", "with", "data", "from", "JSON", "object", "string" ]
[ "\"\"\"Populates instance of FileHash with data from JSON object string\n\n :param str json_string:\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "json_string", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "json_string", "type": null, "docstring": null, "docstring_tok...
ab7b2d9263c91bfed42341a987b28580979d2a25
MarcinOrlowski/dhunter
dhunter/core/file_hash.py
[ "MIT" ]
Python
calculate_hash
None
def calculate_hash(self) -> None: """Calculates hash for given file of this FileHash object. :raises FileNotFoundError :raises OSError """ if self.name is None: raise OSError('File name cannot be None') elif self.path is None: raise OSError('File ...
Calculates hash for given file of this FileHash object. :raises FileNotFoundError :raises OSError
Calculates hash for given file of this FileHash object.
[ "Calculates", "hash", "for", "given", "file", "of", "this", "FileHash", "object", "." ]
def calculate_hash(self) -> None: if self.name is None: raise OSError('File name cannot be None') elif self.path is None: raise OSError('File path cannot be None') if not os.path.exists(self.path): raise FileNotFoundError('"{name}" not found'.format(name=self....
[ "def", "calculate_hash", "(", "self", ")", "->", "None", ":", "if", "self", ".", "name", "is", "None", ":", "raise", "OSError", "(", "'File name cannot be None'", ")", "elif", "self", ".", "path", "is", "None", ":", "raise", "OSError", "(", "'File path can...
Calculates hash for given file of this FileHash object.
[ "Calculates", "hash", "for", "given", "file", "of", "this", "FileHash", "object", "." ]
[ "\"\"\"Calculates hash for given file of this FileHash object.\n\n :raises FileNotFoundError\n :raises OSError\n \"\"\"", "# if self.size > (1024 * 1024 * 10):", "# cmd = ['nice', '-n', str(5)]", "# hash is always plain hex string. No need for utf-8 here, esp. it ends up in JSON files...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ab7b2d9263c91bfed42341a987b28580979d2a25
MarcinOrlowski/dhunter
dhunter/core/file_hash.py
[ "MIT" ]
Python
from_json
None
def from_json(self, json_string: str) -> None: """Populates instance of FileHash with data from JSON object string. """ tmp = json.loads(json_string) for field in self._json_keys: self.__setattr__(field, tmp.get(field)) self.hash_time_seconds = 0
Populates instance of FileHash with data from JSON object string.
Populates instance of FileHash with data from JSON object string.
[ "Populates", "instance", "of", "FileHash", "with", "data", "from", "JSON", "object", "string", "." ]
def from_json(self, json_string: str) -> None: tmp = json.loads(json_string) for field in self._json_keys: self.__setattr__(field, tmp.get(field)) self.hash_time_seconds = 0
[ "def", "from_json", "(", "self", ",", "json_string", ":", "str", ")", "->", "None", ":", "tmp", "=", "json", ".", "loads", "(", "json_string", ")", "for", "field", "in", "self", ".", "_json_keys", ":", "self", ".", "__setattr__", "(", "field", ",", "...
Populates instance of FileHash with data from JSON object string.
[ "Populates", "instance", "of", "FileHash", "with", "data", "from", "JSON", "object", "string", "." ]
[ "\"\"\"Populates instance of FileHash with data from JSON object string.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "json_string", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "json_string", "type": "str", "docstring": null, "docstring_to...
ca4d9d54315e75c27a4af0864b751677ec16b7b3
MarcinOrlowski/dhunter
dhunter/core/hash_base.py
[ "MIT" ]
Python
json_data_valid
bool
def json_data_valid(self, json_dict: dict) -> bool: """Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class """ result = False data_type = json_dict.get(Const.FIELD_TYPE) version = json_dict.get(Const.FIELD_VERSION) if da...
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
[ "Checks", "if", "given", "dict", "structure", "based", "on", "loaded", "JSON", "data", "matches", "requirements", "and", "is", "dump", "of", "our", "class" ]
def json_data_valid(self, json_dict: dict) -> bool: result = False data_type = json_dict.get(Const.FIELD_TYPE) version = json_dict.get(Const.FIELD_VERSION) if data_type is not None and version is not None: result = data_type == self.data_type and version <= self.data_version ...
[ "def", "json_data_valid", "(", "self", ",", "json_dict", ":", "dict", ")", "->", "bool", ":", "result", "=", "False", "data_type", "=", "json_dict", ".", "get", "(", "Const", ".", "FIELD_TYPE", ")", "version", "=", "json_dict", ".", "get", "(", "Const", ...
Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class
[ "Checks", "if", "given", "dict", "structure", "based", "on", "loaded", "JSON", "data", "matches", "requirements", "and", "is", "dump", "of", "our", "class" ]
[ "\"\"\"Checks if given dict structure based on loaded JSON data matches requirements and is dump of our class\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "json_dict", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "json_dict", "type": "dict", "docstring": null, "docstring_tok...
28ec9a33bc55560693b0e59dfd4a14ea9a75b5cc
MarcinOrlowski/dhunter
dhunter/core/log.py
[ "MIT" ]
Python
strip_ansi
<not_specific>
def strip_ansi(message): """Removes all ANSI control codes from given message string Args: message: string to be processed Returns: message string witn ANSI codes striped or None """ if message is not None: pattern = re.compile(r'\x1B\[[0-?]*[ -/...
Removes all ANSI control codes from given message string Args: message: string to be processed Returns: message string witn ANSI codes striped or None
Removes all ANSI control codes from given message string
[ "Removes", "all", "ANSI", "control", "codes", "from", "given", "message", "string" ]
def strip_ansi(message): if message is not None: pattern = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') return pattern.sub('', message) return ''
[ "def", "strip_ansi", "(", "message", ")", ":", "if", "message", "is", "not", "None", ":", "pattern", "=", "re", ".", "compile", "(", "r'\\x1B\\[[0-?]*[ -/]*[@-~]'", ")", "return", "pattern", ".", "sub", "(", "''", ",", "message", ")", "return", "''" ]
Removes all ANSI control codes from given message string
[ "Removes", "all", "ANSI", "control", "codes", "from", "given", "message", "string" ]
[ "\"\"\"Removes all ANSI control codes from given message string\n\n Args:\n message: string to be processed\n\n Returns:\n message string witn ANSI codes striped or None\n \"\"\"" ]
[ { "param": "message", "type": null } ]
{ "returns": [ { "docstring": "message string witn ANSI codes striped or None", "docstring_tokens": [ "message", "string", "witn", "ANSI", "codes", "striped", "or", "None" ], "type": null } ], "raises": [], "params":...