repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
samghelms/mathviz
mathviz_hopper/src/bottle.py
cookie_decode
def cookie_decode(data, key, digestmod=None): """ Verify and decode an encoded string. Return an object or None.""" depr(0, 13, "cookie_decode() will be removed soon.", "Do not use this API directly.") data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1...
python
def cookie_decode(data, key, digestmod=None): """ Verify and decode an encoded string. Return an object or None.""" depr(0, 13, "cookie_decode() will be removed soon.", "Do not use this API directly.") data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1...
[ "def", "cookie_decode", "(", "data", ",", "key", ",", "digestmod", "=", "None", ")", ":", "depr", "(", "0", ",", "13", ",", "\"cookie_decode() will be removed soon.\"", ",", "\"Do not use this API directly.\"", ")", "data", "=", "tob", "(", "data", ")", "if", ...
Verify and decode an encoded string. Return an object or None.
[ "Verify", "and", "decode", "an", "encoded", "string", ".", "Return", "an", "object", "or", "None", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L3052-L3063
train
Verify and decode an encoded string. Return an object or None.
samghelms/mathviz
mathviz_hopper/src/bottle.py
load_app
def load_app(target): """ Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter. """ global NORUN NORUN, nr_old = True, NORUN tmp = defaul...
python
def load_app(target): """ Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter. """ global NORUN NORUN, nr_old = True, NORUN tmp = defaul...
[ "def", "load_app", "(", "target", ")", ":", "global", "NORUN", "NORUN", ",", "nr_old", "=", "True", ",", "NORUN", "tmp", "=", "default_app", ".", "push", "(", ")", "# Create a new \"default application\"", "try", ":", "rv", "=", "load", "(", "target", ")",...
Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter.
[ "Load", "a", "bottle", "application", "from", "a", "module", "and", "make", "sure", "that", "the", "import", "does", "not", "affect", "the", "current", "default", "application", "but", "returns", "a", "separate", "application", "object", ".", "See", ":", "fu...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L3602-L3614
train
Load a bottle application from a module and make sure that the import does not affect the current default application but returns a separate application object.
samghelms/mathviz
mathviz_hopper/src/bottle.py
template
def template(*args, **kwargs): """ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). """ tpl = args[0] if args else None for ...
python
def template(*args, **kwargs): """ Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments). """ tpl = args[0] if args else None for ...
[ "def", "template", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "tpl", "=", "args", "[", "0", "]", "if", "args", "else", "None", "for", "dictarg", "in", "args", "[", "1", ":", "]", ":", "kwargs", ".", "update", "(", "dictarg", ")", "ada...
Get a rendered template as a string iterator. You can use a name, a filename or a template string as first parameter. Template rendering arguments can be passed as dictionaries or directly (as keyword arguments).
[ "Get", "a", "rendered", "template", "as", "a", "string", "iterator", ".", "You", "can", "use", "a", "name", "a", "filename", "or", "a", "template", "string", "as", "first", "parameter", ".", "Template", "rendering", "arguments", "can", "be", "passed", "as"...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L4193-L4217
train
Returns a string iterator that returns a single template string.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Route.get_undecorated_callback
def get_undecorated_callback(self): """ Return the callback. If the callback is a decorated function, try to recover the original function. """ func = self.callback func = getattr(func, '__func__' if py3k else 'im_func', func) closure_attr = '__closure__' if py3k else 'func_c...
python
def get_undecorated_callback(self): """ Return the callback. If the callback is a decorated function, try to recover the original function. """ func = self.callback func = getattr(func, '__func__' if py3k else 'im_func', func) closure_attr = '__closure__' if py3k else 'func_c...
[ "def", "get_undecorated_callback", "(", "self", ")", ":", "func", "=", "self", ".", "callback", "func", "=", "getattr", "(", "func", ",", "'__func__'", "if", "py3k", "else", "'im_func'", ",", "func", ")", "closure_attr", "=", "'__closure__'", "if", "py3k", ...
Return the callback. If the callback is a decorated function, try to recover the original function.
[ "Return", "the", "callback", ".", "If", "the", "callback", "is", "a", "decorated", "function", "try", "to", "recover", "the", "original", "function", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L581-L597
train
Return the original callback.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Route.get_config
def get_config(self, key, default=None): """ Lookup a config field and return its value, first checking the route.config, then route.app.config.""" depr(0, 13, "Route.get_config() is deprectated.", "The Route.config property already includes values from the" ...
python
def get_config(self, key, default=None): """ Lookup a config field and return its value, first checking the route.config, then route.app.config.""" depr(0, 13, "Route.get_config() is deprectated.", "The Route.config property already includes values from the" ...
[ "def", "get_config", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "depr", "(", "0", ",", "13", ",", "\"Route.get_config() is deprectated.\"", ",", "\"The Route.config property already includes values from the\"", "\" application config for missing keys. A...
Lookup a config field and return its value, first checking the route.config, then route.app.config.
[ "Lookup", "a", "config", "field", "and", "return", "its", "value", "first", "checking", "the", "route", ".", "config", "then", "route", ".", "app", ".", "config", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L605-L611
train
Lookup a config field and return its value.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Bottle.mount
def mount(self, prefix, app, **options): """ Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: parent_app.mount('/prefix/', child_app) :param prefix: path prefix or `mount-point`. :param app: an instance of :class:`Bott...
python
def mount(self, prefix, app, **options): """ Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: parent_app.mount('/prefix/', child_app) :param prefix: path prefix or `mount-point`. :param app: an instance of :class:`Bott...
[ "def", "mount", "(", "self", ",", "prefix", ",", "app", ",", "*", "*", "options", ")", ":", "if", "not", "prefix", ".", "startswith", "(", "'/'", ")", ":", "raise", "ValueError", "(", "\"Prefix must start with '/'\"", ")", "if", "isinstance", "(", "app",...
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: parent_app.mount('/prefix/', child_app) :param prefix: path prefix or `mount-point`. :param app: an instance of :class:`Bottle` or a WSGI application. Plugins from ...
[ "Mount", "an", "application", "(", ":", "class", ":", "Bottle", "or", "plain", "WSGI", ")", "to", "a", "specific", "URL", "prefix", ".", "Example", "::" ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L775-L803
train
Mount an application to a specific URL prefix.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Bottle.route
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/<name>') def...
python
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/<name>') def...
[ "def", "route", "(", "self", ",", "path", "=", "None", ",", "method", "=", "'GET'", ",", "callback", "=", "None", ",", "name", "=", "None", ",", "apply", "=", "None", ",", "skip", "=", "None", ",", "*", "*", "config", ")", ":", "if", "callable", ...
A decorator to bind a function to a request URL. Example:: @app.route('/hello/<name>') def hello(name): return 'Hello %s' % name The ``<name>`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path...
[ "A", "decorator", "to", "bind", "a", "function", "to", "a", "request", "URL", ".", "Example", "::" ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L884-L932
train
A decorator to bind a function to a request URL.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Bottle.patch
def patch(self, path=None, method='PATCH', **options): """ Equals :meth:`route` with a ``PATCH`` method parameter. """ return self.route(path, method, **options)
python
def patch(self, path=None, method='PATCH', **options): """ Equals :meth:`route` with a ``PATCH`` method parameter. """ return self.route(path, method, **options)
[ "def", "patch", "(", "self", ",", "path", "=", "None", ",", "method", "=", "'PATCH'", ",", "*", "*", "options", ")", ":", "return", "self", ".", "route", "(", "path", ",", "method", ",", "*", "*", "options", ")" ]
Equals :meth:`route` with a ``PATCH`` method parameter.
[ "Equals", ":", "meth", ":", "route", "with", "a", "PATCH", "method", "parameter", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L950-L952
train
Equals : meth. route with a PATCH method parameter.
samghelms/mathviz
mathviz_hopper/src/bottle.py
Bottle.error
def error(self, code=500, callback=None): """ Register an output handler for a HTTP error code. Can be used as a decorator or called directly :: def error_handler_500(error): return 'error_handler_500' app.error(code=500, callback=error_handler_5...
python
def error(self, code=500, callback=None): """ Register an output handler for a HTTP error code. Can be used as a decorator or called directly :: def error_handler_500(error): return 'error_handler_500' app.error(code=500, callback=error_handler_5...
[ "def", "error", "(", "self", ",", "code", "=", "500", ",", "callback", "=", "None", ")", ":", "def", "decorator", "(", "callback", ")", ":", "if", "isinstance", "(", "callback", ",", "basestring", ")", ":", "callback", "=", "load", "(", "callback", "...
Register an output handler for a HTTP error code. Can be used as a decorator or called directly :: def error_handler_500(error): return 'error_handler_500' app.error(code=500, callback=error_handler_500) @app.error(404) d...
[ "Register", "an", "output", "handler", "for", "a", "HTTP", "error", "code", ".", "Can", "be", "used", "as", "a", "decorator", "or", "called", "directly", "::" ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L954-L974
train
Register an output handler for an HTTP error code.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseRequest.get_cookie
def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cook...
python
def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cook...
[ "def", "get_cookie", "(", "self", ",", "key", ",", "default", "=", "None", ",", "secret", "=", "None", ",", "digestmod", "=", "hashlib", ".", "sha256", ")", ":", "value", "=", "self", ".", "cookies", ".", "get", "(", "key", ")", "if", "secret", ":"...
Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.
[ "Return", "the", "content", "of", "a", "cookie", ".", "To", "read", "a", "Signed", "Cookie", "the", "secret", "must", "match", "the", "one", "used", "to", "create", "the", "cookie", "(", "see", ":", "meth", ":", "BaseResponse", ".", "set_cookie", ")", ...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1215-L1231
train
Get the content of a cookie.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseRequest.json
def json(self): """ If the ``Content-Type`` header is ``application/json`` or ``application/json-rpc``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. Invalid JSO...
python
def json(self): """ If the ``Content-Type`` header is ``application/json`` or ``application/json-rpc``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. Invalid JSO...
[ "def", "json", "(", "self", ")", ":", "ctype", "=", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ".", "lower", "(", ")", ".", "split", "(", "';'", ")", "[", "0", "]", "if", "ctype", "in", "(", "'application/json'", "...
If the ``Content-Type`` header is ``application/json`` or ``application/json-rpc``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. Invalid JSON raises a 400 error respons...
[ "If", "the", "Content", "-", "Type", "header", "is", "application", "/", "json", "or", "application", "/", "json", "-", "rpc", "this", "property", "holds", "the", "parsed", "content", "of", "the", "request", "body", ".", "Only", "requests", "smaller", "tha...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1281-L1297
train
Returns the JSON object of the content of the request.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseRequest.path_shift
def path_shift(self, shift=1): """ Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) """ script, path = path...
python
def path_shift(self, shift=1): """ Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) """ script, path = path...
[ "def", "path_shift", "(", "self", ",", "shift", "=", "1", ")", ":", "script", ",", "path", "=", "path_shift", "(", "self", ".", "environ", ".", "get", "(", "'SCRIPT_NAME'", ",", "'/'", ")", ",", "self", ".", "path", ",", "shift", ")", "self", "[", ...
Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1)
[ "Shift", "path", "segments", "from", ":", "attr", ":", "path", "to", ":", "attr", ":", "script_name", "and", "vice", "versa", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1467-L1475
train
Shift path segments from the path to the script_name and vice versa.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseResponse.set_header
def set_header(self, name, value): """ Create a new response header, replacing any previously defined headers with the same name. """ self._headers[_hkey(name)] = [_hval(value)]
python
def set_header(self, name, value): """ Create a new response header, replacing any previously defined headers with the same name. """ self._headers[_hkey(name)] = [_hval(value)]
[ "def", "set_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", "[", "_hkey", "(", "name", ")", "]", "=", "[", "_hval", "(", "value", ")", "]" ]
Create a new response header, replacing any previously defined headers with the same name.
[ "Create", "a", "new", "response", "header", "replacing", "any", "previously", "defined", "headers", "with", "the", "same", "name", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1751-L1754
train
Create a new response header with the given name and value.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseResponse.add_header
def add_header(self, name, value): """ Add an additional response header, not removing duplicates. """ self._headers.setdefault(_hkey(name), []).append(_hval(value))
python
def add_header(self, name, value): """ Add an additional response header, not removing duplicates. """ self._headers.setdefault(_hkey(name), []).append(_hval(value))
[ "def", "add_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", ".", "setdefault", "(", "_hkey", "(", "name", ")", ",", "[", "]", ")", ".", "append", "(", "_hval", "(", "value", ")", ")" ]
Add an additional response header, not removing duplicates.
[ "Add", "an", "additional", "response", "header", "not", "removing", "duplicates", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1756-L1758
train
Add an additional response header.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseResponse.headerlist
def headerlist(self): """ WSGI conform list of (header, value) tuples. """ out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: ...
python
def headerlist(self): """ WSGI conform list of (header, value) tuples. """ out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: ...
[ "def", "headerlist", "(", "self", ")", ":", "out", "=", "[", "]", "headers", "=", "list", "(", "self", ".", "_headers", ".", "items", "(", ")", ")", "if", "'Content-Type'", "not", "in", "self", ".", "_headers", ":", "headers", ".", "append", "(", "...
WSGI conform list of (header, value) tuples.
[ "WSGI", "conform", "list", "of", "(", "header", "value", ")", "tuples", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1766-L1781
train
WSGI conform list of ( header value ) tuples.
samghelms/mathviz
mathviz_hopper/src/bottle.py
BaseResponse.set_cookie
def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options): """ Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of t...
python
def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options): """ Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of t...
[ "def", "set_cookie", "(", "self", ",", "name", ",", "value", ",", "secret", "=", "None", ",", "digestmod", "=", "hashlib", ".", "sha256", ",", "*", "*", "options", ")", ":", "if", "not", "self", ".", "_cookies", ":", "self", ".", "_cookies", "=", "...
Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. A...
[ "Create", "a", "new", "cookie", "or", "replace", "an", "old", "one", ".", "If", "the", "secret", "parameter", "is", "set", "create", "a", "Signed", "Cookie", "(", "described", "below", ")", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L1797-L1878
train
Create a new cookie or replace an existing one.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict.load_module
def load_module(self, path, squash=True): """Load values from a Python module. Example modue ``config.py``:: DEBUG = True SQLITE = { "db": ":memory:" } >>> c = ConfigDict() >>> c.load_module('config') ...
python
def load_module(self, path, squash=True): """Load values from a Python module. Example modue ``config.py``:: DEBUG = True SQLITE = { "db": ":memory:" } >>> c = ConfigDict() >>> c.load_module('config') ...
[ "def", "load_module", "(", "self", ",", "path", ",", "squash", "=", "True", ")", ":", "config_obj", "=", "load", "(", "path", ")", "obj", "=", "{", "key", ":", "getattr", "(", "config_obj", ",", "key", ")", "for", "key", "in", "dir", "(", "config_o...
Load values from a Python module. Example modue ``config.py``:: DEBUG = True SQLITE = { "db": ":memory:" } >>> c = ConfigDict() >>> c.load_module('config') {DEBUG: True, 'SQLITE.DB': 'memory'} ...
[ "Load", "values", "from", "a", "Python", "module", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2341-L2369
train
Load values from a Python module.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict.load_config
def load_config(self, filename, **options): """ Load values from an ``*.ini`` style config file. A configuration file consists of sections, each led by a ``[section]`` header, followed by key/value entries separated by either ``=`` or ``:``. Section names and keys are case-i...
python
def load_config(self, filename, **options): """ Load values from an ``*.ini`` style config file. A configuration file consists of sections, each led by a ``[section]`` header, followed by key/value entries separated by either ``=`` or ``:``. Section names and keys are case-i...
[ "def", "load_config", "(", "self", ",", "filename", ",", "*", "*", "options", ")", ":", "options", ".", "setdefault", "(", "'allow_no_value'", ",", "True", ")", "if", "py3k", ":", "options", ".", "setdefault", "(", "'interpolation'", ",", "configparser", "...
Load values from an ``*.ini`` style config file. A configuration file consists of sections, each led by a ``[section]`` header, followed by key/value entries separated by either ``=`` or ``:``. Section names and keys are case-insensitive. Leading and trailing whitespace ...
[ "Load", "values", "from", "an", "*", ".", "ini", "style", "config", "file", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2371-L2412
train
Load values from an. ini style config file.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict.update
def update(self, *a, **ka): """ If the first parameter is a string, all keys are prefixed with this namespace. Apart from that it works just as the usual dict.update(). >>> c = ConfigDict() >>> c.update('some.namespace', key='value') """ prefix = '' i...
python
def update(self, *a, **ka): """ If the first parameter is a string, all keys are prefixed with this namespace. Apart from that it works just as the usual dict.update(). >>> c = ConfigDict() >>> c.update('some.namespace', key='value') """ prefix = '' i...
[ "def", "update", "(", "self", ",", "*", "a", ",", "*", "*", "ka", ")", ":", "prefix", "=", "''", "if", "a", "and", "isinstance", "(", "a", "[", "0", "]", ",", "basestring", ")", ":", "prefix", "=", "a", "[", "0", "]", ".", "strip", "(", "'....
If the first parameter is a string, all keys are prefixed with this namespace. Apart from that it works just as the usual dict.update(). >>> c = ConfigDict() >>> c.update('some.namespace', key='value')
[ "If", "the", "first", "parameter", "is", "a", "string", "all", "keys", "are", "prefixed", "with", "this", "namespace", ".", "Apart", "from", "that", "it", "works", "just", "as", "the", "usual", "dict", ".", "update", "()", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2433-L2445
train
Update the dictionary with the keys from a dictionary.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict._set_virtual
def _set_virtual(self, key, value): """ Recursively set or update virtual keys. Do nothing if non-virtual value is present. """ if key in self and key not in self._virtual_keys: return # Do nothing for non-virtual keys. self._virtual_keys.add(key) if key in self...
python
def _set_virtual(self, key, value): """ Recursively set or update virtual keys. Do nothing if non-virtual value is present. """ if key in self and key not in self._virtual_keys: return # Do nothing for non-virtual keys. self._virtual_keys.add(key) if key in self...
[ "def", "_set_virtual", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", "and", "key", "not", "in", "self", ".", "_virtual_keys", ":", "return", "# Do nothing for non-virtual keys.", "self", ".", "_virtual_keys", ".", "add", "(", ...
Recursively set or update virtual keys. Do nothing if non-virtual value is present.
[ "Recursively", "set", "or", "update", "virtual", "keys", ".", "Do", "nothing", "if", "non", "-", "virtual", "value", "is", "present", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2484-L2495
train
Recursively set or update virtual keys.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict._delete_virtual
def _delete_virtual(self, key): """ Recursively delete virtual entry. Do nothing if key is not virtual. """ if key not in self._virtual_keys: return # Do nothing for non-virtual keys. if key in self: self._on_change(key, None) dict.__delitem__(self, key)...
python
def _delete_virtual(self, key): """ Recursively delete virtual entry. Do nothing if key is not virtual. """ if key not in self._virtual_keys: return # Do nothing for non-virtual keys. if key in self: self._on_change(key, None) dict.__delitem__(self, key)...
[ "def", "_delete_virtual", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "_virtual_keys", ":", "return", "# Do nothing for non-virtual keys.", "if", "key", "in", "self", ":", "self", ".", "_on_change", "(", "key", ",", "None", ")...
Recursively delete virtual entry. Do nothing if key is not virtual.
[ "Recursively", "delete", "virtual", "entry", ".", "Do", "nothing", "if", "key", "is", "not", "virtual", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2497-L2508
train
Recursively delete virtual entry.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict.meta_set
def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. """ self._meta.setdefault(key, {})[metafield] = value
python
def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. """ self._meta.setdefault(key, {})[metafield] = value
[ "def", "meta_set", "(", "self", ",", "key", ",", "metafield", ",", "value", ")", ":", "self", ".", "_meta", ".", "setdefault", "(", "key", ",", "{", "}", ")", "[", "metafield", "]", "=", "value" ]
Set the meta field for a key to a new value.
[ "Set", "the", "meta", "field", "for", "a", "key", "to", "a", "new", "value", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2523-L2525
train
Set the meta field for a key to a new value.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict._define
def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET): """ (Unstable) Shortcut for plugins to define own config parameters. """ if default is not _UNSET: self.setdefault(key, default) if help is not _UNSET: self.meta_set(key, 'help', help) if valida...
python
def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET): """ (Unstable) Shortcut for plugins to define own config parameters. """ if default is not _UNSET: self.setdefault(key, default) if help is not _UNSET: self.meta_set(key, 'help', help) if valida...
[ "def", "_define", "(", "self", ",", "key", ",", "default", "=", "_UNSET", ",", "help", "=", "_UNSET", ",", "validate", "=", "_UNSET", ")", ":", "if", "default", "is", "not", "_UNSET", ":", "self", ".", "setdefault", "(", "key", ",", "default", ")", ...
(Unstable) Shortcut for plugins to define own config parameters.
[ "(", "Unstable", ")", "Shortcut", "for", "plugins", "to", "define", "own", "config", "parameters", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2531-L2538
train
Shortcut for plugins to define own config parameters.
samghelms/mathviz
mathviz_hopper/src/bottle.py
ConfigDict._make_overlay
def _make_overlay(self): """ (Unstable) Create a new overlay that acts like a chained map: Values missing in the overlay are copied from the source map. Both maps share the same meta entries. Entries that were copied from the source are called 'virtual'. You can ...
python
def _make_overlay(self): """ (Unstable) Create a new overlay that acts like a chained map: Values missing in the overlay are copied from the source map. Both maps share the same meta entries. Entries that were copied from the source are called 'virtual'. You can ...
[ "def", "_make_overlay", "(", "self", ")", ":", "# Cleanup dead references", "self", ".", "_overlays", "[", ":", "]", "=", "[", "ref", "for", "ref", "in", "self", ".", "_overlays", "if", "ref", "(", ")", "is", "not", "None", "]", "overlay", "=", "Config...
(Unstable) Create a new overlay that acts like a chained map: Values missing in the overlay are copied from the source map. Both maps share the same meta entries. Entries that were copied from the source are called 'virtual'. You can not delete virtual keys, but overwrit...
[ "(", "Unstable", ")", "Create", "a", "new", "overlay", "that", "acts", "like", "a", "chained", "map", ":", "Values", "missing", "in", "the", "overlay", "are", "copied", "from", "the", "source", "map", ".", "Both", "maps", "share", "the", "same", "meta", ...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2546-L2579
train
Create a new overlay that acts like a chained map.
samghelms/mathviz
mathviz_hopper/src/bottle.py
FileUpload.filename
def filename(self): """ Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as 'empty'. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, ...
python
def filename(self): """ Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as 'empty'. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, ...
[ "def", "filename", "(", "self", ")", ":", "fname", "=", "self", ".", "raw_filename", "if", "not", "isinstance", "(", "fname", ",", "unicode", ")", ":", "fname", "=", "fname", ".", "decode", "(", "'utf8'", ",", "'ignore'", ")", "fname", "=", "normalize"...
Name of the file on the client file system, but normalized to ensure file system compatibility. An empty filename is returned as 'empty'. Only ASCII letters, digits, dashes, underscores and dots are allowed in the final filename. Accents are removed, if possible. Whitesp...
[ "Name", "of", "the", "file", "on", "the", "client", "file", "system", "but", "normalized", "to", "ensure", "file", "system", "compatibility", ".", "An", "empty", "filename", "is", "returned", "as", "empty", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2743-L2760
train
Returns the name of the file on the client file system.
BernardFW/bernard
src/bernard/i18n/translator.py
serialize
def serialize(text: TransText): """ Takes as input either a string to translate either an actual string and transforms it into a JSON-serializable structure that can be reconstructed using `unserialize()`. """ if isinstance(text, str): return { 'type': 'string', ...
python
def serialize(text: TransText): """ Takes as input either a string to translate either an actual string and transforms it into a JSON-serializable structure that can be reconstructed using `unserialize()`. """ if isinstance(text, str): return { 'type': 'string', ...
[ "def", "serialize", "(", "text", ":", "TransText", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "return", "{", "'type'", ":", "'string'", ",", "'value'", ":", "text", ",", "}", "elif", "isinstance", "(", "text", ",", "StringToTransl...
Takes as input either a string to translate either an actual string and transforms it into a JSON-serializable structure that can be reconstructed using `unserialize()`.
[ "Takes", "as", "input", "either", "a", "string", "to", "translate", "either", "an", "actual", "string", "and", "transforms", "it", "into", "a", "JSON", "-", "serializable", "structure", "that", "can", "be", "reconstructed", "using", "unserialize", "()", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L550-L571
train
Takes as input either a string to translate either an actual string and transforms it into a JSON - serializable structure that can be reconstructed using deserialize.
BernardFW/bernard
src/bernard/i18n/translator.py
unserialize
def unserialize(wd: WordDictionary, text: Dict): """ Transforms back a serialized value of `serialize()` """ if not isinstance(text, Mapping): raise ValueError('Text has not the right format') try: t = text['type'] if t == 'string': return text['value'] ...
python
def unserialize(wd: WordDictionary, text: Dict): """ Transforms back a serialized value of `serialize()` """ if not isinstance(text, Mapping): raise ValueError('Text has not the right format') try: t = text['type'] if t == 'string': return text['value'] ...
[ "def", "unserialize", "(", "wd", ":", "WordDictionary", ",", "text", ":", "Dict", ")", ":", "if", "not", "isinstance", "(", "text", ",", "Mapping", ")", ":", "raise", "ValueError", "(", "'Text has not the right format'", ")", "try", ":", "t", "=", "text", ...
Transforms back a serialized value of `serialize()`
[ "Transforms", "back", "a", "serialized", "value", "of", "serialize", "()" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L574-L604
train
Unserializes a serialized value of a WordDictionary into a string.
BernardFW/bernard
src/bernard/i18n/translator.py
render
async def render( text: TransText, request: Optional['Request'], multi_line=False) -> Union[Text, List[Text]]: """ Render either a normal string either a string to translate into an actual string for the specified request. """ if isinstance(text, str): out = [text] ...
python
async def render( text: TransText, request: Optional['Request'], multi_line=False) -> Union[Text, List[Text]]: """ Render either a normal string either a string to translate into an actual string for the specified request. """ if isinstance(text, str): out = [text] ...
[ "async", "def", "render", "(", "text", ":", "TransText", ",", "request", ":", "Optional", "[", "'Request'", "]", ",", "multi_line", "=", "False", ")", "->", "Union", "[", "Text", ",", "List", "[", "Text", "]", "]", ":", "if", "isinstance", "(", "text...
Render either a normal string either a string to translate into an actual string for the specified request.
[ "Render", "either", "a", "normal", "string", "either", "a", "string", "to", "translate", "into", "an", "actual", "string", "for", "the", "specified", "request", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L607-L626
train
Render the given text into a list of strings.
BernardFW/bernard
src/bernard/i18n/translator.py
TransItem.score
def score(self, flags: Flags) -> int: """ Counts how many of the flags can be matched """ score = 0 for k, v in flags.items(): if self.flags.get(k) == v: score += 1 return score
python
def score(self, flags: Flags) -> int: """ Counts how many of the flags can be matched """ score = 0 for k, v in flags.items(): if self.flags.get(k) == v: score += 1 return score
[ "def", "score", "(", "self", ",", "flags", ":", "Flags", ")", "->", "int", ":", "score", "=", "0", "for", "k", ",", "v", "in", "flags", ".", "items", "(", ")", ":", "if", "self", ".", "flags", ".", "get", "(", "k", ")", "==", "v", ":", "sco...
Counts how many of the flags can be matched
[ "Counts", "how", "many", "of", "the", "flags", "can", "be", "matched" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L97-L108
train
Returns the score of the flags that can be matched.
BernardFW/bernard
src/bernard/i18n/translator.py
Sentence.best_for_flags
def best_for_flags(self, flags: Flags) -> List[TransItem]: """ Given `flags`, find all items of this sentence that have an equal matching score and put them in a list. """ best_score: int = 0 best_list: List[TransItem] = [] for item in self.items: sc...
python
def best_for_flags(self, flags: Flags) -> List[TransItem]: """ Given `flags`, find all items of this sentence that have an equal matching score and put them in a list. """ best_score: int = 0 best_list: List[TransItem] = [] for item in self.items: sc...
[ "def", "best_for_flags", "(", "self", ",", "flags", ":", "Flags", ")", "->", "List", "[", "TransItem", "]", ":", "best_score", ":", "int", "=", "0", "best_list", ":", "List", "[", "TransItem", "]", "=", "[", "]", "for", "item", "in", "self", ".", "...
Given `flags`, find all items of this sentence that have an equal matching score and put them in a list.
[ "Given", "flags", "find", "all", "items", "of", "this", "sentence", "that", "have", "an", "equal", "matching", "score", "and", "put", "them", "in", "a", "list", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L120-L138
train
Given a list of flags find all items that have a score greater than or equal to the given flags and put them in a list.
BernardFW/bernard
src/bernard/i18n/translator.py
Sentence.render
def render(self, flags: Flags) -> Text: """ Chooses a random sentence from the list and returns it. """ return random.choice(self.best_for_flags(flags)).value
python
def render(self, flags: Flags) -> Text: """ Chooses a random sentence from the list and returns it. """ return random.choice(self.best_for_flags(flags)).value
[ "def", "render", "(", "self", ",", "flags", ":", "Flags", ")", "->", "Text", ":", "return", "random", ".", "choice", "(", "self", ".", "best_for_flags", "(", "flags", ")", ")", ".", "value" ]
Chooses a random sentence from the list and returns it.
[ "Chooses", "a", "random", "sentence", "from", "the", "list", "and", "returns", "it", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L140-L144
train
Renders a random tag from the list and returns it.
BernardFW/bernard
src/bernard/i18n/translator.py
Sentence.update
def update(self, new: 'Sentence', flags: Flags): """ Erase items with the specified flags and insert the new items from the other sentence instead. """ items = [i for i in self.items if i.flags != flags] items.extend(new.items) self.items = items
python
def update(self, new: 'Sentence', flags: Flags): """ Erase items with the specified flags and insert the new items from the other sentence instead. """ items = [i for i in self.items if i.flags != flags] items.extend(new.items) self.items = items
[ "def", "update", "(", "self", ",", "new", ":", "'Sentence'", ",", "flags", ":", "Flags", ")", ":", "items", "=", "[", "i", "for", "i", "in", "self", ".", "items", "if", "i", ".", "flags", "!=", "flags", "]", "items", ".", "extend", "(", "new", ...
Erase items with the specified flags and insert the new items from the other sentence instead.
[ "Erase", "items", "with", "the", "specified", "flags", "and", "insert", "the", "new", "items", "from", "the", "other", "sentence", "instead", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L159-L167
train
Update the items of the current set with the new sentence.
BernardFW/bernard
src/bernard/i18n/translator.py
SentenceGroup.render
def render(self, flags: Flags) -> List[Text]: """ Returns a list of randomly chosen outcomes for each sentence of the list. """ return [x.render(flags) for x in self.sentences]
python
def render(self, flags: Flags) -> List[Text]: """ Returns a list of randomly chosen outcomes for each sentence of the list. """ return [x.render(flags) for x in self.sentences]
[ "def", "render", "(", "self", ",", "flags", ":", "Flags", ")", "->", "List", "[", "Text", "]", ":", "return", "[", "x", ".", "render", "(", "flags", ")", "for", "x", "in", "self", ".", "sentences", "]" ]
Returns a list of randomly chosen outcomes for each sentence of the list.
[ "Returns", "a", "list", "of", "randomly", "chosen", "outcomes", "for", "each", "sentence", "of", "the", "list", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L185-L190
train
Returns a list of random outcomes for each sentence of the list.
BernardFW/bernard
src/bernard/i18n/translator.py
SentenceGroup.append
def append(self, item: TransItem): """ Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent. """ if not (1 <= item.index <= settings.I18N_MAX_SENTE...
python
def append(self, item: TransItem): """ Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent. """ if not (1 <= item.index <= settings.I18N_MAX_SENTE...
[ "def", "append", "(", "self", ",", "item", ":", "TransItem", ")", ":", "if", "not", "(", "1", "<=", "item", ".", "index", "<=", "settings", ".", "I18N_MAX_SENTENCES_PER_GROUP", ")", ":", "return", "if", "len", "(", "self", ".", "sentences", ")", "<", ...
Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent.
[ "Append", "an", "item", "to", "the", "list", ".", "If", "there", "is", "not", "enough", "sentences", "in", "the", "list", "then", "the", "list", "is", "extended", "as", "needed", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L192-L207
train
Append an item to the list.
BernardFW/bernard
src/bernard/i18n/translator.py
SentenceGroup.update
def update(self, group: 'SentenceGroup', flags: Flags) -> None: """ This object is considered to be a "global" sentence group while the other one is flags-specific. All data related to the specified flags will be overwritten by the content of the specified group. """ to_...
python
def update(self, group: 'SentenceGroup', flags: Flags) -> None: """ This object is considered to be a "global" sentence group while the other one is flags-specific. All data related to the specified flags will be overwritten by the content of the specified group. """ to_...
[ "def", "update", "(", "self", ",", "group", ":", "'SentenceGroup'", ",", "flags", ":", "Flags", ")", "->", "None", ":", "to_append", "=", "[", "]", "for", "old", ",", "new", "in", "zip_longest", "(", "self", ".", "sentences", ",", "group", ".", "sent...
This object is considered to be a "global" sentence group while the other one is flags-specific. All data related to the specified flags will be overwritten by the content of the specified group.
[ "This", "object", "is", "considered", "to", "be", "a", "global", "sentence", "group", "while", "the", "other", "one", "is", "flags", "-", "specific", ".", "All", "data", "related", "to", "the", "specified", "flags", "will", "be", "overwritten", "by", "the"...
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L212-L231
train
Updates the internal list of sentences related to the specified group.
BernardFW/bernard
src/bernard/i18n/translator.py
SortingDict.extract
def extract(self): """ Extract only the valid sentence groups into a dictionary. """ out = {} for key, group in self.data.items(): out[key] = group return out
python
def extract(self): """ Extract only the valid sentence groups into a dictionary. """ out = {} for key, group in self.data.items(): out[key] = group return out
[ "def", "extract", "(", "self", ")", ":", "out", "=", "{", "}", "for", "key", ",", "group", "in", "self", ".", "data", ".", "items", "(", ")", ":", "out", "[", "key", "]", "=", "group", "return", "out" ]
Extract only the valid sentence groups into a dictionary.
[ "Extract", "only", "the", "valid", "sentence", "groups", "into", "a", "dictionary", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L245-L255
train
Extract only the valid sentence groups into a dictionary.
BernardFW/bernard
src/bernard/i18n/translator.py
SortingDict.append
def append(self, item: TransItem): """ Append an item to the internal dictionary. """ self.data[item.key].append(item)
python
def append(self, item: TransItem): """ Append an item to the internal dictionary. """ self.data[item.key].append(item)
[ "def", "append", "(", "self", ",", "item", ":", "TransItem", ")", ":", "self", ".", "data", "[", "item", ".", "key", "]", ".", "append", "(", "item", ")" ]
Append an item to the internal dictionary.
[ "Append", "an", "item", "to", "the", "internal", "dictionary", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L257-L262
train
Append an item to the internal dictionary.
BernardFW/bernard
src/bernard/i18n/translator.py
WordDictionary._init_loaders
def _init_loaders(self) -> None: """ This creates the loaders instances and subscribes to their updates. """ for loader in settings.I18N_TRANSLATION_LOADERS: loader_class = import_class(loader['loader']) instance = loader_class() instance.on_update(se...
python
def _init_loaders(self) -> None: """ This creates the loaders instances and subscribes to their updates. """ for loader in settings.I18N_TRANSLATION_LOADERS: loader_class = import_class(loader['loader']) instance = loader_class() instance.on_update(se...
[ "def", "_init_loaders", "(", "self", ")", "->", "None", ":", "for", "loader", "in", "settings", ".", "I18N_TRANSLATION_LOADERS", ":", "loader_class", "=", "import_class", "(", "loader", "[", "'loader'", "]", ")", "instance", "=", "loader_class", "(", ")", "i...
This creates the loaders instances and subscribes to their updates.
[ "This", "creates", "the", "loaders", "instances", "and", "subscribes", "to", "their", "updates", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L276-L285
train
This creates the loaders instances and subscribes to their updates.
BernardFW/bernard
src/bernard/i18n/translator.py
WordDictionary.parse_item
def parse_item(self, key, value, flags: Flags) -> Optional[TransItem]: """ Parse an item (and more specifically its key). """ parts = key.split('+') pure_key = parts[0] try: if len(parts) == 2: index = int(parts[1]) elif len(parts...
python
def parse_item(self, key, value, flags: Flags) -> Optional[TransItem]: """ Parse an item (and more specifically its key). """ parts = key.split('+') pure_key = parts[0] try: if len(parts) == 2: index = int(parts[1]) elif len(parts...
[ "def", "parse_item", "(", "self", ",", "key", ",", "value", ",", "flags", ":", "Flags", ")", "->", "Optional", "[", "TransItem", "]", ":", "parts", "=", "key", ".", "split", "(", "'+'", ")", "pure_key", "=", "parts", "[", "0", "]", "try", ":", "i...
Parse an item (and more specifically its key).
[ "Parse", "an", "item", "(", "and", "more", "specifically", "its", "key", ")", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L287-L313
train
Parses an item and returns the TransItem object.
BernardFW/bernard
src/bernard/i18n/translator.py
WordDictionary.update_lang
def update_lang(self, lang: Optional[Text], data: List[Tuple[Text, Text]], flags: Flags): """ Update translations for one specific lang """ sd = SortingDict() for item in (self.parse_item(x[0], x[1], flags) for x in da...
python
def update_lang(self, lang: Optional[Text], data: List[Tuple[Text, Text]], flags: Flags): """ Update translations for one specific lang """ sd = SortingDict() for item in (self.parse_item(x[0], x[1], flags) for x in da...
[ "def", "update_lang", "(", "self", ",", "lang", ":", "Optional", "[", "Text", "]", ",", "data", ":", "List", "[", "Tuple", "[", "Text", ",", "Text", "]", "]", ",", "flags", ":", "Flags", ")", ":", "sd", "=", "SortingDict", "(", ")", "for", "item"...
Update translations for one specific lang
[ "Update", "translations", "for", "one", "specific", "lang" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L315-L338
train
Update translations for one specific lang
BernardFW/bernard
src/bernard/i18n/translator.py
WordDictionary.update
def update(self, data: TransDict, flags: Flags): """ Update all langs at once """ for lang, lang_data in data.items(): self.update_lang(lang, lang_data, flags)
python
def update(self, data: TransDict, flags: Flags): """ Update all langs at once """ for lang, lang_data in data.items(): self.update_lang(lang, lang_data, flags)
[ "def", "update", "(", "self", ",", "data", ":", "TransDict", ",", "flags", ":", "Flags", ")", ":", "for", "lang", ",", "lang_data", "in", "data", ".", "items", "(", ")", ":", "self", ".", "update_lang", "(", "lang", ",", "lang_data", ",", "flags", ...
Update all langs at once
[ "Update", "all", "langs", "at", "once" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L340-L346
train
Update all langs at once
BernardFW/bernard
src/bernard/i18n/translator.py
WordDictionary.get
def get(self, key: Text, count: Optional[int]=None, formatter: Formatter=None, locale: Text=None, params: Optional[Dict[Text, Any]]=None, flags: Optional[Flags]=None) -> List[Text]: """ Get the appropriate translation given the spec...
python
def get(self, key: Text, count: Optional[int]=None, formatter: Formatter=None, locale: Text=None, params: Optional[Dict[Text, Any]]=None, flags: Optional[Flags]=None) -> List[Text]: """ Get the appropriate translation given the spec...
[ "def", "get", "(", "self", ",", "key", ":", "Text", ",", "count", ":", "Optional", "[", "int", "]", "=", "None", ",", "formatter", ":", "Formatter", "=", "None", ",", "locale", ":", "Text", "=", "None", ",", "params", ":", "Optional", "[", "Dict", ...
Get the appropriate translation given the specified parameters. :param key: Translation key :param count: Count for plurals :param formatter: Optional string formatter to use :param locale: Prefered locale to get the string from :param params: Params to be substituted :p...
[ "Get", "the", "appropriate", "translation", "given", "the", "specified", "parameters", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L348-L395
train
Get the appropriate translation for a specific key.
BernardFW/bernard
src/bernard/i18n/translator.py
StringToTranslate._resolve_params
async def _resolve_params(self, params: Dict[Text, Any], request: Optional['Request']): """ If any StringToTranslate was passed as parameter then it is rendered at this moment. """ out = {} for k, v in params.i...
python
async def _resolve_params(self, params: Dict[Text, Any], request: Optional['Request']): """ If any StringToTranslate was passed as parameter then it is rendered at this moment. """ out = {} for k, v in params.i...
[ "async", "def", "_resolve_params", "(", "self", ",", "params", ":", "Dict", "[", "Text", ",", "Any", "]", ",", "request", ":", "Optional", "[", "'Request'", "]", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "params", ".", "items", ...
If any StringToTranslate was passed as parameter then it is rendered at this moment.
[ "If", "any", "StringToTranslate", "was", "passed", "as", "parameter", "then", "it", "is", "rendered", "at", "this", "moment", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L436-L452
train
Resolves the parameters of the object.
BernardFW/bernard
src/bernard/i18n/translator.py
StringToTranslate.render_list
async def render_list(self, request=None) -> List[Text]: """ Render the translation as a list if there is multiple strings for this single key. :param request: Bot request. """ from bernard.middleware import MiddlewareManager if request: tz = await r...
python
async def render_list(self, request=None) -> List[Text]: """ Render the translation as a list if there is multiple strings for this single key. :param request: Bot request. """ from bernard.middleware import MiddlewareManager if request: tz = await r...
[ "async", "def", "render_list", "(", "self", ",", "request", "=", "None", ")", "->", "List", "[", "Text", "]", ":", "from", "bernard", ".", "middleware", "import", "MiddlewareManager", "if", "request", ":", "tz", "=", "await", "request", ".", "user", ".",...
Render the translation as a list if there is multiple strings for this single key. :param request: Bot request.
[ "Render", "the", "translation", "as", "a", "list", "if", "there", "is", "multiple", "strings", "for", "this", "single", "key", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L466-L497
train
Render the translation as a list if there is multiple strings for this single key.
openvax/varlens
varlens/read_source.py
read_key
def read_key(pysam_alignment_record): ''' Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments. ''' return ( pysam_alignment_record....
python
def read_key(pysam_alignment_record): ''' Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments. ''' return ( pysam_alignment_record....
[ "def", "read_key", "(", "pysam_alignment_record", ")", ":", "return", "(", "pysam_alignment_record", ".", "query_name", ",", "pysam_alignment_record", ".", "is_duplicate", ",", "pysam_alignment_record", ".", "is_read1", ",", "pysam_alignment_record", ".", "is_read2", ",...
Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments.
[ "Given", "a", "pysam", ".", "AlignedSegment", "instance", "return", "the", "attributes", "identifying", "the", "*", "read", "*", "it", "comes", "from", "(", "not", "the", "alignment", ")", ".", "There", "may", "be", "more", "than", "one", "alignment", "for...
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_source.py#L128-L139
train
Given a pysam. AlignedSegment instance return the attributes identifying the read it comes from.
BernardFW/bernard
src/bernard/engine/responder.py
Responder.send
def send(self, stack: Layers): """ Add a message stack to the send list. """ if not isinstance(stack, Stack): stack = Stack(stack) if not self.platform.accept(stack): raise UnacceptableStack('The platform does not allow "{}"' ...
python
def send(self, stack: Layers): """ Add a message stack to the send list. """ if not isinstance(stack, Stack): stack = Stack(stack) if not self.platform.accept(stack): raise UnacceptableStack('The platform does not allow "{}"' ...
[ "def", "send", "(", "self", ",", "stack", ":", "Layers", ")", ":", "if", "not", "isinstance", "(", "stack", ",", "Stack", ")", ":", "stack", "=", "Stack", "(", "stack", ")", "if", "not", "self", ".", "platform", ".", "accept", "(", "stack", ")", ...
Add a message stack to the send list.
[ "Add", "a", "message", "stack", "to", "the", "send", "list", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/responder.py#L46-L58
train
Adds a message stack to the send list.
BernardFW/bernard
src/bernard/engine/responder.py
Responder.flush
async def flush(self, request: 'Request'): """ Send all queued messages. The first step is to convert all media in the stacked layers then the second step is to send all messages as grouped in time as possible. """ from bernard.middleware import MiddlewareManager ...
python
async def flush(self, request: 'Request'): """ Send all queued messages. The first step is to convert all media in the stacked layers then the second step is to send all messages as grouped in time as possible. """ from bernard.middleware import MiddlewareManager ...
[ "async", "def", "flush", "(", "self", ",", "request", ":", "'Request'", ")", ":", "from", "bernard", ".", "middleware", "import", "MiddlewareManager", "for", "stack", "in", "self", ".", "_stacks", ":", "await", "stack", ".", "convert_media", "(", "self", "...
Send all queued messages. The first step is to convert all media in the stacked layers then the second step is to send all messages as grouped in time as possible.
[ "Send", "all", "queued", "messages", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/responder.py#L67-L80
train
Send all queued messages.
BernardFW/bernard
src/bernard/engine/responder.py
Responder._flush
async def _flush(self, request: 'Request', stacks: List[Stack]): """ Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call. """ for stack in stacks: await self.platform.send(request, stack)
python
async def _flush(self, request: 'Request', stacks: List[Stack]): """ Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call. """ for stack in stacks: await self.platform.send(request, stack)
[ "async", "def", "_flush", "(", "self", ",", "request", ":", "'Request'", ",", "stacks", ":", "List", "[", "Stack", "]", ")", ":", "for", "stack", "in", "stacks", ":", "await", "self", ".", "platform", ".", "send", "(", "request", ",", "stack", ")" ]
Perform the actual sending to platform. This is separated from `flush()` since it needs to be inside a middleware call.
[ "Perform", "the", "actual", "sending", "to", "platform", ".", "This", "is", "separated", "from", "flush", "()", "since", "it", "needs", "to", "be", "inside", "a", "middleware", "call", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/responder.py#L82-L89
train
Perform the actual sending to the platform.
BernardFW/bernard
src/bernard/engine/responder.py
Responder.make_transition_register
async def make_transition_register(self, request: 'Request'): """ Use all underlying stacks to generate the next transition register. """ register = {} for stack in self._stacks: register = await stack.patch_register(register, request) return register
python
async def make_transition_register(self, request: 'Request'): """ Use all underlying stacks to generate the next transition register. """ register = {} for stack in self._stacks: register = await stack.patch_register(register, request) return register
[ "async", "def", "make_transition_register", "(", "self", ",", "request", ":", "'Request'", ")", ":", "register", "=", "{", "}", "for", "stack", "in", "self", ".", "_stacks", ":", "register", "=", "await", "stack", ".", "patch_register", "(", "register", ",...
Use all underlying stacks to generate the next transition register.
[ "Use", "all", "underlying", "stacks", "to", "generate", "the", "next", "transition", "register", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/responder.py#L91-L101
train
Create a transition register for the given request.
cloudmesh-cmd3/cmd3
cmd3/plugins/template.py
template.preloop
def preloop(self): """adds the banner to the preloop""" lines = textwrap.dedent(self.banner).split("\n") for line in lines: Console._print("BLUE", "", line)
python
def preloop(self): """adds the banner to the preloop""" lines = textwrap.dedent(self.banner).split("\n") for line in lines: Console._print("BLUE", "", line)
[ "def", "preloop", "(", "self", ")", ":", "lines", "=", "textwrap", ".", "dedent", "(", "self", ".", "banner", ")", ".", "split", "(", "\"\\n\"", ")", "for", "line", "in", "lines", ":", "Console", ".", "_print", "(", "\"BLUE\"", ",", "\"\"", ",", "l...
adds the banner to the preloop
[ "adds", "the", "banner", "to", "the", "preloop" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/template.py#L21-L25
train
adds the banner to the preloop
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.getDebt
def getDebt(self): """Sums up all the balances of the account and returns them. """ debt = float(self['principalBalance']) + float(self['interestBalance']) debt += float(self['feesBalance']) + float(self['penaltyBalance']) return debt
python
def getDebt(self): """Sums up all the balances of the account and returns them. """ debt = float(self['principalBalance']) + float(self['interestBalance']) debt += float(self['feesBalance']) + float(self['penaltyBalance']) return debt
[ "def", "getDebt", "(", "self", ")", ":", "debt", "=", "float", "(", "self", "[", "'principalBalance'", "]", ")", "+", "float", "(", "self", "[", "'interestBalance'", "]", ")", "debt", "+=", "float", "(", "self", "[", "'feesBalance'", "]", ")", "+", "...
Sums up all the balances of the account and returns them.
[ "Sums", "up", "all", "the", "balances", "of", "the", "account", "and", "returns", "them", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L43-L49
train
Sums up all the balances of the account and returns them.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.preprocess
def preprocess(self): """Preprocessing. Each active custom field is given a 'name' key that holds the field name, and for each keyed name, the value of the custom field is assigned. Notes on the group get some html tags removed. """ super(MambuLoan,self).preproc...
python
def preprocess(self): """Preprocessing. Each active custom field is given a 'name' key that holds the field name, and for each keyed name, the value of the custom field is assigned. Notes on the group get some html tags removed. """ super(MambuLoan,self).preproc...
[ "def", "preprocess", "(", "self", ")", ":", "super", "(", "MambuLoan", ",", "self", ")", ".", "preprocess", "(", ")", "try", ":", "self", "[", "'notes'", "]", "=", "strip_tags", "(", "self", "[", "'notes'", "]", ")", "except", "KeyError", ":", "pass"...
Preprocessing. Each active custom field is given a 'name' key that holds the field name, and for each keyed name, the value of the custom field is assigned. Notes on the group get some html tags removed.
[ "Preprocessing", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L52-L66
train
Preprocessing.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setRepayments
def setRepayments(self, *args, **kwargs): """Adds the repayments for this loan to a 'repayments' field. Repayments are MambuRepayment objects. Repayments get sorted by due date. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always tr...
python
def setRepayments(self, *args, **kwargs): """Adds the repayments for this loan to a 'repayments' field. Repayments are MambuRepayment objects. Repayments get sorted by due date. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always tr...
[ "def", "setRepayments", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "duedate", "(", "repayment", ")", ":", "\"\"\"Util function used for sorting repayments according to due Date\"\"\"", "try", ":", "return", "repayment", "[", "'dueDate'"...
Adds the repayments for this loan to a 'repayments' field. Repayments are MambuRepayment objects. Repayments get sorted by due date. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always true that just 1 request was done. It may be ...
[ "Adds", "the", "repayments", "for", "this", "loan", "to", "a", "repayments", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L69-L100
train
Adds the repayments for this loan to a repayments field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setTransactions
def setTransactions(self, *args, **kwargs): """Adds the transactions for this loan to a 'transactions' field. Transactions are MambuTransaction objects. Transactions get sorted by transaction id. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added...
python
def setTransactions(self, *args, **kwargs): """Adds the transactions for this loan to a 'transactions' field. Transactions are MambuTransaction objects. Transactions get sorted by transaction id. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added...
[ "def", "setTransactions", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "transactionid", "(", "transaction", ")", ":", "\"\"\"Util function used for sorting transactions according to id\"\"\"", "try", ":", "return", "transaction", "[", "'t...
Adds the transactions for this loan to a 'transactions' field. Transactions are MambuTransaction objects. Transactions get sorted by transaction id. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always true that just 1 request was ...
[ "Adds", "the", "transactions", "for", "this", "loan", "to", "a", "transactions", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L103-L134
train
Adds the transactions for this loan to a transactions field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setCentre
def setCentre(self, *args, **kwargs): """Adds the centre for this loan to a 'assignedCentre' field. Also adds an 'assignedCentreName' field with the name of the centre. Centre is a MambuCentre object. Returns the number of requests done to Mambu. """ try: ...
python
def setCentre(self, *args, **kwargs): """Adds the centre for this loan to a 'assignedCentre' field. Also adds an 'assignedCentreName' field with the name of the centre. Centre is a MambuCentre object. Returns the number of requests done to Mambu. """ try: ...
[ "def", "setCentre", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "centre", "=", "self", ".", "mambucentreclass", "(", "entid", "=", "self", "[", "'assignedCentreKey'", "]", ",", "*", "args", ",", "*", "*", "kwargs", ...
Adds the centre for this loan to a 'assignedCentre' field. Also adds an 'assignedCentreName' field with the name of the centre. Centre is a MambuCentre object. Returns the number of requests done to Mambu.
[ "Adds", "the", "centre", "for", "this", "loan", "to", "a", "assignedCentre", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L160-L180
train
Adds the centre for this loan to a assignedCentre field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setUser
def setUser(self, *args, **kwargs): """Adds the user for this loan to a 'user' field. User is a MambuUser object. Returns the number of requests done to Mambu. """ try: user = self.mambuuserclass(entid=self['assignedUserKey'], *args, **kwargs) except KeyErro...
python
def setUser(self, *args, **kwargs): """Adds the user for this loan to a 'user' field. User is a MambuUser object. Returns the number of requests done to Mambu. """ try: user = self.mambuuserclass(entid=self['assignedUserKey'], *args, **kwargs) except KeyErro...
[ "def", "setUser", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "self", ".", "mambuuserclass", "(", "entid", "=", "self", "[", "'assignedUserKey'", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", ...
Adds the user for this loan to a 'user' field. User is a MambuUser object. Returns the number of requests done to Mambu.
[ "Adds", "the", "user", "for", "this", "loan", "to", "a", "user", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L183-L208
train
Adds the user for this loan to a user field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setProduct
def setProduct(self, cache=False, *args, **kwargs): """Adds the product for this loan to a 'product' field. Product is a MambuProduct object. cache argument allows to use AllMambuProducts singleton to retrieve the products. See mambuproduct.AllMambuProducts code and pydoc for f...
python
def setProduct(self, cache=False, *args, **kwargs): """Adds the product for this loan to a 'product' field. Product is a MambuProduct object. cache argument allows to use AllMambuProducts singleton to retrieve the products. See mambuproduct.AllMambuProducts code and pydoc for f...
[ "def", "setProduct", "(", "self", ",", "cache", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cache", ":", "try", ":", "prods", "=", "self", ".", "allmambuproductsclass", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
Adds the product for this loan to a 'product' field. Product is a MambuProduct object. cache argument allows to use AllMambuProducts singleton to retrieve the products. See mambuproduct.AllMambuProducts code and pydoc for further information. Returns the number of requests don...
[ "Adds", "the", "product", "for", "this", "loan", "to", "a", "product", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L211-L247
train
Adds the product for this loan to a product field.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.setHolder
def setHolder(self, getClients=False, getRoles=False, *args, **kwargs): """Adds the "holder" of the loan to a 'holder' field. Holder may be a MambuClient or a MambuGroup object, depending on the type of loan created at Mambu. getRoles argument tells this method to retrive the clients w...
python
def setHolder(self, getClients=False, getRoles=False, *args, **kwargs): """Adds the "holder" of the loan to a 'holder' field. Holder may be a MambuClient or a MambuGroup object, depending on the type of loan created at Mambu. getRoles argument tells this method to retrive the clients w...
[ "def", "setHolder", "(", "self", ",", "getClients", "=", "False", ",", "getRoles", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requests", "=", "0", "if", "'fullDetails'", "in", "kwargs", ":", "fullDetails", "=", "kwargs", "[", ...
Adds the "holder" of the loan to a 'holder' field. Holder may be a MambuClient or a MambuGroup object, depending on the type of loan created at Mambu. getRoles argument tells this method to retrive the clients who have specific roles in the group, in case of a group holder. ge...
[ "Adds", "the", "holder", "of", "the", "loan", "to", "a", "holder", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L250-L409
train
This method adds the holder of the loan to a key - value store in the holder field.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoan.getClientDetails
def getClientDetails(self, *args, **kwargs): """Gets the loan details for every client holder of the account. As default, assigns the whole loan amount to each client. This works fine for Client holders of the loan account. When Group holders, this is perhaps not ideal, but I cannot tel...
python
def getClientDetails(self, *args, **kwargs): """Gets the loan details for every client holder of the account. As default, assigns the whole loan amount to each client. This works fine for Client holders of the loan account. When Group holders, this is perhaps not ideal, but I cannot tel...
[ "def", "getClientDetails", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "loannames", "=", "[", "]", "holder", "=", "kwargs", "[", "'holder'", "]", "for", "client", "in", "holder", "[", "'clients'", "]", ":", "loannames", ".", "ap...
Gets the loan details for every client holder of the account. As default, assigns the whole loan amount to each client. This works fine for Client holders of the loan account. When Group holders, this is perhaps not ideal, but I cannot tell. If you inherit MambuLoan you should override...
[ "Gets", "the", "loan", "details", "for", "every", "client", "holder", "of", "the", "account", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L412-L444
train
Gets the loan details for every client in the account.
jstitch/MambuPy
MambuPy/rest/mambuloan.py
MambuLoans.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Loan (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs ...
python
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Loan (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs ...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "n", ",", "l", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!", "try", ":",...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Loan (or your own itemclass) object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dicti...
[ "The", "trick", "for", "iterable", "Mambu", "Objects", "comes", "here", ":" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuloan.py#L515-L542
train
This function converts a list of plain dictionaries into a list of Mambu Loan objects.
inveniosoftware/invenio-query-parser
invenio_query_parser/contrib/elasticsearch/walkers/dsl.py
ElasticSearchDSL.get_fields_for_keyword
def get_fields_for_keyword(self, keyword, mode='a'): """Convert keyword to fields.""" field = self.keyword_to_fields.get(keyword, keyword) if isinstance(field, dict): return field[mode] elif isinstance(field, (list, tuple)): return field return [field]
python
def get_fields_for_keyword(self, keyword, mode='a'): """Convert keyword to fields.""" field = self.keyword_to_fields.get(keyword, keyword) if isinstance(field, dict): return field[mode] elif isinstance(field, (list, tuple)): return field return [field]
[ "def", "get_fields_for_keyword", "(", "self", ",", "keyword", ",", "mode", "=", "'a'", ")", ":", "field", "=", "self", ".", "keyword_to_fields", ".", "get", "(", "keyword", ",", "keyword", ")", "if", "isinstance", "(", "field", ",", "dict", ")", ":", "...
Convert keyword to fields.
[ "Convert", "keyword", "to", "fields", "." ]
21a2c36318003ff52d2e18e7196bb420db8ecb4b
https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/contrib/elasticsearch/walkers/dsl.py#L46-L53
train
Convert keyword to fields.
pyslackers/sir-bot-a-lot
sirbot/utils/__init__.py
merge_dict
def merge_dict(a, b, path=None): """ Merge dict b into a """ if not path: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dict(a[key], b[key], path + [str(key)]) else: continu...
python
def merge_dict(a, b, path=None): """ Merge dict b into a """ if not path: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dict(a[key], b[key], path + [str(key)]) else: continu...
[ "def", "merge_dict", "(", "a", ",", "b", ",", "path", "=", "None", ")", ":", "if", "not", "path", ":", "path", "=", "[", "]", "for", "key", "in", "b", ":", "if", "key", "in", "a", ":", "if", "isinstance", "(", "a", "[", "key", "]", ",", "di...
Merge dict b into a
[ "Merge", "dict", "b", "into", "a" ]
22dfdd6a14d61dbe29423fd131b7a23e618b68d7
https://github.com/pyslackers/sir-bot-a-lot/blob/22dfdd6a14d61dbe29423fd131b7a23e618b68d7/sirbot/utils/__init__.py#L8-L22
train
Merge dict b into a
giancosta86/Iris
info/gianlucacosta/iris/rendering.py
Model.findVars
def findVars(self): """ Returns the dict of model variables, as follows: --each getProperty() and isProperty() getter method is called, and a "property" key is added to the result --variables set via setVar() are added to the result, overwriting any value already pr...
python
def findVars(self): """ Returns the dict of model variables, as follows: --each getProperty() and isProperty() getter method is called, and a "property" key is added to the result --variables set via setVar() are added to the result, overwriting any value already pr...
[ "def", "findVars", "(", "self", ")", ":", "if", "self", ".", "_cacheVars", "and", "(", "self", ".", "_vars", "is", "not", "None", ")", ":", "return", "dict", "(", "self", ".", "_vars", ")", "result", "=", "{", "}", "for", "itemName", "in", "map", ...
Returns the dict of model variables, as follows: --each getProperty() and isProperty() getter method is called, and a "property" key is added to the result --variables set via setVar() are added to the result, overwriting any value already provided by a getter The variable...
[ "Returns", "the", "dict", "of", "model", "variables", "as", "follows", ":" ]
b3d92cca5cce3653519bd032346b211c46a57d05
https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/rendering.py#L40-L79
train
Returns the dict of model variables that are set via setVar.
BernardFW/bernard
src/bernard/i18n/_formatter.py
make_date
def make_date(obj: Union[date, datetime, Text], timezone: tzinfo=None): """ A flexible method to get a date object. It accepts either an ISO 8601 date/time string, either a Python `datetime`, either a Python `date`. If the input is a date/time and a timezone is specified, the resulting date ob...
python
def make_date(obj: Union[date, datetime, Text], timezone: tzinfo=None): """ A flexible method to get a date object. It accepts either an ISO 8601 date/time string, either a Python `datetime`, either a Python `date`. If the input is a date/time and a timezone is specified, the resulting date ob...
[ "def", "make_date", "(", "obj", ":", "Union", "[", "date", ",", "datetime", ",", "Text", "]", ",", "timezone", ":", "tzinfo", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "if", "hasattr", "(", "obj", ",", "'asti...
A flexible method to get a date object. It accepts either an ISO 8601 date/time string, either a Python `datetime`, either a Python `date`. If the input is a date/time and a timezone is specified, the resulting date object will be in the specified time zone.
[ "A", "flexible", "method", "to", "get", "a", "date", "object", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L22-L40
train
A flexible method to get a date object.
BernardFW/bernard
src/bernard/i18n/_formatter.py
I18nFormatter.format_date
def format_date(self, value, format_): """ Format the date using Babel """ date_ = make_date(value) return dates.format_date(date_, format_, locale=self.lang)
python
def format_date(self, value, format_): """ Format the date using Babel """ date_ = make_date(value) return dates.format_date(date_, format_, locale=self.lang)
[ "def", "format_date", "(", "self", ",", "value", ",", "format_", ")", ":", "date_", "=", "make_date", "(", "value", ")", "return", "dates", ".", "format_date", "(", "date_", ",", "format_", ",", "locale", "=", "self", ".", "lang", ")" ]
Format the date using Babel
[ "Format", "the", "date", "using", "Babel" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L80-L85
train
Format the date using Babel s date format
BernardFW/bernard
src/bernard/i18n/_formatter.py
I18nFormatter.format_datetime
def format_datetime(self, value, format_): """ Format the datetime using Babel """ date_ = make_datetime(value) return dates.format_datetime(date_, format_, locale=self.lang)
python
def format_datetime(self, value, format_): """ Format the datetime using Babel """ date_ = make_datetime(value) return dates.format_datetime(date_, format_, locale=self.lang)
[ "def", "format_datetime", "(", "self", ",", "value", ",", "format_", ")", ":", "date_", "=", "make_datetime", "(", "value", ")", "return", "dates", ".", "format_datetime", "(", "date_", ",", "format_", ",", "locale", "=", "self", ".", "lang", ")" ]
Format the datetime using Babel
[ "Format", "the", "datetime", "using", "Babel" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L87-L92
train
Format the datetime using Babel
BernardFW/bernard
src/bernard/i18n/_formatter.py
I18nFormatter.format_field
def format_field(self, value, spec): """ Provide the additional formatters for localization. """ if spec.startswith('date:'): _, format_ = spec.split(':', 1) return self.format_date(value, format_) elif spec.startswith('datetime:'): _, format_...
python
def format_field(self, value, spec): """ Provide the additional formatters for localization. """ if spec.startswith('date:'): _, format_ = spec.split(':', 1) return self.format_date(value, format_) elif spec.startswith('datetime:'): _, format_...
[ "def", "format_field", "(", "self", ",", "value", ",", "spec", ")", ":", "if", "spec", ".", "startswith", "(", "'date:'", ")", ":", "_", ",", "format_", "=", "spec", ".", "split", "(", "':'", ",", "1", ")", "return", "self", ".", "format_date", "("...
Provide the additional formatters for localization.
[ "Provide", "the", "additional", "formatters", "for", "localization", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L100-L114
train
Formats the value according to the spec.
klmitch/turnstile
turnstile/limits.py
_make_units
def _make_units(*units): """ Units map helper. Each argument is treated as a unit descriptor--a tuple where the first element specifies a numerical value, and the second element consists of a sequence of names for that value. Returns a dictionary where each name is mapped to the numerical valu...
python
def _make_units(*units): """ Units map helper. Each argument is treated as a unit descriptor--a tuple where the first element specifies a numerical value, and the second element consists of a sequence of names for that value. Returns a dictionary where each name is mapped to the numerical valu...
[ "def", "_make_units", "(", "*", "units", ")", ":", "units_map", "=", "{", "}", "for", "value", ",", "names", "in", "units", ":", "units_map", "[", "value", "]", "=", "names", "[", "0", "]", "for", "name", "in", "names", ":", "units_map", "[", "name...
Units map helper. Each argument is treated as a unit descriptor--a tuple where the first element specifies a numerical value, and the second element consists of a sequence of names for that value. Returns a dictionary where each name is mapped to the numerical value, and the numerical value is mapped ...
[ "Units", "map", "helper", ".", "Each", "argument", "is", "treated", "as", "a", "unit", "descriptor", "--", "a", "tuple", "where", "the", "first", "element", "specifies", "a", "numerical", "value", "and", "the", "second", "element", "consists", "of", "a", "...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L34-L50
train
Helper function to make a dictionary of units to their respective base classes.
klmitch/turnstile
turnstile/limits.py
BucketKey._encode
def _encode(cls, value): """Encode the given value, taking care of '%' and '/'.""" value = json.dumps(value) return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value)
python
def _encode(cls, value): """Encode the given value, taking care of '%' and '/'.""" value = json.dumps(value) return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value)
[ "def", "_encode", "(", "cls", ",", "value", ")", ":", "value", "=", "json", ".", "dumps", "(", "value", ")", "return", "cls", ".", "_ENC_RE", ".", "sub", "(", "lambda", "x", ":", "'%%%2x'", "%", "ord", "(", "x", ".", "group", "(", "0", ")", ")"...
Encode the given value, taking care of '%' and '/'.
[ "Encode", "the", "given", "value", "taking", "care", "of", "%", "and", "/", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L146-L150
train
Encode the given value taking care of '%' and '/'.
klmitch/turnstile
turnstile/limits.py
BucketKey._decode
def _decode(cls, value): """Decode the given value, reverting '%'-encoded groups.""" value = cls._DEC_RE.sub(lambda x: '%c' % int(x.group(1), 16), value) return json.loads(value)
python
def _decode(cls, value): """Decode the given value, reverting '%'-encoded groups.""" value = cls._DEC_RE.sub(lambda x: '%c' % int(x.group(1), 16), value) return json.loads(value)
[ "def", "_decode", "(", "cls", ",", "value", ")", ":", "value", "=", "cls", ".", "_DEC_RE", ".", "sub", "(", "lambda", "x", ":", "'%c'", "%", "int", "(", "x", ".", "group", "(", "1", ")", ",", "16", ")", ",", "value", ")", "return", "json", "....
Decode the given value, reverting '%'-encoded groups.
[ "Decode", "the", "given", "value", "reverting", "%", "-", "encoded", "groups", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L153-L157
train
Decode the given value reverting '%' - encoded groups.
klmitch/turnstile
turnstile/limits.py
BucketKey.decode
def decode(cls, key): """ Decode a bucket key into a BucketKey instance. :param key: The string form of a bucket key. :returns: A suitable instance of BucketKey corresponding to the passed-in key. """ # Determine bucket key version prefix, sep...
python
def decode(cls, key): """ Decode a bucket key into a BucketKey instance. :param key: The string form of a bucket key. :returns: A suitable instance of BucketKey corresponding to the passed-in key. """ # Determine bucket key version prefix, sep...
[ "def", "decode", "(", "cls", ",", "key", ")", ":", "# Determine bucket key version", "prefix", ",", "sep", ",", "param_str", "=", "key", ".", "partition", "(", "':'", ")", "if", "sep", "!=", "':'", "or", "prefix", "not", "in", "cls", ".", "_prefix_to_ver...
Decode a bucket key into a BucketKey instance. :param key: The string form of a bucket key. :returns: A suitable instance of BucketKey corresponding to the passed-in key.
[ "Decode", "a", "bucket", "key", "into", "a", "BucketKey", "instance", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L198-L229
train
Decodes a string form of a bucket key into a BucketKey instance.
klmitch/turnstile
turnstile/limits.py
BucketLoader.need_summary
def need_summary(self, now, max_updates, max_age): """ Helper method to determine if a "summarize" record should be added. :param now: The current time. :param max_updates: Maximum number of updates before a summarize is required. :param max_a...
python
def need_summary(self, now, max_updates, max_age): """ Helper method to determine if a "summarize" record should be added. :param now: The current time. :param max_updates: Maximum number of updates before a summarize is required. :param max_a...
[ "def", "need_summary", "(", "self", ",", "now", ",", "max_updates", ",", "max_age", ")", ":", "# Handle the case where an old summarize record exists", "if", "self", ".", "summarized", "is", "True", "and", "self", ".", "last_summarize_ts", "+", "max_age", "<=", "n...
Helper method to determine if a "summarize" record should be added. :param now: The current time. :param max_updates: Maximum number of updates before a summarize is required. :param max_age: Maximum age of the last summarize record. T...
[ "Helper", "method", "to", "determine", "if", "a", "summarize", "record", "should", "be", "added", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L403-L423
train
Returns True if a summarize record is needed.
klmitch/turnstile
turnstile/limits.py
Bucket.hydrate
def hydrate(cls, db, bucket, limit, key): """ Given a key and a bucket dict, as generated by dehydrate(), generate an appropriate instance of Bucket. """ return cls(db, limit, key, **bucket)
python
def hydrate(cls, db, bucket, limit, key): """ Given a key and a bucket dict, as generated by dehydrate(), generate an appropriate instance of Bucket. """ return cls(db, limit, key, **bucket)
[ "def", "hydrate", "(", "cls", ",", "db", ",", "bucket", ",", "limit", ",", "key", ")", ":", "return", "cls", "(", "db", ",", "limit", ",", "key", ",", "*", "*", "bucket", ")" ]
Given a key and a bucket dict, as generated by dehydrate(), generate an appropriate instance of Bucket.
[ "Given", "a", "key", "and", "a", "bucket", "dict", "as", "generated", "by", "dehydrate", "()", "generate", "an", "appropriate", "instance", "of", "Bucket", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L456-L462
train
Given a key and a bucket dict generate an appropriate instance of Bucket.
klmitch/turnstile
turnstile/limits.py
Bucket.dehydrate
def dehydrate(self): """Return a dict representing this bucket.""" # Only concerned about very specific attributes result = {} for attr in self.attrs: result[attr] = getattr(self, attr) return result
python
def dehydrate(self): """Return a dict representing this bucket.""" # Only concerned about very specific attributes result = {} for attr in self.attrs: result[attr] = getattr(self, attr) return result
[ "def", "dehydrate", "(", "self", ")", ":", "# Only concerned about very specific attributes", "result", "=", "{", "}", "for", "attr", "in", "self", ".", "attrs", ":", "result", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "return", "res...
Return a dict representing this bucket.
[ "Return", "a", "dict", "representing", "this", "bucket", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L464-L472
train
Return a dict representing this bucket.
klmitch/turnstile
turnstile/limits.py
Bucket.delay
def delay(self, params, now=None): """Determine delay until next request.""" if now is None: now = time.time() # Initialize last... if not self.last: self.last = now elif now < self.last: now = self.last # How much has leaked out? ...
python
def delay(self, params, now=None): """Determine delay until next request.""" if now is None: now = time.time() # Initialize last... if not self.last: self.last = now elif now < self.last: now = self.last # How much has leaked out? ...
[ "def", "delay", "(", "self", ",", "params", ",", "now", "=", "None", ")", ":", "if", "now", "is", "None", ":", "now", "=", "time", ".", "time", "(", ")", "# Initialize last...", "if", "not", "self", ".", "last", ":", "self", ".", "last", "=", "no...
Determine delay until next request.
[ "Determine", "delay", "until", "next", "request", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L474-L506
train
Determine the delay until next request.
klmitch/turnstile
turnstile/limits.py
Bucket.messages
def messages(self): """Return remaining messages before limiting.""" return int(math.floor(((self.limit.unit_value - self.level) / self.limit.unit_value) * self.limit.value))
python
def messages(self): """Return remaining messages before limiting.""" return int(math.floor(((self.limit.unit_value - self.level) / self.limit.unit_value) * self.limit.value))
[ "def", "messages", "(", "self", ")", ":", "return", "int", "(", "math", ".", "floor", "(", "(", "(", "self", ".", "limit", ".", "unit_value", "-", "self", ".", "level", ")", "/", "self", ".", "limit", ".", "unit_value", ")", "*", "self", ".", "li...
Return remaining messages before limiting.
[ "Return", "remaining", "messages", "before", "limiting", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L509-L513
train
Return remaining messages before limiting.
klmitch/turnstile
turnstile/limits.py
Limit.hydrate
def hydrate(cls, db, limit): """ Given a limit dict, as generated by dehydrate(), generate an appropriate instance of Limit (or a subclass). If the required limit class cannot be found, returns None. """ # Extract the limit name from the keyword arguments cls_na...
python
def hydrate(cls, db, limit): """ Given a limit dict, as generated by dehydrate(), generate an appropriate instance of Limit (or a subclass). If the required limit class cannot be found, returns None. """ # Extract the limit name from the keyword arguments cls_na...
[ "def", "hydrate", "(", "cls", ",", "db", ",", "limit", ")", ":", "# Extract the limit name from the keyword arguments", "cls_name", "=", "limit", ".", "pop", "(", "'limit_class'", ")", "# Is it in the registry yet?", "if", "cls_name", "not", "in", "cls", ".", "_re...
Given a limit dict, as generated by dehydrate(), generate an appropriate instance of Limit (or a subclass). If the required limit class cannot be found, returns None.
[ "Given", "a", "limit", "dict", "as", "generated", "by", "dehydrate", "()", "generate", "an", "appropriate", "instance", "of", "Limit", "(", "or", "a", "subclass", ")", ".", "If", "the", "required", "limit", "class", "cannot", "be", "found", "returns", "Non...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L709-L727
train
Given a dict as generated by dehydrate() generate an an appropriate instance of the required limit class.
klmitch/turnstile
turnstile/limits.py
Limit.dehydrate
def dehydrate(self): """Return a dict representing this limit.""" # Only concerned about very specific attributes result = dict(limit_class=self._limit_full_name) for attr in self.attrs: # Using getattr allows the properties to come into play result[attr] = getat...
python
def dehydrate(self): """Return a dict representing this limit.""" # Only concerned about very specific attributes result = dict(limit_class=self._limit_full_name) for attr in self.attrs: # Using getattr allows the properties to come into play result[attr] = getat...
[ "def", "dehydrate", "(", "self", ")", ":", "# Only concerned about very specific attributes", "result", "=", "dict", "(", "limit_class", "=", "self", ".", "_limit_full_name", ")", "for", "attr", "in", "self", ".", "attrs", ":", "# Using getattr allows the properties t...
Return a dict representing this limit.
[ "Return", "a", "dict", "representing", "this", "limit", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L729-L738
train
Return a dict representing this limit.
klmitch/turnstile
turnstile/limits.py
Limit._route
def _route(self, mapper): """ Set up the route(s) corresponding to the limit. This controls which limits are checked against the request. :param mapper: The routes.Mapper object to add the route to. """ # Build up the keyword arguments to feed to connect() kwar...
python
def _route(self, mapper): """ Set up the route(s) corresponding to the limit. This controls which limits are checked against the request. :param mapper: The routes.Mapper object to add the route to. """ # Build up the keyword arguments to feed to connect() kwar...
[ "def", "_route", "(", "self", ",", "mapper", ")", ":", "# Build up the keyword arguments to feed to connect()", "kwargs", "=", "dict", "(", "conditions", "=", "dict", "(", "function", "=", "self", ".", "_filter", ")", ")", "# Restrict the verbs", "if", "self", "...
Set up the route(s) corresponding to the limit. This controls which limits are checked against the request. :param mapper: The routes.Mapper object to add the route to.
[ "Set", "up", "the", "route", "(", "s", ")", "corresponding", "to", "the", "limit", ".", "This", "controls", "which", "limits", "are", "checked", "against", "the", "request", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L740-L763
train
This is the main entry point for the route method.
klmitch/turnstile
turnstile/limits.py
Limit.load
def load(self, key): """ Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object. """ # Turn the key into a BucketKey if isinstance(key, bas...
python
def load(self, key): """ Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object. """ # Turn the key into a BucketKey if isinstance(key, bas...
[ "def", "load", "(", "self", ",", "key", ")", ":", "# Turn the key into a BucketKey", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "key", "=", "BucketKey", ".", "decode", "(", "key", ")", "# Make sure the uuids match", "if", "key", ".", "uuid"...
Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object.
[ "Given", "a", "bucket", "key", "load", "the", "corresponding", "bucket", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L780-L813
train
Given a bucket key load the corresponding bucket.
klmitch/turnstile
turnstile/limits.py
Limit.decode
def decode(self, key): """ Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised ...
python
def decode(self, key): """ Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised ...
[ "def", "decode", "(", "self", ",", "key", ")", ":", "# Parse the bucket key", "key", "=", "BucketKey", ".", "decode", "(", "key", ")", "# Make sure the uuids match", "if", "key", ".", "uuid", "!=", "self", ".", "uuid", ":", "raise", "ValueError", "(", "\"%...
Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised if this is not the case...
[ "Given", "a", "bucket", "key", "compute", "the", "parameters", "used", "to", "compute", "that", "key", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L815-L835
train
Given a bucket key compute the parameters used to compute that key.
klmitch/turnstile
turnstile/limits.py
Limit._filter
def _filter(self, environ, params): """ Performs final filtering of the request to determine if this limit applies. Returns False if the limit does not apply or if the call should not be limited, or True to apply the limit. """ # Search for required query arguments ...
python
def _filter(self, environ, params): """ Performs final filtering of the request to determine if this limit applies. Returns False if the limit does not apply or if the call should not be limited, or True to apply the limit. """ # Search for required query arguments ...
[ "def", "_filter", "(", "self", ",", "environ", ",", "params", ")", ":", "# Search for required query arguments", "if", "self", ".", "queries", ":", "# No query string available", "if", "'QUERY_STRING'", "not", "in", "environ", ":", "return", "False", "# Extract the ...
Performs final filtering of the request to determine if this limit applies. Returns False if the limit does not apply or if the call should not be limited, or True to apply the limit.
[ "Performs", "final", "filtering", "of", "the", "request", "to", "determine", "if", "this", "limit", "applies", ".", "Returns", "False", "if", "the", "limit", "does", "not", "apply", "or", "if", "the", "call", "should", "not", "be", "limited", "or", "True",...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L849-L972
train
Returns True if the limit applies to the request False otherwise.
klmitch/turnstile
turnstile/limits.py
Limit.format
def format(self, status, headers, environ, bucket, delay): """ Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should b...
python
def format(self, status, headers, environ, bucket, delay): """ Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should b...
[ "def", "format", "(", "self", ",", "status", ",", "headers", ",", "environ", ",", "bucket", ",", "delay", ")", ":", "# This is a default response entity, which can be overridden", "# by limit subclasses.", "entity", "=", "(", "\"This request was rate-limited. \"", "\"Ple...
Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should be returned to the caller, or an alternate selected. The...
[ "Formats", "a", "response", "entity", ".", "Returns", "a", "tuple", "of", "the", "desired", "status", "code", "and", "the", "formatted", "entity", ".", "The", "default", "status", "code", "is", "passed", "in", "as", "is", "a", "dictionary", "of", "headers"...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L993-L1023
train
Formats a response entity.
klmitch/turnstile
turnstile/limits.py
Limit.unit
def unit(self, value): """ Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names. """ if isinstance(value, TimeUnit): self._unit = va...
python
def unit(self, value): """ Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names. """ if isinstance(value, TimeUnit): self._unit = va...
[ "def", "unit", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "TimeUnit", ")", ":", "self", ".", "_unit", "=", "value", "else", ":", "self", ".", "_unit", "=", "TimeUnit", "(", "value", ")" ]
Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names.
[ "Change", "the", "unit", "for", "this", "limit", "to", "the", "specified", "unit", ".", "The", "new", "value", "may", "be", "specified", "as", "an", "integer", "a", "string", "indicating", "the", "number", "of", "seconds", "or", "one", "of", "the", "reco...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L1047-L1057
train
Change the unit for this limit to the specified value.
klmitch/turnstile
turnstile/limits.py
Limit.unit_value
def unit_value(self, value): """ Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names. """ if isinstance(value, TimeUnit): self._uni...
python
def unit_value(self, value): """ Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names. """ if isinstance(value, TimeUnit): self._uni...
[ "def", "unit_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "TimeUnit", ")", ":", "self", ".", "_unit", "=", "value", "else", ":", "self", ".", "_unit", "=", "TimeUnit", "(", "value", ")" ]
Change the unit for this limit to the specified unit. The new value may be specified as an integer, a string indicating the number of seconds, or one of the recognized unit names.
[ "Change", "the", "unit", "for", "this", "limit", "to", "the", "specified", "unit", ".", "The", "new", "value", "may", "be", "specified", "as", "an", "integer", "a", "string", "indicating", "the", "number", "of", "seconds", "or", "one", "of", "the", "reco...
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L1069-L1079
train
Change the unit for this limit to the specified value.
openvax/varlens
varlens/util.py
drop_prefix
def drop_prefix(strings): """ Removes common prefix from a collection of strings """ strings_without_extensions = [ s.split(".", 2)[0] for s in strings ] if len(strings_without_extensions) == 1: return [os.path.basename(strings_without_extensions[0])] prefix_len = len(os.pat...
python
def drop_prefix(strings): """ Removes common prefix from a collection of strings """ strings_without_extensions = [ s.split(".", 2)[0] for s in strings ] if len(strings_without_extensions) == 1: return [os.path.basename(strings_without_extensions[0])] prefix_len = len(os.pat...
[ "def", "drop_prefix", "(", "strings", ")", ":", "strings_without_extensions", "=", "[", "s", ".", "split", "(", "\".\"", ",", "2", ")", "[", "0", "]", "for", "s", "in", "strings", "]", "if", "len", "(", "strings_without_extensions", ")", "==", "1", ":"...
Removes common prefix from a collection of strings
[ "Removes", "common", "prefix", "from", "a", "collection", "of", "strings" ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/util.py#L52-L68
train
Removes common prefix from a collection of strings
frostming/marko
marko/__init__.py
Markdown.render
def render(self, parsed): """Call ``self.renderer.render(text)``. Override this to handle parsed result. """ self.renderer.root_node = parsed with self.renderer as r: return r.render(parsed)
python
def render(self, parsed): """Call ``self.renderer.render(text)``. Override this to handle parsed result. """ self.renderer.root_node = parsed with self.renderer as r: return r.render(parsed)
[ "def", "render", "(", "self", ",", "parsed", ")", ":", "self", ".", "renderer", ".", "root_node", "=", "parsed", "with", "self", ".", "renderer", "as", "r", ":", "return", "r", ".", "render", "(", "parsed", ")" ]
Call ``self.renderer.render(text)``. Override this to handle parsed result.
[ "Call", "self", ".", "renderer", ".", "render", "(", "text", ")", "." ]
1cd030b665fa37bad1f8b3a25a89ce1a7c491dde
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/__init__.py#L48-L55
train
Call self. renderer. render ( text ).
ossobv/dutree
dutree/dutree.py
human
def human(value): "If val>=1000 return val/1024+KiB, etc." if value >= 1073741824000: return '{:.1f} T'.format(value / 1099511627776.0) if value >= 1048576000: return '{:.1f} G'.format(value / 1073741824.0) if value >= 1024000: return '{:.1f} M'.format(value / 1048576.0) if v...
python
def human(value): "If val>=1000 return val/1024+KiB, etc." if value >= 1073741824000: return '{:.1f} T'.format(value / 1099511627776.0) if value >= 1048576000: return '{:.1f} G'.format(value / 1073741824.0) if value >= 1024000: return '{:.1f} M'.format(value / 1048576.0) if v...
[ "def", "human", "(", "value", ")", ":", "if", "value", ">=", "1073741824000", ":", "return", "'{:.1f} T'", ".", "format", "(", "value", "/", "1099511627776.0", ")", "if", "value", ">=", "1048576000", ":", "return", "'{:.1f} G'", ".", "format", "(", "value"...
If val>=1000 return val/1024+KiB, etc.
[ "If", "val", ">", "=", "1000", "return", "val", "/", "1024", "+", "KiB", "etc", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L456-L466
train
If val > = 1000 return val / 1073741824 + KiB etc.
ossobv/dutree
dutree/dutree.py
formatwarning
def formatwarning(message, category, filename, lineno, line=None): """ Override default Warning layout, from: /PATH/TO/dutree.py:326: UserWarning: [Errno 2] No such file or directory: '/0.d/05.d' warnings.warn(str(e)) To: dutree.py:330: UserWarning: [Errn...
python
def formatwarning(message, category, filename, lineno, line=None): """ Override default Warning layout, from: /PATH/TO/dutree.py:326: UserWarning: [Errno 2] No such file or directory: '/0.d/05.d' warnings.warn(str(e)) To: dutree.py:330: UserWarning: [Errn...
[ "def", "formatwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "line", "=", "None", ")", ":", "return", "'{basename}:{lineno}: {category}: {message}\\n'", ".", "format", "(", "basename", "=", "path", ".", "basename", "(", "filename...
Override default Warning layout, from: /PATH/TO/dutree.py:326: UserWarning: [Errno 2] No such file or directory: '/0.d/05.d' warnings.warn(str(e)) To: dutree.py:330: UserWarning: [Errno 2] No such file or directory: '/0.d/05.d'
[ "Override", "default", "Warning", "layout", "from", ":" ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L510-L525
train
Format warning message.
ossobv/dutree
dutree/dutree.py
DuNode.count
def count(self): "Return how many nodes this contains, including self." if self._nodes is None: return 1 return sum(i.count() for i in self._nodes)
python
def count(self): "Return how many nodes this contains, including self." if self._nodes is None: return 1 return sum(i.count() for i in self._nodes)
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "1", "return", "sum", "(", "i", ".", "count", "(", ")", "for", "i", "in", "self", ".", "_nodes", ")" ]
Return how many nodes this contains, including self.
[ "Return", "how", "many", "nodes", "this", "contains", "including", "self", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L107-L111
train
Return how many nodes this contains including self.
ossobv/dutree
dutree/dutree.py
DuNode.app_size
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
python
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
[ "def", "app_size", "(", "self", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "self", ".", "_app_size", "return", "sum", "(", "i", ".", "app_size", "(", ")", "for", "i", "in", "self", ".", "_nodes", ")" ]
Return the total apparent size, including children.
[ "Return", "the", "total", "apparent", "size", "including", "children", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L120-L124
train
Return the total apparent size including children.
ossobv/dutree
dutree/dutree.py
DuNode.use_size
def use_size(self): "Return the total used size, including children." if self._nodes is None: return self._use_size return sum(i.use_size() for i in self._nodes)
python
def use_size(self): "Return the total used size, including children." if self._nodes is None: return self._use_size return sum(i.use_size() for i in self._nodes)
[ "def", "use_size", "(", "self", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "self", ".", "_use_size", "return", "sum", "(", "i", ".", "use_size", "(", ")", "for", "i", "in", "self", ".", "_nodes", ")" ]
Return the total used size, including children.
[ "Return", "the", "total", "used", "size", "including", "children", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L127-L131
train
Return the total used size including children.
ossobv/dutree
dutree/dutree.py
DuNode.prune_if_smaller_than
def prune_if_smaller_than(self, small_size, a_or_u): "Prune/merge all nodes that are smaller than small_size." if self._prune_all_if_small(small_size, a_or_u): return for node in self._nodes: node.prune_if_smaller_than(small_size, a_or_u) self._prune_some_if_sma...
python
def prune_if_smaller_than(self, small_size, a_or_u): "Prune/merge all nodes that are smaller than small_size." if self._prune_all_if_small(small_size, a_or_u): return for node in self._nodes: node.prune_if_smaller_than(small_size, a_or_u) self._prune_some_if_sma...
[ "def", "prune_if_smaller_than", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "if", "self", ".", "_prune_all_if_small", "(", "small_size", ",", "a_or_u", ")", ":", "return", "for", "node", "in", "self", ".", "_nodes", ":", "node", ".", "prune_if...
Prune/merge all nodes that are smaller than small_size.
[ "Prune", "/", "merge", "all", "nodes", "that", "are", "smaller", "than", "small_size", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L143-L151
train
Prune / merge all nodes that are smaller than small_size.
ossobv/dutree
dutree/dutree.py
DuNode._prune_all_if_small
def _prune_all_if_small(self, small_size, a_or_u): "Return True and delete children if small enough." if self._nodes is None: return True total_size = (self.app_size() if a_or_u else self.use_size()) if total_size < small_size: if a_or_u: self._se...
python
def _prune_all_if_small(self, small_size, a_or_u): "Return True and delete children if small enough." if self._nodes is None: return True total_size = (self.app_size() if a_or_u else self.use_size()) if total_size < small_size: if a_or_u: self._se...
[ "def", "_prune_all_if_small", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "True", "total_size", "=", "(", "self", ".", "app_size", "(", ")", "if", "a_or_u", "else", "self", ".", "us...
Return True and delete children if small enough.
[ "Return", "True", "and", "delete", "children", "if", "small", "enough", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L153-L166
train
Return True and delete children if small enough.
ossobv/dutree
dutree/dutree.py
DuNode._prune_some_if_small
def _prune_some_if_small(self, small_size, a_or_u): "Merge some nodes in the directory, whilst keeping others." # Assert that we're not messing things up. prev_app_size = self.app_size() prev_use_size = self.use_size() keep_nodes = [] prune_app_size = 0 prune_use...
python
def _prune_some_if_small(self, small_size, a_or_u): "Merge some nodes in the directory, whilst keeping others." # Assert that we're not messing things up. prev_app_size = self.app_size() prev_use_size = self.use_size() keep_nodes = [] prune_app_size = 0 prune_use...
[ "def", "_prune_some_if_small", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "# Assert that we're not messing things up.", "prev_app_size", "=", "self", ".", "app_size", "(", ")", "prev_use_size", "=", "self", ".", "use_size", "(", ")", "keep_nodes", "=...
Merge some nodes in the directory, whilst keeping others.
[ "Merge", "some", "nodes", "in", "the", "directory", "whilst", "keeping", "others", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L168-L215
train
Merge some nodes in the directory whilst keeping others.
ossobv/dutree
dutree/dutree.py
DuNode.merge_upwards_if_smaller_than
def merge_upwards_if_smaller_than(self, small_size, a_or_u): """After prune_if_smaller_than is run, we may still have excess nodes. For example, with a small_size of 609710690: 7 /* 28815419 /data/* 32 /data/srv/* 925746...
python
def merge_upwards_if_smaller_than(self, small_size, a_or_u): """After prune_if_smaller_than is run, we may still have excess nodes. For example, with a small_size of 609710690: 7 /* 28815419 /data/* 32 /data/srv/* 925746...
[ "def", "merge_upwards_if_smaller_than", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "# Assert that we're not messing things up.", "prev_app_size", "=", "self", ".", "app_size", "(", ")", "prev_use_size", "=", "self", ".", "use_size", "(", ")", "small_no...
After prune_if_smaller_than is run, we may still have excess nodes. For example, with a small_size of 609710690: 7 /* 28815419 /data/* 32 /data/srv/* 925746 /data/srv/docker.bak/* 12 /data/srv/docker.bak/sh...
[ "After", "prune_if_smaller_than", "is", "run", "we", "may", "still", "have", "excess", "nodes", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L217-L258
train
This is a private method that merges upwards the tree if the small_size is greater than the current one.
ossobv/dutree
dutree/dutree.py
DuNode.as_tree
def as_tree(self): "Return the nodes as a list of lists." if self._nodes is None: return [self] ret = [self] for node in self._nodes: ret.append(node.as_tree()) return ret
python
def as_tree(self): "Return the nodes as a list of lists." if self._nodes is None: return [self] ret = [self] for node in self._nodes: ret.append(node.as_tree()) return ret
[ "def", "as_tree", "(", "self", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "[", "self", "]", "ret", "=", "[", "self", "]", "for", "node", "in", "self", ".", "_nodes", ":", "ret", ".", "append", "(", "node", ".", "as_tree",...
Return the nodes as a list of lists.
[ "Return", "the", "nodes", "as", "a", "list", "of", "lists", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L272-L279
train
Return the nodes as a list of lists.
ossobv/dutree
dutree/dutree.py
DuNode.get_leaves
def get_leaves(self): "Return a sorted leaves: only nodes with fixed file size." leaves = self._get_leaves() leaves.sort(key=(lambda x: x._path)) # FF sorts "mixed" last return leaves
python
def get_leaves(self): "Return a sorted leaves: only nodes with fixed file size." leaves = self._get_leaves() leaves.sort(key=(lambda x: x._path)) # FF sorts "mixed" last return leaves
[ "def", "get_leaves", "(", "self", ")", ":", "leaves", "=", "self", ".", "_get_leaves", "(", ")", "leaves", ".", "sort", "(", "key", "=", "(", "lambda", "x", ":", "x", ".", "_path", ")", ")", "# FF sorts \"mixed\" last", "return", "leaves" ]
Return a sorted leaves: only nodes with fixed file size.
[ "Return", "a", "sorted", "leaves", ":", "only", "nodes", "with", "fixed", "file", "size", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L281-L285
train
Return a sorted leaves : only nodes with fixed file size.
ossobv/dutree
dutree/dutree.py
DuScan._normpath
def _normpath(self, pathname): "Return path normalized for duscan usage: no trailing slash." if pathname == '/': pathname = '' elif pathname.endswith('/'): pathname = pathname[:-1] assert not pathname.endswith('/'), pathname return pathname
python
def _normpath(self, pathname): "Return path normalized for duscan usage: no trailing slash." if pathname == '/': pathname = '' elif pathname.endswith('/'): pathname = pathname[:-1] assert not pathname.endswith('/'), pathname return pathname
[ "def", "_normpath", "(", "self", ",", "pathname", ")", ":", "if", "pathname", "==", "'/'", ":", "pathname", "=", "''", "elif", "pathname", ".", "endswith", "(", "'/'", ")", ":", "pathname", "=", "pathname", "[", ":", "-", "1", "]", "assert", "not", ...
Return path normalized for duscan usage: no trailing slash.
[ "Return", "path", "normalized", "for", "duscan", "usage", ":", "no", "trailing", "slash", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L311-L318
train
Return path normalized for duscan usage : no trailing slash.
ossobv/dutree
dutree/dutree.py
DuScan._check_path
def _check_path(self): "Immediately check if we can access path. Otherwise bail." if not path.isdir(self._path or '/'): raise OSError('Path {!r} is not a directory'.format(self._path))
python
def _check_path(self): "Immediately check if we can access path. Otherwise bail." if not path.isdir(self._path or '/'): raise OSError('Path {!r} is not a directory'.format(self._path))
[ "def", "_check_path", "(", "self", ")", ":", "if", "not", "path", ".", "isdir", "(", "self", ".", "_path", "or", "'/'", ")", ":", "raise", "OSError", "(", "'Path {!r} is not a directory'", ".", "format", "(", "self", ".", "_path", ")", ")" ]
Immediately check if we can access path. Otherwise bail.
[ "Immediately", "check", "if", "we", "can", "access", "path", ".", "Otherwise", "bail", "." ]
adceeeb17f9fd70a7ed9c674850d7015d820eb2a
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L320-L323
train
Immediately check if we can access path. Otherwise bail.