signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def dump_cookie(key, value='<STR_LIT>', max_age=None, expires=None, path='<STR_LIT:/>',<EOL>domain=None, secure=False, httponly=False,<EOL>charset='<STR_LIT:utf-8>', sync_expires=True): | key = to_bytes(key, charset)<EOL>value = to_bytes(value, charset)<EOL>if path is not None:<EOL><INDENT>path = iri_to_uri(path, charset)<EOL><DEDENT>domain = _make_cookie_domain(domain)<EOL>if isinstance(max_age, timedelta):<EOL><INDENT>max_age = (max_age.days * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>) + max_age.seconds<EOL><... | Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameters are the same as in the cookie Morsel object in the
Python standard library but it accepts unicode data, too.
On Python 3 the return value of this function will be a unicode
string, on Python 2 it will be a native string. ... | f5884:m31 |
def is_byte_range_valid(start, stop, length): | if (start is None) != (stop is None):<EOL><INDENT>return False<EOL><DEDENT>elif start is None:<EOL><INDENT>return length is None or length >= <NUM_LIT:0><EOL><DEDENT>elif length is None:<EOL><INDENT>return <NUM_LIT:0> <= start < stop<EOL><DEDENT>elif start >= stop:<EOL><INDENT>return False<EOL><DEDENT>return <NUM_LIT:0... | Checks if a given byte content range is valid for the given length.
.. versionadded:: 0.7 | f5884:m32 |
def get_content_type(mimetype, charset): | if mimetype.startswith('<STR_LIT>') ormimetype == '<STR_LIT>' or(mimetype.startswith('<STR_LIT>') and<EOL>mimetype.endswith('<STR_LIT>')):<EOL><INDENT>mimetype += '<STR_LIT>' + charset<EOL><DEDENT>return mimetype<EOL> | Return the full content type string with charset for a mimetype.
If the mimetype represents text the charset will be appended as charset
parameter, otherwise the mimetype is returned unchanged.
:param mimetype: the mimetype to be used as content type.
:param charset: the charset to be appended in case... | f5886:m0 |
def format_string(string, context): | def lookup_arg(match):<EOL><INDENT>x = context[match.group(<NUM_LIT:1>) or match.group(<NUM_LIT:2>)]<EOL>if not isinstance(x, string_types):<EOL><INDENT>x = type(string)(x)<EOL><DEDENT>return x<EOL><DEDENT>return _format_re.sub(lookup_arg, string)<EOL> | String-template format a string:
>>> format_string('$foo and ${foo}s', dict(foo=42))
'42 and 42s'
This does not do any attribute lookup etc. For more advanced string
formattings have a look at the `werkzeug.template` module.
:param string: the format string.
:param context: a dict with the v... | f5886:m1 |
def secure_filename(filename): | if isinstance(filename, text_type):<EOL><INDENT>from unicodedata import normalize<EOL>filename = normalize('<STR_LIT>', filename).encode('<STR_LIT:ascii>', '<STR_LIT:ignore>')<EOL>if not PY2:<EOL><INDENT>filename = filename.decode('<STR_LIT:ascii>')<EOL><DEDENT><DEDENT>for sep in os.path.sep, os.path.altsep:<EOL><INDEN... | r"""Pass it a filename and it will return a secure version of it. This
filename can then safely be stored on a regular file system and passed
to :func:`os.path.join`. The filename returned is an ASCII only string
for maximum portability.
On windows system the function also makes sure that the file is... | f5886:m2 |
def escape(s, quote=None): | if s is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif hasattr(s, '<STR_LIT>'):<EOL><INDENT>return text_type(s.__html__())<EOL><DEDENT>elif not isinstance(s, string_types):<EOL><INDENT>s = text_type(s)<EOL><DEDENT>if quote is not None:<EOL><INDENT>from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'... | Replace special characters "&", "<", ">" and (") to HTML-safe sequences.
There is a special handling for `None` which escapes to an empty string.
.. versionchanged:: 0.9
`quote` is now implicitly on.
:param s: the string to escape.
:param quote: ignored. | f5886:m3 |
def unescape(s): | def handle_match(m):<EOL><INDENT>name = m.group(<NUM_LIT:1>)<EOL>if name in HTMLBuilder._entities:<EOL><INDENT>return unichr(HTMLBuilder._entities[name])<EOL><DEDENT>try:<EOL><INDENT>if name[:<NUM_LIT:2>] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return unichr(int(name[<NUM_LIT:2>:], <NUM_LIT:16>))<EOL><DEDENT>elif na... | The reverse function of `escape`. This unescapes all the HTML
entities, not only the XML entities inserted by `escape`.
:param s: the string to unescape. | f5886:m4 |
def redirect(location, code=<NUM_LIT>): | from werkzeug.wrappers import Response<EOL>display_location = escape(location)<EOL>if isinstance(location, text_type):<EOL><INDENT>from werkzeug.urls import iri_to_uri<EOL>location = iri_to_uri(location)<EOL><DEDENT>response = Response(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' %<E... | Return a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since... | f5886:m5 |
def append_slash_redirect(environ, code=<NUM_LIT>): | new_path = environ['<STR_LIT>'].strip('<STR_LIT:/>') + '<STR_LIT:/>'<EOL>query_string = environ.get('<STR_LIT>')<EOL>if query_string:<EOL><INDENT>new_path += '<STR_LIT:?>' + query_string<EOL><DEDENT>return redirect(new_path, code)<EOL> | Redirect to the same URL but with a slash appended. The behavior
of this function is undefined if the path ends with a slash already.
:param environ: the WSGI environment for the request that triggers
the redirect.
:param code: the status code for the redirect. | f5886:m6 |
def import_string(import_name, silent=False): | <EOL>assert isinstance(import_name, string_types)<EOL>import_name = str(import_name)<EOL>try:<EOL><INDENT>if '<STR_LIT::>' in import_name:<EOL><INDENT>module, obj = import_name.split('<STR_LIT::>', <NUM_LIT:1>)<EOL><DEDENT>elif '<STR_LIT:.>' in import_name:<EOL><INDENT>module, obj = import_name.rsplit('<STR_LIT:.>', <N... | Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If `silent` is True the ret... | f5886:m7 |
def find_modules(import_path, include_packages=False, recursive=False): | module = import_string(import_path)<EOL>path = getattr(module, '<STR_LIT>', None)<EOL>if path is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % import_path)<EOL><DEDENT>basename = module.__name__ + '<STR_LIT:.>'<EOL>for importer, modname, ispkg in pkgutil.iter_modules(path):<EOL><INDENT>modname = basename + modname<E... | Find all the modules below a package. This can be useful to
automatically import all views / controllers so that their metaclasses /
function decorators have a chance to register themselves on the
application.
Packages are not returned unless `include_packages` is `True`. This can
also recursivel... | f5886:m8 |
def validate_arguments(func, args, kwargs, drop_extra=True): | parser = _parse_signature(func)<EOL>args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:<NUM_LIT:5>]<EOL>if missing:<EOL><INDENT>raise ArgumentValidationError(tuple(missing))<EOL><DEDENT>elif (extra or extra_positional) and not drop_extra:<EOL><INDENT>raise ArgumentValidationError(None, extra, extra_... | Check if the function accepts the arguments and keyword arguments.
Returns a new ``(args, kwargs)`` tuple that can safely be passed to
the function without causing a `TypeError` because the function signature
is incompatible. If `drop_extra` is set to `True` (which is the default)
any extra positional ... | f5886:m9 |
def bind_arguments(func, args, kwargs): | args, kwargs, missing, extra, extra_positional,arg_spec, vararg_var, kwarg_var = _parse_signature(func)(args, kwargs)<EOL>values = {}<EOL>for (name, has_default, default), value in zip(arg_spec, args):<EOL><INDENT>values[name] = value<EOL><DEDENT>if vararg_var is not None:<EOL><INDENT>values[vararg_var] = tuple(extra_p... | Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorator that uses the function arguments to build
the cache key based o... | f5886:m10 |
def release_local(local): | local.__release_local__()<EOL> | Releases the contents of the local for the current context.
This makes it possible to use locals without a manager.
Example::
>>> loc = Local()
>>> loc.foo = 42
>>> release_local(loc)
>>> hasattr(loc, 'foo')
False
With this function one can release :class:`Local` o... | f5887:m0 |
def __call__(self, proxy): | return LocalProxy(self, proxy)<EOL> | Create a proxy for a name. | f5887:c0:m2 |
def push(self, obj): | rv = getattr(self._local, '<STR_LIT>', None)<EOL>if rv is None:<EOL><INDENT>self._local.stack = rv = []<EOL><DEDENT>rv.append(obj)<EOL>return rv<EOL> | Pushes a new item to the stack | f5887:c1:m5 |
def pop(self): | stack = getattr(self._local, '<STR_LIT>', None)<EOL>if stack is None:<EOL><INDENT>return None<EOL><DEDENT>elif len(stack) == <NUM_LIT:1>:<EOL><INDENT>release_local(self._local)<EOL>return stack[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>return stack.pop()<EOL><DEDENT> | Removes the topmost item from the stack, will return the
old value or `None` if the stack was already empty. | f5887:c1:m6 |
@property<EOL><INDENT>def top(self):<DEDENT> | try:<EOL><INDENT>return self._local.stack[-<NUM_LIT:1>]<EOL><DEDENT>except (AttributeError, IndexError):<EOL><INDENT>return None<EOL><DEDENT> | The topmost item on the stack. If the stack is empty,
`None` is returned. | f5887:c1:m7 |
def get_ident(self): | return self.ident_func()<EOL> | Return the context identifier the local objects use internally for
this context. You cannot override this method to change the behavior
but use it to link other context local objects (such as SQLAlchemy's
scoped sessions) to the Werkzeug locals.
.. versionchanged:: 0.7
Yu ca... | f5887:c2:m1 |
def cleanup(self): | for local in self.locals:<EOL><INDENT>release_local(local)<EOL><DEDENT> | Manually clean up the data in the locals for this context. Call
this at the end of the request or use `make_middleware()`. | f5887:c2:m2 |
def make_middleware(self, app): | def application(environ, start_response):<EOL><INDENT>return ClosingIterator(app(environ, start_response), self.cleanup)<EOL><DEDENT>return application<EOL> | Wrap a WSGI application so that cleaning up happens after
request end. | f5887:c2:m3 |
def middleware(self, func): | return update_wrapper(self.make_middleware(func), func)<EOL> | Like `make_middleware` but for decorating functions.
Example usage::
@manager.middleware
def application(environ, start_response):
...
The difference to `make_middleware` is that the function passed
will have all the arguments copied from the inner appl... | f5887:c2:m4 |
def _get_current_object(self): | if not hasattr(self.__local, '<STR_LIT>'):<EOL><INDENT>return self.__local()<EOL><DEDENT>try:<EOL><INDENT>return getattr(self.__local, self.__name__)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError('<STR_LIT>' % self.__name__)<EOL><DEDENT> | Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context. | f5887:c3:m1 |
def _log(type, message, *args, **kwargs): | global _logger<EOL>if _logger is None:<EOL><INDENT>import logging<EOL>_logger = logging.getLogger('<STR_LIT>')<EOL>if not logging.root.handlers and _logger.level == logging.NOTSET:<EOL><INDENT>_logger.setLevel(logging.INFO)<EOL>handler = logging.StreamHandler()<EOL>_logger.addHandler(handler)<EOL><DEDENT><DEDENT>getatt... | Log into the internal werkzeug logger. | f5888:m1 |
def _parse_signature(func): | if hasattr(func, '<STR_LIT>'):<EOL><INDENT>func = func.im_func<EOL><DEDENT>parse = _signature_cache.get(func)<EOL>if parse is not None:<EOL><INDENT>return parse<EOL><DEDENT>positional, vararg_var, kwarg_var, defaults = inspect.getargspec(func)<EOL>defaults = defaults or ()<EOL>arg_count = len(positional)<EOL>arguments ... | Return a signature object for the function. | f5888:m2 |
def _date_to_unix(arg): | if isinstance(arg, datetime):<EOL><INDENT>arg = arg.utctimetuple()<EOL><DEDENT>elif isinstance(arg, (int, long, float)):<EOL><INDENT>return int(arg)<EOL><DEDENT>year, month, day, hour, minute, second = arg[:<NUM_LIT:6>]<EOL>days = date(year, month, <NUM_LIT:1>).toordinal() - _epoch_ord + day - <NUM_LIT:1><EOL>hours = d... | Converts a timetuple, integer or datetime object into the seconds from
epoch in utc. | f5888:m3 |
def _cookie_parse_impl(b): | i = <NUM_LIT:0><EOL>n = len(b)<EOL>while i < n:<EOL><INDENT>match = _cookie_re.search(b + b'<STR_LIT:;>', i)<EOL>if not match:<EOL><INDENT>break<EOL><DEDENT>key = match.group('<STR_LIT:key>').strip()<EOL>value = match.group('<STR_LIT>')<EOL>i = match.end(<NUM_LIT:0>)<EOL>if key.lower() not in _cookie_params:<EOL><INDEN... | Lowlevel cookie parsing facility that operates on bytes. | f5888:m6 |
def _easteregg(app=None): | def bzzzzzzz(gyver):<EOL><INDENT>import base64<EOL>import zlib<EOL>return zlib.decompress(base64.b64decode(gyver)).decode('<STR_LIT:ascii>')<EOL><DEDENT>gyver = u'<STR_LIT:\n>'.join([x + (<NUM_LIT> - len(x)) * u'<STR_LIT:U+0020>' for x in bzzzzzzz(b'''<STR_LIT>''').splitlines()])<EOL>def easteregged(environ, start_resp... | Like the name says. But who knows how it works? | f5888:m10 |
@classmethod<EOL><INDENT>def wrap(cls, exception, name=None):<DEDENT> | class newcls(cls, exception):<EOL><INDENT>def __init__(self, arg=None, *args, **kwargs):<EOL><INDENT>cls.__init__(self, *args, **kwargs)<EOL>exception.__init__(self, arg)<EOL><DEDENT><DEDENT>newcls.__module__ = sys._getframe(<NUM_LIT:1>).f_globals.get('<STR_LIT>')<EOL>newcls.__name__ = name or cls.__name__ + exception.... | This method returns a new subclass of the exception provided that
also is a subclass of `BadRequest`. | f5890:c0:m1 |
@property<EOL><INDENT>def name(self):<DEDENT> | return HTTP_STATUS_CODES.get(self.code, '<STR_LIT>')<EOL> | The status name. | f5890:c0:m2 |
def get_description(self, environ=None): | return u'<STR_LIT>' % escape(self.description)<EOL> | Get the description. | f5890:c0:m3 |
def get_body(self, environ=None): | return text_type((<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>) % {<EOL>'<STR_LIT:code>': self.code,<EOL>'<STR_LIT:name>': escape(self.name),<EOL>'<STR_LIT:description>': self.get_description(environ)<EOL>})<EOL> | Get the HTML body. | f5890:c0:m4 |
def get_headers(self, environ=None): | return [('<STR_LIT:Content-Type>', '<STR_LIT>')]<EOL> | Get a list of headers. | f5890:c0:m5 |
def get_response(self, environ=None): | if self.response is not None:<EOL><INDENT>return self.response<EOL><DEDENT>if environ is not None:<EOL><INDENT>environ = _get_environ(environ)<EOL><DEDENT>headers = self.get_headers(environ)<EOL>return Response(self.get_body(environ), self.code, headers)<EOL> | Get a response object. If one was passed to the exception
it's returned directly.
:param environ: the optional environ for the request. This
can be used to modify the response depending
on how the request looked like.
:return: a :class:`Response... | f5890:c0:m6 |
def __call__(self, environ, start_response): | response = self.get_response(environ)<EOL>return response(environ, start_response)<EOL> | Call the exception as WSGI application.
:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
server. | f5890:c0:m7 |
def __init__(self, valid_methods=None, description=None): | HTTPException.__init__(self, description)<EOL>self.valid_methods = valid_methods<EOL> | Takes an optional list of valid http methods
starting with werkzeug 0.3 the list will be mandatory. | f5890:c7:m0 |
def get(self, key, default=Empty, creator=Empty, expire=None): | try:<EOL><INDENT>return self.storage.get(key)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>if creator is not Empty:<EOL><INDENT>if callable(creator):<EOL><INDENT>v = creator()<EOL><DEDENT>else:<EOL><INDENT>v = creator<EOL><DEDENT>self.set(key, v, expire)<EOL>return v<EOL><DEDENT>else:<EOL><INDENT>if default is not Emp... | :para default: if default is callable then invoke it, save it and return it | f5891:c4:m3 |
def __init__(self, cache_manager, options): | BaseStorage.__init__(self, cache_manager, options)<EOL>if not options.get('<STR_LIT>'):<EOL><INDENT>options['<STR_LIT>'] = ['<STR_LIT>']<EOL><DEDENT>self.client = self.import_preferred_memcache_lib(options)<EOL>if self.client is None:<EOL><INDENT>raise Error('<STR_LIT>')<EOL><DEDENT> | options =
connection = ['localhost:11211']
module = None | f5893:c1:m0 |
def get(self, key): | if isinstance(key, unicode):<EOL><INDENT>key = key.encode('<STR_LIT:utf-8>')<EOL><DEDENT>v = self.client.get(key)<EOL>if v is None:<EOL><INDENT>raise KeyError("<STR_LIT>" % key)<EOL><DEDENT>else:<EOL><INDENT>return v<EOL><DEDENT> | because memcached does not provide a function to check if a key is existed
so here is a heck way, if the value is None, then raise Exception | f5893:c1:m1 |
def __init__(self, cache_manager, options): | BaseStorage.__init__(self, cache_manager, options)<EOL>self._type = (int, long)<EOL>if '<STR_LIT>' in options:<EOL><INDENT>self.client = redis.Redis(unix_socket_path=options['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>global __connection_pool__<EOL>if not __connection_pool__ or __connection_pool__[<NUM_LIT:0>] != optio... | options =
unix_socket_path = '/tmp/redis.sock'
or
connection_pool = {'host':'localhost', 'port':6379, 'db':0} | f5895:c0:m0 |
def __init__(self, key=None, storage_type='<STR_LIT:file>', options=None, expiry_time=<NUM_LIT>*<NUM_LIT>*<NUM_LIT>,<EOL>serial_cls=None, prefix='<STR_LIT>'): | dict.__init__(self)<EOL>self._old_value = {}<EOL>self._storage_type = storage_type<EOL>self._options = options or {}<EOL>self._storage_cls = self.__get_storage()<EOL>self._storage = None<EOL>self._accessed_time = None<EOL>self.expiry_time = expiry_time<EOL>self.key = key<EOL>self.deleted = False<EOL>self.cookie = Sessi... | expiry_time is just like max_age, the unit is second | f5898:c3:m0 |
def _make_cssmin(python_only=False): | <EOL>if not python_only:<EOL><INDENT>try:<EOL><INDENT>import _rcssmin<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return _rcssmin.cssmin<EOL><DEDENT><DEDENT>nl = r'<STR_LIT>' <EOL>spacechar = r'<STR_LIT>'<EOL>unicoded = r'<STR_LIT>'<EOL>escaped = r'<STR_LIT>'<EOL>escape = r'<STR_LIT>'... | Generate CSS minifier.
:Parameters:
`python_only` : ``bool``
Use only the python variant. If true, the c extension is not even
tried to be loaded.
:Return: Minifier
:Rtype: ``callable`` | f5899:m0 |
def make_application(debug=None, apps_dir='<STR_LIT>', project_dir=None,<EOL>include_apps=None, debug_console=True, settings_file=None,<EOL>local_settings_file=None, start=True, default_settings=None,<EOL>dispatcher_cls=None, dispatcher_kwargs=None, debug_cls=None, debug_kwargs=None,<EOL>reuse=True, verbose=False, pyth... | from uliweb.utils.common import import_attr<EOL>from uliweb.utils.whocallme import print_frame<EOL>from werkzeug.debug import DebuggedApplication<EOL>if reuse and hasattr(SimpleFrame.__global__, '<STR_LIT>') and SimpleFrame.__global__.application:<EOL><INDENT>return SimpleFrame.__global__.application<EOL><DEDENT>settin... | Make an application object | f5900:m3 |
def interact(self, banner=None, call=None): | try:<EOL><INDENT>sys.ps1<EOL><DEDENT>except AttributeError:<EOL><INDENT>sys.ps1 = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>sys.ps2<EOL><DEDENT>except AttributeError:<EOL><INDENT>sys.ps2 = "<STR_LIT>"<EOL><DEDENT>cprt = '<STR_LIT>'<EOL>if banner is None:<EOL><INDENT>self.write("<STR_LIT>" %<EOL>(sys.version, sys.platfor... | Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
... | f5900:c15:m0 |
def _find_template(self, template, tree, blocks, with_filename,<EOL>source, comment): | from uliweb import application<EOL>from uliweb.core.template import _format_code<EOL>def get_rel_filename(filename, path):<EOL><INDENT>f1 = os.path.splitdrive(filename)[<NUM_LIT:1>]<EOL>f2 = os.path.splitdrive(path)[<NUM_LIT:1>]<EOL>f = os.path.relpath(f1, f2).replace('<STR_LIT:\\>', '<STR_LIT:/>')<EOL>if f.startswith(... | If tree is true, then will display the track of template extend or include | f5900:c17:m3 |
def _validate_templates(self, app, files, verbose): | from uliweb import application<EOL>from uliweb.core.template import template_file<EOL>from uliweb.utils.common import trim_path<EOL>app.template_loader.log = None<EOL>for f in files:<EOL><INDENT>try:<EOL><INDENT>t = app.template_loader.load(f)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>', f)<EOL><DEDENT><DEDENT>except... | If tree is true, then will display the track of template extend or include | f5900:c18:m2 |
@iface.property<EOL><INDENT>def time(self) -> typing.Union[int, float]:<DEDENT> | raise NotImplementedError()<EOL> | Get the current processor time.
The time must always be returned as a numeric value that represents
seconds. | f5901:c0:m0 |
@iface.method<EOL><INDENT>def defer(<EOL>self,<EOL>func: typing.Callable[[], typing.Any],<EOL>until: typing.Union[int, float]=-<NUM_LIT:1>,<EOL>) -> typing.Any:<DEDENT> | raise NotImplementedError()<EOL> | Defer the execution of a function until some clock value.
Args:
func (typing.Callable[[], typing.Any]): A callable that accepts no
arguments. All return values are ignored.
until (typing.Union[int, float]): A numeric value that represents
the clock time w... | f5901:c0:m1 |
@iface.method<EOL><INDENT>def defer_for(<EOL>self,<EOL>wait: typing.Union[int, float],<EOL>func: typing.Callable[[], typing.Any],<EOL>) -> typing.Any:<DEDENT> | raise NotImplementedError()<EOL> | Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes available for execution. All given values must be
pos... | f5901:c0:m2 |
@iface.method<EOL><INDENT>def delay(<EOL>self,<EOL>identifier: typing.Any,<EOL>until: typing.Union[int, float]=-<NUM_LIT:1>,<EOL>) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Delay a deferred function until the given time.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
until (typing.Union[int, float]): A numeric value that represents
the clock time when the callback becomes available ... | f5901:c0:m3 |
@iface.method<EOL><INDENT>def delay_for(<EOL>self,<EOL>wait: typing.Union[int, float],<EOL>identifier: typing.Any,<EOL>) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Defer the execution of a function for some number of seconds.
Args:
wait (typing.Union[int, float]): A numeric value that represents
the number of seconds that must pass before the callback
becomes available for execution. All given values must be
pos... | f5901:c0:m4 |
@iface.method<EOL><INDENT>def cancel(self, identifier: typing.Any) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Cancel a deferred function call.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
Returns:
bool: True if the call is cancelled. False if the identifier is
invalid or if the deferred call is already execute... | f5901:c0:m5 |
@iface.method<EOL><INDENT>def pending(self, identifier: typing.Any) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Get the pending status of a deferred function call.
Args:
identifier (typing.Any): The identifier returned from a call
to defer or defer_for.
Returns:
bool: True if the call is pending. False if the identifier is
invalid or if the deferred call i... | f5901:c0:m6 |
@iface.method<EOL><INDENT>def __call__(self) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Enact the processor for one step.
All processors must be a callable that accept zero arguments. | f5903:c0:m0 |
@iface.method<EOL><INDENT>def handle_exception(self) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Handle any uncaught exceptions that are raised by the Processor.
This method will always be called from within an except block. | f5903:c0:m1 |
@iface.method<EOL><INDENT>def fileno(self) -> int:<DEDENT> | raise NotImplementedError()<EOL> | Return an integer file descripter for the object. | f5904:c0:m0 |
@iface.method<EOL><INDENT>def add_reader(<EOL>self,<EOL>fd: IFileLike,<EOL>callback: typing.Callable[[IFileLike], typing.Any],<EOL>) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileL... | f5904:c1:m0 |
@iface.method<EOL><INDENT>def remove_reader(self, fd: IFileLike) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Remove a file descriptor waiting for READ from the processor.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
Returns:
bool: True if the reader was removed. False if it was not in the
p... | f5904:c1:m1 |
@iface.method<EOL><INDENT>def add_writer(<EOL>self,<EOL>fd: IFileLike,<EOL>callback: typing.Callable[[IFileLike], typing.Any],<EOL>) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Add a file descriptor to the processor and wait for WRITE.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFile... | f5904:c1:m2 |
@iface.method<EOL><INDENT>def remove_writer(self, fd: IFileLike) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Remove a file descriptor waiting for WRITE from the processor.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
Returns:
bool: True if the reader was removed. False if it was not in the
... | f5904:c1:m3 |
@iface.attribute<EOL><INDENT>def processors(self) -> typing.Iterable[iprocessor.IProcessor]:<DEDENT> | raise NotImplementedError()<EOL> | Get an iterable of all processors attached to the engine. | f5905:c0:m0 |
@iface.attribute<EOL><INDENT>def running(self) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Get whether the engine is currently running or not. | f5905:c0:m1 |
@iface.method<EOL><INDENT>def start(self) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Start the engine and run it until stopped. | f5905:c0:m2 |
@iface.method<EOL><INDENT>def stop(self) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Stop the engine from executing. | f5905:c0:m3 |
@iface.method<EOL><INDENT>def __next__(self) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Push the engine one step. | f5905:c0:m4 |
@iface.method<EOL><INDENT>def add(self, coro: types.CoroutineType) -> typing.Any:<DEDENT> | raise NotImplementedError()<EOL> | Add a coroutine to the engine for execution.
Args:
coro (types.CoroutineType): A coroutine object.
Returns:
typing.Any: Some opaque identifier that represents the scheduled
coroutine within the engine. | f5906:c0:m0 |
@iface.method<EOL><INDENT>def cancel(<EOL>self,<EOL>identifier: typing.Any,<EOL>exc_type: typing.Optional[type]=None,<EOL>) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Optional[type]): The exception type to throw into
the coroutine on cancel. No exception is thrown if nothing is
g... | f5906:c0:m1 |
@iface.classattribute<EOL><INDENT>def default_max_listeners(self) -> int:<DEDENT> | raise NotImplementedError()<EOL> | The default number of max listeners per event before warning.
A value of zero or less is the same as setting this value to
float('inf'). | f5908:c0:m0 |
@iface.attribute<EOL><INDENT>def max_listeners(self) -> int:<DEDENT> | raise NotImplementedError()<EOL> | The max listeners per event before this instance warns. | f5908:c0:m1 |
@iface.method<EOL><INDENT>def listeners(self, event: str) -> typing.Iterable[typing.Callable]:<DEDENT> | raise NotImplementedError()<EOL> | Get an iterable of listeners for a given event.
Args:
event (str): The case-sensitive name of an event.
Returns:
typing.Iterable[typing.Callable]: An iterable of listeners. | f5908:c0:m2 |
@iface.method<EOL><INDENT>def listeners_count(self, event: str) -> int:<DEDENT> | raise NotImplementedError()<EOL> | Get the number of listeners for a given event.
Args:
event (str): The case-sensitive name of an event.
Returns:
int: The number of listeners for the event. | f5908:c0:m3 |
@iface.method<EOL><INDENT>def on(self, event: str, listener: typing.Callable) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Add a listener for the given event.
This method will not add listeners while the event is being emitted.
If called while emitting the same event, the emitter will queue the
request and process it after all listerners are called.
Args:
event (str): The case-sensitive name of... | f5908:c0:m4 |
@iface.method<EOL><INDENT>def once(self, event: str, listener: typing.Callable) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Add a one time listener for the given event.
Args:
event (str): The case-sensitive name of an event.
listener (typing.Callable): The function to execute when the event
is emitted. | f5908:c0:m5 |
@iface.method<EOL><INDENT>def remove(self, event: str, listener: typing.Callable) -> None:<DEDENT> | raise NotImplementedError()<EOL> | Remove a listener from an event.
This method removes, at most, one listener from the given event.
Listeners are removed in the order in which they were registered.
This method will not remove listeners while the event is being emitted.
If called while emitting the same event, the emitt... | f5908:c0:m6 |
@iface.method<EOL><INDENT>def emit(self, event: str, *args, **kwargs) -> bool:<DEDENT> | raise NotImplementedError()<EOL> | Call all listeners attached to the given event.
All listeners are called with the args and kwargs given to this method.
Returns:
bool: True if the event has listeners else False. | f5908:c0:m7 |
def proxy_for(widget): | proxy_type = widget_proxies.get(widget.__class__)<EOL>if proxy_type is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % widget)<EOL><DEDENT>return proxy_type(widget)<EOL> | Create a proxy for a Widget
:param widget: A gtk.Widget to proxy
This will raise a KeyError if there is no proxy type registered for the
widget type. | f5911:m0 |
def update(self, value): | self.update_internal(value)<EOL>self.emit('<STR_LIT>', self.get_widget_value())<EOL> | Update the widget's value | f5911:c0:m1 |
def read(self): | return self.get_widget_value()<EOL> | Get the widget's value | f5911:c0:m2 |
def update_internal(self, value): | self.block()<EOL>self.set_widget_value(value)<EOL>self.unblock()<EOL> | Update the widget's value without firing a changed signal | f5911:c0:m5 |
def widget_changed(self, *args): | self.emit('<STR_LIT>', self.get_widget_value())<EOL> | Called to indicate that a widget's value has been changed.
This will usually be called from a proxy implementation on response to
whichever signal was connected in `connect_widget`
The `*args` are there so you can use this as a signal handler. | f5911:c0:m6 |
def set_widget_value(self, value): | Set the value of the widget.
This will update the view to match the value given. This is called
internally, and is called while the proxy is blocked, so no signals
are emitted from this action.
This method should be overriden in subclasses depending on how a
widget's value is s... | f5911:c0:m7 | |
def get_widget_value(self): | Get the widget value.
This method should be overridden in subclasses to return a value from
the widget. | f5911:c0:m8 | |
def connect_widget(self): | if self.signal_name is not None:<EOL><INDENT>sid = self.widget.connect(self.signal_name, self.widget_changed)<EOL>self.connections.append(sid)<EOL><DEDENT> | Perform the initial connection of the widget
the default implementation will connect to the widgets signal
based on self.signal_name | f5911:c0:m9 |
def add_proxy(self, name, proxy): | proxy.connect('<STR_LIT>', self._on_proxy_changed, name)<EOL> | Add a proxy to this group
:param name: The name or key of the proxy, which will be emitted with
the changed signal
:param proxy: The proxy instance to add | f5911:c16:m1 |
def add_proxy_for(self, name, widget): | proxy = proxy_for(widget)<EOL>self.add_proxy(name, proxy)<EOL> | Create a proxy for a widget and add it to this group
:param name: The name or key of the proxy, which will be emitted with
the changed signal
:param widget: The widget to create a proxy for | f5911:c16:m2 |
def add_group(self, group): | group.connect('<STR_LIT>', self._on_group_changed)<EOL> | Add an existing group to this group and proxy its signals
:param group: The ProxyGroup instance to add | f5911:c16:m3 |
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra): | global _old_hook<EOL>assert _old_hook is None<EOL>def new_hook(etype, eval, trace):<EOL><INDENT>gobject.idle_add(dialog_handler, dialog, etype, eval, trace, extra)<EOL>if invoke_old_hook:<EOL><INDENT>_old_hook(etype, eval, trace)<EOL><DEDENT><DEDENT>_old_hook = sys.excepthook<EOL>sys.excepthook = new_hook<EOL> | install the configured exception hook wrapping the old exception hook
don't use it twice
:oparam dialog: a different exception dialog class
:oparam invoke_old_hook: should we invoke the old exception hook? | f5912:m2 |
def uninstall_hook(): | global _old_hook<EOL>sys.excepthook = _old_hook<EOL>_old_hook = None<EOL> | uninstall our hook | f5912:m3 |
def _commonprefix(m): | if not m:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>prefix = m[<NUM_LIT:0>]<EOL>for item in m:<EOL><INDENT>for i in range(len(prefix)):<EOL><INDENT>if prefix[:i+<NUM_LIT:1>] != item[:i+<NUM_LIT:1>]:<EOL><INDENT>prefix = prefix[:i]<EOL>if i == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>break<EOL><DEDENT><D... | Given a list of pathnames, returns the longest common leading component | f5913:m0 |
def expand_items(form_values, sep='<STR_LIT:.>'): | output = {}<EOL>for keys_str_i, value_i in form_values:<EOL><INDENT>keys_i = keys_str_i.split(sep)<EOL>parents_i = keys_i[:-<NUM_LIT:1>]<EOL>fieldname_i = keys_i[-<NUM_LIT:1>]<EOL>dict_j = output<EOL>for key_j in parents_i:<EOL><INDENT>dict_j = dict_j.setdefault(key_j, {})<EOL><DEDENT>dict_j[fieldname_i] = value_i<EOL... | Parameters
----------
form_values : list
List of ``(key, value)`` tuples, where ``key`` corresponds to the
ancestor keys of the respective value joined by ``'.'``. For example,
the key ``'a.b.c'`` would be expanded to the dictionary
``{'a': {'b': {'c': 'foo'}}}``.
Returns
-------
dict
Nested dicti... | f5915:m0 |
def flatten_dict(root, parents=None, sep='<STR_LIT:.>'): | if parents is None:<EOL><INDENT>parents = []<EOL><DEDENT>result = []<EOL>for i, (k, v) in enumerate(root.items()):<EOL><INDENT>parents_i = parents + [k]<EOL>key_i = sep.join(parents_i)<EOL>if isinstance(v, dict):<EOL><INDENT>value_i = flatten_dict(v, parents=parents_i, sep=sep)<EOL>result.extend(value_i)<EOL><DEDENT>el... | Args:
root (dict) : Nested dictionary (e.g., JSON object).
parents (list) : List of ancestor keys.
Returns
-------
list
List of ``(key, value)`` tuples, where ``key`` corresponds to the
ancestor keys of the respective value joined by ``'.'``. For example,
for the item in the dictionary ``{'a': {'... | f5915:m2 |
def get_fields_frame(schema): | fields = []<EOL>def get_field_record(i, key, value, parents):<EOL><INDENT>if value.get('<STR_LIT>') or '<STR_LIT:default>' not in value:<EOL><INDENT>raise Skip<EOL><DEDENT>field = (len(parents) - <NUM_LIT:1>, i, tuple(parents[:-<NUM_LIT:1>]), parents[-<NUM_LIT:1>],<EOL>value['<STR_LIT:type>'], value['<STR_LIT:default>'... | Parameters
----------
schema : dict
`JSON schema <http://spacetelescope.github.io/understanding-json-schema/>`_ | f5915:m4 |
def schema_dialog(schema, data=None, device_name=None, max_width=None,<EOL>max_fps=None, **kwargs): | <EOL>if not device_name and device_name is not None:<EOL><INDENT>dialog = SchemaDialog(schema, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>with nostderr():<EOL><INDENT>import pygst_utils as pu<EOL><DEDENT>gtk.threads_init()<EOL>df_modes = pu.get_available_video_source_configs()<EOL>query = (df_modes.width == df_modes.width... | Parameters
----------
schema : dict
jsonschema definition. Each property *must* have a default value.
device_name : False or None or str or list_like, optional
GStreamer video source device name(s).
If `None` (default), first available video device is used.
If `False`, video is disabled.
max_width : ... | f5915:m8 |
def widget_for(element): | view_type = _view_type_for_element(element)<EOL>if view_type is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % element)<EOL><DEDENT>builder = view_widgets.get(view_type)<EOL>if builder is None:<EOL><INDENT>raise KeyError('<STR_LIT>' % view_type)<EOL><DEDENT>return builder(element)<EOL> | Create a widget for a schema item | f5916:m1 |
def get_first_builder_window(builder): | for obj in builder.get_objects():<EOL><INDENT>if isinstance(obj, gtk.Window):<EOL><INDENT>return obj<EOL><DEDENT><DEDENT> | Get the first toplevel widget in a gtk.Builder hierarchy.
This is mostly used for guessing purposes, and an explicit naming is
always going to be a better situation. | f5917:m0 |
def get_builder_toplevel(self, builder): | raise NotImplementedError<EOL> | Get the toplevel widget from a gtk.Builder file. | f5917:c0:m1 |
def create_ui(self): | Create any UI by hand.
Override to create additional UI here.
This can contain any instance initialization, so for example mutation of
the gtk.Builder generated UI, or creating the UI in its entirety. | f5917:c0:m3 | |
def model_set(self): | This method is called when the model is changed | f5917:c0:m4 | |
def add_slave(self, slave, container_name="<STR_LIT>"): | cont = getattr(self, container_name, None)<EOL>if cont is None:<EOL><INDENT>raise AttributeError(<EOL>'<STR_LIT>')<EOL><DEDENT>cont.add(slave.widget)<EOL>self.slaves.append(slave)<EOL>return slave<EOL> | Add a slave delegate | f5917:c0:m5 |
def show(self): | self.widget.show_all()<EOL> | Call show_all on the toplevel widget | f5917:c0:m6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.