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
ProxyModelTests.test_no_cbc
(self)
The proxy must actually have one concrete base class
The proxy must actually have one concrete base class
def test_no_cbc(self): """ The proxy must actually have one concrete base class """ def build_no_cbc(): class TooManyBases(Person, Abstract): class Meta: proxy = True self.assertRaises(TypeError, build_no_cbc)
[ "def", "test_no_cbc", "(", "self", ")", ":", "def", "build_no_cbc", "(", ")", ":", "class", "TooManyBases", "(", "Person", ",", "Abstract", ")", ":", "class", "Meta", ":", "proxy", "=", "True", "self", ".", "assertRaises", "(", "TypeError", ",", "build_n...
[ 127, 4 ]
[ 135, 50 ]
python
en
['en', 'error', 'th']
False
ProxyModelTests.test_proxy_model_signals
(self)
Test save signals for proxy models
Test save signals for proxy models
def test_proxy_model_signals(self): """ Test save signals for proxy models """ output = [] def make_handler(model, event): def _handler(*args, **kwargs): output.append('%s %s save' % (model, event)) return _handler h1 = make_handl...
[ "def", "test_proxy_model_signals", "(", "self", ")", ":", "output", "=", "[", "]", "def", "make_handler", "(", "model", ",", "event", ")", ":", "def", "_handler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "output", ".", "append", "(", "'%s...
[ 223, 4 ]
[ 270, 62 ]
python
en
['en', 'error', 'th']
False
ProxyModelTests.test_proxy_delete
(self)
Proxy objects can be deleted
Proxy objects can be deleted
def test_proxy_delete(self): """ Proxy objects can be deleted """ User.objects.create(name='Bruce') u2 = UserProxy.objects.create(name='George') resp = [u.name for u in UserProxy.objects.all()] self.assertEqual(resp, ['Bruce', 'George']) u2.delete() ...
[ "def", "test_proxy_delete", "(", "self", ")", ":", "User", ".", "objects", ".", "create", "(", "name", "=", "'Bruce'", ")", "u2", "=", "UserProxy", ".", "objects", ".", "create", "(", "name", "=", "'George'", ")", "resp", "=", "[", "u", ".", "name", ...
[ 294, 4 ]
[ 307, 41 ]
python
en
['en', 'error', 'th']
False
ProxyModelTests.test_select_related
(self)
We can still use `select_related()` to include related models in our querysets.
We can still use `select_related()` to include related models in our querysets.
def test_select_related(self): """ We can still use `select_related()` to include related models in our querysets. """ country = Country.objects.create(name='Australia') State.objects.create(name='New South Wales', country=country) resp = [s.name for s in State.o...
[ "def", "test_select_related", "(", "self", ")", ":", "country", "=", "Country", ".", "objects", ".", "create", "(", "name", "=", "'Australia'", ")", "State", ".", "objects", ".", "create", "(", "name", "=", "'New South Wales'", ",", "country", "=", "countr...
[ 309, 4 ]
[ 327, 54 ]
python
en
['en', 'error', 'th']
False
extract_packages
(package_names)
Extract zipfile contents to disk and add to import path
Extract zipfile contents to disk and add to import path
def extract_packages(package_names): """Extract zipfile contents to disk and add to import path""" # Set a safe extraction dir extraction_tmpdir = tempfile.mkdtemp() atexit.register(lambda: shutil.rmtree( extraction_tmpdir, ignore_errors=True)) pkg_resources.set_extraction_path(extraction_t...
[ "def", "extract_packages", "(", "package_names", ")", ":", "# Set a safe extraction dir", "extraction_tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "atexit", ".", "register", "(", "lambda", ":", "shutil", ".", "rmtree", "(", "extraction_tmpdir", ",", "ignore...
[ 32, 0 ]
[ 54, 52 ]
python
en
['en', 'en', 'en']
True
sort_wheels
(whls)
Sorts a list of wheels deterministically.
Sorts a list of wheels deterministically.
def sort_wheels(whls): """Sorts a list of wheels deterministically.""" return sorted(whls, key=lambda w: w.distribution() + '_' + w.version())
[ "def", "sort_wheels", "(", "whls", ")", ":", "return", "sorted", "(", "whls", ",", "key", "=", "lambda", "w", ":", "w", ".", "distribution", "(", ")", "+", "'_'", "+", "w", ".", "version", "(", ")", ")" ]
[ 110, 0 ]
[ 112, 73 ]
python
en
['en', 'en', 'en']
True
determine_possible_extras
(whls)
Determines the list of possible "extras" for each .whl The possibility of an extra is determined by looking at its additional requirements, and determinine whether they are satisfied by the complete list of available wheels. Args: whls: a list of Wheel objects Returns: a dict that is keyed by the W...
Determines the list of possible "extras" for each .whl
def determine_possible_extras(whls): """Determines the list of possible "extras" for each .whl The possibility of an extra is determined by looking at its additional requirements, and determinine whether they are satisfied by the complete list of available wheels. Args: whls: a list of Wheel objects ...
[ "def", "determine_possible_extras", "(", "whls", ")", ":", "whl_map", "=", "{", "whl", ".", "distribution", "(", ")", ":", "whl", "for", "whl", "in", "whls", "}", "# TODO(mattmoor): Consider memoizing if this recursion ever becomes", "# expensive enough to warrant it.", ...
[ 114, 0 ]
[ 166, 3 ]
python
en
['en', 'en', 'en']
True
DefaultFiltersTests.test_dictsort_complex_sorting_key
(self)
Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'.
Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'.
def test_dictsort_complex_sorting_key(self): """ Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'. """ data = [ {'foo': {'bar': 1, 'baz': 'c'}}, {'foo': {'bar': 2, 'baz': 'b'}}, {'foo': {'bar': 3, 'baz': ...
[ "def", "test_dictsort_complex_sorting_key", "(", "self", ")", ":", "data", "=", "[", "{", "'foo'", ":", "{", "'bar'", ":", "1", ",", "'baz'", ":", "'c'", "}", "}", ",", "{", "'foo'", ":", "{", "'bar'", ":", "2", ",", "'baz'", ":", "'b'", "}", "}"...
[ 463, 4 ]
[ 475, 75 ]
python
en
['en', 'error', 'th']
False
wrap_text
(text, width)
wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results.
wrap_text(text : string, width : int) -> [string]
def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ if text is None: return [] if len(text) <= width: return [text] text =...
[ "def", "wrap_text", "(", "text", ",", "width", ")", ":", "if", "text", "is", "None", ":", "return", "[", "]", "if", "len", "(", "text", ")", "<=", "width", ":", "return", "[", "text", "]", "text", "=", "text", ".", "expandtabs", "(", ")", "text",...
[ 374, 0 ]
[ 425, 16 ]
python
en
['en', 'en', 'en']
True
translate_longopt
(opt)
Convert a long option name to a valid Python identifier by changing "-" to "_".
Convert a long option name to a valid Python identifier by changing "-" to "_".
def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ return opt.translate(longopt_xlate)
[ "def", "translate_longopt", "(", "opt", ")", ":", "return", "opt", ".", "translate", "(", "longopt_xlate", ")" ]
[ 428, 0 ]
[ 432, 39 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.has_option
(self, long_option)
Return true if the option table for this parser has an option with long name 'long_option'.
Return true if the option table for this parser has an option with long name 'long_option'.
def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index
[ "def", "has_option", "(", "self", ",", "long_option", ")", ":", "return", "long_option", "in", "self", ".", "option_index" ]
[ 98, 4 ]
[ 101, 47 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.get_attr_name
(self, long_option)
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return long_option.translate(longopt_xlate)
[ "def", "get_attr_name", "(", "self", ",", "long_option", ")", ":", "return", "long_option", ".", "translate", "(", "longopt_xlate", ")" ]
[ 103, 4 ]
[ 107, 51 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.set_aliases
(self, alias)
Set the aliases for this option parser.
Set the aliases for this option parser.
def set_aliases(self, alias): """Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias
[ "def", "set_aliases", "(", "self", ",", "alias", ")", ":", "self", ".", "_check_alias_dict", "(", "alias", ",", "\"alias\"", ")", "self", ".", "alias", "=", "alias" ]
[ 119, 4 ]
[ 122, 26 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.set_negative_aliases
(self, negative_alias)
Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.
Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.
def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.""" self._check_alias_dict(negative...
[ "def", "set_negative_aliases", "(", "self", ",", "negative_alias", ")", ":", "self", ".", "_check_alias_dict", "(", "negative_alias", ",", "\"negative alias\"", ")", "self", ".", "negative_alias", "=", "negative_alias" ]
[ 124, 4 ]
[ 130, 44 ]
python
en
['en', 'en', 'en']
True
FancyGetopt._grok_option_table
(self)
Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile.
Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile.
def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} ...
[ "def", "_grok_option_table", "(", "self", ")", ":", "self", ".", "long_opts", "=", "[", "]", "self", ".", "short_opts", "=", "[", "]", "self", ".", "short2long", ".", "clear", "(", ")", "self", ".", "repeat", "=", "{", "}", "for", "option", "in", "...
[ 132, 4 ]
[ 207, 48 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.getopt
(self, args=None, object=None)
Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If 'object' is supplied, it...
Parse command-line options in args. Store as attributes on object.
def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple...
[ "def", "getopt", "(", "self", ",", "args", "=", "None", ",", "object", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "object", "is", "None", ":", "object", "=", "OptionDummy", ...
[ 209, 4 ]
[ 268, 23 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.get_option_order
(self)
Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet.
Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet.
def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: raise RuntimeError("'getopt()' hasn't been called yet") ...
[ "def", "get_option_order", "(", "self", ")", ":", "if", "self", ".", "option_order", "is", "None", ":", "raise", "RuntimeError", "(", "\"'getopt()' hasn't been called yet\"", ")", "else", ":", "return", "self", ".", "option_order" ]
[ 270, 4 ]
[ 278, 36 ]
python
en
['en', 'en', 'en']
True
FancyGetopt.generate_help
(self, header=None)
Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object.
Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object.
def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ # Blithely assume the option table is good: probably wouldn't call # 'generate_help()' unless you've already ca...
[ "def", "generate_help", "(", "self", ",", "header", "=", "None", ")", ":", "# Blithely assume the option table is good: probably wouldn't call", "# 'generate_help()' unless you've already called 'getopt()'.", "# First pass: determine maximum length of long option names", "max_opt", "=", ...
[ 280, 4 ]
[ 357, 20 ]
python
en
['en', 'en', 'en']
True
OptionDummy.__init__
(self, options=[])
Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.
Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.
def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None)
[ "def", "__init__", "(", "self", ",", "options", "=", "[", "]", ")", ":", "for", "opt", "in", "options", ":", "setattr", "(", "self", ",", "opt", ",", "None", ")" ]
[ 439, 4 ]
[ 443, 36 ]
python
en
['en', 'en', 'en']
True
main
()
this function generates a csv file that contains the performances for the different stimuli sets # python3 svrt_test.py -net resnet50 -pretrained 0
this function generates a csv file that contains the performances for the different stimuli sets # python3 svrt_test.py -net resnet50 -pretrained 0
def main(): ''' this function generates a csv file that contains the performances for the different stimuli sets # python3 svrt_test.py -net resnet50 -pretrained 0 ''' parser = argparse.ArgumentParser(description='SVRT test') parser.add_argument('-net', help='network') parser.add_argumen...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'SVRT test'", ")", "parser", ".", "add_argument", "(", "'-net'", ",", "help", "=", "'network'", ")", "parser", ".", "add_argument", "(", "'-pretrained'"...
[ 42, 0 ]
[ 138, 31 ]
python
en
['en', 'error', 'th']
False
last_arg_byref
(args)
Return the last C argument's value by reference.
Return the last C argument's value by reference.
def last_arg_byref(args): "Return the last C argument's value by reference." return args[-1]._obj.value
[ "def", "last_arg_byref", "(", "args", ")", ":", "return", "args", "[", "-", "1", "]", ".", "_obj", ".", "value" ]
[ 14, 0 ]
[ 16, 30 ]
python
en
['en', 'en', 'en']
True
check_dbl
(result, func, cargs)
Check the status code and returns the double value passed in by reference.
Check the status code and returns the double value passed in by reference.
def check_dbl(result, func, cargs): "Check the status code and returns the double value passed in by reference." # Checking the status code if result != 1: return None # Double passed in by reference, return its value. return last_arg_byref(cargs)
[ "def", "check_dbl", "(", "result", ",", "func", ",", "cargs", ")", ":", "# Checking the status code", "if", "result", "!=", "1", ":", "return", "None", "# Double passed in by reference, return its value.", "return", "last_arg_byref", "(", "cargs", ")" ]
[ 19, 0 ]
[ 25, 32 ]
python
en
['en', 'en', 'en']
True
check_geom
(result, func, cargs)
Error checking on routines that return Geometries.
Error checking on routines that return Geometries.
def check_geom(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__) return result
[ "def", "check_geom", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Error encountered checking Geometry returned from GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "return", "result" ]
[ 28, 0 ]
[ 32, 17 ]
python
en
['en', 'el-Latn', 'en']
True
check_minus_one
(result, func, cargs)
Error checking on routines that should not return -1.
Error checking on routines that should not return -1.
def check_minus_one(result, func, cargs): "Error checking on routines that should not return -1." if result == -1: raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__) else: return result
[ "def", "check_minus_one", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "-", "1", ":", "raise", "GEOSException", "(", "'Error encountered in GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "else", ":", "return", "resul...
[ 35, 0 ]
[ 40, 21 ]
python
en
['en', 'en', 'en']
True
check_predicate
(result, func, cargs)
Error checking for unary/binary predicate functions.
Error checking for unary/binary predicate functions.
def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." if result == 1: return True elif result == 0: return False else: raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
[ "def", "check_predicate", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "1", ":", "return", "True", "elif", "result", "==", "0", ":", "return", "False", "else", ":", "raise", "GEOSException", "(", "'Error encountered on GEOS C pre...
[ 43, 0 ]
[ 50, 99 ]
python
en
['en', 'en', 'en']
True
check_sized_string
(result, func, cargs)
Error checking for routines that return explicitly sized strings. This frees the memory allocated by GEOS at the result pointer.
Error checking for routines that return explicitly sized strings.
def check_sized_string(result, func, cargs): """ Error checking for routines that return explicitly sized strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__)...
[ "def", "check_sized_string", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Invalid string pointer returned by GEOS C function \"%s\"'", "%", "func", ".", "__name__", ")", "# A c_size_t object is passed i...
[ 53, 0 ]
[ 67, 12 ]
python
en
['en', 'error', 'th']
False
check_string
(result, func, cargs)
Error checking for routines that return strings. This frees the memory allocated by GEOS at the result pointer.
Error checking for routines that return strings.
def check_string(result, func, cargs): """ Error checking for routines that return strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__) # ...
[ "def", "check_string", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "not", "result", ":", "raise", "GEOSException", "(", "'Error encountered checking string return value in GEOS C function \"%s\".'", "%", "func", ".", "__name__", ")", "# Getting the string ...
[ 70, 0 ]
[ 82, 12 ]
python
en
['en', 'error', 'th']
False
get_pred
(outputs, labels)
get prediction of model, batch_size has to be 1
get prediction of model, batch_size has to be 1
def get_pred(outputs, labels): ''' get prediction of model, batch_size has to be 1 ''' sigm = torch.nn.Sigmoid()(outputs) predicted = (sigm > 0.5).float() return predicted
[ "def", "get_pred", "(", "outputs", ",", "labels", ")", ":", "sigm", "=", "torch", ".", "nn", ".", "Sigmoid", "(", ")", "(", "outputs", ")", "predicted", "=", "(", "sigm", ">", "0.5", ")", ".", "float", "(", ")", "return", "predicted" ]
[ 23, 0 ]
[ 29, 20 ]
python
en
['en', 'error', 'th']
False
main
()
this function generates a csv file that contains the predictions for the individual images
this function generates a csv file that contains the predictions for the individual images
def main(): ''' this function generates a csv file that contains the predictions for the individual images ''' parser = argparse.ArgumentParser( description='CC generalisation, results for individual images') parser.add_argument( '-exp_name', help='experiment name (has to be ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'CC generalisation, results for individual images'", ")", "parser", ".", "add_argument", "(", "'-exp_name'", ",", "help", "=", "'experiment name (has to be the same...
[ 72, 0 ]
[ 133, 41 ]
python
en
['en', 'error', 'th']
False
JSONConfigSource.file_path
(self)
Path to config file.
Path to config file.
def file_path(self) -> Path: """Path to config file.""" return self._file_path
[ "def", "file_path", "(", "self", ")", "->", "Path", ":", "return", "self", ".", "_file_path" ]
[ 23, 4 ]
[ 25, 30 ]
python
en
['en', 'en', 'en']
True
JSONConfigSource.file_path
(self, value: Path)
Set config file path. Args: value (Path): New path to config file Returns: Path: Path to config file
Set config file path.
def file_path(self, value: Path) -> Path: """Set config file path. Args: value (Path): New path to config file Returns: Path: Path to config file """ self._file_path = value return self._file_path
[ "def", "file_path", "(", "self", ",", "value", ":", "Path", ")", "->", "Path", ":", "self", ".", "_file_path", "=", "value", "return", "self", ".", "_file_path" ]
[ 28, 4 ]
[ 39, 30 ]
python
da
['da', 'fr', 'en']
False
JSONConfigSource.process
(self)
Load config from JSON file. Returns: dict: config in file
Load config from JSON file.
def process(self) -> dict: """Load config from JSON file. Returns: dict: config in file """ content = self.file_path.read_text() if not content: return {} config = json.loads(content) return config
[ "def", "process", "(", "self", ")", "->", "dict", ":", "content", "=", "self", ".", "file_path", ".", "read_text", "(", ")", "if", "not", "content", ":", "return", "{", "}", "config", "=", "json", ".", "loads", "(", "content", ")", "return", "config"...
[ 45, 4 ]
[ 56, 21 ]
python
en
['en', 'en', 'en']
True
JSONConfigSource.save
(self, content: dict)
Save current config. Args: content (dict): content to write to file. Returns: Path: path to config file.
Save current config.
def save(self, content: dict) -> Path: """Save current config. Args: content (dict): content to write to file. Returns: Path: path to config file. """ config = json.dumps(content, indent=4, separators=(",", ": ")) with AtomicSaver((str(self.file...
[ "def", "save", "(", "self", ",", "content", ":", "dict", ")", "->", "Path", ":", "config", "=", "json", ".", "dumps", "(", "content", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",", "\": \"", ")", ")", "with", "AtomicSaver", "("...
[ 64, 4 ]
[ 77, 29 ]
python
en
['en', 'en', 'en']
True
HTTPResponse.get_redirect_location
(self)
Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code.
Should we redirect and where to?
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ ...
[ "def", "get_redirect_location", "(", "self", ")", ":", "if", "self", ".", "status", "in", "self", ".", "REDIRECT_STATUSES", ":", "return", "self", ".", "headers", ".", "get", "(", "\"location\"", ")", "return", "False" ]
[ 260, 4 ]
[ 271, 20 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.drain_conn
(self)
Read and discard any remaining HTTP response data in the response connection. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
Read and discard any remaining HTTP response data in the response connection.
def drain_conn(self): """ Read and discard any remaining HTTP response data in the response connection. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool. """ try: self.read() except (HTTPError, SocketError,...
[ "def", "drain_conn", "(", "self", ")", ":", "try", ":", "self", ".", "read", "(", ")", "except", "(", "HTTPError", ",", "SocketError", ",", "BaseSSLError", ",", "HTTPException", ")", ":", "pass" ]
[ 280, 4 ]
[ 289, 16 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.tell
(self)
Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed).
Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed).
def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "_fp_bytes_read" ]
[ 307, 4 ]
[ 313, 34 ]
python
en
['en', 'error', 'th']
False
HTTPResponse._init_length
(self, request_method)
Set initial length value for Response content if available.
Set initial length value for Response content if available.
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get("content-length") if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can'...
[ "def", "_init_length", "(", "self", ",", "request_method", ")", ":", "length", "=", "self", ".", "headers", ".", "get", "(", "\"content-length\"", ")", "if", "length", "is", "not", "None", ":", "if", "self", ".", "chunked", ":", "# This Response will fail wi...
[ 315, 4 ]
[ 365, 21 ]
python
en
['en', 'error', 'th']
False
HTTPResponse._init_decoder
(self)
Set-up the _decoder attribute if necessary.
Set-up the _decoder attribute if necessary.
def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get("content-encoding", "").lower() if self._decoder is None: ...
[ "def", "_init_decoder", "(", "self", ")", ":", "# Note: content-encoding value should be case-insensitive, per RFC 7230", "# Section 3.2", "content_encoding", "=", "self", ".", "headers", ".", "get", "(", "\"content-encoding\"", ",", "\"\"", ")", ".", "lower", "(", ")",...
[ 367, 4 ]
[ 384, 66 ]
python
en
['en', 'error', 'th']
False
HTTPResponse._decode
(self, data, decode_content, flush_decoder)
Decode the data passed in and potentially flush the decoder.
Decode the data passed in and potentially flush the decoder.
def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ if not decode_content: return data try: if self._decoder: data = self._decoder.decompress(data) except sel...
[ "def", "_decode", "(", "self", ",", "data", ",", "decode_content", ",", "flush_decoder", ")", ":", "if", "not", "decode_content", ":", "return", "data", "try", ":", "if", "self", ".", "_decoder", ":", "data", "=", "self", ".", "_decoder", ".", "decompres...
[ 390, 4 ]
[ 410, 19 ]
python
en
['en', 'error', 'th']
False
HTTPResponse._flush_decoder
(self)
Flushes the decoder. Should only be called if the decoder is actually being used.
Flushes the decoder. Should only be called if the decoder is actually being used.
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b"") return buf + self._decoder.flush() return b""
[ "def", "_flush_decoder", "(", "self", ")", ":", "if", "self", ".", "_decoder", ":", "buf", "=", "self", ".", "_decoder", ".", "decompress", "(", "b\"\"", ")", "return", "buf", "+", "self", ".", "_decoder", ".", "flush", "(", ")", "return", "b\"\"" ]
[ 412, 4 ]
[ 421, 18 ]
python
en
['en', 'error', 'th']
False
HTTPResponse._error_catcher
(self)
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool.
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api.
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: ...
[ "def", "_error_catcher", "(", "self", ")", ":", "clean_exit", "=", "False", "try", ":", "try", ":", "yield", "except", "SocketTimeout", ":", "# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but", "# there is yet no clean way to get at it from this context.",...
[ 424, 4 ]
[ 478, 35 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.read
(self, amt=None, decode_content=None, cache_content=False)
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full ...
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``.
def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped ...
[ "def", "read", "(", "self", ",", "amt", "=", "None", ",", "decode_content", "=", "None", ",", "cache_content", "=", "False", ")", ":", "self", ".", "_init_decoder", "(", ")", "if", "decode_content", "is", "None", ":", "decode_content", "=", "self", ".", ...
[ 480, 4 ]
[ 552, 19 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.stream
(self, amt=2 ** 16, decode_content=None)
A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may r...
A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed.
def stream(self, amt=2 ** 16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator w...
[ "def", "stream", "(", "self", ",", "amt", "=", "2", "**", "16", ",", "decode_content", "=", "None", ")", ":", "if", "self", ".", "chunked", "and", "self", ".", "supports_chunked_reads", "(", ")", ":", "for", "line", "in", "self", ".", "read_chunked", ...
[ 554, 4 ]
[ 578, 30 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.from_httplib
(ResponseCls, r, **response_kw)
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object.
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. ...
[ "def", "from_httplib", "(", "ResponseCls", ",", "r", ",", "*", "*", "response_kw", ")", ":", "headers", "=", "r", ".", "msg", "if", "not", "isinstance", "(", "headers", ",", "HTTPHeaderDict", ")", ":", "if", "PY3", ":", "headers", "=", "HTTPHeaderDict", ...
[ 581, 4 ]
[ 610, 19 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.supports_chunked_reads
(self)
Checks if the underlying file-like object looks like a httplib.HTTPResponse object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked().
Checks if the underlying file-like object looks like a httplib.HTTPResponse object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked().
def supports_chunked_reads(self): """ Checks if the underlying file-like object looks like a httplib.HTTPResponse object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked(). """ return hasatt...
[ "def", "supports_chunked_reads", "(", "self", ")", ":", "return", "hasattr", "(", "self", ".", "_fp", ",", "\"fp\"", ")" ]
[ 679, 4 ]
[ 686, 38 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.read_chunked
(self, amt=None, decode_content=None)
Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :p...
Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``.
def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to c...
[ "def", "read_chunked", "(", "self", ",", "amt", "=", "None", ",", "decode_content", "=", "None", ")", ":", "self", ".", "_init_decoder", "(", ")", "# FIXME: Rewrite this method and make it a class with a better structured logic.", "if", "not", "self", ".", "chunked", ...
[ 724, 4 ]
[ 792, 47 ]
python
en
['en', 'error', 'th']
False
HTTPResponse.geturl
(self)
Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location.
Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location.
def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self....
[ "def", "geturl", "(", "self", ")", ":", "if", "self", ".", "retries", "is", "not", "None", "and", "len", "(", "self", ".", "retries", ".", "history", ")", ":", "return", "self", ".", "retries", ".", "history", "[", "-", "1", "]", ".", "redirect_loc...
[ 794, 4 ]
[ 803, 36 ]
python
en
['en', 'error', 'th']
False
DatabaseWrapper.check_constraints
(self, table_names=None)
To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred.
To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred.
def check_constraints(self, table_names=None): """ To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they are returned to deferred. """ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') self.cursor().execute('SET CONSTRAINTS...
[ "def", "check_constraints", "(", "self", ",", "table_names", "=", "None", ")", ":", "self", ".", "cursor", "(", ")", ".", "execute", "(", "'SET CONSTRAINTS ALL IMMEDIATE'", ")", "self", ".", "cursor", "(", ")", ".", "execute", "(", "'SET CONSTRAINTS ALL DEFERR...
[ 184, 4 ]
[ 190, 61 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_issue_6755
(self)
Regression test for #6755
Regression test for #6755
def test_issue_6755(self): """ Regression test for #6755 """ r = Restaurant(serves_pizza=False, serves_hot_dogs=False) r.save() self.assertEqual(r.id, r.place_ptr_id) orig_id = r.id r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=Fa...
[ "def", "test_issue_6755", "(", "self", ")", ":", "r", "=", "Restaurant", "(", "serves_pizza", "=", "False", ",", "serves_hot_dogs", "=", "False", ")", "r", ".", "save", "(", ")", "self", ".", "assertEqual", "(", "r", ".", "id", ",", "r", ".", "place_...
[ 180, 4 ]
[ 191, 46 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_issue_11764
(self)
Regression test for #11764
Regression test for #11764
def test_issue_11764(self): """ Regression test for #11764 """ wholesalers = list(Wholesaler.objects.all().select_related()) self.assertEqual(wholesalers, [])
[ "def", "test_issue_11764", "(", "self", ")", ":", "wholesalers", "=", "list", "(", "Wholesaler", ".", "objects", ".", "all", "(", ")", ".", "select_related", "(", ")", ")", "self", ".", "assertEqual", "(", "wholesalers", ",", "[", "]", ")" ]
[ 202, 4 ]
[ 207, 41 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_issue_7853
(self)
Regression test for #7853 If the parent class has a self-referential link, make sure that any updates to that link via the child update the right table.
Regression test for #7853 If the parent class has a self-referential link, make sure that any updates to that link via the child update the right table.
def test_issue_7853(self): """ Regression test for #7853 If the parent class has a self-referential link, make sure that any updates to that link via the child update the right table. """ obj = SelfRefChild.objects.create(child_data=37, parent_data=42) obj.delete(...
[ "def", "test_issue_7853", "(", "self", ")", ":", "obj", "=", "SelfRefChild", ".", "objects", ".", "create", "(", "child_data", "=", "37", ",", "parent_data", "=", "42", ")", "obj", ".", "delete", "(", ")" ]
[ 209, 4 ]
[ 216, 20 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_get_next_previous_by_date
(self)
Regression tests for #8076 get_(next/previous)_by_date should work
Regression tests for #8076 get_(next/previous)_by_date should work
def test_get_next_previous_by_date(self): """ Regression tests for #8076 get_(next/previous)_by_date should work """ c1 = ArticleWithAuthor( headline='ArticleWithAuthor 1', author="Person 1", pub_date=datetime.datetime(2005, 8, 1, 3, 0)) ...
[ "def", "test_get_next_previous_by_date", "(", "self", ")", ":", "c1", "=", "ArticleWithAuthor", "(", "headline", "=", "'ArticleWithAuthor 1'", ",", "author", "=", "\"Person 1\"", ",", "pub_date", "=", "datetime", ".", "datetime", "(", "2005", ",", "8", ",", "1...
[ 218, 4 ]
[ 248, 40 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_inherited_fields
(self)
Regression test for #8825 and #9390 Make sure all inherited fields (esp. m2m fields, in this case) appear on the child class.
Regression test for #8825 and #9390 Make sure all inherited fields (esp. m2m fields, in this case) appear on the child class.
def test_inherited_fields(self): """ Regression test for #8825 and #9390 Make sure all inherited fields (esp. m2m fields, in this case) appear on the child class. """ m2mchildren = list(M2MChild.objects.filter(articles__isnull=False)) self.assertEqual(m2mchildren,...
[ "def", "test_inherited_fields", "(", "self", ")", ":", "m2mchildren", "=", "list", "(", "M2MChild", ".", "objects", ".", "filter", "(", "articles__isnull", "=", "False", ")", ")", "self", ".", "assertEqual", "(", "m2mchildren", ",", "[", "]", ")", "# Order...
[ 250, 4 ]
[ 268, 64 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_queryset_update_on_parent_model
(self)
Regression test for #10362 It is possible to call update() and only change a field in an ancestor model.
Regression test for #10362 It is possible to call update() and only change a field in an ancestor model.
def test_queryset_update_on_parent_model(self): """ Regression test for #10362 It is possible to call update() and only change a field in an ancestor model. """ article = ArticleWithAuthor.objects.create( author="fred", headline="Hey there!", ...
[ "def", "test_queryset_update_on_parent_model", "(", "self", ")", ":", "article", "=", "ArticleWithAuthor", ".", "objects", ".", "create", "(", "author", "=", "\"fred\"", ",", "headline", "=", "\"Hey there!\"", ",", "pub_date", "=", "datetime", ".", "datetime", "...
[ 270, 4 ]
[ 295, 48 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_use_explicit_o2o_to_parent_as_pk
(self)
Regression tests for #10406 If there's a one-to-one link between a child model and the parent and no explicit pk declared, we can use the one-to-one link as the pk on the child.
Regression tests for #10406 If there's a one-to-one link between a child model and the parent and no explicit pk declared, we can use the one-to-one link as the pk on the child.
def test_use_explicit_o2o_to_parent_as_pk(self): """ Regression tests for #10406 If there's a one-to-one link between a child model and the parent and no explicit pk declared, we can use the one-to-one link as the pk on the child. """ self.assertEqual(ParkingLot2....
[ "def", "test_use_explicit_o2o_to_parent_as_pk", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "ParkingLot2", ".", "_meta", ".", "pk", ".", "name", ",", "\"parent\"", ")", "# However, the connector from child to parent need not be the pk on", "# the child at all.",...
[ 297, 4 ]
[ 312, 21 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_all_fields_from_abstract_base_class
(self)
Regression tests for #7588
Regression tests for #7588
def test_all_fields_from_abstract_base_class(self): """ Regression tests for #7588 """ # All fields from an ABC, including those inherited non-abstractly # should be available on child classes (#7588). Creating this instance # should work without error. QualityCon...
[ "def", "test_all_fields_from_abstract_base_class", "(", "self", ")", ":", "# All fields from an ABC, including those inherited non-abstractly", "# should be available on child classes (#7588). Creating this instance", "# should work without error.", "QualityControl", ".", "objects", ".", "...
[ 327, 4 ]
[ 338, 30 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_abstract_verbose_name_plural_inheritance
(self)
verbose_name_plural correctly inherited from ABC if inheritance chain includes an abstract model.
verbose_name_plural correctly inherited from ABC if inheritance chain includes an abstract model.
def test_abstract_verbose_name_plural_inheritance(self): """ verbose_name_plural correctly inherited from ABC if inheritance chain includes an abstract model. """ # Regression test for #11369: verbose_name_plural should be inherited # from an ABC even when there are one o...
[ "def", "test_abstract_verbose_name_plural_inheritance", "(", "self", ")", ":", "# Regression test for #11369: verbose_name_plural should be inherited", "# from an ABC even when there are one or more intermediate", "# abstract models in the inheritance chain, for consistency with", "# verbose_name....
[ 377, 4 ]
[ 389, 9 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_concrete_abstract_concrete_pk
(self)
Primary key set correctly with concrete->abstract->concrete inheritance.
Primary key set correctly with concrete->abstract->concrete inheritance.
def test_concrete_abstract_concrete_pk(self): """ Primary key set correctly with concrete->abstract->concrete inheritance. """ # Regression test for #13987: Primary key is incorrectly determined # when more than one model has a concrete->abstract->concrete # inheritance h...
[ "def", "test_concrete_abstract_concrete_pk", "(", "self", ")", ":", "# Regression test for #13987: Primary key is incorrectly determined", "# when more than one model has a concrete->abstract->concrete", "# inheritance hierarchy.", "self", ".", "assertEqual", "(", "len", "(", "[", "f...
[ 406, 4 ]
[ 422, 64 ]
python
en
['en', 'error', 'th']
False
ModelInheritanceTest.test_inherited_unique_field_with_form
(self)
Test that a model which has different primary key for the parent model passes unique field checking correctly. Refs #17615.
Test that a model which has different primary key for the parent model passes unique field checking correctly. Refs #17615.
def test_inherited_unique_field_with_form(self): """ Test that a model which has different primary key for the parent model passes unique field checking correctly. Refs #17615. """ class ProfileForm(forms.ModelForm): class Meta: model = Profile ...
[ "def", "test_inherited_unique_field_with_form", "(", "self", ")", ":", "class", "ProfileForm", "(", "forms", ".", "ModelForm", ")", ":", "class", "Meta", ":", "model", "=", "Profile", "fields", "=", "'__all__'", "User", ".", "objects", ".", "create", "(", "u...
[ 424, 4 ]
[ 438, 40 ]
python
en
['en', 'error', 'th']
False
VarFactory.getNext
(type)
gets the next letter name based on counter name Arguments: type -- name of counter we want the next value for Returns: string
gets the next letter name based on counter name
def getNext(type): """gets the next letter name based on counter name Arguments: type -- name of counter we want the next value for Returns: string """ i = VarFactory.getVersion(type) return VarFactory.getSmallName(i)
[ "def", "getNext", "(", "type", ")", ":", "i", "=", "VarFactory", ".", "getVersion", "(", "type", ")", "return", "VarFactory", ".", "getSmallName", "(", "i", ")" ]
[ 23, 4 ]
[ 34, 41 ]
python
en
['en', 'en', 'en']
True
VarFactory.getVersion
(type)
gets the next number in the counter for this type Arguments: type -- name of counter we are incrementing Resturns: int
gets the next number in the counter for this type
def getVersion(type): """gets the next number in the counter for this type Arguments: type -- name of counter we are incrementing Resturns: int """ if not type in VarFactory.types: VarFactory.types[type] = 0 return 0 VarFactory....
[ "def", "getVersion", "(", "type", ")", ":", "if", "not", "type", "in", "VarFactory", ".", "types", ":", "VarFactory", ".", "types", "[", "type", "]", "=", "0", "return", "0", "VarFactory", ".", "types", "[", "type", "]", "+=", "1", "return", "VarFact...
[ 37, 4 ]
[ 53, 37 ]
python
en
['en', 'en', 'en']
True
VarFactory.getSmallName
(index)
gets a letter index based on the numeric index Arguments: index -- the number you are looking for Returns: string
gets a letter index based on the numeric index
def getSmallName(index): """gets a letter index based on the numeric index Arguments: index -- the number you are looking for Returns: string """ # total number of combinations for this index size combinations = 0 letters = 0 while (comb...
[ "def", "getSmallName", "(", "index", ")", ":", "# total number of combinations for this index size", "combinations", "=", "0", "letters", "=", "0", "while", "(", "combinations", "+", "(", "(", "(", "letters", "-", "1", ")", "*", "26", ")", "-", "1", ")", "...
[ 56, 4 ]
[ 88, 20 ]
python
en
['en', 'en', 'en']
True
config_file
(kind="local")
Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user"
Get the filename of the distutils, local, global, or per-user config
def config_file(kind="local"): """Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user" """ if kind == 'local': return 'setup.cfg' if kind == 'global': return os.path.join( os.path.dirname(distutils.__file...
[ "def", "config_file", "(", "kind", "=", "\"local\"", ")", ":", "if", "kind", "==", "'local'", ":", "return", "'setup.cfg'", "if", "kind", "==", "'global'", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "d...
[ 13, 0 ]
[ 29, 5 ]
python
en
['en', 'en', 'en']
True
edit_config
(filename, settings, dry_run=False)
Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or deleted in that section. A setting of ``None`` means to ...
Edit a configuration file to include `settings`
def edit_config(filename, settings, dry_run=False): """Edit a configuration file to include `settings` `settings` is a dictionary of dictionaries or ``None`` values, keyed by command/section name. A ``None`` value means to delete the entire section, while a dictionary lists settings to be changed or d...
[ "def", "edit_config", "(", "filename", ",", "settings", ",", "dry_run", "=", "False", ")", ":", "log", ".", "debug", "(", "\"Reading configuration from %s\"", ",", "filename", ")", "opts", "=", "configparser", ".", "RawConfigParser", "(", ")", "opts", ".", "...
[ 32, 0 ]
[ 72, 25 ]
python
en
['en', 'en', 'en']
True
BackendSpecificChecksTests.test_check_field
(self)
Test if backend specific checks are performed.
Test if backend specific checks are performed.
def test_check_field(self): """ Test if backend specific checks are performed. """ error = Error('an error', hint=None) def mock(self, field, **kwargs): return [error] class Model(models.Model): field = models.IntegerField() field = Model._meta.get_fie...
[ "def", "test_check_field", "(", "self", ")", ":", "error", "=", "Error", "(", "'an error'", ",", "hint", "=", "None", ")", "def", "mock", "(", "self", ",", "field", ",", "*", "*", "kwargs", ")", ":", "return", "[", "error", "]", "class", "Model", "...
[ 13, 4 ]
[ 36, 41 ]
python
en
['en', 'en', 'en']
True
BackendSpecificChecksTests.test_validate_field
(self)
Errors raised by deprecated `validate_field` method should be collected.
Errors raised by deprecated `validate_field` method should be collected.
def test_validate_field(self): """ Errors raised by deprecated `validate_field` method should be collected. """ def mock(self, errors, opts, field): errors.add(opts, "An error!") class Model(models.Model): field = models.IntegerField() field = Model._me...
[ "def", "test_validate_field", "(", "self", ")", ":", "def", "mock", "(", "self", ",", "errors", ",", "opts", ",", "field", ")", ":", "errors", ".", "add", "(", "opts", ",", "\"An error!\"", ")", "class", "Model", "(", "models", ".", "Model", ")", ":"...
[ 38, 4 ]
[ 67, 42 ]
python
en
['en', 'af', 'en']
True
CommonMiddleware.process_request
(self, request)
Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW
Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW
def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get('HTTP_USER_AGENT') if user_agent is not None: ...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# Check for denied User-Agents", "user_agent", "=", "request", ".", "META", ".", "get", "(", "'HTTP_USER_AGENT'", ")", "if", "user_agent", "is", "not", "None", ":", "for", "user_agent_regex", "in"...
[ 33, 4 ]
[ 60, 61 ]
python
en
['en', 'error', 'th']
False
CommonMiddleware.should_redirect_with_slash
(self, request)
Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one.
Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one.
def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not request.path_info.endswith('/'): urlconf = getattr(re...
[ "def", "should_redirect_with_slash", "(", "self", ",", "request", ")", ":", "if", "settings", ".", "APPEND_SLASH", "and", "not", "request", ".", "path_info", ".", "endswith", "(", "'/'", ")", ":", "urlconf", "=", "getattr", "(", "request", ",", "'urlconf'", ...
[ 62, 4 ]
[ 73, 20 ]
python
en
['en', 'error', 'th']
False
CommonMiddleware.get_full_path_with_slash
(self, request)
Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is POST, PUT, or PATCH.
Return the full path of the request with a trailing slash appended.
def get_full_path_with_slash(self, request): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) ...
[ "def", "get_full_path_with_slash", "(", "self", ",", "request", ")", ":", "new_path", "=", "request", ".", "get_full_path", "(", "force_append_slash", "=", "True", ")", "# Prevent construction of scheme relative urls.", "new_path", "=", "escape_leading_slashes", "(", "n...
[ 75, 4 ]
[ 96, 23 ]
python
en
['en', 'error', 'th']
False
CommonMiddleware.process_response
(self, request, response)
When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True.
When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True.
def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a pa...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "# If the given URL is \"Not Found\", then check if we should redirect to", "# a path with a slash appended.", "if", "response", ".", "status_code", "==", "404", ":", "if", "self", ".", "sh...
[ 98, 4 ]
[ 114, 23 ]
python
en
['en', 'error', 'th']
False
BrokenLinkEmailsMiddleware.process_response
(self, request, response)
Send broken link emails for relevant 404 NOT FOUND responses.
Send broken link emails for relevant 404 NOT FOUND responses.
def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get('HTTP_REFERE...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "response", ".", "status_code", "==", "404", "and", "not", "settings", ".", "DEBUG", ":", "domain", "=", "request", ".", "get_host", "(", ")", "path", "=", "request"...
[ 119, 4 ]
[ 138, 23 ]
python
en
['en', 'da', 'en']
True
BrokenLinkEmailsMiddleware.is_internal_request
(self, domain, referer)
Return True if the referring URL is the same domain as the current request.
Return True if the referring URL is the same domain as the current request.
def is_internal_request(self, domain, referer): """ Return True if the referring URL is the same domain as the current request. """ # Different subdomains are treated as different domains. return bool(re.match("^https?://%s/" % re.escape(domain), referer))
[ "def", "is_internal_request", "(", "self", ",", "domain", ",", "referer", ")", ":", "# Different subdomains are treated as different domains.", "return", "bool", "(", "re", ".", "match", "(", "\"^https?://%s/\"", "%", "re", ".", "escape", "(", "domain", ")", ",", ...
[ 140, 4 ]
[ 146, 75 ]
python
en
['en', 'error', 'th']
False
BrokenLinkEmailsMiddleware.is_ignorable_request
(self, request, uri, domain, referer)
Return True if the given request *shouldn't* notify the site managers according to project settings or in situations outlined by the inline comments.
Return True if the given request *shouldn't* notify the site managers according to project settings or in situations outlined by the inline comments.
def is_ignorable_request(self, request, uri, domain, referer): """ Return True if the given request *shouldn't* notify the site managers according to project settings or in situations outlined by the inline comments. """ # The referer is empty. if not referer: ...
[ "def", "is_ignorable_request", "(", "self", ",", "request", ",", "uri", ",", "domain", ",", "referer", ")", ":", "# The referer is empty.", "if", "not", "referer", ":", "return", "True", "# APPEND_SLASH is enabled and the referer is equal to the current URL", "# without a...
[ 148, 4 ]
[ 173, 82 ]
python
en
['en', 'error', 'th']
False
remote_user_auth_view
(request)
Dummy view for remote user tests
Dummy view for remote user tests
def remote_user_auth_view(request): "Dummy view for remote user tests" t = Template("Username is {{ user }}.") c = RequestContext(request, {}) return HttpResponse(t.render(c))
[ "def", "remote_user_auth_view", "(", "request", ")", ":", "t", "=", "Template", "(", "\"Username is {{ user }}.\"", ")", "c", "=", "RequestContext", "(", "request", ",", "{", "}", ")", "return", "HttpResponse", "(", "t", ".", "render", "(", "c", ")", ")" ]
[ 21, 0 ]
[ 25, 36 ]
python
en
['en', 'en', 'en']
True
clear_duplicate_reactions
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
Zulip's data model for reactions has enforced via code, nontransactionally, that they can only react with one emoji_code for a given reaction_type. This fixes any that were stored in the database via a race; the next migration will add the appropriate database-level unique constraint.
Zulip's data model for reactions has enforced via code, nontransactionally, that they can only react with one emoji_code for a given reaction_type. This fixes any that were stored in the database via a race; the next migration will add the appropriate database-level unique constraint.
def clear_duplicate_reactions(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """Zulip's data model for reactions has enforced via code, nontransactionally, that they can only react with one emoji_code for a given reaction_type. This fixes any that were stored in the database via a race;...
[ "def", "clear_duplicate_reactions", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "Reaction", "=", "apps", ".", "get_model", "(", "\"zerver\"", ",", "\"Reaction\"", ")", "duplicate_reactions", "=", "(", ...
[ 6, 0 ]
[ 25, 29 ]
python
en
['en', 'en', 'en']
True
new_date
(d)
Generate a safe date from a datetime.date object.
Generate a safe date from a datetime.date object.
def new_date(d): "Generate a safe date from a datetime.date object." return date(d.year, d.month, d.day)
[ "def", "new_date", "(", "d", ")", ":", "return", "date", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")" ]
[ 39, 0 ]
[ 41, 39 ]
python
en
['en', 'en', 'en']
True
new_datetime
(d)
Generate a safe datetime from a datetime.date or datetime.datetime object.
Generate a safe datetime from a datetime.date or datetime.datetime object.
def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw)
[ "def", "new_datetime", "(", "d", ")", ":", "kw", "=", "[", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", "]", "if", "isinstance", "(", "d", ",", "real_datetime", ")", ":", "kw", ".", "extend", "(", "[", "d", ".", "hour", ","...
[ 44, 0 ]
[ 51, 24 ]
python
en
['en', 'error', 'th']
False
_xml_escape
(data)
Escape &, <, >, ", ', etc. in a string of data.
Escape &, <, >, ", ', etc. in a string of data.
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split()) for from_, to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) re...
[ "def", "_xml_escape", "(", "data", ")", ":", "# ampersand must be replaced first", "from_symbols", "=", "'&><\"\\''", "to_symbols", "=", "(", "'&'", "+", "s", "+", "';'", "for", "s", "in", "\"amp gt lt quot apos\"", ".", "split", "(", ")", ")", "for", "from_",...
[ 269, 0 ]
[ 277, 15 ]
python
en
['en', 'en', 'en']
True
col
(loc, strg)
Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more information on parsing strings contai...
Returns current column within a string, counting newlines as line separators. The first column is number 1.
def col (loc, strg): """Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more informati...
[ "def", "col", "(", "loc", ",", "strg", ")", ":", "s", "=", "strg", "return", "1", "if", "0", "<", "loc", "<", "len", "(", "s", ")", "and", "s", "[", "loc", "-", "1", "]", "==", "'\\n'", "else", "loc", "-", "s", ".", "rfind", "(", "\"\\n\"",...
[ 1210, 0 ]
[ 1222, 86 ]
python
en
['en', 'en', 'en']
True
lineno
(loc, strg)
Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note - the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more information on parsing strings c...
Returns current line number within a string, counting newlines as line separators. The first line is number 1.
def lineno(loc, strg): """Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note - the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more in...
[ "def", "lineno", "(", "loc", ",", "strg", ")", ":", "return", "strg", ".", "count", "(", "\"\\n\"", ",", "0", ",", "loc", ")", "+", "1" ]
[ 1224, 0 ]
[ 1234, 39 ]
python
en
['en', 'en', 'en']
True
line
(loc, strg)
Returns the line of text containing loc within a string, counting newlines as line separators.
Returns the line of text containing loc within a string, counting newlines as line separators.
def line(loc, strg): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[lastCR + 1:]
[ "def", "line", "(", "loc", ",", "strg", ")", ":", "lastCR", "=", "strg", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "loc", ")", "nextCR", "=", "strg", ".", "find", "(", "\"\\n\"", ",", "loc", ")", "if", "nextCR", ">=", "0", ":", "return", "st...
[ 1236, 0 ]
[ 1244, 32 ]
python
en
['en', 'en', 'en']
True
nullDebugAction
(*args)
Do-nothing' debug action, to suppress debugging output during parsing.
Do-nothing' debug action, to suppress debugging output during parsing.
def nullDebugAction(*args): """'Do-nothing' debug action, to suppress debugging output during parsing.""" pass
[ "def", "nullDebugAction", "(", "*", "args", ")", ":", "pass" ]
[ 1255, 0 ]
[ 1257, 8 ]
python
en
['en', 'jv', 'en']
True
ParseBaseException._from_exception
(cls, pe)
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses
def _from_exception(cls, pe): """ internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses """ return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
[ "def", "_from_exception", "(", "cls", ",", "pe", ")", ":", "return", "cls", "(", "pe", ".", "pstr", ",", "pe", ".", "loc", ",", "pe", ".", "msg", ",", "pe", ".", "parserElement", ")" ]
[ 315, 4 ]
[ 320, 61 ]
python
en
['en', 'error', 'th']
False
ParseBaseException.__getattr__
(self, aname)
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text
def __getattr__(self, aname): """supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ if aname == "lineno": ...
[ "def", "__getattr__", "(", "self", ",", "aname", ")", ":", "if", "aname", "==", "\"lineno\"", ":", "return", "lineno", "(", "self", ".", "loc", ",", "self", ".", "pstr", ")", "elif", "aname", "in", "(", "\"col\"", ",", "\"column\"", ")", ":", "return...
[ 322, 4 ]
[ 335, 39 ]
python
en
['en', 'en', 'en']
True
ParseBaseException.markInputline
(self, markerString=">!<")
Extracts the exception line from the input string, and marks the location of the exception with a special symbol.
Extracts the exception line from the input string, and marks the location of the exception with a special symbol.
def markInputline(self, markerString=">!<"): """Extracts the exception line from the input string, and marks the location of the exception with a special symbol. """ line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join((lin...
[ "def", "markInputline", "(", "self", ",", "markerString", "=", "\">!<\"", ")", ":", "line_str", "=", "self", ".", "line", "line_column", "=", "self", ".", "column", "-", "1", "if", "markerString", ":", "line_str", "=", "\"\"", ".", "join", "(", "(", "l...
[ 349, 4 ]
[ 358, 31 ]
python
en
['en', 'en', 'en']
True
ParseException.explain
(exc, depth=16)
Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised. Parameters: - exc - exception raised during parsing (need not be a ParseException, in support of Python exceptions that ...
Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised.
def explain(exc, depth=16): """ Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised. Parameters: - exc - exception raised during parsing (need not be a ParseException, in suppor...
[ "def", "explain", "(", "exc", ",", "depth", "=", "16", ")", ":", "import", "inspect", "if", "depth", "is", "None", ":", "depth", "=", "sys", ".", "getrecursionlimit", "(", ")", "ret", "=", "[", "]", "if", "isinstance", "(", "exc", ",", "ParseBaseExce...
[ 386, 4 ]
[ 452, 29 ]
python
en
['en', 'error', 'th']
False
ParseResults.haskeys
(self)
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
def haskeys(self): """Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.""" return bool(self.__tokdict)
[ "def", "haskeys", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__tokdict", ")" ]
[ 695, 4 ]
[ 698, 35 ]
python
en
['en', 'en', 'en']
True
ParseResults.pop
(self, *args, **kwargs)
Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed tokens. If passed a non-integer argum...
Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed tokens. If passed a non-integer argum...
def pop(self, *args, **kwargs): """ Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed to...
[ "def", "pop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", ":", "args", "=", "[", "-", "1", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'default'", ":",...
[ 700, 4 ]
[ 753, 31 ]
python
en
['en', 'error', 'th']
False
ParseResults.get
(self, key, defaultValue=None)
Returns named result matching the given key, or if there is no such name, then returns the given ``defaultValue`` or ``None`` if no ``defaultValue`` is specified. Similar to ``dict.get()``. Example:: integer = Word(nums) date_str = integer("year") + '/...
Returns named result matching the given key, or if there is no such name, then returns the given ``defaultValue`` or ``None`` if no ``defaultValue`` is specified.
def get(self, key, defaultValue=None): """ Returns named result matching the given key, or if there is no such name, then returns the given ``defaultValue`` or ``None`` if no ``defaultValue`` is specified. Similar to ``dict.get()``. Example:: integer = Word...
[ "def", "get", "(", "self", ",", "key", ",", "defaultValue", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "else", ":", "return", "defaultValue" ]
[ 755, 4 ]
[ 776, 31 ]
python
en
['en', 'error', 'th']
False
ParseResults.insert
(self, index, insStr)
Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed res...
Inserts new element at location index in the list of parsed tokens.
def insert(self, index, insStr): """ Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the p...
[ "def", "insert", "(", "self", ",", "index", ",", "insStr", ")", ":", "self", ".", "__toklist", ".", "insert", "(", "index", ",", "insStr", ")", "# fixup indices in token dictionary", "for", "name", ",", "occurrences", "in", "self", ".", "__tokdict", ".", "...
[ 778, 4 ]
[ 797, 94 ]
python
en
['en', 'error', 'th']
False
ParseResults.append
(self, item)
Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): ...
Add single element to end of ParseResults list of elements.
def append(self, item): """ Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end ...
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "__toklist", ".", "append", "(", "item", ")" ]
[ 799, 4 ]
[ 812, 35 ]
python
en
['en', 'error', 'th']
False
ParseResults.extend
(self, itemseq)
Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([...
Add sequence of elements to end of ParseResults list of elements.
def extend(self, itemseq): """ Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): ...
[ "def", "extend", "(", "self", ",", "itemseq", ")", ":", "if", "isinstance", "(", "itemseq", ",", "ParseResults", ")", ":", "self", ".", "__iadd__", "(", "itemseq", ")", "else", ":", "self", ".", "__toklist", ".", "extend", "(", "itemseq", ")" ]
[ 814, 4 ]
[ 831, 42 ]
python
en
['en', 'error', 'th']
False
ParseResults.clear
(self)
Clear all elements and results names.
Clear all elements and results names.
def clear(self): """ Clear all elements and results names. """ del self.__toklist[:] self.__tokdict.clear()
[ "def", "clear", "(", "self", ")", ":", "del", "self", ".", "__toklist", "[", ":", "]", "self", ".", "__tokdict", ".", "clear", "(", ")" ]
[ 833, 4 ]
[ 838, 30 ]
python
en
['en', 'error', 'th']
False
ParseResults.asList
(self)
Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseRes...
Returns the parse results as a nested list of matching tokens, all converted to strings.
def asList(self): """ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is ...
[ "def", "asList", "(", "self", ")", ":", "return", "[", "res", ".", "asList", "(", ")", "if", "isinstance", "(", "res", ",", "ParseResults", ")", "else", "res", "for", "res", "in", "self", ".", "__toklist", "]" ]
[ 892, 4 ]
[ 907, 97 ]
python
en
['en', 'error', 'th']
False
ParseResults.asDict
(self)
Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class ...
Returns the named parse results as a nested dictionary.
def asDict(self): """ Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result...
[ "def", "asDict", "(", "self", ")", ":", "if", "PY_3", ":", "item_fn", "=", "self", ".", "items", "else", ":", "item_fn", "=", "self", ".", "iteritems", "def", "toItem", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ParseResults", ")", ...
[ 909, 4 ]
[ 943, 57 ]
python
en
['en', 'error', 'th']
False
ParseResults.copy
(self)
Returns a new copy of a :class:`ParseResults` object.
Returns a new copy of a :class:`ParseResults` object.
def copy(self): """ Returns a new copy of a :class:`ParseResults` object. """ ret = ParseResults(self.__toklist) ret.__tokdict = dict(self.__tokdict.items()) ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name ...
[ "def", "copy", "(", "self", ")", ":", "ret", "=", "ParseResults", "(", "self", ".", "__toklist", ")", "ret", ".", "__tokdict", "=", "dict", "(", "self", ".", "__tokdict", ".", "items", "(", ")", ")", "ret", ".", "__parent", "=", "self", ".", "__par...
[ 945, 4 ]
[ 954, 18 ]
python
en
['en', 'error', 'th']
False
ParseResults.asXML
(self, doctag=None, namedItemsOnly=False, indent="", formatted=True)
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True): """ (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. """ nl = "\n" out = [] namedItems = dict((v[1], k) for (k, vlist) in se...
[ "def", "asXML", "(", "self", ",", "doctag", "=", "None", ",", "namedItemsOnly", "=", "False", ",", "indent", "=", "\"\"", ",", "formatted", "=", "True", ")", ":", "nl", "=", "\"\\n\"", "out", "=", "[", "]", "namedItems", "=", "dict", "(", "(", "v",...
[ 956, 4 ]
[ 1015, 27 ]
python
en
['en', 'error', 'th']
False
ParseResults.getName
(self)
r""" Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, a...
r""" Returns the results name for this token expression. Useful when several different expressions might match at a particular location.
def getName(self): r""" Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = S...
[ "def", "getName", "(", "self", ")", ":", "if", "self", ".", "__name", ":", "return", "self", ".", "__name", "elif", "self", ".", "__parent", ":", "par", "=", "self", ".", "__parent", "(", ")", "if", "par", ":", "return", "par", ".", "__lookup", "("...
[ 1024, 4 ]
[ 1062, 23 ]
python
cy
['en', 'cy', 'hi']
False
ParseResults.dump
(self, indent='', full=True, include_list=True, _depth=0)
Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("...
Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data.
def dump(self, indent='', full=True, include_list=True, _depth=0): """ Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data. Example:: ...
[ "def", "dump", "(", "self", ",", "indent", "=", "''", ",", "full", "=", "True", ",", "include_list", "=", "True", ",", "_depth", "=", "0", ")", ":", "out", "=", "[", "]", "NL", "=", "'\\n'", "if", "include_list", ":", "out", ".", "append", "(", ...
[ 1064, 4 ]
[ 1127, 27 ]
python
en
['en', 'error', 'th']
False
ParseResults.pprint
(self, *args, **kwargs)
Pretty-printer for parsed results as a list, using the `pprint <https://docs.python.org/3/library/pprint.html>`_ module. Accepts additional positional or keyword args as defined for `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ . Example:: ...
Pretty-printer for parsed results as a list, using the `pprint <https://docs.python.org/3/library/pprint.html>`_ module. Accepts additional positional or keyword args as defined for `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
def pprint(self, *args, **kwargs): """ Pretty-printer for parsed results as a list, using the `pprint <https://docs.python.org/3/library/pprint.html>`_ module. Accepts additional positional or keyword args as defined for `pprint.pprint <https://docs.python.org/3/library/pprint.ht...
[ "def", "pprint", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pprint", ".", "pprint", "(", "self", ".", "asList", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 1129, 4 ]
[ 1154, 53 ]
python
en
['en', 'error', 'th']
False