desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns an ErrorDict for self.data'
| def _errors(self):
| if (self.__errors is None):
self.full_clean()
return self.__errors
|
'Returns True if the form has no errors. Otherwise, False. If errors are
being ignored, returns False.'
| def is_valid(self):
| return (self.is_bound and (not bool(self.errors)))
|
'Returns the field name with a prefix appended, if this Form has a
prefix set.
Subclasses may wish to override.'
| def add_prefix(self, field_name):
| return ((self.prefix and ('%s-%s' % (self.prefix, field_name))) or field_name)
|
'Helper function for outputting HTML. Used by as_table(), as_ul(), as_p().'
| def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
| top_errors = self.non_field_errors()
(output, hidden_fields) = ([], [])
for (name, field) in self.fields.items():
bf = BoundField(self, field, name)
bf_errors = ErrorList([escape(error) for error in bf.errors])
if bf.is_hidden:
if bf_errors:
top_errors.ext... |
'Returns this form rendered as HTML <tr>s -- excluding the <table></table>.'
| def as_table(self):
| return self._html_output(u'<tr><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False)
|
'Returns this form rendered as HTML <li>s -- excluding the <ul></ul>.'
| def as_ul(self):
| return self._html_output(u'<li>%(errors)s%(label)s %(field)s%(help_text)s</li>', u'<li>%s</li>', '</li>', u' %s', False)
|
'Returns this form rendered as HTML <p>s.'
| def as_p(self):
| return self._html_output(u'<p>%(label)s %(field)s%(help_text)s</p>', u'<p>%s</p>', '</p>', u' %s', True)
|
'Returns an ErrorList of errors that aren\'t associated with a particular
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
are none.'
| def non_field_errors(self):
| return self.errors.get(NON_FIELD_ERRORS, ErrorList())
|
'Cleans all of self.data and populates self.__errors and self.clean_data.'
| def full_clean(self):
| errors = ErrorDict()
if (not self.is_bound):
self.__errors = errors
return
self.clean_data = {}
for (name, field) in self.fields.items():
value = field.widget.value_from_datadict(self.data, self.add_prefix(name))
try:
value = field.clean(value)
sel... |
'Hook for doing any extra form-wide cleaning after Field.clean() been
called on every field. Any ValidationError raised by this method will
not be associated with a particular field; it will have a special-case
association with the field named \'__all__\'.'
| def clean(self):
| return self.clean_data
|
'Renders this field as an HTML widget.'
| def __unicode__(self):
| value = self.as_widget(self.field.widget)
if (not isinstance(value, basestring)):
value = value.__str__()
return value
|
'Returns an ErrorList for this field. Returns an empty ErrorList
if there are none.'
| def _errors(self):
| return self.form.errors.get(self.name, ErrorList())
|
'Returns a string of HTML for representing this as an <input type="text">.'
| def as_text(self, attrs=None):
| return self.as_widget(TextInput(), attrs)
|
'Returns a string of HTML for representing this as a <textarea>.'
| def as_textarea(self, attrs=None):
| return self.as_widget(Textarea(), attrs)
|
'Returns a string of HTML for representing this as an <input type="hidden">.'
| def as_hidden(self, attrs=None):
| return self.as_widget(self.field.hidden_widget(), attrs)
|
'Returns the data for this BoundField, or None if it wasn\'t given.'
| def _data(self):
| return self.field.widget.value_from_datadict(self.form.data, self.html_name)
|
'Wraps the given contents in a <label>, if the field has an ID attribute.
Does not HTML-escape the contents. If contents aren\'t given, uses the
field\'s HTML-escaped label.
If attrs are given, they\'re used as HTML attributes on the <label> tag.'
| def label_tag(self, contents=None, attrs=None):
| contents = (contents or escape(self.label))
widget = self.field.widget
id_ = (widget.attrs.get('id') or self.auto_id)
if id_:
attrs = ((attrs and flatatt(attrs)) or '')
contents = ('<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, contents))
return contents
|
'Returns True if this BoundField\'s widget is hidden.'
| def _is_hidden(self):
| return self.field.widget.is_hidden
|
'Calculates and returns the ID attribute for this BoundField, if the
associated Form has specified auto_id. Returns an empty string otherwise.'
| def _auto_id(self):
| auto_id = self.form.auto_id
if (auto_id and ('%s' in str(auto_id))):
return (str(auto_id) % self.html_name)
elif auto_id:
return self.html_name
return ''
|
'Returns a mutable copy of this object.'
| def copy(self):
| return self.__deepcopy__()
|
'Full HTTP message, including headers'
| def __str__(self):
| return (('\n'.join([('%s: %s' % (key, value)) for (key, value) in self.headers.items()]) + '\n\n') + self.content)
|
'Case-insensitive check for a header'
| def has_header(self, header):
| header = header.lower()
for key in self.headers.keys():
if (key.lower() == header):
return True
return False
|
'Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.'
| def _import_settings(self):
| try:
settings_module = os.environ[ENVIRONMENT_VARIABLE]
if (not settings_module):
raise KeyError
except KeyError:
raise EnvironmentError, ('Environment variable %s is undefined.' % ENVIRONMENT_VARIABLE)
self._target = Settings(settings_module)
|
'Called to manually configure the settings. The \'default_settings\'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).'
| def configure(self, default_settings=global_settings, **options):
| if (self._target != None):
raise EnvironmentError, 'Settings already configured.'
holder = UserSettingsHolder(default_settings)
for (name, value) in options.items():
setattr(holder, name, value)
self._target = holder
|
'Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).'
| def __init__(self, default_settings):
| self.default_settings = default_settings
|
'If the Test Case class has a \'fixtures\' member, clear the database and
install the named fixtures at the start of each test.'
| def install_fixtures(self):
| management.flush(verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
management.load_data(self.fixtures, verbosity=0)
|
'Wrapper around default run method so that user-defined Test Cases
automatically call install_fixtures without having to include a call to
super().'
| def run(self, result=None):
| self.install_fixtures()
super(TestCase, self).run(result)
|
'Utility method that can be used to store exceptions when they are
generated by a view.'
| def store_exc_info(self, *args, **kwargs):
| self.exc_info = sys.exc_info()
|
'The master request method. Composes the environment dictionary
and passes to the handler, returning the result of the handler.
Assumes defaults for the query environment, which can be overridden
using the arguments to the request.'
| def request(self, **request):
| environ = {'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': None, 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1'}
environ.update(self.defaults)
environ.update(request)
data = {}
on_template_render = curry(store_... |
'Request a response from the server using GET.'
| def get(self, path, data={}, **extra):
| r = {'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': path, 'QUERY_STRING': urlencode(data), 'REQUEST_METHOD': 'GET'}
r.update(extra)
return self.request(**r)
|
'Request a response from the server using POST.'
| def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
| if (content_type is MULTIPART_CONTENT):
post_data = encode_multipart(BOUNDARY, data)
else:
post_data = data
r = {'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': path, 'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO(post_data)}
r.update(extra)
return self... |
'A specialized sequence of GET and POST to log into a view that
is protected by a @login_required access decorator.
path should be the URL of the page that is login protected.
Returns the response from GETting the requested URL after
login is complete. Returns False if login process failed.'
| def login(self, path, username, password, **extra):
| response = self.get(path)
if (response.status_code != 302):
return False
(_, _, login_path, _, data, _) = urlparse(response['Location'])
next = data.split('=')[1]
response = self.get(login_path, **extra)
if (response.status_code != 200):
return False
form_data = {'username': ... |
'Create a new DocTest containing the given examples. The
DocTest\'s globals are initialized with a copy of `globs`.'
| def __init__(self, examples, globs, name, filename, lineno, docstring):
| assert (not isinstance(examples, basestring)), 'DocTest no longer accepts str; use DocTestParser instead'
self.examples = examples
self.docstring = docstring
self.globs = globs.copy()
self.name = name
self.filename = filename
self.lineno = lineno
|
'Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.'
| def parse(self, string, name='<string>'):
| string = string.expandtabs()
min_indent = self._min_indent(string)
if (min_indent > 0):
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
output = []
(charno, lineno) = (0, 0)
for m in self._EXAMPLE_RE.finditer(string):
output.append(string[charno:m.start()])
... |
'Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.'
| def get_doctest(self, string, globs, name, filename, lineno):
| return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
|
'Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it\'s most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called "line 1" then.
The optional argumen... | def get_examples(self, string, name='<string>'):
| return [x for x in self.parse(string, name) if isinstance(x, Example)]
|
'Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example\'s source code (with prompts and indentation stripped);
and `want` is the example\'s expected output (with indentation
stripped).
`name` is the string\'s name, and `lineno` is the line numbe... | def _parse_example(self, m, name, lineno):
| indent = len(m.group('indent'))
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno)
source = '\n'.join([sl[(indent + 4):] for sl in source_lines])
want = m.group('w... |
'Return a dictionary containing option overrides extracted from
option directives in the given source string.
`name` is the string\'s name, and `lineno` is the line number
where the example starts; both are used for error messages.'
| def _find_options(self, source, name, lineno):
| options = {}
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
option_strings = m.group(1).replace(',', ' ').split()
for option in option_strings:
if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)):
raise ValueError(('line %r of the... |
'Return the minimum indentation of any non-blank line in `s`'
| def _min_indent(self, s):
| indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
if (len(indents) > 0):
return min(indents)
else:
return 0
|
'Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.'
| def _check_prompt_blank(self, lines, indent, name, lineno):
| for (i, line) in enumerate(lines):
if ((len(line) >= (indent + 4)) and (line[(indent + 3)] != ' ')):
raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), name, line[indent:(indent + 3)], line)))
|
'Check that every line in the given list starts with the given
prefix; if any line does not, then raise a ValueError.'
| def _check_prefix(self, lines, prefix, name, lineno):
| for (i, line) in enumerate(lines):
if (line and (not line.startswith(prefix))):
raise ValueError(('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (((lineno + i) + 1), name, line)))
|
'Create a new doctest finder.
The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest). The
signature for this factory function should match the signature
of the DocTest constructor.
If the optional argument... | def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True):
| self._parser = parser
self._verbose = verbose
self._recurse = recurse
self._exclude_empty = exclude_empty
self._namefilter = _namefilter
|
'Return a list of the DocTests that are defined by the given
object\'s docstring, or by any of its contained objects\'
docstrings.
The optional parameter `module` is the module that contains
the given object. If the module is not specified or is None, then
the test finder will attempt to automatically determine the
co... | def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
| if (name is None):
name = getattr(obj, '__name__', None)
if (name is None):
raise ValueError(("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),)))
if (module is False):
module = None
elif (module is None)... |
'Return true if the given object should not be examined.'
| def _filter(self, obj, prefix, base):
| return ((self._namefilter is not None) and self._namefilter(prefix, base))
|
'Return true if the given object is defined in the given
module.'
| def _from_module(self, module, object):
| if (module is None):
return True
elif inspect.isfunction(object):
return (module.__dict__ is object.func_globals)
elif inspect.isclass(object):
return (module.__name__ == object.__module__)
elif (inspect.getmodule(object) is not None):
return (module is inspect.getmodule(... |
'Find tests for the given object and any contained objects, and
add them to `tests`.'
| def _find(self, tests, obj, name, module, source_lines, globs, seen):
| if self._verbose:
print ('Finding tests in %s' % name)
if (id(obj) in seen):
return
seen[id(obj)] = 1
test = self._get_test(obj, name, module, globs, source_lines)
if (test is not None):
tests.append(test)
if (inspect.ismodule(obj) and self._recurse):
for... |
'Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.'
| def _get_test(self, obj, name, module, globs, source_lines):
| if isinstance(obj, basestring):
docstring = obj
else:
try:
if (obj.__doc__ is None):
docstring = ''
else:
docstring = obj.__doc__
if (not isinstance(docstring, basestring)):
docstring = str(docstring)
... |
'Return a line number of the given object\'s docstring. Note:
this method assumes that the object has a docstring.'
| def _find_lineno(self, obj, source_lines):
| lineno = None
if inspect.ismodule(obj):
lineno = 0
if inspect.isclass(obj):
if (source_lines is None):
return None
pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-')))
for (i, line) in enumerate(source_lines):
if pat.match(line):
... |
'Create a new test runner.
Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
outputs of doctest examples.
Optional keyword arg \'verbose\' prints lots of stuff if true,
only failures if false; by default, it\'s true iff \'-v\' is in
sys.argv.
Optional a... | def __init__(self, checker=None, verbose=None, optionflags=0):
| self._checker = (checker or OutputChecker())
if (verbose is None):
verbose = ('-v' in sys.argv)
self._verbose = verbose
self.optionflags = optionflags
self.original_optionflags = optionflags
self.tries = 0
self.failures = 0
self._name2ft = {}
self._fakeout = _SpoofOut()
|
'Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)'
| def report_start(self, out, test, example):
| if self._verbose:
if example.want:
out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want)))
else:
out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
|
'Report that the given example ran successfully. (Only
displays a message if verbose=True)'
| def report_success(self, out, test, example, got):
| if self._verbose:
out('ok\n')
|
'Report that the given example failed.'
| def report_failure(self, out, test, example, got):
| out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
|
'Report that the given example raised an unexpected exception.'
| def report_unexpected_exception(self, out, test, example, exc_info):
| out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
|
'Run the examples in `test`. Write the outcome of each example
with one of the `DocTestRunner.report_*` methods, using the
writer function `out`. `compileflags` is the set of compiler
flags that should be used to execute examples. Return a tuple
`(f, t)`, where `t` is the number of examples tried, and `f`
is the num... | def __run(self, test, compileflags, out):
| failures = tries = 0
original_optionflags = self.optionflags
(SUCCESS, FAILURE, BOOM) = range(3)
check = self._checker.check_output
for (examplenum, example) in enumerate(test.examples):
quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0))
self.optionflags = or... |
'Record the fact that the given DocTest (`test`) generated `f`
failures out of `t` tried examples.'
| def __record_outcome(self, test, f, t):
| (f2, t2) = self._name2ft.get(test.name, (0, 0))
self._name2ft[test.name] = ((f + f2), (t + t2))
self.failures += f
self.tries += t
|
'Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
`clear_globs` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
t... | def run(self, test, compileflags=None, out=None, clear_globs=True):
| self.test = test
if (compileflags is None):
compileflags = _extract_future_flags(test.globs)
save_stdout = sys.stdout
if (out is None):
out = save_stdout.write
sys.stdout = self._fakeout
save_set_trace = pdb.set_trace
self.debugger = _OutputRedirectingPdb(save_stdout)
sel... |
'Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then th... | def summarize(self, verbose=None):
| if (verbose is None):
verbose = self._verbose
notests = []
passed = []
failed = []
totalt = totalf = 0
for x in self._name2ft.items():
(name, (f, t)) = x
assert (f <= t)
totalt += t
totalf += f
if (t == 0):
notests.append(name)
... |
'Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for ... | def check_output(self, want, got, optionflags):
| if (got == want):
return True
if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)):
if ((got, want) == ('True\n', '1\n')):
return True
if ((got, want) == ('False\n', '0\n')):
return True
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
want = re.sub(('(?m)^%... |
'Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.'
| def output_difference(self, example, got, optionflags):
| want = example.want
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
if self._do_a_fancy_diff(want, got, optionflags):
want_lines = want.splitlines(True)
got_lines = got.splitlines(True)
if (optionflags & REPORT_UDIFF):... |
'Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
T... | def debug(self):
| self.setUp()
runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False)
runner.run(self._dt_test)
self.tearDown()
|
'val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
>>> print t.get()
123'
| def __init__(self, val):
| self.val = val
|
'square() -> square TestClass\'s associated value
>>> _TestClass(13).square().get()
169'
| def square(self):
| self.val = (self.val ** 2)
return self
|
'get() -> return TestClass\'s associated value.
>>> x = _TestClass(-42)
>>> print x.get()
-42'
| def get(self):
| return self.val
|
'Compilation stage'
| def __init__(self, template_string, origin=None, name='<Unknown Template>'):
| if (settings.TEMPLATE_DEBUG and (origin == None)):
origin = StringOrigin(template_string)
self.nodelist = compile_string(template_string, origin)
self.name = name
|
'Display stage -- can be called many times'
| def render(self, context):
| return self.nodelist.render(context)
|
'The token_type must be TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK or TOKEN_COMMENT'
| def __init__(self, token_type, contents):
| (self.token_type, self.contents) = (token_type, contents)
|
'Return a list of tokens from a given template_string'
| def tokenize(self):
| bits = filter(None, tag_re.split(self.template_string))
return map(self.create_token, bits)
|
'Convert the given token string into a new Token object and return it'
| def create_token(self, token_string):
| if token_string.startswith(VARIABLE_TAG_START):
token = Token(TOKEN_VAR, token_string[len(VARIABLE_TAG_START):(- len(VARIABLE_TAG_END))].strip())
elif token_string.startswith(BLOCK_TAG_START):
token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):(- len(BLOCK_TAG_END))].strip())
elif ... |
'Return a list of tokens from a given template_string'
| def tokenize(self):
| (token_tups, upto) = ([], 0)
for match in tag_re.finditer(self.template_string):
(start, end) = match.span()
if (start > upto):
token_tups.append((self.template_string[upto:start], (upto, start)))
upto = start
token_tups.append((self.template_string[start:end], (s... |
'Convenient wrapper for FilterExpression'
| def compile_filter(self, token):
| return FilterExpression(token, self)
|
'Overload this method to do the actual parsing and return the result.'
| def top(self):
| raise NotImplemented
|
'Returns True if there is more stuff in the tag.'
| def more(self):
| return (self.pointer < len(self.subject))
|
'Undoes the last microparser. Use this for lookahead and backtracking.'
| def back(self):
| if (not len(self.backout)):
raise TemplateSyntaxError, 'back called without some previous parsing'
self.pointer = self.backout.pop()
|
'A microparser that just returns the next tag from the line.'
| def tag(self):
| subject = self.subject
i = self.pointer
if (i >= len(subject)):
raise TemplateSyntaxError, ('expected another tag, found end of string: %s' % subject)
p = i
while ((i < len(subject)) and (subject[i] not in (' ', ' DCTB '))):
i += 1
s = subject[p:i]
whi... |
'A microparser that parses for a value: some string constant or variable name.'
| def value(self):
| subject = self.subject
i = self.pointer
if (i >= len(subject)):
raise TemplateSyntaxError, ('Searching for value. Expected another value but found end of string: %s' % subject)
if (subject[i] in ('"', "'")):
p = i
i += 1
while ((i < len(su... |
'Return the node rendered as a string'
| def render(self, context):
| pass
|
'Return a list of all nodes (within this node and its nodelist) of the given type'
| def get_nodes_by_type(self, nodetype):
| nodes = []
if isinstance(self, nodetype):
nodes.append(self)
if hasattr(self, 'nodelist'):
nodes.extend(self.nodelist.get_nodes_by_type(nodetype))
return nodes
|
'Return a list of all nodes of the given type'
| def get_nodes_by_type(self, nodetype):
| nodes = []
for node in self:
nodes.extend(node.get_nodes_by_type(nodetype))
return nodes
|
'Set a variable in the current context'
| def __setitem__(self, key, value):
| self.dicts[0][key] = value
|
'Get a variable\'s value, starting at the current context and going upward'
| def __getitem__(self, key):
| for d in self.dicts:
if d.has_key(key):
return d[key]
raise KeyError(key)
|
'Delete a variable from the current context'
| def __delitem__(self, key):
| del self.dicts[0][key]
|
'Like dict.update(). Pushes an entire dictionary\'s keys and values onto the context.'
| def update(self, other_dict):
| self.dicts = ([other_dict] + self.dicts)
|
'Returns a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raises FeedDoesNotExist for invalid parameters.'
| def get_feed(self, url=None):
| if url:
try:
obj = self.get_object(url.split('/'))
except (AttributeError, ObjectDoesNotExist):
raise FeedDoesNotExist
else:
obj = None
current_site = Site.objects.get_current()
link = self.__get_dynamic_attr('link', obj)
link = add_domain(current_site... |
'Helper function'
| def get_comment(self, new_data):
| return Comment(None, self.get_user_id(), new_data['content_type_id'], new_data['object_id'], new_data.get('headline', '').strip(), new_data['comment'].strip(), new_data.get('rating1', None), new_data.get('rating2', None), new_data.get('rating3', None), new_data.get('rating4', None), new_data.get('rating5', None), n... |
'Helper function'
| def get_comment(self, new_data):
| return FreeComment(None, new_data['content_type_id'], new_data['object_id'], new_data['comment'].strip(), new_data['person_name'].strip(), datetime.datetime.now(), new_data['is_public'], new_data['ip_address'], False, settings.SITE_ID)
|
'Returns the MD5 hash of the given options (a comma-separated string such as
\'pa,ra\') and target (something like \'lcom.eventtimes:5157\'). Used to
validate that submitted form options have not been tampered-with.'
| def get_security_hash(self, options, photo_options, rating_options, target):
| import md5
return md5.new(((((options + photo_options) + rating_options) + target) + settings.SECRET_KEY)).hexdigest()
|
'Given a rating_string, this returns a tuple of (rating_range, options).
>>> s = "scale:1-10|First_category|Second_category"
>>> Comment.objects.get_rating_options(s)
([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [\'First category\', \'Second category\'])'
| def get_rating_options(self, rating_string):
| (rating_range, options) = rating_string.split('|', 1)
rating_range = range(int(rating_range[6:].split('-')[0]), (int(rating_range[6:].split('-')[1]) + 1))
choices = [c.replace('_', ' ') for c in options.split('|')]
return (rating_range, choices)
|
'Returns a list of Comment objects matching the given lookup terms, with
_karma_total_good and _karma_total_bad filled.'
| def get_list_with_karma(self, **kwargs):
| extra_kwargs = {}
extra_kwargs.setdefault('select', {})
extra_kwargs['select']['_karma_total_good'] = 'SELECT COUNT(*) FROM comments_karmascore, comments_comment WHERE comments_karmascore.comment_id=comments_comment.id AND score=1'
extra_kwargs['select']['_karma_total_bad'] = 'SE... |
'Returns the object that this comment is a comment on. Returns None if
the object no longer exists.'
| def get_content_object(self):
| from django.core.exceptions import ObjectDoesNotExist
try:
return self.content_type.get_object_for_this_type(pk=self.object_id)
except ObjectDoesNotExist:
return None
|
'Helper function that populates good/bad karma caches'
| def _fill_karma_cache(self):
| (good, bad) = (0, 0)
for k in self.karmascore_set:
if (k.score == (-1)):
bad += 1
elif (k.score == 1):
good += 1
(self._karma_total_good, self._karma_total_bad) = (good, bad)
|
'Returns the object that this comment is a comment on. Returns None if
the object no longer exists.'
| def get_content_object(self):
| from django.core.exceptions import ObjectDoesNotExist
try:
return self.content_type.get_object_for_this_type(pk=self.object_id)
except ObjectDoesNotExist:
return None
|
'Given a score between -1 and 1 (inclusive), returns the same score on a
scale between 1 and 10 (inclusive), as an integer.'
| def get_pretty_score(self, score):
| if (score is None):
return DEFAULT_KARMA
return int(round(((4.5 * score) + 5.5)))
|
'Flags the given comment by the given user. If the comment has already
been flagged by the user, or it was a comment posted by the user,
nothing happens.'
| def flag(self, comment, user):
| if (int(comment.user_id) == int(user.id)):
return
try:
f = self.objects.get(user__pk=user.id, comment__pk=comment.id)
except self.model.DoesNotExist:
from django.core.mail import mail_managers
f = self.model(None, user.id, comment.id, None)
message = (_('This comme... |
'Returns the edited object represented by this log entry'
| def get_edited_object(self):
| return self.content_type.get_object_for_this_type(pk=self.object_id)
|
'Returns the admin URL to edit the object represented by this log entry.
This is relative to the Django admin index page.'
| def get_admin_url(self):
| return ('%s/%s/%s/' % (self.content_type.app_label, self.content_type.model, self.object_id))
|
'Returns the given session dictionary pickled and encoded as a string.'
| def encode(self, session_dict):
| pickled = pickle.dumps(session_dict)
pickled_md5 = md5.new((pickled + settings.SECRET_KEY)).hexdigest()
return base64.encodestring((pickled + pickled_md5))
|
'Returns session key that isn\'t being used.'
| def get_new_session_key(self):
| while 1:
session_key = md5.new(((str(random.randint(0, (sys.maxint - 1))) + str(random.randint(0, (sys.maxint - 1)))) + settings.SECRET_KEY)).hexdigest()
try:
self.get(session_key=session_key)
except self.model.DoesNotExist:
break
return session_key
|
'Returns a new session object.'
| def get_new_session_object(self):
| created = False
while (not created):
(obj, created) = self.get_or_create(session_key=self.get_new_session_key(), expire_date=datetime.datetime.now())
random.seed()
return obj
|
'Creates and saves a User with the given username, e-mail and password.'
| def create_user(self, username, email, password):
| now = datetime.datetime.now()
user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
user.set_password(password)
user.save()
return user
|
'Generates a random password with the given length and given allowed_chars'
| def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
| from random import choice
return ''.join([choice(allowed_chars) for i in range(length)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.