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
extract_corner_data_for_Ullman4
(prob_per_crop, custom_prob_per_crop)
extract the data that corresponds to the four corner crops Args: prob_per_crop: list containing the probabilities of all crops custom_prob_per_crop: list containing the custom probabilities of all crops Returns: prob_per_crop: list containing the probabilities of the corn...
extract the data that corresponds to the four corner crops
def extract_corner_data_for_Ullman4(prob_per_crop, custom_prob_per_crop): """extract the data that corresponds to the four corner crops Args: prob_per_crop: list containing the probabilities of all crops custom_prob_per_crop: list containing the custom probabilities of all crops Ret...
[ "def", "extract_corner_data_for_Ullman4", "(", "prob_per_crop", ",", "custom_prob_per_crop", ")", ":", "# get the indices of the corner crops", "n_total_crops", "=", "len", "(", "prob_per_crop", ")", "idx_upper_right", "=", "int", "(", "np", ".", "sqrt", "(", "n_total_c...
[ 293, 0 ]
[ 323, 70 ]
python
en
['en', 'en', 'en']
True
get_most_predictive_crop
( idx_most_predictive_crop, new_image, crop_reduced_resolution_real_px_space, custom_prob_per_crop, descendent_specifier, )
determine crop that corresponds to most predictive crop Args: idx_most_predictive_crop: index of most predictive crop (int) new_image: tensor, dtype = torch.float32. expected dimensions: C X W X H, e.g. torch.Size([3...
determine crop that corresponds to most predictive crop
def get_most_predictive_crop( idx_most_predictive_crop, new_image, crop_reduced_resolution_real_px_space, custom_prob_per_crop, descendent_specifier, ): """determine crop that corresponds to most predictive crop Args: idx_most_predictive_crop: index of most predictive crop (int) ...
[ "def", "get_most_predictive_crop", "(", "idx_most_predictive_crop", ",", "new_image", ",", "crop_reduced_resolution_real_px_space", ",", "custom_prob_per_crop", ",", "descendent_specifier", ",", ")", ":", "# the most predictive crop is the one w/ the reduced resolution", "if", "idx...
[ 326, 0 ]
[ 388, 19 ]
python
en
['en', 'de', 'en']
True
get_resized_img
(image, size, DEVICE)
Calculate the resized image. PIL requires uint8 images on cpu, hence the tranformation back and forth. Args: image: torch tensor, dtype = torch.float32. expected dimensions: CxHxW, e.g. torch.Size([3, 224, 224]) size: size of target image DEVICE: device where ...
Calculate the resized image. PIL requires uint8 images on cpu, hence the tranformation back and forth.
def get_resized_img(image, size, DEVICE): """Calculate the resized image. PIL requires uint8 images on cpu, hence the tranformation back and forth. Args: image: torch tensor, dtype = torch.float32. expected dimensions: CxHxW, e.g. torch.Size([3, 224, 224]) size: siz...
[ "def", "get_resized_img", "(", "image", ",", "size", ",", "DEVICE", ")", ":", "# if the image is on cuda, move it to the cpu", "if", "image", ".", "device", ".", "type", "==", "DEVICE", ".", "type", ":", "image", "=", "image", ".", "cpu", "(", ")", "image_np...
[ 391, 0 ]
[ 417, 13 ]
python
en
['en', 'en', 'en']
True
undo_normalization
(X)
undo ImageNet normalization, that was applied in preprocessing, to a single image Args: X: numpy array, dtype=float32. dimensions: HxWxC Returns: image: numpy array
undo ImageNet normalization, that was applied in preprocessing, to a single image
def undo_normalization(X): """undo ImageNet normalization, that was applied in preprocessing, to a single image Args: X: numpy array, dtype=float32. dimensions: HxWxC Returns: image: numpy array """ image = X.copy() image *= std[None, None] # None twice ...
[ "def", "undo_normalization", "(", "X", ")", ":", "image", "=", "X", ".", "copy", "(", ")", "image", "*=", "std", "[", "None", ",", "None", "]", "# None twice for width and height dimensions", "image", "+=", "mean", "[", "None", ",", "None", "]", "image", ...
[ 424, 0 ]
[ 440, 16 ]
python
en
['en', 'en', 'en']
True
apply_normalization
(X)
apply ImageNet normalization (the same one that was applied in preprocessing) to a single image Args: X: numpy array, dtype=float32. dimensions: HxWxC Returns: image: numpy array
apply ImageNet normalization (the same one that was applied in preprocessing) to a single image
def apply_normalization(X): """apply ImageNet normalization (the same one that was applied in preprocessing) to a single image Args: X: numpy array, dtype=float32. dimensions: HxWxC Returns: image: numpy array """ image = X.copy() image -= mean[None, None...
[ "def", "apply_normalization", "(", "X", ")", ":", "image", "=", "X", ".", "copy", "(", ")", "image", "-=", "mean", "[", "None", ",", "None", "]", "# None twice for width and height dimensions", "image", "/=", "std", "[", "None", ",", "None", "]", "return",...
[ 443, 0 ]
[ 457, 16 ]
python
en
['en', 'en', 'en']
True
get_img_identifier
(Ullman_or_ImageNet, path, target_list)
Create and return an image identifier with its correct class. It is used as a key in dictionaries and as part of filenames for figures. Args: path: absolute path to directory Returns: img_identifier: string to identify an image and its correct class e.g. glass...
Create and return an image identifier with its correct class. It is used as a key in dictionaries and as part of filenames for figures.
def get_img_identifier(Ullman_or_ImageNet, path, target_list): """Create and return an image identifier with its correct class. It is used as a key in dictionaries and as part of filenames for figures. Args: path: absolute path to directory Returns: img_identifier: string to iden...
[ "def", "get_img_identifier", "(", "Ullman_or_ImageNet", ",", "path", ",", "target_list", ")", ":", "if", "Ullman_or_ImageNet", "==", "\"Ullman\"", ":", "img_identifier", "=", "(", "f\"{path[0].split(os.path.sep)[-2]}_INclass{int(target_list[0])}\"", ")", "else", ":", "img...
[ 460, 0 ]
[ 478, 25 ]
python
en
['en', 'en', 'en']
True
reset_cache
(**kwargs)
Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted.
Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted.
def reset_cache(**kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'): global _supported _supported = None check_for_language.cache_clear() ...
[ "def", "reset_cache", "(", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'setting'", "]", "in", "(", "'LANGUAGES'", ",", "'LANGUAGE_CODE'", ")", ":", "global", "_supported", "_supported", "=", "None", "check_for_language", ".", "cache_clear", "(", ")",...
[ 60, 0 ]
[ 69, 52 ]
python
en
['en', 'error', 'th']
False
to_locale
(language, to_lower=False)
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us).
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us).
def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). """ p = language.find('-') if p >= 0: if to_lower: return language[:p].lower() + '_' + language[p + 1:].low...
[ "def", "to_locale", "(", "language", ",", "to_lower", "=", "False", ")", ":", "p", "=", "language", ".", "find", "(", "'-'", ")", "if", "p", ">=", "0", ":", "if", "to_lower", ":", "return", "language", "[", ":", "p", "]", ".", "lower", "(", ")", ...
[ 72, 0 ]
[ 87, 31 ]
python
en
['en', 'error', 'th']
False
to_language
(locale)
Turns a locale name (en_US) into a language name (en-us).
Turns a locale name (en_US) into a language name (en-us).
def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
[ "def", "to_language", "(", "locale", ")", ":", "p", "=", "locale", ".", "find", "(", "'_'", ")", "if", "p", ">=", "0", ":", "return", "locale", "[", ":", "p", "]", ".", "lower", "(", ")", "+", "'-'", "+", "locale", "[", "p", "+", "1", ":", ...
[ 90, 0 ]
[ 96, 29 ]
python
en
['es', 'en', 'en']
True
translation
(language)
Returns a translation object.
Returns a translation object.
def translation(language): """ Returns a translation object. """ global _translations if language not in _translations: _translations[language] = DjangoTranslation(language) return _translations[language]
[ "def", "translation", "(", "language", ")", ":", "global", "_translations", "if", "language", "not", "in", "_translations", ":", "_translations", "[", "language", "]", "=", "DjangoTranslation", "(", "language", ")", "return", "_translations", "[", "language", "]...
[ 203, 0 ]
[ 210, 34 ]
python
en
['en', 'error', 'th']
False
activate
(language)
Fetches the translation object for a given language and installs it as the current translation object for the current thread.
Fetches the translation object for a given language and installs it as the current translation object for the current thread.
def activate(language): """ Fetches the translation object for a given language and installs it as the current translation object for the current thread. """ if language in _DJANGO_DEPRECATED_LOCALES: msg = ("The use of the language code '%s' is deprecated. " "Please use the '...
[ "def", "activate", "(", "language", ")", ":", "if", "language", "in", "_DJANGO_DEPRECATED_LOCALES", ":", "msg", "=", "(", "\"The use of the language code '%s' is deprecated. \"", "\"Please use the '%s' translation instead.\"", ")", "warnings", ".", "warn", "(", "msg", "%"...
[ 213, 0 ]
[ 223, 41 ]
python
en
['en', 'error', 'th']
False
deactivate
()
Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again.
Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again.
def deactivate(): """ Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again. """ if hasattr(_active, "value"): del _active.value
[ "def", "deactivate", "(", ")", ":", "if", "hasattr", "(", "_active", ",", "\"value\"", ")", ":", "del", "_active", ".", "value" ]
[ 226, 0 ]
[ 232, 25 ]
python
en
['en', 'error', 'th']
False
deactivate_all
()
Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
def deactivate_all(): """ Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active.value = gettext_module.NullTranslations()
[ "def", "deactivate_all", "(", ")", ":", "_active", ".", "value", "=", "gettext_module", ".", "NullTranslations", "(", ")" ]
[ 235, 0 ]
[ 241, 53 ]
python
en
['en', 'error', 'th']
False
get_language
()
Returns the currently selected language.
Returns the currently selected language.
def get_language(): """Returns the currently selected language.""" t = getattr(_active, "value", None) if t is not None: try: return t.to_language() except AttributeError: pass # If we don't have a real translation object, assume it's the default language. ret...
[ "def", "get_language", "(", ")", ":", "t", "=", "getattr", "(", "_active", ",", "\"value\"", ",", "None", ")", "if", "t", "is", "not", "None", ":", "try", ":", "return", "t", ".", "to_language", "(", ")", "except", "AttributeError", ":", "pass", "# I...
[ 244, 0 ]
[ 253, 33 ]
python
en
['en', 'en', 'en']
True
get_language_bidi
()
Returns selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout
Returns selected language's BiDi layout.
def get_language_bidi(): """ Returns selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout """ base_lang = get_language().split('-')[0] return base_lang in settings.LANGUAGES_BIDI
[ "def", "get_language_bidi", "(", ")", ":", "base_lang", "=", "get_language", "(", ")", ".", "split", "(", "'-'", ")", "[", "0", "]", "return", "base_lang", "in", "settings", ".", "LANGUAGES_BIDI" ]
[ 256, 0 ]
[ 264, 47 ]
python
en
['en', 'error', 'th']
False
catalog
()
Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string.
def catalog(): """ Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: ...
[ "def", "catalog", "(", ")", ":", "global", "_default", "t", "=", "getattr", "(", "_active", ",", "\"value\"", ",", "None", ")", "if", "t", "is", "not", "None", ":", "return", "t", "if", "_default", "is", "None", ":", "_default", "=", "translation", "...
[ 267, 0 ]
[ 280, 19 ]
python
en
['en', 'error', 'th']
False
do_translate
(message, translation_function)
Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
def do_translate(message, translation_function): """ Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through...
[ "def", "do_translate", "(", "message", ",", "translation_function", ")", ":", "global", "_default", "# str() is allowing a bytestring message to remain bytestring on Python 2", "eol_message", "=", "message", ".", "replace", "(", "str", "(", "'\\r\\n'", ")", ",", "str", ...
[ 283, 0 ]
[ 308, 17 ]
python
en
['en', 'error', 'th']
False
gettext
(message)
Returns a string of the translation of the message. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
Returns a string of the translation of the message.
def gettext(message): """ Returns a string of the translation of the message. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2. """ return do_translate(message, 'gettext')
[ "def", "gettext", "(", "message", ")", ":", "return", "do_translate", "(", "message", ",", "'gettext'", ")" ]
[ 311, 0 ]
[ 317, 43 ]
python
en
['en', 'error', 'th']
False
gettext_noop
(message)
Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
def gettext_noop(message): """ Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message
[ "def", "gettext_noop", "(", "message", ")", ":", "return", "message" ]
[ 336, 0 ]
[ 343, 18 ]
python
en
['en', 'error', 'th']
False
ngettext
(singular, plural, number)
Returns a string of the translation of either the singular or plural, based on the number. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2.
Returns a string of the translation of either the singular or plural, based on the number.
def ngettext(singular, plural, number): """ Returns a string of the translation of either the singular or plural, based on the number. Returns a string on Python 3 and an UTF-8-encoded bytestring on Python 2. """ return do_ntranslate(singular, plural, number, 'ngettext')
[ "def", "ngettext", "(", "singular", ",", "plural", ",", "number", ")", ":", "return", "do_ntranslate", "(", "singular", ",", "plural", ",", "number", ",", "'ngettext'", ")" ]
[ 357, 0 ]
[ 364, 62 ]
python
en
['en', 'error', 'th']
False
all_locale_paths
()
Returns a list of paths to user-provides languages files.
Returns a list of paths to user-provides languages files.
def all_locale_paths(): """ Returns a list of paths to user-provides languages files. """ globalpath = os.path.join( os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale') return [globalpath] + list(settings.LOCALE_PATHS)
[ "def", "all_locale_paths", "(", ")", ":", "globalpath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "upath", "(", "sys", ".", "modules", "[", "settings", ".", "__module__", "]", ".", "__file__", ")", ")", ",", ...
[ 388, 0 ]
[ 394, 53 ]
python
en
['en', 'error', 'th']
False
check_for_language
(lang_code)
Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also ...
Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available.
def check_for_language(lang_code): """ Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are ...
[ "def", "check_for_language", "(", "lang_code", ")", ":", "# First, a quick check to make sure lang_code is well-formed (#21458)", "if", "not", "language_code_re", ".", "search", "(", "lang_code", ")", ":", "return", "False", "for", "path", "in", "all_locale_paths", "(", ...
[ 398, 0 ]
[ 414, 16 ]
python
en
['en', 'error', 'th']
False
get_supported_language_variant
(lang_code, strict=False)
Returns the language-code that's listed in supported languages, possibly selecting a more generic variant. Raises LookupError if nothing found. If `strict` is False (the default), the function will look for an alternative country-specific variant when the currently checked is not found. lru_cache...
Returns the language-code that's listed in supported languages, possibly selecting a more generic variant. Raises LookupError if nothing found.
def get_supported_language_variant(lang_code, strict=False): """ Returns the language-code that's listed in supported languages, possibly selecting a more generic variant. Raises LookupError if nothing found. If `strict` is False (the default), the function will look for an alternative country-spec...
[ "def", "get_supported_language_variant", "(", "lang_code", ",", "strict", "=", "False", ")", ":", "global", "_supported", "if", "_supported", "is", "None", ":", "_supported", "=", "OrderedDict", "(", "settings", ".", "LANGUAGES", ")", "if", "lang_code", ":", "...
[ 418, 0 ]
[ 451, 32 ]
python
en
['en', 'error', 'th']
False
get_language_from_path
(path, strict=False)
Returns the language-code if there is a valid language-code found in the `path`. If `strict` is False (the default), the function will look for an alternative country-specific variant when the currently checked is not found.
Returns the language-code if there is a valid language-code found in the `path`.
def get_language_from_path(path, strict=False): """ Returns the language-code if there is a valid language-code found in the `path`. If `strict` is False (the default), the function will look for an alternative country-specific variant when the currently checked is not found. """ regex_matc...
[ "def", "get_language_from_path", "(", "path", ",", "strict", "=", "False", ")", ":", "regex_match", "=", "language_code_prefix_re", ".", "match", "(", "path", ")", "if", "not", "regex_match", ":", "return", "None", "lang_code", "=", "regex_match", ".", "group"...
[ 454, 0 ]
[ 469, 19 ]
python
en
['en', 'error', 'th']
False
get_language_from_request
(request, check_path=False)
Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be chec...
Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language.
def get_language_from_request(request, check_path=False): """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main langu...
[ "def", "get_language_from_request", "(", "request", ",", "check_path", "=", "False", ")", ":", "global", "_supported", "if", "_supported", "is", "None", ":", "_supported", "=", "OrderedDict", "(", "settings", ".", "LANGUAGES", ")", "if", "check_path", ":", "la...
[ 472, 0 ]
[ 519, 37 ]
python
en
['en', 'error', 'th']
False
blankout
(src, char)
Changes every non-whitespace character to the given char. Used in the templatize function.
Changes every non-whitespace character to the given char. Used in the templatize function.
def blankout(src, char): """ Changes every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src)
[ "def", "blankout", "(", "src", ",", "char", ")", ":", "return", "dot_re", ".", "sub", "(", "char", ",", "src", ")" ]
[ 524, 0 ]
[ 529, 32 ]
python
en
['en', 'error', 'th']
False
templatize
(src, origin=None)
Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
def templatize(src, origin=None): """ Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, T...
[ "def", "templatize", "(", "src", ",", "origin", "=", "None", ")", ":", "from", "django", ".", "template", "import", "(", "Lexer", ",", "TOKEN_TEXT", ",", "TOKEN_VAR", ",", "TOKEN_BLOCK", ",", "TOKEN_COMMENT", ",", "TRANSLATOR_COMMENT_MARK", ")", "src", "=", ...
[ 541, 0 ]
[ 724, 25 ]
python
en
['en', 'error', 'th']
False
parse_accept_lang_header
(lang_string)
Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned.
Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values.
def parse_accept_lang_header(lang_string): """ Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned. """ result = [] pieces = accept...
[ "def", "parse_accept_lang_header", "(", "lang_string", ")", ":", "result", "=", "[", "]", "pieces", "=", "accept_language_re", ".", "split", "(", "lang_string", ".", "lower", "(", ")", ")", "if", "pieces", "[", "-", "1", "]", ":", "return", "[", "]", "...
[ 727, 0 ]
[ 751, 17 ]
python
en
['en', 'error', 'th']
False
DjangoTranslation.__init__
(self, language)
Create a GNUTranslations() using many locale directories
Create a GNUTranslations() using many locale directories
def __init__(self, language): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self.plural = lambda n: in...
[ "def", "__init__", "(", "self", ",", "language", ")", ":", "gettext_module", ".", "GNUTranslations", ".", "__init__", "(", "self", ")", "self", ".", "__language", "=", "language", "self", ".", "__to_language", "=", "to_language", "(", "language", ")", "self"...
[ 109, 4 ]
[ 121, 28 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._new_gnu_trans
(self, localedir, use_null_fallback=True)
Returns a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'.
Returns a mergeable gettext.GNUTranslations instance.
def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Returns a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. ...
[ "def", "_new_gnu_trans", "(", "self", ",", "localedir", ",", "use_null_fallback", "=", "True", ")", ":", "translation", "=", "gettext_module", ".", "translation", "(", "domain", "=", "'django'", ",", "localedir", "=", "localedir", ",", "languages", "=", "[", ...
[ 126, 4 ]
[ 144, 26 ]
python
en
['en', 'error', 'th']
False
DjangoTranslation._init_translation_catalog
(self)
Creates a base catalog using global django translations.
Creates a base catalog using global django translations.
def _init_translation_catalog(self): """Creates a base catalog using global django translations.""" settingsfile = upath(sys.modules[settings.__module__].__file__) localedir = os.path.join(os.path.dirname(settingsfile), 'locale') use_null_fallback = True if self.__language == set...
[ "def", "_init_translation_catalog", "(", "self", ")", ":", "settingsfile", "=", "upath", "(", "sys", ".", "modules", "[", "settings", ".", "__module__", "]", ".", "__file__", ")", "localedir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ...
[ 146, 4 ]
[ 157, 51 ]
python
en
['en', 'zu', 'en']
True
DjangoTranslation._add_installed_apps_translations
(self)
Merges translations from each installed app.
Merges translations from each installed app.
def _add_installed_apps_translations(self): """Merges translations from each installed app.""" try: app_configs = reversed(list(apps.get_app_configs())) except AppRegistryNotReady: raise AppRegistryNotReady( "The translation infrastructure cannot be initia...
[ "def", "_add_installed_apps_translations", "(", "self", ")", ":", "try", ":", "app_configs", "=", "reversed", "(", "list", "(", "apps", ".", "get_app_configs", "(", ")", ")", ")", "except", "AppRegistryNotReady", ":", "raise", "AppRegistryNotReady", "(", "\"The ...
[ 159, 4 ]
[ 171, 35 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._add_local_translations
(self)
Merges translations defined in LOCALE_PATHS.
Merges translations defined in LOCALE_PATHS.
def _add_local_translations(self): """Merges translations defined in LOCALE_PATHS.""" for localedir in reversed(settings.LOCALE_PATHS): translation = self._new_gnu_trans(localedir) self.merge(translation)
[ "def", "_add_local_translations", "(", "self", ")", ":", "for", "localedir", "in", "reversed", "(", "settings", ".", "LOCALE_PATHS", ")", ":", "translation", "=", "self", ".", "_new_gnu_trans", "(", "localedir", ")", "self", ".", "merge", "(", "translation", ...
[ 173, 4 ]
[ 177, 35 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation._add_fallback
(self)
Sets the GNUTranslations() fallback with the default language.
Sets the GNUTranslations() fallback with the default language.
def _add_fallback(self): """Sets the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or for # en-us (as it's empty, so it'll ALWAYS fall back to the default # language; found this as part of #21498, as we set en-us for # ma...
[ "def", "_add_fallback", "(", "self", ")", ":", "# Don't set a fallback for the default language or for", "# en-us (as it's empty, so it'll ALWAYS fall back to the default", "# language; found this as part of #21498, as we set en-us for", "# management commands)", "if", "self", ".", "__lang...
[ 179, 4 ]
[ 188, 46 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation.merge
(self, other)
Merge another translation into this catalog.
Merge another translation into this catalog.
def merge(self, other): """Merge another translation into this catalog.""" self._catalog.update(other._catalog)
[ "def", "merge", "(", "self", ",", "other", ")", ":", "self", ".", "_catalog", ".", "update", "(", "other", ".", "_catalog", ")" ]
[ 190, 4 ]
[ 192, 44 ]
python
en
['en', 'en', 'en']
True
DjangoTranslation.language
(self)
Returns the translation language.
Returns the translation language.
def language(self): """Returns the translation language.""" return self.__language
[ "def", "language", "(", "self", ")", ":", "return", "self", ".", "__language" ]
[ 194, 4 ]
[ 196, 30 ]
python
en
['en', 'zu', 'en']
True
DjangoTranslation.to_language
(self)
Returns the translation language name.
Returns the translation language name.
def to_language(self): """Returns the translation language name.""" return self.__to_language
[ "def", "to_language", "(", "self", ")", ":", "return", "self", ".", "__to_language" ]
[ 198, 4 ]
[ 200, 33 ]
python
en
['en', 'zu', 'en']
True
MadryEtAlMultiGPU.__init__
(self, *args, **kwargs)
Create a MadryEtAlMultiGPU instance.
Create a MadryEtAlMultiGPU instance.
def __init__(self, *args, **kwargs): """ Create a MadryEtAlMultiGPU instance. """ super(MadryEtAlMultiGPU, self).__init__(*args, **kwargs) self.structural_kwargs += ["ngpu"]
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "MadryEtAlMultiGPU", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "structural_kwargs", "+=", "[", ...
[ 25, 4 ]
[ 30, 42 ]
python
en
['en', 'error', 'th']
False
MadryEtAlMultiGPU.attack
(self, x, y_p, **kwargs)
This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. Stop gradient is needed to get the speed-up. This prevents us from being able to back-prop through the attack. :param x: A tensor with the input image. ...
This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs.
def attack(self, x, y_p, **kwargs): """ This method creates a symoblic graph of the MadryEtAl attack on multiple GPUs. The graph is created on the first n GPUs. Stop gradient is needed to get the speed-up. This prevents us from being able to back-prop through the attack. ...
[ "def", "attack", "(", "self", ",", "x", ",", "y_p", ",", "*", "*", "kwargs", ")", ":", "inputs", "=", "[", "]", "outputs", "=", "[", "]", "# Create the initial random perturbation", "device_name", "=", "\"/gpu:0\"", "self", ".", "model", ".", "set_device",...
[ 40, 4 ]
[ 106, 30 ]
python
en
['en', 'error', 'th']
False
MadryEtAlMultiGPU.generate_np
(self, x_val, **kwargs)
Facilitates testing this attack.
Facilitates testing this attack.
def generate_np(self, x_val, **kwargs): """ Facilitates testing this attack. """ _, feedable, _feedable_types, hash_key = self.construct_variables(kwargs) if hash_key not in self.graphs: with tf.variable_scope(None, "attack_%d" % len(self.graphs)): # ...
[ "def", "generate_np", "(", "self", ",", "x_val", ",", "*", "*", "kwargs", ")", ":", "_", ",", "feedable", ",", "_feedable_types", ",", "hash_key", "=", "self", ".", "construct_variables", "(", "kwargs", ")", "if", "hash_key", "not", "in", "self", ".", ...
[ 108, 4 ]
[ 135, 29 ]
python
en
['en', 'error', 'th']
False
MadryEtAlMultiGPU.parse_params
(self, ngpu=1, **kwargs)
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param ngpu: (required int) the number of GPUs available. :param kwargs: A dictionary of parameters for MadryEtAl attack.
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes.
def parse_params(self, ngpu=1, **kwargs): """ Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param ngpu: (required int) the number of GPUs available. :param kwargs: A dictionary of para...
[ "def", "parse_params", "(", "self", ",", "ngpu", "=", "1", ",", "*", "*", "kwargs", ")", ":", "return_status", "=", "super", "(", "MadryEtAlMultiGPU", ",", "self", ")", ".", "parse_params", "(", "*", "*", "kwargs", ")", "self", ".", "ngpu", "=", "ngp...
[ 137, 4 ]
[ 150, 28 ]
python
en
['en', 'error', 'th']
False
Field.__init__
(self, feat, index)
Initializes on the feature object and the integer index of the field within the feature.
Initializes on the feature object and the integer index of the field within the feature.
def __init__(self, feat, index): """ Initializes on the feature object and the integer index of the field within the feature. """ # Setting the feature pointer and index. self._feat = feat self._index = index # Getting the pointer for this field. ...
[ "def", "__init__", "(", "self", ",", "feat", ",", "index", ")", ":", "# Setting the feature pointer and index.", "self", ".", "_feat", "=", "feat", "self", ".", "_index", "=", "index", "# Getting the pointer for this field.", "fld_ptr", "=", "capi", ".", "get_feat...
[ 19, 4 ]
[ 40, 31 ]
python
en
['en', 'error', 'th']
False
Field.__str__
(self)
Returns the string representation of the Field.
Returns the string representation of the Field.
def __str__(self): "Returns the string representation of the Field." return str(self.value).strip()
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "value", ")", ".", "strip", "(", ")" ]
[ 42, 4 ]
[ 44, 38 ]
python
en
['en', 'en', 'en']
True
Field.as_double
(self)
Retrieves the Field's value as a double (float).
Retrieves the Field's value as a double (float).
def as_double(self): "Retrieves the Field's value as a double (float)." return capi.get_field_as_double(self._feat.ptr, self._index)
[ "def", "as_double", "(", "self", ")", ":", "return", "capi", ".", "get_field_as_double", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")" ]
[ 47, 4 ]
[ 49, 68 ]
python
en
['en', 'en', 'en']
True
Field.as_int
(self)
Retrieves the Field's value as an integer.
Retrieves the Field's value as an integer.
def as_int(self): "Retrieves the Field's value as an integer." return capi.get_field_as_integer(self._feat.ptr, self._index)
[ "def", "as_int", "(", "self", ")", ":", "return", "capi", ".", "get_field_as_integer", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")" ]
[ 51, 4 ]
[ 53, 69 ]
python
en
['en', 'en', 'en']
True
Field.as_string
(self)
Retrieves the Field's value as a string.
Retrieves the Field's value as a string.
def as_string(self): "Retrieves the Field's value as a string." string = capi.get_field_as_string(self._feat.ptr, self._index) return force_text(string, encoding=self._feat.encoding, strings_only=True)
[ "def", "as_string", "(", "self", ")", ":", "string", "=", "capi", ".", "get_field_as_string", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")", "return", "force_text", "(", "string", ",", "encoding", "=", "self", ".", "_feat", "."...
[ 55, 4 ]
[ 58, 82 ]
python
en
['en', 'sk', 'en']
True
Field.as_datetime
(self)
Retrieves the Field's value as a tuple of date & time components.
Retrieves the Field's value as a tuple of date & time components.
def as_datetime(self): "Retrieves the Field's value as a tuple of date & time components." yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] status = capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byr...
[ "def", "as_datetime", "(", "self", ")", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "[", "c_int", "(", ")", "for", "i", "in", "range", "(", "7", ")", "]", "status", "=", "capi", ".", "get_field_as_datetime"...
[ 60, 4 ]
[ 69, 92 ]
python
en
['en', 'en', 'en']
True
Field.name
(self)
Returns the name of this Field.
Returns the name of this Field.
def name(self): "Returns the name of this Field." name = capi.get_field_name(self.ptr) return force_text(name, encoding=self._feat.encoding, strings_only=True)
[ "def", "name", "(", "self", ")", ":", "name", "=", "capi", ".", "get_field_name", "(", "self", ".", "ptr", ")", "return", "force_text", "(", "name", ",", "encoding", "=", "self", ".", "_feat", ".", "encoding", ",", "strings_only", "=", "True", ")" ]
[ 73, 4 ]
[ 76, 80 ]
python
en
['en', 'en', 'en']
True
Field.precision
(self)
Returns the precision of this Field.
Returns the precision of this Field.
def precision(self): "Returns the precision of this Field." return capi.get_field_precision(self.ptr)
[ "def", "precision", "(", "self", ")", ":", "return", "capi", ".", "get_field_precision", "(", "self", ".", "ptr", ")" ]
[ 79, 4 ]
[ 81, 49 ]
python
en
['en', 'en', 'en']
True
Field.type
(self)
Returns the OGR type of this Field.
Returns the OGR type of this Field.
def type(self): "Returns the OGR type of this Field." return capi.get_field_type(self.ptr)
[ "def", "type", "(", "self", ")", ":", "return", "capi", ".", "get_field_type", "(", "self", ".", "ptr", ")" ]
[ 84, 4 ]
[ 86, 44 ]
python
en
['en', 'en', 'en']
True
Field.type_name
(self)
Return the OGR field type name for this Field.
Return the OGR field type name for this Field.
def type_name(self): "Return the OGR field type name for this Field." return capi.get_field_type_name(self.type)
[ "def", "type_name", "(", "self", ")", ":", "return", "capi", ".", "get_field_type_name", "(", "self", ".", "type", ")" ]
[ 89, 4 ]
[ 91, 50 ]
python
en
['en', 'en', 'en']
True
Field.value
(self)
Returns the value of this Field.
Returns the value of this Field.
def value(self): "Returns the value of this Field." # Default is to get the field as a string. return self.as_string()
[ "def", "value", "(", "self", ")", ":", "# Default is to get the field as a string.", "return", "self", ".", "as_string", "(", ")" ]
[ 94, 4 ]
[ 97, 31 ]
python
en
['en', 'en', 'en']
True
Field.width
(self)
Returns the width of this Field.
Returns the width of this Field.
def width(self): "Returns the width of this Field." return capi.get_field_width(self.ptr)
[ "def", "width", "(", "self", ")", ":", "return", "capi", ".", "get_field_width", "(", "self", ".", "ptr", ")" ]
[ 100, 4 ]
[ 102, 45 ]
python
en
['en', 'en', 'en']
True
OFTInteger.value
(self)
Returns an integer contained in this field.
Returns an integer contained in this field.
def value(self): "Returns an integer contained in this field." if self._double: # If this is really from an OFTReal field with no precision, # read as a double and cast as Python int (to prevent overflow). return int(self.as_double()) else: return ...
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_double", ":", "# If this is really from an OFTReal field with no precision,", "# read as a double and cast as Python int (to prevent overflow).", "return", "int", "(", "self", ".", "as_double", "(", ")", ")", "el...
[ 110, 4 ]
[ 117, 32 ]
python
en
['en', 'en', 'en']
True
OFTInteger.type
(self)
GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal.
GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal.
def type(self): """ GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal. """ return 0
[ "def", "type", "(", "self", ")", ":", "return", "0" ]
[ 120, 4 ]
[ 126, 16 ]
python
en
['en', 'error', 'th']
False
OFTReal.value
(self)
Returns a float contained in this field.
Returns a float contained in this field.
def value(self): "Returns a float contained in this field." return self.as_double()
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "as_double", "(", ")" ]
[ 131, 4 ]
[ 133, 31 ]
python
en
['en', 'en', 'en']
True
OFTDate.value
(self)
Returns a Python `date` object for the OFTDate field.
Returns a Python `date` object for the OFTDate field.
def value(self): "Returns a Python `date` object for the OFTDate field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return date(yy.value, mm.value, dd.value) except (ValueError, OGRException): return None
[ "def", "value", "(", "self", ")", ":", "try", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "self", ".", "as_datetime", "(", ")", "return", "date", "(", "yy", ".", "value", ",", "mm", ".", "value", ",", "...
[ 152, 4 ]
[ 158, 23 ]
python
en
['en', 'en', 'en']
True
OFTDateTime.value
(self)
Returns a Python `datetime` object for this OFTDateTime field.
Returns a Python `datetime` object for this OFTDateTime field.
def value(self): "Returns a Python `datetime` object for this OFTDateTime field." # TODO: Adapt timezone information. # See http://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html # The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous), # 100=GMT, 104...
[ "def", "value", "(", "self", ")", ":", "# TODO: Adapt timezone information.", "# See http://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html", "# The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous),", "# 100=GMT, 104=GMT+1, 80=GMT-5, etc.", "try", ":", "yy", ...
[ 163, 4 ]
[ 173, 23 ]
python
en
['en', 'en', 'en']
True
OFTTime.value
(self)
Returns a Python `time` object for this OFTTime field.
Returns a Python `time` object for this OFTTime field.
def value(self): "Returns a Python `time` object for this OFTTime field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return time(hh.value, mn.value, ss.value) except (ValueError, OGRException): return None
[ "def", "value", "(", "self", ")", ":", "try", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "self", ".", "as_datetime", "(", ")", "return", "time", "(", "hh", ".", "value", ",", "mn", ".", "value", ",", "...
[ 178, 4 ]
[ 184, 23 ]
python
en
['en', 'en', 'en']
True
set_script_prefix
(prefix)
Set the script prefix for the current thread.
Set the script prefix for the current thread.
def set_script_prefix(prefix): """ Set the script prefix for the current thread. """ if not prefix.endswith('/'): prefix += '/' _prefixes.value = prefix
[ "def", "set_script_prefix", "(", "prefix", ")", ":", "if", "not", "prefix", ".", "endswith", "(", "'/'", ")", ":", "prefix", "+=", "'/'", "_prefixes", ".", "value", "=", "prefix" ]
[ 98, 0 ]
[ 104, 28 ]
python
en
['en', 'error', 'th']
False
get_script_prefix
()
Return the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner).
Return the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner).
def get_script_prefix(): """ Return the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner). """ return getattr(_prefixes, "value", '/')
[ "def", "get_script_prefix", "(", ")", ":", "return", "getattr", "(", "_prefixes", ",", "\"value\"", ",", "'/'", ")" ]
[ 107, 0 ]
[ 113, 43 ]
python
en
['en', 'error', 'th']
False
clear_script_prefix
()
Unset the script prefix for the current thread.
Unset the script prefix for the current thread.
def clear_script_prefix(): """ Unset the script prefix for the current thread. """ try: del _prefixes.value except AttributeError: pass
[ "def", "clear_script_prefix", "(", ")", ":", "try", ":", "del", "_prefixes", ".", "value", "except", "AttributeError", ":", "pass" ]
[ 116, 0 ]
[ 123, 12 ]
python
en
['en', 'error', 'th']
False
set_urlconf
(urlconf_name)
Set the URLconf for the current thread (overriding the default one in settings). If urlconf_name is None, revert back to the default.
Set the URLconf for the current thread (overriding the default one in settings). If urlconf_name is None, revert back to the default.
def set_urlconf(urlconf_name): """ Set the URLconf for the current thread (overriding the default one in settings). If urlconf_name is None, revert back to the default. """ if urlconf_name: _urlconfs.value = urlconf_name else: if hasattr(_urlconfs, "value"): del _urlc...
[ "def", "set_urlconf", "(", "urlconf_name", ")", ":", "if", "urlconf_name", ":", "_urlconfs", ".", "value", "=", "urlconf_name", "else", ":", "if", "hasattr", "(", "_urlconfs", ",", "\"value\"", ")", ":", "del", "_urlconfs", ".", "value" ]
[ 126, 0 ]
[ 135, 31 ]
python
en
['en', 'error', 'th']
False
get_urlconf
(default=None)
Return the root URLconf to use for the current thread if it has been changed from the default one.
Return the root URLconf to use for the current thread if it has been changed from the default one.
def get_urlconf(default=None): """ Return the root URLconf to use for the current thread if it has been changed from the default one. """ return getattr(_urlconfs, "value", default)
[ "def", "get_urlconf", "(", "default", "=", "None", ")", ":", "return", "getattr", "(", "_urlconfs", ",", "\"value\"", ",", "default", ")" ]
[ 138, 0 ]
[ 143, 47 ]
python
en
['en', 'error', 'th']
False
is_valid_path
(path, urlconf=None)
Return True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding try...except blocks.
Return True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding try...except blocks.
def is_valid_path(path, urlconf=None): """ Return True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding try...except blocks. """ try: resolve(path, urlconf) re...
[ "def", "is_valid_path", "(", "path", ",", "urlconf", "=", "None", ")", ":", "try", ":", "resolve", "(", "path", ",", "urlconf", ")", "return", "True", "except", "Resolver404", ":", "return", "False" ]
[ 146, 0 ]
[ 156, 20 ]
python
en
['en', 'error', 'th']
False
translate_url
(url, lang_code)
Given a URL (absolute or relative), try to get its translated version in the `lang_code` language (either by i18n_patterns or by translated regex). Return the original URL if no translated version is found.
Given a URL (absolute or relative), try to get its translated version in the `lang_code` language (either by i18n_patterns or by translated regex). Return the original URL if no translated version is found.
def translate_url(url, lang_code): """ Given a URL (absolute or relative), try to get its translated version in the `lang_code` language (either by i18n_patterns or by translated regex). Return the original URL if no translated version is found. """ parsed = urlsplit(url) try: match ...
[ "def", "translate_url", "(", "url", ",", "lang_code", ")", ":", "parsed", "=", "urlsplit", "(", "url", ")", "try", ":", "match", "=", "resolve", "(", "parsed", ".", "path", ")", "except", "Resolver404", ":", "pass", "else", ":", "to_be_reversed", "=", ...
[ 159, 0 ]
[ 179, 14 ]
python
en
['en', 'error', 'th']
False
clean_ipv6_address
(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address."))
Clean an IPv6 address string. Raise ValidationError if the address is invalid. Replace the longest continuous zero-sequence with "::", remove leading zeroes, and make sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is fou...
Clean an IPv6 address string.
def clean_ipv6_address(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")): """ Clean an IPv6 address string. Raise ValidationError if the address is invalid. Replace the longest continuous zero-sequence with "::", remove leading zeroes, and make...
[ "def", "clean_ipv6_address", "(", "ip_str", ",", "unpack_ipv4", "=", "False", ",", "error_message", "=", "_", "(", "\"This is not a valid IPv6 address.\"", ")", ")", ":", "try", ":", "addr", "=", "ipaddress", ".", "IPv6Address", "(", "int", "(", "ipaddress", "...
[ 6, 0 ]
[ 34, 20 ]
python
en
['en', 'error', 'th']
False
is_valid_ipv6_address
(ip_str)
Return whether or not the `ip_str` string is a valid IPv6 address.
Return whether or not the `ip_str` string is a valid IPv6 address.
def is_valid_ipv6_address(ip_str): """ Return whether or not the `ip_str` string is a valid IPv6 address. """ try: ipaddress.IPv6Address(ip_str) except ValueError: return False return True
[ "def", "is_valid_ipv6_address", "(", "ip_str", ")", ":", "try", ":", "ipaddress", ".", "IPv6Address", "(", "ip_str", ")", "except", "ValueError", ":", "return", "False", "return", "True" ]
[ 37, 0 ]
[ 45, 15 ]
python
en
['en', 'error', 'th']
False
file_upload_view
(request)
Check that a file upload can be updated into the POST dictionary without going pear-shaped.
Check that a file upload can be updated into the POST dictionary without going pear-shaped.
def file_upload_view(request): """ Check that a file upload can be updated into the POST dictionary without going pear-shaped. """ form_data = request.POST.copy() form_data.update(request.FILES) if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], six.te...
[ "def", "file_upload_view", "(", "request", ")", ":", "form_data", "=", "request", ".", "POST", ".", "copy", "(", ")", "form_data", ".", "update", "(", "request", ".", "FILES", ")", "if", "isinstance", "(", "form_data", ".", "get", "(", "'file_field'", ")...
[ 16, 0 ]
[ 30, 40 ]
python
en
['en', 'error', 'th']
False
file_upload_view_verify
(request)
Use the sha digest hash to verify the uploaded contents.
Use the sha digest hash to verify the uploaded contents.
def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) for key, value in form_data.items(): if key.endswith('_hash'): continue if key + '_hash' not in form...
[ "def", "file_upload_view_verify", "(", "request", ")", ":", "form_data", "=", "request", ".", "POST", ".", "copy", "(", ")", "form_data", ".", "update", "(", "request", ".", "FILES", ")", "for", "key", ",", "value", "in", "form_data", ".", "items", "(", ...
[ 33, 0 ]
[ 58, 27 ]
python
en
['en', 'error', 'th']
False
file_upload_echo
(request)
Simple view to echo back info about uploaded files for tests.
Simple view to echo back info about uploaded files for tests.
def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. """ r = dict((k, f.name) for k, f in request.FILES.items()) return HttpResponse(json.dumps(r))
[ "def", "file_upload_echo", "(", "request", ")", ":", "r", "=", "dict", "(", "(", "k", ",", "f", ".", "name", ")", "for", "k", ",", "f", "in", "request", ".", "FILES", ".", "items", "(", ")", ")", "return", "HttpResponse", "(", "json", ".", "dumps...
[ 90, 0 ]
[ 95, 38 ]
python
en
['en', 'error', 'th']
False
file_upload_echo_content
(request)
Simple view to echo back the content of uploaded files for tests.
Simple view to echo back the content of uploaded files for tests.
def file_upload_echo_content(request): """ Simple view to echo back the content of uploaded files for tests. """ r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items()) return HttpResponse(json.dumps(r))
[ "def", "file_upload_echo_content", "(", "request", ")", ":", "r", "=", "dict", "(", "(", "k", ",", "f", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "for", "k", ",", "f", "in", "request", ".", "FILES", ".", "items", "(", ")", ...
[ 98, 0 ]
[ 103, 38 ]
python
en
['en', 'error', 'th']
False
file_upload_quota
(request)
Dynamically add in an upload handler.
Dynamically add in an upload handler.
def file_upload_quota(request): """ Dynamically add in an upload handler. """ request.upload_handlers.insert(0, QuotaUploadHandler()) return file_upload_echo(request)
[ "def", "file_upload_quota", "(", "request", ")", ":", "request", ".", "upload_handlers", ".", "insert", "(", "0", ",", "QuotaUploadHandler", "(", ")", ")", "return", "file_upload_echo", "(", "request", ")" ]
[ 106, 0 ]
[ 111, 36 ]
python
en
['en', 'error', 'th']
False
file_upload_quota_broken
(request)
You can't change handlers after reading FILES; this view shouldn't work.
You can't change handlers after reading FILES; this view shouldn't work.
def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
[ "def", "file_upload_quota_broken", "(", "request", ")", ":", "response", "=", "file_upload_echo", "(", "request", ")", "request", ".", "upload_handlers", ".", "insert", "(", "0", ",", "QuotaUploadHandler", "(", ")", ")", "return", "response" ]
[ 114, 0 ]
[ 120, 19 ]
python
en
['en', 'error', 'th']
False
file_upload_getlist_count
(request)
Check the .getlist() function to ensure we receive the correct number of files.
Check the .getlist() function to ensure we receive the correct number of files.
def file_upload_getlist_count(request): """ Check the .getlist() function to ensure we receive the correct number of files. """ file_counts = {} for key in request.FILES.keys(): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts))
[ "def", "file_upload_getlist_count", "(", "request", ")", ":", "file_counts", "=", "{", "}", "for", "key", "in", "request", ".", "FILES", ".", "keys", "(", ")", ":", "file_counts", "[", "key", "]", "=", "len", "(", "request", ".", "FILES", ".", "getlist...
[ 123, 0 ]
[ 131, 48 ]
python
en
['en', 'error', 'th']
False
file_upload_filename_case_view
(request)
Check adding the file to the database will preserve the filename case.
Check adding the file to the database will preserve the filename case.
def file_upload_filename_case_view(request): """ Check adding the file to the database will preserve the filename case. """ file = request.FILES['file_field'] obj = FileModel() obj.testfile.save(file.name, file) return HttpResponse('%d' % obj.pk)
[ "def", "file_upload_filename_case_view", "(", "request", ")", ":", "file", "=", "request", ".", "FILES", "[", "'file_field'", "]", "obj", "=", "FileModel", "(", ")", "obj", ".", "testfile", ".", "save", "(", "file", ".", "name", ",", "file", ")", "return...
[ 139, 0 ]
[ 146, 38 ]
python
en
['en', 'error', 'th']
False
file_upload_content_type_extra
(request)
Simple view to echo back extra content-type parameters.
Simple view to echo back extra content-type parameters.
def file_upload_content_type_extra(request): """ Simple view to echo back extra content-type parameters. """ params = {} for file_name, uploadedfile in request.FILES.items(): params[file_name] = dict([ (k, smart_str(v)) for k, v in uploadedfile.content_type_extra.items() ...
[ "def", "file_upload_content_type_extra", "(", "request", ")", ":", "params", "=", "{", "}", "for", "file_name", ",", "uploadedfile", "in", "request", ".", "FILES", ".", "items", "(", ")", ":", "params", "[", "file_name", "]", "=", "dict", "(", "[", "(", ...
[ 149, 0 ]
[ 158, 43 ]
python
en
['en', 'error', 'th']
False
generic_inlineformset_factory
(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, ...
Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively.
Return a ``GenericInlineFormSet`` for the given kwargs.
def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=...
[ "def", "generic_inlineformset_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseGenericInlineFormSet", ",", "ct_field", "=", "\"content_type\"", ",", "fk_field", "=", "\"object_id\"", ",", "fields", "=", "None", ",", "exclude", "=", ...
[ 51, 0 ]
[ 81, 18 ]
python
en
['en', 'error', 'th']
False
SwappableModelTests.test_generated_data
(self)
Permissions and content types are not created for a swapped model
Permissions and content types are not created for a swapped model
def test_generated_data(self): "Permissions and content types are not created for a swapped model" # Delete all permissions and content_types Permission.objects.filter(content_type__app_label='swappable_models').delete() ContentType.objects.filter(app_label='swappable_models').delete() ...
[ "def", "test_generated_data", "(", "self", ")", ":", "# Delete all permissions and content_types", "Permission", ".", "objects", ".", "filter", "(", "content_type__app_label", "=", "'swappable_models'", ")", ".", "delete", "(", ")", "ContentType", ".", "objects", ".",...
[ 21, 4 ]
[ 42, 70 ]
python
en
['en', 'en', 'en']
True
SwappableModelTests.test_case_insensitive
(self)
Model names are case insensitive. Check that model swapping honors this.
Model names are case insensitive. Check that model swapping honors this.
def test_case_insensitive(self): "Model names are case insensitive. Check that model swapping honors this." try: Article.objects.all() except AttributeError: self.fail('Swappable model names should be case insensitive.') self.assertIsNone(Article._meta.swapped)
[ "def", "test_case_insensitive", "(", "self", ")", ":", "try", ":", "Article", ".", "objects", ".", "all", "(", ")", "except", "AttributeError", ":", "self", ".", "fail", "(", "'Swappable model names should be case insensitive.'", ")", "self", ".", "assertIsNone", ...
[ 45, 4 ]
[ 52, 48 ]
python
en
['en', 'en', 'en']
True
make_directory_writable
(dirname)
Makes directory readable and writable by everybody. If you run something inside Docker container and it writes files, then these files will be written as root user with restricted permissions. So to be able to read/modify these files outside of Docker you have to change permissions to be world readable...
Makes directory readable and writable by everybody.
def make_directory_writable(dirname): """Makes directory readable and writable by everybody. If you run something inside Docker container and it writes files, then these files will be written as root user with restricted permissions. So to be able to read/modify these files outside of Docker you have t...
[ "def", "make_directory_writable", "(", "dirname", ")", ":", "shell_call", "(", "[", "\"docker\"", ",", "\"run\"", ",", "\"-v\"", ",", "\"{0}:/output_dir\"", ".", "format", "(", "dirname", ")", ",", "\"busybox:1.27.2\"", ",", "\"chmod\"", ",", "\"-R\"", ",", "\...
[ 92, 0 ]
[ 118, 5 ]
python
en
['en', 'en', 'en']
True
sudo_remove_dirtree
(dir_name)
Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root.
Removes directory tree as a superuser.
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ t...
[ "def", "sudo_remove_dirtree", "(", "dir_name", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "\"sudo\"", ",", "\"rm\"", ",", "\"-rf\"", ",", "dir_name", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise"...
[ 121, 0 ]
[ 134, 77 ]
python
en
['en', 'en', 'en']
True
get_id_of_running_docker
(container_name)
Returns ID of running docker container.
Returns ID of running docker container.
def get_id_of_running_docker(container_name): """Returns ID of running docker container.""" return shell_call( [DOCKER_BINARY, "ps", "-q", "--filter=name={}".format(container_name)] ).strip()
[ "def", "get_id_of_running_docker", "(", "container_name", ")", ":", "return", "shell_call", "(", "[", "DOCKER_BINARY", ",", "\"ps\"", ",", "\"-q\"", ",", "\"--filter=name={}\"", ".", "format", "(", "container_name", ")", "]", ")", ".", "strip", "(", ")" ]
[ 164, 0 ]
[ 168, 13 ]
python
en
['en', 'sn', 'en']
True
is_docker_still_running
(container_name)
Returns whether given Docker container is still running.
Returns whether given Docker container is still running.
def is_docker_still_running(container_name): """Returns whether given Docker container is still running.""" return bool(get_id_of_running_docker(container_name))
[ "def", "is_docker_still_running", "(", "container_name", ")", ":", "return", "bool", "(", "get_id_of_running_docker", "(", "container_name", ")", ")" ]
[ 171, 0 ]
[ 173, 57 ]
python
en
['en', 'en', 'en']
True
kill_docker_container
(container_name)
Kills given docker container.
Kills given docker container.
def kill_docker_container(container_name): """Kills given docker container.""" docker_id = get_id_of_running_docker(container_name) shell_call([DOCKER_BINARY, "stop", docker_id])
[ "def", "kill_docker_container", "(", "container_name", ")", ":", "docker_id", "=", "get_id_of_running_docker", "(", "container_name", ")", "shell_call", "(", "[", "DOCKER_BINARY", ",", "\"stop\"", ",", "docker_id", "]", ")" ]
[ 176, 0 ]
[ 179, 50 ]
python
en
['da', 'en', 'en']
True
main
(args)
Main function which runs worker.
Main function which runs worker.
def main(args): """Main function which runs worker.""" title = "## Starting evaluation of round {0} ##".format(args.round_name) logging.info( "\n" + "#" * len(title) + "\n" + "#" * len(title) + "\n" + "##" + " " * (len(title) - 2) + "##" ...
[ "def", "main", "(", "args", ")", ":", "title", "=", "\"## Starting evaluation of round {0} ##\"", ".", "format", "(", "args", ".", "round_name", ")", "logging", ".", "info", "(", "\"\\n\"", "+", "\"#\"", "*", "len", "(", "title", ")", "+", "\"\\n\"", "+", ...
[ 1029, 0 ]
[ 1074, 26 ]
python
en
['en', 'en', 'en']
True
WorkerError.__init__
(self, message, exc=None)
Initializes WorkerError. Args: message: error message exc: optional underlying exception.
Initializes WorkerError.
def __init__(self, message, exc=None): """Initializes WorkerError. Args: message: error message exc: optional underlying exception. """ super(WorkerError, self).__init__() self.msg = message self.exc = exc
[ "def", "__init__", "(", "self", ",", "message", ",", "exc", "=", "None", ")", ":", "super", "(", "WorkerError", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "msg", "=", "message", "self", ".", "exc", "=", "exc" ]
[ 145, 4 ]
[ 154, 22 ]
python
en
['pl', 'en', 'nl']
False
WorkerError.__str__
(self)
Returns human readable string representation of the exception.
Returns human readable string representation of the exception.
def __str__(self): """Returns human readable string representation of the exception.""" if self.exc: return "{0}\nUnderlying exception:\n{1}".format(self.msg, self.exc) else: return self.msg
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "exc", ":", "return", "\"{0}\\nUnderlying exception:\\n{1}\"", ".", "format", "(", "self", ".", "msg", ",", "self", ".", "exc", ")", "else", ":", "return", "self", ".", "msg" ]
[ 156, 4 ]
[ 161, 27 ]
python
en
['en', 'en', 'en']
True
ExecutableSubmission.__init__
(self, submission_id, submissions, storage_bucket)
Initializes ExecutableSubmission. Args: submission_id: ID of the submissions submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are stored Raises: WorkerError: if submission was not found ...
Initializes ExecutableSubmission.
def __init__(self, submission_id, submissions, storage_bucket): """Initializes ExecutableSubmission. Args: submission_id: ID of the submissions submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are sto...
[ "def", "__init__", "(", "self", ",", "submission_id", ",", "submissions", ",", "storage_bucket", ")", ":", "self", ".", "submission_id", "=", "submission_id", "self", ".", "storage_bucket", "=", "storage_bucket", "self", ".", "type", "=", "None", "self", ".", ...
[ 185, 4 ]
[ 214, 44 ]
python
en
['pl', 'en', 'en']
False
ExecutableSubmission.download
(self)
Method which downloads submission to local directory.
Method which downloads submission to local directory.
def download(self): """Method which downloads submission to local directory.""" # Structure of the download directory: # submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id # submission_dir/s.ext <-- archived submission # submission_dir/extracted <-- extracted submission ...
[ "def", "download", "(", "self", ")", ":", "# Structure of the download directory:", "# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id", "# submission_dir/s.ext <-- archived submission", "# submission_dir/extracted <-- extracted submission", "# Check whether submission is already there...
[ 216, 4 ]
[ 332, 17 ]
python
en
['en', 'en', 'en']
True
ExecutableSubmission.temp_copy_extracted_submission
(self)
Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary copy of submission is deleted....
Creates a temporary copy of extracted submission.
def temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a...
[ "def", "temp_copy_extracted_submission", "(", "self", ")", ":", "tmp_copy_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "submission_dir", ",", "\"tmp_copy\"", ")", "shell_call", "(", "[", "\"cp\"", ",", "\"-R\"", ",", "os", ".", "path", ".",...
[ 334, 4 ]
[ 349, 27 ]
python
en
['en', 'en', 'en']
True
ExecutableSubmission.run_without_time_limit
(self, cmd)
Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if error occurred during execution of the submission ...
Runs docker command without time limit.
def run_without_time_limit(self, cmd): """Runs docker command without time limit. Args: cmd: list with the command line arguments which are passed to docker binary Returns: how long it took to run submission in seconds Raises: WorkerError: if ...
[ "def", "run_without_time_limit", "(", "self", ",", "cmd", ")", ":", "cmd", "=", "[", "DOCKER_BINARY", ",", "\"run\"", ",", "DOCKER_NVIDIA_RUNTIME", "]", "+", "cmd", "logging", ".", "info", "(", "\"Docker command: %s\"", ",", "\" \"", ".", "join", "(", "cmd",...
[ 351, 4 ]
[ 374, 31 ]
python
en
['en', 'en', 'en']
True
ExecutableSubmission.run_with_time_limit
(self, cmd, time_limit=SUBMISSION_TIME_LIMIT)
Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no limit. Returns: how long it took to run submission in seconds ...
Runs docker command and enforces time limit.
def run_with_time_limit(self, cmd, time_limit=SUBMISSION_TIME_LIMIT): """Runs docker command and enforces time limit. Args: cmd: list with the command line arguments which are passed to docker binary after run time_limit: time limit, in seconds. Negative value means no l...
[ "def", "run_with_time_limit", "(", "self", ",", "cmd", ",", "time_limit", "=", "SUBMISSION_TIME_LIMIT", ")", ":", "if", "time_limit", "<", "0", ":", "return", "self", ".", "run_without_time_limit", "(", "cmd", ")", "container_name", "=", "str", "(", "uuid", ...
[ 376, 4 ]
[ 418, 31 ]
python
en
['en', 'fr', 'en']
True
AttackSubmission.__init__
(self, submission_id, submissions, storage_bucket)
Initializes AttackSubmission. Args: submission_id: ID of the submission submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are stored Raises: WorkerError: if submission has incorrect type ...
Initializes AttackSubmission.
def __init__(self, submission_id, submissions, storage_bucket): """Initializes AttackSubmission. Args: submission_id: ID of the submission submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are stored ...
[ "def", "__init__", "(", "self", ",", "submission_id", ",", "submissions", ",", "storage_bucket", ")", ":", "super", "(", "AttackSubmission", ",", "self", ")", ".", "__init__", "(", "submission_id", ",", "submissions", ",", "storage_bucket", ")", "if", "(", "...
[ 424, 4 ]
[ 441, 13 ]
python
en
['en', 'en', 'en']
False
AttackSubmission.run
(self, input_dir, output_dir, epsilon)
Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, should be in range [0, 255]. Returns: ho...
Runs attack inside Docker.
def run(self, input_dir, output_dir, epsilon): """Runs attack inside Docker. Args: input_dir: directory with input (dataset). output_dir: directory where output (adversarial images) should be written. epsilon: maximum allowed size of adversarial perturbation, s...
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_dir", ",", "epsilon", ")", ":", "logging", ".", "info", "(", "\"Running attack %s\"", ",", "self", ".", "submission_id", ")", "tmp_run_dir", "=", "self", ".", "temp_copy_extracted_submission", "(", ")",...
[ 443, 4 ]
[ 477, 31 ]
python
en
['en', 'sv', 'en']
True
DefenseSubmission.__init__
(self, submission_id, submissions, storage_bucket)
Initializes DefenseSubmission. Args: submission_id: ID of the submission submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are stored Raises: WorkerError: if submission has incorrect type ...
Initializes DefenseSubmission.
def __init__(self, submission_id, submissions, storage_bucket): """Initializes DefenseSubmission. Args: submission_id: ID of the submission submissions: instance of CompetitionSubmissions with all submissions storage_bucket: storage bucket where all submissions are stored ...
[ "def", "__init__", "(", "self", ",", "submission_id", ",", "submissions", ",", "storage_bucket", ")", ":", "super", "(", "DefenseSubmission", ",", "self", ")", ".", "__init__", "(", "submission_id", ",", "submissions", ",", "storage_bucket", ")", "if", "self",...
[ 483, 4 ]
[ 500, 13 ]
python
en
['pl', 'en', 'en']
False
DefenseSubmission.run
(self, input_dir, output_file_path)
Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds
Runs defense inside Docker.
def run(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds """ logging.inf...
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_file_path", ")", ":", "logging", ".", "info", "(", "\"Running defense %s\"", ",", "self", ".", "submission_id", ")", "tmp_run_dir", "=", "self", ".", "temp_copy_extracted_submission", "(", ")", "output_di...
[ 502, 4 ]
[ 535, 31 ]
python
en
['fr', 'sv', 'en']
False
EvaluationWorker.__init__
( self, worker_id, storage_client, datastore_client, storage_bucket, round_name, dataset_name, blacklisted_submissions="", num_defense_shards=None, )
Initializes EvaluationWorker. Args: worker_id: ID of the worker storage_client: instance of eval_lib.CompetitionStorageClient datastore_client: instance of eval_lib.CompetitionDatastoreClient storage_bucket: name of the Google Cloud Storage bucket where all c...
Initializes EvaluationWorker.
def __init__( self, worker_id, storage_client, datastore_client, storage_bucket, round_name, dataset_name, blacklisted_submissions="", num_defense_shards=None, ): """Initializes EvaluationWorker. Args: worker_id: ID o...
[ "def", "__init__", "(", "self", ",", "worker_id", ",", "storage_client", ",", "datastore_client", ",", "storage_bucket", ",", "round_name", ",", "dataset_name", ",", "blacklisted_submissions", "=", "\"\"", ",", "num_defense_shards", "=", "None", ",", ")", ":", "...
[ 546, 4 ]
[ 615, 32 ]
python
en
['pl', 'la', 'en']
False
EvaluationWorker.read_dataset_metadata
(self)
Read `dataset_meta` field from bucket
Read `dataset_meta` field from bucket
def read_dataset_metadata(self): """Read `dataset_meta` field from bucket""" if self.dataset_meta: return shell_call( [ "gsutil", "cp", "gs://" + self.storage_client.bucket_name + "/" ...
[ "def", "read_dataset_metadata", "(", "self", ")", ":", "if", "self", ".", "dataset_meta", ":", "return", "shell_call", "(", "[", "\"gsutil\"", ",", "\"cp\"", ",", "\"gs://\"", "+", "self", ".", "storage_client", ".", "bucket_name", "+", "\"/\"", "+", "\"data...
[ 617, 4 ]
[ 635, 59 ]
python
en
['en', 'nl', 'en']
True
EvaluationWorker.fetch_attacks_data
(self)
Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop.
Initializes data necessary to execute attacks.
def fetch_attacks_data(self): """Initializes data necessary to execute attacks. This method could be called multiple times, only first call does initialization, subsequent calls are noop. """ if self.attacks_data_initialized: return # init data from datastore...
[ "def", "fetch_attacks_data", "(", "self", ")", ":", "if", "self", ".", "attacks_data_initialized", ":", "return", "# init data from datastore", "self", ".", "submissions", ".", "init_from_datastore", "(", ")", "self", ".", "dataset_batches", ".", "init_from_datastore"...
[ 637, 4 ]
[ 661, 44 ]
python
en
['en', 'en', 'en']
True