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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
abilian/abilian-core | abilian/web/blueprints.py | allow_access_for_roles | def allow_access_for_roles(roles):
"""Access control helper to check user's roles against a list of valid
roles."""
if isinstance(roles, Role):
roles = (roles,)
valid_roles = frozenset(roles)
if Anonymous in valid_roles:
return allow_anonymous
def check_role(user, roles, **kwargs):
from abilian.services import get_service
security = get_service("security")
return security.has_role(user, valid_roles)
return check_role | python | def allow_access_for_roles(roles):
"""Access control helper to check user's roles against a list of valid
roles."""
if isinstance(roles, Role):
roles = (roles,)
valid_roles = frozenset(roles)
if Anonymous in valid_roles:
return allow_anonymous
def check_role(user, roles, **kwargs):
from abilian.services import get_service
security = get_service("security")
return security.has_role(user, valid_roles)
return check_role | [
"def",
"allow_access_for_roles",
"(",
"roles",
")",
":",
"if",
"isinstance",
"(",
"roles",
",",
"Role",
")",
":",
"roles",
"=",
"(",
"roles",
",",
")",
"valid_roles",
"=",
"frozenset",
"(",
"roles",
")",
"if",
"Anonymous",
"in",
"valid_roles",
":",
"retu... | Access control helper to check user's roles against a list of valid
roles. | [
"Access",
"control",
"helper",
"to",
"check",
"user",
"s",
"roles",
"against",
"a",
"list",
"of",
"valid",
"roles",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/blueprints.py#L12-L28 | train | 43,000 |
abilian/abilian-core | abilian/web/forms/fields.py | FileField.populate_obj | def populate_obj(self, obj, name):
"""Store file."""
from abilian.core.models.blob import Blob
delete_value = self.allow_delete and self.delete_files_index
if not self.has_file() and not delete_value:
# nothing uploaded, and nothing to delete
return
state = sa.inspect(obj)
mapper = state.mapper
if name not in mapper.relationships:
# directly store in database
return super().populate_obj(obj, name)
rel = getattr(mapper.relationships, name)
if rel.uselist:
raise ValueError("Only single target supported; else use ModelFieldList")
if delete_value:
setattr(obj, name, None)
return
# FIXME: propose option to always create a new blob
cls = rel.mapper.class_
val = getattr(obj, name)
if val is None:
val = cls()
setattr(obj, name, val)
data = ""
if self.has_file():
data = self.data
if not issubclass(cls, Blob):
data = data.read()
setattr(val, self.blob_attr, data) | python | def populate_obj(self, obj, name):
"""Store file."""
from abilian.core.models.blob import Blob
delete_value = self.allow_delete and self.delete_files_index
if not self.has_file() and not delete_value:
# nothing uploaded, and nothing to delete
return
state = sa.inspect(obj)
mapper = state.mapper
if name not in mapper.relationships:
# directly store in database
return super().populate_obj(obj, name)
rel = getattr(mapper.relationships, name)
if rel.uselist:
raise ValueError("Only single target supported; else use ModelFieldList")
if delete_value:
setattr(obj, name, None)
return
# FIXME: propose option to always create a new blob
cls = rel.mapper.class_
val = getattr(obj, name)
if val is None:
val = cls()
setattr(obj, name, val)
data = ""
if self.has_file():
data = self.data
if not issubclass(cls, Blob):
data = data.read()
setattr(val, self.blob_attr, data) | [
"def",
"populate_obj",
"(",
"self",
",",
"obj",
",",
"name",
")",
":",
"from",
"abilian",
".",
"core",
".",
"models",
".",
"blob",
"import",
"Blob",
"delete_value",
"=",
"self",
".",
"allow_delete",
"and",
"self",
".",
"delete_files_index",
"if",
"not",
... | Store file. | [
"Store",
"file",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/fields.py#L243-L281 | train | 43,001 |
abilian/abilian-core | abilian/services/settings/service.py | SettingsService.keys | def keys(self, prefix=None):
"""List all keys, with optional prefix filtering."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
# don't use iteritems: 'value' require little processing whereas we only
# want 'key'
return [i[0] for i in query.yield_per(1000).values(Setting.key)] | python | def keys(self, prefix=None):
"""List all keys, with optional prefix filtering."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
# don't use iteritems: 'value' require little processing whereas we only
# want 'key'
return [i[0] for i in query.yield_per(1000).values(Setting.key)] | [
"def",
"keys",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"query",
"=",
"Setting",
".",
"query",
"if",
"prefix",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Setting",
".",
"key",
".",
"startswith",
"(",
"prefix",
")",
")",
"# don't use i... | List all keys, with optional prefix filtering. | [
"List",
"all",
"keys",
"with",
"optional",
"prefix",
"filtering",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/settings/service.py#L18-L26 | train | 43,002 |
abilian/abilian-core | abilian/services/settings/service.py | SettingsService.iteritems | def iteritems(self, prefix=None):
"""Like dict.iteritems."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
for s in query.yield_per(1000):
yield (s.key, s.value) | python | def iteritems(self, prefix=None):
"""Like dict.iteritems."""
query = Setting.query
if prefix:
query = query.filter(Setting.key.startswith(prefix))
for s in query.yield_per(1000):
yield (s.key, s.value) | [
"def",
"iteritems",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"query",
"=",
"Setting",
".",
"query",
"if",
"prefix",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Setting",
".",
"key",
".",
"startswith",
"(",
"prefix",
")",
")",
"for",
... | Like dict.iteritems. | [
"Like",
"dict",
".",
"iteritems",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/settings/service.py#L28-L35 | train | 43,003 |
abilian/abilian-core | abilian/core/models/comment.py | for_entity | def for_entity(obj, check_commentable=False):
"""Return comments on an entity."""
if check_commentable and not is_commentable(obj):
return []
return getattr(obj, ATTRIBUTE) | python | def for_entity(obj, check_commentable=False):
"""Return comments on an entity."""
if check_commentable and not is_commentable(obj):
return []
return getattr(obj, ATTRIBUTE) | [
"def",
"for_entity",
"(",
"obj",
",",
"check_commentable",
"=",
"False",
")",
":",
"if",
"check_commentable",
"and",
"not",
"is_commentable",
"(",
"obj",
")",
":",
"return",
"[",
"]",
"return",
"getattr",
"(",
"obj",
",",
"ATTRIBUTE",
")"
] | Return comments on an entity. | [
"Return",
"comments",
"on",
"an",
"entity",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/comment.py#L57-L62 | train | 43,004 |
abilian/abilian-core | abilian/web/action.py | Action.available | def available(self, context):
"""Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter.
"""
if not self._enabled:
return False
try:
return self.pre_condition(context) and self._check_condition(context)
except Exception:
return False | python | def available(self, context):
"""Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter.
"""
if not self._enabled:
return False
try:
return self.pre_condition(context) and self._check_condition(context)
except Exception:
return False | [
"def",
"available",
"(",
"self",
",",
"context",
")",
":",
"if",
"not",
"self",
".",
"_enabled",
":",
"return",
"False",
"try",
":",
"return",
"self",
".",
"pre_condition",
"(",
"context",
")",
"and",
"self",
".",
"_check_condition",
"(",
"context",
")",... | Determine if this actions is available in this `context`.
:param context: a dict whose content is left to application needs; if
:attr:`.condition` is a callable it receives `context`
in parameter. | [
"Determine",
"if",
"this",
"actions",
"is",
"available",
"in",
"this",
"context",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L398-L410 | train | 43,005 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.installed | def installed(self, app=None):
"""Return `True` if the registry has been installed in current
applications."""
if app is None:
app = current_app
return self.__EXTENSION_NAME in app.extensions | python | def installed(self, app=None):
"""Return `True` if the registry has been installed in current
applications."""
if app is None:
app = current_app
return self.__EXTENSION_NAME in app.extensions | [
"def",
"installed",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"current_app",
"return",
"self",
".",
"__EXTENSION_NAME",
"in",
"app",
".",
"extensions"
] | Return `True` if the registry has been installed in current
applications. | [
"Return",
"True",
"if",
"the",
"registry",
"has",
"been",
"installed",
"in",
"current",
"applications",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L574-L579 | train | 43,006 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.actions | def actions(self, context=None):
"""Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`).
"""
assert self.installed(), "Actions not enabled on this application"
result = {}
if context is None:
context = self.context
for cat, actions in self._state["categories"].items():
result[cat] = [a for a in actions if a.available(context)]
return result | python | def actions(self, context=None):
"""Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`).
"""
assert self.installed(), "Actions not enabled on this application"
result = {}
if context is None:
context = self.context
for cat, actions in self._state["categories"].items():
result[cat] = [a for a in actions if a.available(context)]
return result | [
"def",
"actions",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"assert",
"self",
".",
"installed",
"(",
")",
",",
"\"Actions not enabled on this application\"",
"result",
"=",
"{",
"}",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
"."... | Return a mapping of category => actions list.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`). | [
"Return",
"a",
"mapping",
"of",
"category",
"=",
">",
"actions",
"list",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L597-L612 | train | 43,007 |
abilian/abilian-core | abilian/web/action.py | ActionRegistry.for_category | def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.installed(), "Actions not enabled on this application"
actions = self._state["categories"].get(category, [])
if context is None:
context = self.context
return [a for a in actions if a.available(context)] | python | def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.installed(), "Actions not enabled on this application"
actions = self._state["categories"].get(category, [])
if context is None:
context = self.context
return [a for a in actions if a.available(context)] | [
"def",
"for_category",
"(",
"self",
",",
"category",
",",
"context",
"=",
"None",
")",
":",
"assert",
"self",
".",
"installed",
"(",
")",
",",
"\"Actions not enabled on this application\"",
"actions",
"=",
"self",
".",
"_state",
"[",
"\"categories\"",
"]",
"."... | Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`) | [
"Returns",
"actions",
"list",
"for",
"this",
"category",
"in",
"current",
"application",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/action.py#L614-L628 | train | 43,008 |
abilian/abilian-core | abilian/services/auth/models.py | LoginSessionQuery.get_active_for | def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_agent.
:type user_agent: string or None, or absent
:param ip_address: client IP, or `None` to have ip_address extracted from
request object (requires header 'X-Forwarded-For'). If not provided at
all, no filtering on ip_address.
:type ip_address: string or None, or absent
:rtype: `LoginSession` or `None` if no session is found.
"""
conditions = [LoginSession.user == user]
if user_agent is not _MARK:
if user_agent is None:
user_agent = request.environ.get("HTTP_USER_AGENT", "")
conditions.append(LoginSession.user_agent == user_agent)
if ip_address is not _MARK:
if ip_address is None:
ip_addresses = request.headers.getlist("X-Forwarded-For")
ip_address = ip_addresses[0] if ip_addresses else request.remote_addr
conditions.append(LoginSession.ip_address == ip_address)
session = (
LoginSession.query.filter(*conditions)
.order_by(LoginSession.id.desc())
.first()
)
return session | python | def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_agent.
:type user_agent: string or None, or absent
:param ip_address: client IP, or `None` to have ip_address extracted from
request object (requires header 'X-Forwarded-For'). If not provided at
all, no filtering on ip_address.
:type ip_address: string or None, or absent
:rtype: `LoginSession` or `None` if no session is found.
"""
conditions = [LoginSession.user == user]
if user_agent is not _MARK:
if user_agent is None:
user_agent = request.environ.get("HTTP_USER_AGENT", "")
conditions.append(LoginSession.user_agent == user_agent)
if ip_address is not _MARK:
if ip_address is None:
ip_addresses = request.headers.getlist("X-Forwarded-For")
ip_address = ip_addresses[0] if ip_addresses else request.remote_addr
conditions.append(LoginSession.ip_address == ip_address)
session = (
LoginSession.query.filter(*conditions)
.order_by(LoginSession.id.desc())
.first()
)
return session | [
"def",
"get_active_for",
"(",
"self",
",",
"user",
",",
"user_agent",
"=",
"_MARK",
",",
"ip_address",
"=",
"_MARK",
")",
":",
"conditions",
"=",
"[",
"LoginSession",
".",
"user",
"==",
"user",
"]",
"if",
"user_agent",
"is",
"not",
"_MARK",
":",
"if",
... | Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_agent.
:type user_agent: string or None, or absent
:param ip_address: client IP, or `None` to have ip_address extracted from
request object (requires header 'X-Forwarded-For'). If not provided at
all, no filtering on ip_address.
:type ip_address: string or None, or absent
:rtype: `LoginSession` or `None` if no session is found. | [
"Return",
"last",
"known",
"session",
"for",
"given",
"user",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/models.py#L18-L54 | train | 43,009 |
Ceasar/staticjinja | staticjinja/reloader.py | Reloader.should_handle | def should_handle(self, event_type, filename):
"""Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event.
"""
return (event_type in ("modified", "created") and
filename.startswith(self.searchpath) and
os.path.isfile(filename)) | python | def should_handle(self, event_type, filename):
"""Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event.
"""
return (event_type in ("modified", "created") and
filename.startswith(self.searchpath) and
os.path.isfile(filename)) | [
"def",
"should_handle",
"(",
"self",
",",
"event_type",
",",
"filename",
")",
":",
"return",
"(",
"event_type",
"in",
"(",
"\"modified\"",
",",
"\"created\"",
")",
"and",
"filename",
".",
"startswith",
"(",
"self",
".",
"searchpath",
")",
"and",
"os",
".",... | Check if an event should be handled.
An event should be handled if a file in the searchpath was modified.
:param event_type: a string, representing the type of event
:param filename: the path to the file that triggered the event. | [
"Check",
"if",
"an",
"event",
"should",
"be",
"handled",
"."
] | 57b8cac81da7fee3387510af4843e1bd1fd3ba28 | https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/reloader.py#L20-L31 | train | 43,010 |
Ceasar/staticjinja | staticjinja/reloader.py | Reloader.event_handler | def event_handler(self, event_type, src_path):
"""Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event.
"""
filename = os.path.relpath(src_path, self.searchpath)
if self.should_handle(event_type, src_path):
print("%s %s" % (event_type, filename))
if self.site.is_static(filename):
files = self.site.get_dependencies(filename)
self.site.copy_static(files)
else:
templates = self.site.get_dependencies(filename)
self.site.render_templates(templates) | python | def event_handler(self, event_type, src_path):
"""Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event.
"""
filename = os.path.relpath(src_path, self.searchpath)
if self.should_handle(event_type, src_path):
print("%s %s" % (event_type, filename))
if self.site.is_static(filename):
files = self.site.get_dependencies(filename)
self.site.copy_static(files)
else:
templates = self.site.get_dependencies(filename)
self.site.render_templates(templates) | [
"def",
"event_handler",
"(",
"self",
",",
"event_type",
",",
"src_path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"src_path",
",",
"self",
".",
"searchpath",
")",
"if",
"self",
".",
"should_handle",
"(",
"event_type",
",",
"src_... | Re-render templates if they are modified.
:param event_type: a string, representing the type of event
:param src_path: the path to the file that triggered the event. | [
"Re",
"-",
"render",
"templates",
"if",
"they",
"are",
"modified",
"."
] | 57b8cac81da7fee3387510af4843e1bd1fd3ba28 | https://github.com/Ceasar/staticjinja/blob/57b8cac81da7fee3387510af4843e1bd1fd3ba28/staticjinja/reloader.py#L33-L49 | train | 43,011 |
abilian/abilian-core | abilian/web/csrf.py | protect | def protect(view):
"""Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails.
"""
@wraps(view)
def csrf_check(*args, **kwargs):
# an empty form is used to validate current csrf token and only that!
if not FlaskForm().validate():
raise Forbidden("CSRF validation failed.")
return view(*args, **kwargs)
return csrf_check | python | def protect(view):
"""Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails.
"""
@wraps(view)
def csrf_check(*args, **kwargs):
# an empty form is used to validate current csrf token and only that!
if not FlaskForm().validate():
raise Forbidden("CSRF validation failed.")
return view(*args, **kwargs)
return csrf_check | [
"def",
"protect",
"(",
"view",
")",
":",
"@",
"wraps",
"(",
"view",
")",
"def",
"csrf_check",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# an empty form is used to validate current csrf token and only that!",
"if",
"not",
"FlaskForm",
"(",
")",
".",... | Protects a view agains CSRF attacks by checking `csrf_token` value in
submitted values. Do nothing if `config.WTF_CSRF_ENABLED` is not set.
Raises `werkzeug.exceptions.Forbidden` if validation fails. | [
"Protects",
"a",
"view",
"agains",
"CSRF",
"attacks",
"by",
"checking",
"csrf_token",
"value",
"in",
"submitted",
"values",
".",
"Do",
"nothing",
"if",
"config",
".",
"WTF_CSRF_ENABLED",
"is",
"not",
"set",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/csrf.py#L60-L75 | train | 43,012 |
abilian/abilian-core | abilian/core/entities.py | auto_slug_after_insert | def auto_slug_after_insert(mapper, connection, target):
"""Generate a slug from entity_type and id, unless slug is already set."""
if target.slug is None:
target.slug = "{name}{sep}{id}".format(
name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id
) | python | def auto_slug_after_insert(mapper, connection, target):
"""Generate a slug from entity_type and id, unless slug is already set."""
if target.slug is None:
target.slug = "{name}{sep}{id}".format(
name=target.entity_class.lower(), sep=target.SLUG_SEPARATOR, id=target.id
) | [
"def",
"auto_slug_after_insert",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"slug",
"is",
"None",
":",
"target",
".",
"slug",
"=",
"\"{name}{sep}{id}\"",
".",
"format",
"(",
"name",
"=",
"target",
".",
"entity_class",
"... | Generate a slug from entity_type and id, unless slug is already set. | [
"Generate",
"a",
"slug",
"from",
"entity_type",
"and",
"id",
"unless",
"slug",
"is",
"already",
"set",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L79-L84 | train | 43,013 |
abilian/abilian-core | abilian/core/entities.py | setup_default_permissions | def setup_default_permissions(session, instance):
"""Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`.
"""
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_context. Raw object manipulation
return
_setup_default_permissions(instance) | python | def setup_default_permissions(session, instance):
"""Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`.
"""
if instance not in session.new or not isinstance(instance, Entity):
return
if not current_app:
# working outside app_context. Raw object manipulation
return
_setup_default_permissions(instance) | [
"def",
"setup_default_permissions",
"(",
"session",
",",
"instance",
")",
":",
"if",
"instance",
"not",
"in",
"session",
".",
"new",
"or",
"not",
"isinstance",
"(",
"instance",
",",
"Entity",
")",
":",
"return",
"if",
"not",
"current_app",
":",
"# working ou... | Setup default permissions on newly created entities according to.
:attr:`Entity.__default_permissions__`. | [
"Setup",
"default",
"permissions",
"on",
"newly",
"created",
"entities",
"according",
"to",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L88-L100 | train | 43,014 |
abilian/abilian-core | abilian/core/entities.py | _setup_default_permissions | def _setup_default_permissions(instance):
"""Separate method to conveniently call it from scripts for example."""
from abilian.services import get_service
security = get_service("security")
for permission, roles in instance.__default_permissions__:
if permission == "create":
# use str for comparison instead of `abilian.services.security.CREATE`
# symbol to avoid imports that quickly become circular.
#
# FIXME: put roles and permissions in a separate, isolated module.
continue
for role in roles:
security.add_permission(permission, role, obj=instance) | python | def _setup_default_permissions(instance):
"""Separate method to conveniently call it from scripts for example."""
from abilian.services import get_service
security = get_service("security")
for permission, roles in instance.__default_permissions__:
if permission == "create":
# use str for comparison instead of `abilian.services.security.CREATE`
# symbol to avoid imports that quickly become circular.
#
# FIXME: put roles and permissions in a separate, isolated module.
continue
for role in roles:
security.add_permission(permission, role, obj=instance) | [
"def",
"_setup_default_permissions",
"(",
"instance",
")",
":",
"from",
"abilian",
".",
"services",
"import",
"get_service",
"security",
"=",
"get_service",
"(",
"\"security\"",
")",
"for",
"permission",
",",
"roles",
"in",
"instance",
".",
"__default_permissions__"... | Separate method to conveniently call it from scripts for example. | [
"Separate",
"method",
"to",
"conveniently",
"call",
"it",
"from",
"scripts",
"for",
"example",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L103-L116 | train | 43,015 |
abilian/abilian-core | abilian/core/entities.py | polymorphic_update_timestamp | def polymorphic_update_timestamp(session, flush_context, instances):
"""This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted.
"""
for obj in session.dirty:
if not isinstance(obj, Entity):
continue
state = sa.inspect(obj)
history = state.attrs["updated_at"].history
if not any((history.added, history.deleted)):
obj.updated_at = datetime.utcnow() | python | def polymorphic_update_timestamp(session, flush_context, instances):
"""This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted.
"""
for obj in session.dirty:
if not isinstance(obj, Entity):
continue
state = sa.inspect(obj)
history = state.attrs["updated_at"].history
if not any((history.added, history.deleted)):
obj.updated_at = datetime.utcnow() | [
"def",
"polymorphic_update_timestamp",
"(",
"session",
",",
"flush_context",
",",
"instances",
")",
":",
"for",
"obj",
"in",
"session",
".",
"dirty",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Entity",
")",
":",
"continue",
"state",
"=",
"sa",
".",
... | This listener ensures an update statement is emited for "entity" table
to update 'updated_at'.
With joined-table inheritance if the only modified attributes are
subclass's ones, then no update statement will be emitted. | [
"This",
"listener",
"ensures",
"an",
"update",
"statement",
"is",
"emited",
"for",
"entity",
"table",
"to",
"update",
"updated_at",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L486-L499 | train | 43,016 |
abilian/abilian-core | abilian/core/entities.py | all_entity_classes | def all_entity_classes():
"""Return the list of all concrete persistent classes that are subclasses
of Entity."""
persistent_classes = Entity._decl_class_registry.values()
# with sqlalchemy 0.8 _decl_class_registry holds object that are not
# classes
return [
cls for cls in persistent_classes if isclass(cls) and issubclass(cls, Entity)
] | python | def all_entity_classes():
"""Return the list of all concrete persistent classes that are subclasses
of Entity."""
persistent_classes = Entity._decl_class_registry.values()
# with sqlalchemy 0.8 _decl_class_registry holds object that are not
# classes
return [
cls for cls in persistent_classes if isclass(cls) and issubclass(cls, Entity)
] | [
"def",
"all_entity_classes",
"(",
")",
":",
"persistent_classes",
"=",
"Entity",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
"# with sqlalchemy 0.8 _decl_class_registry holds object that are not",
"# classes",
"return",
"[",
"cls",
"for",
"cls",
"in",
"persisten... | Return the list of all concrete persistent classes that are subclasses
of Entity. | [
"Return",
"the",
"list",
"of",
"all",
"concrete",
"persistent",
"classes",
"that",
"are",
"subclasses",
"of",
"Entity",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L503-L511 | train | 43,017 |
abilian/abilian-core | abilian/core/entities.py | Entity.auto_slug | def auto_slug(self):
"""This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses.
"""
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.object_session(self)
if not session:
return None
query = session.query(Entity.slug).filter(
Entity._entity_type == self.object_type
)
if self.id is not None:
query = query.filter(Entity.id != self.id)
slug_re = re.compile(re.escape(slug) + r"-?(-\d+)?")
results = [
int(m.group(1) or 0) # 0: for the unnumbered slug
for m in (slug_re.match(s.slug) for s in query.all() if s.slug)
if m
]
max_id = max(-1, -1, *results) + 1
if max_id:
slug = f"{slug}-{max_id}"
return slug | python | def auto_slug(self):
"""This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses.
"""
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.object_session(self)
if not session:
return None
query = session.query(Entity.slug).filter(
Entity._entity_type == self.object_type
)
if self.id is not None:
query = query.filter(Entity.id != self.id)
slug_re = re.compile(re.escape(slug) + r"-?(-\d+)?")
results = [
int(m.group(1) or 0) # 0: for the unnumbered slug
for m in (slug_re.match(s.slug) for s in query.all() if s.slug)
if m
]
max_id = max(-1, -1, *results) + 1
if max_id:
slug = f"{slug}-{max_id}"
return slug | [
"def",
"auto_slug",
"(",
"self",
")",
":",
"slug",
"=",
"self",
".",
"name",
"if",
"slug",
"is",
"not",
"None",
":",
"slug",
"=",
"slugify",
"(",
"slug",
",",
"separator",
"=",
"self",
".",
"SLUG_SEPARATOR",
")",
"session",
"=",
"sa",
".",
"orm",
"... | This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses. | [
"This",
"property",
"is",
"used",
"to",
"auto",
"-",
"generate",
"a",
"slug",
"from",
"the",
"name",
"attribute",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L355-L382 | train | 43,018 |
abilian/abilian-core | abilian/core/entities.py | Entity._indexable_tags | def _indexable_tags(self):
"""Index tag ids for tags defined in this Entity's default tags
namespace."""
tags = current_app.extensions.get("tags")
if not tags or not tags.supports_taggings(self):
return ""
default_ns = tags.entity_default_ns(self)
return [t for t in tags.entity_tags(self) if t.ns == default_ns] | python | def _indexable_tags(self):
"""Index tag ids for tags defined in this Entity's default tags
namespace."""
tags = current_app.extensions.get("tags")
if not tags or not tags.supports_taggings(self):
return ""
default_ns = tags.entity_default_ns(self)
return [t for t in tags.entity_tags(self) if t.ns == default_ns] | [
"def",
"_indexable_tags",
"(",
"self",
")",
":",
"tags",
"=",
"current_app",
".",
"extensions",
".",
"get",
"(",
"\"tags\"",
")",
"if",
"not",
"tags",
"or",
"not",
"tags",
".",
"supports_taggings",
"(",
"self",
")",
":",
"return",
"\"\"",
"default_ns",
"... | Index tag ids for tags defined in this Entity's default tags
namespace. | [
"Index",
"tag",
"ids",
"for",
"tags",
"defined",
"in",
"this",
"Entity",
"s",
"default",
"tags",
"namespace",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/entities.py#L426-L434 | train | 43,019 |
abilian/abilian-core | abilian/i18n.py | supported_app_locales | def supported_app_locales():
"""Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale.
"""
locale = _get_locale()
codes = current_app.config["BABEL_ACCEPT_LANGUAGES"]
return ((Locale.parse(code), locale.languages.get(code, code)) for code in codes) | python | def supported_app_locales():
"""Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale.
"""
locale = _get_locale()
codes = current_app.config["BABEL_ACCEPT_LANGUAGES"]
return ((Locale.parse(code), locale.languages.get(code, code)) for code in codes) | [
"def",
"supported_app_locales",
"(",
")",
":",
"locale",
"=",
"_get_locale",
"(",
")",
"codes",
"=",
"current_app",
".",
"config",
"[",
"\"BABEL_ACCEPT_LANGUAGES\"",
"]",
"return",
"(",
"(",
"Locale",
".",
"parse",
"(",
"code",
")",
",",
"locale",
".",
"la... | Language codes and labels supported by current application.
:return: an iterable of `(:class:`babel.Locale`, label)`, label being the
locale language human name in current locale. | [
"Language",
"codes",
"and",
"labels",
"supported",
"by",
"current",
"application",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L150-L158 | train | 43,020 |
abilian/abilian-core | abilian/i18n.py | timezones_choices | def timezones_choices():
"""Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale.
"""
utcnow = pytz.utc.localize(datetime.utcnow())
locale = _get_locale()
for tz in sorted(pytz.common_timezones):
tz = get_timezone(tz)
now = tz.normalize(utcnow.astimezone(tz))
label = "({}) {}".format(get_timezone_gmt(now, locale=locale), tz.zone)
yield (tz, label) | python | def timezones_choices():
"""Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale.
"""
utcnow = pytz.utc.localize(datetime.utcnow())
locale = _get_locale()
for tz in sorted(pytz.common_timezones):
tz = get_timezone(tz)
now = tz.normalize(utcnow.astimezone(tz))
label = "({}) {}".format(get_timezone_gmt(now, locale=locale), tz.zone)
yield (tz, label) | [
"def",
"timezones_choices",
"(",
")",
":",
"utcnow",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
"locale",
"=",
"_get_locale",
"(",
")",
"for",
"tz",
"in",
"sorted",
"(",
"pytz",
".",
"common_timezones",
")"... | Timezones values and their labels for current locale.
:return: an iterable of `(code, label)`, code being a timezone code and label
the timezone name in current locale. | [
"Timezones",
"values",
"and",
"their",
"labels",
"for",
"current",
"locale",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L161-L173 | train | 43,021 |
abilian/abilian-core | abilian/i18n.py | _get_translations_multi_paths | def _get_translations_multi_paths():
"""Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found.
"""
ctx = _request_ctx_stack.top
if ctx is None:
return None
translations = getattr(ctx, "babel_translations", None)
if translations is None:
babel_ext = ctx.app.extensions["babel"]
translations = None
trs = None
# reverse order: thus the application catalog is loaded last, so that
# translations from libraries can be overriden
for (dirname, domain) in reversed(babel_ext._translations_paths):
trs = Translations.load(
dirname, locales=[flask_babel.get_locale()], domain=domain
)
# babel.support.Translations is a subclass of
# babel.support.NullTranslations, so we test if object has a 'merge'
# method
if not trs or not hasattr(trs, "merge"):
# got None or NullTranslations instance
continue
elif translations is not None and hasattr(translations, "merge"):
translations.merge(trs)
else:
translations = trs
# ensure translations is at least a NullTranslations object
if translations is None:
translations = trs
ctx.babel_translations = translations
return translations | python | def _get_translations_multi_paths():
"""Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found.
"""
ctx = _request_ctx_stack.top
if ctx is None:
return None
translations = getattr(ctx, "babel_translations", None)
if translations is None:
babel_ext = ctx.app.extensions["babel"]
translations = None
trs = None
# reverse order: thus the application catalog is loaded last, so that
# translations from libraries can be overriden
for (dirname, domain) in reversed(babel_ext._translations_paths):
trs = Translations.load(
dirname, locales=[flask_babel.get_locale()], domain=domain
)
# babel.support.Translations is a subclass of
# babel.support.NullTranslations, so we test if object has a 'merge'
# method
if not trs or not hasattr(trs, "merge"):
# got None or NullTranslations instance
continue
elif translations is not None and hasattr(translations, "merge"):
translations.merge(trs)
else:
translations = trs
# ensure translations is at least a NullTranslations object
if translations is None:
translations = trs
ctx.babel_translations = translations
return translations | [
"def",
"_get_translations_multi_paths",
"(",
")",
":",
"ctx",
"=",
"_request_ctx_stack",
".",
"top",
"if",
"ctx",
"is",
"None",
":",
"return",
"None",
"translations",
"=",
"getattr",
"(",
"ctx",
",",
"\"babel_translations\"",
",",
"None",
")",
"if",
"translati... | Return the correct gettext translations that should be used for this
request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found. | [
"Return",
"the",
"correct",
"gettext",
"translations",
"that",
"should",
"be",
"used",
"for",
"this",
"request",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L250-L292 | train | 43,022 |
abilian/abilian-core | abilian/i18n.py | localeselector | def localeselector():
"""Default locale selector used in abilian applications."""
# if a user is logged in, use the locale from the user settings
user = getattr(g, "user", None)
if user is not None:
locale = getattr(user, "locale", None)
if locale:
return locale
# Otherwise, try to guess the language from the user accept header the browser
# transmits. By default we support en/fr. The best match wins.
return request.accept_languages.best_match(
current_app.config["BABEL_ACCEPT_LANGUAGES"]
) | python | def localeselector():
"""Default locale selector used in abilian applications."""
# if a user is logged in, use the locale from the user settings
user = getattr(g, "user", None)
if user is not None:
locale = getattr(user, "locale", None)
if locale:
return locale
# Otherwise, try to guess the language from the user accept header the browser
# transmits. By default we support en/fr. The best match wins.
return request.accept_languages.best_match(
current_app.config["BABEL_ACCEPT_LANGUAGES"]
) | [
"def",
"localeselector",
"(",
")",
":",
"# if a user is logged in, use the locale from the user settings",
"user",
"=",
"getattr",
"(",
"g",
",",
"\"user\"",
",",
"None",
")",
"if",
"user",
"is",
"not",
"None",
":",
"locale",
"=",
"getattr",
"(",
"user",
",",
... | Default locale selector used in abilian applications. | [
"Default",
"locale",
"selector",
"used",
"in",
"abilian",
"applications",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L302-L315 | train | 43,023 |
abilian/abilian-core | abilian/i18n.py | get_template_i18n | def get_template_i18n(template_name, locale):
"""Build template list with preceding locale if found."""
if locale is None:
return [template_name]
template_list = []
parts = template_name.rsplit(".", 1)
root = parts[0]
suffix = parts[1]
if locale.territory is not None:
locale_string = "_".join([locale.language, locale.territory])
localized_template_path = ".".join([root, locale_string, suffix])
template_list.append(localized_template_path)
localized_template_path = ".".join([root, locale.language, suffix])
template_list.append(localized_template_path)
# append the default
template_list.append(template_name)
return template_list | python | def get_template_i18n(template_name, locale):
"""Build template list with preceding locale if found."""
if locale is None:
return [template_name]
template_list = []
parts = template_name.rsplit(".", 1)
root = parts[0]
suffix = parts[1]
if locale.territory is not None:
locale_string = "_".join([locale.language, locale.territory])
localized_template_path = ".".join([root, locale_string, suffix])
template_list.append(localized_template_path)
localized_template_path = ".".join([root, locale.language, suffix])
template_list.append(localized_template_path)
# append the default
template_list.append(template_name)
return template_list | [
"def",
"get_template_i18n",
"(",
"template_name",
",",
"locale",
")",
":",
"if",
"locale",
"is",
"None",
":",
"return",
"[",
"template_name",
"]",
"template_list",
"=",
"[",
"]",
"parts",
"=",
"template_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
... | Build template list with preceding locale if found. | [
"Build",
"template",
"list",
"with",
"preceding",
"locale",
"if",
"found",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L323-L343 | train | 43,024 |
abilian/abilian-core | abilian/i18n.py | render_template_i18n | def render_template_i18n(template_name_or_list, **context):
"""Try to build an ordered list of template to satisfy the current
locale."""
template_list = []
# Use locale if present in **context
if "locale" in context:
locale = Locale.parse(context["locale"])
else:
# Use get_locale() or default_locale
locale = flask_babel.get_locale()
if isinstance(template_name_or_list, str):
template_list = get_template_i18n(template_name_or_list, locale)
else:
# Search for locale for each member of the list, do not bypass
for template in template_name_or_list:
template_list.extend(get_template_i18n(template, locale))
with ensure_request_context(), force_locale(locale):
return render_template(template_list, **context) | python | def render_template_i18n(template_name_or_list, **context):
"""Try to build an ordered list of template to satisfy the current
locale."""
template_list = []
# Use locale if present in **context
if "locale" in context:
locale = Locale.parse(context["locale"])
else:
# Use get_locale() or default_locale
locale = flask_babel.get_locale()
if isinstance(template_name_or_list, str):
template_list = get_template_i18n(template_name_or_list, locale)
else:
# Search for locale for each member of the list, do not bypass
for template in template_name_or_list:
template_list.extend(get_template_i18n(template, locale))
with ensure_request_context(), force_locale(locale):
return render_template(template_list, **context) | [
"def",
"render_template_i18n",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"template_list",
"=",
"[",
"]",
"# Use locale if present in **context",
"if",
"\"locale\"",
"in",
"context",
":",
"locale",
"=",
"Locale",
".",
"parse",
"(",
"context"... | Try to build an ordered list of template to satisfy the current
locale. | [
"Try",
"to",
"build",
"an",
"ordered",
"list",
"of",
"template",
"to",
"satisfy",
"the",
"current",
"locale",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L364-L383 | train | 43,025 |
abilian/abilian-core | abilian/i18n.py | Babel.add_translations | def add_translations(
self, module_name, translations_dir="translations", domain="messages"
):
"""Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module.
"""
module = importlib.import_module(module_name)
for path in (Path(p, translations_dir) for p in module.__path__):
if not (path.exists() and path.is_dir()):
continue
if not os.access(str(path), os.R_OK):
self.app.logger.warning(
"Babel translations: read access not allowed {}, skipping."
"".format(repr(str(path).encode("utf-8")))
)
continue
self._translations_paths.append((str(path), domain)) | python | def add_translations(
self, module_name, translations_dir="translations", domain="messages"
):
"""Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module.
"""
module = importlib.import_module(module_name)
for path in (Path(p, translations_dir) for p in module.__path__):
if not (path.exists() and path.is_dir()):
continue
if not os.access(str(path), os.R_OK):
self.app.logger.warning(
"Babel translations: read access not allowed {}, skipping."
"".format(repr(str(path).encode("utf-8")))
)
continue
self._translations_paths.append((str(path), domain)) | [
"def",
"add_translations",
"(",
"self",
",",
"module_name",
",",
"translations_dir",
"=",
"\"translations\"",
",",
"domain",
"=",
"\"messages\"",
")",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"for",
"path",
"in",
"(",
"Pa... | Add translations from external module.
For example::
babel.add_translations('abilian.core')
Will add translations files from `abilian.core` module. | [
"Add",
"translations",
"from",
"external",
"module",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/i18n.py#L190-L213 | train | 43,026 |
abilian/abilian-core | abilian/core/sqlalchemy.py | ping_connection | def ping_connection(dbapi_connection, connection_record, connection_proxy):
"""Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections.
"""
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except Exception:
# optional - dispose the whole pool
# instead of invalidating one at a time
# connection_proxy._pool.dispose()
# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise sa.exc.DisconnectionError()
cursor.close() | python | def ping_connection(dbapi_connection, connection_record, connection_proxy):
"""Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections.
"""
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except Exception:
# optional - dispose the whole pool
# instead of invalidating one at a time
# connection_proxy._pool.dispose()
# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise sa.exc.DisconnectionError()
cursor.close() | [
"def",
"ping_connection",
"(",
"dbapi_connection",
",",
"connection_record",
",",
"connection_proxy",
")",
":",
"cursor",
"=",
"dbapi_connection",
".",
"cursor",
"(",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT 1\"",
")",
"except",
"Exception",
":"... | Ensure connections are valid.
From: `http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html`
In case db has been restarted pool may return invalid connections. | [
"Ensure",
"connections",
"are",
"valid",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L27-L45 | train | 43,027 |
abilian/abilian-core | abilian/core/sqlalchemy.py | filter_cols | def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
filtered_columns
)
) | python | def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
filtered_columns
)
) | [
"def",
"filter_cols",
"(",
"model",
",",
"*",
"filtered_columns",
")",
":",
"m",
"=",
"sa",
".",
"orm",
".",
"class_mapper",
"(",
"model",
")",
"return",
"list",
"(",
"{",
"p",
".",
"key",
"for",
"p",
"in",
"m",
".",
"iterate_properties",
"if",
"hasa... | Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest | [
"Return",
"columnsnames",
"for",
"a",
"model",
"except",
"named",
"ones",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L114-L124 | train | 43,028 |
abilian/abilian-core | abilian/core/sqlalchemy.py | JSONList | def JSONList(*args, **kwargs):
"""Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted.
"""
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueListType
except KeyError:
pass
return MutationList.as_mutable(type_(*args, **kwargs)) | python | def JSONList(*args, **kwargs):
"""Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted.
"""
type_ = JSON
try:
if kwargs.pop("unique_sorted"):
type_ = JSONUniqueListType
except KeyError:
pass
return MutationList.as_mutable(type_(*args, **kwargs)) | [
"def",
"JSONList",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"type_",
"=",
"JSON",
"try",
":",
"if",
"kwargs",
".",
"pop",
"(",
"\"unique_sorted\"",
")",
":",
"type_",
"=",
"JSONUniqueListType",
"except",
"KeyError",
":",
"pass",
"return",
"... | Stores a list as JSON on database, with mutability support.
If kwargs has a param `unique_sorted` (which evaluated to True),
list values are made unique and sorted. | [
"Stores",
"a",
"list",
"as",
"JSON",
"on",
"database",
"with",
"mutability",
"support",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L302-L315 | train | 43,029 |
abilian/abilian-core | abilian/core/sqlalchemy.py | MutationDict.coerce | def coerce(cls, key, value):
"""Convert plain dictionaries to MutationDict."""
if not isinstance(value, MutationDict):
if isinstance(value, dict):
return MutationDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | python | def coerce(cls, key, value):
"""Convert plain dictionaries to MutationDict."""
if not isinstance(value, MutationDict):
if isinstance(value, dict):
return MutationDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"MutationDict",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"MutationDict",
"(",
"value",
")",
"# this call ... | Convert plain dictionaries to MutationDict. | [
"Convert",
"plain",
"dictionaries",
"to",
"MutationDict",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L131-L140 | train | 43,030 |
abilian/abilian-core | abilian/core/sqlalchemy.py | MutationList.coerce | def coerce(cls, key, value):
"""Convert list to MutationList."""
if not isinstance(value, MutationList):
if isinstance(value, list):
return MutationList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | python | def coerce(cls, key, value):
"""Convert list to MutationList."""
if not isinstance(value, MutationList):
if isinstance(value, list):
return MutationList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"MutationList",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"MutationList",
"(",
"value",
")",
"# this call ... | Convert list to MutationList. | [
"Convert",
"list",
"to",
"MutationList",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/sqlalchemy.py#L187-L196 | train | 43,031 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.add_file | def add_file(self, user, file_obj, **metadata):
"""Add a new file.
:returns: file handle
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
user_dir.mkdir(mode=0o775)
handle = str(uuid1())
file_path = user_dir / handle
with file_path.open("wb") as out:
for chunk in iter(lambda: file_obj.read(CHUNK_SIZE), b""):
out.write(chunk)
if metadata:
meta_file = user_dir / f"{handle}.metadata"
with meta_file.open("wb") as out:
metadata_json = json.dumps(metadata, skipkeys=True).encode("ascii")
out.write(metadata_json)
return handle | python | def add_file(self, user, file_obj, **metadata):
"""Add a new file.
:returns: file handle
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
user_dir.mkdir(mode=0o775)
handle = str(uuid1())
file_path = user_dir / handle
with file_path.open("wb") as out:
for chunk in iter(lambda: file_obj.read(CHUNK_SIZE), b""):
out.write(chunk)
if metadata:
meta_file = user_dir / f"{handle}.metadata"
with meta_file.open("wb") as out:
metadata_json = json.dumps(metadata, skipkeys=True).encode("ascii")
out.write(metadata_json)
return handle | [
"def",
"add_file",
"(",
"self",
",",
"user",
",",
"file_obj",
",",
"*",
"*",
"metadata",
")",
":",
"user_dir",
"=",
"self",
".",
"user_dir",
"(",
"user",
")",
"if",
"not",
"user_dir",
".",
"exists",
"(",
")",
":",
"user_dir",
".",
"mkdir",
"(",
"mo... | Add a new file.
:returns: file handle | [
"Add",
"a",
"new",
"file",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L86-L108 | train | 43,032 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.get_file | def get_file(self, user, handle):
"""Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle.
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if not is_valid_handle(handle):
return None
file_path = user_dir / handle
if not file_path.exists() and not file_path.is_file():
return None
return file_path | python | def get_file(self, user, handle):
"""Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle.
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if not is_valid_handle(handle):
return None
file_path = user_dir / handle
if not file_path.exists() and not file_path.is_file():
return None
return file_path | [
"def",
"get_file",
"(",
"self",
",",
"user",
",",
"handle",
")",
":",
"user_dir",
"=",
"self",
".",
"user_dir",
"(",
"user",
")",
"if",
"not",
"user_dir",
".",
"exists",
"(",
")",
":",
"return",
"None",
"if",
"not",
"is_valid_handle",
"(",
"handle",
... | Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle. | [
"Retrieve",
"a",
"file",
"for",
"a",
"user",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L110-L128 | train | 43,033 |
abilian/abilian-core | abilian/web/uploads/extension.py | FileUploadsExtension.clear_stalled_files | def clear_stalled_files(self):
"""Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago.
"""
# FIXME: put lock in directory?
CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"]
minimum_age = time.time() - CLEAR_AFTER
for user_dir in self.UPLOAD_DIR.iterdir():
if not user_dir.is_dir():
logger.error("Found non-directory in upload dir: %r", bytes(user_dir))
continue
for content in user_dir.iterdir():
if not content.is_file():
logger.error(
"Found non-file in user upload dir: %r", bytes(content)
)
continue
if content.stat().st_ctime < minimum_age:
content.unlink() | python | def clear_stalled_files(self):
"""Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago.
"""
# FIXME: put lock in directory?
CLEAR_AFTER = self.config["DELETE_STALLED_AFTER"]
minimum_age = time.time() - CLEAR_AFTER
for user_dir in self.UPLOAD_DIR.iterdir():
if not user_dir.is_dir():
logger.error("Found non-directory in upload dir: %r", bytes(user_dir))
continue
for content in user_dir.iterdir():
if not content.is_file():
logger.error(
"Found non-file in user upload dir: %r", bytes(content)
)
continue
if content.stat().st_ctime < minimum_age:
content.unlink() | [
"def",
"clear_stalled_files",
"(",
"self",
")",
":",
"# FIXME: put lock in directory?",
"CLEAR_AFTER",
"=",
"self",
".",
"config",
"[",
"\"DELETE_STALLED_AFTER\"",
"]",
"minimum_age",
"=",
"time",
".",
"time",
"(",
")",
"-",
"CLEAR_AFTER",
"for",
"user_dir",
"in",... | Scan upload directory and delete stalled files.
Stalled files are files uploaded more than
`DELETE_STALLED_AFTER` seconds ago. | [
"Scan",
"upload",
"directory",
"and",
"delete",
"stalled",
"files",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/uploads/extension.py#L164-L187 | train | 43,034 |
abilian/abilian-core | abilian/core/util.py | friendly_fqcn | def friendly_fqcn(cls_name):
"""Friendly name of fully qualified class name.
:param cls_name: a string or a class
"""
if isinstance(cls_name, type):
cls_name = fqcn(cls_name)
return cls_name.rsplit(".", 1)[-1] | python | def friendly_fqcn(cls_name):
"""Friendly name of fully qualified class name.
:param cls_name: a string or a class
"""
if isinstance(cls_name, type):
cls_name = fqcn(cls_name)
return cls_name.rsplit(".", 1)[-1] | [
"def",
"friendly_fqcn",
"(",
"cls_name",
")",
":",
"if",
"isinstance",
"(",
"cls_name",
",",
"type",
")",
":",
"cls_name",
"=",
"fqcn",
"(",
"cls_name",
")",
"return",
"cls_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"-",
"1",
"]"
] | Friendly name of fully qualified class name.
:param cls_name: a string or a class | [
"Friendly",
"name",
"of",
"fully",
"qualified",
"class",
"name",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L37-L45 | train | 43,035 |
abilian/abilian-core | abilian/core/util.py | local_dt | def local_dt(dt):
"""Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ.
"""
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | python | def local_dt(dt):
"""Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ.
"""
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return LOCALTZ.normalize(dt.astimezone(LOCALTZ)) | [
"def",
"local_dt",
"(",
"dt",
")",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"dt",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"dt",
")",
"return",
"LOCALTZ",
".",
"normalize",
"(",
"dt",
".",
"astimezone",
"(",
"LOCALTZ",
")",
")"
] | Return an aware datetime in system timezone, from a naive or aware
datetime.
Naive datetime are assumed to be in UTC TZ. | [
"Return",
"an",
"aware",
"datetime",
"in",
"system",
"timezone",
"from",
"a",
"naive",
"or",
"aware",
"datetime",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L53-L61 | train | 43,036 |
abilian/abilian-core | abilian/core/util.py | utc_dt | def utc_dt(dt):
"""Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ.
"""
if not dt.tzinfo:
return pytz.utc.localize(dt)
return dt.astimezone(pytz.utc) | python | def utc_dt(dt):
"""Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ.
"""
if not dt.tzinfo:
return pytz.utc.localize(dt)
return dt.astimezone(pytz.utc) | [
"def",
"utc_dt",
"(",
"dt",
")",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"return",
"pytz",
".",
"utc",
".",
"localize",
"(",
"dt",
")",
"return",
"dt",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")"
] | Set UTC timezone on a datetime object.
A naive datetime is assumed to be in UTC TZ. | [
"Set",
"UTC",
"timezone",
"on",
"a",
"datetime",
"object",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L64-L71 | train | 43,037 |
abilian/abilian-core | abilian/core/util.py | get_params | def get_params(names):
"""Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt.
"""
params = {}
for name in names:
value = request.form.get(name) or request.files.get(name)
if value is not None:
params[name] = value
return params | python | def get_params(names):
"""Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt.
"""
params = {}
for name in names:
value = request.form.get(name) or request.files.get(name)
if value is not None:
params[name] = value
return params | [
"def",
"get_params",
"(",
"names",
")",
":",
"params",
"=",
"{",
"}",
"for",
"name",
"in",
"names",
":",
"value",
"=",
"request",
".",
"form",
".",
"get",
"(",
"name",
")",
"or",
"request",
".",
"files",
".",
"get",
"(",
"name",
")",
"if",
"value... | Return a dictionary with params from request.
TODO: I think we don't use it anymore and it should be removed
before someone gets hurt. | [
"Return",
"a",
"dictionary",
"with",
"params",
"from",
"request",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L74-L85 | train | 43,038 |
abilian/abilian-core | abilian/core/util.py | slugify | def slugify(value, separator="-"):
"""Slugify an Unicode string, to make it URL friendly."""
if not isinstance(value, str):
raise ValueError("value must be a Unicode string")
value = _NOT_WORD_RE.sub(" ", value)
value = unicodedata.normalize("NFKD", value)
value = value.encode("ascii", "ignore")
value = value.decode("ascii")
value = value.strip().lower()
value = re.sub(fr"[{separator}_\s]+", separator, value)
return value | python | def slugify(value, separator="-"):
"""Slugify an Unicode string, to make it URL friendly."""
if not isinstance(value, str):
raise ValueError("value must be a Unicode string")
value = _NOT_WORD_RE.sub(" ", value)
value = unicodedata.normalize("NFKD", value)
value = value.encode("ascii", "ignore")
value = value.decode("ascii")
value = value.strip().lower()
value = re.sub(fr"[{separator}_\s]+", separator, value)
return value | [
"def",
"slugify",
"(",
"value",
",",
"separator",
"=",
"\"-\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"value must be a Unicode string\"",
")",
"value",
"=",
"_NOT_WORD_RE",
".",
"sub",
"(",
"... | Slugify an Unicode string, to make it URL friendly. | [
"Slugify",
"an",
"Unicode",
"string",
"to",
"make",
"it",
"URL",
"friendly",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/util.py#L178-L188 | train | 43,039 |
abilian/abilian-core | abilian/web/forms/validators.py | luhn | def luhn(n):
"""Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0 | python | def luhn(n):
"""Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0 | [
"def",
"luhn",
"(",
"n",
")",
":",
"r",
"=",
"[",
"int",
"(",
"ch",
")",
"for",
"ch",
"in",
"str",
"(",
"n",
")",
"]",
"[",
":",
":",
"-",
"1",
"]",
"return",
"(",
"sum",
"(",
"r",
"[",
"0",
":",
":",
"2",
"]",
")",
"+",
"sum",
"(",
... | Validate that a string made of numeric characters verify Luhn test. Used
by siret validator.
from
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python
https://en.wikipedia.org/wiki/Luhn_algorithm | [
"Validate",
"that",
"a",
"string",
"made",
"of",
"numeric",
"characters",
"verify",
"Luhn",
"test",
".",
"Used",
"by",
"siret",
"validator",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/validators.py#L218-L227 | train | 43,040 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.rel_path | def rel_path(self, uuid):
# type: (UUID) -> Path
"""Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance
"""
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename[2:4], filename) | python | def rel_path(self, uuid):
# type: (UUID) -> Path
"""Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance
"""
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename[2:4], filename) | [
"def",
"rel_path",
"(",
"self",
",",
"uuid",
")",
":",
"# type: (UUID) -> Path",
"_assert_uuid",
"(",
"uuid",
")",
"filename",
"=",
"str",
"(",
"uuid",
")",
"return",
"Path",
"(",
"filename",
"[",
"0",
":",
"2",
"]",
",",
"filename",
"[",
"2",
":",
"... | Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance | [
"Contruct",
"relative",
"path",
"from",
"repository",
"top",
"directory",
"to",
"the",
"file",
"named",
"after",
"this",
"uuid",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L48-L57 | train | 43,041 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.set | def set(self, uuid, content, encoding="utf-8"):
# type: (UUID, Any, Optional[Text]) -> None
"""Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode
"""
dest = self.abs_path(uuid)
if not dest.parent.exists():
dest.parent.mkdir(0o775, parents=True)
if hasattr(content, "read"):
content = content.read()
mode = "tw"
if not isinstance(content, str):
mode = "bw"
encoding = None
with dest.open(mode, encoding=encoding) as f:
f.write(content) | python | def set(self, uuid, content, encoding="utf-8"):
# type: (UUID, Any, Optional[Text]) -> None
"""Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode
"""
dest = self.abs_path(uuid)
if not dest.parent.exists():
dest.parent.mkdir(0o775, parents=True)
if hasattr(content, "read"):
content = content.read()
mode = "tw"
if not isinstance(content, str):
mode = "bw"
encoding = None
with dest.open(mode, encoding=encoding) as f:
f.write(content) | [
"def",
"set",
"(",
"self",
",",
"uuid",
",",
"content",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"# type: (UUID, Any, Optional[Text]) -> None",
"dest",
"=",
"self",
".",
"abs_path",
"(",
"uuid",
")",
"if",
"not",
"dest",
".",
"parent",
".",
"exists",
"... | Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode | [
"Store",
"binary",
"content",
"with",
"uuid",
"as",
"key",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L83-L104 | train | 43,042 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryService.delete | def delete(self, uuid):
# type: (UUID) -> None
"""Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists
"""
dest = self.abs_path(uuid)
if not dest.exists():
raise KeyError("No file can be found for this uuid", uuid)
dest.unlink() | python | def delete(self, uuid):
# type: (UUID) -> None
"""Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists
"""
dest = self.abs_path(uuid)
if not dest.exists():
raise KeyError("No file can be found for this uuid", uuid)
dest.unlink() | [
"def",
"delete",
"(",
"self",
",",
"uuid",
")",
":",
"# type: (UUID) -> None",
"dest",
"=",
"self",
".",
"abs_path",
"(",
"uuid",
")",
"if",
"not",
"dest",
".",
"exists",
"(",
")",
":",
"raise",
"KeyError",
"(",
"\"No file can be found for this uuid\"",
",",... | Delete file with given uuid.
:param:uuid: :class:`UUID` instance
:raises:KeyError if file does not exists | [
"Delete",
"file",
"with",
"given",
"uuid",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L106-L117 | train | 43,043 |
abilian/abilian-core | abilian/services/repository/service.py | SessionRepositoryService._session_for | def _session_for(self, model_or_session):
"""Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scoped
session will be used (db.session())
If parameter is a scoped_session instance, a new session will be
instanciated.
"""
session = model_or_session
if not isinstance(session, (Session, sa.orm.scoped_session)):
if session is not None:
session = sa.orm.object_session(model_or_session)
if session is None:
session = db.session
if isinstance(session, sa.orm.scoped_session):
session = session()
return session | python | def _session_for(self, model_or_session):
"""Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scoped
session will be used (db.session())
If parameter is a scoped_session instance, a new session will be
instanciated.
"""
session = model_or_session
if not isinstance(session, (Session, sa.orm.scoped_session)):
if session is not None:
session = sa.orm.object_session(model_or_session)
if session is None:
session = db.session
if isinstance(session, sa.orm.scoped_session):
session = session()
return session | [
"def",
"_session_for",
"(",
"self",
",",
"model_or_session",
")",
":",
"session",
"=",
"model_or_session",
"if",
"not",
"isinstance",
"(",
"session",
",",
"(",
"Session",
",",
"sa",
".",
"orm",
".",
"scoped_session",
")",
")",
":",
"if",
"session",
"is",
... | Return session instance for object parameter.
If parameter is a session instance, it is return as is.
If parameter is a registered model instance, its session will be used.
If parameter is a detached model instance, or None, application scoped
session will be used (db.session())
If parameter is a scoped_session instance, a new session will be
instanciated. | [
"Return",
"session",
"instance",
"for",
"object",
"parameter",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L289-L312 | train | 43,044 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryTransaction.commit | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transaction
self._commit_parent()
else:
self._commit_repository()
self._clear() | python | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transaction
self._commit_parent()
else:
self._commit_repository()
self._clear() | [
"def",
"commit",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"self",
".",
"__cleared",
":",
"return",
"if",
"self",
".",
"_parent",
":",
"# nested transaction",
"self",
".",
"_commit_parent",
"(",
")",
"else",
":",
"self",
".",
"_commit_rep... | Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session | [
"Merge",
"modified",
"objects",
"into",
"parent",
"transaction",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L407-L422 | train | 43,045 |
abilian/abilian-core | abilian/services/repository/service.py | RepositoryTransaction._add_to | def _add_to(self, uuid, dest, other):
"""Add `item` to `dest` set, ensuring `item` is not present in `other`
set."""
_assert_uuid(uuid)
try:
other.remove(uuid)
except KeyError:
pass
dest.add(uuid) | python | def _add_to(self, uuid, dest, other):
"""Add `item` to `dest` set, ensuring `item` is not present in `other`
set."""
_assert_uuid(uuid)
try:
other.remove(uuid)
except KeyError:
pass
dest.add(uuid) | [
"def",
"_add_to",
"(",
"self",
",",
"uuid",
",",
"dest",
",",
"other",
")",
":",
"_assert_uuid",
"(",
"uuid",
")",
"try",
":",
"other",
".",
"remove",
"(",
"uuid",
")",
"except",
"KeyError",
":",
"pass",
"dest",
".",
"add",
"(",
"uuid",
")"
] | Add `item` to `dest` set, ensuring `item` is not present in `other`
set. | [
"Add",
"item",
"to",
"dest",
"set",
"ensuring",
"item",
"is",
"not",
"present",
"in",
"other",
"set",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/repository/service.py#L453-L461 | train | 43,046 |
abilian/abilian-core | abilian/web/tags/extension.py | ns | def ns(ns):
"""Class decorator that sets default tags namespace to use with its
instances."""
def setup_ns(cls):
setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)
return cls
return setup_ns | python | def ns(ns):
"""Class decorator that sets default tags namespace to use with its
instances."""
def setup_ns(cls):
setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns)
return cls
return setup_ns | [
"def",
"ns",
"(",
"ns",
")",
":",
"def",
"setup_ns",
"(",
"cls",
")",
":",
"setattr",
"(",
"cls",
",",
"ENTITY_DEFAULT_NS_ATTR",
",",
"ns",
")",
"return",
"cls",
"return",
"setup_ns"
] | Class decorator that sets default tags namespace to use with its
instances. | [
"Class",
"decorator",
"that",
"sets",
"default",
"tags",
"namespace",
"to",
"use",
"with",
"its",
"instances",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L19-L27 | train | 43,047 |
abilian/abilian-core | abilian/web/tags/extension.py | TagsExtension.entity_tags_form | def entity_tags_form(self, entity, ns=None):
"""Construct a form class with a field for tags in namespace `ns`."""
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
return cls | python | def entity_tags_form(self, entity, ns=None):
"""Construct a form class with a field for tags in namespace `ns`."""
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
return cls | [
"def",
"entity_tags_form",
"(",
"self",
",",
"entity",
",",
"ns",
"=",
"None",
")",
":",
"if",
"ns",
"is",
"None",
":",
"ns",
"=",
"self",
".",
"entity_default_ns",
"(",
"entity",
")",
"field",
"=",
"TagsField",
"(",
"label",
"=",
"_l",
"(",
"\"Tags\... | Construct a form class with a field for tags in namespace `ns`. | [
"Construct",
"a",
"form",
"class",
"with",
"a",
"field",
"for",
"tags",
"in",
"namespace",
"ns",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/extension.py#L90-L97 | train | 43,048 |
abilian/abilian-core | abilian/cli/indexing.py | reindex | def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in single transaction mode. If `None` then
all documents of same content type are written at once.
"""
reindexer = Reindexer(clear, progressive, batch_size)
reindexer.reindex_all() | python | def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in single transaction mode. If `None` then
all documents of same content type are written at once.
"""
reindexer = Reindexer(clear, progressive, batch_size)
reindexer.reindex_all() | [
"def",
"reindex",
"(",
"clear",
":",
"bool",
",",
"progressive",
":",
"bool",
",",
"batch_size",
":",
"int",
")",
":",
"reindexer",
"=",
"Reindexer",
"(",
"clear",
",",
"progressive",
",",
"batch_size",
")",
"reindexer",
".",
"reindex_all",
"(",
")"
] | Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in single transaction mode. If `None` then
all documents of same content type are written at once. | [
"Reindex",
"all",
"content",
";",
"optionally",
"clear",
"index",
"before",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/cli/indexing.py#L30-L42 | train | 43,049 |
abilian/abilian-core | abilian/services/indexing/service.py | url_for_hit | def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
logger.error("Error building URL for search result", exc_info=True)
return default | python | def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
logger.error("Error building URL for search result", exc_info=True)
return default | [
"def",
"url_for_hit",
"(",
"hit",
",",
"default",
"=",
"\"#\"",
")",
":",
"try",
":",
"object_type",
"=",
"hit",
"[",
"\"object_type\"",
"]",
"object_id",
"=",
"int",
"(",
"hit",
"[",
"\"id\"",
"]",
")",
"return",
"current_app",
".",
"default_view",
".",... | Helper for building URLs from results. | [
"Helper",
"for",
"building",
"URLs",
"from",
"results",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L49-L59 | train | 43,050 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.init_indexes | def init_indexes(self):
"""Create indexes for schemas."""
state = self.app_state
for name, schema in self.schemas.items():
if current_app.testing:
storage = TestingStorage()
else:
index_path = (Path(state.whoosh_base) / name).absolute()
if not index_path.exists():
index_path.mkdir(parents=True)
storage = FileStorage(str(index_path))
if storage.index_exists(name):
index = FileIndex(storage, schema, name)
else:
index = FileIndex.create(storage, schema, name)
state.indexes[name] = index | python | def init_indexes(self):
"""Create indexes for schemas."""
state = self.app_state
for name, schema in self.schemas.items():
if current_app.testing:
storage = TestingStorage()
else:
index_path = (Path(state.whoosh_base) / name).absolute()
if not index_path.exists():
index_path.mkdir(parents=True)
storage = FileStorage(str(index_path))
if storage.index_exists(name):
index = FileIndex(storage, schema, name)
else:
index = FileIndex.create(storage, schema, name)
state.indexes[name] = index | [
"def",
"init_indexes",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"app_state",
"for",
"name",
",",
"schema",
"in",
"self",
".",
"schemas",
".",
"items",
"(",
")",
":",
"if",
"current_app",
".",
"testing",
":",
"storage",
"=",
"TestingStorage",
"... | Create indexes for schemas. | [
"Create",
"indexes",
"for",
"schemas",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L161-L179 | train | 43,051 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.clear | def clear(self):
"""Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes.
"""
logger.info("Resetting indexes")
state = self.app_state
for _name, idx in state.indexes.items():
writer = AsyncWriter(idx)
writer.commit(merge=True, optimize=True, mergetype=CLEAR)
state.indexes.clear()
state.indexed_classes.clear()
state.indexed_fqcn.clear()
self.clear_update_queue()
if self.running:
self.stop() | python | def clear(self):
"""Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes.
"""
logger.info("Resetting indexes")
state = self.app_state
for _name, idx in state.indexes.items():
writer = AsyncWriter(idx)
writer.commit(merge=True, optimize=True, mergetype=CLEAR)
state.indexes.clear()
state.indexed_classes.clear()
state.indexed_fqcn.clear()
self.clear_update_queue()
if self.running:
self.stop() | [
"def",
"clear",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Resetting indexes\"",
")",
"state",
"=",
"self",
".",
"app_state",
"for",
"_name",
",",
"idx",
"in",
"state",
".",
"indexes",
".",
"items",
"(",
")",
":",
"writer",
"=",
"AsyncWriter... | Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes. | [
"Remove",
"all",
"content",
"from",
"indexes",
"and",
"unregister",
"all",
"classes",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L181-L200 | train | 43,052 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.register_class | def register_class(self, cls, app_state=None):
"""Register a model class."""
state = app_state if app_state is not None else self.app_state
for Adapter in self.adapters_cls:
if Adapter.can_adapt(cls):
break
else:
return
cls_fqcn = fqcn(cls)
self.adapted[cls_fqcn] = Adapter(cls, self.schemas["default"])
state.indexed_classes.add(cls)
state.indexed_fqcn.add(cls_fqcn) | python | def register_class(self, cls, app_state=None):
"""Register a model class."""
state = app_state if app_state is not None else self.app_state
for Adapter in self.adapters_cls:
if Adapter.can_adapt(cls):
break
else:
return
cls_fqcn = fqcn(cls)
self.adapted[cls_fqcn] = Adapter(cls, self.schemas["default"])
state.indexed_classes.add(cls)
state.indexed_fqcn.add(cls_fqcn) | [
"def",
"register_class",
"(",
"self",
",",
"cls",
",",
"app_state",
"=",
"None",
")",
":",
"state",
"=",
"app_state",
"if",
"app_state",
"is",
"not",
"None",
"else",
"self",
".",
"app_state",
"for",
"Adapter",
"in",
"self",
".",
"adapters_cls",
":",
"if"... | Register a model class. | [
"Register",
"a",
"model",
"class",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L364-L377 | train | 43,053 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.after_commit | def after_commit(self, session):
"""Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
of a model.
"""
if (
not self.running
or session.transaction.nested # inside a sub-transaction:
# not yet written in DB
or session is not db.session()
):
# note: we have not tested too far if session is enclosed in a transaction
# at connection level. For now it's not a standard use case, it would most
# likely happens during tests (which don't do that for now)
return
primary_field = "id"
state = self.app_state
items = []
for op, obj in state.to_update:
model_name = fqcn(obj.__class__)
if model_name not in self.adapted or not self.adapted[model_name].indexable:
# safeguard
continue
# safeguard against DetachedInstanceError
if sa.orm.object_session(obj) is not None:
items.append((op, model_name, getattr(obj, primary_field), {}))
if items:
index_update.apply_async(kwargs={"index": "default", "items": items})
self.clear_update_queue() | python | def after_commit(self, session):
"""Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
of a model.
"""
if (
not self.running
or session.transaction.nested # inside a sub-transaction:
# not yet written in DB
or session is not db.session()
):
# note: we have not tested too far if session is enclosed in a transaction
# at connection level. For now it's not a standard use case, it would most
# likely happens during tests (which don't do that for now)
return
primary_field = "id"
state = self.app_state
items = []
for op, obj in state.to_update:
model_name = fqcn(obj.__class__)
if model_name not in self.adapted or not self.adapted[model_name].indexable:
# safeguard
continue
# safeguard against DetachedInstanceError
if sa.orm.object_session(obj) is not None:
items.append((op, model_name, getattr(obj, primary_field), {}))
if items:
index_update.apply_async(kwargs={"index": "default", "items": items})
self.clear_update_queue() | [
"def",
"after_commit",
"(",
"self",
",",
"session",
")",
":",
"if",
"(",
"not",
"self",
".",
"running",
"or",
"session",
".",
"transaction",
".",
"nested",
"# inside a sub-transaction:",
"# not yet written in DB",
"or",
"session",
"is",
"not",
"db",
".",
"sess... | Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
of a model. | [
"Any",
"db",
"updates",
"go",
"through",
"here",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L399-L434 | train | 43,054 |
abilian/abilian-core | abilian/services/indexing/service.py | WhooshIndexService.index_objects | def index_objects(self, objects, index="default"):
"""Bulk index a list of objects."""
if not objects:
return
index_name = index
index = self.app_state.indexes[index_name]
indexed = set()
with index.writer() as writer:
for obj in objects:
document = self.get_document(obj)
if document is None:
continue
object_key = document["object_key"]
if object_key in indexed:
continue
writer.delete_by_term("object_key", object_key)
try:
writer.add_document(**document)
except ValueError:
# logger is here to give us more infos in order to catch a weird bug
# that happens regularly on CI but is not reliably
# reproductible.
logger.error("writer.add_document(%r)", document, exc_info=True)
raise
indexed.add(object_key) | python | def index_objects(self, objects, index="default"):
"""Bulk index a list of objects."""
if not objects:
return
index_name = index
index = self.app_state.indexes[index_name]
indexed = set()
with index.writer() as writer:
for obj in objects:
document = self.get_document(obj)
if document is None:
continue
object_key = document["object_key"]
if object_key in indexed:
continue
writer.delete_by_term("object_key", object_key)
try:
writer.add_document(**document)
except ValueError:
# logger is here to give us more infos in order to catch a weird bug
# that happens regularly on CI but is not reliably
# reproductible.
logger.error("writer.add_document(%r)", document, exc_info=True)
raise
indexed.add(object_key) | [
"def",
"index_objects",
"(",
"self",
",",
"objects",
",",
"index",
"=",
"\"default\"",
")",
":",
"if",
"not",
"objects",
":",
"return",
"index_name",
"=",
"index",
"index",
"=",
"self",
".",
"app_state",
".",
"indexes",
"[",
"index_name",
"]",
"indexed",
... | Bulk index a list of objects. | [
"Bulk",
"index",
"a",
"list",
"of",
"objects",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/indexing/service.py#L464-L492 | train | 43,055 |
abilian/abilian-core | abilian/web/forms/widgets.py | linkify_url | def linkify_url(value):
"""Tranform an URL pulled from the database to a safe HTML fragment."""
value = value.strip()
rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)
value = re_scripts.sub("", value)
url = value
if not url.startswith("http://") and not url.startswith("https://"):
url = "http://" + url
url = parse.urlsplit(url).geturl()
if '"' in url:
url = url.split('"')[0]
if "<" in url:
url = url.split("<")[0]
if value.startswith("http://"):
value = value[len("http://") :]
elif value.startswith("https://"):
value = value[len("https://") :]
if value.count("/") == 1 and value.endswith("/"):
value = value[0:-1]
return '<a href="{}">{}</a> <i class="fa fa-external-link"></i>'.format(
url, value
) | python | def linkify_url(value):
"""Tranform an URL pulled from the database to a safe HTML fragment."""
value = value.strip()
rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)
value = re_scripts.sub("", value)
url = value
if not url.startswith("http://") and not url.startswith("https://"):
url = "http://" + url
url = parse.urlsplit(url).geturl()
if '"' in url:
url = url.split('"')[0]
if "<" in url:
url = url.split("<")[0]
if value.startswith("http://"):
value = value[len("http://") :]
elif value.startswith("https://"):
value = value[len("https://") :]
if value.count("/") == 1 and value.endswith("/"):
value = value[0:-1]
return '<a href="{}">{}</a> <i class="fa fa-external-link"></i>'.format(
url, value
) | [
"def",
"linkify_url",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"rjs",
"=",
"r\"[\\s]*(&#x.{1,7})?\"",
".",
"join",
"(",
"list",
"(",
"\"javascript:\"",
")",
")",
"rvb",
"=",
"r\"[\\s]*(&#x.{1,7})?\"",
".",
"join",
"(",
"list",... | Tranform an URL pulled from the database to a safe HTML fragment. | [
"Tranform",
"an",
"URL",
"pulled",
"from",
"the",
"database",
"to",
"a",
"safe",
"HTML",
"fragment",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/forms/widgets.py#L81-L112 | train | 43,056 |
abilian/abilian-core | abilian/services/preferences/service.py | PreferenceService.get_preferences | def get_preferences(self, user=None):
"""Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead.
"""
if user is None:
user = current_user
return {pref.key: pref.value for pref in user.preferences} | python | def get_preferences(self, user=None):
"""Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead.
"""
if user is None:
user = current_user
return {pref.key: pref.value for pref in user.preferences} | [
"def",
"get_preferences",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"current_user",
"return",
"{",
"pref",
".",
"key",
":",
"pref",
".",
"value",
"for",
"pref",
"in",
"user",
".",
"preferences",
"}... | Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead. | [
"Return",
"a",
"string",
"-",
">",
"value",
"dictionnary",
"representing",
"the",
"given",
"user",
"preferences",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/preferences/service.py#L63-L71 | train | 43,057 |
abilian/abilian-core | abilian/services/preferences/service.py | PreferenceService.set_preferences | def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
else:
d[k] = UserPreference(user=user, key=k, value=v)
db.session.add(d[k]) | python | def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
else:
d[k] = UserPreference(user=user, key=k, value=v)
db.session.add(d[k]) | [
"def",
"set_preferences",
"(",
"self",
",",
"user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"current_user",
"d",
"=",
"{",
"pref",
".",
"key",
":",
"pref",
"for",
"pref",
"in",
"user",
".",
"p... | Set preferences from keyword arguments. | [
"Set",
"preferences",
"from",
"keyword",
"arguments",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/preferences/service.py#L73-L84 | train | 43,058 |
abilian/abilian-core | abilian/services/auth/service.py | AuthService.do_access_control | def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get(0)
login_user(user, force=True)
return
state = self.app_state
user = unwrap(current_user)
# Another special case for tests
if current_app.testing and getattr(user, "is_admin", False):
return
security = get_service("security")
user_roles = frozenset(security.get_roles(user))
endpoint = request.endpoint
blueprint = request.blueprint
access_controllers = []
access_controllers.extend(state.bp_access_controllers.get(None, []))
if blueprint and blueprint in state.bp_access_controllers:
access_controllers.extend(state.bp_access_controllers[blueprint])
if endpoint and endpoint in state.endpoint_access_controllers:
access_controllers.extend(state.endpoint_access_controllers[endpoint])
for access_controller in reversed(access_controllers):
verdict = access_controller(user=user, roles=user_roles)
if verdict is None:
continue
elif verdict is True:
return
else:
if user.is_anonymous:
return self.redirect_to_login()
raise Forbidden()
# default policy
if current_app.config.get("PRIVATE_SITE") and user.is_anonymous:
return self.redirect_to_login() | python | def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get(0)
login_user(user, force=True)
return
state = self.app_state
user = unwrap(current_user)
# Another special case for tests
if current_app.testing and getattr(user, "is_admin", False):
return
security = get_service("security")
user_roles = frozenset(security.get_roles(user))
endpoint = request.endpoint
blueprint = request.blueprint
access_controllers = []
access_controllers.extend(state.bp_access_controllers.get(None, []))
if blueprint and blueprint in state.bp_access_controllers:
access_controllers.extend(state.bp_access_controllers[blueprint])
if endpoint and endpoint in state.endpoint_access_controllers:
access_controllers.extend(state.endpoint_access_controllers[endpoint])
for access_controller in reversed(access_controllers):
verdict = access_controller(user=user, roles=user_roles)
if verdict is None:
continue
elif verdict is True:
return
else:
if user.is_anonymous:
return self.redirect_to_login()
raise Forbidden()
# default policy
if current_app.config.get("PRIVATE_SITE") and user.is_anonymous:
return self.redirect_to_login() | [
"def",
"do_access_control",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
"import",
"get_service",
"if",
"current_app",
".",
"testing",
"and",
"current_app",
".",
"config",
".",
"get",
"(",
"\"NO_LOGIN\"",
")",
":",
"# Special case for tests",
"user... | `before_request` handler to check if user should be redirected to
login page. | [
"before_request",
"handler",
"to",
"check",
"if",
"user",
"should",
"be",
"redirected",
"to",
"login",
"page",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/service.py#L174-L219 | train | 43,059 |
abilian/abilian-core | abilian/web/tags/admin.py | get_entities_for_reindex | def get_entities_for_reindex(tags):
"""Collect entities for theses tags."""
if isinstance(tags, Tag):
tags = (tags,)
session = db.session()
indexing = get_service("indexing")
tbl = Entity.__table__
tag_ids = [t.id for t in tags]
query = (
sa.sql.select([tbl.c.entity_type, tbl.c.id])
.select_from(tbl.join(entity_tag_tbl, entity_tag_tbl.c.entity_id == tbl.c.id))
.where(entity_tag_tbl.c.tag_id.in_(tag_ids))
)
entities = set()
with session.no_autoflush:
for entity_type, entity_id in session.execute(query):
if entity_type not in indexing.adapted:
logger.debug("%r is not indexed, skipping", entity_type)
item = ("changed", entity_type, entity_id, ())
entities.add(item)
return entities | python | def get_entities_for_reindex(tags):
"""Collect entities for theses tags."""
if isinstance(tags, Tag):
tags = (tags,)
session = db.session()
indexing = get_service("indexing")
tbl = Entity.__table__
tag_ids = [t.id for t in tags]
query = (
sa.sql.select([tbl.c.entity_type, tbl.c.id])
.select_from(tbl.join(entity_tag_tbl, entity_tag_tbl.c.entity_id == tbl.c.id))
.where(entity_tag_tbl.c.tag_id.in_(tag_ids))
)
entities = set()
with session.no_autoflush:
for entity_type, entity_id in session.execute(query):
if entity_type not in indexing.adapted:
logger.debug("%r is not indexed, skipping", entity_type)
item = ("changed", entity_type, entity_id, ())
entities.add(item)
return entities | [
"def",
"get_entities_for_reindex",
"(",
"tags",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"Tag",
")",
":",
"tags",
"=",
"(",
"tags",
",",
")",
"session",
"=",
"db",
".",
"session",
"(",
")",
"indexing",
"=",
"get_service",
"(",
"\"indexing\"",
")... | Collect entities for theses tags. | [
"Collect",
"entities",
"for",
"theses",
"tags",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/tags/admin.py#L29-L54 | train | 43,060 |
noirbizarre/bumpr | bumpr/helpers.py | check_output | def check_output(*args, **kwargs):
'''Compatibility wrapper for Python 2.6 missin g subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
*args, **kwargs)
else:
process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, **kwargs)
output, _ = process.communicate()
retcode = process.poll()
if retcode:
error = subprocess.CalledProcessError(retcode, args[0])
error.output = output
raise error
return output | python | def check_output(*args, **kwargs):
'''Compatibility wrapper for Python 2.6 missin g subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
*args, **kwargs)
else:
process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, **kwargs)
output, _ = process.communicate()
retcode = process.poll()
if retcode:
error = subprocess.CalledProcessError(retcode, args[0])
error.output = output
raise error
return output | [
"def",
"check_output",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"subprocess",
",",
"'check_output'",
")",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_n... | Compatibility wrapper for Python 2.6 missin g subprocess.check_output | [
"Compatibility",
"wrapper",
"for",
"Python",
"2",
".",
"6",
"missin",
"g",
"subprocess",
".",
"check_output"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/helpers.py#L13-L27 | train | 43,061 |
abilian/abilian-core | abilian/web/views/object.py | ObjectEdit.form_valid | def form_valid(self, redirect_to=None):
"""Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default.
"""
session = db.session()
with session.no_autoflush:
self.before_populate_obj()
self.form.populate_obj(self.obj)
session.add(self.obj)
self.after_populate_obj()
try:
session.flush()
self.send_activity()
session.commit()
except ValidationError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
flash(str(e), "error")
return self.get()
except sa.exc.IntegrityError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
logger.error(e)
flash(_("An entity with this name already exists in the system."), "error")
return self.get()
else:
self.commit_success()
flash(self.message_success(), "success")
if redirect_to:
return redirect(redirect_to)
else:
return self.redirect_to_view() | python | def form_valid(self, redirect_to=None):
"""Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default.
"""
session = db.session()
with session.no_autoflush:
self.before_populate_obj()
self.form.populate_obj(self.obj)
session.add(self.obj)
self.after_populate_obj()
try:
session.flush()
self.send_activity()
session.commit()
except ValidationError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
flash(str(e), "error")
return self.get()
except sa.exc.IntegrityError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
logger.error(e)
flash(_("An entity with this name already exists in the system."), "error")
return self.get()
else:
self.commit_success()
flash(self.message_success(), "success")
if redirect_to:
return redirect(redirect_to)
else:
return self.redirect_to_view() | [
"def",
"form_valid",
"(",
"self",
",",
"redirect_to",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"session",
"(",
")",
"with",
"session",
".",
"no_autoflush",
":",
"self",
".",
"before_populate_obj",
"(",
")",
"self",
".",
"form",
".",
"populate_ob... | Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default. | [
"Save",
"object",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L345-L390 | train | 43,062 |
abilian/abilian-core | abilian/web/views/object.py | JSONModelSearch.get_item | def get_item(self, obj):
"""Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values
"""
return {"id": obj.id, "text": self.get_label(obj), "name": obj.name} | python | def get_item(self, obj):
"""Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values
"""
return {"id": obj.id, "text": self.get_label(obj), "name": obj.name} | [
"def",
"get_item",
"(",
"self",
",",
"obj",
")",
":",
"return",
"{",
"\"id\"",
":",
"obj",
".",
"id",
",",
"\"text\"",
":",
"self",
".",
"get_label",
"(",
"obj",
")",
",",
"\"name\"",
":",
"obj",
".",
"name",
"}"
] | Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values | [
"Return",
"a",
"result",
"item",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/object.py#L625-L631 | train | 43,063 |
noirbizarre/bumpr | setup.py | pip | def pip(name):
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | python | def pip(name):
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | [
"def",
"pip",
"(",
"name",
")",
":",
"with",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'requirements'",
",",
"'{0}.pip'",
".",
"format",
"(",
"name",
")",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"readlines",
"(",
")"
] | Parse requirements file | [
"Parse",
"requirements",
"file"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/setup.py#L19-L22 | train | 43,064 |
abilian/abilian-core | abilian/services/conversion/handlers.py | PdfToPpmHandler.convert | def convert(self, blob, size=500):
"""Size is the maximum horizontal size."""
file_list = []
with make_temp_file(blob) as in_fn, make_temp_file() as out_fn:
try:
subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn])
file_list = sorted(glob.glob(f"{out_fn}-*.jpg"))
converted_images = []
for fn in file_list:
converted = resize(open(fn, "rb").read(), size, size)
converted_images.append(converted)
return converted_images
except Exception as e:
raise ConversionError("pdftoppm failed") from e
finally:
for fn in file_list:
try:
os.remove(fn)
except OSError:
pass | python | def convert(self, blob, size=500):
"""Size is the maximum horizontal size."""
file_list = []
with make_temp_file(blob) as in_fn, make_temp_file() as out_fn:
try:
subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn])
file_list = sorted(glob.glob(f"{out_fn}-*.jpg"))
converted_images = []
for fn in file_list:
converted = resize(open(fn, "rb").read(), size, size)
converted_images.append(converted)
return converted_images
except Exception as e:
raise ConversionError("pdftoppm failed") from e
finally:
for fn in file_list:
try:
os.remove(fn)
except OSError:
pass | [
"def",
"convert",
"(",
"self",
",",
"blob",
",",
"size",
"=",
"500",
")",
":",
"file_list",
"=",
"[",
"]",
"with",
"make_temp_file",
"(",
"blob",
")",
"as",
"in_fn",
",",
"make_temp_file",
"(",
")",
"as",
"out_fn",
":",
"try",
":",
"subprocess",
".",... | Size is the maximum horizontal size. | [
"Size",
"is",
"the",
"maximum",
"horizontal",
"size",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L225-L246 | train | 43,065 |
abilian/abilian-core | abilian/services/conversion/handlers.py | UnoconvPdfHandler.convert | def convert(self, blob, **kw):
"""Convert using unoconv converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for my Mac, FIXME later
if Path("/Applications/LibreOffice.app/Contents/program/python").exists():
cmd = [
"/Applications/LibreOffice.app/Contents/program/python",
"/usr/local/bin/unoconv",
] + args
else:
cmd = [self.unoconv] + args
def run_uno():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("run_uno error: %s", bytes(e), exc_info=True)
raise ConversionError("unoconv failed") from e
run_thread = threading.Thread(target=run_uno)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
converted = open(out_fn).read()
return converted
finally:
self._process = None | python | def convert(self, blob, **kw):
"""Convert using unoconv converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for my Mac, FIXME later
if Path("/Applications/LibreOffice.app/Contents/program/python").exists():
cmd = [
"/Applications/LibreOffice.app/Contents/program/python",
"/usr/local/bin/unoconv",
] + args
else:
cmd = [self.unoconv] + args
def run_uno():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("run_uno error: %s", bytes(e), exc_info=True)
raise ConversionError("unoconv failed") from e
run_thread = threading.Thread(target=run_uno)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
converted = open(out_fn).read()
return converted
finally:
self._process = None | [
"def",
"convert",
"(",
"self",
",",
"blob",
",",
"*",
"*",
"kw",
")",
":",
"timeout",
"=",
"self",
".",
"run_timeout",
"with",
"make_temp_file",
"(",
"blob",
")",
"as",
"in_fn",
",",
"make_temp_file",
"(",
"prefix",
"=",
"\"tmp-unoconv-\"",
",",
"suffix"... | Convert using unoconv converter. | [
"Convert",
"using",
"unoconv",
"converter",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L314-L361 | train | 43,066 |
abilian/abilian-core | abilian/services/conversion/handlers.py | LibreOfficePdfHandler.convert | def convert(self, blob, **kw):
"""Convert using soffice converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn:
cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn]
# # TODO: fix this if needed, or remove if not needed
# if os.path.exists(
# "/Applications/LibreOffice.app/Contents/program/python"):
# cmd = [
# '/Applications/LibreOffice.app/Contents/program/python',
# '/usr/local/bin/unoconv', '-f', 'pdf', '-o', out_fn, in_fn
# ]
def run_soffice():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("soffice error: %s", bytes(e), exc_info=True)
raise ConversionError("soffice conversion failed") from e
run_thread = threading.Thread(target=run_soffice)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
out_fn = os.path.splitext(in_fn)[0] + ".pdf"
converted = open(out_fn, "rb").read()
return converted
finally:
self._process = None | python | def convert(self, blob, **kw):
"""Convert using soffice converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn:
cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn]
# # TODO: fix this if needed, or remove if not needed
# if os.path.exists(
# "/Applications/LibreOffice.app/Contents/program/python"):
# cmd = [
# '/Applications/LibreOffice.app/Contents/program/python',
# '/usr/local/bin/unoconv', '-f', 'pdf', '-o', out_fn, in_fn
# ]
def run_soffice():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("soffice error: %s", bytes(e), exc_info=True)
raise ConversionError("soffice conversion failed") from e
run_thread = threading.Thread(target=run_soffice)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
out_fn = os.path.splitext(in_fn)[0] + ".pdf"
converted = open(out_fn, "rb").read()
return converted
finally:
self._process = None | [
"def",
"convert",
"(",
"self",
",",
"blob",
",",
"*",
"*",
"kw",
")",
":",
"timeout",
"=",
"self",
".",
"run_timeout",
"with",
"make_temp_file",
"(",
"blob",
")",
"as",
"in_fn",
":",
"cmd",
"=",
"[",
"self",
".",
"soffice",
",",
"\"--headless\"",
","... | Convert using soffice converter. | [
"Convert",
"using",
"soffice",
"converter",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/conversion/handlers.py#L416-L462 | train | 43,067 |
abilian/abilian-core | abilian/web/filters.py | autoescape | def autoescape(filter_func):
"""Decorator to autoescape result from filters."""
@evalcontextfilter
@wraps(filter_func)
def _autoescape(eval_ctx, *args, **kwargs):
result = filter_func(*args, **kwargs)
if eval_ctx.autoescape:
result = Markup(result)
return result
return _autoescape | python | def autoescape(filter_func):
"""Decorator to autoescape result from filters."""
@evalcontextfilter
@wraps(filter_func)
def _autoescape(eval_ctx, *args, **kwargs):
result = filter_func(*args, **kwargs)
if eval_ctx.autoescape:
result = Markup(result)
return result
return _autoescape | [
"def",
"autoescape",
"(",
"filter_func",
")",
":",
"@",
"evalcontextfilter",
"@",
"wraps",
"(",
"filter_func",
")",
"def",
"_autoescape",
"(",
"eval_ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"filter_func",
"(",
"*",
"args"... | Decorator to autoescape result from filters. | [
"Decorator",
"to",
"autoescape",
"result",
"from",
"filters",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L22-L33 | train | 43,068 |
abilian/abilian-core | abilian/web/filters.py | paragraphs | def paragraphs(value):
"""Blank lines delimitates paragraphs."""
result = "\n\n".join(
"<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
for p in _PARAGRAPH_RE.split(escape(value))
)
return result | python | def paragraphs(value):
"""Blank lines delimitates paragraphs."""
result = "\n\n".join(
"<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
for p in _PARAGRAPH_RE.split(escape(value))
)
return result | [
"def",
"paragraphs",
"(",
"value",
")",
":",
"result",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"\"<p>{}</p>\"",
".",
"format",
"(",
"p",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"Markup",
"(",
"\"<br />\\n\"",
")",
")",
")",
"for",
"... | Blank lines delimitates paragraphs. | [
"Blank",
"lines",
"delimitates",
"paragraphs",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L47-L53 | train | 43,069 |
abilian/abilian-core | abilian/web/filters.py | roughsize | def roughsize(size, above=20, mod=10):
"""6 -> '6' 15 -> '15' 134 -> '130+'."""
if size < above:
return str(size)
return "{:d}+".format(size - size % mod) | python | def roughsize(size, above=20, mod=10):
"""6 -> '6' 15 -> '15' 134 -> '130+'."""
if size < above:
return str(size)
return "{:d}+".format(size - size % mod) | [
"def",
"roughsize",
"(",
"size",
",",
"above",
"=",
"20",
",",
"mod",
"=",
"10",
")",
":",
"if",
"size",
"<",
"above",
":",
"return",
"str",
"(",
"size",
")",
"return",
"\"{:d}+\"",
".",
"format",
"(",
"size",
"-",
"size",
"%",
"mod",
")"
] | 6 -> '6' 15 -> '15' 134 -> '130+'. | [
"6",
"-",
">",
"6",
"15",
"-",
">",
"15",
"134",
"-",
">",
"130",
"+",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L86-L91 | train | 43,070 |
abilian/abilian-core | abilian/web/filters.py | datetimeparse | def datetimeparse(s):
"""Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC.
"""
try:
dt = dateutil.parser.parse(s)
except ValueError:
return None
return utc_dt(dt) | python | def datetimeparse(s):
"""Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC.
"""
try:
dt = dateutil.parser.parse(s)
except ValueError:
return None
return utc_dt(dt) | [
"def",
"datetimeparse",
"(",
"s",
")",
":",
"try",
":",
"dt",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"s",
")",
"except",
"ValueError",
":",
"return",
"None",
"return",
"utc_dt",
"(",
"dt",
")"
] | Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC. | [
"Parse",
"a",
"string",
"date",
"time",
"to",
"a",
"datetime",
"object",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/filters.py#L94-L106 | train | 43,071 |
abilian/abilian-core | abilian/services/base.py | Service.start | def start(self, ignore_state=False):
"""Starts the service."""
self.logger.debug("Start service")
self._toggle_running(True, ignore_state) | python | def start(self, ignore_state=False):
"""Starts the service."""
self.logger.debug("Start service")
self._toggle_running(True, ignore_state) | [
"def",
"start",
"(",
"self",
",",
"ignore_state",
"=",
"False",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Start service\"",
")",
"self",
".",
"_toggle_running",
"(",
"True",
",",
"ignore_state",
")"
] | Starts the service. | [
"Starts",
"the",
"service",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L51-L54 | train | 43,072 |
abilian/abilian-core | abilian/services/base.py | Service.app_state | def app_state(self):
"""Current service state in current application.
:raise:RuntimeError if working outside application context.
"""
try:
return current_app.extensions[self.name]
except KeyError:
raise ServiceNotRegistered(self.name) | python | def app_state(self):
"""Current service state in current application.
:raise:RuntimeError if working outside application context.
"""
try:
return current_app.extensions[self.name]
except KeyError:
raise ServiceNotRegistered(self.name) | [
"def",
"app_state",
"(",
"self",
")",
":",
"try",
":",
"return",
"current_app",
".",
"extensions",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"ServiceNotRegistered",
"(",
"self",
".",
"name",
")"
] | Current service state in current application.
:raise:RuntimeError if working outside application context. | [
"Current",
"service",
"state",
"in",
"current",
"application",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L69-L77 | train | 43,073 |
abilian/abilian-core | abilian/services/base.py | Service.if_running | def if_running(meth):
"""Decorator for service methods that must be ran only if service is in
running state."""
@wraps(meth)
def check_running(self, *args, **kwargs):
if not self.running:
return
return meth(self, *args, **kwargs)
return check_running | python | def if_running(meth):
"""Decorator for service methods that must be ran only if service is in
running state."""
@wraps(meth)
def check_running(self, *args, **kwargs):
if not self.running:
return
return meth(self, *args, **kwargs)
return check_running | [
"def",
"if_running",
"(",
"meth",
")",
":",
"@",
"wraps",
"(",
"meth",
")",
"def",
"check_running",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"return",
"meth",
"(",
"self",... | Decorator for service methods that must be ran only if service is in
running state. | [
"Decorator",
"for",
"service",
"methods",
"that",
"must",
"be",
"ran",
"only",
"if",
"service",
"is",
"in",
"running",
"state",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/base.py#L94-L104 | train | 43,074 |
noirbizarre/bumpr | bumpr/releaser.py | Releaser.clean | def clean(self):
'''Clean the workspace'''
if self.config.clean:
logger.info('Cleaning')
self.execute(self.config.clean) | python | def clean(self):
'''Clean the workspace'''
if self.config.clean:
logger.info('Cleaning')
self.execute(self.config.clean) | [
"def",
"clean",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"clean",
":",
"logger",
".",
"info",
"(",
"'Cleaning'",
")",
"self",
".",
"execute",
"(",
"self",
".",
"config",
".",
"clean",
")"
] | Clean the workspace | [
"Clean",
"the",
"workspace"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/releaser.py#L145-L149 | train | 43,075 |
noirbizarre/bumpr | bumpr/releaser.py | Releaser.publish | def publish(self):
'''Publish the current release to PyPI'''
if self.config.publish:
logger.info('Publish')
self.execute(self.config.publish) | python | def publish(self):
'''Publish the current release to PyPI'''
if self.config.publish:
logger.info('Publish')
self.execute(self.config.publish) | [
"def",
"publish",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"publish",
":",
"logger",
".",
"info",
"(",
"'Publish'",
")",
"self",
".",
"execute",
"(",
"self",
".",
"config",
".",
"publish",
")"
] | Publish the current release to PyPI | [
"Publish",
"the",
"current",
"release",
"to",
"PyPI"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/bumpr/releaser.py#L174-L178 | train | 43,076 |
noirbizarre/bumpr | tasks.py | deps | def deps(ctx):
'''Install or update development dependencies'''
header(deps.__doc__)
with ctx.cd(ROOT):
ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True) | python | def deps(ctx):
'''Install or update development dependencies'''
header(deps.__doc__)
with ctx.cd(ROOT):
ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True) | [
"def",
"deps",
"(",
"ctx",
")",
":",
"header",
"(",
"deps",
".",
"__doc__",
")",
"with",
"ctx",
".",
"cd",
"(",
"ROOT",
")",
":",
"ctx",
".",
"run",
"(",
"'pip install -r requirements/develop.pip -r requirements/doc.pip'",
",",
"pty",
"=",
"True",
")"
] | Install or update development dependencies | [
"Install",
"or",
"update",
"development",
"dependencies"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L80-L84 | train | 43,077 |
noirbizarre/bumpr | tasks.py | doc | def doc(ctx):
'''Build the documentation'''
header(doc.__doc__)
with ctx.cd(os.path.join(ROOT, 'doc')):
ctx.run('make html', pty=True)
success('Documentation available in doc/_build/html') | python | def doc(ctx):
'''Build the documentation'''
header(doc.__doc__)
with ctx.cd(os.path.join(ROOT, 'doc')):
ctx.run('make html', pty=True)
success('Documentation available in doc/_build/html') | [
"def",
"doc",
"(",
"ctx",
")",
":",
"header",
"(",
"doc",
".",
"__doc__",
")",
"with",
"ctx",
".",
"cd",
"(",
"os",
".",
"path",
".",
"join",
"(",
"ROOT",
",",
"'doc'",
")",
")",
":",
"ctx",
".",
"run",
"(",
"'make html'",
",",
"pty",
"=",
"T... | Build the documentation | [
"Build",
"the",
"documentation"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L153-L158 | train | 43,078 |
noirbizarre/bumpr | tasks.py | completion | def completion(ctx):
'''Generate bash completion script'''
header(completion.__doc__)
with ctx.cd(ROOT):
ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True)
success('Completion generated in bumpr-complete.sh') | python | def completion(ctx):
'''Generate bash completion script'''
header(completion.__doc__)
with ctx.cd(ROOT):
ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True)
success('Completion generated in bumpr-complete.sh') | [
"def",
"completion",
"(",
"ctx",
")",
":",
"header",
"(",
"completion",
".",
"__doc__",
")",
"with",
"ctx",
".",
"cd",
"(",
"ROOT",
")",
":",
"ctx",
".",
"run",
"(",
"'_bumpr_COMPLETE=source bumpr > bumpr-complete.sh'",
",",
"pty",
"=",
"True",
")",
"succe... | Generate bash completion script | [
"Generate",
"bash",
"completion",
"script"
] | 221dbb3deaf1cae7922f6a477f3d29d6bf0c0035 | https://github.com/noirbizarre/bumpr/blob/221dbb3deaf1cae7922f6a477f3d29d6bf0c0035/tasks.py#L162-L167 | train | 43,079 |
abilian/abilian-core | abilian/core/models/attachment.py | for_entity | def for_entity(obj, check_support_attachments=False):
"""Return attachments on an entity."""
if check_support_attachments and not supports_attachments(obj):
return []
return getattr(obj, ATTRIBUTE) | python | def for_entity(obj, check_support_attachments=False):
"""Return attachments on an entity."""
if check_support_attachments and not supports_attachments(obj):
return []
return getattr(obj, ATTRIBUTE) | [
"def",
"for_entity",
"(",
"obj",
",",
"check_support_attachments",
"=",
"False",
")",
":",
"if",
"check_support_attachments",
"and",
"not",
"supports_attachments",
"(",
"obj",
")",
":",
"return",
"[",
"]",
"return",
"getattr",
"(",
"obj",
",",
"ATTRIBUTE",
")"... | Return attachments on an entity. | [
"Return",
"attachments",
"on",
"an",
"entity",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/attachment.py#L61-L66 | train | 43,080 |
abilian/abilian-core | abilian/services/vocabularies/models.py | strip_label | def strip_label(mapper, connection, target):
"""Strip labels at ORM level so the unique=True means something."""
if target.label is not None:
target.label = target.label.strip() | python | def strip_label(mapper, connection, target):
"""Strip labels at ORM level so the unique=True means something."""
if target.label is not None:
target.label = target.label.strip() | [
"def",
"strip_label",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"label",
"is",
"not",
"None",
":",
"target",
".",
"label",
"=",
"target",
".",
"label",
".",
"strip",
"(",
")"
] | Strip labels at ORM level so the unique=True means something. | [
"Strip",
"labels",
"at",
"ORM",
"level",
"so",
"the",
"unique",
"=",
"True",
"means",
"something",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L111-L114 | train | 43,081 |
abilian/abilian-core | abilian/services/vocabularies/models.py | _before_insert | def _before_insert(mapper, connection, target):
"""Set item to last position if position not defined."""
if target.position is None:
func = sa.sql.func
stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
target.position = connection.execute(stmt).scalar() + 1 | python | def _before_insert(mapper, connection, target):
"""Set item to last position if position not defined."""
if target.position is None:
func = sa.sql.func
stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
target.position = connection.execute(stmt).scalar() + 1 | [
"def",
"_before_insert",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"position",
"is",
"None",
":",
"func",
"=",
"sa",
".",
"sql",
".",
"func",
"stmt",
"=",
"sa",
".",
"select",
"(",
"[",
"func",
".",
"coalesce",
... | Set item to last position if position not defined. | [
"Set",
"item",
"to",
"last",
"position",
"if",
"position",
"not",
"defined",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L118-L123 | train | 43,082 |
abilian/abilian-core | abilian/web/errors.py | ErrorManagerMixin.init_sentry | def init_sentry(self):
"""Install Sentry handler if config defines 'SENTRY_DSN'."""
dsn = self.config.get("SENTRY_DSN")
if not dsn:
return
try:
import sentry_sdk
except ImportError:
logger.error(
'SENTRY_DSN is defined in config but package "sentry-sdk"'
" is not installed."
)
return
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(dsn=dsn, integrations=[FlaskIntegration()]) | python | def init_sentry(self):
"""Install Sentry handler if config defines 'SENTRY_DSN'."""
dsn = self.config.get("SENTRY_DSN")
if not dsn:
return
try:
import sentry_sdk
except ImportError:
logger.error(
'SENTRY_DSN is defined in config but package "sentry-sdk"'
" is not installed."
)
return
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(dsn=dsn, integrations=[FlaskIntegration()]) | [
"def",
"init_sentry",
"(",
"self",
")",
":",
"dsn",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"SENTRY_DSN\"",
")",
"if",
"not",
"dsn",
":",
"return",
"try",
":",
"import",
"sentry_sdk",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"'... | Install Sentry handler if config defines 'SENTRY_DSN'. | [
"Install",
"Sentry",
"handler",
"if",
"config",
"defines",
"SENTRY_DSN",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L112-L129 | train | 43,083 |
abilian/abilian-core | abilian/web/errors.py | ErrorManagerMixin.install_default_handler | def install_default_handler(self, http_error_code):
"""Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404.
"""
logger.debug(
"Set Default HTTP error handler for status code %d", http_error_code
)
handler = partial(self.handle_http_error, http_error_code)
self.errorhandler(http_error_code)(handler) | python | def install_default_handler(self, http_error_code):
"""Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404.
"""
logger.debug(
"Set Default HTTP error handler for status code %d", http_error_code
)
handler = partial(self.handle_http_error, http_error_code)
self.errorhandler(http_error_code)(handler) | [
"def",
"install_default_handler",
"(",
"self",
",",
"http_error_code",
")",
":",
"logger",
".",
"debug",
"(",
"\"Set Default HTTP error handler for status code %d\"",
",",
"http_error_code",
")",
"handler",
"=",
"partial",
"(",
"self",
".",
"handle_http_error",
",",
"... | Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404. | [
"Install",
"a",
"default",
"error",
"handler",
"for",
"http_error_code",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/errors.py#L141-L151 | train | 43,084 |
abilian/abilian-core | abilian/web/views/registry.py | Registry.register | def register(self, entity, url_func):
"""Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it.
"""
if not inspect.isclass(entity):
entity = entity.__class__
assert issubclass(entity, db.Model)
self._map[entity.entity_type] = url_func | python | def register(self, entity, url_func):
"""Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it.
"""
if not inspect.isclass(entity):
entity = entity.__class__
assert issubclass(entity, db.Model)
self._map[entity.entity_type] = url_func | [
"def",
"register",
"(",
"self",
",",
"entity",
",",
"url_func",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"entity",
")",
":",
"entity",
"=",
"entity",
".",
"__class__",
"assert",
"issubclass",
"(",
"entity",
",",
"db",
".",
"Model",
")",
... | Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it. | [
"Associate",
"a",
"url_func",
"with",
"entity",
"s",
"type",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/registry.py#L21-L33 | train | 43,085 |
abilian/abilian-core | abilian/web/views/registry.py | Registry.url_for | def url_for(self, entity=None, object_type=None, object_id=None, **kwargs):
"""Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
:class:`abilian.core.extensions.db.Model`,
:class:`whoosh.searching.Hit` or :class:`python:dict`
:param object_id: if `entity` is not an instance, this parameter
must be set to target id. This is usefull when you know the type and
id of an object but don't want to retrieve it from DB.
:raise KeyError: if no view can be found for the given entity.
"""
if object_type is None:
assert isinstance(entity, (db.Model, Hit, dict))
getter = attrgetter if isinstance(entity, db.Model) else itemgetter
object_id = getter("id")(entity)
object_type = getter("object_type")(entity)
url_func = self._map.get(object_type) # type: Optional[Callable]
if url_func is not None:
return url_func(entity, object_type, object_id, **kwargs)
try:
return url_for(
"{}.view".format(object_type.rsplit(".")[-1].lower()),
object_id=object_id,
**kwargs
)
except Exception:
raise KeyError(object_type) | python | def url_for(self, entity=None, object_type=None, object_id=None, **kwargs):
"""Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
:class:`abilian.core.extensions.db.Model`,
:class:`whoosh.searching.Hit` or :class:`python:dict`
:param object_id: if `entity` is not an instance, this parameter
must be set to target id. This is usefull when you know the type and
id of an object but don't want to retrieve it from DB.
:raise KeyError: if no view can be found for the given entity.
"""
if object_type is None:
assert isinstance(entity, (db.Model, Hit, dict))
getter = attrgetter if isinstance(entity, db.Model) else itemgetter
object_id = getter("id")(entity)
object_type = getter("object_type")(entity)
url_func = self._map.get(object_type) # type: Optional[Callable]
if url_func is not None:
return url_func(entity, object_type, object_id, **kwargs)
try:
return url_for(
"{}.view".format(object_type.rsplit(".")[-1].lower()),
object_id=object_id,
**kwargs
)
except Exception:
raise KeyError(object_type) | [
"def",
"url_for",
"(",
"self",
",",
"entity",
"=",
"None",
",",
"object_type",
"=",
"None",
",",
"object_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"object_type",
"is",
"None",
":",
"assert",
"isinstance",
"(",
"entity",
",",
"(",
"db... | Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
:class:`abilian.core.extensions.db.Model`,
:class:`whoosh.searching.Hit` or :class:`python:dict`
:param object_id: if `entity` is not an instance, this parameter
must be set to target id. This is usefull when you know the type and
id of an object but don't want to retrieve it from DB.
:raise KeyError: if no view can be found for the given entity. | [
"Return",
"canonical",
"view",
"URL",
"for",
"given",
"entity",
"instance",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/views/registry.py#L35-L69 | train | 43,086 |
abilian/abilian-core | abilian/core/models/blob.py | Blob.value | def value(self):
# type: () -> bytes
"""Binary value content."""
v = self.file
return v.open("rb").read() if v is not None else v | python | def value(self):
# type: () -> bytes
"""Binary value content."""
v = self.file
return v.open("rb").read() if v is not None else v | [
"def",
"value",
"(",
"self",
")",
":",
"# type: () -> bytes",
"v",
"=",
"self",
".",
"file",
"return",
"v",
".",
"open",
"(",
"\"rb\"",
")",
".",
"read",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"else",
"v"
] | Binary value content. | [
"Binary",
"value",
"content",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L76-L80 | train | 43,087 |
abilian/abilian-core | abilian/core/models/blob.py | Blob.value | def value(self):
"""Remove value from repository."""
from abilian.services.repository import session_repository as repository
repository.delete(self, self.uuid) | python | def value(self):
"""Remove value from repository."""
from abilian.services.repository import session_repository as repository
repository.delete(self, self.uuid) | [
"def",
"value",
"(",
"self",
")",
":",
"from",
"abilian",
".",
"services",
".",
"repository",
"import",
"session_repository",
"as",
"repository",
"repository",
".",
"delete",
"(",
"self",
",",
"self",
".",
"uuid",
")"
] | Remove value from repository. | [
"Remove",
"value",
"from",
"repository",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L105-L109 | train | 43,088 |
abilian/abilian-core | abilian/core/models/blob.py | Blob.md5 | def md5(self):
"""Return md5 from meta, or compute it if absent."""
md5 = self.meta.get("md5")
if md5 is None:
md5 = str(hashlib.md5(self.value).hexdigest())
return md5 | python | def md5(self):
"""Return md5 from meta, or compute it if absent."""
md5 = self.meta.get("md5")
if md5 is None:
md5 = str(hashlib.md5(self.value).hexdigest())
return md5 | [
"def",
"md5",
"(",
"self",
")",
":",
"md5",
"=",
"self",
".",
"meta",
".",
"get",
"(",
"\"md5\"",
")",
"if",
"md5",
"is",
"None",
":",
"md5",
"=",
"str",
"(",
"hashlib",
".",
"md5",
"(",
"self",
".",
"value",
")",
".",
"hexdigest",
"(",
")",
... | Return md5 from meta, or compute it if absent. | [
"Return",
"md5",
"from",
"meta",
"or",
"compute",
"it",
"if",
"absent",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/core/models/blob.py#L112-L118 | train | 43,089 |
abilian/abilian-core | abilian/services/auth/views.py | forgotten_pw | def forgotten_pw(new_user=False):
"""Reset password for users who have already activated their accounts."""
email = request.form.get("email", "").lower()
action = request.form.get("action")
if action == "cancel":
return redirect(url_for("login.login_form"))
if not email:
flash(_("You must provide your email address."), "error")
return render_template("login/forgotten_password.html")
try:
user = User.query.filter(
sql.func.lower(User.email) == email, User.can_login == True
).one()
except NoResultFound:
flash(
_("Sorry, we couldn't find an account for " "email '{email}'.").format(
email=email
),
"error",
)
return render_template("login/forgotten_password.html"), 401
if user.can_login and not user.password:
user.set_password(random_password())
db.session.commit()
send_reset_password_instructions(user)
flash(
_("Password reset instructions have been sent to your email address."), "info"
)
return redirect(url_for("login.login_form")) | python | def forgotten_pw(new_user=False):
"""Reset password for users who have already activated their accounts."""
email = request.form.get("email", "").lower()
action = request.form.get("action")
if action == "cancel":
return redirect(url_for("login.login_form"))
if not email:
flash(_("You must provide your email address."), "error")
return render_template("login/forgotten_password.html")
try:
user = User.query.filter(
sql.func.lower(User.email) == email, User.can_login == True
).one()
except NoResultFound:
flash(
_("Sorry, we couldn't find an account for " "email '{email}'.").format(
email=email
),
"error",
)
return render_template("login/forgotten_password.html"), 401
if user.can_login and not user.password:
user.set_password(random_password())
db.session.commit()
send_reset_password_instructions(user)
flash(
_("Password reset instructions have been sent to your email address."), "info"
)
return redirect(url_for("login.login_form")) | [
"def",
"forgotten_pw",
"(",
"new_user",
"=",
"False",
")",
":",
"email",
"=",
"request",
".",
"form",
".",
"get",
"(",
"\"email\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"action",
"=",
"request",
".",
"form",
".",
"get",
"(",
"\"action\"",
")",
... | Reset password for users who have already activated their accounts. | [
"Reset",
"password",
"for",
"users",
"who",
"have",
"already",
"activated",
"their",
"accounts",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L150-L184 | train | 43,090 |
abilian/abilian-core | abilian/services/auth/views.py | send_reset_password_instructions | def send_reset_password_instructions(user):
# type: (User) -> None
"""Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to
"""
token = generate_reset_password_token(user)
url = url_for("login.reset_password", token=token)
reset_link = request.url_root[:-1] + url
subject = _("Password reset instruction for {site_name}").format(
site_name=current_app.config.get("SITE_NAME")
)
mail_template = "password_reset_instructions"
send_mail(subject, user.email, mail_template, user=user, reset_link=reset_link) | python | def send_reset_password_instructions(user):
# type: (User) -> None
"""Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to
"""
token = generate_reset_password_token(user)
url = url_for("login.reset_password", token=token)
reset_link = request.url_root[:-1] + url
subject = _("Password reset instruction for {site_name}").format(
site_name=current_app.config.get("SITE_NAME")
)
mail_template = "password_reset_instructions"
send_mail(subject, user.email, mail_template, user=user, reset_link=reset_link) | [
"def",
"send_reset_password_instructions",
"(",
"user",
")",
":",
"# type: (User) -> None",
"token",
"=",
"generate_reset_password_token",
"(",
"user",
")",
"url",
"=",
"url_for",
"(",
"\"login.reset_password\"",
",",
"token",
"=",
"token",
")",
"reset_link",
"=",
"... | Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to | [
"Send",
"the",
"reset",
"password",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L267-L281 | train | 43,091 |
abilian/abilian-core | abilian/services/auth/views.py | generate_reset_password_token | def generate_reset_password_token(user):
# type: (User) -> Any
"""Generate a unique reset password token for the specified user.
:param user: The user to work with
"""
data = [str(user.id), md5(user.password)]
return get_serializer("reset").dumps(data) | python | def generate_reset_password_token(user):
# type: (User) -> Any
"""Generate a unique reset password token for the specified user.
:param user: The user to work with
"""
data = [str(user.id), md5(user.password)]
return get_serializer("reset").dumps(data) | [
"def",
"generate_reset_password_token",
"(",
"user",
")",
":",
"# type: (User) -> Any",
"data",
"=",
"[",
"str",
"(",
"user",
".",
"id",
")",
",",
"md5",
"(",
"user",
".",
"password",
")",
"]",
"return",
"get_serializer",
"(",
"\"reset\"",
")",
".",
"dumps... | Generate a unique reset password token for the specified user.
:param user: The user to work with | [
"Generate",
"a",
"unique",
"reset",
"password",
"token",
"for",
"the",
"specified",
"user",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L284-L291 | train | 43,092 |
abilian/abilian-core | abilian/services/auth/views.py | send_mail | def send_mail(subject, recipient, template, **context):
"""Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
config = current_app.config
sender = config["MAIL_SENDER"]
msg = Message(subject, sender=sender, recipients=[recipient])
template_name = f"login/email/{template}.txt"
msg.body = render_template_i18n(template_name, **context)
# msg.html = render_template('%s/%s.html' % ctx, **context)
mail = current_app.extensions.get("mail")
current_app.logger.debug("Sending mail...")
mail.send(msg) | python | def send_mail(subject, recipient, template, **context):
"""Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
config = current_app.config
sender = config["MAIL_SENDER"]
msg = Message(subject, sender=sender, recipients=[recipient])
template_name = f"login/email/{template}.txt"
msg.body = render_template_i18n(template_name, **context)
# msg.html = render_template('%s/%s.html' % ctx, **context)
mail = current_app.extensions.get("mail")
current_app.logger.debug("Sending mail...")
mail.send(msg) | [
"def",
"send_mail",
"(",
"subject",
",",
"recipient",
",",
"template",
",",
"*",
"*",
"context",
")",
":",
"config",
"=",
"current_app",
".",
"config",
"sender",
"=",
"config",
"[",
"\"MAIL_SENDER\"",
"]",
"msg",
"=",
"Message",
"(",
"subject",
",",
"sen... | Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | [
"Send",
"an",
"email",
"using",
"the",
"Flask",
"-",
"Mail",
"extension",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L329-L348 | train | 43,093 |
abilian/abilian-core | abilian/app.py | PluginManager.register_plugin | def register_plugin(self, name):
"""Load and register a plugin given its package name."""
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | python | def register_plugin(self, name):
"""Load and register a plugin given its package name."""
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | [
"def",
"register_plugin",
"(",
"self",
",",
"name",
")",
":",
"logger",
".",
"info",
"(",
"\"Registering plugin: \"",
"+",
"name",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"module",
".",
"register_plugin",
"(",
"self",
")"
] | Load and register a plugin given its package name. | [
"Load",
"and",
"register",
"a",
"plugin",
"given",
"its",
"package",
"name",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L84-L88 | train | 43,094 |
abilian/abilian-core | abilian/app.py | PluginManager.register_plugins | def register_plugins(self):
"""Load plugins listed in config variable 'PLUGINS'."""
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | python | def register_plugins(self):
"""Load plugins listed in config variable 'PLUGINS'."""
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | [
"def",
"register_plugins",
"(",
"self",
")",
":",
"registered",
"=",
"set",
"(",
")",
"for",
"plugin_fqdn",
"in",
"chain",
"(",
"self",
".",
"APP_PLUGINS",
",",
"self",
".",
"config",
"[",
"\"PLUGINS\"",
"]",
")",
":",
"if",
"plugin_fqdn",
"not",
"in",
... | Load plugins listed in config variable 'PLUGINS'. | [
"Load",
"plugins",
"listed",
"in",
"config",
"variable",
"PLUGINS",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L90-L96 | train | 43,095 |
abilian/abilian-core | abilian/app.py | Application.init_breadcrumbs | def init_breadcrumbs(self):
"""Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers.
"""
g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_root)) | python | def init_breadcrumbs(self):
"""Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers.
"""
g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_root)) | [
"def",
"init_breadcrumbs",
"(",
"self",
")",
":",
"g",
".",
"breadcrumb",
".",
"append",
"(",
"BreadcrumbItem",
"(",
"icon",
"=",
"\"home\"",
",",
"url",
"=",
"\"/\"",
"+",
"request",
".",
"script_root",
")",
")"
] | Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers. | [
"Insert",
"the",
"first",
"element",
"in",
"breadcrumbs",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L217-L223 | train | 43,096 |
abilian/abilian-core | abilian/app.py | Application.check_instance_folder | def check_instance_folder(self, create=False):
"""Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong.
"""
path = Path(self.instance_path)
err = None
eno = 0
if not path.exists():
if create:
logger.info("Create instance folder: %s", path)
path.mkdir(0o775, parents=True)
else:
err = "Instance folder does not exists"
eno = errno.ENOENT
elif not path.is_dir():
err = "Instance folder is not a directory"
eno = errno.ENOTDIR
elif not os.access(str(path), os.R_OK | os.W_OK | os.X_OK):
err = 'Require "rwx" access rights, please verify permissions'
eno = errno.EPERM
if err:
raise OSError(eno, err, str(path)) | python | def check_instance_folder(self, create=False):
"""Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong.
"""
path = Path(self.instance_path)
err = None
eno = 0
if not path.exists():
if create:
logger.info("Create instance folder: %s", path)
path.mkdir(0o775, parents=True)
else:
err = "Instance folder does not exists"
eno = errno.ENOENT
elif not path.is_dir():
err = "Instance folder is not a directory"
eno = errno.ENOTDIR
elif not os.access(str(path), os.R_OK | os.W_OK | os.X_OK):
err = 'Require "rwx" access rights, please verify permissions'
eno = errno.EPERM
if err:
raise OSError(eno, err, str(path)) | [
"def",
"check_instance_folder",
"(",
"self",
",",
"create",
"=",
"False",
")",
":",
"path",
"=",
"Path",
"(",
"self",
".",
"instance_path",
")",
"err",
"=",
"None",
"eno",
"=",
"0",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"if",
"create",
... | Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong. | [
"Verify",
"instance",
"folder",
"exists",
"is",
"a",
"directory",
"and",
"has",
"necessary",
"permissions",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L251-L278 | train | 43,097 |
abilian/abilian-core | abilian/app.py | Application.init_extensions | def init_extensions(self):
"""Initialize flask extensions, helpers and services."""
extensions.redis.init_app(self)
extensions.mail.init_app(self)
extensions.deferred_js.init_app(self)
extensions.upstream_info.extension.init_app(self)
actions.init_app(self)
# auth_service installs a `before_request` handler (actually it's
# flask-login). We want to authenticate user ASAP, so that sentry and
# logs can report which user encountered any error happening later,
# in particular in a before_request handler (like csrf validator)
auth_service.init_app(self)
# webassets
self.setup_asset_extension()
self.register_base_assets()
# Babel (for i18n)
babel = abilian.i18n.babel
# Temporary (?) workaround
babel.locale_selector_func = None
babel.timezone_selector_func = None
babel.init_app(self)
babel.add_translations("wtforms", translations_dir="locale", domain="wtforms")
babel.add_translations("abilian")
babel.localeselector(abilian.i18n.localeselector)
babel.timezoneselector(abilian.i18n.timezoneselector)
# Flask-Migrate
Migrate(self, db)
# CSRF by default
if self.config.get("WTF_CSRF_ENABLED"):
extensions.csrf.init_app(self)
self.extensions["csrf"] = extensions.csrf
extensions.abilian_csrf.init_app(self)
self.register_blueprint(csrf.blueprint)
# images blueprint
from .web.views.images import blueprint as images_bp
self.register_blueprint(images_bp)
# Abilian Core services
security_service.init_app(self)
repository_service.init_app(self)
session_repository_service.init_app(self)
audit_service.init_app(self)
index_service.init_app(self)
activity_service.init_app(self)
preferences_service.init_app(self)
conversion_service.init_app(self)
vocabularies_service.init_app(self)
antivirus.init_app(self)
from .web.preferences.user import UserPreferencesPanel
preferences_service.register_panel(UserPreferencesPanel(), self)
from .web.coreviews import users
self.register_blueprint(users.blueprint)
# Admin interface
Admin().init_app(self)
# Celery async service
# this allows all shared tasks to use this celery app
if getattr(self, "celery_app_cls", None):
celery_app = self.extensions["celery"] = self.celery_app_cls()
# force reading celery conf now - default celery app will
# also update our config with default settings
celery_app.conf # noqa
celery_app.set_default()
# dev helper
if self.debug:
# during dev, one can go to /http_error/403 to see rendering of 403
http_error_pages = Blueprint("http_error_pages", __name__)
@http_error_pages.route("/<int:code>")
def error_page(code):
"""Helper for development to show 403, 404, 500..."""
abort(code)
self.register_blueprint(http_error_pages, url_prefix="/http_error") | python | def init_extensions(self):
"""Initialize flask extensions, helpers and services."""
extensions.redis.init_app(self)
extensions.mail.init_app(self)
extensions.deferred_js.init_app(self)
extensions.upstream_info.extension.init_app(self)
actions.init_app(self)
# auth_service installs a `before_request` handler (actually it's
# flask-login). We want to authenticate user ASAP, so that sentry and
# logs can report which user encountered any error happening later,
# in particular in a before_request handler (like csrf validator)
auth_service.init_app(self)
# webassets
self.setup_asset_extension()
self.register_base_assets()
# Babel (for i18n)
babel = abilian.i18n.babel
# Temporary (?) workaround
babel.locale_selector_func = None
babel.timezone_selector_func = None
babel.init_app(self)
babel.add_translations("wtforms", translations_dir="locale", domain="wtforms")
babel.add_translations("abilian")
babel.localeselector(abilian.i18n.localeselector)
babel.timezoneselector(abilian.i18n.timezoneselector)
# Flask-Migrate
Migrate(self, db)
# CSRF by default
if self.config.get("WTF_CSRF_ENABLED"):
extensions.csrf.init_app(self)
self.extensions["csrf"] = extensions.csrf
extensions.abilian_csrf.init_app(self)
self.register_blueprint(csrf.blueprint)
# images blueprint
from .web.views.images import blueprint as images_bp
self.register_blueprint(images_bp)
# Abilian Core services
security_service.init_app(self)
repository_service.init_app(self)
session_repository_service.init_app(self)
audit_service.init_app(self)
index_service.init_app(self)
activity_service.init_app(self)
preferences_service.init_app(self)
conversion_service.init_app(self)
vocabularies_service.init_app(self)
antivirus.init_app(self)
from .web.preferences.user import UserPreferencesPanel
preferences_service.register_panel(UserPreferencesPanel(), self)
from .web.coreviews import users
self.register_blueprint(users.blueprint)
# Admin interface
Admin().init_app(self)
# Celery async service
# this allows all shared tasks to use this celery app
if getattr(self, "celery_app_cls", None):
celery_app = self.extensions["celery"] = self.celery_app_cls()
# force reading celery conf now - default celery app will
# also update our config with default settings
celery_app.conf # noqa
celery_app.set_default()
# dev helper
if self.debug:
# during dev, one can go to /http_error/403 to see rendering of 403
http_error_pages = Blueprint("http_error_pages", __name__)
@http_error_pages.route("/<int:code>")
def error_page(code):
"""Helper for development to show 403, 404, 500..."""
abort(code)
self.register_blueprint(http_error_pages, url_prefix="/http_error") | [
"def",
"init_extensions",
"(",
"self",
")",
":",
"extensions",
".",
"redis",
".",
"init_app",
"(",
"self",
")",
"extensions",
".",
"mail",
".",
"init_app",
"(",
"self",
")",
"extensions",
".",
"deferred_js",
".",
"init_app",
"(",
"self",
")",
"extensions",... | Initialize flask extensions, helpers and services. | [
"Initialize",
"flask",
"extensions",
"helpers",
"and",
"services",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L288-L376 | train | 43,098 |
abilian/abilian-core | abilian/app.py | Application.add_access_controller | def add_access_controller(self, name: str, func: Callable, endpoint: bool = False):
"""Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint.
"""
auth_state = self.extensions[auth_service.name]
adder = auth_state.add_bp_access_controller
if endpoint:
adder = auth_state.add_endpoint_access_controller
if not isinstance(name, str):
msg = "{} is not a valid endpoint name".format(repr(name))
raise ValueError(msg)
adder(name, func) | python | def add_access_controller(self, name: str, func: Callable, endpoint: bool = False):
"""Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint.
"""
auth_state = self.extensions[auth_service.name]
adder = auth_state.add_bp_access_controller
if endpoint:
adder = auth_state.add_endpoint_access_controller
if not isinstance(name, str):
msg = "{} is not a valid endpoint name".format(repr(name))
raise ValueError(msg)
adder(name, func) | [
"def",
"add_access_controller",
"(",
"self",
",",
"name",
":",
"str",
",",
"func",
":",
"Callable",
",",
"endpoint",
":",
"bool",
"=",
"False",
")",
":",
"auth_state",
"=",
"self",
".",
"extensions",
"[",
"auth_service",
".",
"name",
"]",
"adder",
"=",
... | Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint. | [
"Add",
"an",
"access",
"controller",
"."
] | 0a71275bf108c3d51e13ca9e093c0249235351e3 | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/app.py#L392-L408 | train | 43,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.