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
WarningsRecorder.__len__
(self)
The number of recorded warnings.
The number of recorded warnings.
def __len__(self): """The number of recorded warnings.""" return len(self._list)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_list", ")" ]
[ 164, 4 ]
[ 166, 30 ]
python
en
['en', 'en', 'en']
True
WarningsRecorder.pop
(self, cls=Warning)
Pop the first recorded warning, raise exception if not exists.
Pop the first recorded warning, raise exception if not exists.
def pop(self, cls=Warning): """Pop the first recorded warning, raise exception if not exists.""" for i, w in enumerate(self._list): if issubclass(w.category, cls): return self._list.pop(i) __tracebackhide__ = True raise AssertionError("%r not found in warning ...
[ "def", "pop", "(", "self", ",", "cls", "=", "Warning", ")", ":", "for", "i", ",", "w", "in", "enumerate", "(", "self", ".", "_list", ")", ":", "if", "issubclass", "(", "w", ".", "category", ",", "cls", ")", ":", "return", "self", ".", "_list", ...
[ 168, 4 ]
[ 174, 66 ]
python
en
['en', 'en', 'en']
True
WarningsRecorder.clear
(self)
Clear the list of recorded warnings.
Clear the list of recorded warnings.
def clear(self): """Clear the list of recorded warnings.""" self._list[:] = []
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_list", "[", ":", "]", "=", "[", "]" ]
[ 176, 4 ]
[ 178, 26 ]
python
en
['en', 'en', 'en']
True
EntityCache.entities
(self)
Возвращает список объектов либо QuerySet в зависимости от подхода к получению объектов
Возвращает список объектов либо QuerySet в зависимости от подхода к получению объектов
def entities(self) -> Union[QueryType[Model], List[Model]]: """ Возвращает список объектов либо QuerySet в зависимости от подхода к получению объектов """ return self._entities
[ "def", "entities", "(", "self", ")", "->", "Union", "[", "QueryType", "[", "Model", "]", ",", "List", "[", "Model", "]", "]", ":", "return", "self", ".", "_entities" ]
[ 103, 4 ]
[ 108, 29 ]
python
en
['en', 'error', 'th']
False
EntityCache._before_prepare
(self)
Точка расширения перед подготовкой кеша
Точка расширения перед подготовкой кеша
def _before_prepare(self): """ Точка расширения перед подготовкой кеша """ pass
[ "def", "_before_prepare", "(", "self", ")", ":", "pass" ]
[ 110, 4 ]
[ 114, 12 ]
python
en
['en', 'error', 'th']
False
EntityCache._after_prepare
(self)
Точка расширения после подготовки кеша
Точка расширения после подготовки кеша
def _after_prepare(self): """ Точка расширения после подготовки кеша """ pass
[ "def", "_after_prepare", "(", "self", ")", ":", "pass" ]
[ 116, 4 ]
[ 120, 12 ]
python
en
['en', 'error', 'th']
False
EntityCache._prepare
(self)
Метод подготовки кеша
Метод подготовки кеша
def _prepare(self): """ Метод подготовки кеша """ self._prepare_entities() self._prepare_entities_hash_table()
[ "def", "_prepare", "(", "self", ")", ":", "self", ".", "_prepare_entities", "(", ")", "self", ".", "_prepare_entities_hash_table", "(", ")" ]
[ 122, 4 ]
[ 127, 43 ]
python
en
['en', 'error', 'th']
False
EntityCache._prepare_entities
(self)
Получение выборки объектов модели по указанными параметрам
Получение выборки объектов модели по указанными параметрам
def _prepare_entities(self): """ Получение выборки объектов модели по указанными параметрам """ self._entities = self._actual_entities_queryset.filter( **self._additional_filter_params, ) if self._only_fields: self._entities = self._entities.only(...
[ "def", "_prepare_entities", "(", "self", ")", ":", "self", ".", "_entities", "=", "self", ".", "_actual_entities_queryset", ".", "filter", "(", "*", "*", "self", ".", "_additional_filter_params", ",", ")", "if", "self", ".", "_only_fields", ":", "self", ".",...
[ 129, 4 ]
[ 140, 50 ]
python
en
['en', 'error', 'th']
False
EntityCache._prepare_entities_hash_table
(self)
Отвечает за построение хеш таблицы для дальнейшего поиска. В качестве ключа можно задавать строку - наименование поля или кортеж наименований полей. Если требуется доступ через внешний ключ, то необходимо использовать точку в качестве разделителей. Например, searching_k...
Отвечает за построение хеш таблицы для дальнейшего поиска. В качестве ключа можно задавать строку - наименование поля или кортеж наименований полей.
def _prepare_entities_hash_table(self): """ Отвечает за построение хеш таблицы для дальнейшего поиска. В качестве ключа можно задавать строку - наименование поля или кортеж наименований полей. Если требуется доступ через внешний ключ, то необходимо использовать точку в к...
[ "def", "_prepare_entities_hash_table", "(", "self", ")", ":", "hash_table", "=", "{", "}", "key_items_count", "=", "len", "(", "self", ".", "_searching_key", ")", "for", "entity", "in", "self", ".", "_entities", ":", "temp_hash_item", "=", "hash_table", "for",...
[ 142, 4 ]
[ 182, 46 ]
python
en
['en', 'error', 'th']
False
EntityCache._prepare_actual_entities_queryset
(self)
Подготовка менеджена с указанием идентификатора учреждения и состояния, если такие имеются у модели
Подготовка менеджена с указанием идентификатора учреждения и состояния, если такие имеются у модели
def _prepare_actual_entities_queryset(self): """ Подготовка менеджена с указанием идентификатора учреждения и состояния, если такие имеются у модели """ actual_entities_queryset = self._model._base_manager.all() if self._select_related_fields: actual_entities...
[ "def", "_prepare_actual_entities_queryset", "(", "self", ")", ":", "actual_entities_queryset", "=", "self", ".", "_model", ".", "_base_manager", ".", "all", "(", ")", "if", "self", ".", "_select_related_fields", ":", "actual_entities_queryset", "=", "actual_entities_q...
[ 184, 4 ]
[ 196, 39 ]
python
en
['en', 'error', 'th']
False
EntityCache.filter
( self, only_first: bool = False, **kwargs, )
Метод фильтрации объектов кеша по заданным параметрам. Пример использования: some_objects_list = cache.filter(code='12345', only_first=True) Можно получать первое попавшееся значение с указанием only_first=True
Метод фильтрации объектов кеша по заданным параметрам.
def filter( self, only_first: bool = False, **kwargs, ): """ Метод фильтрации объектов кеша по заданным параметрам. Пример использования: some_objects_list = cache.filter(code='12345', only_first=True) Можно получать первое попавшееся значение с ука...
[ "def", "filter", "(", "self", ",", "only_first", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ",", ")", ":", "filter_", "=", "OrderedDict", "(", ")", "for", "field_name", ",", "field_value", "in", "kwargs", ".", "items", "(", ")", ":", "prepar...
[ 198, 4 ]
[ 240, 21 ]
python
en
['en', 'error', 'th']
False
EntityCache.flat_values_list
( self, field_name: str, )
Получение плоского списка значений объектов указанного свойства без пустых значений. : param field_name: наименование поля
Получение плоского списка значений объектов указанного свойства без пустых значений.
def flat_values_list( self, field_name: str, ): """ Получение плоского списка значений объектов указанного свойства без пустых значений. : param field_name: наименование поля """ return list( filter( None, [...
[ "def", "flat_values_list", "(", "self", ",", "field_name", ":", "str", ",", ")", ":", "return", "list", "(", "filter", "(", "None", ",", "[", "getattr", "(", "entity", ",", "field_name", ",", "None", ")", "for", "entity", "in", "self", ".", "_entities"...
[ 242, 4 ]
[ 260, 9 ]
python
en
['en', 'error', 'th']
False
EntityCache._check_is_iterable
(self, object_)
Проверяет, является ли передаваемый объект итерабельным
Проверяет, является ли передаваемый объект итерабельным
def _check_is_iterable(self, object_): """ Проверяет, является ли передаваемый объект итерабельным """ return ( isinstance(object_, (Iterable, Sequence)) and not isinstance(object_, str) )
[ "def", "_check_is_iterable", "(", "self", ",", "object_", ")", ":", "return", "(", "isinstance", "(", "object_", ",", "(", "Iterable", ",", "Sequence", ")", ")", "and", "not", "isinstance", "(", "object_", ",", "str", ")", ")" ]
[ 262, 4 ]
[ 269, 9 ]
python
en
['en', 'error', 'th']
False
EntityCache.get_by_key
( self, key: Union[Any, Tuple[Any]], strict_mode=True, )
Метод получения значения из кеша по ключу поиска. В общем случае передаваемый ключ должен совпадать с _searching_key. Если отключить строгий режим поиска - strict_mode=False, то можно получить промежуточный результат по части ключа следующего с начала.
Метод получения значения из кеша по ключу поиска.
def get_by_key( self, key: Union[Any, Tuple[Any]], strict_mode=True, ): """ Метод получения значения из кеша по ключу поиска. В общем случае передаваемый ключ должен совпадать с _searching_key. Если отключить строгий режим поиска - strict_mode=False, то можно...
[ "def", "get_by_key", "(", "self", ",", "key", ":", "Union", "[", "Any", ",", "Tuple", "[", "Any", "]", "]", ",", "strict_mode", "=", "True", ",", ")", ":", "key", "=", "(", "key", "if", "self", ".", "_check_is_iterable", "(", "key", ")", "else", ...
[ 271, 4 ]
[ 314, 21 ]
python
en
['en', 'error', 'th']
False
EntityCache.values_list
( self, fields: Tuple[str, ...], )
Получение списка кортежей состоящих из значений полей объектов согласно заданным параметрам :param fields: кортеж наименований полей
Получение списка кортежей состоящих из значений полей объектов согласно заданным параметрам
def values_list( self, fields: Tuple[str, ...], ) -> Optional[List[Tuple]]: """ Получение списка кортежей состоящих из значений полей объектов согласно заданным параметрам :param fields: кортеж наименований полей """ fields_getter = attrgetter(*fields...
[ "def", "values_list", "(", "self", ",", "fields", ":", "Tuple", "[", "str", ",", "...", "]", ",", ")", "->", "Optional", "[", "List", "[", "Tuple", "]", "]", ":", "fields_getter", "=", "attrgetter", "(", "*", "fields", ")", "return", "[", "fields_get...
[ 316, 4 ]
[ 331, 9 ]
python
en
['en', 'error', 'th']
False
EntityCache.first
(self)
Получение первого элемента из кеша
Получение первого элемента из кеша
def first(self): """ Получение первого элемента из кеша """ result = None if self._entities: result = self._entities[0] return result
[ "def", "first", "(", "self", ")", ":", "result", "=", "None", "if", "self", ".", "_entities", ":", "result", "=", "self", ".", "_entities", "[", "0", "]", "return", "result" ]
[ 333, 4 ]
[ 342, 21 ]
python
en
['en', 'error', 'th']
False
ActualEntityCache._prepare_actual_entities_queryset
(self)
Метод получения фильтра актуализации по дате.
Метод получения фильтра актуализации по дате.
def _prepare_actual_entities_queryset(self) -> Dict[str, date]: """ Метод получения фильтра актуализации по дате. """ actual_entities_queryset = super()._prepare_actual_entities_queryset() actual_entities_queryset = actual_entities_queryset.filter( begin__lte=self._a...
[ "def", "_prepare_actual_entities_queryset", "(", "self", ")", "->", "Dict", "[", "str", ",", "date", "]", ":", "actual_entities_queryset", "=", "super", "(", ")", ".", "_prepare_actual_entities_queryset", "(", ")", "actual_entities_queryset", "=", "actual_entities_que...
[ 360, 4 ]
[ 371, 39 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache.old
(self)
Кеш объектов модели актуальных на начальную дату
Кеш объектов модели актуальных на начальную дату
def old(self): """ Кеш объектов модели актуальных на начальную дату """ return self._old_entities_cache
[ "def", "old", "(", "self", ")", ":", "return", "self", ".", "_old_entities_cache" ]
[ 435, 4 ]
[ 439, 39 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache.new
(self)
Кеш объектов модели актуальный на конечную дату
Кеш объектов модели актуальный на конечную дату
def new(self): """ Кеш объектов модели актуальный на конечную дату """ return self._new_entities_cache
[ "def", "new", "(", "self", ")", ":", "return", "self", ".", "_new_entities_cache" ]
[ 442, 4 ]
[ 446, 39 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._get_actuality_filter
( self, period_type: str, )
Метод получения фильтра актуализации по дате. При получении счетов или аналитик при переносе остатков необходимо учитывать период действия следуя следующей логике: -- старые - begin < date_from && end >= date_from -- новые - begin <= date_to && end > date_to :param di...
Метод получения фильтра актуализации по дате.
def _get_actuality_filter( self, period_type: str, ) -> Dict[str, date]: """ Метод получения фильтра актуализации по дате. При получении счетов или аналитик при переносе остатков необходимо учитывать период действия следуя следующей логике: -- старые - begin ...
[ "def", "_get_actuality_filter", "(", "self", ",", "period_type", ":", "str", ",", ")", "->", "Dict", "[", "str", ",", "date", "]", ":", "if", "period_type", "==", "TransferPeriodEnum", ".", "OLD", ":", "actuality_filter", "=", "{", "'begin__lt'", ":", "sel...
[ 448, 4 ]
[ 474, 31 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_entities_cache
( self, additional_filter_params: Optional[Dict[str, Any]] )
Создание кеша объектов модели на указанную дату по указанным параметром с ключом поиска для построения хеш-таблицы
Создание кеша объектов модели на указанную дату по указанным параметром с ключом поиска для построения хеш-таблицы
def _prepare_entities_cache( self, additional_filter_params: Optional[Dict[str, Any]] ): """ Создание кеша объектов модели на указанную дату по указанным параметром с ключом поиска для построения хеш-таблицы """ entities_cache = self.entity_cache_class( ...
[ "def", "_prepare_entities_cache", "(", "self", ",", "additional_filter_params", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ")", ":", "entities_cache", "=", "self", ".", "entity_cache_class", "(", "model", "=", "self", ".", "_model", ",",...
[ 476, 4 ]
[ 492, 29 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_additional_filter_params
( self, period_type: str, )
Подготовка словаря с дополнительными параметрами для дальнейшей фильтрации объектов при формировании кеша
Подготовка словаря с дополнительными параметрами для дальнейшей фильтрации объектов при формировании кеша
def _prepare_additional_filter_params( self, period_type: str, ): """ Подготовка словаря с дополнительными параметрами для дальнейшей фильтрации объектов при формировании кеша """ additional_filter_params = deepcopy(self._additional_filter_params) addi...
[ "def", "_prepare_additional_filter_params", "(", "self", ",", "period_type", ":", "str", ",", ")", ":", "additional_filter_params", "=", "deepcopy", "(", "self", ".", "_additional_filter_params", ")", "additional_filter_params", ".", "update", "(", "*", "*", "self",...
[ 494, 4 ]
[ 509, 39 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_old_additional_filter_params
(self)
Подготовка дополнительных параметров фильтрации на начальную дату
Подготовка дополнительных параметров фильтрации на начальную дату
def _prepare_old_additional_filter_params(self): """ Подготовка дополнительных параметров фильтрации на начальную дату """ return self._prepare_additional_filter_params( period_type=TransferPeriodEnum.OLD, )
[ "def", "_prepare_old_additional_filter_params", "(", "self", ")", ":", "return", "self", ".", "_prepare_additional_filter_params", "(", "period_type", "=", "TransferPeriodEnum", ".", "OLD", ",", ")" ]
[ 511, 4 ]
[ 517, 9 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_new_additional_filter_params
(self)
Подготовка дополнительных параметров фильтрации на конечную дату
Подготовка дополнительных параметров фильтрации на конечную дату
def _prepare_new_additional_filter_params(self): """ Подготовка дополнительных параметров фильтрации на конечную дату """ return self._prepare_additional_filter_params( period_type=TransferPeriodEnum.NEW, )
[ "def", "_prepare_new_additional_filter_params", "(", "self", ")", ":", "return", "self", ".", "_prepare_additional_filter_params", "(", "period_type", "=", "TransferPeriodEnum", ".", "NEW", ",", ")" ]
[ 519, 4 ]
[ 525, 9 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_old_entities_cache
(self)
Формирование кеша объектов модели на начальную дату
Формирование кеша объектов модели на начальную дату
def _prepare_old_entities_cache(self): """ Формирование кеша объектов модели на начальную дату """ additional_filter_params = self._prepare_old_additional_filter_params() self._old_entities_cache = self._prepare_entities_cache( additional_filter_params=additional_filt...
[ "def", "_prepare_old_entities_cache", "(", "self", ")", ":", "additional_filter_params", "=", "self", ".", "_prepare_old_additional_filter_params", "(", ")", "self", ".", "_old_entities_cache", "=", "self", ".", "_prepare_entities_cache", "(", "additional_filter_params", ...
[ 527, 4 ]
[ 534, 9 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare_new_entities_cache
(self)
Формирование кеша объектов модели на конечную дату
Формирование кеша объектов модели на конечную дату
def _prepare_new_entities_cache(self): """ Формирование кеша объектов модели на конечную дату """ additional_filter_params = self._prepare_new_additional_filter_params() self._new_entities_cache = self._prepare_entities_cache( additional_filter_params=additional_filte...
[ "def", "_prepare_new_entities_cache", "(", "self", ")", ":", "additional_filter_params", "=", "self", ".", "_prepare_new_additional_filter_params", "(", ")", "self", ".", "_new_entities_cache", "=", "self", ".", "_prepare_entities_cache", "(", "additional_filter_params", ...
[ 536, 4 ]
[ 543, 9 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._before_prepare
(self)
Точка расширения перед формированием кеша
Точка расширения перед формированием кеша
def _before_prepare(self): """ Точка расширения перед формированием кеша """
[ "def", "_before_prepare", "(", "self", ")", ":" ]
[ 545, 4 ]
[ 548, 11 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._prepare
(self)
Формирование кешей на начальную и конечную даты
Формирование кешей на начальную и конечную даты
def _prepare(self): """ Формирование кешей на начальную и конечную даты """ self._prepare_old_entities_cache() self._prepare_new_entities_cache()
[ "def", "_prepare", "(", "self", ")", ":", "self", ".", "_prepare_old_entities_cache", "(", ")", "self", ".", "_prepare_new_entities_cache", "(", ")" ]
[ 550, 4 ]
[ 555, 42 ]
python
en
['en', 'error', 'th']
False
PeriodicalEntityCache._after_prepare
(self)
Точка расширения после формирования кеша
Точка расширения после формирования кеша
def _after_prepare(self): """ Точка расширения после формирования кеша """
[ "def", "_after_prepare", "(", "self", ")", ":" ]
[ 557, 4 ]
[ 560, 11 ]
python
en
['en', 'error', 'th']
False
PyCollectorMock._makeitem
(self, *k)
hack to disable the actual behaviour
hack to disable the actual behaviour
def _makeitem(self, *k): """hack to disable the actual behaviour""" self.called = True
[ "def", "_makeitem", "(", "self", ",", "*", "k", ")", ":", "self", ".", "called", "=", "True" ]
[ 11, 4 ]
[ 13, 26 ]
python
en
['en', 'en', 'en']
True
test_importplugin_error_message
(testdir, pytestpm)
Don't hide import errors when importing plugins and provide an easy to debug message. See #375 and #1998.
Don't hide import errors when importing plugins and provide an easy to debug message.
def test_importplugin_error_message(testdir, pytestpm): """Don't hide import errors when importing plugins and provide an easy to debug message. See #375 and #1998. """ testdir.syspathinsert(testdir.tmpdir) testdir.makepyfile(qwe=""" # encoding: UTF-8 def test_traceback(): ...
[ "def", "test_importplugin_error_message", "(", "testdir", ",", "pytestpm", ")", ":", "testdir", ".", "syspathinsert", "(", "testdir", ".", "tmpdir", ")", "testdir", ".", "makepyfile", "(", "qwe", "=", "\"\"\"\n # encoding: UTF-8\n def test_traceback():\n ...
[ 194, 0 ]
[ 213, 67 ]
python
en
['en', 'en', 'en']
True
TestPytestPluginInteractions.test_hook_proxy
(self, testdir)
Test the gethookproxy function(#2016)
Test the gethookproxy function(#2016)
def test_hook_proxy(self, testdir): """Test the gethookproxy function(#2016)""" config = testdir.parseconfig() session = Session(config) testdir.makepyfile(**{ 'tests/conftest.py': '', 'tests/subdir/conftest.py': '', }) conftest1 = testdir.tmpdir....
[ "def", "test_hook_proxy", "(", "self", ",", "testdir", ")", ":", "config", "=", "testdir", ".", "parseconfig", "(", ")", "session", "=", "Session", "(", "config", ")", "testdir", ".", "makepyfile", "(", "*", "*", "{", "'tests/conftest.py'", ":", "''", ",...
[ 140, 4 ]
[ 157, 37 ]
python
en
['en', 'en', 'en']
True
AutoLinker.updated
(self, properties, prev, next)
Notification that a values was updated and the linkage between the I{properties} contained with I{prev} need to be relinked to the L{Properties} contained within the I{next} value.
Notification that a values was updated and the linkage between the I{properties} contained with I{prev} need to be relinked to the L{Properties} contained within the I{next} value.
def updated(self, properties, prev, next): """ Notification that a values was updated and the linkage between the I{properties} contained with I{prev} need to be relinked to the L{Properties} contained within the I{next} value. """ pass
[ "def", "updated", "(", "self", ",", "properties", ",", "prev", ",", "next", ")", ":", "pass" ]
[ 31, 4 ]
[ 38, 12 ]
python
en
['en', 'error', 'th']
False
Link.__init__
(self, a, b)
@param a: Property (A) to link. @type a: L{Property} @param b: Property (B) to link. @type b: L{Property}
def __init__(self, a, b): """ @param a: Property (A) to link. @type a: L{Property} @param b: Property (B) to link. @type b: L{Property} """ pA = Endpoint(self, a) pB = Endpoint(self, b) self.endpoints = (pA, pB) self.validate(a, b) ...
[ "def", "__init__", "(", "self", ",", "a", ",", "b", ")", ":", "pA", "=", "Endpoint", "(", "self", ",", "a", ")", "pB", "=", "Endpoint", "(", "self", ",", "b", ")", "self", ".", "endpoints", "=", "(", "pA", ",", "pB", ")", "self", ".", "valida...
[ 47, 4 ]
[ 59, 26 ]
python
en
['en', 'error', 'th']
False
Link.validate
(self, pA, pB)
Validate that the two properties may be linked. @param pA: Endpoint (A) to link. @type pA: L{Endpoint} @param pB: Endpoint (B) to link. @type pB: L{Endpoint} @return: self @rtype: L{Link}
Validate that the two properties may be linked.
def validate(self, pA, pB): """ Validate that the two properties may be linked. @param pA: Endpoint (A) to link. @type pA: L{Endpoint} @param pB: Endpoint (B) to link. @type pB: L{Endpoint} @return: self @rtype: L{Link} """ if pA in pB.link...
[ "def", "validate", "(", "self", ",", "pA", ",", "pB", ")", ":", "if", "pA", "in", "pB", ".", "links", "or", "pB", "in", "pA", ".", "links", ":", "raise", "Exception", ",", "'Already linked'", "dA", "=", "pA", ".", "domains", "(", ")", "dB", "=", ...
[ 61, 4 ]
[ 90, 19 ]
python
en
['en', 'error', 'th']
False
Link.teardown
(self)
Teardown the link. Removes endpoints from properties I{links} collection. @return: self @rtype: L{Link}
Teardown the link. Removes endpoints from properties I{links} collection.
def teardown(self): """ Teardown the link. Removes endpoints from properties I{links} collection. @return: self @rtype: L{Link} """ pA, pB = self.endpoints if pA in pB.links: pB.links.remove(pA) if pB in pA.links: pA.links.r...
[ "def", "teardown", "(", "self", ")", ":", "pA", ",", "pB", "=", "self", ".", "endpoints", "if", "pA", "in", "pB", ".", "links", ":", "pB", ".", "links", ".", "remove", "(", "pA", ")", "if", "pB", "in", "pA", ".", "links", ":", "pA", ".", "lin...
[ 92, 4 ]
[ 104, 19 ]
python
en
['en', 'error', 'th']
False
Definition.__init__
(self, name, classes, default, linker=AutoLinker())
@param name: The property name. @type name: str @param classes: The (class) list of permitted values @type classes: tuple @param default: The default value. @type default: any
def __init__(self, name, classes, default, linker=AutoLinker()): """ @param name: The property name. @type name: str @param classes: The (class) list of permitted values @type classes: tuple @param default: The default value. @type default: any """ ...
[ "def", "__init__", "(", "self", ",", "name", ",", "classes", ",", "default", ",", "linker", "=", "AutoLinker", "(", ")", ")", ":", "if", "not", "isinstance", "(", "classes", ",", "(", "list", ",", "tuple", ")", ")", ":", "classes", "=", "(", "class...
[ 142, 4 ]
[ 156, 28 ]
python
en
['en', 'error', 'th']
False
Definition.nvl
(self, value=None)
Convert the I{value} into the default when I{None}. @param value: The proposed value. @type value: any @return: The I{default} when I{value} is I{None}, else I{value}. @rtype: any
Convert the I{value} into the default when I{None}.
def nvl(self, value=None): """ Convert the I{value} into the default when I{None}. @param value: The proposed value. @type value: any @return: The I{default} when I{value} is I{None}, else I{value}. @rtype: any """ if value is None: return self...
[ "def", "nvl", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "self", ".", "default", "else", ":", "return", "value" ]
[ 158, 4 ]
[ 169, 24 ]
python
en
['en', 'error', 'th']
False
Definition.validate
(self, value)
Validate the I{value} is of the correct class. @param value: The value to validate. @type value: any @raise AttributeError: When I{value} is invalid.
Validate the I{value} is of the correct class.
def validate(self, value): """ Validate the I{value} is of the correct class. @param value: The value to validate. @type value: any @raise AttributeError: When I{value} is invalid. """ if value is None: return if len(self.classes) and \ ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "if", "len", "(", "self", ".", "classes", ")", "and", "not", "isinstance", "(", "value", ",", "self", ".", "classes", ")", ":", "msg", "=", "'\"%s\"...
[ 171, 4 ]
[ 183, 40 ]
python
en
['en', 'error', 'th']
False
Properties.__init__
(self, domain, definitions, kwargs)
@param domain: The property domain name. @type domain: str @param definitions: A table of property definitions. @type definitions: {name: L{Definition}} @param kwargs: A list of property name/values to set. @type kwargs: dict
def __init__(self, domain, definitions, kwargs): """ @param domain: The property domain name. @type domain: str @param definitions: A table of property definitions. @type definitions: {name: L{Definition}} @param kwargs: A list of property name/values to set. @typ...
[ "def", "__init__", "(", "self", ",", "domain", ",", "definitions", ",", "kwargs", ")", ":", "self", ".", "definitions", "=", "{", "}", "for", "d", "in", "definitions", ":", "self", ".", "definitions", "[", "d", ".", "name", "]", "=", "d", "self", "...
[ 214, 4 ]
[ 231, 27 ]
python
en
['en', 'error', 'th']
False
Properties.definition
(self, name)
Get the definition for the property I{name}. @param name: The property I{name} to find the definition for. @type name: str @return: The property definition @rtype: L{Definition} @raise AttributeError: On not found.
Get the definition for the property I{name}.
def definition(self, name): """ Get the definition for the property I{name}. @param name: The property I{name} to find the definition for. @type name: str @return: The property definition @rtype: L{Definition} @raise AttributeError: On not found. """ ...
[ "def", "definition", "(", "self", ",", "name", ")", ":", "d", "=", "self", ".", "definitions", ".", "get", "(", "name", ")", "if", "d", "is", "None", ":", "raise", "AttributeError", "(", "name", ")", "return", "d" ]
[ 233, 4 ]
[ 245, 16 ]
python
en
['en', 'error', 'th']
False
Properties.update
(self, other)
Update the property values as specified by keyword/value. @param other: An object to update from. @type other: (dict|L{Properties}) @return: self @rtype: L{Properties}
Update the property values as specified by keyword/value.
def update(self, other): """ Update the property values as specified by keyword/value. @param other: An object to update from. @type other: (dict|L{Properties}) @return: self @rtype: L{Properties} """ if isinstance(other, Properties): other = o...
[ "def", "update", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Properties", ")", ":", "other", "=", "other", ".", "defined", "for", "n", ",", "v", "in", "other", ".", "items", "(", ")", ":", "self", ".", "set", "(",...
[ 247, 4 ]
[ 259, 19 ]
python
en
['en', 'error', 'th']
False
Properties.notset
(self, name)
Get whether a property has never been set by I{name}. @param name: A property name. @type name: str @return: True if never been set. @rtype: bool
Get whether a property has never been set by I{name}.
def notset(self, name): """ Get whether a property has never been set by I{name}. @param name: A property name. @type name: str @return: True if never been set. @rtype: bool """ self.provider(name).__notset(name)
[ "def", "notset", "(", "self", ",", "name", ")", ":", "self", ".", "provider", "(", "name", ")", ".", "__notset", "(", "name", ")" ]
[ 261, 4 ]
[ 269, 42 ]
python
en
['en', 'error', 'th']
False
Properties.set
(self, name, value)
Set the I{value} of a property by I{name}. The value is validated against the definition and set to the default when I{value} is None. @param name: The property name. @type name: str @param value: The new property value. @type value: any @return: self ...
Set the I{value} of a property by I{name}. The value is validated against the definition and set to the default when I{value} is None.
def set(self, name, value): """ Set the I{value} of a property by I{name}. The value is validated against the definition and set to the default when I{value} is None. @param name: The property name. @type name: str @param value: The new property value. @ty...
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "provider", "(", "name", ")", ".", "__set", "(", "name", ",", "value", ")", "return", "self" ]
[ 271, 4 ]
[ 284, 19 ]
python
en
['en', 'error', 'th']
False
Properties.unset
(self, name)
Unset a property by I{name}. @param name: A property name. @type name: str @return: self @rtype: L{Properties}
Unset a property by I{name}.
def unset(self, name): """ Unset a property by I{name}. @param name: A property name. @type name: str @return: self @rtype: L{Properties} """ self.provider(name).__set(name, None) return self
[ "def", "unset", "(", "self", ",", "name", ")", ":", "self", ".", "provider", "(", "name", ")", ".", "__set", "(", "name", ",", "None", ")", "return", "self" ]
[ 286, 4 ]
[ 295, 19 ]
python
en
['en', 'error', 'th']
False
Properties.get
(self, name, *df)
Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set. @rtype: any
Get the value of a property by I{name}.
def get(self, name, *df): """ Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set...
[ "def", "get", "(", "self", ",", "name", ",", "*", "df", ")", ":", "return", "self", ".", "provider", "(", "name", ")", ".", "__get", "(", "name", ",", "*", "df", ")" ]
[ 297, 4 ]
[ 308, 51 ]
python
en
['en', 'error', 'th']
False
Properties.link
(self, other)
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties}
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional.
def link(self, other): """ Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties} """ ...
[ "def", "link", "(", "self", ",", "other", ")", ":", "Link", "(", "self", ",", "other", ")", "return", "self" ]
[ 310, 4 ]
[ 320, 19 ]
python
en
['en', 'error', 'th']
False
Properties.unlink
(self, *others)
Unlink (disassociate) the specified properties object. @param others: The list object to unlink. Unspecified means unlink all. @type others: [L{Properties},..] @return: self @rtype: L{Properties}
Unlink (disassociate) the specified properties object.
def unlink(self, *others): """ Unlink (disassociate) the specified properties object. @param others: The list object to unlink. Unspecified means unlink all. @type others: [L{Properties},..] @return: self @rtype: L{Properties} """ if not len(others): ...
[ "def", "unlink", "(", "self", ",", "*", "others", ")", ":", "if", "not", "len", "(", "others", ")", ":", "others", "=", "self", ".", "links", "[", ":", "]", "for", "p", "in", "self", ".", "links", "[", ":", "]", ":", "if", "p", "in", "others"...
[ 322, 4 ]
[ 335, 19 ]
python
en
['en', 'error', 'th']
False
Properties.provider
(self, name, history=None)
Find the provider of the property by I{name}. @param name: The property name. @type name: str @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: The provider when found. Otherwise, None (when ne...
Find the provider of the property by I{name}.
def provider(self, name, history=None): """ Find the provider of the property by I{name}. @param name: The property name. @type name: str @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return:...
[ "def", "provider", "(", "self", ",", "name", ",", "history", "=", "None", ")", ":", "if", "history", "is", "None", ":", "history", "=", "[", "]", "history", ".", "append", "(", "self", ")", "if", "name", "in", "self", ".", "definitions", ":", "retu...
[ 337, 4 ]
[ 363, 19 ]
python
en
['en', 'error', 'th']
False
Properties.keys
(self, history=None)
Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list
Get the set of I{all} property names.
def keys(self, history=None): """ Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list """ if history is N...
[ "def", "keys", "(", "self", ",", "history", "=", "None", ")", ":", "if", "history", "is", "None", ":", "history", "=", "[", "]", "history", ".", "append", "(", "self", ")", "keys", "=", "set", "(", ")", "keys", ".", "update", "(", "self", ".", ...
[ 365, 4 ]
[ 384, 19 ]
python
en
['en', 'error', 'th']
False
Properties.domains
(self, history=None)
Get the set of I{all} domain names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of domain names. @rtype: list
Get the set of I{all} domain names.
def domains(self, history=None): """ Get the set of I{all} domain names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of domain names. @rtype: list """ if history is No...
[ "def", "domains", "(", "self", ",", "history", "=", "None", ")", ":", "if", "history", "is", "None", ":", "history", "=", "[", "]", "history", ".", "append", "(", "self", ")", "domains", "=", "set", "(", ")", "domains", ".", "add", "(", "self", "...
[ 386, 4 ]
[ 405, 22 ]
python
en
['en', 'error', 'th']
False
Properties.prime
(self)
Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties}
Prime the stored values based on default values found in property definitions.
def prime(self): """ Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties} """ for d in self.definitions.values(): self.defined[d.name] = d.default return self
[ "def", "prime", "(", "self", ")", ":", "for", "d", "in", "self", ".", "definitions", ".", "values", "(", ")", ":", "self", ".", "defined", "[", "d", ".", "name", "]", "=", "d", ".", "default", "return", "self" ]
[ 407, 4 ]
[ 416, 19 ]
python
en
['en', 'error', 'th']
False
Inspector.get
(self, name, *df)
Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set. @rtype: any
Get the value of a property by I{name}.
def get(self, name, *df): """ Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set...
[ "def", "get", "(", "self", ",", "name", ",", "*", "df", ")", ":", "return", "self", ".", "properties", ".", "get", "(", "name", ",", "*", "df", ")" ]
[ 498, 4 ]
[ 509, 45 ]
python
en
['en', 'error', 'th']
False
Inspector.update
(self, **kwargs)
Update the property values as specified by keyword/value. @param kwargs: A list of property name/values to set. @type kwargs: dict @return: self @rtype: L{Properties}
Update the property values as specified by keyword/value.
def update(self, **kwargs): """ Update the property values as specified by keyword/value. @param kwargs: A list of property name/values to set. @type kwargs: dict @return: self @rtype: L{Properties} """ return self.properties.update(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "properties", ".", "update", "(", "*", "*", "kwargs", ")" ]
[ 511, 4 ]
[ 519, 47 ]
python
en
['en', 'error', 'th']
False
Inspector.link
(self, other)
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties}
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional.
def link(self, other): """ Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties} """ ...
[ "def", "link", "(", "self", ",", "other", ")", ":", "p", "=", "other", ".", "__pts__", "return", "self", ".", "properties", ".", "link", "(", "p", ")" ]
[ 521, 4 ]
[ 531, 38 ]
python
en
['en', 'error', 'th']
False
Inspector.unlink
(self, other)
Unlink (disassociate) the specified properties object. @param other: The object to unlink. @type other: L{Properties} @return: self @rtype: L{Properties}
Unlink (disassociate) the specified properties object.
def unlink(self, other): """ Unlink (disassociate) the specified properties object. @param other: The object to unlink. @type other: L{Properties} @return: self @rtype: L{Properties} """ p = other.__pts__ return self.properties.unlink(p)
[ "def", "unlink", "(", "self", ",", "other", ")", ":", "p", "=", "other", ".", "__pts__", "return", "self", ".", "properties", ".", "unlink", "(", "p", ")" ]
[ 533, 4 ]
[ 542, 40 ]
python
en
['en', 'error', 'th']
False
ParamGenerator.generate_params
(self, randomize=True)
Supposed to be a generator (so should yield dicts of parameters).
Supposed to be a generator (so should yield dicts of parameters).
def generate_params(self, randomize=True): """Supposed to be a generator (so should yield dicts of parameters).""" pass
[ "def", "generate_params", "(", "self", ",", "randomize", "=", "True", ")", ":", "pass" ]
[ 14, 4 ]
[ 16, 12 ]
python
en
['en', 'en', 'en']
True
ParamGrid.__init__
(self, grid_tuples)
Uses OrderedDict, so must be initialized with the list of tuples if you want to preserve order.
Uses OrderedDict, so must be initialized with the list of tuples if you want to preserve order.
def __init__(self, grid_tuples): """Uses OrderedDict, so must be initialized with the list of tuples if you want to preserve order.""" super(ParamGrid, self).__init__() self.grid = OrderedDict(grid_tuples)
[ "def", "__init__", "(", "self", ",", "grid_tuples", ")", ":", "super", "(", "ParamGrid", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "grid", "=", "OrderedDict", "(", "grid_tuples", ")" ]
[ 39, 4 ]
[ 42, 44 ]
python
en
['en', 'en', 'en']
True
ParamGrid._generate_combinations
(self, param_idx, params)
Recursively generate all parameter combinations in a grid.
Recursively generate all parameter combinations in a grid.
def _generate_combinations(self, param_idx, params): """Recursively generate all parameter combinations in a grid.""" if param_idx == len(self.grid) - 1: # last parameter, just return list of values for this parameter return [[value] for value in self.grid[params[param_idx]]] ...
[ "def", "_generate_combinations", "(", "self", ",", "param_idx", ",", "params", ")", ":", "if", "param_idx", "==", "len", "(", "self", ".", "grid", ")", "-", "1", ":", "# last parameter, just return list of values for this parameter", "return", "[", "[", "value", ...
[ 44, 4 ]
[ 59, 25 ]
python
en
['en', 'en', 'en']
True
Experiment.__init__
(self, name, cmd, param_generator, env_vars=None)
:param cmd: base command to append the parameters to :param param_generator: iterable of parameter dicts
:param cmd: base command to append the parameters to :param param_generator: iterable of parameter dicts
def __init__(self, name, cmd, param_generator, env_vars=None): """ :param cmd: base command to append the parameters to :param param_generator: iterable of parameter dicts """ self.base_name = name self.cmd = cmd self.params = list(param_generator) self.en...
[ "def", "__init__", "(", "self", ",", "name", ",", "cmd", ",", "param_generator", ",", "env_vars", "=", "None", ")", ":", "self", ".", "base_name", "=", "name", "self", ".", "cmd", "=", "cmd", "self", ".", "params", "=", "list", "(", "param_generator", ...
[ 82, 4 ]
[ 90, 32 ]
python
en
['en', 'error', 'th']
False
Experiment.generate_experiments
(self)
Yields tuples of (cmd, experiment_name)
Yields tuples of (cmd, experiment_name)
def generate_experiments(self): """Yields tuples of (cmd, experiment_name)""" num_experiments = 1 if len(self.params) == 0 else len(self.params) for experiment_idx in range(num_experiments): cmd_tokens = [self.cmd] experiment_name_tokens = [self.base_name] #...
[ "def", "generate_experiments", "(", "self", ")", ":", "num_experiments", "=", "1", "if", "len", "(", "self", ".", "params", ")", "==", "0", "else", "len", "(", "self", ".", "params", ")", "for", "experiment_idx", "in", "range", "(", "num_experiments", ")...
[ 92, 4 ]
[ 124, 44 ]
python
en
['en', 'en', 'en']
True
RunDescription.generate_experiments
(self)
Yields tuples (final cmd for experiment, experiment_name, root_dir).
Yields tuples (final cmd for experiment, experiment_name, root_dir).
def generate_experiments(self): """Yields tuples (final cmd for experiment, experiment_name, root_dir).""" for experiment in self.experiments: root_dir = join(self.run_name, f'{experiment.base_name}_{self.experiment_suffix}') experiment_cmds = experiment.generate_experiments() ...
[ "def", "generate_experiments", "(", "self", ")", ":", "for", "experiment", "in", "self", ".", "experiments", ":", "root_dir", "=", "join", "(", "self", ".", "run_name", ",", "f'{experiment.base_name}_{self.experiment_suffix}'", ")", "experiment_cmds", "=", "experime...
[ 137, 4 ]
[ 145, 84 ]
python
en
['en', 'en', 'en']
True
deep_getattr
( obj, attr, default=None, )
Получить значение атрибута с любого уровня цепочки вложенных объектов. :param object obj: объект, у которого ищется значение атрибута :param str attr: атрибут, значение которого необходимо получить ( указывается полная цепочка, т.е. 'attr1.attr2.atr3') :param object default: значение по умолча...
Получить значение атрибута с любого уровня цепочки вложенных объектов.
def deep_getattr( obj, attr, default=None, ): """ Получить значение атрибута с любого уровня цепочки вложенных объектов. :param object obj: объект, у которого ищется значение атрибута :param str attr: атрибут, значение которого необходимо получить ( указывается полная цепочка, т.е. ...
[ "def", "deep_getattr", "(", "obj", ",", "attr", ",", "default", "=", "None", ",", ")", ":", "try", ":", "value", "=", "operator", ".", "attrgetter", "(", "attr", ")", "(", "obj", ")", "except", "(", "AttributeError", ",", "ValueError", ",", "ObjectDoes...
[ 16, 0 ]
[ 40, 16 ]
python
en
['en', 'error', 'th']
False
date2str
(date, template=None)
datetime.strftime глючит с годом < 1900 типа обходной маневр (взято из django) WARNING from django: # This library does not support strftime's \"%s\" or \"%y\" format strings. # Allowed if there's an even number of \"%\"s because they are escaped.
datetime.strftime глючит с годом < 1900 типа обходной маневр (взято из django)
def date2str(date, template=None): """ datetime.strftime глючит с годом < 1900 типа обходной маневр (взято из django) WARNING from django: # This library does not support strftime's \"%s\" or \"%y\" format strings. # Allowed if there's an even number of \"%\"s because they are escaped. """ ...
[ "def", "date2str", "(", "date", ",", "template", "=", "None", ")", ":", "return", "datetime_safe", ".", "new_datetime", "(", "date", ")", ".", "strftime", "(", "template", "or", "settings", ".", "DATE_FORMAT", "or", "'%d.%m.%Y'", ")" ]
[ 43, 0 ]
[ 56, 5 ]
python
en
['en', 'error', 'th']
False
rebind_model_rel_id
(obj)
Функция перепривязки идентификатора объекта выступающего в роли внешней связи. Для FK-полей, если сохранили внешнюю модель, то проставим значение id в поле
Функция перепривязки идентификатора объекта выступающего в роли внешней связи. Для FK-полей, если сохранили внешнюю модель, то проставим значение id в поле
def rebind_model_rel_id(obj): """ Функция перепривязки идентификатора объекта выступающего в роли внешней связи. Для FK-полей, если сохранили внешнюю модель, то проставим значение id в поле """ assert isinstance(obj, Model) for field in obj._meta.concrete_fields: if ( f...
[ "def", "rebind_model_rel_id", "(", "obj", ")", ":", "assert", "isinstance", "(", "obj", ",", "Model", ")", "for", "field", "in", "obj", ".", "_meta", ".", "concrete_fields", ":", "if", "(", "field", ".", "is_relation", "and", "not", "getattr", "(", "obj"...
[ 59, 0 ]
[ 74, 78 ]
python
en
['en', 'error', 'th']
False
DayOfTheWeek.__str__
(self)
Allow to directly assign enum values to the model field.
Allow to directly assign enum values to the model field.
def __str__(self): """Allow to directly assign enum values to the model field.""" return self.name
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "name" ]
[ 13, 4 ]
[ 15, 24 ]
python
en
['en', 'en', 'en']
True
api_canarytoken_webhook
( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), )
Construct a response to a webhook event from a Thinkst canarytoken from canarytokens.org. Canarytokens from Thinkst's paid product have a different schema and should use the "thinkst" integration. See linked documentation below for a schema: https://help.canary.tools/hc/en-gb/articles/360002426577...
Construct a response to a webhook event from a Thinkst canarytoken from canarytokens.org. Canarytokens from Thinkst's paid product have a different schema and should use the "thinkst" integration. See linked documentation below for a schema:
def api_canarytoken_webhook( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), ) -> HttpResponse: """ Construct a response to a webhook event from a Thinkst canarytoken from ...
[ "def", "api_canarytoken_webhook", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "message", ":", "Dict", "[", "str", ",", "Any", "]", "=", "REQ", "(", "argument_type", "=", "\"body\"", ")", ",", "user_specified_topic", ":", ...
[ 14, 0 ]
[ 39, 25 ]
python
en
['en', 'error', 'th']
False
newer_pairwise_group
(sources_groups, targets)
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
def newer_pairwise_group(sources_groups, targets): """Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'. """ if ...
[ "def", "newer_pairwise_group", "(", "sources_groups", ",", "targets", ")", ":", "if", "len", "(", "sources_groups", ")", "!=", "len", "(", "targets", ")", ":", "raise", "ValueError", "(", "\"'sources_group' and 'targets' must be the same length\"", ")", "# build a pai...
[ 6, 0 ]
[ 24, 31 ]
python
en
['en', 'en', 'en']
True
TypesPrintTest.check_signature
( self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any )
Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. func will be decorated with print_types within this function.
Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. func will be decorated with print_types within this function.
def check_signature( self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any ) -> None: """ Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. ...
[ "def", "check_signature", "(", "self", ",", "signature", ":", "str", ",", "retval", ":", "T", ",", "func", ":", "Callable", "[", "...", ",", "T", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "t...
[ 27, 4 ]
[ 41, 40 ]
python
en
['en', 'error', 'th']
False
make_safe_digest
(string: str, hash_func: Callable[[bytes], Any] = hashlib.sha1)
return a hex digest of `string`.
return a hex digest of `string`.
def make_safe_digest(string: str, hash_func: Callable[[bytes], Any] = hashlib.sha1) -> str: """ return a hex digest of `string`. """ # hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must # be encoded. return hash_func(string.encode("utf-8")).hexdigest()
[ "def", "make_safe_digest", "(", "string", ":", "str", ",", "hash_func", ":", "Callable", "[", "[", "bytes", "]", ",", "Any", "]", "=", "hashlib", ".", "sha1", ")", "->", "str", ":", "# hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must", "# be encoded...
[ 88, 0 ]
[ 94, 56 ]
python
en
['en', 'error', 'th']
False
log_statsd_event
(name: str)
Sends a single event to statsd with the desired name and the current timestamp This can be used to provide vertical lines in generated graphs, for example when doing a prod deploy, bankruptcy request, or other one-off events Note that to draw this event as a vertical line in graphite you can ...
Sends a single event to statsd with the desired name and the current timestamp
def log_statsd_event(name: str) -> None: """ Sends a single event to statsd with the desired name and the current timestamp This can be used to provide vertical lines in generated graphs, for example when doing a prod deploy, bankruptcy request, or other one-off events Note that to draw this e...
[ "def", "log_statsd_event", "(", "name", ":", "str", ")", "->", "None", ":", "event_name", "=", "f\"events.{name}\"", "statsd", ".", "incr", "(", "event_name", ")" ]
[ 97, 0 ]
[ 109, 27 ]
python
en
['en', 'error', 'th']
False
query_chunker
( queries: List[Any], id_collector: Optional[Set[int]] = None, chunk_size: int = 1000, db_chunk_size: Optional[int] = None, )
This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during each yield, preserving id order across all results.. Queries should satisfy these conditions: - They should be Django filters. - They should return Django objects w...
This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during each yield, preserving id order across all results..
def query_chunker( queries: List[Any], id_collector: Optional[Set[int]] = None, chunk_size: int = 1000, db_chunk_size: Optional[int] = None, ) -> Iterator[Any]: """ This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during e...
[ "def", "query_chunker", "(", "queries", ":", "List", "[", "Any", "]", ",", "id_collector", ":", "Optional", "[", "Set", "[", "int", "]", "]", "=", "None", ",", "chunk_size", ":", "int", "=", "1000", ",", "db_chunk_size", ":", "Optional", "[", "int", ...
[ 124, 0 ]
[ 181, 51 ]
python
en
['en', 'error', 'th']
False
split_by
(array: List[Any], group_size: int, filler: Any)
Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html
Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html
def split_by(array: List[Any], group_size: int, filler: Any) -> List[List[Any]]: """ Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html """ args = [iter(array)] * group_size return list(map(list, zip_long...
[ "def", "split_by", "(", "array", ":", "List", "[", "Any", "]", ",", "group_size", ":", "int", ",", "filler", ":", "Any", ")", "->", "List", "[", "List", "[", "Any", "]", "]", ":", "args", "=", "[", "iter", "(", "array", ")", "]", "*", "group_si...
[ 197, 0 ]
[ 203, 64 ]
python
en
['en', 'error', 'th']
False
StatsDWrapper._our_gauge
(self, stat: str, value: float, rate: float = 1, delta: bool = False)
Set a gauge value.
Set a gauge value.
def _our_gauge(self, stat: str, value: float, rate: float = 1, delta: bool = False) -> None: """Set a gauge value.""" from django_statsd.clients import statsd if delta: value_str = f"{value:+g}|g" else: value_str = f"{value:g}|g" statsd._send(stat, value_...
[ "def", "_our_gauge", "(", "self", ",", "stat", ":", "str", ",", "value", ":", "float", ",", "rate", ":", "float", "=", "1", ",", "delta", ":", "bool", "=", "False", ")", "->", "None", ":", "from", "django_statsd", ".", "clients", "import", "statsd", ...
[ 31, 4 ]
[ 39, 43 ]
python
en
['en', 'da', 'en']
True
MirroredMessageUsersTest.test_zephyr_mirror_new_recipient
(self, ignored: object)
Test mirror dummy user creation for PM recipients
Test mirror dummy user creation for PM recipients
def test_zephyr_mirror_new_recipient(self, ignored: object) -> None: """Test mirror dummy user creation for PM recipients""" client = get_client(name="zephyr_mirror") user = self.mit_user("starnine") sender = self.mit_user("sipbtest") new_user_email = "bob_the_new_user@mit.edu" ...
[ "def", "test_zephyr_mirror_new_recipient", "(", "self", ",", "ignored", ":", "object", ")", "->", "None", ":", "client", "=", "get_client", "(", "name", "=", "\"zephyr_mirror\"", ")", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "sender", ...
[ 62, 4 ]
[ 87, 44 ]
python
de
['nb', 'de', 'en']
False
MirroredMessageUsersTest.test_zephyr_mirror_new_sender
(self, ignored: object)
Test mirror dummy user creation for sender when sending to stream
Test mirror dummy user creation for sender when sending to stream
def test_zephyr_mirror_new_sender(self, ignored: object) -> None: """Test mirror dummy user creation for sender when sending to stream""" client = get_client(name="zephyr_mirror") user = self.mit_user("starnine") sender_email = "new_sender@mit.edu" recipients = ["stream_name"] ...
[ "def", "test_zephyr_mirror_new_sender", "(", "self", ",", "ignored", ":", "object", ")", "->", "None", ":", "client", "=", "get_client", "(", "name", "=", "\"zephyr_mirror\"", ")", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "sender_email",...
[ 93, 4 ]
[ 110, 54 ]
python
en
['en', 'no', 'en']
True
_cmp_raises_type_error
(self, other)
__cmp__ implementation which raises TypeError. Used by Approx base classes to implement only == and != and raise a TypeError for other comparisons. Needed in Python 2 only, Python 3 all it takes is not implementing the other operators at all.
__cmp__ implementation which raises TypeError. Used by Approx base classes to implement only == and != and raise a TypeError for other comparisons.
def _cmp_raises_type_error(self, other): """__cmp__ implementation which raises TypeError. Used by Approx base classes to implement only == and != and raise a TypeError for other comparisons. Needed in Python 2 only, Python 3 all it takes is not implementing the other operators at all. """ ...
[ "def", "_cmp_raises_type_error", "(", "self", ",", "other", ")", ":", "__tracebackhide__", "=", "True", "raise", "TypeError", "(", "'Comparison operators other than == and != not supported by approx objects'", ")" ]
[ 11, 0 ]
[ 20, 96 ]
python
en
['en', 'sr', 'en']
True
approx
(expected, rel=None, abs=None, nan_ok=False)
Assert that two numbers (or two sets of numbers) are equal to each other within some tolerance. Due to the `intricacies of floating-point arithmetic`__, numbers that we would intuitively expect to be equal are not always so:: >>> 0.1 + 0.2 == 0.3 False __ https://docs.python.org/...
Assert that two numbers (or two sets of numbers) are equal to each other within some tolerance.
def approx(expected, rel=None, abs=None, nan_ok=False): """ Assert that two numbers (or two sets of numbers) are equal to each other within some tolerance. Due to the `intricacies of floating-point arithmetic`__, numbers that we would intuitively expect to be equal are not always so:: >>> ...
[ "def", "approx", "(", "expected", ",", "rel", "=", "None", ",", "abs", "=", "None", ",", "nan_ok", "=", "False", ")", ":", "from", "collections", "import", "Mapping", ",", "Sequence", "from", "_pytest", ".", "compat", "import", "STRING_TYPES", "as", "Str...
[ 263, 0 ]
[ 439, 42 ]
python
en
['en', 'error', 'th']
False
_is_numpy_array
(obj)
Return true if the given object is a numpy array. Make a special effort to avoid importing numpy unless it's really necessary.
Return true if the given object is a numpy array. Make a special effort to avoid importing numpy unless it's really necessary.
def _is_numpy_array(obj): """ Return true if the given object is a numpy array. Make a special effort to avoid importing numpy unless it's really necessary. """ import inspect for cls in inspect.getmro(type(obj)): if cls.__module__ == 'numpy': try: import nu...
[ "def", "_is_numpy_array", "(", "obj", ")", ":", "import", "inspect", "for", "cls", "in", "inspect", ".", "getmro", "(", "type", "(", "obj", ")", ")", ":", "if", "cls", ".", "__module__", "==", "'numpy'", ":", "try", ":", "import", "numpy", "as", "np"...
[ 442, 0 ]
[ 457, 16 ]
python
en
['en', 'error', 'th']
False
raises
(expected_exception, *args, **kwargs)
Assert that a code block/function call raises ``expected_exception`` and raise a failure exception otherwise. :arg message: if specified, provides a custom failure message if the exception is not raised :arg match: if specified, asserts that the exception matches a text or regex This help...
Assert that a code block/function call raises ``expected_exception`` and raise a failure exception otherwise.
def raises(expected_exception, *args, **kwargs): """ Assert that a code block/function call raises ``expected_exception`` and raise a failure exception otherwise. :arg message: if specified, provides a custom failure message if the exception is not raised :arg match: if specified, asserts t...
[ "def", "raises", "(", "expected_exception", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "__tracebackhide__", "=", "True", "msg", "=", "(", "\"exceptions must be old-style classes or\"", "\" derived from BaseException, not %s\"", ")", "if", "isinstance", "(", ...
[ 462, 0 ]
[ 606, 17 ]
python
en
['en', 'error', 'th']
False
ApproxBase._yield_comparisons
(self, actual)
Yield all the pairs of numbers to be compared. This is used to implement the `__eq__` method.
Yield all the pairs of numbers to be compared. This is used to implement the `__eq__` method.
def _yield_comparisons(self, actual): """ Yield all the pairs of numbers to be compared. This is used to implement the `__eq__` method. """ raise NotImplementedError
[ "def", "_yield_comparisons", "(", "self", ",", "actual", ")", ":", "raise", "NotImplementedError" ]
[ 57, 4 ]
[ 62, 33 ]
python
en
['en', 'error', 'th']
False
ApproxScalar.__repr__
(self)
Return a string communicating both the expected value and the tolerance for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode plus/minus symbol if this is python3 (it's too hard to get right for python2).
Return a string communicating both the expected value and the tolerance for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode plus/minus symbol if this is python3 (it's too hard to get right for python2).
def __repr__(self): """ Return a string communicating both the expected value and the tolerance for the comparison being made, e.g. '1.0 +- 1e-6'. Use the unicode plus/minus symbol if this is python3 (it's too hard to get right for python2). """ if isinstance(sel...
[ "def", "__repr__", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "expected", ",", "complex", ")", ":", "return", "str", "(", "self", ".", "expected", ")", "# Infinities aren't compared using tolerances, so don't show a", "# tolerance.", "if", "math"...
[ 158, 4 ]
[ 183, 76 ]
python
en
['en', 'error', 'th']
False
ApproxScalar.__eq__
(self, actual)
Return true if the given value is equal to the expected value within the pre-specified tolerance.
Return true if the given value is equal to the expected value within the pre-specified tolerance.
def __eq__(self, actual): """ Return true if the given value is equal to the expected value within the pre-specified tolerance. """ # Short-circuit exact equality. if actual == self.expected: return True # Allow the user to control whether NaNs are c...
[ "def", "__eq__", "(", "self", ",", "actual", ")", ":", "# Short-circuit exact equality.", "if", "actual", "==", "self", ".", "expected", ":", "return", "True", "# Allow the user to control whether NaNs are considered equal to each", "# other or not. The abs() calls are for com...
[ 185, 4 ]
[ 211, 60 ]
python
en
['en', 'error', 'th']
False
ApproxScalar.tolerance
(self)
Return the tolerance for the comparison. This could be either an absolute tolerance or a relative tolerance, depending on what the user specified or which would be larger.
Return the tolerance for the comparison. This could be either an absolute tolerance or a relative tolerance, depending on what the user specified or which would be larger.
def tolerance(self): """ Return the tolerance for the comparison. This could be either an absolute tolerance or a relative tolerance, depending on what the user specified or which would be larger. """ def set_default(x, default): return x if x is not None els...
[ "def", "tolerance", "(", "self", ")", ":", "def", "set_default", "(", "x", ",", "default", ")", ":", "return", "x", "if", "x", "is", "not", "None", "else", "default", "# Figure out what the absolute tolerance should be. ``self.abs`` is", "# either None or a value spe...
[ 216, 4 ]
[ 253, 58 ]
python
en
['en', 'error', 'th']
False
DBBenchRunner._parse_output
(self, get_perf_context=False)
Sample db_bench output after running 'readwhilewriting' benchmark: DB path: [/tmp/rocksdbtest-155919/dbbench]\n readwhilewriting : 16.582 micros/op 60305 ops/sec; 4.2 MB/s (3433828\ of 5427999 found)\n PERF_CONTEXT:\n user_key_comparison_count = 500466712, block_cache_hi...
Sample db_bench output after running 'readwhilewriting' benchmark: DB path: [/tmp/rocksdbtest-155919/dbbench]\n readwhilewriting : 16.582 micros/op 60305 ops/sec; 4.2 MB/s (3433828\ of 5427999 found)\n PERF_CONTEXT:\n user_key_comparison_count = 500466712, block_cache_hi...
def _parse_output(self, get_perf_context=False): ''' Sample db_bench output after running 'readwhilewriting' benchmark: DB path: [/tmp/rocksdbtest-155919/dbbench]\n readwhilewriting : 16.582 micros/op 60305 ops/sec; 4.2 MB/s (3433828\ of 5427999 found)\n PERF_CONTEXT:\n ...
[ "def", "_parse_output", "(", "self", ",", "get_perf_context", "=", "False", ")", ":", "output", "=", "{", "self", ".", "THROUGHPUT", ":", "None", ",", "self", ".", "DB_PATH", ":", "None", ",", "self", ".", "PERF_CON", ":", "None", "}", "perf_context_begi...
[ 55, 4 ]
[ 116, 21 ]
python
en
['en', 'error', 'th']
False
DBBenchRunner._get_options_command_line_args_str
(self, curr_options)
This method uses the provided Rocksdb OPTIONS to create a string of command-line arguments for db_bench. The --options_file argument is always given and the options that are not supported by the OPTIONS file are given as separate arguments.
This method uses the provided Rocksdb OPTIONS to create a string of command-line arguments for db_bench. The --options_file argument is always given and the options that are not supported by the OPTIONS file are given as separate arguments.
def _get_options_command_line_args_str(self, curr_options): ''' This method uses the provided Rocksdb OPTIONS to create a string of command-line arguments for db_bench. The --options_file argument is always given and the options that are not supported by the OPTIONS file are give...
[ "def", "_get_options_command_line_args_str", "(", "self", ",", "curr_options", ")", ":", "optional_args_str", "=", "DBBenchRunner", ".", "get_opt_args_str", "(", "curr_options", ".", "get_misc_options", "(", ")", ")", "# generate an options configuration file", "options_fil...
[ 148, 4 ]
[ 161, 32 ]
python
en
['en', 'error', 'th']
False
Jcal.setUp
(self)
Setting up test.
Setting up test.
def setUp(self): """Setting up test.""" self.server_url = self.conf_get('main', 'url')
[ "def", "setUp", "(", "self", ")", ":", "self", ".", "server_url", "=", "self", ".", "conf_get", "(", "'main'", ",", "'url'", ")" ]
[ 12, 4 ]
[ 14, 54 ]
python
en
['en', 'en', 'en']
True
test_mongodb_auth_connection
()
Test the auth service to make sure we can authenticate into Mongo
Test the auth service to make sure we can authenticate into Mongo
def test_mongodb_auth_connection(): """Test the auth service to make sure we can authenticate into Mongo""" server: mockupdb.MockupDB = mockupdb.MockupDB(auto_ismaster={"maxWireVersion": 3}) server.run() mongo_client: MongoClient = MongoAuthentication(server.uri).connect() return mongo_client.server...
[ "def", "test_mongodb_auth_connection", "(", ")", ":", "server", ":", "mockupdb", ".", "MockupDB", "=", "mockupdb", ".", "MockupDB", "(", "auto_ismaster", "=", "{", "\"maxWireVersion\"", ":", "3", "}", ")", "server", ".", "run", "(", ")", "mongo_client", ":",...
[ 5, 0 ]
[ 10, 37 ]
python
en
['en', 'en', 'en']
True
HomeTest._sanity_check
(self, result: HttpResponse)
Use this for tests that are geared toward specific edge cases, but which still want the home page to load properly.
Use this for tests that are geared toward specific edge cases, but which still want the home page to load properly.
def _sanity_check(self, result: HttpResponse) -> None: """ Use this for tests that are geared toward specific edge cases, but which still want the home page to load properly. """ html = result.content.decode("utf-8") if "start a conversation" not in html: rais...
[ "def", "_sanity_check", "(", "self", ",", "result", ":", "HttpResponse", ")", "->", "None", ":", "html", "=", "result", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "if", "\"start a conversation\"", "not", "in", "html", ":", "raise", "AssertionError...
[ 408, 4 ]
[ 415, 68 ]
python
en
['en', 'error', 'th']
False
HomeTest.test_people
(self)
We send three lists of users. The first two below are disjoint lists of users, and the records we send for them have identical structure. The realm_bots bucket is somewhat redundant, since all bots will be in one of the first two buckets. They do include fields, however, ...
We send three lists of users. The first two below are disjoint lists of users, and the records we send for them have identical structure.
def test_people(self) -> None: hamlet = self.example_user("hamlet") realm = get_realm("zulip") self.login_user(hamlet) bots = {} for i in range(3): bots[i] = self.create_bot( owner=hamlet, bot_email=f"bot-{i}@zulip.com", ...
[ "def", "test_people", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "self", ".", "login_user", "(", "hamlet", ")", "bots", "=", "{", "}", "for"...
[ 543, 4 ]
[ 677, 9 ]
python
en
['en', 'error', 'th']
False
test_overview_append_mappings
(html_test_table, header_index, fixture_features, expected_html, template)
Testing if appending mappings (wrapped in HTML) to the element works properly.
Testing if appending mappings (wrapped in HTML) to the element works properly.
def test_overview_append_mappings(html_test_table, header_index, fixture_features, expected_html, template): """Testing if appending mappings (wrapped in HTML) to the element works properly.""" html_table = BeautifulSoup(html_test_table, "html.parser") headers = html_table.table.select("table tbody tr th") ...
[ "def", "test_overview_append_mappings", "(", "html_test_table", ",", "header_index", ",", "fixture_features", ",", "expected_html", ",", "template", ")", ":", "html_table", "=", "BeautifulSoup", "(", "html_test_table", ",", "\"html.parser\"", ")", "headers", "=", "htm...
[ 23, 0 ]
[ 32, 65 ]
python
en
['en', 'en', 'en']
True
test_overview_append_mappings_more_than_limit
( html_test_table, fixture_features, header_index, expected_html, template )
Testing if, when the amount of mapped categories exceeds the limit, then the HTML mappings are chopped off appropriately.
Testing if, when the amount of mapped categories exceeds the limit, then the HTML mappings are chopped off appropriately.
def test_overview_append_mappings_more_than_limit( html_test_table, fixture_features, header_index, expected_html, template ): """Testing if, when the amount of mapped categories exceeds the limit, then the HTML mappings are chopped off appropriately. """ html_table = BeautifulSoup(html_test_table, ...
[ "def", "test_overview_append_mappings_more_than_limit", "(", "html_test_table", ",", "fixture_features", ",", "header_index", ",", "expected_html", ",", "template", ")", ":", "html_table", "=", "BeautifulSoup", "(", "html_test_table", ",", "\"html.parser\"", ")", "headers...
[ 47, 0 ]
[ 63, 80 ]
python
en
['en', 'en', 'en']
True
test_stylize_html_table
(html_test_table, expected_mapping, fixture_features, template)
Testing if the ._stylize_html_table() function creates correct HTML output.
Testing if the ._stylize_html_table() function creates correct HTML output.
def test_stylize_html_table(html_test_table, expected_mapping, fixture_features, template): """Testing if the ._stylize_html_table() function creates correct HTML output.""" # text is 'dedented' to match the output provided by the function. expected_html = """ <table> <thead><tr><th></th><th></th></tr></the...
[ "def", "test_stylize_html_table", "(", "html_test_table", ",", "expected_mapping", ",", "fixture_features", ",", "template", ")", ":", "# text is 'dedented' to match the output provided by the function.", "expected_html", "=", "\"\"\"\n<table>\n<thead><tr><th></th><th></th></tr></thead...
[ 66, 0 ]
[ 97, 39 ]
python
en
['en', 'en', 'en']
True
test_overview_unused_features_html
(input_list, expected_string, template)
Testing if creating HTML output of unused features works properly.
Testing if creating HTML output of unused features works properly.
def test_overview_unused_features_html(input_list, expected_string, template): """Testing if creating HTML output of unused features works properly.""" o = Overview(template, "test_css", "test-description") actual_html = o._unused_features_html(input_list) assert actual_html == expected_string
[ "def", "test_overview_unused_features_html", "(", "input_list", ",", "expected_string", ",", "template", ")", ":", "o", "=", "Overview", "(", "template", ",", "\"test_css\"", ",", "\"test-description\"", ")", "actual_html", "=", "o", ".", "_unused_features_html", "(...
[ 108, 0 ]
[ 113, 41 ]
python
en
['en', 'en', 'en']
True
test_features_view_create_features_menu
(input_features, template)
Testing if Features menu is created properly given the input features.
Testing if Features menu is created properly given the input features.
def test_features_view_create_features_menu(input_features, template): """Testing if Features menu is created properly given the input features.""" fv = FeatureView(template, "test_css", "test_html", "test-target", []) title_template = fv._feature_menu_header fv._menu_single_feature_class = "test-class...
[ "def", "test_features_view_create_features_menu", "(", "input_features", ",", "template", ")", ":", "fv", "=", "FeatureView", "(", "template", ",", "\"test_css\"", ",", "\"test_html\"", ",", "\"test-target\"", ",", "[", "]", ")", "title_template", "=", "fv", ".", ...
[ 124, 0 ]
[ 138, 43 ]
python
en
['en', 'en', 'en']
True
test_features_view_create_features_menu_target_name
(target_name, expected_feature_text, template)
Testing if target-class is being added to the output of features_menu HTML where feature name is a target at the same time.
Testing if target-class is being added to the output of features_menu HTML where feature name is a target at the same time.
def test_features_view_create_features_menu_target_name(target_name, expected_feature_text, template): """Testing if target-class is being added to the output of features_menu HTML where feature name is a target at the same time.""" features = ["Feature0", "Feature1", "Feature2", "Feature3"] fv = Featur...
[ "def", "test_features_view_create_features_menu_target_name", "(", "target_name", ",", "expected_feature_text", ",", "template", ")", ":", "features", "=", "[", "\"Feature0\"", ",", "\"Feature1\"", ",", "\"Feature2\"", ",", "\"Feature3\"", "]", "fv", "=", "FeatureView",...
[ 150, 0 ]
[ 162, 56 ]
python
en
['en', 'en', 'en']
True
test_features_view_transformed_dataframe_html
(input_series, input_df, expected_result, template)
Testing if transformed_dataframe_html() method creates correct HTML output.
Testing if transformed_dataframe_html() method creates correct HTML output.
def test_features_view_transformed_dataframe_html(input_series, input_df, expected_result, template): """Testing if transformed_dataframe_html() method creates correct HTML output.""" test_subtitle = "test-subtitle-class" test_title = "test-title" prefix = "test_prefix-" fv = FeatureView(template, ...
[ "def", "test_features_view_transformed_dataframe_html", "(", "input_series", ",", "input_df", ",", "expected_result", ",", "template", ")", ":", "test_subtitle", "=", "\"test-subtitle-class\"", "test_title", "=", "\"test-title\"", "prefix", "=", "\"test_prefix-\"", "fv", ...
[ 197, 0 ]
[ 212, 43 ]
python
en
['en', 'zu', 'en']
True
test_features_view_transformers_html
(input_transformers, expected_result, template)
Testing if transformers_html() method returns correct HTML output based on provided list of transformers.
Testing if transformers_html() method returns correct HTML output based on provided list of transformers.
def test_features_view_transformers_html(input_transformers, expected_result, template): """Testing if transformers_html() method returns correct HTML output based on provided list of transformers.""" fv = FeatureView(template, "test_css", "test_html", "test-target", []) fv._transformed_feature_single_trans...
[ "def", "test_features_view_transformers_html", "(", "input_transformers", ",", "expected_result", ",", "template", ")", ":", "fv", "=", "FeatureView", "(", "template", ",", "\"test_css\"", ",", "\"test_html\"", ",", "\"test-target\"", ",", "[", "]", ")", "fv", "."...
[ 251, 0 ]
[ 264, 43 ]
python
en
['en', 'en', 'en']
True
test_features_view_transformed_features_divs
( data_classification_balanced, transformed_classification_data, transformer_classification_fitted, numerical_features, input_feature, template )
Testing if transformed_features_divs() method creates correct HTML output with appropriate classes set to their respective divs.
Testing if transformed_features_divs() method creates correct HTML output with appropriate classes set to their respective divs.
def test_features_view_transformed_features_divs( data_classification_balanced, transformed_classification_data, transformer_classification_fitted, numerical_features, input_feature, template ): """Testing if transformed_features_divs() method creates correct HTML output with appropriate classes set...
[ "def", "test_features_view_transformed_features_divs", "(", "data_classification_balanced", ",", "transformed_classification_data", ",", "transformer_classification_fitted", ",", "numerical_features", ",", "input_feature", ",", "template", ")", ":", "# setting up necessary objects", ...
[ 279, 0 ]
[ 318, 74 ]
python
en
['en', 'en', 'en']
True
test_model_view_results_table
(input_df, expected_row_number, template)
Testing if html output produced by results_table method properly assigns css classes to table rows.
Testing if html output produced by results_table method properly assigns css classes to table rows.
def test_model_view_results_table(input_df, expected_row_number, template): """Testing if html output produced by results_table method properly assigns css classes to table rows.""" mv = ModelsView(template, "test_css", "params", "test-class") first_row_class = mv._first_model_class middle_row_class = m...
[ "def", "test_model_view_results_table", "(", "input_df", ",", "expected_row_number", ",", "template", ")", ":", "mv", "=", "ModelsView", "(", "template", ",", "\"test_css\"", ",", "\"params\"", ",", "\"test-class\"", ")", "first_row_class", "=", "mv", ".", "_first...
[ 348, 0 ]
[ 363, 29 ]
python
en
['en', 'en', 'en']
True