Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ReconfigStats.__init__
(self, logger: logging.Logger, max_incr_between_checks=100, max_time_between_checks=600, max_config_between_timers=10, max_time_between_timers=120 )
Initialize this ReconfigStats. :param max_incr_between_checks: Maximum number of outstanding incrementals before a sanity check :param max_time_between_checks: Maximum number of seconds between sanity checks :param max_config_between_timers: Maximum number of configurations before logg...
Initialize this ReconfigStats.
def __init__(self, logger: logging.Logger, max_incr_between_checks=100, max_time_between_checks=600, max_config_between_timers=10, max_time_between_timers=120 ) -> None: """ Initialize this ReconfigStats. :param max_incr_between_checks: Maximum ...
[ "def", "__init__", "(", "self", ",", "logger", ":", "logging", ".", "Logger", ",", "max_incr_between_checks", "=", "100", ",", "max_time_between_checks", "=", "600", ",", "max_config_between_timers", "=", "10", ",", "max_time_between_timers", "=", "120", ")", "-...
[ 31, 4 ]
[ 84, 23 ]
python
en
['en', 'error', 'th']
False
ReconfigStats.mark
(self, what: str, when: Optional[PerfCounter]=None)
Mark that a reconfigure has occurred. The 'what' parameter is one of "complete" for a complete reconfigure, "incremental" for an incremental, or "diag" to indicate that we're not really reconfiguring, we just generated the diagnostics so may need to log timers. :param what: "co...
Mark that a reconfigure has occurred. The 'what' parameter is one of "complete" for a complete reconfigure, "incremental" for an incremental, or "diag" to indicate that we're not really reconfiguring, we just generated the diagnostics so may need to log timers.
def mark(self, what: str, when: Optional[PerfCounter]=None) -> None: """ Mark that a reconfigure has occurred. The 'what' parameter is one of "complete" for a complete reconfigure, "incremental" for an incremental, or "diag" to indicate that we're not really reconfiguring, we just genera...
[ "def", "mark", "(", "self", ",", "what", ":", "str", ",", "when", ":", "Optional", "[", "PerfCounter", "]", "=", "None", ")", "->", "None", ":", "if", "not", "when", ":", "when", "=", "time", ".", "perf_counter", "(", ")", "if", "(", "what", "=="...
[ 86, 4 ]
[ 143, 37 ]
python
en
['en', 'error', 'th']
False
ReconfigStats.needs_check
(self, when: Optional[PerfCounter]=None)
Determine if we need to do a complete reconfigure to doublecheck our incrementals. The logic here is that we need a check every 100 incrementals or every 10 minutes, whichever comes first. :param when: Override the effective time of the check. Primarily useful for testing. :ret...
Determine if we need to do a complete reconfigure to doublecheck our incrementals. The logic here is that we need a check every 100 incrementals or every 10 minutes, whichever comes first.
def needs_check(self, when: Optional[PerfCounter]=None) -> bool: """ Determine if we need to do a complete reconfigure to doublecheck our incrementals. The logic here is that we need a check every 100 incrementals or every 10 minutes, whichever comes first. :param when: Override...
[ "def", "needs_check", "(", "self", ",", "when", ":", "Optional", "[", "PerfCounter", "]", "=", "None", ")", "->", "bool", ":", "if", "not", "when", ":", "when", "=", "time", ".", "perf_counter", "(", ")", "if", "len", "(", "self", ".", "reconfigures"...
[ 145, 4 ]
[ 201, 20 ]
python
en
['en', 'error', 'th']
False
ReconfigStats.needs_timers
(self, when: Optional[PerfCounter]=None)
Determine if we need to log the timers or not. The logic here is that we need to log every max_configs_between_timers incrementals or every or every max_time_between_timers seconds, whichever comes first. :param when: Override the effective time of the check. Primarily useful for test...
Determine if we need to log the timers or not. The logic here is that we need to log every max_configs_between_timers incrementals or every or every max_time_between_timers seconds, whichever comes first.
def needs_timers(self, when: Optional[PerfCounter]=None) -> bool: """ Determine if we need to log the timers or not. The logic here is that we need to log every max_configs_between_timers incrementals or every or every max_time_between_timers seconds, whichever comes first. :pa...
[ "def", "needs_timers", "(", "self", ",", "when", ":", "Optional", "[", "PerfCounter", "]", "=", "None", ")", "->", "bool", ":", "if", "not", "when", ":", "when", "=", "time", ".", "perf_counter", "(", ")", "if", "len", "(", "self", ".", "reconfigures...
[ 203, 4 ]
[ 250, 20 ]
python
en
['en', 'error', 'th']
False
ReconfigStats.mark_checked
(self, result: bool, when: Optional[PerfCounter]=None)
Mark that we have done a check, and note the results. This resets our outstanding incrementals to 0, and also resets our last check time. :param result: True if the check was good, False if not :param when: Override the effective time. Primarily useful for testing.
Mark that we have done a check, and note the results. This resets our outstanding incrementals to 0, and also resets our last check time.
def mark_checked(self, result: bool, when: Optional[PerfCounter]=None) -> None: """ Mark that we have done a check, and note the results. This resets our outstanding incrementals to 0, and also resets our last check time. :param result: True if the check was good, False if not :...
[ "def", "mark_checked", "(", "self", ",", "result", ":", "bool", ",", "when", ":", "Optional", "[", "PerfCounter", "]", "=", "None", ")", "->", "None", ":", "self", ".", "logger", ".", "debug", "(", "f\"MARK_CHECKED @ {when}: {result}\"", ")", "self", ".", ...
[ 252, 4 ]
[ 269, 53 ]
python
en
['en', 'error', 'th']
False
ReconfigStats.mark_timers_logged
(self, when: Optional[PerfCounter]=None)
Mark that we have logged timers. This resets our outstanding configurations to 0, and also resets our last timer log time. :param when: Override the effective time. Primarily useful for testing.
Mark that we have logged timers. This resets our outstanding configurations to 0, and also resets our last timer log time.
def mark_timers_logged(self, when: Optional[PerfCounter]=None) -> None: """ Mark that we have logged timers. This resets our outstanding configurations to 0, and also resets our last timer log time. :param when: Override the effective time. Primarily useful for testing. """ ...
[ "def", "mark_timers_logged", "(", "self", ",", "when", ":", "Optional", "[", "PerfCounter", "]", "=", "None", ")", "->", "None", ":", "self", ".", "logger", ".", "debug", "(", "f\"MARK_TIMERS @ {when}\"", ")", "self", ".", "configs_outstanding", "=", "0", ...
[ 271, 4 ]
[ 282, 57 ]
python
en
['en', 'error', 'th']
False
xarray_values_in
(data, values, data_vars=None)
Returns a mask for an xarray Dataset or DataArray, with `True` wherever the value is in values. Parameters ---------- data: xarray.Dataset or xarray.DataArray The data to check for value matches. values: list-like The values to check for. data_vars: list-like The names ...
Returns a mask for an xarray Dataset or DataArray, with `True` wherever the value is in values.
def xarray_values_in(data, values, data_vars=None): """ Returns a mask for an xarray Dataset or DataArray, with `True` wherever the value is in values. Parameters ---------- data: xarray.Dataset or xarray.DataArray The data to check for value matches. values: list-like The value...
[ "def", "xarray_values_in", "(", "data", ",", "values", ",", "data_vars", "=", "None", ")", ":", "data_vars_to_check", "=", "data_vars", "if", "data_vars", "is", "not", "None", "else", "list", "(", "data", ".", "data_vars", ".", "keys", "(", ")", ")", "if...
[ 8, 0 ]
[ 37, 15 ]
python
en
['en', 'error', 'th']
False
create_2D_mosaic_clean_mask
(clean_mask)
The clean mask of a mosaic should be determined by the compositing function (e.g. mean mosaic, median mosaic, etc.). This is simply supposed to be a decent approximation of a clean mask for a mosaic that has no time dimension. Parameters ---------- clean_mask: np.ndarray The 3D c...
The clean mask of a mosaic should be determined by the compositing function (e.g. mean mosaic, median mosaic, etc.). This is simply supposed to be a decent approximation of a clean mask for a mosaic that has no time dimension. Parameters ---------- clean_mask: np.ndarray The 3D c...
def create_2D_mosaic_clean_mask(clean_mask): """ The clean mask of a mosaic should be determined by the compositing function (e.g. mean mosaic, median mosaic, etc.). This is simply supposed to be a decent approximation of a clean mask for a mosaic that has no time dimension. Parameters --...
[ "def", "create_2D_mosaic_clean_mask", "(", "clean_mask", ")", ":", "mosaic_clean_mask", "=", "clean_mask", "[", "0", "]", "# Take the logical OR of clean masks through time.", "for", "i", "in", "range", "(", "1", ",", "clean_mask", ".", "shape", "[", "0", "]", ")"...
[ 43, 0 ]
[ 63, 28 ]
python
en
['en', 'error', 'th']
False
create_circular_mask
(h, w, center=None, radius=None)
Creates a NumPy array mask with a circle. Credit goes to https://stackoverflow.com/a/44874588/5449970. Parameters ---------- h, w: int The height and width of the data to mask, respectively. center: 2-tuple of int The center of the circle, specified as a 2-tuple of the x and y ...
Creates a NumPy array mask with a circle. Credit goes to https://stackoverflow.com/a/44874588/5449970.
def create_circular_mask(h, w, center=None, radius=None): """ Creates a NumPy array mask with a circle. Credit goes to https://stackoverflow.com/a/44874588/5449970. Parameters ---------- h, w: int The height and width of the data to mask, respectively. center: 2-tuple of int ...
[ "def", "create_circular_mask", "(", "h", ",", "w", ",", "center", "=", "None", ",", "radius", "=", "None", ")", ":", "if", "center", "is", "None", ":", "# use the middle of the image", "center", "=", "[", "int", "(", "w", "/", "2", ")", ",", "int", "...
[ 65, 0 ]
[ 96, 15 ]
python
en
['en', 'error', 'th']
False
landsat_clean_mask_invalid
(dataset)
Masks out invalid data according to the LANDSAT surface reflectance specifications. See this document: https://landsat.usgs.gov/sites/default/files/documents/ledaps_product_guide.pdf pages 19-20. Parameters ---------- dataset: xarray.Dataset An `xarray.Dataset` containing bands such as...
Masks out invalid data according to the LANDSAT surface reflectance specifications. See this document: https://landsat.usgs.gov/sites/default/files/documents/ledaps_product_guide.pdf pages 19-20.
def landsat_clean_mask_invalid(dataset): """ Masks out invalid data according to the LANDSAT surface reflectance specifications. See this document: https://landsat.usgs.gov/sites/default/files/documents/ledaps_product_guide.pdf pages 19-20. Parameters ---------- dataset: xarray.Dataset ...
[ "def", "landsat_clean_mask_invalid", "(", "dataset", ")", ":", "invalid_mask", "=", "None", "data_arr_names", "=", "[", "arr_name", "for", "arr_name", "in", "list", "(", "dataset", ".", "data_vars", ")", "if", "arr_name", "not", "in", "[", "'pixel_qa'", ",", ...
[ 102, 0 ]
[ 126, 23 ]
python
en
['en', 'error', 'th']
False
landsat_qa_clean_mask
(dataset, platform, cover_types=['clear', 'water'])
Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Landsat pixel_qa band. Note that Landsat masks specify what to keep, not what to remove. This means that using `cover_types=['clear', 'water']` should keep only clear land and water. See "pixel_qa band" here: ht...
Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Landsat pixel_qa band. Note that Landsat masks specify what to keep, not what to remove. This means that using `cover_types=['clear', 'water']` should keep only clear land and water.
def landsat_qa_clean_mask(dataset, platform, cover_types=['clear', 'water']): """ Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Landsat pixel_qa band. Note that Landsat masks specify what to keep, not what to remove. This means that using `cover_types=['clear...
[ "def", "landsat_qa_clean_mask", "(", "dataset", ",", "platform", ",", "cover_types", "=", "[", "'clear'", ",", "'water'", "]", ")", ":", "processing_options", "=", "{", "\"LANDSAT_5\"", ":", "ls5_unpack_qa", ",", "\"LANDSAT_7\"", ":", "ls7_unpack_qa", ",", "\"LA...
[ 129, 0 ]
[ 181, 21 ]
python
en
['en', 'error', 'th']
False
sentinel2_fmask_clean_mask
(dataset, cover_types=['valid', 'water'])
Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Sentinel 2 fmask band. Note that clean masks specify what to keep, not what to remove. This means that using `cover_types=['valid', 'water']` should keep only clear land and water. See "Classification Mask Gener...
Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Sentinel 2 fmask band. Note that clean masks specify what to keep, not what to remove. This means that using `cover_types=['valid', 'water']` should keep only clear land and water.
def sentinel2_fmask_clean_mask(dataset, cover_types=['valid', 'water']): """ Returns a clean_mask for `dataset` that masks out various types of terrain cover using the Sentinel 2 fmask band. Note that clean masks specify what to keep, not what to remove. This means that using `cover_types=['valid', 'wat...
[ "def", "sentinel2_fmask_clean_mask", "(", "dataset", ",", "cover_types", "=", "[", "'valid'", ",", "'water'", "]", ")", ":", "fmask_table", "=", "{", "'null'", ":", "0", ",", "'valid'", ":", "1", ",", "'cloud'", ":", "2", ",", "'cloud_shadow'", ":", "3",...
[ 187, 0 ]
[ 231, 21 ]
python
en
['en', 'error', 'th']
False
index_entry_t.__init__
(self, filesigs, configsig)
:param filesigs: a list of tuples( `fileid`, `sig`)... :param configsig: the signature of the configuration object.
:param filesigs: a list of tuples( `fileid`, `sig`)... :param configsig: the signature of the configuration object.
def __init__(self, filesigs, configsig): """ :param filesigs: a list of tuples( `fileid`, `sig`)... :param configsig: the signature of the configuration object. """ self.filesigs = filesigs self.configsig = configsig
[ "def", "__init__", "(", "self", ",", "filesigs", ",", "configsig", ")", ":", "self", ".", "filesigs", "=", "filesigs", "self", ".", "configsig", "=", "configsig" ]
[ 43, 4 ]
[ 50, 34 ]
python
en
['en', 'error', 'th']
False
directory_cache_t.__init__
( self, dir="cache", directory="cache", compression=False, sha1_sigs=True)
:param dir: cache directory path, it is created, if it does not exist :param compression: if `True`, the cache files will be compressed using `gzip` :param sha1_sigs: `sha1_sigs` determines whether file modifications is checked by computing...
:param dir: cache directory path, it is created, if it does not exist
def __init__( self, dir="cache", directory="cache", compression=False, sha1_sigs=True): """ :param dir: cache directory path, it is created, if it does not exist :param compression: if `True`, the cache files will be compressed using `gzip` ...
[ "def", "__init__", "(", "self", ",", "dir", "=", "\"cache\"", ",", "directory", "=", "\"cache\"", ",", "compression", "=", "False", ",", "sha1_sigs", "=", "True", ")", ":", "if", "dir", "!=", "\"cache\"", ":", "# Somebody explicitly set a different value for dir...
[ 73, 4 ]
[ 131, 32 ]
python
en
['en', 'error', 'th']
False
directory_cache_t.flush
(self)
Save the index table to disk.
Save the index table to disk.
def flush(self): """Save the index table to disk.""" self._save()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_save", "(", ")" ]
[ 133, 4 ]
[ 135, 20 ]
python
en
['en', 'en', 'en']
True
directory_cache_t.update
(self, source_file, configuration, declarations, included_files)
Replace a cache entry by a new value. :param source_file: a C++ source file name. :type source_file: str :param configuration: configuration object. :type configuration: :class:`xml_generator_configuration_t` :param declarations: declarations contained in the `source_file` ...
Replace a cache entry by a new value.
def update(self, source_file, configuration, declarations, included_files): """Replace a cache entry by a new value. :param source_file: a C++ source file name. :type source_file: str :param configuration: configuration object. :type configuration: :class:`xml_generator_configu...
[ "def", "update", "(", "self", ",", "source_file", ",", "configuration", ",", "declarations", ",", "included_files", ")", ":", "# Normlize all paths...", "source_file", "=", "os", ".", "path", ".", "normpath", "(", "source_file", ")", "included_files", "=", "[", ...
[ 137, 4 ]
[ 181, 53 ]
python
en
['en', 'en', 'en']
True
directory_cache_t.cached_value
(self, source_file, configuration)
Return the cached declarations or None. :param source_file: Header file name :type source_file: str :param configuration: Configuration object :type configuration: :class:`parser.xml_generator_configuration_t` :rtype: Cached declarations or None
Return the cached declarations or None.
def cached_value(self, source_file, configuration): """Return the cached declarations or None. :param source_file: Header file name :type source_file: str :param configuration: Configuration object :type configuration: :class:`parser.xml_generator_configuration_t` :rtype...
[ "def", "cached_value", "(", "self", ",", "source_file", ",", "configuration", ")", ":", "# Check if the cache contains an entry for source_file", "key", "=", "self", ".", "_create_cache_key", "(", "source_file", ")", "entry", "=", "self", ".", "__index", ".", "get",...
[ 183, 4 ]
[ 227, 20 ]
python
en
['en', 'en', 'en']
True
directory_cache_t._load
(self)
Load the cache. Loads the `index.dat` file, which contains the index table and the file name repository. This method is called by the :meth:`__init__`
Load the cache.
def _load(self): """Load the cache. Loads the `index.dat` file, which contains the index table and the file name repository. This method is called by the :meth:`__init__` """ indexfilename = os.path.join(self.__dir, "index.dat") if os.path.exists(indexfilename)...
[ "def", "_load", "(", "self", ")", ":", "indexfilename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "\"index.dat\"", ")", "if", "os", ".", "path", ".", "exists", "(", "indexfilename", ")", ":", "data", "=", "self", ".", "_r...
[ 229, 4 ]
[ 253, 36 ]
python
en
['en', 'it', 'en']
True
directory_cache_t._save
(self)
save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat`
save the cache index, in case it was modified.
def _save(self): """ save the cache index, in case it was modified. Saves the index table and the file name repository in the file `index.dat` """ if self.__modified_flag: self.__filename_rep.update_id_counter() indexfilename = os.path.join(self....
[ "def", "_save", "(", "self", ")", ":", "if", "self", ".", "__modified_flag", ":", "self", ".", "__filename_rep", ".", "update_id_counter", "(", ")", "indexfilename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "\"index.dat\"", ")...
[ 255, 4 ]
[ 271, 40 ]
python
en
['en', 'error', 'th']
False
directory_cache_t._read_file
(self, filename)
read a Python object from a cache file. Reads a pickled object from disk and returns it. :param filename: Name of the file that should be read. :type filename: str :rtype: object
read a Python object from a cache file.
def _read_file(self, filename): """ read a Python object from a cache file. Reads a pickled object from disk and returns it. :param filename: Name of the file that should be read. :type filename: str :rtype: object """ if self.__compression: ...
[ "def", "_read_file", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "__compression", ":", "f", "=", "gzip", ".", "GzipFile", "(", "filename", ",", "\"rb\"", ")", "else", ":", "f", "=", "open", "(", "filename", ",", "\"rb\"", ")", "res", ...
[ 273, 4 ]
[ 290, 18 ]
python
en
['en', 'error', 'th']
False
directory_cache_t._write_file
(self, filename, data)
Write a data item into a file. The data object is written to a file using the pickle mechanism. :param filename: Output file name :type filename: str :param data: A Python object that will be pickled
Write a data item into a file.
def _write_file(self, filename, data): """Write a data item into a file. The data object is written to a file using the pickle mechanism. :param filename: Output file name :type filename: str :param data: A Python object that will be pickled """ if self.__compr...
[ "def", "_write_file", "(", "self", ",", "filename", ",", "data", ")", ":", "if", "self", ".", "__compression", ":", "f", "=", "gzip", ".", "GzipFile", "(", "filename", ",", "\"wb\"", ")", "else", ":", "f", "=", "open", "(", "filename", ",", "\"wb\"",...
[ 292, 4 ]
[ 307, 17 ]
python
en
['it', 'en', 'en']
True
directory_cache_t._remove_entry
(self, source_file, key)
Remove an entry from the cache. source_file is the name of the header and key is its corresponding cache key (obtained by a call to :meth:_create_cache_key ). The entry is removed from the index table, any referenced file name is released and the cache file is deleted. If key r...
Remove an entry from the cache.
def _remove_entry(self, source_file, key): """Remove an entry from the cache. source_file is the name of the header and key is its corresponding cache key (obtained by a call to :meth:_create_cache_key ). The entry is removed from the index table, any referenced file name is rel...
[ "def", "_remove_entry", "(", "self", ",", "source_file", ",", "key", ")", ":", "entry", "=", "self", ".", "__index", ".", "get", "(", "key", ")", "if", "entry", "is", "None", ":", "return", "# Release the referenced files...", "for", "id_", ",", "_", "in...
[ 309, 4 ]
[ 343, 57 ]
python
en
['en', 'en', 'en']
True
directory_cache_t._create_cache_key
(source_file)
return the cache key for a header file. :param source_file: Header file name :type source_file: str :rtype: str
return the cache key for a header file.
def _create_cache_key(source_file): """ return the cache key for a header file. :param source_file: Header file name :type source_file: str :rtype: str """ path, name = os.path.split(source_file) return name + str(hash(path))
[ "def", "_create_cache_key", "(", "source_file", ")", ":", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "source_file", ")", "return", "name", "+", "str", "(", "hash", "(", "path", ")", ")" ]
[ 346, 4 ]
[ 355, 37 ]
python
en
['en', 'error', 'th']
False
directory_cache_t._create_cache_filename
(self, source_file)
return the cache file name for a header file. :param source_file: Header file name :type source_file: str :rtype: str
return the cache file name for a header file.
def _create_cache_filename(self, source_file): """ return the cache file name for a header file. :param source_file: Header file name :type source_file: str :rtype: str """ res = self._create_cache_key(source_file) + ".cache" return os.path.join(self.__di...
[ "def", "_create_cache_filename", "(", "self", ",", "source_file", ")", ":", "res", "=", "self", ".", "_create_cache_key", "(", "source_file", ")", "+", "\".cache\"", "return", "os", ".", "path", ".", "join", "(", "self", ".", "__dir", ",", "res", ")" ]
[ 357, 4 ]
[ 366, 44 ]
python
en
['en', 'error', 'th']
False
directory_cache_t._create_config_signature
(config)
return the signature for a config object. The signature is computed as sha1 digest of the contents of working_directory, include_paths, define_symbols and undefine_symbols. :param config: Configuration object :type config: :class:`parser.xml_generator_configuration_t` ...
return the signature for a config object.
def _create_config_signature(config): """ return the signature for a config object. The signature is computed as sha1 digest of the contents of working_directory, include_paths, define_symbols and undefine_symbols. :param config: Configuration object :type confi...
[ "def", "_create_config_signature", "(", "config", ")", ":", "m", "=", "hashlib", ".", "sha1", "(", ")", "m", ".", "update", "(", "config", ".", "working_directory", ".", "encode", "(", "\"utf-8\"", ")", ")", "for", "p", "in", "config", ".", "include_path...
[ 369, 4 ]
[ 391, 25 ]
python
en
['en', 'error', 'th']
False
filename_entry_t.__init__
(self, filename)
Constructor. The reference count is initially set to 0.
Constructor.
def __init__(self, filename): """Constructor. The reference count is initially set to 0. """ # Filename self.filename = filename # Reference count self.refcount = 0 # Cached signature value for the file. # If sig_valid flag is False, the signatur...
[ "def", "__init__", "(", "self", ",", "filename", ")", ":", "# Filename", "self", ".", "filename", "=", "filename", "# Reference count", "self", ".", "refcount", "=", "0", "# Cached signature value for the file.", "# If sig_valid flag is False, the signature still has to be ...
[ 403, 4 ]
[ 418, 29 ]
python
en
['en', 'en', 'en']
False
filename_entry_t.inc_ref_count
(self)
Increase the reference count by 1.
Increase the reference count by 1.
def inc_ref_count(self): """Increase the reference count by 1.""" self.refcount += 1
[ "def", "inc_ref_count", "(", "self", ")", ":", "self", ".", "refcount", "+=", "1" ]
[ 429, 4 ]
[ 432, 26 ]
python
en
['en', 'en', 'en']
True
filename_entry_t.dec_ref_count
(self)
Decrease the reference count by 1 and return the new count.
Decrease the reference count by 1 and return the new count.
def dec_ref_count(self): """Decrease the reference count by 1 and return the new count.""" self.refcount -= 1 return self.refcount
[ "def", "dec_ref_count", "(", "self", ")", ":", "self", ".", "refcount", "-=", "1", "return", "self", ".", "refcount" ]
[ 434, 4 ]
[ 438, 28 ]
python
en
['en', 'en', 'en']
True
filename_repository_t.__init__
(self, sha1_sigs)
Constructor.
Constructor.
def __init__(self, sha1_sigs): """Constructor. """ # Flag that determines whether the signature is a sha1 digest or # the modification time # (this flag is passed to the filename_repository_t class) self._sha1_sigs = sha1_sigs # ID lookup table (key: filename / ...
[ "def", "__init__", "(", "self", ",", "sha1_sigs", ")", ":", "# Flag that determines whether the signature is a sha1 digest or", "# the modification time", "# (this flag is passed to the filename_repository_t class)", "self", ".", "_sha1_sigs", "=", "sha1_sigs", "# ID lookup table (ke...
[ 454, 4 ]
[ 474, 26 ]
python
en
['en', 'en', 'en']
False
filename_repository_t.acquire_filename
(self, name)
Acquire a file name and return its id and its signature.
Acquire a file name and return its id and its signature.
def acquire_filename(self, name): """Acquire a file name and return its id and its signature. """ id_ = self.__id_lut.get(name) # Is this a new entry? if id_ is None: # then create one... id_ = self.__next_id self.__next_id += 1 se...
[ "def", "acquire_filename", "(", "self", ",", "name", ")", ":", "id_", "=", "self", ".", "__id_lut", ".", "get", "(", "name", ")", "# Is this a new entry?", "if", "id_", "is", "None", ":", "# then create one...", "id_", "=", "self", ".", "__next_id", "self"...
[ 476, 4 ]
[ 494, 46 ]
python
en
['en', 'en', 'en']
True
filename_repository_t.release_filename
(self, id_)
Release a file name.
Release a file name.
def release_filename(self, id_): """Release a file name. """ entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id (%d)" % id_) # Decrease reference count and check if the entry has to be removed... if entry.dec_ref_count() ...
[ "def", "release_filename", "(", "self", ",", "id_", ")", ":", "entry", "=", "self", ".", "__entries", ".", "get", "(", "id_", ")", "if", "entry", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid filename id (%d)\"", "%", "id_", ")", "# Decrease re...
[ 496, 4 ]
[ 507, 45 ]
python
en
['en', 'en', 'en']
True
filename_repository_t.is_file_modified
(self, id_, signature)
Check if the file referred to by `id_` has been modified.
Check if the file referred to by `id_` has been modified.
def is_file_modified(self, id_, signature): """Check if the file referred to by `id_` has been modified. """ entry = self.__entries.get(id_) if entry is None: raise ValueError("Invalid filename id_ (%d)" % id_) # Is the signature already known? if entry.sig_...
[ "def", "is_file_modified", "(", "self", ",", "id_", ",", "signature", ")", ":", "entry", "=", "self", ".", "__entries", ".", "get", "(", "id_", ")", "if", "entry", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid filename id_ (%d)\"", "%", "id_", ...
[ 509, 4 ]
[ 527, 35 ]
python
en
['en', 'en', 'en']
True
filename_repository_t.update_id_counter
(self)
Update the `id_` counter so that it doesn't grow forever.
Update the `id_` counter so that it doesn't grow forever.
def update_id_counter(self): """Update the `id_` counter so that it doesn't grow forever. """ if not self.__entries: self.__next_id = 1 else: self.__next_id = max(self.__entries.keys()) + 1
[ "def", "update_id_counter", "(", "self", ")", ":", "if", "not", "self", ".", "__entries", ":", "self", ".", "__next_id", "=", "1", "else", ":", "self", ".", "__next_id", "=", "max", "(", "self", ".", "__entries", ".", "keys", "(", ")", ")", "+", "1...
[ 529, 4 ]
[ 536, 59 ]
python
en
['en', 'en', 'en']
True
filename_repository_t._get_signature
(self, entry)
Return the signature of the file stored in entry.
Return the signature of the file stored in entry.
def _get_signature(self, entry): """Return the signature of the file stored in entry. """ if self._sha1_sigs: # return sha1 digest of the file content... if not os.path.exists(entry.filename): return None try: with open(entry.f...
[ "def", "_get_signature", "(", "self", ",", "entry", ")", ":", "if", "self", ".", "_sha1_sigs", ":", "# return sha1 digest of the file content...", "if", "not", "os", ".", "path", ".", "exists", "(", "entry", ".", "filename", ")", ":", "return", "None", "try"...
[ 538, 4 ]
[ 558, 27 ]
python
en
['en', 'en', 'en']
True
filename_repository_t._dump
(self)
Dump contents for debugging/testing.
Dump contents for debugging/testing.
def _dump(self): # pragma: no cover """ Dump contents for debugging/testing. """ print(70 * "-") print("ID lookup table:") for name in self.__id_lut: id_ = self.__id_lut[name] print(" %s -> %d" % (name, id_)) print(70 * "-") pri...
[ "def", "_dump", "(", "self", ")", ":", "# pragma: no cover", "print", "(", "70", "*", "\"-\"", ")", "print", "(", "\"ID lookup table:\"", ")", "for", "name", "in", "self", ".", "__id_lut", ":", "id_", "=", "self", ".", "__id_lut", "[", "name", "]", "pr...
[ 560, 4 ]
[ 576, 74 ]
python
en
['en', 'error', 'th']
False
DatabaseStoreBackend.store_backend_id
(self)
Create a store_backend_id if one does not exist, and return it if it exists Ephemeral store_backend_id for database_store_backend until there is a place to store metadata Returns: store_backend_id which is a UUID(version=4)
Create a store_backend_id if one does not exist, and return it if it exists Ephemeral store_backend_id for database_store_backend until there is a place to store metadata Returns: store_backend_id which is a UUID(version=4)
def store_backend_id(self) -> str: """ Create a store_backend_id if one does not exist, and return it if it exists Ephemeral store_backend_id for database_store_backend until there is a place to store metadata Returns: store_backend_id which is a UUID(version=4) """ ...
[ "def", "store_backend_id", "(", "self", ")", "->", "str", ":", "if", "not", "self", ".", "_store_backend_id", ":", "store_id", "=", "(", "self", ".", "_manually_initialize_store_backend_id", "if", "self", ".", "_manually_initialize_store_backend_id", "else", "str", ...
[ 146, 4 ]
[ 161, 79 ]
python
en
['en', 'error', 'th']
False
DatabaseStoreBackend._build_engine
(self, credentials, **kwargs)
Using a set of given credentials, constructs an Execution Engine , connecting to a database using a URL or a private key path.
Using a set of given credentials, constructs an Execution Engine , connecting to a database using a URL or a private key path.
def _build_engine(self, credentials, **kwargs) -> "sa.engine.Engine": """ Using a set of given credentials, constructs an Execution Engine , connecting to a database using a URL or a private key path. """ # Update credentials with anything passed during connection time dr...
[ "def", "_build_engine", "(", "self", ",", "credentials", ",", "*", "*", "kwargs", ")", "->", "\"sa.engine.Engine\"", ":", "# Update credentials with anything passed during connection time", "drivername", "=", "credentials", ".", "pop", "(", "\"drivername\"", ")", "creat...
[ 163, 4 ]
[ 186, 21 ]
python
en
['en', 'error', 'th']
False
DatabaseStoreBackend._get_sqlalchemy_key_pair_auth_url
( self, drivername: str, credentials: dict )
Utilizing a private key path and a passphrase in a given credentials dictionary, attempts to encode the provided values into a private key. If passphrase is incorrect, this will fail and an exception is raised. Args: drivername(str) - The name of the driver class creden...
Utilizing a private key path and a passphrase in a given credentials dictionary, attempts to encode the provided values into a private key. If passphrase is incorrect, this will fail and an exception is raised.
def _get_sqlalchemy_key_pair_auth_url( self, drivername: str, credentials: dict ) -> Tuple["URL", Dict]: """ Utilizing a private key path and a passphrase in a given credentials dictionary, attempts to encode the provided values into a private key. If passphrase is incorrect, this wi...
[ "def", "_get_sqlalchemy_key_pair_auth_url", "(", "self", ",", "drivername", ":", "str", ",", "credentials", ":", "dict", ")", "->", "Tuple", "[", "\"URL\"", ",", "Dict", "]", ":", "from", "cryptography", ".", "hazmat", ".", "backends", "import", "default_backe...
[ 188, 4 ]
[ 236, 9 ]
python
en
['en', 'error', 'th']
False
TransformersTranslator.__init__
( self, model_name_or_path: str, tokenizer_name: Optional[str] = None, max_seq_len: Optional[int] = None, clean_up_tokenization_spaces: Optional[bool] = True )
Initialize the translator with a model that fits your targeted languages. While we support all seq2seq models from Hugging Face's model hub, we recommend using the OPUS models from Helsiniki NLP. They provide plenty of different models, usually one model per language pair and translation direction. ...
Initialize the translator with a model that fits your targeted languages. While we support all seq2seq models from Hugging Face's model hub, we recommend using the OPUS models from Helsiniki NLP. They provide plenty of different models, usually one model per language pair and translation direction. ...
def __init__( self, model_name_or_path: str, tokenizer_name: Optional[str] = None, max_seq_len: Optional[int] = None, clean_up_tokenization_spaces: Optional[bool] = True ): """ Initialize the translator with a model that fits your targeted languages. While we support ...
[ "def", "__init__", "(", "self", ",", "model_name_or_path", ":", "str", ",", "tokenizer_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "max_seq_len", ":", "Optional", "[", "int", "]", "=", "None", ",", "clean_up_tokenization_spaces", ":", "Optiona...
[ 31, 4 ]
[ 64, 78 ]
python
en
['en', 'en', 'en']
True
TransformersTranslator.translate
( self, query: Optional[str] = None, documents: Optional[Union[List[Document], List[str], List[Dict[str, Any]]]] = None, dict_key: Optional[str] = None, **kwargs )
Run the actual translation. You can supply a query or a list of documents. Whatever is supplied will be translated.
Run the actual translation. You can supply a query or a list of documents. Whatever is supplied will be translated.
def translate( self, query: Optional[str] = None, documents: Optional[Union[List[Document], List[str], List[Dict[str, Any]]]] = None, dict_key: Optional[str] = None, **kwargs ) -> Union[str, List[Document], List[str], List[Dict[str, Any]]]: """ Run the actual ...
[ "def", "translate", "(", "self", ",", "query", ":", "Optional", "[", "str", "]", "=", "None", ",", "documents", ":", "Optional", "[", "Union", "[", "List", "[", "Document", "]", ",", "List", "[", "str", "]", ",", "List", "[", "Dict", "[", "str", ...
[ 66, 4 ]
[ 126, 89 ]
python
en
['en', 'error', 'th']
False
BaseConverter.__init__
(self, remove_numeric_tables: bool = False, valid_languages: Optional[List[str]] = None)
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables. The tabular structures in documents might be noise for the reader model if it does not have table parsing capability for finding answers....
:param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables. The tabular structures in documents might be noise for the reader model if it does not have table parsing capability for finding answers....
def __init__(self, remove_numeric_tables: bool = False, valid_languages: Optional[List[str]] = None): """ :param remove_numeric_tables: This option uses heuristics to remove numeric rows from the tables. The tabular structures in documents might be noise for the rea...
[ "def", "__init__", "(", "self", ",", "remove_numeric_tables", ":", "bool", "=", "False", ",", "valid_languages", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ")", ":", "self", ".", "remove_numeric_tables", "=", "remove_numeric_tables", "s...
[ 16, 4 ]
[ 30, 46 ]
python
en
['en', 'error', 'th']
False
BaseConverter.convert
( self, file_path: Path, meta: Optional[Dict[str, str]], remove_numeric_tables: Optional[bool] = None, valid_languages: Optional[List[str]] = None, )
Convert a file to a dictionary containing the text and any associated meta data. File converters may extract file meta like name or size. In addition to it, user supplied meta data like author, url, external IDs can be supplied as a dictionary. :param file_path: path of the file to co...
Convert a file to a dictionary containing the text and any associated meta data.
def convert( self, file_path: Path, meta: Optional[Dict[str, str]], remove_numeric_tables: Optional[bool] = None, valid_languages: Optional[List[str]] = None, ) -> Dict[str, Any]: """ Convert a file to a dictionary containing the text and any associated meta d...
[ "def", "convert", "(", "self", ",", "file_path", ":", "Path", ",", "meta", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", ",", "remove_numeric_tables", ":", "Optional", "[", "bool", "]", "=", "None", ",", "valid_languages", ":", "Optio...
[ 33, 4 ]
[ 59, 12 ]
python
en
['en', 'error', 'th']
False
BaseConverter.validate_language
(self, text: str)
Validate if the language of the text is one of valid languages.
Validate if the language of the text is one of valid languages.
def validate_language(self, text: str) -> bool: """ Validate if the language of the text is one of valid languages. """ if not self.valid_languages: return True try: lang = langdetect.detect(text) except langdetect.lang_detect_exception.LangDetect...
[ "def", "validate_language", "(", "self", ",", "text", ":", "str", ")", "->", "bool", ":", "if", "not", "self", ".", "valid_languages", ":", "return", "True", "try", ":", "lang", "=", "langdetect", ".", "detect", "(", "text", ")", "except", "langdetect", ...
[ 61, 4 ]
[ 76, 24 ]
python
en
['en', 'error', 'th']
False
fillna
(X, value=None, method=None, axis=None, limit=None, downcast=None)
Impute missing values. This function fills the missing values of the input sequence with the next/ previous known value. If there are contigous NaN values, they will all be filled with the same next/previous known value. Args: X (ndarray or pandas.DataFrame): Array of input sequenc...
Impute missing values.
def fillna(X, value=None, method=None, axis=None, limit=None, downcast=None): """Impute missing values. This function fills the missing values of the input sequence with the next/ previous known value. If there are contigous NaN values, they will all be filled with the same next/previous known value. ...
[ "def", "fillna", "(", "X", ",", "value", "=", "None", ",", "method", "=", "None", ",", "axis", "=", "None", ",", "limit", "=", "None", ",", "downcast", "=", "None", ")", ":", "if", "isinstance", "(", "method", ",", "str", ")", "or", "method", "is...
[ 4, 0 ]
[ 58, 20 ]
python
en
['nl', 'et', 'en']
False
SuiteEditNotebookRenderer.render
( self, suite: ExpectationSuite, batch_request: Optional[ Union[str, Dict[str, Union[str, int, Dict[str, Any]]]] ] = None, )
Render a notebook dict from an expectation suite.
Render a notebook dict from an expectation suite.
def render( self, suite: ExpectationSuite, batch_request: Optional[ Union[str, Dict[str, Union[str, int, Dict[str, Any]]]] ] = None, ) -> nbformat.NotebookNode: """ Render a notebook dict from an expectation suite. """ if not isinstance(sui...
[ "def", "render", "(", "self", ",", "suite", ":", "ExpectationSuite", ",", "batch_request", ":", "Optional", "[", "Union", "[", "str", ",", "Dict", "[", "str", ",", "Union", "[", "str", ",", "int", ",", "Dict", "[", "str", ",", "Any", "]", "]", "]",...
[ 353, 4 ]
[ 388, 29 ]
python
en
['en', 'error', 'th']
False
SuiteEditNotebookRenderer.render_to_disk
( self, suite: ExpectationSuite, notebook_file_path: str, batch_request: Optional[ Union[str, Dict[str, Union[str, int, Dict[str, Any]]]] ] = None, )
Render a notebook to disk from an expectation suite. If batch_request dictionary is passed, its properties will override any found in suite citations.
Render a notebook to disk from an expectation suite.
def render_to_disk( self, suite: ExpectationSuite, notebook_file_path: str, batch_request: Optional[ Union[str, Dict[str, Union[str, int, Dict[str, Any]]]] ] = None, ) -> None: """ Render a notebook to disk from an expectation suite. If ba...
[ "def", "render_to_disk", "(", "self", ",", "suite", ":", "ExpectationSuite", ",", "notebook_file_path", ":", "str", ",", "batch_request", ":", "Optional", "[", "Union", "[", "str", ",", "Dict", "[", "str", ",", "Union", "[", "str", ",", "int", ",", "Dict...
[ 391, 4 ]
[ 410, 9 ]
python
en
['en', 'error', 'th']
False
venv
(request)
Prepares a virtual environment for nose. :rtype : virtual_environments.VirtualEnvDescription
Prepares a virtual environment for nose. :rtype : virtual_environments.VirtualEnvDescription
def venv(request): """ Prepares a virtual environment for nose. :rtype : virtual_environments.VirtualEnvDescription """ return virtual_environments.prepare_virtualenv([request.param])
[ "def", "venv", "(", "request", ")", ":", "return", "virtual_environments", ".", "prepare_virtualenv", "(", "[", "request", ".", "param", "]", ")" ]
[ 11, 0 ]
[ 16, 67 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.__init__
( self, url: str = "sqlite://", index: str = "document", label_index: str = "label", update_existing_documents: bool = False, )
An SQL backed DocumentStore. Currently supports SQLite, PostgreSQL and MySQL backends. :param url: URL for SQL database as expected by SQLAlchemy. More info here: https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls :param index: The documents are scoped to an index attribute that...
An SQL backed DocumentStore. Currently supports SQLite, PostgreSQL and MySQL backends.
def __init__( self, url: str = "sqlite://", index: str = "document", label_index: str = "label", update_existing_documents: bool = False, ): """ An SQL backed DocumentStore. Currently supports SQLite, PostgreSQL and MySQL backends. :param url: URL for...
[ "def", "__init__", "(", "self", ",", "url", ":", "str", "=", "\"sqlite://\"", ",", "index", ":", "str", "=", "\"document\"", ",", "label_index", ":", "str", "=", "\"label\"", ",", "update_existing_documents", ":", "bool", "=", "False", ",", ")", ":", "en...
[ 70, 4 ]
[ 103, 47 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.get_document_by_id
(self, id: str, index: Optional[str] = None)
Fetch a document by specifying its text id string
Fetch a document by specifying its text id string
def get_document_by_id(self, id: str, index: Optional[str] = None) -> Optional[Document]: """Fetch a document by specifying its text id string""" documents = self.get_documents_by_id([id], index) document = documents[0] if documents else None return document
[ "def", "get_document_by_id", "(", "self", ",", "id", ":", "str", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Optional", "[", "Document", "]", ":", "documents", "=", "self", ".", "get_documents_by_id", "(", "[", "id", "]", ...
[ 105, 4 ]
[ 109, 23 ]
python
en
['en', 'en', 'en']
True
SQLDocumentStore.get_documents_by_id
(self, ids: List[str], index: Optional[str] = None, batch_size: int = 10_000)
Fetch documents by specifying a list of text id strings
Fetch documents by specifying a list of text id strings
def get_documents_by_id(self, ids: List[str], index: Optional[str] = None, batch_size: int = 10_000) -> List[Document]: """Fetch documents by specifying a list of text id strings""" index = index or self.index documents = [] for i in range(0, len(ids), batch_size): query = s...
[ "def", "get_documents_by_id", "(", "self", ",", "ids", ":", "List", "[", "str", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ")", "->", "List", "[", "Document", "]", ":", "index", "...
[ 111, 4 ]
[ 124, 24 ]
python
en
['en', 'en', 'en']
True
SQLDocumentStore.get_documents_by_vector_ids
( self, vector_ids: List[str], index: Optional[str] = None, batch_size: int = 10_000 )
Fetch documents by specifying a list of text vector id strings :param vector_ids: List of vector_id strings. :param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param batch_size: When wo...
Fetch documents by specifying a list of text vector id strings
def get_documents_by_vector_ids( self, vector_ids: List[str], index: Optional[str] = None, batch_size: int = 10_000 ): """ Fetch documents by specifying a list of text vector id strings :param vector_ids: List of vector_id strings. :param index: Name ...
[ "def", "get_documents_by_vector_ids", "(", "self", ",", "vector_ids", ":", "List", "[", "str", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ")", ":", "result", "=", "self", ".", "_query...
[ 126, 4 ]
[ 148, 31 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.get_all_documents_generator
( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, )
Get documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory. :param index: ...
Get documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory.
def get_all_documents_generator( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, ) -> Generator[Document, None, None]: """ Get documents from the document sto...
[ "def", "get_all_documents_generator", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "return_embedding", ":",...
[ 159, 4 ]
[ 186, 25 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore._query
( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, vector_ids: Optional[List[str]] = None, only_documents_without_embedding: bool = False, batch_size: int = 10_000 )
:param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param filters: Optional filters to narrow down the documents to return. Example: {"name": ["some", "more"], "category": ["only_...
:param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param filters: Optional filters to narrow down the documents to return. Example: {"name": ["some", "more"], "category": ["only_...
def _query( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, vector_ids: Optional[List[str]] = None, only_documents_without_embedding: bool = False, batch_size: int = 10_000 ): """ :param index: Name of the index to ge...
[ "def", "_query", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "vector_ids", ":", "Optional", "[", "Li...
[ 188, 4 ]
[ 245, 45 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.get_all_labels
(self, index=None, filters: Optional[dict] = None)
Return all labels in the document store
Return all labels in the document store
def get_all_labels(self, index=None, filters: Optional[dict] = None): """ Return all labels in the document store """ index = index or self.label_index # TODO: Use batch_size label_rows = self.session.query(LabelORM).filter_by(index=index).all() labels = [self._co...
[ "def", "get_all_labels", "(", "self", ",", "index", "=", "None", ",", "filters", ":", "Optional", "[", "dict", "]", "=", "None", ")", ":", "index", "=", "index", "or", "self", ".", "label_index", "# TODO: Use batch_size", "label_rows", "=", "self", ".", ...
[ 259, 4 ]
[ 268, 21 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.write_documents
( self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000 )
Indexes documents for later queries. :param documents: a list of Python dictionaries or a list of Haystack Document objects. For documents as dictionaries, the format is {"text": "<the-actual-text>"}. Optionally: Include meta data via {"text": "<the-...
Indexes documents for later queries.
def write_documents( self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000 ): """ Indexes documents for later queries. :param documents: a list of Python dictionaries or a list of Haystack Document objects. ...
[ "def", "write_documents", "(", "self", ",", "documents", ":", "Union", "[", "List", "[", "dict", "]", ",", "List", "[", "Document", "]", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ...
[ 270, 4 ]
[ 315, 24 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.write_labels
(self, labels, index=None)
Write annotation labels into document store.
Write annotation labels into document store.
def write_labels(self, labels, index=None): """Write annotation labels into document store.""" labels = [Label.from_dict(l) if isinstance(l, dict) else l for l in labels] index = index or self.label_index # TODO: Use batch_size for label in labels: label_orm = LabelO...
[ "def", "write_labels", "(", "self", ",", "labels", ",", "index", "=", "None", ")", ":", "labels", "=", "[", "Label", ".", "from_dict", "(", "l", ")", "if", "isinstance", "(", "l", ",", "dict", ")", "else", "l", "for", "l", "in", "labels", "]", "i...
[ 317, 4 ]
[ 337, 29 ]
python
en
['en', 'en', 'en']
True
SQLDocumentStore.update_vector_ids
(self, vector_id_map: Dict[str, str], index: Optional[str] = None, batch_size: int = 10_000)
Update vector_ids for given document_ids. :param vector_id_map: dict containing mapping of document_id -> vector_id. :param index: filter documents by the optional index attribute for documents in database. :param batch_size: When working with large number of documents, batching can he...
Update vector_ids for given document_ids.
def update_vector_ids(self, vector_id_map: Dict[str, str], index: Optional[str] = None, batch_size: int = 10_000): """ Update vector_ids for given document_ids. :param vector_id_map: dict containing mapping of document_id -> vector_id. :param index: filter documents by the optional inde...
[ "def", "update_vector_ids", "(", "self", ",", "vector_id_map", ":", "Dict", "[", "str", ",", "str", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ")", ":", "index", "=", "index", "or",...
[ 339, 4 ]
[ 363, 24 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.reset_vector_ids
(self, index: Optional[str] = None)
Set vector IDs for all documents as None
Set vector IDs for all documents as None
def reset_vector_ids(self, index: Optional[str] = None): """ Set vector IDs for all documents as None """ index = index or self.index self.session.query(DocumentORM).filter_by(index=index).update({DocumentORM.vector_id: null()}) self.session.commit()
[ "def", "reset_vector_ids", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "index", "=", "index", "or", "self", ".", "index", "self", ".", "session", ".", "query", "(", "DocumentORM", ")", ".", "filter_by", "(", "i...
[ 365, 4 ]
[ 371, 29 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.update_document_meta
(self, id: str, meta: Dict[str, str])
Update the metadata dictionary of a document by specifying its string id
Update the metadata dictionary of a document by specifying its string id
def update_document_meta(self, id: str, meta: Dict[str, str]): """ Update the metadata dictionary of a document by specifying its string id """ self.session.query(MetaORM).filter_by(document_id=id).delete() meta_orms = [MetaORM(name=key, value=value, document_id=id) for key, valu...
[ "def", "update_document_meta", "(", "self", ",", "id", ":", "str", ",", "meta", ":", "Dict", "[", "str", ",", "str", "]", ")", ":", "self", ".", "session", ".", "query", "(", "MetaORM", ")", ".", "filter_by", "(", "document_id", "=", "id", ")", "."...
[ 373, 4 ]
[ 381, 29 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.get_document_count
(self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None)
Return the number of documents in the document store.
Return the number of documents in the document store.
def get_document_count(self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None) -> int: """ Return the number of documents in the document store. """ index = index or self.index query = self.session.query(DocumentORM).filter_by(index=index) if f...
[ "def", "get_document_count", "(", "self", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "int", ":", "index", ...
[ 383, 4 ]
[ 396, 20 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.get_label_count
(self, index: Optional[str] = None)
Return the number of labels in the document store
Return the number of labels in the document store
def get_label_count(self, index: Optional[str] = None) -> int: """ Return the number of labels in the document store """ index = index or self.index return self.session.query(LabelORM).filter_by(index=index).count()
[ "def", "get_label_count", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "int", ":", "index", "=", "index", "or", "self", ".", "index", "return", "self", ".", "session", ".", "query", "(", "LabelORM", ")", ".", ...
[ 398, 4 ]
[ 403, 74 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore.delete_all_documents
(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None)
Delete documents in an index. All documents are deleted if no filters are passed. :param index: Index name to delete the document from. :param filters: Optional filters to narrow down the documents to be deleted. :return: None
Delete documents in an index. All documents are deleted if no filters are passed.
def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None): """ Delete documents in an index. All documents are deleted if no filters are passed. :param index: Index name to delete the document from. :param filters: Optional filters to na...
[ "def", "delete_all_documents", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ")", ":", "index", "=", "index",...
[ 442, 4 ]
[ 463, 29 ]
python
en
['en', 'error', 'th']
False
SQLDocumentStore._column_windows
(self, session, column, windowsize)
Return a series of WHERE clauses against a given column that break it into windows. Result is an iterable of tuples, consisting of ((start, end), whereclause), where (start, end) are the ids. The code is taken from: https://github.com/sqlalchemy/sqlalchemy/wiki/RangeQuery-and-WindowedR...
Return a series of WHERE clauses against a given column that break it into windows.
def _column_windows(self, session, column, windowsize): """Return a series of WHERE clauses against a given column that break it into windows. Result is an iterable of tuples, consisting of ((start, end), whereclause), where (start, end) are the ids. The code is taken from: htt...
[ "def", "_column_windows", "(", "self", ",", "session", ",", "column", ",", "windowsize", ")", ":", "def", "int_for_range", "(", "start_id", ",", "end_id", ")", ":", "if", "end_id", ":", "return", "and_", "(", "column", ">=", "start_id", ",", "column", "<...
[ 480, 4 ]
[ 517, 43 ]
python
en
['en', 'en', 'en']
True
SQLDocumentStore._windowed_query
(self, q, column, windowsize)
Break a Query into windows on a given column.
Break a Query into windows on a given column.
def _windowed_query(self, q, column, windowsize): """"Break a Query into windows on a given column.""" for whereclause in self._column_windows( q.session, column, windowsize): for row in q.filter(whereclause).order_by(column): yield row
[ "def", "_windowed_query", "(", "self", ",", "q", ",", "column", ",", "windowsize", ")", ":", "for", "whereclause", "in", "self", ".", "_column_windows", "(", "q", ".", "session", ",", "column", ",", "windowsize", ")", ":", "for", "row", "in", "q", ".",...
[ 519, 4 ]
[ 526, 25 ]
python
en
['en', 'gl', 'en']
True
FlexGroupLayer.op_cat
(self, x_out, m, groups)
Usage: Concat by input joints ratio of the first layer, always keep the ratio = N_i : 1; N_i is joint number in the ith group. :return: Concat with other info and adjust the channel size
Usage: Concat by input joints ratio of the first layer, always keep the ratio = N_i : 1; N_i is joint number in the ith group. :return: Concat with other info and adjust the channel size
def op_cat(self, x_out, m, groups): """ Usage: Concat by input joints ratio of the first layer, always keep the ratio = N_i : 1; N_i is joint number in the ith group. :return: Concat with other info and adjust the channel size """ cat_m = [] for i,group in enumerate(group...
[ "def", "op_cat", "(", "self", ",", "x_out", ",", "m", ",", "groups", ")", ":", "cat_m", "=", "[", "]", "for", "i", ",", "group", "in", "enumerate", "(", "groups", ")", ":", "indexes", "=", "group", "xs", "=", "[", "]", "for", "index", "in", "in...
[ 164, 4 ]
[ 177, 38 ]
python
en
['en', 'error', 'th']
False
FlexGroupLayer._keep_ratio
(self, inc_num, fix_seq, index, added_dim, by_ratio)
For concat by a certain ratio, you can change [joint_dim] to give various concat ratios. :param inc_num: input channel number of a group. type:torch.Tensor :param fix_seq: output index sequence of 1st layer, knowing the groups number. :return: a concatenated input channel number ...
For concat by a certain ratio, you can change [joint_dim] to give various concat ratios. :param inc_num: input channel number of a group. type:torch.Tensor :param fix_seq: output index sequence of 1st layer, knowing the groups number. :return: a concatenated input channel number ...
def _keep_ratio(self, inc_num, fix_seq, index, added_dim, by_ratio): """ For concat by a certain ratio, you can change [joint_dim] to give various concat ratios. :param inc_num: input channel number of a group. type:torch.Tensor :param fix_seq: output index sequence of 1st layer, knowing...
[ "def", "_keep_ratio", "(", "self", ",", "inc_num", ",", "fix_seq", ",", "index", ",", "added_dim", ",", "by_ratio", ")", ":", "ori_size", "=", "len", "(", "fix_seq", "[", "index", "]", ")", "# add [x,y] dimension", "if", "by_ratio", ":", "# Add the dimension...
[ 179, 4 ]
[ 193, 35 ]
python
en
['en', 'error', 'th']
False
FlexGroupLayer._get_partial_input
(self, x)
Usage: Get inputs as Group representation :param x: all 2d joints inputs, x.shape=[B, 34, T] :param out_seq: output index sequence of each layer :return: 1. x_self: Each group inputs; type: list 2. x_other: Out of the group values; type: list
Usage: Get inputs as Group representation :param x: all 2d joints inputs, x.shape=[B, 34, T] :param out_seq: output index sequence of each layer :return: 1. x_self: Each group inputs; type: list 2. x_other: Out of the group values; type: list
def _get_partial_input(self, x): """ Usage: Get inputs as Group representation :param x: all 2d joints inputs, x.shape=[B, 34, T] :param out_seq: output index sequence of each layer :return: 1. x_self: Each group inputs; type: list 2. x_other: Out of the group val...
[ "def", "_get_partial_input", "(", "self", ",", "x", ")", ":", "x_other", "=", "[", "]", "x_self", "=", "[", "]", "in_dim", "=", "[", "]", "v", "=", "0", "for", "i", ",", "group", "in", "enumerate", "(", "self", ".", "groups", ")", ":", "indexes",...
[ 198, 4 ]
[ 220, 25 ]
python
en
['en', 'error', 'th']
False
FlexGroupLayer._split_fc
(self, x, dtype)
Usage: Split channels into groups :param x: Input features :return: x1: each group features. type: list x_cat: concatenate each group features. type:torch.Tensor
Usage: Split channels into groups :param x: Input features :return: x1: each group features. type: list x_cat: concatenate each group features. type:torch.Tensor
def _split_fc(self, x, dtype): """ Usage: Split channels into groups :param x: Input features :return: x1: each group features. type: list x_cat: concatenate each group features. type:torch.Tensor """ x1 = [] for i,group in enumerate(self.groups):...
[ "def", "_split_fc", "(", "self", ",", "x", ",", "dtype", ")", ":", "x1", "=", "[", "]", "for", "i", ",", "group", "in", "enumerate", "(", "self", ".", "groups", ")", ":", "indexes", "=", "group", "xs", "=", "[", "]", "for", "index", "in", "inde...
[ 222, 4 ]
[ 240, 24 ]
python
en
['en', 'error', 'th']
False
FlexGroupLayer._group_conv
(self, x, groups)
Usage: fully connection in a group :param x: features :param groups: depend on concat or not of different input size :return: final outputs after group conv.
Usage: fully connection in a group :param x: features :param groups: depend on concat or not of different input size :return: final outputs after group conv.
def _group_conv(self, x, groups): """ Usage: fully connection in a group :param x: features :param groups: depend on concat or not of different input size :return: final outputs after group conv. """ outs = [] ks = self.kernel_size for i, group in ...
[ "def", "_group_conv", "(", "self", ",", "x", ",", "groups", ")", ":", "outs", "=", "[", "]", "ks", "=", "self", ".", "kernel_size", "for", "i", ",", "group", "in", "enumerate", "(", "groups", ")", ":", "indexes", "=", "group", "xs", "=", "[", "]"...
[ 242, 4 ]
[ 262, 37 ]
python
en
['en', 'error', 'th']
False
dc
(input1, input2)
Dice coefficient Computes the Dice coefficient (also known as Sorensen index) between the binary objects in two images. The metric is defined as .. math:: DC = \frac{2|A\capB|}{|A|+|B|} , where A is the first and B the second set of samples (here binary objects). Parameters ...
Dice coefficient
def dc(input1, input2): """ Dice coefficient Computes the Dice coefficient (also known as Sorensen index) between the binary objects in two images. The metric is defined as .. math:: DC = \frac{2|A\capB|}{|A|+|B|} , where A is the first and B the second set of samples (here bina...
[ "def", "dc", "(", "input1", ",", "input2", ")", ":", "input1", "=", "numpy", ".", "atleast_1d", "(", "input1", ".", "astype", "(", "numpy", ".", "bool", ")", ")", "input2", "=", "numpy", ".", "atleast_1d", "(", "input2", ".", "astype", "(", "numpy", ...
[ 9, 0 ]
[ 56, 13 ]
python
en
['en', 'error', 'th']
False
dice_ratio
(preds, labels)
preds & labels should only contain 0 or 1.
preds & labels should only contain 0 or 1.
def dice_ratio(preds, labels): ''' preds & labels should only contain 0 or 1. ''' if np.sum(preds) + np.sum(labels) == 0: return 1 return np.sum(preds[labels==1])*2.0 / (np.sum(preds) + np.sum(labels))
[ "def", "dice_ratio", "(", "preds", ",", "labels", ")", ":", "if", "np", ".", "sum", "(", "preds", ")", "+", "np", ".", "sum", "(", "labels", ")", "==", "0", ":", "return", "1", "return", "np", ".", "sum", "(", "preds", "[", "labels", "==", "1",...
[ 59, 0 ]
[ 65, 74 ]
python
en
['en', 'error', 'th']
False
GirderExternalDataCli.__init__
(self, apiKey, objectStore)
initialization function to create a GirderCli instance, will attempt to authenticate with the designated Girder instance.
initialization function to create a GirderCli instance, will attempt to authenticate with the designated Girder instance.
def __init__(self, apiKey, objectStore): """initialization function to create a GirderCli instance, will attempt to authenticate with the designated Girder instance. """ GirderClient.__init__(self, apiUrl='https://data.kitware.com/api/v1') self.objec...
[ "def", "__init__", "(", "self", ",", "apiKey", ",", "objectStore", ")", ":", "GirderClient", ".", "__init__", "(", "self", ",", "apiUrl", "=", "'https://data.kitware.com/api/v1'", ")", "self", ".", "objectStore", "=", "objectStore", "self", ".", "authenticate", ...
[ 19, 4 ]
[ 26, 40 ]
python
en
['en', 'en', 'en']
True
GirderExternalDataCli.content_link_upload
(self, localFolder, parentId, ext='.sha512', parentType='folder', blacklist=['.git', '.ExternalData'], reuseExisting=True, dryRun=False)
Upload objects corresponding to CMake ExternalData content links. This will recursively walk down the tree and find content links ending with the specified extension and create a hierarchy on the server under the parentId. :param ext: Content link file extension. :param parentI...
Upload objects corresponding to CMake ExternalData content links.
def content_link_upload(self, localFolder, parentId, ext='.sha512', parentType='folder', blacklist=['.git', '.ExternalData'], reuseExisting=True, dryRun=False): """Upload objects corresponding to CMake ExternalData content links. This will recursively walk down the tree and find...
[ "def", "content_link_upload", "(", "self", ",", "localFolder", ",", "parentId", ",", "ext", "=", "'.sha512'", ",", "parentType", "=", "'folder'", ",", "blacklist", "=", "[", "'.git'", ",", "'.ExternalData'", "]", ",", "reuseExisting", "=", "True", ",", "dryR...
[ 28, 4 ]
[ 59, 34 ]
python
en
['en', 'en', 'en']
True
GirderExternalDataCli._uploadContentLinkItem
(self, name, content_link, folder, ext='.sha512', parentType='folder', dryRun=False, reuseExisting=False)
Upload objects corresponding to CMake ExternalData content links. This will upload the file with name, *name*, for the content link located at *content_link* to the Girder folder, *folder*. :param ext: Content link file extension. :param parentType: one of (collection,folder,user), def...
Upload objects corresponding to CMake ExternalData content links.
def _uploadContentLinkItem(self, name, content_link, folder, ext='.sha512', parentType='folder', dryRun=False, reuseExisting=False): """Upload objects corresponding to CMake ExternalData content links. This will upload the file with name, *name*, for the content link loc...
[ "def", "_uploadContentLinkItem", "(", "self", ",", "name", ",", "content_link", ",", "folder", ",", "ext", "=", "'.sha512'", ",", "parentType", "=", "'folder'", ",", "dryRun", "=", "False", ",", "reuseExisting", "=", "False", ")", ":", "content_link", "=", ...
[ 61, 4 ]
[ 90, 34 ]
python
en
['en', 'en', 'en']
True
GirderExternalDataCli._uploadFolderRecursive
(self, localFolder, parentId, parentType, ext='.sha512', reuseExisting=False, blacklist=[], dryRun=False)
Function to recursively upload a folder and all of its descendants. :param localFolder: full path to local folder to be uploaded :param parentId: id of parent in Girder, where new folder will be added :param parentType: one of (collection, folder, user) :param leaf_folders_as...
Function to recursively upload a folder and all of its descendants. :param localFolder: full path to local folder to be uploaded :param parentId: id of parent in Girder, where new folder will be added :param parentType: one of (collection, folder, user) :param leaf_folders_as...
def _uploadFolderRecursive(self, localFolder, parentId, parentType, ext='.sha512', reuseExisting=False, blacklist=[], dryRun=False): """Function to recursively upload a folder and ...
[ "def", "_uploadFolderRecursive", "(", "self", ",", "localFolder", ",", "parentId", ",", "parentType", ",", "ext", "=", "'.sha512'", ",", "reuseExisting", "=", "False", ",", "blacklist", "=", "[", "]", ",", "dryRun", "=", "False", ")", ":", "localFolder", "...
[ 92, 4 ]
[ 157, 49 ]
python
en
['en', 'en', 'en']
True
get_bin_intervals
(data, num_bins)
Returns bin intervals for 1D data. Parameters ---------- data: np.ndarray A 1D NumPy array of values to get bin intervals for. num_bins: int The number of bins to create. Returns ------- bin_intervals: np.ndarray of shape (num_bins, 2) A 2D NumPy array of bin i...
Returns bin intervals for 1D data.
def get_bin_intervals(data, num_bins): """ Returns bin intervals for 1D data. Parameters ---------- data: np.ndarray A 1D NumPy array of values to get bin intervals for. num_bins: int The number of bins to create. Returns ------- bin_intervals: np.ndarray of shape (...
[ "def", "get_bin_intervals", "(", "data", ",", "num_bins", ")", ":", "# Transition points between bins.", "bin_trans", "=", "np", ".", "linspace", "(", "data", "[", "0", "]", ",", "data", "[", "-", "1", "]", ",", "num_bins", "+", "1", ",", "endpoint", "="...
[ 10, 0 ]
[ 33, 24 ]
python
en
['en', 'error', 'th']
False
xr_scale_res
(dataset, x_coord='longitude', y_coord='latitude', frac_res=None, abs_res=None)
Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution. Parameters ---------- dataset: xarray.Dataset or xarray.DataArray The Dataset or DataArray to reduce the resolution of. x_coord, y_coord: str N...
Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution.
def xr_scale_res(dataset, x_coord='longitude', y_coord='latitude', frac_res=None, abs_res=None): """ Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution. Parameters ---------- dataset: xarray.Data...
[ "def", "xr_scale_res", "(", "dataset", ",", "x_coord", "=", "'longitude'", ",", "y_coord", "=", "'latitude'", ",", "frac_res", "=", "None", ",", "abs_res", "=", "None", ")", ":", "assert", "frac_res", "is", "not", "None", "or", "abs_res", "is", "not", "N...
[ 36, 0 ]
[ 74, 74 ]
python
en
['en', 'error', 'th']
False
xr_sel_time_by_bin
(dataset, num_bins, time_coord='time')
Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions. Parameters ---------- dataset: xarray.Dataset or xarray.DataArray The Dataset or DataArray to aggregate by binning. ...
Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions.
def xr_sel_time_by_bin(dataset, num_bins, time_coord='time'): """ Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions. Parameters ---------- dataset: xarray.Dataset or xarray.DataArr...
[ "def", "xr_sel_time_by_bin", "(", "dataset", ",", "num_bins", ",", "time_coord", "=", "'time'", ")", ":", "return", "xr_interp", "(", "dataset", ",", "{", "time_coord", ":", "(", "'bin'", ",", "{", "'num'", ":", "num_bins", "}", ")", "}", ")" ]
[ 77, 0 ]
[ 98, 71 ]
python
en
['en', 'error', 'th']
False
xr_interp
(dataset, interp_config)
Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption. First, coordinates are interpolated according to `interp_config`. Then the data values for those interpolated coordinates are obtained ...
Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption.
def xr_interp(dataset, interp_config): """ Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption. First, coordinates are interpolated according to `interp_config`. Then the data values for...
[ "def", "xr_interp", "(", "dataset", ",", "interp_config", ")", ":", "# Create the new coordinates.", "new_coords", "=", "{", "}", "for", "dim", ",", "(", "interp_type", ",", "interp_kwargs", ")", "in", "interp_config", ".", "items", "(", ")", ":", "# Determine...
[ 101, 0 ]
[ 173, 22 ]
python
en
['en', 'error', 'th']
False
dt_to_str
(date, fmt='%Y-%m-%d')
Converts a datetime object to a string.
Converts a datetime object to a string.
def dt_to_str(date, fmt='%Y-%m-%d'): """ Converts a datetime object to a string. """ return date.strftime(fmt)
[ "def", "dt_to_str", "(", "date", ",", "fmt", "=", "'%Y-%m-%d'", ")", ":", "return", "date", ".", "strftime", "(", "fmt", ")" ]
[ 3, 0 ]
[ 7, 29 ]
python
en
['en', 'error', 'th']
False
_n64_to_datetime
(n64)
Converts Numpy 64 bit timestamps to datetime objects. Units in seconds
Converts Numpy 64 bit timestamps to datetime objects. Units in seconds
def _n64_to_datetime(n64): """ Converts Numpy 64 bit timestamps to datetime objects. Units in seconds """ return datetime.utcfromtimestamp(n64.tolist() / 1e9)
[ "def", "_n64_to_datetime", "(", "n64", ")", ":", "return", "datetime", ".", "utcfromtimestamp", "(", "n64", ".", "tolist", "(", ")", "/", "1e9", ")" ]
[ 9, 0 ]
[ 13, 56 ]
python
en
['en', 'error', 'th']
False
_n64_datetime_to_scalar
(dt64)
Converts a NumPy datetime64 object to the number of seconds since midnight, January 1, 1970, as a NumPy float64. Returns ------- scalar: numpy.float64 The number of seconds since midnight, January 1, 1970, as a NumPy float64.
Converts a NumPy datetime64 object to the number of seconds since midnight, January 1, 1970, as a NumPy float64. Returns ------- scalar: numpy.float64 The number of seconds since midnight, January 1, 1970, as a NumPy float64.
def _n64_datetime_to_scalar(dt64): """ Converts a NumPy datetime64 object to the number of seconds since midnight, January 1, 1970, as a NumPy float64. Returns ------- scalar: numpy.float64 The number of seconds since midnight, January 1, 1970, as a NumPy float64. """ retur...
[ "def", "_n64_datetime_to_scalar", "(", "dt64", ")", ":", "return", "(", "dt64", "-", "np", ".", "datetime64", "(", "'1970-01-01T00:00:00Z'", ")", ")", "/", "np", ".", "timedelta64", "(", "1", ",", "'s'", ")" ]
[ 15, 0 ]
[ 25, 82 ]
python
en
['en', 'error', 'th']
False
_scalar_to_n64_datetime
(scalar)
Converts a floating point number to a NumPy datetime64 object. Returns ------- dt64: numpy.datetime64 The NumPy datetime64 object representing the datetime of the scalar argument.
Converts a floating point number to a NumPy datetime64 object. Returns ------- dt64: numpy.datetime64 The NumPy datetime64 object representing the datetime of the scalar argument.
def _scalar_to_n64_datetime(scalar): """ Converts a floating point number to a NumPy datetime64 object. Returns ------- dt64: numpy.datetime64 The NumPy datetime64 object representing the datetime of the scalar argument. """ return (scalar * np.timedelta64(1, 's')) + np.datetime...
[ "def", "_scalar_to_n64_datetime", "(", "scalar", ")", ":", "return", "(", "scalar", "*", "np", ".", "timedelta64", "(", "1", ",", "'s'", ")", ")", "+", "np", ".", "datetime64", "(", "'1970-01-01T00:00:00Z'", ")" ]
[ 27, 0 ]
[ 36, 84 ]
python
en
['en', 'error', 'th']
False
SuiteScaffoldNotebookRenderer.render_to_disk
(self, notebook_file_path: str)
Render a notebook to disk from an expectation suite. If batch_kwargs are passed they will override any found in suite citations.
Render a notebook to disk from an expectation suite.
def render_to_disk(self, notebook_file_path: str) -> None: """ Render a notebook to disk from an expectation suite. If batch_kwargs are passed they will override any found in suite citations. """ self.render(self.batch_kwargs) self.write_notebook_to_disk(self._no...
[ "def", "render_to_disk", "(", "self", ",", "notebook_file_path", ":", "str", ")", "->", "None", ":", "self", ".", "render", "(", "self", ".", "batch_kwargs", ")", "self", ".", "write_notebook_to_disk", "(", "self", ".", "_notebook", ",", "notebook_file_path", ...
[ 152, 4 ]
[ 160, 71 ]
python
en
['en', 'error', 'th']
False
Instruments.add_instrument
(self, instrument: Instrument)
Start instrumenting the current run loop with the given instrument. Args: instrument (trio.abc.Instrument): The instrument to activate. If ``instrument`` is already active, does nothing.
Start instrumenting the current run loop with the given instrument.
def add_instrument(self, instrument: Instrument) -> None: """Start instrumenting the current run loop with the given instrument. Args: instrument (trio.abc.Instrument): The instrument to activate. If ``instrument`` is already active, does nothing. """ if instrument i...
[ "def", "add_instrument", "(", "self", ",", "instrument", ":", "Instrument", ")", "->", "None", ":", "if", "instrument", "in", "self", "[", "\"_all\"", "]", ":", "return", "self", "[", "\"_all\"", "]", "[", "instrument", "]", "=", "None", "try", ":", "f...
[ 37, 4 ]
[ 64, 17 ]
python
en
['en', 'en', 'en']
True
Instruments.remove_instrument
(self, instrument: Instrument)
Stop instrumenting the current run loop with the given instrument. Args: instrument (trio.abc.Instrument): The instrument to de-activate. Raises: KeyError: if the instrument is not currently active. This could occur either because you never added it, or because you ad...
Stop instrumenting the current run loop with the given instrument.
def remove_instrument(self, instrument: Instrument) -> None: """Stop instrumenting the current run loop with the given instrument. Args: instrument (trio.abc.Instrument): The instrument to de-activate. Raises: KeyError: if the instrument is not currently active. This could ...
[ "def", "remove_instrument", "(", "self", ",", "instrument", ":", "Instrument", ")", "->", "None", ":", "# If instrument isn't present, the KeyError propagates out", "self", "[", "\"_all\"", "]", ".", "pop", "(", "instrument", ")", "for", "hookname", ",", "instrument...
[ 67, 4 ]
[ 86, 38 ]
python
en
['en', 'en', 'en']
True
Instruments.call
(self, hookname: str, *args: Any)
Call hookname(*args) on each applicable instrument. You must first check whether there are any instruments installed for that hook, e.g.:: if "before_task_step" in instruments: instruments.call("before_task_step", task)
Call hookname(*args) on each applicable instrument.
def call(self, hookname: str, *args: Any) -> None: """Call hookname(*args) on each applicable instrument. You must first check whether there are any instruments installed for that hook, e.g.:: if "before_task_step" in instruments: instruments.call("before_task_step"...
[ "def", "call", "(", "self", ",", "hookname", ":", "str", ",", "*", "args", ":", "Any", ")", "->", "None", ":", "for", "instrument", "in", "list", "(", "self", "[", "hookname", "]", ")", ":", "try", ":", "getattr", "(", "instrument", ",", "hookname"...
[ 88, 4 ]
[ 107, 17 ]
python
en
['en', 'en', 'en']
True
contextual_confusion_matrix
(expected, observed, data=None, start=None, end=None, weighted=True)
Compute the confusion matrix between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing two columns: start and stop. observed (DataFrame or list of tuples): D...
Compute the confusion matrix between the ground truth and the detected anomalies.
def contextual_confusion_matrix(expected, observed, data=None, start=None, end=None, weighted=True): """Compute the confusion matrix between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``...
[ "def", "contextual_confusion_matrix", "(", "expected", ",", "observed", ",", "data", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "weighted", "=", "True", ")", ":", "def", "_ws", "(", "x", ",", "y", ",", "z", ",", "w", ")",...
[ 61, 0 ]
[ 108, 51 ]
python
en
['en', 'en', 'en']
True
contextual_accuracy
(expected, observed, data=None, start=None, end=None, weighted=True)
Compute an accuracy score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing two columns: start and stop. observed (DataFrame or list of tuples): Dete...
Compute an accuracy score between the ground truth and the detected anomalies.
def contextual_accuracy(expected, observed, data=None, start=None, end=None, weighted=True): """Compute an accuracy score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing ...
[ "def", "contextual_accuracy", "(", "expected", ",", "observed", ",", "data", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "weighted", "=", "True", ")", ":", "def", "_cm", "(", "x", ",", "y", ",", "z", ",", "w", ",", "f", ...
[ 111, 0 ]
[ 138, 63 ]
python
en
['en', 'en', 'en']
True
contextual_precision
(expected, observed, data=None, start=None, end=None, weighted=True)
Compute an precision score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing two columns: start and stop. observed (DataFrame or list of tuples): Det...
Compute an precision score between the ground truth and the detected anomalies.
def contextual_precision(expected, observed, data=None, start=None, end=None, weighted=True): """Compute an precision score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing ...
[ "def", "contextual_precision", "(", "expected", ",", "observed", ",", "data", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "weighted", "=", "True", ")", ":", "def", "_cm", "(", "x", ",", "y", ",", "z", ",", "w", ",", "f",...
[ 141, 0 ]
[ 168, 64 ]
python
en
['en', 'en', 'en']
True
contextual_recall
(expected, observed, data=None, start=None, end=None, weighted=True)
Compute an recall score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing two columns: start and stop. observed (DataFrame or list of tuples): Detect...
Compute an recall score between the ground truth and the detected anomalies.
def contextual_recall(expected, observed, data=None, start=None, end=None, weighted=True): """Compute an recall score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing ...
[ "def", "contextual_recall", "(", "expected", ",", "observed", ",", "data", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "weighted", "=", "True", ")", ":", "def", "_cm", "(", "x", ",", "y", ",", "z", ",", "w", ",", "f", ...
[ 171, 0 ]
[ 198, 61 ]
python
en
['en', 'en', 'en']
True
contextual_f1_score
(expected, observed, data=None, start=None, end=None, weighted=True)
Compute an f1 score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing two columns: start and stop. observed (DataFrame or list of tuples): Detected a...
Compute an f1 score between the ground truth and the detected anomalies.
def contextual_f1_score(expected, observed, data=None, start=None, end=None, weighted=True): """Compute an f1 score between the ground truth and the detected anomalies. Args: expected (DataFrame or list of tuples): Ground truth passed as a ``pandas.DataFrame`` or list containing ...
[ "def", "contextual_f1_score", "(", "expected", ",", "observed", ",", "data", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "weighted", "=", "True", ")", ":", "def", "_cm", "(", "x", ",", "y", ",", "z", ",", "w", ",", "f", ...
[ 201, 0 ]
[ 228, 63 ]
python
en
['en', 'en', 'en']
True
my_fun
(one, two, three, four, five, six)
Sample function with multiple code issues
Sample function with multiple code issues
def my_fun(one, two, three, four, five, six): # pylint: disable=W0613 """Sample function with multiple code issues""" one += 1; two += 2 # More than one statement on a single line (C0321) seven = eight # Unused variable "seven" (W0612), undefined variable "eight" (E1101) return one + two + nine
[ "def", "my_fun", "(", "one", ",", "two", ",", "three", ",", "four", ",", "five", ",", "six", ")", ":", "# pylint: disable=W0613", "one", "+=", "1", "two", "+=", "2", "# More than one statement on a single line (C0321)", "seven", "=", "eight", "# Unused variable ...
[ 3, 0 ]
[ 7, 27 ]
python
en
['en', 'en', 'en']
True
export_answers_to_csv
(agg_results: list, output_file)
Exports answers coming from finder.get_answers() to a CSV file :param agg_results: list of predictions coming from finder.get_answers() :param output_file: filename of output file :return: None
Exports answers coming from finder.get_answers() to a CSV file :param agg_results: list of predictions coming from finder.get_answers() :param output_file: filename of output file :return: None
def export_answers_to_csv(agg_results: list, output_file): """ Exports answers coming from finder.get_answers() to a CSV file :param agg_results: list of predictions coming from finder.get_answers() :param output_file: filename of output file :return: None """ if isinstance(agg_results, dict...
[ "def", "export_answers_to_csv", "(", "agg_results", ":", "list", ",", "output_file", ")", ":", "if", "isinstance", "(", "agg_results", ",", "dict", ")", ":", "agg_results", "=", "[", "agg_results", "]", "assert", "\"query\"", "in", "agg_results", "[", "0", "...
[ 33, 0 ]
[ 61, 39 ]
python
en
['en', 'error', 'th']
False
convert_labels_to_squad
(labels_file: str)
Convert the export from the labeling UI to SQuAD format for training. :param labels_file: path for export file from the labeling tool :return:
Convert the export from the labeling UI to SQuAD format for training.
def convert_labels_to_squad(labels_file: str): """ Convert the export from the labeling UI to SQuAD format for training. :param labels_file: path for export file from the labeling tool :return: """ with open(labels_file, encoding='utf-8') as label_file: labels = json.load(label_file) ...
[ "def", "convert_labels_to_squad", "(", "labels_file", ":", "str", ")", ":", "with", "open", "(", "labels_file", ",", "encoding", "=", "'utf-8'", ")", "as", "label_file", ":", "labels", "=", "json", ".", "load", "(", "label_file", ")", "labels_grouped_by_docume...
[ 65, 0 ]
[ 115, 50 ]
python
en
['en', 'error', 'th']
False
get_batches_from_generator
(iterable, n)
Batch elements of an iterable into fixed-length chunks or blocks.
Batch elements of an iterable into fixed-length chunks or blocks.
def get_batches_from_generator(iterable, n): """ Batch elements of an iterable into fixed-length chunks or blocks. """ it = iter(iterable) x = tuple(islice(it, n)) while x: yield x x = tuple(islice(it, n))
[ "def", "get_batches_from_generator", "(", "iterable", ",", "n", ")", ":", "it", "=", "iter", "(", "iterable", ")", "x", "=", "tuple", "(", "islice", "(", "it", ",", "n", ")", ")", "while", "x", ":", "yield", "x", "x", "=", "tuple", "(", "islice", ...
[ 118, 0 ]
[ 126, 32 ]
python
en
['en', 'error', 'th']
False
initialized_project
(mock_webbrowser, tmp_path_factory)
This is an initialized project through the CLI.
This is an initialized project through the CLI.
def initialized_project(mock_webbrowser, tmp_path_factory): """This is an initialized project through the CLI.""" project_dir = str(tmp_path_factory.mktemp("my_rad_project")) os.makedirs(os.path.join(project_dir, "data")) data_folder_path = os.path.join(project_dir, "data") data_path = os.path.join(...
[ "def", "initialized_project", "(", "mock_webbrowser", ",", "tmp_path_factory", ")", ":", "project_dir", "=", "str", "(", "tmp_path_factory", ".", "mktemp", "(", "\"my_rad_project\"", ")", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", ...
[ 274, 0 ]
[ 300, 22 ]
python
en
['en', 'en', 'en']
True
scheduler_trace
()
Returns a scheduler-dependent value we can use to check determinism.
Returns a scheduler-dependent value we can use to check determinism.
async def scheduler_trace(): """Returns a scheduler-dependent value we can use to check determinism.""" trace = [] async def tracer(name): for i in range(50): trace.append((name, i)) await trio.sleep(0) async with trio.open_nursery() as nursery: for i in range(5...
[ "async", "def", "scheduler_trace", "(", ")", ":", "trace", "=", "[", "]", "async", "def", "tracer", "(", "name", ")", ":", "for", "i", "in", "range", "(", "50", ")", ":", "trace", ".", "append", "(", "(", "name", ",", "i", ")", ")", "await", "t...
[ 3, 0 ]
[ 16, 23 ]
python
en
['en', 'en', 'en']
True
store
(ctx)
Store operations
Store operations
def store(ctx): """Store operations""" directory: str = toolkit.parse_cli_config_file_location( config_file_location=ctx.obj.config_file_location ).get("directory") context: DataContext = toolkit.load_data_context_with_error_handling( directory=directory, from_cli_upgrade_command...
[ "def", "store", "(", "ctx", ")", ":", "directory", ":", "str", "=", "toolkit", ".", "parse_cli_config_file_location", "(", "config_file_location", "=", "ctx", ".", "obj", ".", "config_file_location", ")", ".", "get", "(", "\"directory\"", ")", "context", ":", ...
[ 9, 0 ]
[ 27, 57 ]
python
en
['en', 'en', 'en']
False
store_list
(ctx)
List active Stores.
List active Stores.
def store_list(ctx): """List active Stores.""" context = ctx.obj.data_context usage_event_end: str = ctx.obj.usage_event_end try: stores = context.list_active_stores() cli_message(f"{len(stores)} active Stores found:") for store in stores: cli_message("") ...
[ "def", "store_list", "(", "ctx", ")", ":", "context", "=", "ctx", ".", "obj", ".", "data_context", "usage_event_end", ":", "str", "=", "ctx", ".", "obj", ".", "usage_event_end", "try", ":", "stores", "=", "context", ".", "list_active_stores", "(", ")", "...
[ 32, 0 ]
[ 52, 14 ]
python
en
['es', 'en', 'en']
True