repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
BernardFW/bernard | src/bernard/trigram.py | LabelMatcher.similarity | def similarity(self, other: Trigram) -> Tuple[float, L]:
"""
Returns the best matching score and the associated label.
"""
return max(
((t % other, l) for t, l in self.trigrams),
key=lambda x: x[0],
) | python | def similarity(self, other: Trigram) -> Tuple[float, L]:
"""
Returns the best matching score and the associated label.
"""
return max(
((t % other, l) for t, l in self.trigrams),
key=lambda x: x[0],
) | [
"def",
"similarity",
"(",
"self",
",",
"other",
":",
"Trigram",
")",
"->",
"Tuple",
"[",
"float",
",",
"L",
"]",
":",
"return",
"max",
"(",
"(",
"(",
"t",
"%",
"other",
",",
"l",
")",
"for",
"t",
",",
"l",
"in",
"self",
".",
"trigrams",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
",",
")"
] | Returns the best matching score and the associated label. | [
"Returns",
"the",
"best",
"matching",
"score",
"and",
"the",
"associated",
"label",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/trigram.py#L159-L167 | train |
transifex/transifex-python-library | txlib/http/base.py | BaseRequest._exception_for | def _exception_for(self, code):
"""Return the exception class suitable for the specified HTTP
status code.
Raises:
UnknownError: The HTTP status code is not one of the knowns.
"""
if code in self.errors:
return self.errors[code]
elif 500 <= code < 599:
return exceptions.RemoteServerError
else:
return exceptions.UnknownError | python | def _exception_for(self, code):
"""Return the exception class suitable for the specified HTTP
status code.
Raises:
UnknownError: The HTTP status code is not one of the knowns.
"""
if code in self.errors:
return self.errors[code]
elif 500 <= code < 599:
return exceptions.RemoteServerError
else:
return exceptions.UnknownError | [
"def",
"_exception_for",
"(",
"self",
",",
"code",
")",
":",
"if",
"code",
"in",
"self",
".",
"errors",
":",
"return",
"self",
".",
"errors",
"[",
"code",
"]",
"elif",
"500",
"<=",
"code",
"<",
"599",
":",
"return",
"exceptions",
".",
"RemoteServerError",
"else",
":",
"return",
"exceptions",
".",
"UnknownError"
] | Return the exception class suitable for the specified HTTP
status code.
Raises:
UnknownError: The HTTP status code is not one of the knowns. | [
"Return",
"the",
"exception",
"class",
"suitable",
"for",
"the",
"specified",
"HTTP",
"status",
"code",
"."
] | 9fea86b718973de35ccca6d54bd1f445c9632406 | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/http/base.py#L86-L98 | train |
jstitch/MambuPy | MambuPy/rest/mambuclient.py | MambuClient.setGroups | def setGroups(self, *args, **kwargs):
"""Adds the groups to which this client belongs.
The 'groupKeys' field of the client holds a list of the
encodedKeys of the groups to which this client belongs.
Returns the number of requests done to Mambu.
"""
requests = 0
groups = []
try:
for gk in self['groupKeys']:
try:
g = self.mambugroupclass(entid=gk, *args, **kwargs)
except AttributeError as ae:
from .mambugroup import MambuGroup
self.mambugroupclass = MambuGroup
g = self.mambugroupclass(entid=gk, *args, **kwargs)
requests += 1
groups.append(g)
except KeyError:
pass
self['groups'] = groups
return requests | python | def setGroups(self, *args, **kwargs):
"""Adds the groups to which this client belongs.
The 'groupKeys' field of the client holds a list of the
encodedKeys of the groups to which this client belongs.
Returns the number of requests done to Mambu.
"""
requests = 0
groups = []
try:
for gk in self['groupKeys']:
try:
g = self.mambugroupclass(entid=gk, *args, **kwargs)
except AttributeError as ae:
from .mambugroup import MambuGroup
self.mambugroupclass = MambuGroup
g = self.mambugroupclass(entid=gk, *args, **kwargs)
requests += 1
groups.append(g)
except KeyError:
pass
self['groups'] = groups
return requests | [
"def",
"setGroups",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requests",
"=",
"0",
"groups",
"=",
"[",
"]",
"try",
":",
"for",
"gk",
"in",
"self",
"[",
"'groupKeys'",
"]",
":",
"try",
":",
"g",
"=",
"self",
".",
"mambugroupclass",
"(",
"entid",
"=",
"gk",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mambugroup",
"import",
"MambuGroup",
"self",
".",
"mambugroupclass",
"=",
"MambuGroup",
"g",
"=",
"self",
".",
"mambugroupclass",
"(",
"entid",
"=",
"gk",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"requests",
"+=",
"1",
"groups",
".",
"append",
"(",
"g",
")",
"except",
"KeyError",
":",
"pass",
"self",
"[",
"'groups'",
"]",
"=",
"groups",
"return",
"requests"
] | Adds the groups to which this client belongs.
The 'groupKeys' field of the client holds a list of the
encodedKeys of the groups to which this client belongs.
Returns the number of requests done to Mambu. | [
"Adds",
"the",
"groups",
"to",
"which",
"this",
"client",
"belongs",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuclient.py#L136-L162 | train |
jstitch/MambuPy | MambuPy/rest/mambuclient.py | MambuClient.setBranch | def setBranch(self, *args, **kwargs):
"""Adds the branch to which the client belongs.
"""
try:
branch = self.mambubranchclass(entid=self['assignedBranchKey'], *args, **kwargs)
except AttributeError as ae:
from .mambubranch import MambuBranch
self.mambubranchclass = MambuBranch
branch = self.mambubranchclass(entid=self['assignedBranchKey'], *args, **kwargs)
self['assignedBranchName'] = branch['name']
self['assignedBranch'] = branch
return 1 | python | def setBranch(self, *args, **kwargs):
"""Adds the branch to which the client belongs.
"""
try:
branch = self.mambubranchclass(entid=self['assignedBranchKey'], *args, **kwargs)
except AttributeError as ae:
from .mambubranch import MambuBranch
self.mambubranchclass = MambuBranch
branch = self.mambubranchclass(entid=self['assignedBranchKey'], *args, **kwargs)
self['assignedBranchName'] = branch['name']
self['assignedBranch'] = branch
return 1 | [
"def",
"setBranch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"branch",
"=",
"self",
".",
"mambubranchclass",
"(",
"entid",
"=",
"self",
"[",
"'assignedBranchKey'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mambubranch",
"import",
"MambuBranch",
"self",
".",
"mambubranchclass",
"=",
"MambuBranch",
"branch",
"=",
"self",
".",
"mambubranchclass",
"(",
"entid",
"=",
"self",
"[",
"'assignedBranchKey'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
"[",
"'assignedBranchName'",
"]",
"=",
"branch",
"[",
"'name'",
"]",
"self",
"[",
"'assignedBranch'",
"]",
"=",
"branch",
"return",
"1"
] | Adds the branch to which the client belongs. | [
"Adds",
"the",
"branch",
"to",
"which",
"the",
"client",
"belongs",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuclient.py#L164-L177 | train |
jpscaletti/authcode | authcode/auth_authorization_mixin.py | AuthorizationMixin.protected | def protected(self, *tests, **kwargs):
"""Factory of decorators for limit the access to views.
:tests: *function, optional
One or more functions that takes the args and kwargs of the
view and returns either `True` or `False`.
All test must return True to show the view.
Options:
:role: str, optional
Test for the user having a role with this name.
:roles: list, optional
Test for the user having **any** role in this list of names.
:csrf: bool, None, optional
If ``None`` (the default), the decorator will check the value
of the CSFR token for POST, PUT or DELETE requests.
If ``True`` it will do the same also for all requests.
If ``False``, the value of the CSFR token will not be checked.
:url_sign_in: str, function, optional
If any required condition fail, redirect to this place.
Override the default URL. This can also be a callable.
:request: obj, optional
Overwrite the request for testing.
The rest of the ``key=value`` pairs in ``kwargs`` are interpreted as tests.
The user must have a property `key` with a value equals to `value`.
If the user has a method named `key`, that method is called with
`value` as a single argument and must return True to show the view.
"""
_role = kwargs.pop('role', None)
_roles = kwargs.pop('roles', None) or []
_csrf = kwargs.pop('csrf', None)
_url_sign_in = kwargs.pop('url_sign_in', None)
_request = kwargs.pop('request', None)
if _role:
_roles.append(_role)
_roles = [to_unicode(r) for r in _roles]
_tests = tests
_user_tests = kwargs
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
logger = logging.getLogger(__name__)
request = _request or self.request or args and args[0]
url_sign_in = self._get_url_sign_in(request, _url_sign_in)
user = self.get_user()
if not user:
return self._login_required(request, url_sign_in)
if hasattr(user, 'has_role') and _roles:
if not user.has_role(*_roles):
logger.debug(u'User `{0}`: has_role fail'.format(user.login))
logger.debug(u'User roles: {0}'.format([r.name for r in user.roles]))
return self.wsgi.raise_forbidden()
for test in _tests:
test_pass = test(user, *args, **kwargs)
if not test_pass:
logger.debug(u'User `{0}`: test fail'.format(user.login))
return self.wsgi.raise_forbidden()
for name, value in _user_tests.items():
user_test = getattr(user, name)
test_pass = user_test(value, *args, **kwargs)
if not test_pass:
logger.debug(u'User `{0}`: test fail'.format(user.login))
return self.wsgi.raise_forbidden()
disable_csrf = _csrf == False # noqa
if (not self.wsgi.is_idempotent(request) and not disable_csrf) or _csrf:
if not self.csrf_token_is_valid(request):
logger.debug(u'User `{0}`: invalid CSFR token'.format(user.login))
return self.wsgi.raise_forbidden("CSFR token isn't valid")
return f(*args, **kwargs)
return wrapper
return decorator | python | def protected(self, *tests, **kwargs):
"""Factory of decorators for limit the access to views.
:tests: *function, optional
One or more functions that takes the args and kwargs of the
view and returns either `True` or `False`.
All test must return True to show the view.
Options:
:role: str, optional
Test for the user having a role with this name.
:roles: list, optional
Test for the user having **any** role in this list of names.
:csrf: bool, None, optional
If ``None`` (the default), the decorator will check the value
of the CSFR token for POST, PUT or DELETE requests.
If ``True`` it will do the same also for all requests.
If ``False``, the value of the CSFR token will not be checked.
:url_sign_in: str, function, optional
If any required condition fail, redirect to this place.
Override the default URL. This can also be a callable.
:request: obj, optional
Overwrite the request for testing.
The rest of the ``key=value`` pairs in ``kwargs`` are interpreted as tests.
The user must have a property `key` with a value equals to `value`.
If the user has a method named `key`, that method is called with
`value` as a single argument and must return True to show the view.
"""
_role = kwargs.pop('role', None)
_roles = kwargs.pop('roles', None) or []
_csrf = kwargs.pop('csrf', None)
_url_sign_in = kwargs.pop('url_sign_in', None)
_request = kwargs.pop('request', None)
if _role:
_roles.append(_role)
_roles = [to_unicode(r) for r in _roles]
_tests = tests
_user_tests = kwargs
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
logger = logging.getLogger(__name__)
request = _request or self.request or args and args[0]
url_sign_in = self._get_url_sign_in(request, _url_sign_in)
user = self.get_user()
if not user:
return self._login_required(request, url_sign_in)
if hasattr(user, 'has_role') and _roles:
if not user.has_role(*_roles):
logger.debug(u'User `{0}`: has_role fail'.format(user.login))
logger.debug(u'User roles: {0}'.format([r.name for r in user.roles]))
return self.wsgi.raise_forbidden()
for test in _tests:
test_pass = test(user, *args, **kwargs)
if not test_pass:
logger.debug(u'User `{0}`: test fail'.format(user.login))
return self.wsgi.raise_forbidden()
for name, value in _user_tests.items():
user_test = getattr(user, name)
test_pass = user_test(value, *args, **kwargs)
if not test_pass:
logger.debug(u'User `{0}`: test fail'.format(user.login))
return self.wsgi.raise_forbidden()
disable_csrf = _csrf == False # noqa
if (not self.wsgi.is_idempotent(request) and not disable_csrf) or _csrf:
if not self.csrf_token_is_valid(request):
logger.debug(u'User `{0}`: invalid CSFR token'.format(user.login))
return self.wsgi.raise_forbidden("CSFR token isn't valid")
return f(*args, **kwargs)
return wrapper
return decorator | [
"def",
"protected",
"(",
"self",
",",
"*",
"tests",
",",
"*",
"*",
"kwargs",
")",
":",
"_role",
"=",
"kwargs",
".",
"pop",
"(",
"'role'",
",",
"None",
")",
"_roles",
"=",
"kwargs",
".",
"pop",
"(",
"'roles'",
",",
"None",
")",
"or",
"[",
"]",
"_csrf",
"=",
"kwargs",
".",
"pop",
"(",
"'csrf'",
",",
"None",
")",
"_url_sign_in",
"=",
"kwargs",
".",
"pop",
"(",
"'url_sign_in'",
",",
"None",
")",
"_request",
"=",
"kwargs",
".",
"pop",
"(",
"'request'",
",",
"None",
")",
"if",
"_role",
":",
"_roles",
".",
"append",
"(",
"_role",
")",
"_roles",
"=",
"[",
"to_unicode",
"(",
"r",
")",
"for",
"r",
"in",
"_roles",
"]",
"_tests",
"=",
"tests",
"_user_tests",
"=",
"kwargs",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"request",
"=",
"_request",
"or",
"self",
".",
"request",
"or",
"args",
"and",
"args",
"[",
"0",
"]",
"url_sign_in",
"=",
"self",
".",
"_get_url_sign_in",
"(",
"request",
",",
"_url_sign_in",
")",
"user",
"=",
"self",
".",
"get_user",
"(",
")",
"if",
"not",
"user",
":",
"return",
"self",
".",
"_login_required",
"(",
"request",
",",
"url_sign_in",
")",
"if",
"hasattr",
"(",
"user",
",",
"'has_role'",
")",
"and",
"_roles",
":",
"if",
"not",
"user",
".",
"has_role",
"(",
"*",
"_roles",
")",
":",
"logger",
".",
"debug",
"(",
"u'User `{0}`: has_role fail'",
".",
"format",
"(",
"user",
".",
"login",
")",
")",
"logger",
".",
"debug",
"(",
"u'User roles: {0}'",
".",
"format",
"(",
"[",
"r",
".",
"name",
"for",
"r",
"in",
"user",
".",
"roles",
"]",
")",
")",
"return",
"self",
".",
"wsgi",
".",
"raise_forbidden",
"(",
")",
"for",
"test",
"in",
"_tests",
":",
"test_pass",
"=",
"test",
"(",
"user",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"test_pass",
":",
"logger",
".",
"debug",
"(",
"u'User `{0}`: test fail'",
".",
"format",
"(",
"user",
".",
"login",
")",
")",
"return",
"self",
".",
"wsgi",
".",
"raise_forbidden",
"(",
")",
"for",
"name",
",",
"value",
"in",
"_user_tests",
".",
"items",
"(",
")",
":",
"user_test",
"=",
"getattr",
"(",
"user",
",",
"name",
")",
"test_pass",
"=",
"user_test",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"test_pass",
":",
"logger",
".",
"debug",
"(",
"u'User `{0}`: test fail'",
".",
"format",
"(",
"user",
".",
"login",
")",
")",
"return",
"self",
".",
"wsgi",
".",
"raise_forbidden",
"(",
")",
"disable_csrf",
"=",
"_csrf",
"==",
"False",
"# noqa",
"if",
"(",
"not",
"self",
".",
"wsgi",
".",
"is_idempotent",
"(",
"request",
")",
"and",
"not",
"disable_csrf",
")",
"or",
"_csrf",
":",
"if",
"not",
"self",
".",
"csrf_token_is_valid",
"(",
"request",
")",
":",
"logger",
".",
"debug",
"(",
"u'User `{0}`: invalid CSFR token'",
".",
"format",
"(",
"user",
".",
"login",
")",
")",
"return",
"self",
".",
"wsgi",
".",
"raise_forbidden",
"(",
"\"CSFR token isn't valid\"",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] | Factory of decorators for limit the access to views.
:tests: *function, optional
One or more functions that takes the args and kwargs of the
view and returns either `True` or `False`.
All test must return True to show the view.
Options:
:role: str, optional
Test for the user having a role with this name.
:roles: list, optional
Test for the user having **any** role in this list of names.
:csrf: bool, None, optional
If ``None`` (the default), the decorator will check the value
of the CSFR token for POST, PUT or DELETE requests.
If ``True`` it will do the same also for all requests.
If ``False``, the value of the CSFR token will not be checked.
:url_sign_in: str, function, optional
If any required condition fail, redirect to this place.
Override the default URL. This can also be a callable.
:request: obj, optional
Overwrite the request for testing.
The rest of the ``key=value`` pairs in ``kwargs`` are interpreted as tests.
The user must have a property `key` with a value equals to `value`.
If the user has a method named `key`, that method is called with
`value` as a single argument and must return True to show the view. | [
"Factory",
"of",
"decorators",
"for",
"limit",
"the",
"access",
"to",
"views",
"."
] | 91529b6d0caec07d1452758d937e1e0745826139 | https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_authorization_mixin.py#L31-L117 | train |
jpscaletti/authcode | authcode/auth_authorization_mixin.py | AuthorizationMixin.replace_flask_route | def replace_flask_route(self, bp, *args, **kwargs):
"""Replace the Flask `app.route` or `blueprint.route` with a version
that first apply the protected decorator to the view, so all views
are automatically protected."""
protected = self.protected
def protected_route(rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
protected_f = protected(*args, **kwargs)(f)
bp.add_url_rule(rule, endpoint, protected_f, **options)
return f
return decorator
bp.route = protected_route | python | def replace_flask_route(self, bp, *args, **kwargs):
"""Replace the Flask `app.route` or `blueprint.route` with a version
that first apply the protected decorator to the view, so all views
are automatically protected."""
protected = self.protected
def protected_route(rule, **options):
"""Like :meth:`Flask.route` but for a blueprint. The endpoint for the
:func:`url_for` function is prefixed with the name of the blueprint.
"""
def decorator(f):
endpoint = options.pop("endpoint", f.__name__)
protected_f = protected(*args, **kwargs)(f)
bp.add_url_rule(rule, endpoint, protected_f, **options)
return f
return decorator
bp.route = protected_route | [
"def",
"replace_flask_route",
"(",
"self",
",",
"bp",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"protected",
"=",
"self",
".",
"protected",
"def",
"protected_route",
"(",
"rule",
",",
"*",
"*",
"options",
")",
":",
"\"\"\"Like :meth:`Flask.route` but for a blueprint. The endpoint for the\n :func:`url_for` function is prefixed with the name of the blueprint.\n \"\"\"",
"def",
"decorator",
"(",
"f",
")",
":",
"endpoint",
"=",
"options",
".",
"pop",
"(",
"\"endpoint\"",
",",
"f",
".",
"__name__",
")",
"protected_f",
"=",
"protected",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"(",
"f",
")",
"bp",
".",
"add_url_rule",
"(",
"rule",
",",
"endpoint",
",",
"protected_f",
",",
"*",
"*",
"options",
")",
"return",
"f",
"return",
"decorator",
"bp",
".",
"route",
"=",
"protected_route"
] | Replace the Flask `app.route` or `blueprint.route` with a version
that first apply the protected decorator to the view, so all views
are automatically protected. | [
"Replace",
"the",
"Flask",
"app",
".",
"route",
"or",
"blueprint",
".",
"route",
"with",
"a",
"version",
"that",
"first",
"apply",
"the",
"protected",
"decorator",
"to",
"the",
"view",
"so",
"all",
"views",
"are",
"automatically",
"protected",
"."
] | 91529b6d0caec07d1452758d937e1e0745826139 | https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_authorization_mixin.py#L119-L136 | train |
inveniosoftware/invenio-query-parser | invenio_query_parser/contrib/spires/converter.py | SpiresToInvenioSyntaxConverter.parse_query | def parse_query(self, query):
"""Parse query string using given grammar"""
tree = pypeg2.parse(query, Main, whitespace="")
return tree.accept(self.converter) | python | def parse_query(self, query):
"""Parse query string using given grammar"""
tree = pypeg2.parse(query, Main, whitespace="")
return tree.accept(self.converter) | [
"def",
"parse_query",
"(",
"self",
",",
"query",
")",
":",
"tree",
"=",
"pypeg2",
".",
"parse",
"(",
"query",
",",
"Main",
",",
"whitespace",
"=",
"\"\"",
")",
"return",
"tree",
".",
"accept",
"(",
"self",
".",
"converter",
")"
] | Parse query string using given grammar | [
"Parse",
"query",
"string",
"using",
"given",
"grammar"
] | 21a2c36318003ff52d2e18e7196bb420db8ecb4b | https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/contrib/spires/converter.py#L39-L42 | train |
blockstack-packages/jsontokens-py | jsontokens/token_verifier.py | decode_token | def decode_token(token):
"""
Top-level method to decode a JWT.
Takes either a compact-encoded JWT with a single signature,
or a multi-sig JWT in the JSON-serialized format.
Returns the deserialized token, as a dict.
The signatures will still be base64-encoded
"""
if isinstance(token, (unicode,str)):
return _decode_token_compact(token)
else:
return _decode_token_json(token) | python | def decode_token(token):
"""
Top-level method to decode a JWT.
Takes either a compact-encoded JWT with a single signature,
or a multi-sig JWT in the JSON-serialized format.
Returns the deserialized token, as a dict.
The signatures will still be base64-encoded
"""
if isinstance(token, (unicode,str)):
return _decode_token_compact(token)
else:
return _decode_token_json(token) | [
"def",
"decode_token",
"(",
"token",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"return",
"_decode_token_compact",
"(",
"token",
")",
"else",
":",
"return",
"_decode_token_json",
"(",
"token",
")"
] | Top-level method to decode a JWT.
Takes either a compact-encoded JWT with a single signature,
or a multi-sig JWT in the JSON-serialized format.
Returns the deserialized token, as a dict.
The signatures will still be base64-encoded | [
"Top",
"-",
"level",
"method",
"to",
"decode",
"a",
"JWT",
".",
"Takes",
"either",
"a",
"compact",
"-",
"encoded",
"JWT",
"with",
"a",
"single",
"signature",
"or",
"a",
"multi",
"-",
"sig",
"JWT",
"in",
"the",
"JSON",
"-",
"serialized",
"format",
"."
] | 1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3 | https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_verifier.py#L164-L177 | train |
blockstack-packages/jsontokens-py | jsontokens/token_verifier.py | TokenVerifier._verify_multi | def _verify_multi(self, token, verifying_keys, num_required=None):
"""
Verify a JSON-formatted JWT signed by multiple keys is authentic.
Optionally set a threshold of required valid signatures with num_required.
Return True if valid
Return False if not
TODO: support multiple types of keys
"""
headers, payload, raw_signatures, signing_inputs = _unpack_token_json(token)
if num_required is None:
num_required = len(raw_signatures)
if num_required > len(verifying_keys):
# not possible
return False
if len(headers) != len(raw_signatures):
# invalid
raise DecodeError('Header/signature mismatch')
verifying_keys = [load_verifying_key(vk, self.crypto_backend) for vk in verifying_keys]
# sanity check: only support one type of key :(
for vk in verifying_keys:
if vk.curve.name != verifying_keys[0].curve.name:
raise DecodeError("TODO: only support using keys from one curve per JWT")
der_signatures = [raw_to_der_signature(rs, verifying_keys[0].curve) for rs in raw_signatures]
# verify until threshold is met
num_verified = 0
for (signing_input, der_sig) in zip(signing_inputs, der_signatures):
for vk in verifying_keys:
verifier = self._get_verifier(vk, der_sig)
verifier.update(signing_input)
try:
verifier.verify()
num_verified += 1
verifying_keys.remove(vk)
break
except InvalidSignature:
pass
if num_verified >= num_required:
break
return (num_verified >= num_required) | python | def _verify_multi(self, token, verifying_keys, num_required=None):
"""
Verify a JSON-formatted JWT signed by multiple keys is authentic.
Optionally set a threshold of required valid signatures with num_required.
Return True if valid
Return False if not
TODO: support multiple types of keys
"""
headers, payload, raw_signatures, signing_inputs = _unpack_token_json(token)
if num_required is None:
num_required = len(raw_signatures)
if num_required > len(verifying_keys):
# not possible
return False
if len(headers) != len(raw_signatures):
# invalid
raise DecodeError('Header/signature mismatch')
verifying_keys = [load_verifying_key(vk, self.crypto_backend) for vk in verifying_keys]
# sanity check: only support one type of key :(
for vk in verifying_keys:
if vk.curve.name != verifying_keys[0].curve.name:
raise DecodeError("TODO: only support using keys from one curve per JWT")
der_signatures = [raw_to_der_signature(rs, verifying_keys[0].curve) for rs in raw_signatures]
# verify until threshold is met
num_verified = 0
for (signing_input, der_sig) in zip(signing_inputs, der_signatures):
for vk in verifying_keys:
verifier = self._get_verifier(vk, der_sig)
verifier.update(signing_input)
try:
verifier.verify()
num_verified += 1
verifying_keys.remove(vk)
break
except InvalidSignature:
pass
if num_verified >= num_required:
break
return (num_verified >= num_required) | [
"def",
"_verify_multi",
"(",
"self",
",",
"token",
",",
"verifying_keys",
",",
"num_required",
"=",
"None",
")",
":",
"headers",
",",
"payload",
",",
"raw_signatures",
",",
"signing_inputs",
"=",
"_unpack_token_json",
"(",
"token",
")",
"if",
"num_required",
"is",
"None",
":",
"num_required",
"=",
"len",
"(",
"raw_signatures",
")",
"if",
"num_required",
">",
"len",
"(",
"verifying_keys",
")",
":",
"# not possible",
"return",
"False",
"if",
"len",
"(",
"headers",
")",
"!=",
"len",
"(",
"raw_signatures",
")",
":",
"# invalid ",
"raise",
"DecodeError",
"(",
"'Header/signature mismatch'",
")",
"verifying_keys",
"=",
"[",
"load_verifying_key",
"(",
"vk",
",",
"self",
".",
"crypto_backend",
")",
"for",
"vk",
"in",
"verifying_keys",
"]",
"# sanity check: only support one type of key :(",
"for",
"vk",
"in",
"verifying_keys",
":",
"if",
"vk",
".",
"curve",
".",
"name",
"!=",
"verifying_keys",
"[",
"0",
"]",
".",
"curve",
".",
"name",
":",
"raise",
"DecodeError",
"(",
"\"TODO: only support using keys from one curve per JWT\"",
")",
"der_signatures",
"=",
"[",
"raw_to_der_signature",
"(",
"rs",
",",
"verifying_keys",
"[",
"0",
"]",
".",
"curve",
")",
"for",
"rs",
"in",
"raw_signatures",
"]",
"# verify until threshold is met",
"num_verified",
"=",
"0",
"for",
"(",
"signing_input",
",",
"der_sig",
")",
"in",
"zip",
"(",
"signing_inputs",
",",
"der_signatures",
")",
":",
"for",
"vk",
"in",
"verifying_keys",
":",
"verifier",
"=",
"self",
".",
"_get_verifier",
"(",
"vk",
",",
"der_sig",
")",
"verifier",
".",
"update",
"(",
"signing_input",
")",
"try",
":",
"verifier",
".",
"verify",
"(",
")",
"num_verified",
"+=",
"1",
"verifying_keys",
".",
"remove",
"(",
"vk",
")",
"break",
"except",
"InvalidSignature",
":",
"pass",
"if",
"num_verified",
">=",
"num_required",
":",
"break",
"return",
"(",
"num_verified",
">=",
"num_required",
")"
] | Verify a JSON-formatted JWT signed by multiple keys is authentic.
Optionally set a threshold of required valid signatures with num_required.
Return True if valid
Return False if not
TODO: support multiple types of keys | [
"Verify",
"a",
"JSON",
"-",
"formatted",
"JWT",
"signed",
"by",
"multiple",
"keys",
"is",
"authentic",
".",
"Optionally",
"set",
"a",
"threshold",
"of",
"required",
"valid",
"signatures",
"with",
"num_required",
".",
"Return",
"True",
"if",
"valid",
"Return",
"False",
"if",
"not"
] | 1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3 | https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_verifier.py#L219-L266 | train |
blockstack-packages/jsontokens-py | jsontokens/token_verifier.py | TokenVerifier.verify | def verify(self, token, verifying_key_or_keys, num_required=None):
"""
Verify a compact-formated JWT or a JSON-formatted JWT signed by multiple keys.
Return True if valid
Return False if not valid
TODO: support multiple types of keys
"""
if not isinstance(verifying_key_or_keys, (list, str, unicode)):
raise ValueError("Invalid verifying key(s): expected list or string")
if isinstance(verifying_key_or_keys, list):
return self._verify_multi(token, verifying_key_or_keys, num_required=num_required)
else:
return self._verify_single(token, str(verifying_key_or_keys)) | python | def verify(self, token, verifying_key_or_keys, num_required=None):
"""
Verify a compact-formated JWT or a JSON-formatted JWT signed by multiple keys.
Return True if valid
Return False if not valid
TODO: support multiple types of keys
"""
if not isinstance(verifying_key_or_keys, (list, str, unicode)):
raise ValueError("Invalid verifying key(s): expected list or string")
if isinstance(verifying_key_or_keys, list):
return self._verify_multi(token, verifying_key_or_keys, num_required=num_required)
else:
return self._verify_single(token, str(verifying_key_or_keys)) | [
"def",
"verify",
"(",
"self",
",",
"token",
",",
"verifying_key_or_keys",
",",
"num_required",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"verifying_key_or_keys",
",",
"(",
"list",
",",
"str",
",",
"unicode",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid verifying key(s): expected list or string\"",
")",
"if",
"isinstance",
"(",
"verifying_key_or_keys",
",",
"list",
")",
":",
"return",
"self",
".",
"_verify_multi",
"(",
"token",
",",
"verifying_key_or_keys",
",",
"num_required",
"=",
"num_required",
")",
"else",
":",
"return",
"self",
".",
"_verify_single",
"(",
"token",
",",
"str",
"(",
"verifying_key_or_keys",
")",
")"
] | Verify a compact-formated JWT or a JSON-formatted JWT signed by multiple keys.
Return True if valid
Return False if not valid
TODO: support multiple types of keys | [
"Verify",
"a",
"compact",
"-",
"formated",
"JWT",
"or",
"a",
"JSON",
"-",
"formatted",
"JWT",
"signed",
"by",
"multiple",
"keys",
".",
"Return",
"True",
"if",
"valid",
"Return",
"False",
"if",
"not",
"valid"
] | 1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3 | https://github.com/blockstack-packages/jsontokens-py/blob/1a4e71ed63456e8381b7d3fd566ce38e6ebfa7d3/jsontokens/token_verifier.py#L269-L284 | train |
cloudmesh-cmd3/cmd3 | cmd3/plugins/script.py | script.activate_script | def activate_script(self):
"""activates the script command"""
# must be rethought
# ./scripts
# deploydir/./scripts
self._add_scope("script")
self.scripts = {}
self.script_files = [
"./scripts/script_*.txt", "~/.cloudmesh/scripts/script_*.txt"]
self._load_scripts(self.script_files) | python | def activate_script(self):
"""activates the script command"""
# must be rethought
# ./scripts
# deploydir/./scripts
self._add_scope("script")
self.scripts = {}
self.script_files = [
"./scripts/script_*.txt", "~/.cloudmesh/scripts/script_*.txt"]
self._load_scripts(self.script_files) | [
"def",
"activate_script",
"(",
"self",
")",
":",
"# must be rethought",
"# ./scripts",
"# deploydir/./scripts",
"self",
".",
"_add_scope",
"(",
"\"script\"",
")",
"self",
".",
"scripts",
"=",
"{",
"}",
"self",
".",
"script_files",
"=",
"[",
"\"./scripts/script_*.txt\"",
",",
"\"~/.cloudmesh/scripts/script_*.txt\"",
"]",
"self",
".",
"_load_scripts",
"(",
"self",
".",
"script_files",
")"
] | activates the script command | [
"activates",
"the",
"script",
"command"
] | 92e33c96032fd3921f159198a0e57917c4dc34ed | https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/script.py#L16-L26 | train |
giancosta86/Iris | info/gianlucacosta/iris/io/utils.py | PathOperations.touch | def touch(path):
"""
Creates the given path as a file, also creating
intermediate directories if required.
"""
parentDirPath = os.path.dirname(path)
PathOperations.safeMakeDirs(parentDirPath)
with open(path, "wb"):
pass | python | def touch(path):
"""
Creates the given path as a file, also creating
intermediate directories if required.
"""
parentDirPath = os.path.dirname(path)
PathOperations.safeMakeDirs(parentDirPath)
with open(path, "wb"):
pass | [
"def",
"touch",
"(",
"path",
")",
":",
"parentDirPath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"PathOperations",
".",
"safeMakeDirs",
"(",
"parentDirPath",
")",
"with",
"open",
"(",
"path",
",",
"\"wb\"",
")",
":",
"pass"
] | Creates the given path as a file, also creating
intermediate directories if required. | [
"Creates",
"the",
"given",
"path",
"as",
"a",
"file",
"also",
"creating",
"intermediate",
"directories",
"if",
"required",
"."
] | b3d92cca5cce3653519bd032346b211c46a57d05 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/io/utils.py#L47-L57 | train |
giancosta86/Iris | info/gianlucacosta/iris/io/utils.py | PathOperations.safeRmTree | def safeRmTree(rootPath):
"""
Deletes a tree and returns true if it was correctly deleted
"""
shutil.rmtree(rootPath, True)
return not os.path.exists(rootPath) | python | def safeRmTree(rootPath):
"""
Deletes a tree and returns true if it was correctly deleted
"""
shutil.rmtree(rootPath, True)
return not os.path.exists(rootPath) | [
"def",
"safeRmTree",
"(",
"rootPath",
")",
":",
"shutil",
".",
"rmtree",
"(",
"rootPath",
",",
"True",
")",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rootPath",
")"
] | Deletes a tree and returns true if it was correctly deleted | [
"Deletes",
"a",
"tree",
"and",
"returns",
"true",
"if",
"it",
"was",
"correctly",
"deleted"
] | b3d92cca5cce3653519bd032346b211c46a57d05 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/io/utils.py#L61-L67 | train |
giancosta86/Iris | info/gianlucacosta/iris/io/utils.py | PathOperations.linearWalk | def linearWalk(rootPath, currentDirFilter=None):
"""
Returns a list of LinearWalkItem's, one for each file in the tree whose root is "rootPath".
The parameter "currentDirFilter" is a method applied
to every tuple (dirPath, dirNames, fileNames) automatically processed by os.walk():
--it can modify its "dirNames" parameter, so as to prevent
them to be processed later (just as in os.walk())
--it can modify its "fileNames" parameter, so as to alter the
global result linearWalk() (because it only returns files)
--if it returns True, the files in "fileNames" will be added to the global result
of linearWalk(); otherwise, they won't be added
If no filter is passed, all the files are automatically added to the result.
"""
for dirTuple in os.walk(rootPath):
(dirPath, dirNames, fileNames) = dirTuple
if currentDirFilter is not None and not currentDirFilter(dirPath, dirNames, fileNames):
continue
for fileName in fileNames:
yield LinearWalkItem(
dirPath,
fileName
) | python | def linearWalk(rootPath, currentDirFilter=None):
"""
Returns a list of LinearWalkItem's, one for each file in the tree whose root is "rootPath".
The parameter "currentDirFilter" is a method applied
to every tuple (dirPath, dirNames, fileNames) automatically processed by os.walk():
--it can modify its "dirNames" parameter, so as to prevent
them to be processed later (just as in os.walk())
--it can modify its "fileNames" parameter, so as to alter the
global result linearWalk() (because it only returns files)
--if it returns True, the files in "fileNames" will be added to the global result
of linearWalk(); otherwise, they won't be added
If no filter is passed, all the files are automatically added to the result.
"""
for dirTuple in os.walk(rootPath):
(dirPath, dirNames, fileNames) = dirTuple
if currentDirFilter is not None and not currentDirFilter(dirPath, dirNames, fileNames):
continue
for fileName in fileNames:
yield LinearWalkItem(
dirPath,
fileName
) | [
"def",
"linearWalk",
"(",
"rootPath",
",",
"currentDirFilter",
"=",
"None",
")",
":",
"for",
"dirTuple",
"in",
"os",
".",
"walk",
"(",
"rootPath",
")",
":",
"(",
"dirPath",
",",
"dirNames",
",",
"fileNames",
")",
"=",
"dirTuple",
"if",
"currentDirFilter",
"is",
"not",
"None",
"and",
"not",
"currentDirFilter",
"(",
"dirPath",
",",
"dirNames",
",",
"fileNames",
")",
":",
"continue",
"for",
"fileName",
"in",
"fileNames",
":",
"yield",
"LinearWalkItem",
"(",
"dirPath",
",",
"fileName",
")"
] | Returns a list of LinearWalkItem's, one for each file in the tree whose root is "rootPath".
The parameter "currentDirFilter" is a method applied
to every tuple (dirPath, dirNames, fileNames) automatically processed by os.walk():
--it can modify its "dirNames" parameter, so as to prevent
them to be processed later (just as in os.walk())
--it can modify its "fileNames" parameter, so as to alter the
global result linearWalk() (because it only returns files)
--if it returns True, the files in "fileNames" will be added to the global result
of linearWalk(); otherwise, they won't be added
If no filter is passed, all the files are automatically added to the result. | [
"Returns",
"a",
"list",
"of",
"LinearWalkItem",
"s",
"one",
"for",
"each",
"file",
"in",
"the",
"tree",
"whose",
"root",
"is",
"rootPath",
"."
] | b3d92cca5cce3653519bd032346b211c46a57d05 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/io/utils.py#L71-L99 | train |
BernardFW/bernard | src/bernard/cli/_base.py | init_live_reload | def init_live_reload(run):
"""
Start the live reload task
:param run: run the task inside of this function or just create it
"""
from asyncio import get_event_loop
from ._live_reload import start_child
loop = get_event_loop()
if run:
loop.run_until_complete(start_child())
else:
get_event_loop().create_task(start_child()) | python | def init_live_reload(run):
"""
Start the live reload task
:param run: run the task inside of this function or just create it
"""
from asyncio import get_event_loop
from ._live_reload import start_child
loop = get_event_loop()
if run:
loop.run_until_complete(start_child())
else:
get_event_loop().create_task(start_child()) | [
"def",
"init_live_reload",
"(",
"run",
")",
":",
"from",
"asyncio",
"import",
"get_event_loop",
"from",
".",
"_live_reload",
"import",
"start_child",
"loop",
"=",
"get_event_loop",
"(",
")",
"if",
"run",
":",
"loop",
".",
"run_until_complete",
"(",
"start_child",
"(",
")",
")",
"else",
":",
"get_event_loop",
"(",
")",
".",
"create_task",
"(",
"start_child",
"(",
")",
")"
] | Start the live reload task
:param run: run the task inside of this function or just create it | [
"Start",
"the",
"live",
"reload",
"task"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/cli/_base.py#L20-L34 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | cmp_name | def cmp_name(first_node, second_node):
"""
Compare two name recursively.
:param first_node: First node
:param second_node: Second state
:return: 0 if same name, 1 if names are differents.
"""
if len(first_node.children) == len(second_node.children):
for first_child, second_child in zip(first_node.children,
second_node.children):
for key in first_child.__dict__.keys():
if key.startswith('_'):
continue
if first_child.__dict__[key] != second_child.__dict__[key]:
return 1
ret_val = cmp_name(first_child, second_child)
if ret_val != 0:
return 1
else:
return 1
return 0 | python | def cmp_name(first_node, second_node):
"""
Compare two name recursively.
:param first_node: First node
:param second_node: Second state
:return: 0 if same name, 1 if names are differents.
"""
if len(first_node.children) == len(second_node.children):
for first_child, second_child in zip(first_node.children,
second_node.children):
for key in first_child.__dict__.keys():
if key.startswith('_'):
continue
if first_child.__dict__[key] != second_child.__dict__[key]:
return 1
ret_val = cmp_name(first_child, second_child)
if ret_val != 0:
return 1
else:
return 1
return 0 | [
"def",
"cmp_name",
"(",
"first_node",
",",
"second_node",
")",
":",
"if",
"len",
"(",
"first_node",
".",
"children",
")",
"==",
"len",
"(",
"second_node",
".",
"children",
")",
":",
"for",
"first_child",
",",
"second_child",
"in",
"zip",
"(",
"first_node",
".",
"children",
",",
"second_node",
".",
"children",
")",
":",
"for",
"key",
"in",
"first_child",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"if",
"first_child",
".",
"__dict__",
"[",
"key",
"]",
"!=",
"second_child",
".",
"__dict__",
"[",
"key",
"]",
":",
"return",
"1",
"ret_val",
"=",
"cmp_name",
"(",
"first_child",
",",
"second_child",
")",
"if",
"ret_val",
"!=",
"0",
":",
"return",
"1",
"else",
":",
"return",
"1",
"return",
"0"
] | Compare two name recursively.
:param first_node: First node
:param second_node: Second state
:return: 0 if same name, 1 if names are differents. | [
"Compare",
"two",
"name",
"recursively",
"."
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L99-L122 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | parse_division | def parse_division(l, c, line, root_node, last_section_node):
"""
Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last_div_node, last_section_node)
"""
name = line
name = name.replace(".", "")
# trim whitespaces/tabs between XXX and DIVISION
tokens = [t for t in name.split(' ') if t]
node = Name(Name.Type.Division, l, c, '%s %s' % (tokens[0], tokens[1]))
root_node.add_child(node)
last_div_node = node
# do not take previous sections into account
if last_section_node:
last_section_node.end_line = l
last_section_node = None
return last_div_node, last_section_node | python | def parse_division(l, c, line, root_node, last_section_node):
"""
Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last_div_node, last_section_node)
"""
name = line
name = name.replace(".", "")
# trim whitespaces/tabs between XXX and DIVISION
tokens = [t for t in name.split(' ') if t]
node = Name(Name.Type.Division, l, c, '%s %s' % (tokens[0], tokens[1]))
root_node.add_child(node)
last_div_node = node
# do not take previous sections into account
if last_section_node:
last_section_node.end_line = l
last_section_node = None
return last_div_node, last_section_node | [
"def",
"parse_division",
"(",
"l",
",",
"c",
",",
"line",
",",
"root_node",
",",
"last_section_node",
")",
":",
"name",
"=",
"line",
"name",
"=",
"name",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"# trim whitespaces/tabs between XXX and DIVISION",
"tokens",
"=",
"[",
"t",
"for",
"t",
"in",
"name",
".",
"split",
"(",
"' '",
")",
"if",
"t",
"]",
"node",
"=",
"Name",
"(",
"Name",
".",
"Type",
".",
"Division",
",",
"l",
",",
"c",
",",
"'%s %s'",
"%",
"(",
"tokens",
"[",
"0",
"]",
",",
"tokens",
"[",
"1",
"]",
")",
")",
"root_node",
".",
"add_child",
"(",
"node",
")",
"last_div_node",
"=",
"node",
"# do not take previous sections into account",
"if",
"last_section_node",
":",
"last_section_node",
".",
"end_line",
"=",
"l",
"last_section_node",
"=",
"None",
"return",
"last_div_node",
",",
"last_section_node"
] | Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last_div_node, last_section_node) | [
"Extracts",
"a",
"division",
"node",
"from",
"a",
"line"
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L125-L150 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | parse_section | def parse_section(l, c, last_div_node, last_vars, line):
"""
Extracts a section node from a line.
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: last_section_node
"""
name = line
name = name.replace(".", "")
node = Name(Name.Type.Section, l, c, name)
last_div_node.add_child(node)
last_section_node = node
# do not take previous var into account
last_vars.clear()
return last_section_node | python | def parse_section(l, c, last_div_node, last_vars, line):
"""
Extracts a section node from a line.
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: last_section_node
"""
name = line
name = name.replace(".", "")
node = Name(Name.Type.Section, l, c, name)
last_div_node.add_child(node)
last_section_node = node
# do not take previous var into account
last_vars.clear()
return last_section_node | [
"def",
"parse_section",
"(",
"l",
",",
"c",
",",
"last_div_node",
",",
"last_vars",
",",
"line",
")",
":",
"name",
"=",
"line",
"name",
"=",
"name",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"node",
"=",
"Name",
"(",
"Name",
".",
"Type",
".",
"Section",
",",
"l",
",",
"c",
",",
"name",
")",
"last_div_node",
".",
"add_child",
"(",
"node",
")",
"last_section_node",
"=",
"node",
"# do not take previous var into account",
"last_vars",
".",
"clear",
"(",
")",
"return",
"last_section_node"
] | Extracts a section node from a line.
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: last_section_node | [
"Extracts",
"a",
"section",
"node",
"from",
"a",
"line",
"."
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L153-L174 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | parse_pic_field | def parse_pic_field(l, c, last_section_node, last_vars, line):
"""
Parse a pic field line. Return A VariableNode or None in case of malformed
code.
:param l: The line number (starting from 0)
:param c: The column number (starting from 0)
:param last_section_node: The last section node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: The extracted variable node
"""
parent_node = None
raw_tokens = line.split(" ")
tokens = []
for t in raw_tokens:
if not t.isspace() and t != "":
tokens.append(t)
try:
if tokens[0].upper() == "FD":
lvl = 1
else:
lvl = int(tokens[0], 16)
name = tokens[1]
except ValueError:
return None
except IndexError:
# line not complete
return None
name = name.replace(".", "")
if name in ALL_KEYWORDS or name in ['-', '/']:
return None
m = re.findall(r'pic.*\.', line, re.IGNORECASE)
if m:
description = ' '.join([t for t in m[0].split(' ') if t])
else:
description = line
try:
index = description.lower().index('value')
except ValueError:
description = description.replace('.', '')
else:
description = description[index:].replace('value', '')[:80]
if lvl == int('78', 16):
lvl = 1
if lvl == 1:
parent_node = last_section_node
last_vars.clear()
else:
# find parent level
levels = sorted(last_vars.keys(), reverse=True)
for lv in levels:
if lv < lvl:
parent_node = last_vars[lv]
break
if not parent_node:
# malformed code
return None
# todo: enabled this with an option in pyqode 3.0
# if lvl == int('88', 16):
# return None
if not name or name.upper().strip() == 'PIC':
name = 'FILLER'
node = Name(Name.Type.Variable, l, c, name, description)
parent_node.add_child(node)
last_vars[lvl] = node
# remove closed variables
levels = sorted(last_vars.keys(), reverse=True)
for l in levels:
if l > lvl:
last_vars.pop(l)
return node | python | def parse_pic_field(l, c, last_section_node, last_vars, line):
"""
Parse a pic field line. Return A VariableNode or None in case of malformed
code.
:param l: The line number (starting from 0)
:param c: The column number (starting from 0)
:param last_section_node: The last section node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: The extracted variable node
"""
parent_node = None
raw_tokens = line.split(" ")
tokens = []
for t in raw_tokens:
if not t.isspace() and t != "":
tokens.append(t)
try:
if tokens[0].upper() == "FD":
lvl = 1
else:
lvl = int(tokens[0], 16)
name = tokens[1]
except ValueError:
return None
except IndexError:
# line not complete
return None
name = name.replace(".", "")
if name in ALL_KEYWORDS or name in ['-', '/']:
return None
m = re.findall(r'pic.*\.', line, re.IGNORECASE)
if m:
description = ' '.join([t for t in m[0].split(' ') if t])
else:
description = line
try:
index = description.lower().index('value')
except ValueError:
description = description.replace('.', '')
else:
description = description[index:].replace('value', '')[:80]
if lvl == int('78', 16):
lvl = 1
if lvl == 1:
parent_node = last_section_node
last_vars.clear()
else:
# find parent level
levels = sorted(last_vars.keys(), reverse=True)
for lv in levels:
if lv < lvl:
parent_node = last_vars[lv]
break
if not parent_node:
# malformed code
return None
# todo: enabled this with an option in pyqode 3.0
# if lvl == int('88', 16):
# return None
if not name or name.upper().strip() == 'PIC':
name = 'FILLER'
node = Name(Name.Type.Variable, l, c, name, description)
parent_node.add_child(node)
last_vars[lvl] = node
# remove closed variables
levels = sorted(last_vars.keys(), reverse=True)
for l in levels:
if l > lvl:
last_vars.pop(l)
return node | [
"def",
"parse_pic_field",
"(",
"l",
",",
"c",
",",
"last_section_node",
",",
"last_vars",
",",
"line",
")",
":",
"parent_node",
"=",
"None",
"raw_tokens",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"tokens",
"=",
"[",
"]",
"for",
"t",
"in",
"raw_tokens",
":",
"if",
"not",
"t",
".",
"isspace",
"(",
")",
"and",
"t",
"!=",
"\"\"",
":",
"tokens",
".",
"append",
"(",
"t",
")",
"try",
":",
"if",
"tokens",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"==",
"\"FD\"",
":",
"lvl",
"=",
"1",
"else",
":",
"lvl",
"=",
"int",
"(",
"tokens",
"[",
"0",
"]",
",",
"16",
")",
"name",
"=",
"tokens",
"[",
"1",
"]",
"except",
"ValueError",
":",
"return",
"None",
"except",
"IndexError",
":",
"# line not complete",
"return",
"None",
"name",
"=",
"name",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"if",
"name",
"in",
"ALL_KEYWORDS",
"or",
"name",
"in",
"[",
"'-'",
",",
"'/'",
"]",
":",
"return",
"None",
"m",
"=",
"re",
".",
"findall",
"(",
"r'pic.*\\.'",
",",
"line",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"m",
":",
"description",
"=",
"' '",
".",
"join",
"(",
"[",
"t",
"for",
"t",
"in",
"m",
"[",
"0",
"]",
".",
"split",
"(",
"' '",
")",
"if",
"t",
"]",
")",
"else",
":",
"description",
"=",
"line",
"try",
":",
"index",
"=",
"description",
".",
"lower",
"(",
")",
".",
"index",
"(",
"'value'",
")",
"except",
"ValueError",
":",
"description",
"=",
"description",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"else",
":",
"description",
"=",
"description",
"[",
"index",
":",
"]",
".",
"replace",
"(",
"'value'",
",",
"''",
")",
"[",
":",
"80",
"]",
"if",
"lvl",
"==",
"int",
"(",
"'78'",
",",
"16",
")",
":",
"lvl",
"=",
"1",
"if",
"lvl",
"==",
"1",
":",
"parent_node",
"=",
"last_section_node",
"last_vars",
".",
"clear",
"(",
")",
"else",
":",
"# find parent level",
"levels",
"=",
"sorted",
"(",
"last_vars",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"True",
")",
"for",
"lv",
"in",
"levels",
":",
"if",
"lv",
"<",
"lvl",
":",
"parent_node",
"=",
"last_vars",
"[",
"lv",
"]",
"break",
"if",
"not",
"parent_node",
":",
"# malformed code",
"return",
"None",
"# todo: enabled this with an option in pyqode 3.0",
"# if lvl == int('88', 16):",
"# return None",
"if",
"not",
"name",
"or",
"name",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"==",
"'PIC'",
":",
"name",
"=",
"'FILLER'",
"node",
"=",
"Name",
"(",
"Name",
".",
"Type",
".",
"Variable",
",",
"l",
",",
"c",
",",
"name",
",",
"description",
")",
"parent_node",
".",
"add_child",
"(",
"node",
")",
"last_vars",
"[",
"lvl",
"]",
"=",
"node",
"# remove closed variables",
"levels",
"=",
"sorted",
"(",
"last_vars",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"True",
")",
"for",
"l",
"in",
"levels",
":",
"if",
"l",
">",
"lvl",
":",
"last_vars",
".",
"pop",
"(",
"l",
")",
"return",
"node"
] | Parse a pic field line. Return A VariableNode or None in case of malformed
code.
:param l: The line number (starting from 0)
:param c: The column number (starting from 0)
:param last_section_node: The last section node found
:param last_vars: The last vars dict
:param line: The line string (without indentation)
:return: The extracted variable node | [
"Parse",
"a",
"pic",
"field",
"line",
".",
"Return",
"A",
"VariableNode",
"or",
"None",
"in",
"case",
"of",
"malformed",
"code",
"."
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L177-L248 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | parse_paragraph | def parse_paragraph(l, c, last_div_node, last_section_node, line):
"""
Extracts a paragraph node
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_section_node: The last section node found
:param line: The line string (without indentation)
:return: The extracted paragraph node
"""
if not line.endswith('.'):
return None
name = line.replace(".", "")
if name.strip() == '':
return None
if name.upper() in ALL_KEYWORDS:
return None
parent_node = last_div_node
if last_section_node is not None:
parent_node = last_section_node
node = Name(Name.Type.Paragraph, l, c, name)
parent_node.add_child(node)
return node | python | def parse_paragraph(l, c, last_div_node, last_section_node, line):
"""
Extracts a paragraph node
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_section_node: The last section node found
:param line: The line string (without indentation)
:return: The extracted paragraph node
"""
if not line.endswith('.'):
return None
name = line.replace(".", "")
if name.strip() == '':
return None
if name.upper() in ALL_KEYWORDS:
return None
parent_node = last_div_node
if last_section_node is not None:
parent_node = last_section_node
node = Name(Name.Type.Paragraph, l, c, name)
parent_node.add_child(node)
return node | [
"def",
"parse_paragraph",
"(",
"l",
",",
"c",
",",
"last_div_node",
",",
"last_section_node",
",",
"line",
")",
":",
"if",
"not",
"line",
".",
"endswith",
"(",
"'.'",
")",
":",
"return",
"None",
"name",
"=",
"line",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"if",
"name",
".",
"strip",
"(",
")",
"==",
"''",
":",
"return",
"None",
"if",
"name",
".",
"upper",
"(",
")",
"in",
"ALL_KEYWORDS",
":",
"return",
"None",
"parent_node",
"=",
"last_div_node",
"if",
"last_section_node",
"is",
"not",
"None",
":",
"parent_node",
"=",
"last_section_node",
"node",
"=",
"Name",
"(",
"Name",
".",
"Type",
".",
"Paragraph",
",",
"l",
",",
"c",
",",
"name",
")",
"parent_node",
".",
"add_child",
"(",
"node",
")",
"return",
"node"
] | Extracts a paragraph node
:param l: The line number (starting from 0)
:param last_div_node: The last div node found
:param last_section_node: The last section node found
:param line: The line string (without indentation)
:return: The extracted paragraph node | [
"Extracts",
"a",
"paragraph",
"node"
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L251-L273 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | Name.find | def find(self, name):
"""
Finds a possible child whose name match the name parameter.
:param name: name of the child node to look up
:type name: str
:return: DocumentNode or None
"""
for c in self.children:
if c.name == name:
return c
result = c.find(name)
if result:
return result | python | def find(self, name):
"""
Finds a possible child whose name match the name parameter.
:param name: name of the child node to look up
:type name: str
:return: DocumentNode or None
"""
for c in self.children:
if c.name == name:
return c
result = c.find(name)
if result:
return result | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"for",
"c",
"in",
"self",
".",
"children",
":",
"if",
"c",
".",
"name",
"==",
"name",
":",
"return",
"c",
"result",
"=",
"c",
".",
"find",
"(",
"name",
")",
"if",
"result",
":",
"return",
"result"
] | Finds a possible child whose name match the name parameter.
:param name: name of the child node to look up
:type name: str
:return: DocumentNode or None | [
"Finds",
"a",
"possible",
"child",
"whose",
"name",
"match",
"the",
"name",
"parameter",
"."
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L55-L69 | train |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | Name.to_definition | def to_definition(self):
"""
Converts the name instance to a pyqode.core.share.Definition
"""
icon = {
Name.Type.Root: icons.ICON_MIMETYPE,
Name.Type.Division: icons.ICON_DIVISION,
Name.Type.Section: icons.ICON_SECTION,
Name.Type.Variable: icons.ICON_VAR,
Name.Type.Paragraph: icons.ICON_FUNC
}[self.node_type]
d = Definition(self.name, self.line, self.column, icon, self.description)
for ch in self.children:
d.add_child(ch.to_definition())
return d | python | def to_definition(self):
"""
Converts the name instance to a pyqode.core.share.Definition
"""
icon = {
Name.Type.Root: icons.ICON_MIMETYPE,
Name.Type.Division: icons.ICON_DIVISION,
Name.Type.Section: icons.ICON_SECTION,
Name.Type.Variable: icons.ICON_VAR,
Name.Type.Paragraph: icons.ICON_FUNC
}[self.node_type]
d = Definition(self.name, self.line, self.column, icon, self.description)
for ch in self.children:
d.add_child(ch.to_definition())
return d | [
"def",
"to_definition",
"(",
"self",
")",
":",
"icon",
"=",
"{",
"Name",
".",
"Type",
".",
"Root",
":",
"icons",
".",
"ICON_MIMETYPE",
",",
"Name",
".",
"Type",
".",
"Division",
":",
"icons",
".",
"ICON_DIVISION",
",",
"Name",
".",
"Type",
".",
"Section",
":",
"icons",
".",
"ICON_SECTION",
",",
"Name",
".",
"Type",
".",
"Variable",
":",
"icons",
".",
"ICON_VAR",
",",
"Name",
".",
"Type",
".",
"Paragraph",
":",
"icons",
".",
"ICON_FUNC",
"}",
"[",
"self",
".",
"node_type",
"]",
"d",
"=",
"Definition",
"(",
"self",
".",
"name",
",",
"self",
".",
"line",
",",
"self",
".",
"column",
",",
"icon",
",",
"self",
".",
"description",
")",
"for",
"ch",
"in",
"self",
".",
"children",
":",
"d",
".",
"add_child",
"(",
"ch",
".",
"to_definition",
"(",
")",
")",
"return",
"d"
] | Converts the name instance to a pyqode.core.share.Definition | [
"Converts",
"the",
"name",
"instance",
"to",
"a",
"pyqode",
".",
"core",
".",
"share",
".",
"Definition"
] | eedae4e320a4b2d0c44abb2c3061091321648fb7 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L82-L96 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | connectDb | def connectDb(engine = dbeng,
user = dbuser,
password = dbpwd,
host = dbhost,
port = dbport,
database = dbname,
params = "?charset=utf8&use_unicode=1",
echoopt = False):
"""Connect to database utility function.
Uses SQLAlchemy ORM library.
Useful when using schema modules in MambuPy
"""
return create_engine('%s://%s:%s@%s:%s/%s%s' % (engine, user, password, host, port, database, params), echo=echoopt) | python | def connectDb(engine = dbeng,
user = dbuser,
password = dbpwd,
host = dbhost,
port = dbport,
database = dbname,
params = "?charset=utf8&use_unicode=1",
echoopt = False):
"""Connect to database utility function.
Uses SQLAlchemy ORM library.
Useful when using schema modules in MambuPy
"""
return create_engine('%s://%s:%s@%s:%s/%s%s' % (engine, user, password, host, port, database, params), echo=echoopt) | [
"def",
"connectDb",
"(",
"engine",
"=",
"dbeng",
",",
"user",
"=",
"dbuser",
",",
"password",
"=",
"dbpwd",
",",
"host",
"=",
"dbhost",
",",
"port",
"=",
"dbport",
",",
"database",
"=",
"dbname",
",",
"params",
"=",
"\"?charset=utf8&use_unicode=1\"",
",",
"echoopt",
"=",
"False",
")",
":",
"return",
"create_engine",
"(",
"'%s://%s:%s@%s:%s/%s%s'",
"%",
"(",
"engine",
",",
"user",
",",
"password",
",",
"host",
",",
"port",
",",
"database",
",",
"params",
")",
",",
"echo",
"=",
"echoopt",
")"
] | Connect to database utility function.
Uses SQLAlchemy ORM library.
Useful when using schema modules in MambuPy | [
"Connect",
"to",
"database",
"utility",
"function",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L67-L81 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getbranchesurl | def getbranchesurl(idbranch, *args, **kwargs):
"""Request Branches URL.
If idbranch is set, you'll get a response adequate for a MambuBranch object.
If not set, you'll get a response adequate for a MambuBranches object.
See mambubranch module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
branchidparam = "" if idbranch == "" else "/"+idbranch
url = getmambuurl(*args, **kwargs) + "branches" + branchidparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getbranchesurl(idbranch, *args, **kwargs):
"""Request Branches URL.
If idbranch is set, you'll get a response adequate for a MambuBranch object.
If not set, you'll get a response adequate for a MambuBranches object.
See mambubranch module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
branchidparam = "" if idbranch == "" else "/"+idbranch
url = getmambuurl(*args, **kwargs) + "branches" + branchidparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getbranchesurl",
"(",
"idbranch",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"branchidparam",
"=",
"\"\"",
"if",
"idbranch",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idbranch",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"branches\"",
"+",
"branchidparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Branches URL.
If idbranch is set, you'll get a response adequate for a MambuBranch object.
If not set, you'll get a response adequate for a MambuBranches object.
See mambubranch module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Branches",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L100-L135 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getcentresurl | def getcentresurl(idcentre, *args, **kwargs):
"""Request Centres URL.
If idcentre is set, you'll get a response adequate for a MambuCentre object.
If not set, you'll get a response adequate for a MambuCentres object.
See mambucentre module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
centreidparam = "" if idcentre == "" else "/"+idcentre
url = getmambuurl(*args, **kwargs) + "centres" + centreidparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getcentresurl(idcentre, *args, **kwargs):
"""Request Centres URL.
If idcentre is set, you'll get a response adequate for a MambuCentre object.
If not set, you'll get a response adequate for a MambuCentres object.
See mambucentre module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
centreidparam = "" if idcentre == "" else "/"+idcentre
url = getmambuurl(*args, **kwargs) + "centres" + centreidparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getcentresurl",
"(",
"idcentre",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"centreidparam",
"=",
"\"\"",
"if",
"idcentre",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idcentre",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"centres\"",
"+",
"centreidparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Centres URL.
If idcentre is set, you'll get a response adequate for a MambuCentre object.
If not set, you'll get a response adequate for a MambuCentres object.
See mambucentre module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Centres",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L137-L172 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getrepaymentsurl | def getrepaymentsurl(idcred, *args, **kwargs):
"""Request loan Repayments URL.
If idcred is set, you'll get a response adequate for a
MambuRepayments object. There's a MambuRepayment object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuRepayment object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for repayments of one and just
one loan account.
See mamburepayment module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
url = getmambuurl(*args,**kwargs) + "loans/" + idcred + "/repayments"
return url | python | def getrepaymentsurl(idcred, *args, **kwargs):
"""Request loan Repayments URL.
If idcred is set, you'll get a response adequate for a
MambuRepayments object. There's a MambuRepayment object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuRepayment object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for repayments of one and just
one loan account.
See mamburepayment module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
url = getmambuurl(*args,**kwargs) + "loans/" + idcred + "/repayments"
return url | [
"def",
"getrepaymentsurl",
"(",
"idcred",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"loans/\"",
"+",
"idcred",
"+",
"\"/repayments\"",
"return",
"url"
] | Request loan Repayments URL.
If idcred is set, you'll get a response adequate for a
MambuRepayments object. There's a MambuRepayment object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuRepayment object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for repayments of one and just
one loan account.
See mamburepayment module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"loan",
"Repayments",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L174-L195 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getloansurl | def getloansurl(idcred, *args, **kwargs):
"""Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* accountState
* branchId
* centreId
* creditOfficerUsername
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("centreId=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("creditOfficerUsername=%s" % kwargs["creditOfficerUsername"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
idcredparam = "" if idcred == "" else "/"+idcred
url = getmambuurl(*args,**kwargs) + "loans" + idcredparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getloansurl(idcred, *args, **kwargs):
"""Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* accountState
* branchId
* centreId
* creditOfficerUsername
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("centreId=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("creditOfficerUsername=%s" % kwargs["creditOfficerUsername"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
idcredparam = "" if idcred == "" else "/"+idcred
url = getmambuurl(*args,**kwargs) + "loans" + idcredparam + ("" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getloansurl",
"(",
"idcred",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"accountState=%s\"",
"%",
"kwargs",
"[",
"\"accountState\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"branchId=%s\"",
"%",
"kwargs",
"[",
"\"branchId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"centreId=%s\"",
"%",
"kwargs",
"[",
"\"centreId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"creditOfficerUsername=%s\"",
"%",
"kwargs",
"[",
"\"creditOfficerUsername\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"idcredparam",
"=",
"\"\"",
"if",
"idcred",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idcred",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"loans\"",
"+",
"idcredparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Loans URL.
If idcred is set, you'll get a response adequate for a MambuLoan object.
If not set, you'll get a response adequate for a MambuLoans object.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* accountState
* branchId
* centreId
* creditOfficerUsername
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Loans",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L197-L252 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getgroupurl | def getgroupurl(idgroup, *args, **kwargs):
"""Request Groups URL.
If idgroup is set, you'll get a response adequate for a MambuGroup object.
If not set, you'll get a response adequate for a MambuGroups object.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* creditOfficerUsername
* branchId
* centreId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("creditOfficerUsername=%s" % kwargs["creditOfficerUsername"])
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("centreId=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
groupidparam = "" if idgroup == "" else "/"+idgroup
url = getmambuurl(*args,**kwargs) + "groups" + groupidparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getgroupurl(idgroup, *args, **kwargs):
"""Request Groups URL.
If idgroup is set, you'll get a response adequate for a MambuGroup object.
If not set, you'll get a response adequate for a MambuGroups object.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* creditOfficerUsername
* branchId
* centreId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("creditOfficerUsername=%s" % kwargs["creditOfficerUsername"])
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("centreId=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
groupidparam = "" if idgroup == "" else "/"+idgroup
url = getmambuurl(*args,**kwargs) + "groups" + groupidparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getgroupurl",
"(",
"idgroup",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"creditOfficerUsername=%s\"",
"%",
"kwargs",
"[",
"\"creditOfficerUsername\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"branchId=%s\"",
"%",
"kwargs",
"[",
"\"branchId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"centreId=%s\"",
"%",
"kwargs",
"[",
"\"centreId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"groupidparam",
"=",
"\"\"",
"if",
"idgroup",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idgroup",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"groups\"",
"+",
"groupidparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Groups URL.
If idgroup is set, you'll get a response adequate for a MambuGroup object.
If not set, you'll get a response adequate for a MambuGroups object.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* creditOfficerUsername
* branchId
* centreId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Groups",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L254-L303 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getgrouploansurl | def getgrouploansurl(idgroup, *args, **kwargs):
"""Request Group loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getgrouploansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain group.
If idgroup is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one group.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
groupidparam = "/" + idgroup
url = getmambuurl(*args,**kwargs) + "groups" + groupidparam + "/loans" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getgrouploansurl(idgroup, *args, **kwargs):
"""Request Group loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getgrouploansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain group.
If idgroup is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one group.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
groupidparam = "/" + idgroup
url = getmambuurl(*args,**kwargs) + "groups" + groupidparam + "/loans" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getgrouploansurl",
"(",
"idgroup",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"accountState=%s\"",
"%",
"kwargs",
"[",
"\"accountState\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"groupidparam",
"=",
"\"/\"",
"+",
"idgroup",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"groups\"",
"+",
"groupidparam",
"+",
"\"/loans\"",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Group loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getgrouploansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain group.
If idgroup is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one group.
See mambugroup module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Group",
"loans",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L305-L344 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getgroupcustominformationurl | def getgroupcustominformationurl(idgroup, customfield="", *args, **kwargs):
"""Request Group Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
groupidparam = "/" + idgroup
url = getmambuurl(*args, **kwargs) + "groups" + groupidparam + "/custominformation" + ( ("/"+customfield) if customfield else "" )
return url | python | def getgroupcustominformationurl(idgroup, customfield="", *args, **kwargs):
"""Request Group Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
groupidparam = "/" + idgroup
url = getmambuurl(*args, **kwargs) + "groups" + groupidparam + "/custominformation" + ( ("/"+customfield) if customfield else "" )
return url | [
"def",
"getgroupcustominformationurl",
"(",
"idgroup",
",",
"customfield",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"groupidparam",
"=",
"\"/\"",
"+",
"idgroup",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"groups\"",
"+",
"groupidparam",
"+",
"\"/custominformation\"",
"+",
"(",
"(",
"\"/\"",
"+",
"customfield",
")",
"if",
"customfield",
"else",
"\"\"",
")",
"return",
"url"
] | Request Group Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Group",
"Custom",
"Information",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L346-L356 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | gettransactionsurl | def gettransactionsurl(idcred, *args, **kwargs):
"""Request loan Transactions URL.
If idcred is set, you'll get a response adequate for a
MambuTransactions object. There's a MambuTransaction object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuTransaction object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for transactions of one and just
one loan account.
See mambutransaction module and pydoc for further information.
Currently implemented filter parameters:
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "loans/" + idcred + "/transactions" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def gettransactionsurl(idcred, *args, **kwargs):
"""Request loan Transactions URL.
If idcred is set, you'll get a response adequate for a
MambuTransactions object. There's a MambuTransaction object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuTransaction object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for transactions of one and just
one loan account.
See mambutransaction module and pydoc for further information.
Currently implemented filter parameters:
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "loans/" + idcred + "/transactions" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"gettransactionsurl",
"(",
"idcred",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"loans/\"",
"+",
"idcred",
"+",
"\"/transactions\"",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request loan Transactions URL.
If idcred is set, you'll get a response adequate for a
MambuTransactions object. There's a MambuTransaction object too, but
you'll get a list first and each element of it will be automatically
converted to a MambuTransaction object that you may use.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for transactions of one and just
one loan account.
See mambutransaction module and pydoc for further information.
Currently implemented filter parameters:
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"loan",
"Transactions",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L358-L391 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getclienturl | def getclienturl(idclient, *args, **kwargs):
"""Request Clients URL.
If idclient is set, you'll get a response adequate for a MambuClient object.
If not set, you'll get a response adequate for a MambuClients object.
See mambuclient module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* firstName
* lastName
* idDocument
* birthdate
* state
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("firstName=%s" % kwargs["firstName"])
except Exception as ex:
pass
try:
getparams.append("lastName=%s" % kwargs["lastName"])
except Exception as ex:
pass
try:
getparams.append("idDocument=%s" % kwargs["idDocument"])
except Exception as ex:
pass
try:
getparams.append("birthdate=%s" % kwargs["birthdate"])
except Exception as ex:
pass
try:
getparams.append("state=%s" % kwargs["state"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
clientidparam = "" if idclient == "" else "/"+idclient
url = getmambuurl(*args,**kwargs) + "clients" + clientidparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getclienturl(idclient, *args, **kwargs):
"""Request Clients URL.
If idclient is set, you'll get a response adequate for a MambuClient object.
If not set, you'll get a response adequate for a MambuClients object.
See mambuclient module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* firstName
* lastName
* idDocument
* birthdate
* state
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("firstName=%s" % kwargs["firstName"])
except Exception as ex:
pass
try:
getparams.append("lastName=%s" % kwargs["lastName"])
except Exception as ex:
pass
try:
getparams.append("idDocument=%s" % kwargs["idDocument"])
except Exception as ex:
pass
try:
getparams.append("birthdate=%s" % kwargs["birthdate"])
except Exception as ex:
pass
try:
getparams.append("state=%s" % kwargs["state"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
clientidparam = "" if idclient == "" else "/"+idclient
url = getmambuurl(*args,**kwargs) + "clients" + clientidparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getclienturl",
"(",
"idclient",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"firstName=%s\"",
"%",
"kwargs",
"[",
"\"firstName\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"lastName=%s\"",
"%",
"kwargs",
"[",
"\"lastName\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"idDocument=%s\"",
"%",
"kwargs",
"[",
"\"idDocument\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"birthdate=%s\"",
"%",
"kwargs",
"[",
"\"birthdate\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"state=%s\"",
"%",
"kwargs",
"[",
"\"state\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"clientidparam",
"=",
"\"\"",
"if",
"idclient",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idclient",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"clients\"",
"+",
"clientidparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Clients URL.
If idclient is set, you'll get a response adequate for a MambuClient object.
If not set, you'll get a response adequate for a MambuClients object.
See mambuclient module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* firstName
* lastName
* idDocument
* birthdate
* state
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Clients",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L393-L452 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getclientloansurl | def getclientloansurl(idclient, *args, **kwargs):
"""Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain client.
If idclient is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one client.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
clientidparam = "/" + idclient
url = getmambuurl(*args,**kwargs) + "clients" + clientidparam + "/loans" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getclientloansurl(idclient, *args, **kwargs):
"""Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain client.
If idclient is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one client.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("accountState=%s" % kwargs["accountState"])
except Exception as ex:
pass
clientidparam = "/" + idclient
url = getmambuurl(*args,**kwargs) + "clients" + clientidparam + "/loans" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getclientloansurl",
"(",
"idclient",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"accountState=%s\"",
"%",
"kwargs",
"[",
"\"accountState\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"clientidparam",
"=",
"\"/\"",
"+",
"idclient",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"clients\"",
"+",
"clientidparam",
"+",
"\"/loans\"",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain client.
If idclient is set, you'll get a response adequate for a
MambuLoans object.
If not set, you'll get a Jar Jar Binks object, or something quite
strange and useless as JarJar. A MambuError must likely since I
haven't needed it for anything but for loans of one and just
one client.
See mambuloan module and pydoc for further information.
Currently implemented filter parameters:
* accountState
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Client",
"loans",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L454-L493 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getclientcustominformationurl | def getclientcustominformationurl(idclient, customfield="", *args, **kwargs):
"""Request Client Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
clientidparam = "/" + idclient
url = getmambuurl(*args, **kwargs) + "clients" + clientidparam + "/custominformation" + ( ("/"+customfield) if customfield else "" )
return url | python | def getclientcustominformationurl(idclient, customfield="", *args, **kwargs):
"""Request Client Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
clientidparam = "/" + idclient
url = getmambuurl(*args, **kwargs) + "clients" + clientidparam + "/custominformation" + ( ("/"+customfield) if customfield else "" )
return url | [
"def",
"getclientcustominformationurl",
"(",
"idclient",
",",
"customfield",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"clientidparam",
"=",
"\"/\"",
"+",
"idclient",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"clients\"",
"+",
"clientidparam",
"+",
"\"/custominformation\"",
"+",
"(",
"(",
"\"/\"",
"+",
"customfield",
")",
"if",
"customfield",
"else",
"\"\"",
")",
"return",
"url"
] | Request Client Custom Information URL.
See mambugroup module and pydoc for further information.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Client",
"Custom",
"Information",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L495-L505 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getuserurl | def getuserurl(iduser, *args, **kwargs):
"""Request Users URL.
If iduser is set, you'll get a response adequate for a MambuUser object.
If not set, you'll get a response adequate for a MambuUsers object.
See mambuuser module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* branchId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
useridparam = "" if iduser == "" else "/"+iduser
url = getmambuurl(*args,**kwargs) + "users" + useridparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getuserurl(iduser, *args, **kwargs):
"""Request Users URL.
If iduser is set, you'll get a response adequate for a MambuUser object.
If not set, you'll get a response adequate for a MambuUsers object.
See mambuuser module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* branchId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pass
try:
getparams.append("branchId=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
useridparam = "" if iduser == "" else "/"+iduser
url = getmambuurl(*args,**kwargs) + "users" + useridparam + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getuserurl",
"(",
"iduser",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=true\"",
")",
"else",
":",
"getparams",
".",
"append",
"(",
"\"fullDetails=false\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"branchId=%s\"",
"%",
"kwargs",
"[",
"\"branchId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"useridparam",
"=",
"\"\"",
"if",
"iduser",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"iduser",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"users\"",
"+",
"useridparam",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Users URL.
If iduser is set, you'll get a response adequate for a MambuUser object.
If not set, you'll get a response adequate for a MambuUsers object.
See mambuuser module and pydoc for further information.
Currently implemented filter parameters:
* fullDetails
* branchId
* limit
* offset
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Users",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L507-L546 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getproductsurl | def getproductsurl(idproduct, *args, **kwargs):
"""Request loan Products URL.
If idproduct is set, you'll get a response adequate for a MambuProduct object.
If not set, you'll get a response adequate for a MambuProducts object.
See mambuproduct module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
productidparam = "" if idproduct == "" else "/"+idproduct
url = getmambuurl(*args,**kwargs) + "loanproducts" + productidparam
return url | python | def getproductsurl(idproduct, *args, **kwargs):
"""Request loan Products URL.
If idproduct is set, you'll get a response adequate for a MambuProduct object.
If not set, you'll get a response adequate for a MambuProducts object.
See mambuproduct module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
productidparam = "" if idproduct == "" else "/"+idproduct
url = getmambuurl(*args,**kwargs) + "loanproducts" + productidparam
return url | [
"def",
"getproductsurl",
"(",
"idproduct",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"productidparam",
"=",
"\"\"",
"if",
"idproduct",
"==",
"\"\"",
"else",
"\"/\"",
"+",
"idproduct",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"loanproducts\"",
"+",
"productidparam",
"return",
"url"
] | Request loan Products URL.
If idproduct is set, you'll get a response adequate for a MambuProduct object.
If not set, you'll get a response adequate for a MambuProducts object.
See mambuproduct module and pydoc for further information.
No current implemented filter parameters.
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"loan",
"Products",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L548-L562 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | gettasksurl | def gettasksurl(dummyId='', *args, **kwargs):
"""Request Tasks URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Tasks, because of
that dummyId defaults to '', but in practice it is never used (if
someone sends dummyId='someId' nothing happens). The fact of forcing
to send an entid is a technical debt that should be payed.
Currently implemented filter parameters:
* username
* clientId
* groupId
* status
* limit
* offset
Mambu REST API defaults to open when status not provided. Here we
are just making that explicit always defaulting status to 'OPEN'
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
getparams.append("username=%s" % kwargs["username"])
except Exception as ex:
pass
try:
getparams.append("clientid=%s" % kwargs["clientId"])
except Exception as ex:
pass
try:
getparams.append("groupid=%s" % kwargs["groupId"])
except Exception as ex:
pass
try:
getparams.append("status=%s" % kwargs["status"])
except Exception as ex:
getparams.append("status=OPEN")
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "tasks" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def gettasksurl(dummyId='', *args, **kwargs):
"""Request Tasks URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Tasks, because of
that dummyId defaults to '', but in practice it is never used (if
someone sends dummyId='someId' nothing happens). The fact of forcing
to send an entid is a technical debt that should be payed.
Currently implemented filter parameters:
* username
* clientId
* groupId
* status
* limit
* offset
Mambu REST API defaults to open when status not provided. Here we
are just making that explicit always defaulting status to 'OPEN'
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
getparams = []
if kwargs:
try:
getparams.append("username=%s" % kwargs["username"])
except Exception as ex:
pass
try:
getparams.append("clientid=%s" % kwargs["clientId"])
except Exception as ex:
pass
try:
getparams.append("groupid=%s" % kwargs["groupId"])
except Exception as ex:
pass
try:
getparams.append("status=%s" % kwargs["status"])
except Exception as ex:
getparams.append("status=OPEN")
try:
getparams.append("offset=%s" % kwargs["offset"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "tasks" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"gettasksurl",
"(",
"dummyId",
"=",
"''",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"getparams",
".",
"append",
"(",
"\"username=%s\"",
"%",
"kwargs",
"[",
"\"username\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"clientid=%s\"",
"%",
"kwargs",
"[",
"\"clientId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"groupid=%s\"",
"%",
"kwargs",
"[",
"\"groupId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"status=%s\"",
"%",
"kwargs",
"[",
"\"status\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"getparams",
".",
"append",
"(",
"\"status=OPEN\"",
")",
"try",
":",
"getparams",
".",
"append",
"(",
"\"offset=%s\"",
"%",
"kwargs",
"[",
"\"offset\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"tasks\"",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Tasks URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Tasks, because of
that dummyId defaults to '', but in practice it is never used (if
someone sends dummyId='someId' nothing happens). The fact of forcing
to send an entid is a technical debt that should be payed.
Currently implemented filter parameters:
* username
* clientId
* groupId
* status
* limit
* offset
Mambu REST API defaults to open when status not provided. Here we
are just making that explicit always defaulting status to 'OPEN'
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Tasks",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L564-L620 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getactivitiesurl | def getactivitiesurl(dummyId='', *args, **kwargs):
"""Request Activities URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Activities,
because of that dummyId defaults to '', but in practice it is never
used (if someone sends dummyId='someId' nothing happens). The fact
of forcing to send an entid is a technical debt that should be
payed.
Currently implemented filter parameters:
* from
* to
* branchID
* clientID
* centreID
* userID
* loanAccountID
* groupID
* limit
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
from datetime import datetime
getparams = []
if kwargs:
try:
getparams.append("from=%s" % kwargs["fromDate"])
except Exception as ex:
getparams.append("from=%s" % '1900-01-01')
try:
getparams.append("to=%s" % kwargs["toDate"])
except Exception as ex:
hoy = datetime.now().strftime('%Y-%m-%d')
getparams.append("to=%s" % hoy)
try:
getparams.append("branchID=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("clientID=%s" % kwargs["clientId"])
except Exception as ex:
pass
try:
getparams.append("centreID=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("userID=%s" % kwargs["userId"])
except Exception as ex:
pass
try:
getparams.append("loanAccountID=%s" % kwargs["loanAccountId"])
except Exception as ex:
pass
try:
getparams.append("groupID=%s" % kwargs["groupId"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "activities" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | python | def getactivitiesurl(dummyId='', *args, **kwargs):
"""Request Activities URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Activities,
because of that dummyId defaults to '', but in practice it is never
used (if someone sends dummyId='someId' nothing happens). The fact
of forcing to send an entid is a technical debt that should be
payed.
Currently implemented filter parameters:
* from
* to
* branchID
* clientID
* centreID
* userID
* loanAccountID
* groupID
* limit
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future.
"""
from datetime import datetime
getparams = []
if kwargs:
try:
getparams.append("from=%s" % kwargs["fromDate"])
except Exception as ex:
getparams.append("from=%s" % '1900-01-01')
try:
getparams.append("to=%s" % kwargs["toDate"])
except Exception as ex:
hoy = datetime.now().strftime('%Y-%m-%d')
getparams.append("to=%s" % hoy)
try:
getparams.append("branchID=%s" % kwargs["branchId"])
except Exception as ex:
pass
try:
getparams.append("clientID=%s" % kwargs["clientId"])
except Exception as ex:
pass
try:
getparams.append("centreID=%s" % kwargs["centreId"])
except Exception as ex:
pass
try:
getparams.append("userID=%s" % kwargs["userId"])
except Exception as ex:
pass
try:
getparams.append("loanAccountID=%s" % kwargs["loanAccountId"])
except Exception as ex:
pass
try:
getparams.append("groupID=%s" % kwargs["groupId"])
except Exception as ex:
pass
try:
getparams.append("limit=%s" % kwargs["limit"])
except Exception as ex:
pass
url = getmambuurl(*args,**kwargs) + "activities" + ( "" if len(getparams) == 0 else "?" + "&".join(getparams) )
return url | [
"def",
"getactivitiesurl",
"(",
"dummyId",
"=",
"''",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"datetime",
"import",
"datetime",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"getparams",
".",
"append",
"(",
"\"from=%s\"",
"%",
"kwargs",
"[",
"\"fromDate\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"getparams",
".",
"append",
"(",
"\"from=%s\"",
"%",
"'1900-01-01'",
")",
"try",
":",
"getparams",
".",
"append",
"(",
"\"to=%s\"",
"%",
"kwargs",
"[",
"\"toDate\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"hoy",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"getparams",
".",
"append",
"(",
"\"to=%s\"",
"%",
"hoy",
")",
"try",
":",
"getparams",
".",
"append",
"(",
"\"branchID=%s\"",
"%",
"kwargs",
"[",
"\"branchId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"clientID=%s\"",
"%",
"kwargs",
"[",
"\"clientId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"centreID=%s\"",
"%",
"kwargs",
"[",
"\"centreId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"userID=%s\"",
"%",
"kwargs",
"[",
"\"userId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"loanAccountID=%s\"",
"%",
"kwargs",
"[",
"\"loanAccountId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"groupID=%s\"",
"%",
"kwargs",
"[",
"\"groupId\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"try",
":",
"getparams",
".",
"append",
"(",
"\"limit=%s\"",
"%",
"kwargs",
"[",
"\"limit\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"pass",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"activities\"",
"+",
"(",
"\"\"",
"if",
"len",
"(",
"getparams",
")",
"==",
"0",
"else",
"\"?\"",
"+",
"\"&\"",
".",
"join",
"(",
"getparams",
")",
")",
"return",
"url"
] | Request Activities URL.
dummyId is used because MambuStruct always requires an Id from an
entity, but the Mambu API doesn't requires it for Activities,
because of that dummyId defaults to '', but in practice it is never
used (if someone sends dummyId='someId' nothing happens). The fact
of forcing to send an entid is a technical debt that should be
payed.
Currently implemented filter parameters:
* from
* to
* branchID
* clientID
* centreID
* userID
* loanAccountID
* groupID
* limit
See Mambu official developer documentation for further details, and
info on parameters that may be implemented here in the future. | [
"Request",
"Activities",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L622-L697 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | getrolesurl | def getrolesurl(idrole='', *args, **kwargs):
"""Request Roles URL.
If idrole is set, you'll get a response adequate for a MambuRole
object. If not set, you'll get a response adequate for a MambuRoles
object too. See mamburoles module and pydoc for further
information.
See Mambu official developer documentation for further details.
"""
url = getmambuurl(*args,**kwargs) + "userroles" + (("/" + idrole) if idrole else "")
return url | python | def getrolesurl(idrole='', *args, **kwargs):
"""Request Roles URL.
If idrole is set, you'll get a response adequate for a MambuRole
object. If not set, you'll get a response adequate for a MambuRoles
object too. See mamburoles module and pydoc for further
information.
See Mambu official developer documentation for further details.
"""
url = getmambuurl(*args,**kwargs) + "userroles" + (("/" + idrole) if idrole else "")
return url | [
"def",
"getrolesurl",
"(",
"idrole",
"=",
"''",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"userroles\"",
"+",
"(",
"(",
"\"/\"",
"+",
"idrole",
")",
"if",
"idrole",
"else",
"\"\"",
")",
"return",
"url"
] | Request Roles URL.
If idrole is set, you'll get a response adequate for a MambuRole
object. If not set, you'll get a response adequate for a MambuRoles
object too. See mamburoles module and pydoc for further
information.
See Mambu official developer documentation for further details. | [
"Request",
"Roles",
"URL",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L699-L710 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | strip_tags | def strip_tags(html):
"""Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
from html.parser import HTMLParser
class MLStripper(HTMLParser):
"""Aux class for stripping HTML tags.
fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
def __init__(self):
try:
super().__init__() # required for python3
except TypeError as e:
pass # with python2 raises TypeError
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
s = MLStripper()
s.feed(html.replace(" "," "))
return s.get_data() | python | def strip_tags(html):
"""Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
from html.parser import HTMLParser
class MLStripper(HTMLParser):
"""Aux class for stripping HTML tags.
fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea.
"""
def __init__(self):
try:
super().__init__() # required for python3
except TypeError as e:
pass # with python2 raises TypeError
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
s = MLStripper()
s.feed(html.replace(" "," "))
return s.get_data() | [
"def",
"strip_tags",
"(",
"html",
")",
":",
"from",
"html",
".",
"parser",
"import",
"HTMLParser",
"class",
"MLStripper",
"(",
"HTMLParser",
")",
":",
"\"\"\"Aux class for stripping HTML tags.\n\n fields on several Mambu entities come with additional HTML tags\n (they are rich text fields, I guess that's why). Sometimes they are\n useless, so stripping them is a good idea.\n \"\"\"",
"def",
"__init__",
"(",
"self",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"# required for python3",
"except",
"TypeError",
"as",
"e",
":",
"pass",
"# with python2 raises TypeError",
"self",
".",
"reset",
"(",
")",
"self",
".",
"fed",
"=",
"[",
"]",
"def",
"handle_data",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"fed",
".",
"append",
"(",
"d",
")",
"def",
"get_data",
"(",
"self",
")",
":",
"return",
"''",
".",
"join",
"(",
"self",
".",
"fed",
")",
"s",
"=",
"MLStripper",
"(",
")",
"s",
".",
"feed",
"(",
"html",
".",
"replace",
"(",
"\" \"",
",",
"\" \"",
")",
")",
"return",
"s",
".",
"get_data",
"(",
")"
] | Stripts HTML tags from text.
Note fields on several Mambu entities come with additional HTML tags
(they are rich text fields, I guess that's why). Sometimes they are
useless, so stripping them is a good idea. | [
"Stripts",
"HTML",
"tags",
"from",
"text",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L715-L744 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | strip_consecutive_repeated_char | def strip_consecutive_repeated_char(s, ch):
"""Strip characters in a string which are consecutively repeated.
Useful when in notes or some other free text fields on Mambu, users
capture anything and a lot of capture errors not always detected by
Mambu get through. You want some cleaning? this may be useful.
This is a string processing function.
"""
sdest = ""
for i,c in enumerate(s):
if i != 0 and s[i] == ch and s[i] == s[i-1]:
continue
sdest += s[i]
return sdest | python | def strip_consecutive_repeated_char(s, ch):
"""Strip characters in a string which are consecutively repeated.
Useful when in notes or some other free text fields on Mambu, users
capture anything and a lot of capture errors not always detected by
Mambu get through. You want some cleaning? this may be useful.
This is a string processing function.
"""
sdest = ""
for i,c in enumerate(s):
if i != 0 and s[i] == ch and s[i] == s[i-1]:
continue
sdest += s[i]
return sdest | [
"def",
"strip_consecutive_repeated_char",
"(",
"s",
",",
"ch",
")",
":",
"sdest",
"=",
"\"\"",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"s",
")",
":",
"if",
"i",
"!=",
"0",
"and",
"s",
"[",
"i",
"]",
"==",
"ch",
"and",
"s",
"[",
"i",
"]",
"==",
"s",
"[",
"i",
"-",
"1",
"]",
":",
"continue",
"sdest",
"+=",
"s",
"[",
"i",
"]",
"return",
"sdest"
] | Strip characters in a string which are consecutively repeated.
Useful when in notes or some other free text fields on Mambu, users
capture anything and a lot of capture errors not always detected by
Mambu get through. You want some cleaning? this may be useful.
This is a string processing function. | [
"Strip",
"characters",
"in",
"a",
"string",
"which",
"are",
"consecutively",
"repeated",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L747-L761 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | encoded_dict | def encoded_dict(in_dict):
"""Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode.
"""
out_dict = {}
for k, v in in_dict.items():
if isinstance(v, unicode):
if sys.version_info < (3, 0):
v = v.encode('utf8')
elif isinstance(v, str):
# Must be encoded in UTF-8
if sys.version_info < (3, 0):
v.decode('utf8')
out_dict[k] = v
return out_dict | python | def encoded_dict(in_dict):
"""Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode.
"""
out_dict = {}
for k, v in in_dict.items():
if isinstance(v, unicode):
if sys.version_info < (3, 0):
v = v.encode('utf8')
elif isinstance(v, str):
# Must be encoded in UTF-8
if sys.version_info < (3, 0):
v.decode('utf8')
out_dict[k] = v
return out_dict | [
"def",
"encoded_dict",
"(",
"in_dict",
")",
":",
"out_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"in_dict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"unicode",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"v",
"=",
"v",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"# Must be encoded in UTF-8",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"v",
".",
"decode",
"(",
"'utf8'",
")",
"out_dict",
"[",
"k",
"]",
"=",
"v",
"return",
"out_dict"
] | Encode every value of a dict to UTF-8.
Useful for POSTing requests on the 'data' parameter of urlencode. | [
"Encode",
"every",
"value",
"of",
"a",
"dict",
"to",
"UTF",
"-",
"8",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L811-L826 | train |
jstitch/MambuPy | MambuPy/mambuutil.py | backup_db | def backup_db(callback, bool_func, output_fname, *args, **kwargs):
"""Backup Mambu Database via REST API.
Makes two calls to Mambu API:
- a POST to request a backup to be made
- a GET, once the backup is ready, to download the latest backup
* callback is a string to a callback URL Mambu will internally call
when the backup is ready to download. You should have a webservice
there to warn you when the backup is ready.
* bool_func is a function you use against your own code to test if the
said backup is ready. This function backup_db manages both the logic
of the request of a backup and the downloading of it too, so
bool_func allows you to have some way on your side to know when this
function will download the backup.
The thing is you have to build a webservice (for the callback)
making some kind of flag turn that your bool_func will read and know
when to say True, telling backup_db to begin the download of the
backup.
* output_fname the name of the file that will hold the downloaded
backup. PLEASE MIND that Mambu sends a ZIP file here.
* user, pwd and url allow you to change the Mambu permissions for
the getmambuurl internally called here.
* verbose is a boolean flag for verbosity.
* retries number of retries for bool_func or -1 for keep waiting.
* force_download_latest boolean, True to force download even if no
callback is called. False to throw error if callback isn't received
after retries.
* returns a dictionary with info about the download
-latest boolean flag, if the db downloaded was the latest or not
"""
from datetime import datetime
try:
verbose = kwargs['verbose']
except KeyError:
verbose = False
try:
retries = kwargs['retries']
except KeyError:
retries = -1
try:
force_download_latest = bool(kwargs['force_download_latest'])
except KeyError:
force_download_latest = False
if verbose:
log = open('/tmp/log_mambu_backup','a')
log.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " - Mambu DB Backup\n")
log.flush()
user = kwargs.pop('user', apiuser)
pwd = kwargs.pop('pwd', apipwd)
data = {'callback' : callback}
try:
posturl = iriToUri(getmambuurl(*args, **kwargs) + "database/backup")
if verbose:
log.write("open url: "+posturl+"\n")
log.flush()
resp = requests.post(posturl, data=data, headers={'content-type': 'application/json'}, auth=(apiuser, apipwd))
except Exception as ex:
mess = "Error requesting backup: %s" % repr(ex)
if verbose:
log.write(mess + "\n")
log.close()
raise MambuError(mess)
if resp.status_code != 200:
mess = "Error posting request for backup: %s" % resp.content
if verbose:
log.write(mess + "\n")
log.close()
raise MambuCommError(mess)
data['latest'] = True
while retries and not bool_func():
if verbose:
log.write("waiting...\n")
log.flush()
sleep(10)
retries -= 1
if retries < 0: retries = -1
if not retries:
mess = "Tired of waiting, giving up..."
if verbose:
log.write(mess + "\n")
log.flush()
if not force_download_latest:
if verbose:
log.close()
raise MambuError(mess)
else:
data['latest'] = False
sleep(30)
geturl = iriToUri(getmambuurl(*args, **kwargs) + "database/backup/LATEST")
if verbose:
log.write("open url: "+geturl+"\n")
log.flush()
resp = requests.get(geturl, auth=(apiuser, apipwd))
if resp.status_code != 200:
mess = "Error getting database backup: %s" % resp.content
if verbose:
log.write(mess + "\n")
log.close()
raise MambuCommError(mess)
if verbose:
log.write("saving...\n")
log.flush()
with open(output_fname, "w") as fw:
fw.write(resp.content)
if verbose:
log.write("DONE!\n")
log.close()
return data | python | def backup_db(callback, bool_func, output_fname, *args, **kwargs):
"""Backup Mambu Database via REST API.
Makes two calls to Mambu API:
- a POST to request a backup to be made
- a GET, once the backup is ready, to download the latest backup
* callback is a string to a callback URL Mambu will internally call
when the backup is ready to download. You should have a webservice
there to warn you when the backup is ready.
* bool_func is a function you use against your own code to test if the
said backup is ready. This function backup_db manages both the logic
of the request of a backup and the downloading of it too, so
bool_func allows you to have some way on your side to know when this
function will download the backup.
The thing is you have to build a webservice (for the callback)
making some kind of flag turn that your bool_func will read and know
when to say True, telling backup_db to begin the download of the
backup.
* output_fname the name of the file that will hold the downloaded
backup. PLEASE MIND that Mambu sends a ZIP file here.
* user, pwd and url allow you to change the Mambu permissions for
the getmambuurl internally called here.
* verbose is a boolean flag for verbosity.
* retries number of retries for bool_func or -1 for keep waiting.
* force_download_latest boolean, True to force download even if no
callback is called. False to throw error if callback isn't received
after retries.
* returns a dictionary with info about the download
-latest boolean flag, if the db downloaded was the latest or not
"""
from datetime import datetime
try:
verbose = kwargs['verbose']
except KeyError:
verbose = False
try:
retries = kwargs['retries']
except KeyError:
retries = -1
try:
force_download_latest = bool(kwargs['force_download_latest'])
except KeyError:
force_download_latest = False
if verbose:
log = open('/tmp/log_mambu_backup','a')
log.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " - Mambu DB Backup\n")
log.flush()
user = kwargs.pop('user', apiuser)
pwd = kwargs.pop('pwd', apipwd)
data = {'callback' : callback}
try:
posturl = iriToUri(getmambuurl(*args, **kwargs) + "database/backup")
if verbose:
log.write("open url: "+posturl+"\n")
log.flush()
resp = requests.post(posturl, data=data, headers={'content-type': 'application/json'}, auth=(apiuser, apipwd))
except Exception as ex:
mess = "Error requesting backup: %s" % repr(ex)
if verbose:
log.write(mess + "\n")
log.close()
raise MambuError(mess)
if resp.status_code != 200:
mess = "Error posting request for backup: %s" % resp.content
if verbose:
log.write(mess + "\n")
log.close()
raise MambuCommError(mess)
data['latest'] = True
while retries and not bool_func():
if verbose:
log.write("waiting...\n")
log.flush()
sleep(10)
retries -= 1
if retries < 0: retries = -1
if not retries:
mess = "Tired of waiting, giving up..."
if verbose:
log.write(mess + "\n")
log.flush()
if not force_download_latest:
if verbose:
log.close()
raise MambuError(mess)
else:
data['latest'] = False
sleep(30)
geturl = iriToUri(getmambuurl(*args, **kwargs) + "database/backup/LATEST")
if verbose:
log.write("open url: "+geturl+"\n")
log.flush()
resp = requests.get(geturl, auth=(apiuser, apipwd))
if resp.status_code != 200:
mess = "Error getting database backup: %s" % resp.content
if verbose:
log.write(mess + "\n")
log.close()
raise MambuCommError(mess)
if verbose:
log.write("saving...\n")
log.flush()
with open(output_fname, "w") as fw:
fw.write(resp.content)
if verbose:
log.write("DONE!\n")
log.close()
return data | [
"def",
"backup_db",
"(",
"callback",
",",
"bool_func",
",",
"output_fname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"datetime",
"import",
"datetime",
"try",
":",
"verbose",
"=",
"kwargs",
"[",
"'verbose'",
"]",
"except",
"KeyError",
":",
"verbose",
"=",
"False",
"try",
":",
"retries",
"=",
"kwargs",
"[",
"'retries'",
"]",
"except",
"KeyError",
":",
"retries",
"=",
"-",
"1",
"try",
":",
"force_download_latest",
"=",
"bool",
"(",
"kwargs",
"[",
"'force_download_latest'",
"]",
")",
"except",
"KeyError",
":",
"force_download_latest",
"=",
"False",
"if",
"verbose",
":",
"log",
"=",
"open",
"(",
"'/tmp/log_mambu_backup'",
",",
"'a'",
")",
"log",
".",
"write",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"+",
"\" - Mambu DB Backup\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"user",
"=",
"kwargs",
".",
"pop",
"(",
"'user'",
",",
"apiuser",
")",
"pwd",
"=",
"kwargs",
".",
"pop",
"(",
"'pwd'",
",",
"apipwd",
")",
"data",
"=",
"{",
"'callback'",
":",
"callback",
"}",
"try",
":",
"posturl",
"=",
"iriToUri",
"(",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"database/backup\"",
")",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"\"open url: \"",
"+",
"posturl",
"+",
"\"\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"posturl",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
",",
"auth",
"=",
"(",
"apiuser",
",",
"apipwd",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"mess",
"=",
"\"Error requesting backup: %s\"",
"%",
"repr",
"(",
"ex",
")",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"mess",
"+",
"\"\\n\"",
")",
"log",
".",
"close",
"(",
")",
"raise",
"MambuError",
"(",
"mess",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"mess",
"=",
"\"Error posting request for backup: %s\"",
"%",
"resp",
".",
"content",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"mess",
"+",
"\"\\n\"",
")",
"log",
".",
"close",
"(",
")",
"raise",
"MambuCommError",
"(",
"mess",
")",
"data",
"[",
"'latest'",
"]",
"=",
"True",
"while",
"retries",
"and",
"not",
"bool_func",
"(",
")",
":",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"\"waiting...\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"sleep",
"(",
"10",
")",
"retries",
"-=",
"1",
"if",
"retries",
"<",
"0",
":",
"retries",
"=",
"-",
"1",
"if",
"not",
"retries",
":",
"mess",
"=",
"\"Tired of waiting, giving up...\"",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"mess",
"+",
"\"\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"if",
"not",
"force_download_latest",
":",
"if",
"verbose",
":",
"log",
".",
"close",
"(",
")",
"raise",
"MambuError",
"(",
"mess",
")",
"else",
":",
"data",
"[",
"'latest'",
"]",
"=",
"False",
"sleep",
"(",
"30",
")",
"geturl",
"=",
"iriToUri",
"(",
"getmambuurl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"+",
"\"database/backup/LATEST\"",
")",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"\"open url: \"",
"+",
"geturl",
"+",
"\"\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"geturl",
",",
"auth",
"=",
"(",
"apiuser",
",",
"apipwd",
")",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"mess",
"=",
"\"Error getting database backup: %s\"",
"%",
"resp",
".",
"content",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"mess",
"+",
"\"\\n\"",
")",
"log",
".",
"close",
"(",
")",
"raise",
"MambuCommError",
"(",
"mess",
")",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"\"saving...\\n\"",
")",
"log",
".",
"flush",
"(",
")",
"with",
"open",
"(",
"output_fname",
",",
"\"w\"",
")",
"as",
"fw",
":",
"fw",
".",
"write",
"(",
"resp",
".",
"content",
")",
"if",
"verbose",
":",
"log",
".",
"write",
"(",
"\"DONE!\\n\"",
")",
"log",
".",
"close",
"(",
")",
"return",
"data"
] | Backup Mambu Database via REST API.
Makes two calls to Mambu API:
- a POST to request a backup to be made
- a GET, once the backup is ready, to download the latest backup
* callback is a string to a callback URL Mambu will internally call
when the backup is ready to download. You should have a webservice
there to warn you when the backup is ready.
* bool_func is a function you use against your own code to test if the
said backup is ready. This function backup_db manages both the logic
of the request of a backup and the downloading of it too, so
bool_func allows you to have some way on your side to know when this
function will download the backup.
The thing is you have to build a webservice (for the callback)
making some kind of flag turn that your bool_func will read and know
when to say True, telling backup_db to begin the download of the
backup.
* output_fname the name of the file that will hold the downloaded
backup. PLEASE MIND that Mambu sends a ZIP file here.
* user, pwd and url allow you to change the Mambu permissions for
the getmambuurl internally called here.
* verbose is a boolean flag for verbosity.
* retries number of retries for bool_func or -1 for keep waiting.
* force_download_latest boolean, True to force download even if no
callback is called. False to throw error if callback isn't received
after retries.
* returns a dictionary with info about the download
-latest boolean flag, if the db downloaded was the latest or not | [
"Backup",
"Mambu",
"Database",
"via",
"REST",
"API",
"."
] | 2af98cc12e7ed5ec183b3e97644e880e70b79ee8 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L831-L959 | train |
polyaxon/hestia | hestia/memoize_decorators.py | memoize | def memoize(func):
"""
Provides memoization for methods on a specific instance.
Results are cached for given parameter list.
See also: http://en.wikipedia.org/wiki/Memoization
N.B. The cache object gets added to the instance instead of the global scope.
Therefore cached results are restricted to that instance.
The cache dictionary gets a name containing the name of the decorated function to
avoid clashes.
Example:
class MyClass(object):
@memoize
def foo(self, a, b):
return self._do_calculation(a, b)
HINT: - The decorator does not work with keyword arguments.
"""
cache_name = '__CACHED_{}'.format(func.__name__)
def wrapper(self, *args):
cache = getattr(self, cache_name, None)
if cache is None:
cache = {}
setattr(self, cache_name, cache)
if args not in cache:
cache[args] = func(self, *args)
return cache[args]
return wrapper | python | def memoize(func):
"""
Provides memoization for methods on a specific instance.
Results are cached for given parameter list.
See also: http://en.wikipedia.org/wiki/Memoization
N.B. The cache object gets added to the instance instead of the global scope.
Therefore cached results are restricted to that instance.
The cache dictionary gets a name containing the name of the decorated function to
avoid clashes.
Example:
class MyClass(object):
@memoize
def foo(self, a, b):
return self._do_calculation(a, b)
HINT: - The decorator does not work with keyword arguments.
"""
cache_name = '__CACHED_{}'.format(func.__name__)
def wrapper(self, *args):
cache = getattr(self, cache_name, None)
if cache is None:
cache = {}
setattr(self, cache_name, cache)
if args not in cache:
cache[args] = func(self, *args)
return cache[args]
return wrapper | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache_name",
"=",
"'__CACHED_{}'",
".",
"format",
"(",
"func",
".",
"__name__",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
")",
":",
"cache",
"=",
"getattr",
"(",
"self",
",",
"cache_name",
",",
"None",
")",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"setattr",
"(",
"self",
",",
"cache_name",
",",
"cache",
")",
"if",
"args",
"not",
"in",
"cache",
":",
"cache",
"[",
"args",
"]",
"=",
"func",
"(",
"self",
",",
"*",
"args",
")",
"return",
"cache",
"[",
"args",
"]",
"return",
"wrapper"
] | Provides memoization for methods on a specific instance.
Results are cached for given parameter list.
See also: http://en.wikipedia.org/wiki/Memoization
N.B. The cache object gets added to the instance instead of the global scope.
Therefore cached results are restricted to that instance.
The cache dictionary gets a name containing the name of the decorated function to
avoid clashes.
Example:
class MyClass(object):
@memoize
def foo(self, a, b):
return self._do_calculation(a, b)
HINT: - The decorator does not work with keyword arguments. | [
"Provides",
"memoization",
"for",
"methods",
"on",
"a",
"specific",
"instance",
".",
"Results",
"are",
"cached",
"for",
"given",
"parameter",
"list",
"."
] | 382ed139cff8bf35c987cfc30a31b72c0d6b808e | https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/memoize_decorators.py#L1-L34 | train |
greenelab/PathCORE-T | pathcore/feature_pathway_overrepresentation.py | _pathway_side_information | def _pathway_side_information(pathway_positive_series,
pathway_negative_series,
index):
"""Create the pandas.Series containing the side labels that correspond
to each pathway, based on the user-specified gene signature definition.
"""
positive_series_label = pd.Series(["pos"] * len(pathway_positive_series))
negative_series_label = pd.Series(["neg"] * len(pathway_negative_series))
side_information = positive_series_label.append(
negative_series_label)
side_information.index = index
side_information.name = "side"
return side_information | python | def _pathway_side_information(pathway_positive_series,
pathway_negative_series,
index):
"""Create the pandas.Series containing the side labels that correspond
to each pathway, based on the user-specified gene signature definition.
"""
positive_series_label = pd.Series(["pos"] * len(pathway_positive_series))
negative_series_label = pd.Series(["neg"] * len(pathway_negative_series))
side_information = positive_series_label.append(
negative_series_label)
side_information.index = index
side_information.name = "side"
return side_information | [
"def",
"_pathway_side_information",
"(",
"pathway_positive_series",
",",
"pathway_negative_series",
",",
"index",
")",
":",
"positive_series_label",
"=",
"pd",
".",
"Series",
"(",
"[",
"\"pos\"",
"]",
"*",
"len",
"(",
"pathway_positive_series",
")",
")",
"negative_series_label",
"=",
"pd",
".",
"Series",
"(",
"[",
"\"neg\"",
"]",
"*",
"len",
"(",
"pathway_negative_series",
")",
")",
"side_information",
"=",
"positive_series_label",
".",
"append",
"(",
"negative_series_label",
")",
"side_information",
".",
"index",
"=",
"index",
"side_information",
".",
"name",
"=",
"\"side\"",
"return",
"side_information"
] | Create the pandas.Series containing the side labels that correspond
to each pathway, based on the user-specified gene signature definition. | [
"Create",
"the",
"pandas",
".",
"Series",
"containing",
"the",
"side",
"labels",
"that",
"correspond",
"to",
"each",
"pathway",
"based",
"on",
"the",
"user",
"-",
"specified",
"gene",
"signature",
"definition",
"."
] | 9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c | https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/feature_pathway_overrepresentation.py#L114-L126 | train |
greenelab/PathCORE-T | pathcore/feature_pathway_overrepresentation.py | _significant_pathways_dataframe | def _significant_pathways_dataframe(pvalue_information,
side_information,
alpha):
"""Create the significant pathways pandas.DataFrame.
Given the p-values corresponding to each pathway in a feature,
apply the FDR correction for multiple testing and remove those that
do not have a q-value of less than `alpha`.
"""
significant_pathways = pd.concat(
[pvalue_information, side_information], axis=1)
# fdr_bh: false discovery rate, Benjamini & Hochberg (1995, 2000)
below_alpha, qvalues, _, _ = multipletests(
significant_pathways["p-value"], alpha=alpha, method="fdr_bh")
below_alpha = pd.Series(
below_alpha, index=pvalue_information.index, name="pass")
qvalues = pd.Series(
qvalues, index=pvalue_information.index, name="q-value")
significant_pathways = pd.concat(
[significant_pathways, below_alpha, qvalues], axis=1)
significant_pathways = significant_pathways[significant_pathways["pass"]]
significant_pathways.drop("pass", axis=1, inplace=True)
significant_pathways.loc[:, "pathway"] = significant_pathways.index
return significant_pathways | python | def _significant_pathways_dataframe(pvalue_information,
side_information,
alpha):
"""Create the significant pathways pandas.DataFrame.
Given the p-values corresponding to each pathway in a feature,
apply the FDR correction for multiple testing and remove those that
do not have a q-value of less than `alpha`.
"""
significant_pathways = pd.concat(
[pvalue_information, side_information], axis=1)
# fdr_bh: false discovery rate, Benjamini & Hochberg (1995, 2000)
below_alpha, qvalues, _, _ = multipletests(
significant_pathways["p-value"], alpha=alpha, method="fdr_bh")
below_alpha = pd.Series(
below_alpha, index=pvalue_information.index, name="pass")
qvalues = pd.Series(
qvalues, index=pvalue_information.index, name="q-value")
significant_pathways = pd.concat(
[significant_pathways, below_alpha, qvalues], axis=1)
significant_pathways = significant_pathways[significant_pathways["pass"]]
significant_pathways.drop("pass", axis=1, inplace=True)
significant_pathways.loc[:, "pathway"] = significant_pathways.index
return significant_pathways | [
"def",
"_significant_pathways_dataframe",
"(",
"pvalue_information",
",",
"side_information",
",",
"alpha",
")",
":",
"significant_pathways",
"=",
"pd",
".",
"concat",
"(",
"[",
"pvalue_information",
",",
"side_information",
"]",
",",
"axis",
"=",
"1",
")",
"# fdr_bh: false discovery rate, Benjamini & Hochberg (1995, 2000)",
"below_alpha",
",",
"qvalues",
",",
"_",
",",
"_",
"=",
"multipletests",
"(",
"significant_pathways",
"[",
"\"p-value\"",
"]",
",",
"alpha",
"=",
"alpha",
",",
"method",
"=",
"\"fdr_bh\"",
")",
"below_alpha",
"=",
"pd",
".",
"Series",
"(",
"below_alpha",
",",
"index",
"=",
"pvalue_information",
".",
"index",
",",
"name",
"=",
"\"pass\"",
")",
"qvalues",
"=",
"pd",
".",
"Series",
"(",
"qvalues",
",",
"index",
"=",
"pvalue_information",
".",
"index",
",",
"name",
"=",
"\"q-value\"",
")",
"significant_pathways",
"=",
"pd",
".",
"concat",
"(",
"[",
"significant_pathways",
",",
"below_alpha",
",",
"qvalues",
"]",
",",
"axis",
"=",
"1",
")",
"significant_pathways",
"=",
"significant_pathways",
"[",
"significant_pathways",
"[",
"\"pass\"",
"]",
"]",
"significant_pathways",
".",
"drop",
"(",
"\"pass\"",
",",
"axis",
"=",
"1",
",",
"inplace",
"=",
"True",
")",
"significant_pathways",
".",
"loc",
"[",
":",
",",
"\"pathway\"",
"]",
"=",
"significant_pathways",
".",
"index",
"return",
"significant_pathways"
] | Create the significant pathways pandas.DataFrame.
Given the p-values corresponding to each pathway in a feature,
apply the FDR correction for multiple testing and remove those that
do not have a q-value of less than `alpha`. | [
"Create",
"the",
"significant",
"pathways",
"pandas",
".",
"DataFrame",
".",
"Given",
"the",
"p",
"-",
"values",
"corresponding",
"to",
"each",
"pathway",
"in",
"a",
"feature",
"apply",
"the",
"FDR",
"correction",
"for",
"multiple",
"testing",
"and",
"remove",
"those",
"that",
"do",
"not",
"have",
"a",
"q",
"-",
"value",
"of",
"less",
"than",
"alpha",
"."
] | 9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c | https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/feature_pathway_overrepresentation.py#L129-L151 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoSleep.flush | async def flush(self, request: Request, stacks: List[Stack]):
"""
For all stacks to be sent, append a pause after each text layer.
"""
ns = await self.expand_stacks(request, stacks)
ns = self.split_stacks(ns)
ns = self.clean_stacks(ns)
await self.next(request, [Stack(x) for x in ns]) | python | async def flush(self, request: Request, stacks: List[Stack]):
"""
For all stacks to be sent, append a pause after each text layer.
"""
ns = await self.expand_stacks(request, stacks)
ns = self.split_stacks(ns)
ns = self.clean_stacks(ns)
await self.next(request, [Stack(x) for x in ns]) | [
"async",
"def",
"flush",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stacks",
":",
"List",
"[",
"Stack",
"]",
")",
":",
"ns",
"=",
"await",
"self",
".",
"expand_stacks",
"(",
"request",
",",
"stacks",
")",
"ns",
"=",
"self",
".",
"split_stacks",
"(",
"ns",
")",
"ns",
"=",
"self",
".",
"clean_stacks",
"(",
"ns",
")",
"await",
"self",
".",
"next",
"(",
"request",
",",
"[",
"Stack",
"(",
"x",
")",
"for",
"x",
"in",
"ns",
"]",
")"
] | For all stacks to be sent, append a pause after each text layer. | [
"For",
"all",
"stacks",
"to",
"be",
"sent",
"append",
"a",
"pause",
"after",
"each",
"text",
"layer",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L45-L54 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoSleep.split_stacks | def split_stacks(self, stacks: List[List[BaseLayer]]) \
-> List[List[BaseLayer]]:
"""
First step of the stacks cleanup process. We consider that if inside
a stack there's a text layer showing up then it's the beginning of a
new stack and split upon that.
"""
ns: List[List[BaseLayer]] = []
for stack in stacks:
cur: List[BaseLayer] = []
for layer in stack:
if cur and isinstance(layer, lyr.RawText):
ns.append(cur)
cur = []
cur.append(layer)
if cur:
ns.append(cur)
return ns | python | def split_stacks(self, stacks: List[List[BaseLayer]]) \
-> List[List[BaseLayer]]:
"""
First step of the stacks cleanup process. We consider that if inside
a stack there's a text layer showing up then it's the beginning of a
new stack and split upon that.
"""
ns: List[List[BaseLayer]] = []
for stack in stacks:
cur: List[BaseLayer] = []
for layer in stack:
if cur and isinstance(layer, lyr.RawText):
ns.append(cur)
cur = []
cur.append(layer)
if cur:
ns.append(cur)
return ns | [
"def",
"split_stacks",
"(",
"self",
",",
"stacks",
":",
"List",
"[",
"List",
"[",
"BaseLayer",
"]",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"BaseLayer",
"]",
"]",
":",
"ns",
":",
"List",
"[",
"List",
"[",
"BaseLayer",
"]",
"]",
"=",
"[",
"]",
"for",
"stack",
"in",
"stacks",
":",
"cur",
":",
"List",
"[",
"BaseLayer",
"]",
"=",
"[",
"]",
"for",
"layer",
"in",
"stack",
":",
"if",
"cur",
"and",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"RawText",
")",
":",
"ns",
".",
"append",
"(",
"cur",
")",
"cur",
"=",
"[",
"]",
"cur",
".",
"append",
"(",
"layer",
")",
"if",
"cur",
":",
"ns",
".",
"append",
"(",
"cur",
")",
"return",
"ns"
] | First step of the stacks cleanup process. We consider that if inside
a stack there's a text layer showing up then it's the beginning of a
new stack and split upon that. | [
"First",
"step",
"of",
"the",
"stacks",
"cleanup",
"process",
".",
"We",
"consider",
"that",
"if",
"inside",
"a",
"stack",
"there",
"s",
"a",
"text",
"layer",
"showing",
"up",
"then",
"it",
"s",
"the",
"beginning",
"of",
"a",
"new",
"stack",
"and",
"split",
"upon",
"that",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L70-L93 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoSleep.expand | async def expand(self, request: Request, layer: BaseLayer):
"""
Expand a layer into a list of layers including the pauses.
"""
if isinstance(layer, lyr.RawText):
t = self.reading_time(layer.text)
yield layer
yield lyr.Sleep(t)
elif isinstance(layer, lyr.MultiText):
texts = await render(layer.text, request, True)
for text in texts:
t = self.reading_time(text)
yield lyr.RawText(text)
yield lyr.Sleep(t)
elif isinstance(layer, lyr.Text):
text = await render(layer.text, request)
t = self.reading_time(text)
yield lyr.RawText(text)
yield lyr.Sleep(t)
else:
yield layer | python | async def expand(self, request: Request, layer: BaseLayer):
"""
Expand a layer into a list of layers including the pauses.
"""
if isinstance(layer, lyr.RawText):
t = self.reading_time(layer.text)
yield layer
yield lyr.Sleep(t)
elif isinstance(layer, lyr.MultiText):
texts = await render(layer.text, request, True)
for text in texts:
t = self.reading_time(text)
yield lyr.RawText(text)
yield lyr.Sleep(t)
elif isinstance(layer, lyr.Text):
text = await render(layer.text, request)
t = self.reading_time(text)
yield lyr.RawText(text)
yield lyr.Sleep(t)
else:
yield layer | [
"async",
"def",
"expand",
"(",
"self",
",",
"request",
":",
"Request",
",",
"layer",
":",
"BaseLayer",
")",
":",
"if",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"RawText",
")",
":",
"t",
"=",
"self",
".",
"reading_time",
"(",
"layer",
".",
"text",
")",
"yield",
"layer",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"elif",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"MultiText",
")",
":",
"texts",
"=",
"await",
"render",
"(",
"layer",
".",
"text",
",",
"request",
",",
"True",
")",
"for",
"text",
"in",
"texts",
":",
"t",
"=",
"self",
".",
"reading_time",
"(",
"text",
")",
"yield",
"lyr",
".",
"RawText",
"(",
"text",
")",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"elif",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"Text",
")",
":",
"text",
"=",
"await",
"render",
"(",
"layer",
".",
"text",
",",
"request",
")",
"t",
"=",
"self",
".",
"reading_time",
"(",
"text",
")",
"yield",
"lyr",
".",
"RawText",
"(",
"text",
")",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"else",
":",
"yield",
"layer"
] | Expand a layer into a list of layers including the pauses. | [
"Expand",
"a",
"layer",
"into",
"a",
"list",
"of",
"layers",
"including",
"the",
"pauses",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L121-L146 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoSleep.reading_time | def reading_time(self, text: TextT):
"""
Computes the time in seconds that the user will need to read a bubble
containing the text passed as parameter.
"""
wc = re.findall(r'\w+', text)
period = 60.0 / settings.USERS_READING_SPEED
return float(len(wc)) * period + settings.USERS_READING_BUBBLE_START | python | def reading_time(self, text: TextT):
"""
Computes the time in seconds that the user will need to read a bubble
containing the text passed as parameter.
"""
wc = re.findall(r'\w+', text)
period = 60.0 / settings.USERS_READING_SPEED
return float(len(wc)) * period + settings.USERS_READING_BUBBLE_START | [
"def",
"reading_time",
"(",
"self",
",",
"text",
":",
"TextT",
")",
":",
"wc",
"=",
"re",
".",
"findall",
"(",
"r'\\w+'",
",",
"text",
")",
"period",
"=",
"60.0",
"/",
"settings",
".",
"USERS_READING_SPEED",
"return",
"float",
"(",
"len",
"(",
"wc",
")",
")",
"*",
"period",
"+",
"settings",
".",
"USERS_READING_BUBBLE_START"
] | Computes the time in seconds that the user will need to read a bubble
containing the text passed as parameter. | [
"Computes",
"the",
"time",
"in",
"seconds",
"that",
"the",
"user",
"will",
"need",
"to",
"read",
"a",
"bubble",
"containing",
"the",
"text",
"passed",
"as",
"parameter",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L148-L156 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoType.flush | async def flush(self, request: Request, stacks: List[Stack]):
"""
Add a typing stack after each stack.
"""
ns: List[Stack] = []
for stack in stacks:
ns.extend(self.typify(stack))
if len(ns) > 1 and ns[-1] == Stack([lyr.Typing()]):
ns[-1].get_layer(lyr.Typing).active = False
await self.next(request, ns) | python | async def flush(self, request: Request, stacks: List[Stack]):
"""
Add a typing stack after each stack.
"""
ns: List[Stack] = []
for stack in stacks:
ns.extend(self.typify(stack))
if len(ns) > 1 and ns[-1] == Stack([lyr.Typing()]):
ns[-1].get_layer(lyr.Typing).active = False
await self.next(request, ns) | [
"async",
"def",
"flush",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stacks",
":",
"List",
"[",
"Stack",
"]",
")",
":",
"ns",
":",
"List",
"[",
"Stack",
"]",
"=",
"[",
"]",
"for",
"stack",
"in",
"stacks",
":",
"ns",
".",
"extend",
"(",
"self",
".",
"typify",
"(",
"stack",
")",
")",
"if",
"len",
"(",
"ns",
")",
">",
"1",
"and",
"ns",
"[",
"-",
"1",
"]",
"==",
"Stack",
"(",
"[",
"lyr",
".",
"Typing",
"(",
")",
"]",
")",
":",
"ns",
"[",
"-",
"1",
"]",
".",
"get_layer",
"(",
"lyr",
".",
"Typing",
")",
".",
"active",
"=",
"False",
"await",
"self",
".",
"next",
"(",
"request",
",",
"ns",
")"
] | Add a typing stack after each stack. | [
"Add",
"a",
"typing",
"stack",
"after",
"each",
"stack",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L165-L178 | train |
BernardFW/bernard | src/bernard/middleware/_builtins.py | AutoType.pre_handle | async def pre_handle(self, request: Request, responder: 'Responder'):
"""
Start typing right when the message is received.
"""
responder.send([lyr.Typing()])
await responder.flush(request)
responder.clear()
await self.next(request, responder) | python | async def pre_handle(self, request: Request, responder: 'Responder'):
"""
Start typing right when the message is received.
"""
responder.send([lyr.Typing()])
await responder.flush(request)
responder.clear()
await self.next(request, responder) | [
"async",
"def",
"pre_handle",
"(",
"self",
",",
"request",
":",
"Request",
",",
"responder",
":",
"'Responder'",
")",
":",
"responder",
".",
"send",
"(",
"[",
"lyr",
".",
"Typing",
"(",
")",
"]",
")",
"await",
"responder",
".",
"flush",
"(",
"request",
")",
"responder",
".",
"clear",
"(",
")",
"await",
"self",
".",
"next",
"(",
"request",
",",
"responder",
")"
] | Start typing right when the message is received. | [
"Start",
"typing",
"right",
"when",
"the",
"message",
"is",
"received",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L180-L189 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | TelegramUser.get_friendly_name | async def get_friendly_name(self) -> Text:
"""
Let's use the first name of the user as friendly name. In some cases
the user object is incomplete, and in those cases the full user is
fetched.
"""
if 'first_name' not in self._user:
user = await self._get_full_user()
else:
user = self._user
return user.get('first_name') | python | async def get_friendly_name(self) -> Text:
"""
Let's use the first name of the user as friendly name. In some cases
the user object is incomplete, and in those cases the full user is
fetched.
"""
if 'first_name' not in self._user:
user = await self._get_full_user()
else:
user = self._user
return user.get('first_name') | [
"async",
"def",
"get_friendly_name",
"(",
"self",
")",
"->",
"Text",
":",
"if",
"'first_name'",
"not",
"in",
"self",
".",
"_user",
":",
"user",
"=",
"await",
"self",
".",
"_get_full_user",
"(",
")",
"else",
":",
"user",
"=",
"self",
".",
"_user",
"return",
"user",
".",
"get",
"(",
"'first_name'",
")"
] | Let's use the first name of the user as friendly name. In some cases
the user object is incomplete, and in those cases the full user is
fetched. | [
"Let",
"s",
"use",
"the",
"first",
"name",
"of",
"the",
"user",
"as",
"friendly",
"name",
".",
"In",
"some",
"cases",
"the",
"user",
"object",
"is",
"incomplete",
"and",
"in",
"those",
"cases",
"the",
"full",
"user",
"is",
"fetched",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L152-L164 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | TelegramMessage._get_chat | def _get_chat(self) -> Dict:
"""
As Telegram changes where the chat object is located in the response,
this method tries to be smart about finding it in the right place.
"""
if 'callback_query' in self._update:
query = self._update['callback_query']
if 'message' in query:
return query['message']['chat']
else:
return {'id': query['chat_instance']}
elif 'inline_query' in self._update:
return patch_dict(
self._update['inline_query']['from'],
is_inline_query=True,
)
elif 'message' in self._update:
return self._update['message']['chat'] | python | def _get_chat(self) -> Dict:
"""
As Telegram changes where the chat object is located in the response,
this method tries to be smart about finding it in the right place.
"""
if 'callback_query' in self._update:
query = self._update['callback_query']
if 'message' in query:
return query['message']['chat']
else:
return {'id': query['chat_instance']}
elif 'inline_query' in self._update:
return patch_dict(
self._update['inline_query']['from'],
is_inline_query=True,
)
elif 'message' in self._update:
return self._update['message']['chat'] | [
"def",
"_get_chat",
"(",
"self",
")",
"->",
"Dict",
":",
"if",
"'callback_query'",
"in",
"self",
".",
"_update",
":",
"query",
"=",
"self",
".",
"_update",
"[",
"'callback_query'",
"]",
"if",
"'message'",
"in",
"query",
":",
"return",
"query",
"[",
"'message'",
"]",
"[",
"'chat'",
"]",
"else",
":",
"return",
"{",
"'id'",
":",
"query",
"[",
"'chat_instance'",
"]",
"}",
"elif",
"'inline_query'",
"in",
"self",
".",
"_update",
":",
"return",
"patch_dict",
"(",
"self",
".",
"_update",
"[",
"'inline_query'",
"]",
"[",
"'from'",
"]",
",",
"is_inline_query",
"=",
"True",
",",
")",
"elif",
"'message'",
"in",
"self",
".",
"_update",
":",
"return",
"self",
".",
"_update",
"[",
"'message'",
"]",
"[",
"'chat'",
"]"
] | As Telegram changes where the chat object is located in the response,
this method tries to be smart about finding it in the right place. | [
"As",
"Telegram",
"changes",
"where",
"the",
"chat",
"object",
"is",
"located",
"in",
"the",
"response",
"this",
"method",
"tries",
"to",
"be",
"smart",
"about",
"finding",
"it",
"in",
"the",
"right",
"place",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L238-L256 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | TelegramResponder.send | def send(self, stack: Layers):
"""
Intercept any potential "AnswerCallbackQuery" before adding the stack
to the output buffer.
"""
if not isinstance(stack, Stack):
stack = Stack(stack)
if 'callback_query' in self._update and stack.has_layer(Update):
layer = stack.get_layer(Update)
try:
msg = self._update['callback_query']['message']
except KeyError:
layer.inline_message_id = \
self._update['callback_query']['inline_message_id']
else:
layer.chat_id = msg['chat']['id']
layer.message_id = msg['message_id']
if stack.has_layer(AnswerCallbackQuery):
self._acq = stack.get_layer(AnswerCallbackQuery)
stack = Stack([
l for l in stack.layers
if not isinstance(l, AnswerCallbackQuery)
])
if stack.has_layer(Reply):
layer = stack.get_layer(Reply)
if 'message' in self._update:
layer.message = self._update['message']
elif 'callback_query' in self._update:
layer.message = self._update['callback_query']['message']
if 'inline_query' in self._update \
and stack.has_layer(AnswerInlineQuery):
a = stack.get_layer(AnswerInlineQuery)
a.inline_query_id = self._update['inline_query']['id']
if stack.layers:
return super(TelegramResponder, self).send(stack) | python | def send(self, stack: Layers):
"""
Intercept any potential "AnswerCallbackQuery" before adding the stack
to the output buffer.
"""
if not isinstance(stack, Stack):
stack = Stack(stack)
if 'callback_query' in self._update and stack.has_layer(Update):
layer = stack.get_layer(Update)
try:
msg = self._update['callback_query']['message']
except KeyError:
layer.inline_message_id = \
self._update['callback_query']['inline_message_id']
else:
layer.chat_id = msg['chat']['id']
layer.message_id = msg['message_id']
if stack.has_layer(AnswerCallbackQuery):
self._acq = stack.get_layer(AnswerCallbackQuery)
stack = Stack([
l for l in stack.layers
if not isinstance(l, AnswerCallbackQuery)
])
if stack.has_layer(Reply):
layer = stack.get_layer(Reply)
if 'message' in self._update:
layer.message = self._update['message']
elif 'callback_query' in self._update:
layer.message = self._update['callback_query']['message']
if 'inline_query' in self._update \
and stack.has_layer(AnswerInlineQuery):
a = stack.get_layer(AnswerInlineQuery)
a.inline_query_id = self._update['inline_query']['id']
if stack.layers:
return super(TelegramResponder, self).send(stack) | [
"def",
"send",
"(",
"self",
",",
"stack",
":",
"Layers",
")",
":",
"if",
"not",
"isinstance",
"(",
"stack",
",",
"Stack",
")",
":",
"stack",
"=",
"Stack",
"(",
"stack",
")",
"if",
"'callback_query'",
"in",
"self",
".",
"_update",
"and",
"stack",
".",
"has_layer",
"(",
"Update",
")",
":",
"layer",
"=",
"stack",
".",
"get_layer",
"(",
"Update",
")",
"try",
":",
"msg",
"=",
"self",
".",
"_update",
"[",
"'callback_query'",
"]",
"[",
"'message'",
"]",
"except",
"KeyError",
":",
"layer",
".",
"inline_message_id",
"=",
"self",
".",
"_update",
"[",
"'callback_query'",
"]",
"[",
"'inline_message_id'",
"]",
"else",
":",
"layer",
".",
"chat_id",
"=",
"msg",
"[",
"'chat'",
"]",
"[",
"'id'",
"]",
"layer",
".",
"message_id",
"=",
"msg",
"[",
"'message_id'",
"]",
"if",
"stack",
".",
"has_layer",
"(",
"AnswerCallbackQuery",
")",
":",
"self",
".",
"_acq",
"=",
"stack",
".",
"get_layer",
"(",
"AnswerCallbackQuery",
")",
"stack",
"=",
"Stack",
"(",
"[",
"l",
"for",
"l",
"in",
"stack",
".",
"layers",
"if",
"not",
"isinstance",
"(",
"l",
",",
"AnswerCallbackQuery",
")",
"]",
")",
"if",
"stack",
".",
"has_layer",
"(",
"Reply",
")",
":",
"layer",
"=",
"stack",
".",
"get_layer",
"(",
"Reply",
")",
"if",
"'message'",
"in",
"self",
".",
"_update",
":",
"layer",
".",
"message",
"=",
"self",
".",
"_update",
"[",
"'message'",
"]",
"elif",
"'callback_query'",
"in",
"self",
".",
"_update",
":",
"layer",
".",
"message",
"=",
"self",
".",
"_update",
"[",
"'callback_query'",
"]",
"[",
"'message'",
"]",
"if",
"'inline_query'",
"in",
"self",
".",
"_update",
"and",
"stack",
".",
"has_layer",
"(",
"AnswerInlineQuery",
")",
":",
"a",
"=",
"stack",
".",
"get_layer",
"(",
"AnswerInlineQuery",
")",
"a",
".",
"inline_query_id",
"=",
"self",
".",
"_update",
"[",
"'inline_query'",
"]",
"[",
"'id'",
"]",
"if",
"stack",
".",
"layers",
":",
"return",
"super",
"(",
"TelegramResponder",
",",
"self",
")",
".",
"send",
"(",
"stack",
")"
] | Intercept any potential "AnswerCallbackQuery" before adding the stack
to the output buffer. | [
"Intercept",
"any",
"potential",
"AnswerCallbackQuery",
"before",
"adding",
"the",
"stack",
"to",
"the",
"output",
"buffer",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L313-L355 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | TelegramResponder.flush | async def flush(self, request: BernardRequest):
"""
If there's a AnswerCallbackQuery scheduled for reply, place the call
before actually flushing the buffer.
"""
if self._acq and 'callback_query' in self._update:
try:
cbq_id = self._update['callback_query']['id']
except KeyError:
pass
else:
await self.platform.call(
'answerCallbackQuery',
**(await self._acq.serialize(cbq_id))
)
return await super(TelegramResponder, self).flush(request) | python | async def flush(self, request: BernardRequest):
"""
If there's a AnswerCallbackQuery scheduled for reply, place the call
before actually flushing the buffer.
"""
if self._acq and 'callback_query' in self._update:
try:
cbq_id = self._update['callback_query']['id']
except KeyError:
pass
else:
await self.platform.call(
'answerCallbackQuery',
**(await self._acq.serialize(cbq_id))
)
return await super(TelegramResponder, self).flush(request) | [
"async",
"def",
"flush",
"(",
"self",
",",
"request",
":",
"BernardRequest",
")",
":",
"if",
"self",
".",
"_acq",
"and",
"'callback_query'",
"in",
"self",
".",
"_update",
":",
"try",
":",
"cbq_id",
"=",
"self",
".",
"_update",
"[",
"'callback_query'",
"]",
"[",
"'id'",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"await",
"self",
".",
"platform",
".",
"call",
"(",
"'answerCallbackQuery'",
",",
"*",
"*",
"(",
"await",
"self",
".",
"_acq",
".",
"serialize",
"(",
"cbq_id",
")",
")",
")",
"return",
"await",
"super",
"(",
"TelegramResponder",
",",
"self",
")",
".",
"flush",
"(",
"request",
")"
] | If there's a AnswerCallbackQuery scheduled for reply, place the call
before actually flushing the buffer. | [
"If",
"there",
"s",
"a",
"AnswerCallbackQuery",
"scheduled",
"for",
"reply",
"place",
"the",
"call",
"before",
"actually",
"flushing",
"the",
"buffer",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L357-L374 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram.receive_updates | async def receive_updates(self, request: Request):
"""
Handle updates from Telegram
"""
body = await request.read()
try:
content = ujson.loads(body)
except ValueError:
return json_response({
'error': True,
'message': 'Cannot decode body',
}, status=400)
logger.debug('Received from Telegram: %s', content)
message = TelegramMessage(content, self)
responder = TelegramResponder(content, self)
await self._notify(message, responder)
return json_response({
'error': False,
}) | python | async def receive_updates(self, request: Request):
"""
Handle updates from Telegram
"""
body = await request.read()
try:
content = ujson.loads(body)
except ValueError:
return json_response({
'error': True,
'message': 'Cannot decode body',
}, status=400)
logger.debug('Received from Telegram: %s', content)
message = TelegramMessage(content, self)
responder = TelegramResponder(content, self)
await self._notify(message, responder)
return json_response({
'error': False,
}) | [
"async",
"def",
"receive_updates",
"(",
"self",
",",
"request",
":",
"Request",
")",
":",
"body",
"=",
"await",
"request",
".",
"read",
"(",
")",
"try",
":",
"content",
"=",
"ujson",
".",
"loads",
"(",
"body",
")",
"except",
"ValueError",
":",
"return",
"json_response",
"(",
"{",
"'error'",
":",
"True",
",",
"'message'",
":",
"'Cannot decode body'",
",",
"}",
",",
"status",
"=",
"400",
")",
"logger",
".",
"debug",
"(",
"'Received from Telegram: %s'",
",",
"content",
")",
"message",
"=",
"TelegramMessage",
"(",
"content",
",",
"self",
")",
"responder",
"=",
"TelegramResponder",
"(",
"content",
",",
"self",
")",
"await",
"self",
".",
"_notify",
"(",
"message",
",",
"responder",
")",
"return",
"json_response",
"(",
"{",
"'error'",
":",
"False",
",",
"}",
")"
] | Handle updates from Telegram | [
"Handle",
"updates",
"from",
"Telegram"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L438-L461 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram.make_url | def make_url(self, method):
"""
Generate a Telegram URL for this bot.
"""
token = self.settings()['token']
return TELEGRAM_URL.format(
token=quote(token),
method=quote(method),
) | python | def make_url(self, method):
"""
Generate a Telegram URL for this bot.
"""
token = self.settings()['token']
return TELEGRAM_URL.format(
token=quote(token),
method=quote(method),
) | [
"def",
"make_url",
"(",
"self",
",",
"method",
")",
":",
"token",
"=",
"self",
".",
"settings",
"(",
")",
"[",
"'token'",
"]",
"return",
"TELEGRAM_URL",
".",
"format",
"(",
"token",
"=",
"quote",
"(",
"token",
")",
",",
"method",
"=",
"quote",
"(",
"method",
")",
",",
")"
] | Generate a Telegram URL for this bot. | [
"Generate",
"a",
"Telegram",
"URL",
"for",
"this",
"bot",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L503-L513 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram.call | async def call(self,
method: Text,
_ignore: Set[Text] = None,
**params: Any):
"""
Call a telegram method
:param _ignore: List of reasons to ignore
:param method: Name of the method to call
:param params: Dictionary of the parameters to send
:return: Returns the API response
"""
logger.debug('Calling Telegram %s(%s)', method, params)
url = self.make_url(method)
headers = {
'content-type': 'application/json',
}
post = self.session.post(
url,
data=ujson.dumps(params),
headers=headers,
)
async with post as r:
out = await self._handle_telegram_response(r, _ignore)
logger.debug('Telegram replied: %s', out)
return out | python | async def call(self,
method: Text,
_ignore: Set[Text] = None,
**params: Any):
"""
Call a telegram method
:param _ignore: List of reasons to ignore
:param method: Name of the method to call
:param params: Dictionary of the parameters to send
:return: Returns the API response
"""
logger.debug('Calling Telegram %s(%s)', method, params)
url = self.make_url(method)
headers = {
'content-type': 'application/json',
}
post = self.session.post(
url,
data=ujson.dumps(params),
headers=headers,
)
async with post as r:
out = await self._handle_telegram_response(r, _ignore)
logger.debug('Telegram replied: %s', out)
return out | [
"async",
"def",
"call",
"(",
"self",
",",
"method",
":",
"Text",
",",
"_ignore",
":",
"Set",
"[",
"Text",
"]",
"=",
"None",
",",
"*",
"*",
"params",
":",
"Any",
")",
":",
"logger",
".",
"debug",
"(",
"'Calling Telegram %s(%s)'",
",",
"method",
",",
"params",
")",
"url",
"=",
"self",
".",
"make_url",
"(",
"method",
")",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
",",
"}",
"post",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"ujson",
".",
"dumps",
"(",
"params",
")",
",",
"headers",
"=",
"headers",
",",
")",
"async",
"with",
"post",
"as",
"r",
":",
"out",
"=",
"await",
"self",
".",
"_handle_telegram_response",
"(",
"r",
",",
"_ignore",
")",
"logger",
".",
"debug",
"(",
"'Telegram replied: %s'",
",",
"out",
")",
"return",
"out"
] | Call a telegram method
:param _ignore: List of reasons to ignore
:param method: Name of the method to call
:param params: Dictionary of the parameters to send
:return: Returns the API response | [
"Call",
"a",
"telegram",
"method"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L515-L546 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram._handle_telegram_response | async def _handle_telegram_response(self, response, ignore=None):
"""
Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data
"""
if ignore is None:
ignore = set()
ok = response.status == 200
try:
data = await response.json()
if not ok:
desc = data['description']
if desc in ignore:
return
raise PlatformOperationError(
'Telegram replied with an error: {}'
.format(desc)
)
except (ValueError, TypeError, KeyError):
raise PlatformOperationError('An unknown Telegram error occurred')
return data | python | async def _handle_telegram_response(self, response, ignore=None):
"""
Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data
"""
if ignore is None:
ignore = set()
ok = response.status == 200
try:
data = await response.json()
if not ok:
desc = data['description']
if desc in ignore:
return
raise PlatformOperationError(
'Telegram replied with an error: {}'
.format(desc)
)
except (ValueError, TypeError, KeyError):
raise PlatformOperationError('An unknown Telegram error occurred')
return data | [
"async",
"def",
"_handle_telegram_response",
"(",
"self",
",",
"response",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"ignore",
"is",
"None",
":",
"ignore",
"=",
"set",
"(",
")",
"ok",
"=",
"response",
".",
"status",
"==",
"200",
"try",
":",
"data",
"=",
"await",
"response",
".",
"json",
"(",
")",
"if",
"not",
"ok",
":",
"desc",
"=",
"data",
"[",
"'description'",
"]",
"if",
"desc",
"in",
"ignore",
":",
"return",
"raise",
"PlatformOperationError",
"(",
"'Telegram replied with an error: {}'",
".",
"format",
"(",
"desc",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"raise",
"PlatformOperationError",
"(",
"'An unknown Telegram error occurred'",
")",
"return",
"data"
] | Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data | [
"Parse",
"a",
"response",
"from",
"Telegram",
".",
"If",
"there",
"s",
"an",
"error",
"an",
"exception",
"will",
"be",
"raised",
"with",
"an",
"explicative",
"message",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L548-L578 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram.make_hook_path | def make_hook_path(self):
"""
Compute the path to the hook URL
"""
token = self.settings()['token']
h = sha256()
h.update(token.encode())
key = str(h.hexdigest())
return f'/hooks/telegram/{key}' | python | def make_hook_path(self):
"""
Compute the path to the hook URL
"""
token = self.settings()['token']
h = sha256()
h.update(token.encode())
key = str(h.hexdigest())
return f'/hooks/telegram/{key}' | [
"def",
"make_hook_path",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"settings",
"(",
")",
"[",
"'token'",
"]",
"h",
"=",
"sha256",
"(",
")",
"h",
".",
"update",
"(",
"token",
".",
"encode",
"(",
")",
")",
"key",
"=",
"str",
"(",
"h",
".",
"hexdigest",
"(",
")",
")",
"return",
"f'/hooks/telegram/{key}'"
] | Compute the path to the hook URL | [
"Compute",
"the",
"path",
"to",
"the",
"hook",
"URL"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L580-L589 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram._deferred_init | async def _deferred_init(self):
"""
Register the web hook onto which Telegram should send its messages.
"""
hook_path = self.make_hook_path()
url = urljoin(settings.BERNARD_BASE_URL, hook_path)
await self.call('setWebhook', url=url)
logger.info('Setting Telegram webhook to "%s"', url) | python | async def _deferred_init(self):
"""
Register the web hook onto which Telegram should send its messages.
"""
hook_path = self.make_hook_path()
url = urljoin(settings.BERNARD_BASE_URL, hook_path)
await self.call('setWebhook', url=url)
logger.info('Setting Telegram webhook to "%s"', url) | [
"async",
"def",
"_deferred_init",
"(",
"self",
")",
":",
"hook_path",
"=",
"self",
".",
"make_hook_path",
"(",
")",
"url",
"=",
"urljoin",
"(",
"settings",
".",
"BERNARD_BASE_URL",
",",
"hook_path",
")",
"await",
"self",
".",
"call",
"(",
"'setWebhook'",
",",
"url",
"=",
"url",
")",
"logger",
".",
"info",
"(",
"'Setting Telegram webhook to \"%s\"'",
",",
"url",
")"
] | Register the web hook onto which Telegram should send its messages. | [
"Register",
"the",
"web",
"hook",
"onto",
"which",
"Telegram",
"should",
"send",
"its",
"messages",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L591-L599 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram._send_text | async def _send_text(self,
request: Request,
stack: Stack,
parse_mode: Optional[Text] = None):
"""
Base function for sending text
"""
parts = []
chat_id = request.message.get_chat_id()
for layer in stack.layers:
if isinstance(layer, (lyr.Text, lyr.RawText, lyr.Markdown)):
text = await render(layer.text, request)
parts.append(text)
for part in parts[:-1]:
await self.call(
'sendMessage',
text=part,
chat_id=chat_id,
)
msg = {
'text': parts[-1],
'chat_id': chat_id,
}
if parse_mode is not None:
msg['parse_mode'] = parse_mode
await set_reply_markup(msg, request, stack)
if stack.has_layer(Reply):
reply = stack.get_layer(Reply)
if reply.message:
msg['reply_to_message_id'] = reply.message['message_id']
if stack.has_layer(Update):
update = stack.get_layer(Update)
if update.inline_message_id:
msg['inline_message_id'] = update.inline_message_id
del msg['chat_id']
else:
msg['message_id'] = update.message_id
await self.call(
'editMessageText',
{'Bad Request: message is not modified'},
**msg
)
else:
await self.call('sendMessage', **msg) | python | async def _send_text(self,
request: Request,
stack: Stack,
parse_mode: Optional[Text] = None):
"""
Base function for sending text
"""
parts = []
chat_id = request.message.get_chat_id()
for layer in stack.layers:
if isinstance(layer, (lyr.Text, lyr.RawText, lyr.Markdown)):
text = await render(layer.text, request)
parts.append(text)
for part in parts[:-1]:
await self.call(
'sendMessage',
text=part,
chat_id=chat_id,
)
msg = {
'text': parts[-1],
'chat_id': chat_id,
}
if parse_mode is not None:
msg['parse_mode'] = parse_mode
await set_reply_markup(msg, request, stack)
if stack.has_layer(Reply):
reply = stack.get_layer(Reply)
if reply.message:
msg['reply_to_message_id'] = reply.message['message_id']
if stack.has_layer(Update):
update = stack.get_layer(Update)
if update.inline_message_id:
msg['inline_message_id'] = update.inline_message_id
del msg['chat_id']
else:
msg['message_id'] = update.message_id
await self.call(
'editMessageText',
{'Bad Request: message is not modified'},
**msg
)
else:
await self.call('sendMessage', **msg) | [
"async",
"def",
"_send_text",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
",",
"parse_mode",
":",
"Optional",
"[",
"Text",
"]",
"=",
"None",
")",
":",
"parts",
"=",
"[",
"]",
"chat_id",
"=",
"request",
".",
"message",
".",
"get_chat_id",
"(",
")",
"for",
"layer",
"in",
"stack",
".",
"layers",
":",
"if",
"isinstance",
"(",
"layer",
",",
"(",
"lyr",
".",
"Text",
",",
"lyr",
".",
"RawText",
",",
"lyr",
".",
"Markdown",
")",
")",
":",
"text",
"=",
"await",
"render",
"(",
"layer",
".",
"text",
",",
"request",
")",
"parts",
".",
"append",
"(",
"text",
")",
"for",
"part",
"in",
"parts",
"[",
":",
"-",
"1",
"]",
":",
"await",
"self",
".",
"call",
"(",
"'sendMessage'",
",",
"text",
"=",
"part",
",",
"chat_id",
"=",
"chat_id",
",",
")",
"msg",
"=",
"{",
"'text'",
":",
"parts",
"[",
"-",
"1",
"]",
",",
"'chat_id'",
":",
"chat_id",
",",
"}",
"if",
"parse_mode",
"is",
"not",
"None",
":",
"msg",
"[",
"'parse_mode'",
"]",
"=",
"parse_mode",
"await",
"set_reply_markup",
"(",
"msg",
",",
"request",
",",
"stack",
")",
"if",
"stack",
".",
"has_layer",
"(",
"Reply",
")",
":",
"reply",
"=",
"stack",
".",
"get_layer",
"(",
"Reply",
")",
"if",
"reply",
".",
"message",
":",
"msg",
"[",
"'reply_to_message_id'",
"]",
"=",
"reply",
".",
"message",
"[",
"'message_id'",
"]",
"if",
"stack",
".",
"has_layer",
"(",
"Update",
")",
":",
"update",
"=",
"stack",
".",
"get_layer",
"(",
"Update",
")",
"if",
"update",
".",
"inline_message_id",
":",
"msg",
"[",
"'inline_message_id'",
"]",
"=",
"update",
".",
"inline_message_id",
"del",
"msg",
"[",
"'chat_id'",
"]",
"else",
":",
"msg",
"[",
"'message_id'",
"]",
"=",
"update",
".",
"message_id",
"await",
"self",
".",
"call",
"(",
"'editMessageText'",
",",
"{",
"'Bad Request: message is not modified'",
"}",
",",
"*",
"*",
"msg",
")",
"else",
":",
"await",
"self",
".",
"call",
"(",
"'sendMessage'",
",",
"*",
"*",
"msg",
")"
] | Base function for sending text | [
"Base",
"function",
"for",
"sending",
"text"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L601-L654 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram._send_sleep | async def _send_sleep(self, request: Request, stack: Stack):
"""
Sleep for the amount of time specified in the Sleep layer
"""
duration = stack.get_layer(lyr.Sleep).duration
await sleep(duration) | python | async def _send_sleep(self, request: Request, stack: Stack):
"""
Sleep for the amount of time specified in the Sleep layer
"""
duration = stack.get_layer(lyr.Sleep).duration
await sleep(duration) | [
"async",
"def",
"_send_sleep",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"duration",
"=",
"stack",
".",
"get_layer",
"(",
"lyr",
".",
"Sleep",
")",
".",
"duration",
"await",
"sleep",
"(",
"duration",
")"
] | Sleep for the amount of time specified in the Sleep layer | [
"Sleep",
"for",
"the",
"amount",
"of",
"time",
"specified",
"in",
"the",
"Sleep",
"layer"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L670-L676 | train |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | Telegram._send_typing | async def _send_typing(self, request: Request, stack: Stack):
"""
In telegram, the typing stops when the message is received. Thus, there
is no "typing stops" messages to send. The API is only called when
typing must start.
"""
t = stack.get_layer(lyr.Typing)
if t.active:
await self.call(
'sendChatAction',
chat_id=request.message.get_chat_id(),
action='typing',
) | python | async def _send_typing(self, request: Request, stack: Stack):
"""
In telegram, the typing stops when the message is received. Thus, there
is no "typing stops" messages to send. The API is only called when
typing must start.
"""
t = stack.get_layer(lyr.Typing)
if t.active:
await self.call(
'sendChatAction',
chat_id=request.message.get_chat_id(),
action='typing',
) | [
"async",
"def",
"_send_typing",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"t",
"=",
"stack",
".",
"get_layer",
"(",
"lyr",
".",
"Typing",
")",
"if",
"t",
".",
"active",
":",
"await",
"self",
".",
"call",
"(",
"'sendChatAction'",
",",
"chat_id",
"=",
"request",
".",
"message",
".",
"get_chat_id",
"(",
")",
",",
"action",
"=",
"'typing'",
",",
")"
] | In telegram, the typing stops when the message is received. Thus, there
is no "typing stops" messages to send. The API is only called when
typing must start. | [
"In",
"telegram",
"the",
"typing",
"stops",
"when",
"the",
"message",
"is",
"received",
".",
"Thus",
"there",
"is",
"no",
"typing",
"stops",
"messages",
"to",
"send",
".",
"The",
"API",
"is",
"only",
"called",
"when",
"typing",
"must",
"start",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L683-L697 | train |
ikalnytskyi/holocron | src/holocron/core/factories.py | create_app | def create_app(metadata, processors=None, pipes=None):
"""Return an application instance with processors & pipes setup."""
instance = Application(metadata)
# In order to avoid code duplication, we use existing built-in import
# processor to import and register built-in processors on the application
# instance. This is, to be honest, the main purpose of this factory
# function, because otherwise one must create an Application instance
# directly.
import_processors.process(instance, [], imports=[
"archive = holocron.processors.archive:process",
"commonmark = holocron.processors.commonmark:process",
"feed = holocron.processors.feed:process",
"frontmatter = holocron.processors.frontmatter:process",
"import-processors = holocron.processors.import_processors:process",
"jinja2 = holocron.processors.jinja2:process",
"markdown = holocron.processors.markdown:process",
"metadata = holocron.processors.metadata:process",
"pipe = holocron.processors.pipe:process",
"prettyuri = holocron.processors.prettyuri:process",
"restructuredtext = holocron.processors.restructuredtext:process",
"save = holocron.processors.save:process",
"sitemap = holocron.processors.sitemap:process",
"source = holocron.processors.source:process",
"todatetime = holocron.processors.todatetime:process",
"when = holocron.processors.when:process",
])
for name, processor in (processors or {}).items():
instance.add_processor(name, processor)
for name, pipeline in (pipes or {}).items():
instance.add_pipe(name, pipeline)
return instance | python | def create_app(metadata, processors=None, pipes=None):
"""Return an application instance with processors & pipes setup."""
instance = Application(metadata)
# In order to avoid code duplication, we use existing built-in import
# processor to import and register built-in processors on the application
# instance. This is, to be honest, the main purpose of this factory
# function, because otherwise one must create an Application instance
# directly.
import_processors.process(instance, [], imports=[
"archive = holocron.processors.archive:process",
"commonmark = holocron.processors.commonmark:process",
"feed = holocron.processors.feed:process",
"frontmatter = holocron.processors.frontmatter:process",
"import-processors = holocron.processors.import_processors:process",
"jinja2 = holocron.processors.jinja2:process",
"markdown = holocron.processors.markdown:process",
"metadata = holocron.processors.metadata:process",
"pipe = holocron.processors.pipe:process",
"prettyuri = holocron.processors.prettyuri:process",
"restructuredtext = holocron.processors.restructuredtext:process",
"save = holocron.processors.save:process",
"sitemap = holocron.processors.sitemap:process",
"source = holocron.processors.source:process",
"todatetime = holocron.processors.todatetime:process",
"when = holocron.processors.when:process",
])
for name, processor in (processors or {}).items():
instance.add_processor(name, processor)
for name, pipeline in (pipes or {}).items():
instance.add_pipe(name, pipeline)
return instance | [
"def",
"create_app",
"(",
"metadata",
",",
"processors",
"=",
"None",
",",
"pipes",
"=",
"None",
")",
":",
"instance",
"=",
"Application",
"(",
"metadata",
")",
"# In order to avoid code duplication, we use existing built-in import",
"# processor to import and register built-in processors on the application",
"# instance. This is, to be honest, the main purpose of this factory",
"# function, because otherwise one must create an Application instance",
"# directly.",
"import_processors",
".",
"process",
"(",
"instance",
",",
"[",
"]",
",",
"imports",
"=",
"[",
"\"archive = holocron.processors.archive:process\"",
",",
"\"commonmark = holocron.processors.commonmark:process\"",
",",
"\"feed = holocron.processors.feed:process\"",
",",
"\"frontmatter = holocron.processors.frontmatter:process\"",
",",
"\"import-processors = holocron.processors.import_processors:process\"",
",",
"\"jinja2 = holocron.processors.jinja2:process\"",
",",
"\"markdown = holocron.processors.markdown:process\"",
",",
"\"metadata = holocron.processors.metadata:process\"",
",",
"\"pipe = holocron.processors.pipe:process\"",
",",
"\"prettyuri = holocron.processors.prettyuri:process\"",
",",
"\"restructuredtext = holocron.processors.restructuredtext:process\"",
",",
"\"save = holocron.processors.save:process\"",
",",
"\"sitemap = holocron.processors.sitemap:process\"",
",",
"\"source = holocron.processors.source:process\"",
",",
"\"todatetime = holocron.processors.todatetime:process\"",
",",
"\"when = holocron.processors.when:process\"",
",",
"]",
")",
"for",
"name",
",",
"processor",
"in",
"(",
"processors",
"or",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"instance",
".",
"add_processor",
"(",
"name",
",",
"processor",
")",
"for",
"name",
",",
"pipeline",
"in",
"(",
"pipes",
"or",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"instance",
".",
"add_pipe",
"(",
"name",
",",
"pipeline",
")",
"return",
"instance"
] | Return an application instance with processors & pipes setup. | [
"Return",
"an",
"application",
"instance",
"with",
"processors",
"&",
"pipes",
"setup",
"."
] | d202f6bccfeca64162857c6d0ee5bb53e773d2f2 | https://github.com/ikalnytskyi/holocron/blob/d202f6bccfeca64162857c6d0ee5bb53e773d2f2/src/holocron/core/factories.py#L7-L42 | train |
BernardFW/bernard | src/bernard/analytics/ga/_ga.py | GoogleAnalytics.page_view | async def page_view(self,
url: str,
title: str,
user_id: str,
user_lang: str='') -> None:
"""
Log a page view.
:param url: URL of the "page"
:param title: Title of the "page"
:param user_id: ID of the user seeing the page.
:param user_lang: Current language of the UI.
"""
ga_url = 'https://www.google-analytics.com/collect'
args = {
'v': '1',
'ds': 'web',
'de': 'UTF-8',
'tid': self.ga_id,
'cid': self.hash_user_id(user_id),
't': 'pageview',
'dh': self.ga_domain,
'dp': url,
'dt': title,
}
if user_lang:
args['ul'] = user_lang
logger.debug('GA settings = %s', urlencode(args))
async with self.session.post(ga_url, data=args) as r:
if r.status == 200:
logger.debug(f'Sent to GA {url} ({title}) for user {user_id}')
else:
logger.warning(f'Could not contact GA') | python | async def page_view(self,
url: str,
title: str,
user_id: str,
user_lang: str='') -> None:
"""
Log a page view.
:param url: URL of the "page"
:param title: Title of the "page"
:param user_id: ID of the user seeing the page.
:param user_lang: Current language of the UI.
"""
ga_url = 'https://www.google-analytics.com/collect'
args = {
'v': '1',
'ds': 'web',
'de': 'UTF-8',
'tid': self.ga_id,
'cid': self.hash_user_id(user_id),
't': 'pageview',
'dh': self.ga_domain,
'dp': url,
'dt': title,
}
if user_lang:
args['ul'] = user_lang
logger.debug('GA settings = %s', urlencode(args))
async with self.session.post(ga_url, data=args) as r:
if r.status == 200:
logger.debug(f'Sent to GA {url} ({title}) for user {user_id}')
else:
logger.warning(f'Could not contact GA') | [
"async",
"def",
"page_view",
"(",
"self",
",",
"url",
":",
"str",
",",
"title",
":",
"str",
",",
"user_id",
":",
"str",
",",
"user_lang",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"ga_url",
"=",
"'https://www.google-analytics.com/collect'",
"args",
"=",
"{",
"'v'",
":",
"'1'",
",",
"'ds'",
":",
"'web'",
",",
"'de'",
":",
"'UTF-8'",
",",
"'tid'",
":",
"self",
".",
"ga_id",
",",
"'cid'",
":",
"self",
".",
"hash_user_id",
"(",
"user_id",
")",
",",
"'t'",
":",
"'pageview'",
",",
"'dh'",
":",
"self",
".",
"ga_domain",
",",
"'dp'",
":",
"url",
",",
"'dt'",
":",
"title",
",",
"}",
"if",
"user_lang",
":",
"args",
"[",
"'ul'",
"]",
"=",
"user_lang",
"logger",
".",
"debug",
"(",
"'GA settings = %s'",
",",
"urlencode",
"(",
"args",
")",
")",
"async",
"with",
"self",
".",
"session",
".",
"post",
"(",
"ga_url",
",",
"data",
"=",
"args",
")",
"as",
"r",
":",
"if",
"r",
".",
"status",
"==",
"200",
":",
"logger",
".",
"debug",
"(",
"f'Sent to GA {url} ({title}) for user {user_id}'",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"f'Could not contact GA'",
")"
] | Log a page view.
:param url: URL of the "page"
:param title: Title of the "page"
:param user_id: ID of the user seeing the page.
:param user_lang: Current language of the UI. | [
"Log",
"a",
"page",
"view",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/ga/_ga.py#L37-L74 | train |
transifex/transifex-python-library | txlib/http/auth.py | AuthInfo.get | def get(self, username=None, password=None, headers={}):
"""Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, return an auth
object that supports basic authentication.
Args:
`username`: The username of the user.
`password`: The password of the user.
`headers`: Custom headers to be sent to each request.
Raises:
ValueError in case one of the two arguments evaluates to False,
(such as having the None value).
"""
if all((username, password, )):
return BasicAuth(username, password, headers)
elif not any((username, password, )):
return AnonymousAuth(headers)
else:
if username is None:
data = ("username", username, )
else:
data = ("Password", password, )
msg = "%s must have a value (instead of '%s')" % (data[0], data[1])
raise ValueError(msg) | python | def get(self, username=None, password=None, headers={}):
"""Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, return an auth
object that supports basic authentication.
Args:
`username`: The username of the user.
`password`: The password of the user.
`headers`: Custom headers to be sent to each request.
Raises:
ValueError in case one of the two arguments evaluates to False,
(such as having the None value).
"""
if all((username, password, )):
return BasicAuth(username, password, headers)
elif not any((username, password, )):
return AnonymousAuth(headers)
else:
if username is None:
data = ("username", username, )
else:
data = ("Password", password, )
msg = "%s must have a value (instead of '%s')" % (data[0], data[1])
raise ValueError(msg) | [
"def",
"get",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
")",
":",
"if",
"all",
"(",
"(",
"username",
",",
"password",
",",
")",
")",
":",
"return",
"BasicAuth",
"(",
"username",
",",
"password",
",",
"headers",
")",
"elif",
"not",
"any",
"(",
"(",
"username",
",",
"password",
",",
")",
")",
":",
"return",
"AnonymousAuth",
"(",
"headers",
")",
"else",
":",
"if",
"username",
"is",
"None",
":",
"data",
"=",
"(",
"\"username\"",
",",
"username",
",",
")",
"else",
":",
"data",
"=",
"(",
"\"Password\"",
",",
"password",
",",
")",
"msg",
"=",
"\"%s must have a value (instead of '%s')\"",
"%",
"(",
"data",
"[",
"0",
"]",
",",
"data",
"[",
"1",
"]",
")",
"raise",
"ValueError",
"(",
"msg",
")"
] | Factory method to get the correct AuthInfo object.
The returned value depends on the arguments given. In case the
username and password don't have a value (ie evaluate to False),
return an object for anonymous access. Else, return an auth
object that supports basic authentication.
Args:
`username`: The username of the user.
`password`: The password of the user.
`headers`: Custom headers to be sent to each request.
Raises:
ValueError in case one of the two arguments evaluates to False,
(such as having the None value). | [
"Factory",
"method",
"to",
"get",
"the",
"correct",
"AuthInfo",
"object",
"."
] | 9fea86b718973de35ccca6d54bd1f445c9632406 | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/http/auth.py#L14-L40 | train |
transifex/transifex-python-library | txlib/http/auth.py | BasicAuth.populate_request_data | def populate_request_data(self, request_args):
"""Add the authentication info to the supplied dictionary.
We use the `requests.HTTPBasicAuth` class as the `auth` param.
Args:
`request_args`: The arguments that will be passed to the request.
Returns:
The updated arguments for the request.
"""
request_args['auth'] = HTTPBasicAuth(
self._username, self._password)
return request_args | python | def populate_request_data(self, request_args):
"""Add the authentication info to the supplied dictionary.
We use the `requests.HTTPBasicAuth` class as the `auth` param.
Args:
`request_args`: The arguments that will be passed to the request.
Returns:
The updated arguments for the request.
"""
request_args['auth'] = HTTPBasicAuth(
self._username, self._password)
return request_args | [
"def",
"populate_request_data",
"(",
"self",
",",
"request_args",
")",
":",
"request_args",
"[",
"'auth'",
"]",
"=",
"HTTPBasicAuth",
"(",
"self",
".",
"_username",
",",
"self",
".",
"_password",
")",
"return",
"request_args"
] | Add the authentication info to the supplied dictionary.
We use the `requests.HTTPBasicAuth` class as the `auth` param.
Args:
`request_args`: The arguments that will be passed to the request.
Returns:
The updated arguments for the request. | [
"Add",
"the",
"authentication",
"info",
"to",
"the",
"supplied",
"dictionary",
"."
] | 9fea86b718973de35ccca6d54bd1f445c9632406 | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/http/auth.py#L74-L86 | train |
inveniosoftware-contrib/invenio-workflows | invenio_workflows/ext.py | _WorkflowState.register_workflow | def register_workflow(self, name, workflow):
"""Register an workflow to be showed in the workflows list."""
assert name not in self.workflows
self.workflows[name] = workflow | python | def register_workflow(self, name, workflow):
"""Register an workflow to be showed in the workflows list."""
assert name not in self.workflows
self.workflows[name] = workflow | [
"def",
"register_workflow",
"(",
"self",
",",
"name",
",",
"workflow",
")",
":",
"assert",
"name",
"not",
"in",
"self",
".",
"workflows",
"self",
".",
"workflows",
"[",
"name",
"]",
"=",
"workflow"
] | Register an workflow to be showed in the workflows list. | [
"Register",
"an",
"workflow",
"to",
"be",
"showed",
"in",
"the",
"workflows",
"list",
"."
] | 9c09fd29509a3db975ac2aba337e6760d8cfd3c2 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/ext.py#L52-L55 | train |
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 |
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')
{DEBUG: True, 'SQLITE.DB': 'memory'}
>>> c.load_module("config", False)
{'DEBUG': True, 'SQLITE': {'DB': 'memory'}}
:param squash: If true (default), dictionary values are assumed to
represent namespaces (see :meth:`load_dict`).
"""
config_obj = load(path)
obj = {key: getattr(config_obj, key) for key in dir(config_obj)
if key.isupper()}
if squash:
self.load_dict(obj)
else:
self.update(obj)
return self | 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')
{DEBUG: True, 'SQLITE.DB': 'memory'}
>>> c.load_module("config", False)
{'DEBUG': True, 'SQLITE': {'DB': 'memory'}}
:param squash: If true (default), dictionary values are assumed to
represent namespaces (see :meth:`load_dict`).
"""
config_obj = load(path)
obj = {key: getattr(config_obj, key) for key in dir(config_obj)
if key.isupper()}
if squash:
self.load_dict(obj)
else:
self.update(obj)
return self | [
"def",
"load_module",
"(",
"self",
",",
"path",
",",
"squash",
"=",
"True",
")",
":",
"config_obj",
"=",
"load",
"(",
"path",
")",
"obj",
"=",
"{",
"key",
":",
"getattr",
"(",
"config_obj",
",",
"key",
")",
"for",
"key",
"in",
"dir",
"(",
"config_obj",
")",
"if",
"key",
".",
"isupper",
"(",
")",
"}",
"if",
"squash",
":",
"self",
".",
"load_dict",
"(",
"obj",
")",
"else",
":",
"self",
".",
"update",
"(",
"obj",
")",
"return",
"self"
] | 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'}
>>> c.load_module("config", False)
{'DEBUG': True, 'SQLITE': {'DB': 'memory'}}
:param squash: If true (default), dictionary values are assumed to
represent namespaces (see :meth:`load_dict`). | [
"Load",
"values",
"from",
"a",
"Python",
"module",
"."
] | 30fe89537379faea4de8c8b568ac6e52e4d15353 | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2341-L2369 | train |
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 and self[key] is not value:
self._on_change(key, value)
dict.__setitem__(self, key, value)
for overlay in self._iter_overlays():
overlay._set_virtual(key, value) | 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 and self[key] is not value:
self._on_change(key, value)
dict.__setitem__(self, key, value)
for overlay in self._iter_overlays():
overlay._set_virtual(key, value) | [
"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",
"(",
"key",
")",
"if",
"key",
"in",
"self",
"and",
"self",
"[",
"key",
"]",
"is",
"not",
"value",
":",
"self",
".",
"_on_change",
"(",
"key",
",",
"value",
")",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
"for",
"overlay",
"in",
"self",
".",
"_iter_overlays",
"(",
")",
":",
"overlay",
".",
"_set_virtual",
"(",
"key",
",",
"value",
")"
] | 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 |
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)
self._virtual_keys.discard(key)
for overlay in self._iter_overlays():
overlay._delete_virtual(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)
self._virtual_keys.discard(key)
for overlay in self._iter_overlays():
overlay._delete_virtual(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",
")",
"dict",
".",
"__delitem__",
"(",
"self",
",",
"key",
")",
"self",
".",
"_virtual_keys",
".",
"discard",
"(",
"key",
")",
"for",
"overlay",
"in",
"self",
".",
"_iter_overlays",
"(",
")",
":",
"overlay",
".",
"_delete_virtual",
"(",
"key",
")"
] | 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 |
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 |
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, if possible.
Whitespace is replaced by a single dash. Leading or tailing dots
or dashes are removed. The filename is limited to 255 characters.
"""
fname = self.raw_filename
if not isinstance(fname, unicode):
fname = fname.decode('utf8', 'ignore')
fname = normalize('NFKD', fname)
fname = fname.encode('ASCII', 'ignore').decode('ASCII')
fname = os.path.basename(fname.replace('\\', os.path.sep))
fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip()
fname = re.sub(r'[-\s]+', '-', fname).strip('.-')
return fname[:255] or 'empty' | 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, if possible.
Whitespace is replaced by a single dash. Leading or tailing dots
or dashes are removed. The filename is limited to 255 characters.
"""
fname = self.raw_filename
if not isinstance(fname, unicode):
fname = fname.decode('utf8', 'ignore')
fname = normalize('NFKD', fname)
fname = fname.encode('ASCII', 'ignore').decode('ASCII')
fname = os.path.basename(fname.replace('\\', os.path.sep))
fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip()
fname = re.sub(r'[-\s]+', '-', fname).strip('.-')
return fname[:255] or 'empty' | [
"def",
"filename",
"(",
"self",
")",
":",
"fname",
"=",
"self",
".",
"raw_filename",
"if",
"not",
"isinstance",
"(",
"fname",
",",
"unicode",
")",
":",
"fname",
"=",
"fname",
".",
"decode",
"(",
"'utf8'",
",",
"'ignore'",
")",
"fname",
"=",
"normalize",
"(",
"'NFKD'",
",",
"fname",
")",
"fname",
"=",
"fname",
".",
"encode",
"(",
"'ASCII'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"'ASCII'",
")",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
".",
"replace",
"(",
"'\\\\'",
",",
"os",
".",
"path",
".",
"sep",
")",
")",
"fname",
"=",
"re",
".",
"sub",
"(",
"r'[^a-zA-Z0-9-_.\\s]'",
",",
"''",
",",
"fname",
")",
".",
"strip",
"(",
")",
"fname",
"=",
"re",
".",
"sub",
"(",
"r'[-\\s]+'",
",",
"'-'",
",",
"fname",
")",
".",
"strip",
"(",
"'.-'",
")",
"return",
"fname",
"[",
":",
"255",
"]",
"or",
"'empty'"
] | 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.
Whitespace is replaced by a single dash. Leading or tailing dots
or dashes are removed. The filename is limited to 255 characters. | [
"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 |
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]
elif isinstance(text, StringToTranslate):
out = await text.render_list(request)
else:
raise TypeError('Provided text cannot be rendered')
if multi_line:
return out
else:
return ' '.join(out) | 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]
elif isinstance(text, StringToTranslate):
out = await text.render_list(request)
else:
raise TypeError('Provided text cannot be rendered')
if multi_line:
return out
else:
return ' '.join(out) | [
"async",
"def",
"render",
"(",
"text",
":",
"TransText",
",",
"request",
":",
"Optional",
"[",
"'Request'",
"]",
",",
"multi_line",
"=",
"False",
")",
"->",
"Union",
"[",
"Text",
",",
"List",
"[",
"Text",
"]",
"]",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"out",
"=",
"[",
"text",
"]",
"elif",
"isinstance",
"(",
"text",
",",
"StringToTranslate",
")",
":",
"out",
"=",
"await",
"text",
".",
"render_list",
"(",
"request",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Provided text cannot be rendered'",
")",
"if",
"multi_line",
":",
"return",
"out",
"else",
":",
"return",
"' '",
".",
"join",
"(",
"out",
")"
] | 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 |
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",
":",
"score",
"+=",
"1",
"return",
"score"
] | 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 |
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:
score = item.score(flags)
if score == best_score:
best_list.append(item)
elif score > best_score:
best_list = [item]
best_score = score
return best_list | 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:
score = item.score(flags)
if score == best_score:
best_list.append(item)
elif score > best_score:
best_list = [item]
best_score = score
return best_list | [
"def",
"best_for_flags",
"(",
"self",
",",
"flags",
":",
"Flags",
")",
"->",
"List",
"[",
"TransItem",
"]",
":",
"best_score",
":",
"int",
"=",
"0",
"best_list",
":",
"List",
"[",
"TransItem",
"]",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"items",
":",
"score",
"=",
"item",
".",
"score",
"(",
"flags",
")",
"if",
"score",
"==",
"best_score",
":",
"best_list",
".",
"append",
"(",
"item",
")",
"elif",
"score",
">",
"best_score",
":",
"best_list",
"=",
"[",
"item",
"]",
"best_score",
"=",
"score",
"return",
"best_list"
] | 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 |
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 |
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",
".",
"items",
")",
"self",
".",
"items",
"=",
"items"
] | 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 |
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 |
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_SENTENCES_PER_GROUP):
return
if len(self.sentences) < item.index:
for _ in range(len(self.sentences), item.index):
self.sentences.append(Sentence())
self.sentences[item.index - 1].append(item) | 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_SENTENCES_PER_GROUP):
return
if len(self.sentences) < item.index:
for _ in range(len(self.sentences), item.index):
self.sentences.append(Sentence())
self.sentences[item.index - 1].append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
":",
"TransItem",
")",
":",
"if",
"not",
"(",
"1",
"<=",
"item",
".",
"index",
"<=",
"settings",
".",
"I18N_MAX_SENTENCES_PER_GROUP",
")",
":",
"return",
"if",
"len",
"(",
"self",
".",
"sentences",
")",
"<",
"item",
".",
"index",
":",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sentences",
")",
",",
"item",
".",
"index",
")",
":",
"self",
".",
"sentences",
".",
"append",
"(",
"Sentence",
"(",
")",
")",
"self",
".",
"sentences",
"[",
"item",
".",
"index",
"-",
"1",
"]",
".",
"append",
"(",
"item",
")"
] | 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 |
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_append = []
for old, new in zip_longest(self.sentences, group.sentences):
if old is None:
old = Sentence()
to_append.append(old)
if new is None:
new = Sentence()
old.update(new, flags)
self.sentences.extend(to_append) | 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_append = []
for old, new in zip_longest(self.sentences, group.sentences):
if old is None:
old = Sentence()
to_append.append(old)
if new is None:
new = Sentence()
old.update(new, flags)
self.sentences.extend(to_append) | [
"def",
"update",
"(",
"self",
",",
"group",
":",
"'SentenceGroup'",
",",
"flags",
":",
"Flags",
")",
"->",
"None",
":",
"to_append",
"=",
"[",
"]",
"for",
"old",
",",
"new",
"in",
"zip_longest",
"(",
"self",
".",
"sentences",
",",
"group",
".",
"sentences",
")",
":",
"if",
"old",
"is",
"None",
":",
"old",
"=",
"Sentence",
"(",
")",
"to_append",
".",
"append",
"(",
"old",
")",
"if",
"new",
"is",
"None",
":",
"new",
"=",
"Sentence",
"(",
")",
"old",
".",
"update",
"(",
"new",
",",
"flags",
")",
"self",
".",
"sentences",
".",
"extend",
"(",
"to_append",
")"
] | 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",
"content",
"of",
"the",
"specified",
"group",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L212-L231 | train |
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 |
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 |
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(self.update)
run(instance.load(**loader['params'])) | 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(self.update)
run(instance.load(**loader['params'])) | [
"def",
"_init_loaders",
"(",
"self",
")",
"->",
"None",
":",
"for",
"loader",
"in",
"settings",
".",
"I18N_TRANSLATION_LOADERS",
":",
"loader_class",
"=",
"import_class",
"(",
"loader",
"[",
"'loader'",
"]",
")",
"instance",
"=",
"loader_class",
"(",
")",
"instance",
".",
"on_update",
"(",
"self",
".",
"update",
")",
"run",
"(",
"instance",
".",
"load",
"(",
"*",
"*",
"loader",
"[",
"'params'",
"]",
")",
")"
] | 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 |
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 data):
if item:
sd.append(item)
if lang not in self.dict:
self.dict[lang] = {}
d = self.dict[lang]
for k, v in sd.extract().items():
if k not in d:
d[k] = SentenceGroup()
d[k].update(v, flags) | 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 data):
if item:
sd.append(item)
if lang not in self.dict:
self.dict[lang] = {}
d = self.dict[lang]
for k, v in sd.extract().items():
if k not in d:
d[k] = SentenceGroup()
d[k].update(v, flags) | [
"def",
"update_lang",
"(",
"self",
",",
"lang",
":",
"Optional",
"[",
"Text",
"]",
",",
"data",
":",
"List",
"[",
"Tuple",
"[",
"Text",
",",
"Text",
"]",
"]",
",",
"flags",
":",
"Flags",
")",
":",
"sd",
"=",
"SortingDict",
"(",
")",
"for",
"item",
"in",
"(",
"self",
".",
"parse_item",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
",",
"flags",
")",
"for",
"x",
"in",
"data",
")",
":",
"if",
"item",
":",
"sd",
".",
"append",
"(",
"item",
")",
"if",
"lang",
"not",
"in",
"self",
".",
"dict",
":",
"self",
".",
"dict",
"[",
"lang",
"]",
"=",
"{",
"}",
"d",
"=",
"self",
".",
"dict",
"[",
"lang",
"]",
"for",
"k",
",",
"v",
"in",
"sd",
".",
"extract",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"d",
":",
"d",
"[",
"k",
"]",
"=",
"SentenceGroup",
"(",
")",
"d",
"[",
"k",
"]",
".",
"update",
"(",
"v",
",",
"flags",
")"
] | 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 |
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 |
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 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
:param flags: Flags to help choosing one version or the other
"""
if params is None:
params = {}
if count is not None:
raise TranslationError('Count parameter is not supported yet')
locale = self.choose_locale(locale)
try:
group: SentenceGroup = self.dict[locale][key]
except KeyError:
raise MissingTranslationError('Translation "{}" does not exist'
.format(key))
try:
trans = group.render(flags or {})
out = []
for line in trans:
if not formatter:
out.append(line.format(**params))
else:
out.append(formatter.format(line, **params))
except KeyError as e:
raise MissingParamError(
'Parameter "{}" missing to translate "{}"'
.format(e.args[0], key)
)
else:
return out | 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 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
:param flags: Flags to help choosing one version or the other
"""
if params is None:
params = {}
if count is not None:
raise TranslationError('Count parameter is not supported yet')
locale = self.choose_locale(locale)
try:
group: SentenceGroup = self.dict[locale][key]
except KeyError:
raise MissingTranslationError('Translation "{}" does not exist'
.format(key))
try:
trans = group.render(flags or {})
out = []
for line in trans:
if not formatter:
out.append(line.format(**params))
else:
out.append(formatter.format(line, **params))
except KeyError as e:
raise MissingParamError(
'Parameter "{}" missing to translate "{}"'
.format(e.args[0], key)
)
else:
return out | [
"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",
"]",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"count",
"is",
"not",
"None",
":",
"raise",
"TranslationError",
"(",
"'Count parameter is not supported yet'",
")",
"locale",
"=",
"self",
".",
"choose_locale",
"(",
"locale",
")",
"try",
":",
"group",
":",
"SentenceGroup",
"=",
"self",
".",
"dict",
"[",
"locale",
"]",
"[",
"key",
"]",
"except",
"KeyError",
":",
"raise",
"MissingTranslationError",
"(",
"'Translation \"{}\" does not exist'",
".",
"format",
"(",
"key",
")",
")",
"try",
":",
"trans",
"=",
"group",
".",
"render",
"(",
"flags",
"or",
"{",
"}",
")",
"out",
"=",
"[",
"]",
"for",
"line",
"in",
"trans",
":",
"if",
"not",
"formatter",
":",
"out",
".",
"append",
"(",
"line",
".",
"format",
"(",
"*",
"*",
"params",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"formatter",
".",
"format",
"(",
"line",
",",
"*",
"*",
"params",
")",
")",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"MissingParamError",
"(",
"'Parameter \"{}\" missing to translate \"{}\"'",
".",
"format",
"(",
"e",
".",
"args",
"[",
"0",
"]",
",",
"key",
")",
")",
"else",
":",
"return",
"out"
] | 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
:param flags: Flags to help choosing one version or the other | [
"Get",
"the",
"appropriate",
"translation",
"given",
"the",
"specified",
"parameters",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L348-L395 | train |
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.items():
if isinstance(v, StringToTranslate):
out[k] = await render(v, request)
else:
out[k] = v
return out | 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.items():
if isinstance(v, StringToTranslate):
out[k] = await render(v, request)
else:
out[k] = v
return out | [
"async",
"def",
"_resolve_params",
"(",
"self",
",",
"params",
":",
"Dict",
"[",
"Text",
",",
"Any",
"]",
",",
"request",
":",
"Optional",
"[",
"'Request'",
"]",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"StringToTranslate",
")",
":",
"out",
"[",
"k",
"]",
"=",
"await",
"render",
"(",
"v",
",",
"request",
")",
"else",
":",
"out",
"[",
"k",
"]",
"=",
"v",
"return",
"out"
] | 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 |
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 request.user.get_timezone()
locale = await request.get_locale()
flags = await request.get_trans_flags()
else:
tz = None
locale = self.wd.list_locales()[0]
flags = {}
rp = MiddlewareManager.instance()\
.get('resolve_trans_params', self._resolve_params)
resolved_params = await rp(self.params, request)
f = I18nFormatter(self.wd.choose_locale(locale), tz)
return self.wd.get(
self.key,
self.count,
f,
locale,
resolved_params,
flags,
) | 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 request.user.get_timezone()
locale = await request.get_locale()
flags = await request.get_trans_flags()
else:
tz = None
locale = self.wd.list_locales()[0]
flags = {}
rp = MiddlewareManager.instance()\
.get('resolve_trans_params', self._resolve_params)
resolved_params = await rp(self.params, request)
f = I18nFormatter(self.wd.choose_locale(locale), tz)
return self.wd.get(
self.key,
self.count,
f,
locale,
resolved_params,
flags,
) | [
"async",
"def",
"render_list",
"(",
"self",
",",
"request",
"=",
"None",
")",
"->",
"List",
"[",
"Text",
"]",
":",
"from",
"bernard",
".",
"middleware",
"import",
"MiddlewareManager",
"if",
"request",
":",
"tz",
"=",
"await",
"request",
".",
"user",
".",
"get_timezone",
"(",
")",
"locale",
"=",
"await",
"request",
".",
"get_locale",
"(",
")",
"flags",
"=",
"await",
"request",
".",
"get_trans_flags",
"(",
")",
"else",
":",
"tz",
"=",
"None",
"locale",
"=",
"self",
".",
"wd",
".",
"list_locales",
"(",
")",
"[",
"0",
"]",
"flags",
"=",
"{",
"}",
"rp",
"=",
"MiddlewareManager",
".",
"instance",
"(",
")",
".",
"get",
"(",
"'resolve_trans_params'",
",",
"self",
".",
"_resolve_params",
")",
"resolved_params",
"=",
"await",
"rp",
"(",
"self",
".",
"params",
",",
"request",
")",
"f",
"=",
"I18nFormatter",
"(",
"self",
".",
"wd",
".",
"choose_locale",
"(",
"locale",
")",
",",
"tz",
")",
"return",
"self",
".",
"wd",
".",
"get",
"(",
"self",
".",
"key",
",",
"self",
".",
"count",
",",
"f",
",",
"locale",
",",
"resolved_params",
",",
"flags",
",",
")"
] | 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 |
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 "{}"'
.format(stack.describe()))
self._stacks.append(stack) | 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 "{}"'
.format(stack.describe()))
self._stacks.append(stack) | [
"def",
"send",
"(",
"self",
",",
"stack",
":",
"Layers",
")",
":",
"if",
"not",
"isinstance",
"(",
"stack",
",",
"Stack",
")",
":",
"stack",
"=",
"Stack",
"(",
"stack",
")",
"if",
"not",
"self",
".",
"platform",
".",
"accept",
"(",
"stack",
")",
":",
"raise",
"UnacceptableStack",
"(",
"'The platform does not allow \"{}\"'",
".",
"format",
"(",
"stack",
".",
"describe",
"(",
")",
")",
")",
"self",
".",
"_stacks",
".",
"append",
"(",
"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 |
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
for stack in self._stacks:
await stack.convert_media(self.platform)
func = MiddlewareManager.instance().get('flush', self._flush)
await func(request, self._stacks) | 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
for stack in self._stacks:
await stack.convert_media(self.platform)
func = MiddlewareManager.instance().get('flush', self._flush)
await func(request, self._stacks) | [
"async",
"def",
"flush",
"(",
"self",
",",
"request",
":",
"'Request'",
")",
":",
"from",
"bernard",
".",
"middleware",
"import",
"MiddlewareManager",
"for",
"stack",
"in",
"self",
".",
"_stacks",
":",
"await",
"stack",
".",
"convert_media",
"(",
"self",
".",
"platform",
")",
"func",
"=",
"MiddlewareManager",
".",
"instance",
"(",
")",
".",
"get",
"(",
"'flush'",
",",
"self",
".",
"_flush",
")",
"await",
"func",
"(",
"request",
",",
"self",
".",
"_stacks",
")"
] | 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 |
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",
",",
"request",
")",
"return",
"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 |
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\"",
",",
"\"\"",
",",
"line",
")"
] | 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 |
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'",
"]",
")",
"+",
"float",
"(",
"self",
"[",
"'penaltyBalance'",
"]",
")",
"return",
"debt"
] | 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 |
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 true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def duedate(repayment):
"""Util function used for sorting repayments according to due Date"""
try:
return repayment['dueDate']
except KeyError as kerr:
return datetime.now()
try:
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mamburepayment import MambuRepayments
self.mamburepaymentsclass = MambuRepayments
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
reps.attrs = sorted(reps.attrs, key=duedate)
self['repayments'] = reps
return 1 | 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 true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def duedate(repayment):
"""Util function used for sorting repayments according to due Date"""
try:
return repayment['dueDate']
except KeyError as kerr:
return datetime.now()
try:
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mamburepayment import MambuRepayments
self.mamburepaymentsclass = MambuRepayments
reps = self.mamburepaymentsclass(entid=self['id'], *args, **kwargs)
reps.attrs = sorted(reps.attrs, key=duedate)
self['repayments'] = reps
return 1 | [
"def",
"setRepayments",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"duedate",
"(",
"repayment",
")",
":",
"\"\"\"Util function used for sorting repayments according to due Date\"\"\"",
"try",
":",
"return",
"repayment",
"[",
"'dueDate'",
"]",
"except",
"KeyError",
"as",
"kerr",
":",
"return",
"datetime",
".",
"now",
"(",
")",
"try",
":",
"reps",
"=",
"self",
".",
"mamburepaymentsclass",
"(",
"entid",
"=",
"self",
"[",
"'id'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mamburepayment",
"import",
"MambuRepayments",
"self",
".",
"mamburepaymentsclass",
"=",
"MambuRepayments",
"reps",
"=",
"self",
".",
"mamburepaymentsclass",
"(",
"entid",
"=",
"self",
"[",
"'id'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"reps",
".",
"attrs",
"=",
"sorted",
"(",
"reps",
".",
"attrs",
",",
"key",
"=",
"duedate",
")",
"self",
"[",
"'repayments'",
"]",
"=",
"reps",
"return",
"1"
] | 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 more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete | [
"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 |
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, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def transactionid(transaction):
"""Util function used for sorting transactions according to id"""
try:
return transaction['transactionId']
except KeyError as kerr:
return None
try:
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mambutransaction import MambuTransactions
self.mambutransactionsclass = MambuTransactions
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
trans.attrs = sorted(trans.attrs, key=transactionid)
self['transactions'] = trans
return 1 | 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, is not always true that
just 1 request was done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete
"""
def transactionid(transaction):
"""Util function used for sorting transactions according to id"""
try:
return transaction['transactionId']
except KeyError as kerr:
return None
try:
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
except AttributeError as ae:
from .mambutransaction import MambuTransactions
self.mambutransactionsclass = MambuTransactions
trans = self.mambutransactionsclass(entid=self['id'], *args, **kwargs)
trans.attrs = sorted(trans.attrs, key=transactionid)
self['transactions'] = trans
return 1 | [
"def",
"setTransactions",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"transactionid",
"(",
"transaction",
")",
":",
"\"\"\"Util function used for sorting transactions according to id\"\"\"",
"try",
":",
"return",
"transaction",
"[",
"'transactionId'",
"]",
"except",
"KeyError",
"as",
"kerr",
":",
"return",
"None",
"try",
":",
"trans",
"=",
"self",
".",
"mambutransactionsclass",
"(",
"entid",
"=",
"self",
"[",
"'id'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mambutransaction",
"import",
"MambuTransactions",
"self",
".",
"mambutransactionsclass",
"=",
"MambuTransactions",
"trans",
"=",
"self",
".",
"mambutransactionsclass",
"(",
"entid",
"=",
"self",
"[",
"'id'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"trans",
".",
"attrs",
"=",
"sorted",
"(",
"trans",
".",
"attrs",
",",
"key",
"=",
"transactionid",
")",
"self",
"[",
"'transactions'",
"]",
"=",
"trans",
"return",
"1"
] | 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 done. It may be more! But since request
counter singleton holds true information about how many requests
were done to Mambu, in fact this return value may be obsolete | [
"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 |
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:
centre = self.mambucentreclass(entid=self['assignedCentreKey'], *args, **kwargs)
except AttributeError as ae:
from .mambucentre import MambuCentre
self.mambucentreclass = MambuCentre
centre = self.mambucentreclass(entid=self['assignedCentreKey'], *args, **kwargs)
self['assignedCentreName'] = centre['name']
self['assignedCentre'] = centre
return 1 | 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:
centre = self.mambucentreclass(entid=self['assignedCentreKey'], *args, **kwargs)
except AttributeError as ae:
from .mambucentre import MambuCentre
self.mambucentreclass = MambuCentre
centre = self.mambucentreclass(entid=self['assignedCentreKey'], *args, **kwargs)
self['assignedCentreName'] = centre['name']
self['assignedCentre'] = centre
return 1 | [
"def",
"setCentre",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"centre",
"=",
"self",
".",
"mambucentreclass",
"(",
"entid",
"=",
"self",
"[",
"'assignedCentreKey'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AttributeError",
"as",
"ae",
":",
"from",
".",
"mambucentre",
"import",
"MambuCentre",
"self",
".",
"mambucentreclass",
"=",
"MambuCentre",
"centre",
"=",
"self",
".",
"mambucentreclass",
"(",
"entid",
"=",
"self",
"[",
"'assignedCentreKey'",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
"[",
"'assignedCentreName'",
"]",
"=",
"centre",
"[",
"'name'",
"]",
"self",
"[",
"'assignedCentre'",
"]",
"=",
"centre",
"return",
"1"
] | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.