id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,400 | django-leonardo/django-leonardo | leonardo/module/web/page/utils.py | get_anonymous_request | def get_anonymous_request(leonardo_page):
"""returns inicialized request
"""
request_factory = RequestFactory()
request = request_factory.get(
leonardo_page.get_absolute_url(), data={})
request.feincms_page = request.leonardo_page = leonardo_page
request.frontend_editing = False
request.user = AnonymousUser()
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
request.path = leonardo_page.get_absolute_url()
request.frontend_editing = False
leonardo_page.run_request_processors(request)
request.LEONARDO_CONFIG = ContextConfig(request)
handler = BaseHandler()
handler.load_middleware()
# Apply request middleware
for middleware_method in handler._request_middleware:
try:
middleware_method(request)
except:
pass
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
fn(leonardo_page, request)
return request | python | def get_anonymous_request(leonardo_page):
request_factory = RequestFactory()
request = request_factory.get(
leonardo_page.get_absolute_url(), data={})
request.feincms_page = request.leonardo_page = leonardo_page
request.frontend_editing = False
request.user = AnonymousUser()
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
request.path = leonardo_page.get_absolute_url()
request.frontend_editing = False
leonardo_page.run_request_processors(request)
request.LEONARDO_CONFIG = ContextConfig(request)
handler = BaseHandler()
handler.load_middleware()
# Apply request middleware
for middleware_method in handler._request_middleware:
try:
middleware_method(request)
except:
pass
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
fn(leonardo_page, request)
return request | [
"def",
"get_anonymous_request",
"(",
"leonardo_page",
")",
":",
"request_factory",
"=",
"RequestFactory",
"(",
")",
"request",
"=",
"request_factory",
".",
"get",
"(",
"leonardo_page",
".",
"get_absolute_url",
"(",
")",
",",
"data",
"=",
"{",
"}",
")",
"reques... | returns inicialized request | [
"returns",
"inicialized",
"request"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/utils.py#L8-L43 |
22,401 | django-leonardo/django-leonardo | leonardo/module/web/processors/font.py | webfont_cookie | def webfont_cookie(request):
'''Adds WEBFONT Flag to the context'''
if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None):
return {
WEBFONT_COOKIE_NAME.upper(): True
}
return {
WEBFONT_COOKIE_NAME.upper(): False
} | python | def webfont_cookie(request):
'''Adds WEBFONT Flag to the context'''
if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None):
return {
WEBFONT_COOKIE_NAME.upper(): True
}
return {
WEBFONT_COOKIE_NAME.upper(): False
} | [
"def",
"webfont_cookie",
"(",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'COOKIES'",
")",
"and",
"request",
".",
"COOKIES",
".",
"get",
"(",
"WEBFONT_COOKIE_NAME",
",",
"None",
")",
":",
"return",
"{",
"WEBFONT_COOKIE_NAME",
".",
"upper",
... | Adds WEBFONT Flag to the context | [
"Adds",
"WEBFONT",
"Flag",
"to",
"the",
"context"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/font.py#L10-L21 |
22,402 | django-leonardo/django-leonardo | leonardo/utils/widgets.py | get_all_widget_classes | def get_all_widget_classes():
"""returns collected Leonardo Widgets
if not declared in settings is used __subclasses__
which not supports widget subclassing
"""
from leonardo.module.web.models import Widget
_widgets = getattr(settings,
'WIDGETS', Widget.__subclasses__())
widgets = []
if isinstance(_widgets, dict):
for group, widget_cls in six.iteritems(_widgets):
widgets.extend(widget_cls)
elif isinstance(_widgets, list):
widgets = _widgets
return load_widget_classes(widgets) | python | def get_all_widget_classes():
from leonardo.module.web.models import Widget
_widgets = getattr(settings,
'WIDGETS', Widget.__subclasses__())
widgets = []
if isinstance(_widgets, dict):
for group, widget_cls in six.iteritems(_widgets):
widgets.extend(widget_cls)
elif isinstance(_widgets, list):
widgets = _widgets
return load_widget_classes(widgets) | [
"def",
"get_all_widget_classes",
"(",
")",
":",
"from",
"leonardo",
".",
"module",
".",
"web",
".",
"models",
"import",
"Widget",
"_widgets",
"=",
"getattr",
"(",
"settings",
",",
"'WIDGETS'",
",",
"Widget",
".",
"__subclasses__",
"(",
")",
")",
"widgets",
... | returns collected Leonardo Widgets
if not declared in settings is used __subclasses__
which not supports widget subclassing | [
"returns",
"collected",
"Leonardo",
"Widgets"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/widgets.py#L45-L61 |
22,403 | django-leonardo/django-leonardo | leonardo/utils/widgets.py | render_region | def render_region(widget=None, request=None, view=None,
page=None, region=None):
"""returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method
"""
# change the request
if not isinstance(request, dict):
request.query_string = None
request.method = "GET"
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
leonardo_page = widget.parent if widget else page
render_region = widget.region if widget else region
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
try:
r = fn(leonardo_page, request)
except:
pass
contents = {}
for content in leonardo_page.content.all_of_type(tuple(
leonardo_page._feincms_content_types_with_process)):
try:
r = content.process(request, view=view)
except:
pass
else:
# this is HttpResponse object or string
if not isinstance(r, six.string_types):
r.render()
contents[content.fe_identifier] = getattr(r, 'content', r)
else:
contents[content.fe_identifier] = r
from leonardo.templatetags.leonardo_tags import _render_content
region_content = ''.join(
contents[content.fe_identifier] if content.fe_identifier in contents else _render_content(
content, request=request, context={})
for content in getattr(leonardo_page.content, render_region))
return region_content | python | def render_region(widget=None, request=None, view=None,
page=None, region=None):
# change the request
if not isinstance(request, dict):
request.query_string = None
request.method = "GET"
if not hasattr(request, '_feincms_extra_context'):
request._feincms_extra_context = {}
leonardo_page = widget.parent if widget else page
render_region = widget.region if widget else region
# call processors
for fn in reversed(list(leonardo_page.request_processors.values())):
try:
r = fn(leonardo_page, request)
except:
pass
contents = {}
for content in leonardo_page.content.all_of_type(tuple(
leonardo_page._feincms_content_types_with_process)):
try:
r = content.process(request, view=view)
except:
pass
else:
# this is HttpResponse object or string
if not isinstance(r, six.string_types):
r.render()
contents[content.fe_identifier] = getattr(r, 'content', r)
else:
contents[content.fe_identifier] = r
from leonardo.templatetags.leonardo_tags import _render_content
region_content = ''.join(
contents[content.fe_identifier] if content.fe_identifier in contents else _render_content(
content, request=request, context={})
for content in getattr(leonardo_page.content, render_region))
return region_content | [
"def",
"render_region",
"(",
"widget",
"=",
"None",
",",
"request",
"=",
"None",
",",
"view",
"=",
"None",
",",
"page",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"# change the request",
"if",
"not",
"isinstance",
"(",
"request",
",",
"dict",
"... | returns rendered content
this is not too clear and little tricky,
because external apps needs calling process method | [
"returns",
"rendered",
"content",
"this",
"is",
"not",
"too",
"clear",
"and",
"little",
"tricky",
"because",
"external",
"apps",
"needs",
"calling",
"process",
"method"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/widgets.py#L124-L173 |
22,404 | django-leonardo/django-leonardo | leonardo/module/web/admin.py | PageAdmin.get_feincms_inlines | def get_feincms_inlines(self, model, request):
""" Generate genuine django inlines for registered content types. """
model._needs_content_types()
inlines = []
for content_type in model._feincms_content_types:
if not self.can_add_content(request, content_type):
continue
attrs = {
'__module__': model.__module__,
'model': content_type,
}
if hasattr(content_type, 'feincms_item_editor_inline'):
inline = content_type.feincms_item_editor_inline
attrs['form'] = inline.form
#if hasattr(content_type, 'feincms_item_editor_form'):
# warnings.warn(
# 'feincms_item_editor_form on %s is ignored because '
# 'feincms_item_editor_inline is set too' % content_type,
# RuntimeWarning)
else:
inline = FeinCMSInline
attrs['form'] = getattr(
content_type, 'feincms_item_editor_form', inline.form)
name = '%sFeinCMSInline' % content_type.__name__
# TODO: We generate a new class every time. Is that really wanted?
inline_class = type(str(name), (inline,), attrs)
inlines.append(inline_class)
return inlines | python | def get_feincms_inlines(self, model, request):
model._needs_content_types()
inlines = []
for content_type in model._feincms_content_types:
if not self.can_add_content(request, content_type):
continue
attrs = {
'__module__': model.__module__,
'model': content_type,
}
if hasattr(content_type, 'feincms_item_editor_inline'):
inline = content_type.feincms_item_editor_inline
attrs['form'] = inline.form
#if hasattr(content_type, 'feincms_item_editor_form'):
# warnings.warn(
# 'feincms_item_editor_form on %s is ignored because '
# 'feincms_item_editor_inline is set too' % content_type,
# RuntimeWarning)
else:
inline = FeinCMSInline
attrs['form'] = getattr(
content_type, 'feincms_item_editor_form', inline.form)
name = '%sFeinCMSInline' % content_type.__name__
# TODO: We generate a new class every time. Is that really wanted?
inline_class = type(str(name), (inline,), attrs)
inlines.append(inline_class)
return inlines | [
"def",
"get_feincms_inlines",
"(",
"self",
",",
"model",
",",
"request",
")",
":",
"model",
".",
"_needs_content_types",
"(",
")",
"inlines",
"=",
"[",
"]",
"for",
"content_type",
"in",
"model",
".",
"_feincms_content_types",
":",
"if",
"not",
"self",
".",
... | Generate genuine django inlines for registered content types. | [
"Generate",
"genuine",
"django",
"inlines",
"for",
"registered",
"content",
"types",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/admin.py#L49-L82 |
22,405 | django-leonardo/django-leonardo | leonardo/module/web/admin.py | PageAdmin.get_changeform_initial_data | def get_changeform_initial_data(self, request):
'''Copy initial data from parent'''
initial = super(PageAdmin, self).get_changeform_initial_data(request)
if ('translation_of' in request.GET):
original = self.model._tree_manager.get(
pk=request.GET.get('translation_of'))
initial['layout'] = original.layout
initial['theme'] = original.theme
initial['color_scheme'] = original.color_scheme
# optionaly translate title and make slug
old_lang = translation.get_language()
translation.activate(request.GET.get('language'))
title = _(original.title)
if title != original.title:
initial['title'] = title
initial['slug'] = slugify(title)
translation.activate(old_lang)
return initial | python | def get_changeform_initial_data(self, request):
'''Copy initial data from parent'''
initial = super(PageAdmin, self).get_changeform_initial_data(request)
if ('translation_of' in request.GET):
original = self.model._tree_manager.get(
pk=request.GET.get('translation_of'))
initial['layout'] = original.layout
initial['theme'] = original.theme
initial['color_scheme'] = original.color_scheme
# optionaly translate title and make slug
old_lang = translation.get_language()
translation.activate(request.GET.get('language'))
title = _(original.title)
if title != original.title:
initial['title'] = title
initial['slug'] = slugify(title)
translation.activate(old_lang)
return initial | [
"def",
"get_changeform_initial_data",
"(",
"self",
",",
"request",
")",
":",
"initial",
"=",
"super",
"(",
"PageAdmin",
",",
"self",
")",
".",
"get_changeform_initial_data",
"(",
"request",
")",
"if",
"(",
"'translation_of'",
"in",
"request",
".",
"GET",
")",
... | Copy initial data from parent | [
"Copy",
"initial",
"data",
"from",
"parent"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/admin.py#L84-L103 |
22,406 | django-leonardo/django-leonardo | leonardo/utils/package.py | install_package | def install_package(package, upgrade=True,
target=None):
"""Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successful.
"""
# Not using 'import pip; pip.main([])' because it breaks the logger
with INSTALL_LOCK:
if check_package_exists(package, target):
return True
_LOGGER.info('Attempting install of %s', package)
args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
if upgrade:
args.append('--upgrade')
if target:
args += ['--target', os.path.abspath(target)]
try:
return subprocess.call(args) == 0
except subprocess.SubprocessError:
_LOGGER.exception('Unable to install pacakge %s', package)
return False | python | def install_package(package, upgrade=True,
target=None):
# Not using 'import pip; pip.main([])' because it breaks the logger
with INSTALL_LOCK:
if check_package_exists(package, target):
return True
_LOGGER.info('Attempting install of %s', package)
args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
if upgrade:
args.append('--upgrade')
if target:
args += ['--target', os.path.abspath(target)]
try:
return subprocess.call(args) == 0
except subprocess.SubprocessError:
_LOGGER.exception('Unable to install pacakge %s', package)
return False | [
"def",
"install_package",
"(",
"package",
",",
"upgrade",
"=",
"True",
",",
"target",
"=",
"None",
")",
":",
"# Not using 'import pip; pip.main([])' because it breaks the logger",
"with",
"INSTALL_LOCK",
":",
"if",
"check_package_exists",
"(",
"package",
",",
"target",
... | Install a package on PyPi. Accepts pip compatible package strings.
Return boolean if install successful. | [
"Install",
"a",
"package",
"on",
"PyPi",
".",
"Accepts",
"pip",
"compatible",
"package",
"strings",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/package.py#L19-L41 |
22,407 | django-leonardo/django-leonardo | leonardo/utils/package.py | check_package_exists | def check_package_exists(package, lib_dir):
"""Check if a package is installed globally or in lib_dir.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req.
"""
try:
req = pkg_resources.Requirement.parse(package)
except ValueError:
# This is a zip file
req = pkg_resources.Requirement.parse(urlparse(package).fragment)
# Check packages from lib dir
if lib_dir is not None:
if any(dist in req for dist in
pkg_resources.find_distributions(lib_dir)):
return True
# Check packages from global + virtual environment
# pylint: disable=not-an-iterable
return any(dist in req for dist in pkg_resources.working_set) | python | def check_package_exists(package, lib_dir):
try:
req = pkg_resources.Requirement.parse(package)
except ValueError:
# This is a zip file
req = pkg_resources.Requirement.parse(urlparse(package).fragment)
# Check packages from lib dir
if lib_dir is not None:
if any(dist in req for dist in
pkg_resources.find_distributions(lib_dir)):
return True
# Check packages from global + virtual environment
# pylint: disable=not-an-iterable
return any(dist in req for dist in pkg_resources.working_set) | [
"def",
"check_package_exists",
"(",
"package",
",",
"lib_dir",
")",
":",
"try",
":",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"package",
")",
"except",
"ValueError",
":",
"# This is a zip file",
"req",
"=",
"pkg_resources",
".",
"Req... | Check if a package is installed globally or in lib_dir.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req. | [
"Check",
"if",
"a",
"package",
"is",
"installed",
"globally",
"or",
"in",
"lib_dir",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/package.py#L44-L64 |
22,408 | django-leonardo/django-leonardo | leonardo/views/ajax.py | AJAXMixin.render_widget | def render_widget(self, request, widget_id):
'''Returns rendered widget in JSON response'''
widget = get_widget_from_id(widget_id)
response = widget.render(**{'request': request})
return JsonResponse({'result': response, 'id': widget_id}) | python | def render_widget(self, request, widget_id):
'''Returns rendered widget in JSON response'''
widget = get_widget_from_id(widget_id)
response = widget.render(**{'request': request})
return JsonResponse({'result': response, 'id': widget_id}) | [
"def",
"render_widget",
"(",
"self",
",",
"request",
",",
"widget_id",
")",
":",
"widget",
"=",
"get_widget_from_id",
"(",
"widget_id",
")",
"response",
"=",
"widget",
".",
"render",
"(",
"*",
"*",
"{",
"'request'",
":",
"request",
"}",
")",
"return",
"J... | Returns rendered widget in JSON response | [
"Returns",
"rendered",
"widget",
"in",
"JSON",
"response"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L31-L38 |
22,409 | django-leonardo/django-leonardo | leonardo/views/ajax.py | AJAXMixin.render_region | def render_region(self, request):
'''Returns rendered region in JSON response'''
page = self.get_object()
try:
region = request.POST['region']
except KeyError:
region = request.GET['region']
request.query_string = None
from leonardo.utils.widgets import render_region
result = render_region(page=page, request=request, region=region)
return JsonResponse({'result': result, 'region': region}) | python | def render_region(self, request):
'''Returns rendered region in JSON response'''
page = self.get_object()
try:
region = request.POST['region']
except KeyError:
region = request.GET['region']
request.query_string = None
from leonardo.utils.widgets import render_region
result = render_region(page=page, request=request, region=region)
return JsonResponse({'result': result, 'region': region}) | [
"def",
"render_region",
"(",
"self",
",",
"request",
")",
":",
"page",
"=",
"self",
".",
"get_object",
"(",
")",
"try",
":",
"region",
"=",
"request",
".",
"POST",
"[",
"'region'",
"]",
"except",
"KeyError",
":",
"region",
"=",
"request",
".",
"GET",
... | Returns rendered region in JSON response | [
"Returns",
"rendered",
"region",
"in",
"JSON",
"response"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L40-L56 |
22,410 | django-leonardo/django-leonardo | leonardo/views/ajax.py | AJAXMixin.handle_ajax_method | def handle_ajax_method(self, request, method):
"""handle ajax methods and return serialized reponse
in the default state allows only authentificated users
- Depends on method parameter render whole region or single widget
- If widget_id is present then try to load this widget
and call method on them
- If class_name is present then try to load class
and then call static method on this class
- If class_name is present then try to load class
and if method_name == render_preview then
render widget preview without instance
"""
response = {}
def get_param(request, name):
try:
return request.POST[name]
except KeyError:
return request.GET.get(name, None)
widget_id = get_param(request, "widget_id")
class_name = get_param(request, "class_name")
if method in 'widget_content':
return self.render_widget(request, widget_id)
if method == 'region':
return self.render_region(request)
# handle methods called directly on widget
if widget_id:
widget = get_widget_from_id(widget_id)
try:
func = getattr(widget, method)
except AttributeError:
response["exception"] = "%s method is not implmented on %s" % (
method, widget)
else:
response["result"] = func(request)
elif class_name:
# handle calling classmethod without instance
try:
cls = get_model(*class_name.split('.'))
except Exception as e:
response["exception"] = str(e)
return JsonResponse(data=response)
if method == "render_preview":
# TODO: i think that we need only simple form
# for loading relations but maybe this would be need it
# custom_form_cls = getattr(
# cls, 'feincms_item_editor_form', None)
# if custom_form_cls:
# FormCls = modelform_factory(cls, form=custom_form_cls,
# exclude=('pk', 'id'))
FormCls = modelform_factory(cls, exclude=('pk', 'id'))
form = FormCls(request.POST)
if form.is_valid():
widget = cls(**form.cleaned_data)
request.frontend_editing = False
try:
content = widget.render(**{'request': request})
except Exception as e:
response['result'] = widget.handle_exception(request, e)
else:
response['result'] = content
response['id'] = widget_id
else:
response['result'] = form.errors
response['id'] = widget_id
else:
# standard method
try:
func = getattr(cls, method)
except Exception as e:
response["exception"] = str(e)
else:
response["result"] = func(request)
return JsonResponse(data=response) | python | def handle_ajax_method(self, request, method):
response = {}
def get_param(request, name):
try:
return request.POST[name]
except KeyError:
return request.GET.get(name, None)
widget_id = get_param(request, "widget_id")
class_name = get_param(request, "class_name")
if method in 'widget_content':
return self.render_widget(request, widget_id)
if method == 'region':
return self.render_region(request)
# handle methods called directly on widget
if widget_id:
widget = get_widget_from_id(widget_id)
try:
func = getattr(widget, method)
except AttributeError:
response["exception"] = "%s method is not implmented on %s" % (
method, widget)
else:
response["result"] = func(request)
elif class_name:
# handle calling classmethod without instance
try:
cls = get_model(*class_name.split('.'))
except Exception as e:
response["exception"] = str(e)
return JsonResponse(data=response)
if method == "render_preview":
# TODO: i think that we need only simple form
# for loading relations but maybe this would be need it
# custom_form_cls = getattr(
# cls, 'feincms_item_editor_form', None)
# if custom_form_cls:
# FormCls = modelform_factory(cls, form=custom_form_cls,
# exclude=('pk', 'id'))
FormCls = modelform_factory(cls, exclude=('pk', 'id'))
form = FormCls(request.POST)
if form.is_valid():
widget = cls(**form.cleaned_data)
request.frontend_editing = False
try:
content = widget.render(**{'request': request})
except Exception as e:
response['result'] = widget.handle_exception(request, e)
else:
response['result'] = content
response['id'] = widget_id
else:
response['result'] = form.errors
response['id'] = widget_id
else:
# standard method
try:
func = getattr(cls, method)
except Exception as e:
response["exception"] = str(e)
else:
response["result"] = func(request)
return JsonResponse(data=response) | [
"def",
"handle_ajax_method",
"(",
"self",
",",
"request",
",",
"method",
")",
":",
"response",
"=",
"{",
"}",
"def",
"get_param",
"(",
"request",
",",
"name",
")",
":",
"try",
":",
"return",
"request",
".",
"POST",
"[",
"name",
"]",
"except",
"KeyError... | handle ajax methods and return serialized reponse
in the default state allows only authentificated users
- Depends on method parameter render whole region or single widget
- If widget_id is present then try to load this widget
and call method on them
- If class_name is present then try to load class
and then call static method on this class
- If class_name is present then try to load class
and if method_name == render_preview then
render widget preview without instance | [
"handle",
"ajax",
"methods",
"and",
"return",
"serialized",
"reponse",
"in",
"the",
"default",
"state",
"allows",
"only",
"authentificated",
"users"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/ajax.py#L59-L160 |
22,411 | django-leonardo/django-leonardo | leonardo/templatetags/form_helpers.py | add_bootstrap_class | def add_bootstrap_class(field):
"""Add a "form-control" CSS class to the field's widget.
This is so that Bootstrap styles it properly.
"""
if not isinstance(field.field.widget, (
django.forms.widgets.CheckboxInput,
django.forms.widgets.CheckboxSelectMultiple,
django.forms.widgets.RadioSelect,
django.forms.widgets.FileInput,
str
)):
field_classes = set(field.field.widget.attrs.get('class', '').split())
field_classes.add('form-control')
field.field.widget.attrs['class'] = ' '.join(field_classes)
return field | python | def add_bootstrap_class(field):
if not isinstance(field.field.widget, (
django.forms.widgets.CheckboxInput,
django.forms.widgets.CheckboxSelectMultiple,
django.forms.widgets.RadioSelect,
django.forms.widgets.FileInput,
str
)):
field_classes = set(field.field.widget.attrs.get('class', '').split())
field_classes.add('form-control')
field.field.widget.attrs['class'] = ' '.join(field_classes)
return field | [
"def",
"add_bootstrap_class",
"(",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"field",
".",
"field",
".",
"widget",
",",
"(",
"django",
".",
"forms",
".",
"widgets",
".",
"CheckboxInput",
",",
"django",
".",
"forms",
".",
"widgets",
".",
"Checkbo... | Add a "form-control" CSS class to the field's widget.
This is so that Bootstrap styles it properly. | [
"Add",
"a",
"form",
"-",
"control",
"CSS",
"class",
"to",
"the",
"field",
"s",
"widget",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/templatetags/form_helpers.py#L20-L35 |
22,412 | django-leonardo/django-leonardo | leonardo/module/media/admin/clipboardadmin.py | ClipboardAdmin.ajax_upload | def ajax_upload(self, request, folder_id=None):
"""
receives an upload from the uploader. Receives only one file at the time.
"""
mimetype = "application/json" if request.is_ajax() else "text/html"
content_type_key = 'content_type'
response_params = {content_type_key: mimetype}
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
**response_params)
# check permissions
if folder and not folder.has_add_children_permission(request):
return HttpResponse(
json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
**response_params)
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# Get clipboad
# TODO: Deprecated/refactor
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in media_settings.MEDIA_FILE_MODELS:
FileSubClass = load_object(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
json_response = {
'thumbnail': file_obj.icons['32'],
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
return HttpResponse(json.dumps(json_response),
**response_params)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (form_errors,))
except UploadException as e:
return HttpResponse(json.dumps({'error': str(e)}),
**response_params) | python | def ajax_upload(self, request, folder_id=None):
mimetype = "application/json" if request.is_ajax() else "text/html"
content_type_key = 'content_type'
response_params = {content_type_key: mimetype}
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
**response_params)
# check permissions
if folder and not folder.has_add_children_permission(request):
return HttpResponse(
json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
**response_params)
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# Get clipboad
# TODO: Deprecated/refactor
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in media_settings.MEDIA_FILE_MODELS:
FileSubClass = load_object(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
json_response = {
'thumbnail': file_obj.icons['32'],
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
return HttpResponse(json.dumps(json_response),
**response_params)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (form_errors,))
except UploadException as e:
return HttpResponse(json.dumps({'error': str(e)}),
**response_params) | [
"def",
"ajax_upload",
"(",
"self",
",",
"request",
",",
"folder_id",
"=",
"None",
")",
":",
"mimetype",
"=",
"\"application/json\"",
"if",
"request",
".",
"is_ajax",
"(",
")",
"else",
"\"text/html\"",
"content_type_key",
"=",
"'content_type'",
"response_params",
... | receives an upload from the uploader. Receives only one file at the time. | [
"receives",
"an",
"upload",
"from",
"the",
"uploader",
".",
"Receives",
"only",
"one",
"file",
"at",
"the",
"time",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/admin/clipboardadmin.py#L62-L135 |
22,413 | django-leonardo/django-leonardo | leonardo/module/web/management/commands/sync_page_themes.py | Command.set_options | def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = False
self.verbosity = options['verbosity']
self.symlink = ""
self.clear = False
ignore_patterns = []
self.ignore_patterns = list(set(ignore_patterns))
self.page_themes_updated = 0
self.skins_updated = 0 | python | def set_options(self, **options):
self.interactive = False
self.verbosity = options['verbosity']
self.symlink = ""
self.clear = False
ignore_patterns = []
self.ignore_patterns = list(set(ignore_patterns))
self.page_themes_updated = 0
self.skins_updated = 0 | [
"def",
"set_options",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"interactive",
"=",
"False",
"self",
".",
"verbosity",
"=",
"options",
"[",
"'verbosity'",
"]",
"self",
".",
"symlink",
"=",
"\"\"",
"self",
".",
"clear",
"=",
"False",... | Set instance variables based on an options dict | [
"Set",
"instance",
"variables",
"based",
"on",
"an",
"options",
"dict"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/management/commands/sync_page_themes.py#L30-L41 |
22,414 | django-leonardo/django-leonardo | leonardo/module/web/management/commands/sync_page_themes.py | Command.collect | def collect(self):
"""
Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss
"""
self.ignore_patterns = [
'*.png', '*.jpg', '*.js', '*.gif', '*.ttf', '*.md', '*.rst',
'*.svg']
page_themes = PageTheme.objects.all()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
for t in page_themes:
static_path = 'themes/{0}'.format(t.name.split('/')[-1])
if static_path in path:
try:
page_theme = PageTheme.objects.get(id=t.id)
except PageTheme.DoesNotExist:
raise Exception(
"Run sync_themes before this command")
except Exception as e:
self.stdout.write(
"Cannot load {} into database original error: {}".format(t, e))
# find and load skins
skins_path = os.path.join(
storage.path('/'.join(path.split('/')[0:-1])))
for dirpath, skins, filenames in os.walk(skins_path):
for skin in [s for s in skins if s not in ['fonts']]:
for skin_dirpath, skins, filenames in os.walk(os.path.join(dirpath, skin)):
skin, created = PageColorScheme.objects.get_or_create(
theme=page_theme, label=skin, name=skin.title())
for f in filenames:
if 'styles' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as style_file:
skin.styles = style_file.read()
elif 'variables' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as variables_file:
skin.variables = variables_file.read()
skin.save()
self.skins_updated += 1
self.page_themes_updated += len(page_themes) | python | def collect(self):
self.ignore_patterns = [
'*.png', '*.jpg', '*.js', '*.gif', '*.ttf', '*.md', '*.rst',
'*.svg']
page_themes = PageTheme.objects.all()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
for t in page_themes:
static_path = 'themes/{0}'.format(t.name.split('/')[-1])
if static_path in path:
try:
page_theme = PageTheme.objects.get(id=t.id)
except PageTheme.DoesNotExist:
raise Exception(
"Run sync_themes before this command")
except Exception as e:
self.stdout.write(
"Cannot load {} into database original error: {}".format(t, e))
# find and load skins
skins_path = os.path.join(
storage.path('/'.join(path.split('/')[0:-1])))
for dirpath, skins, filenames in os.walk(skins_path):
for skin in [s for s in skins if s not in ['fonts']]:
for skin_dirpath, skins, filenames in os.walk(os.path.join(dirpath, skin)):
skin, created = PageColorScheme.objects.get_or_create(
theme=page_theme, label=skin, name=skin.title())
for f in filenames:
if 'styles' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as style_file:
skin.styles = style_file.read()
elif 'variables' in f:
with codecs.open(os.path.join(skin_dirpath, f)) as variables_file:
skin.variables = variables_file.read()
skin.save()
self.skins_updated += 1
self.page_themes_updated += len(page_themes) | [
"def",
"collect",
"(",
"self",
")",
":",
"self",
".",
"ignore_patterns",
"=",
"[",
"'*.png'",
",",
"'*.jpg'",
",",
"'*.js'",
",",
"'*.gif'",
",",
"'*.ttf'",
",",
"'*.md'",
",",
"'*.rst'",
",",
"'*.svg'",
"]",
"page_themes",
"=",
"PageTheme",
".",
"object... | Load and save ``PageColorScheme`` for every ``PageTheme``
.. code-block:: bash
static/themes/bootswatch/united/variables.scss
static/themes/bootswatch/united/styles.scss | [
"Load",
"and",
"save",
"PageColorScheme",
"for",
"every",
"PageTheme"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/management/commands/sync_page_themes.py#L43-L91 |
22,415 | django-leonardo/django-leonardo | leonardo/module/media/models/abstract.py | BaseImage.has_generic_permission | def has_generic_permission(self, request, permission_type):
"""
Return true if the current user has permission on this
image. Return the string 'ALL' if the user has all rights.
"""
user = request.user
if not user.is_authenticated():
return False
elif user.is_superuser:
return True
elif user == self.owner:
return True
elif self.folder:
return self.folder.has_generic_permission(request, permission_type)
else:
return False | python | def has_generic_permission(self, request, permission_type):
user = request.user
if not user.is_authenticated():
return False
elif user.is_superuser:
return True
elif user == self.owner:
return True
elif self.folder:
return self.folder.has_generic_permission(request, permission_type)
else:
return False | [
"def",
"has_generic_permission",
"(",
"self",
",",
"request",
",",
"permission_type",
")",
":",
"user",
"=",
"request",
".",
"user",
"if",
"not",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"False",
"elif",
"user",
".",
"is_superuser",
":",
"... | Return true if the current user has permission on this
image. Return the string 'ALL' if the user has all rights. | [
"Return",
"true",
"if",
"the",
"current",
"user",
"has",
"permission",
"on",
"this",
"image",
".",
"Return",
"the",
"string",
"ALL",
"if",
"the",
"user",
"has",
"all",
"rights",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/models/abstract.py#L101-L116 |
22,416 | django-leonardo/django-leonardo | leonardo/module/media/widget/mediagallery/models.py | MediaGalleryWidget.get_template_data | def get_template_data(self, request, *args, **kwargs):
'''Add image dimensions'''
# little tricky with vertical centering
dimension = int(self.get_size().split('x')[0])
data = {}
if dimension <= 356:
data['image_dimension'] = "row-md-13"
if self.get_template_name().name.split("/")[-1] == "directories.html":
data['directories'] = self.get_directories(request)
return data | python | def get_template_data(self, request, *args, **kwargs):
'''Add image dimensions'''
# little tricky with vertical centering
dimension = int(self.get_size().split('x')[0])
data = {}
if dimension <= 356:
data['image_dimension'] = "row-md-13"
if self.get_template_name().name.split("/")[-1] == "directories.html":
data['directories'] = self.get_directories(request)
return data | [
"def",
"get_template_data",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# little tricky with vertical centering",
"dimension",
"=",
"int",
"(",
"self",
".",
"get_size",
"(",
")",
".",
"split",
"(",
"'x'",
")",
"[",
... | Add image dimensions | [
"Add",
"image",
"dimensions"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/widget/mediagallery/models.py#L81-L95 |
22,417 | django-leonardo/django-leonardo | leonardo/decorators.py | _decorate_urlconf | def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):
'''Decorate all urlpatterns by specified decorator'''
if isinstance(urlpatterns, (list, tuple)):
for pattern in urlpatterns:
if getattr(pattern, 'callback', None):
pattern._callback = decorator(
pattern.callback, *args, **kwargs)
if getattr(pattern, 'url_patterns', []):
_decorate_urlconf(
pattern.url_patterns, decorator, *args, **kwargs)
else:
if getattr(urlpatterns, 'callback', None):
urlpatterns._callback = decorator(
urlpatterns.callback, *args, **kwargs) | python | def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):
'''Decorate all urlpatterns by specified decorator'''
if isinstance(urlpatterns, (list, tuple)):
for pattern in urlpatterns:
if getattr(pattern, 'callback', None):
pattern._callback = decorator(
pattern.callback, *args, **kwargs)
if getattr(pattern, 'url_patterns', []):
_decorate_urlconf(
pattern.url_patterns, decorator, *args, **kwargs)
else:
if getattr(urlpatterns, 'callback', None):
urlpatterns._callback = decorator(
urlpatterns.callback, *args, **kwargs) | [
"def",
"_decorate_urlconf",
"(",
"urlpatterns",
",",
"decorator",
"=",
"require_auth",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"urlpatterns",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"pattern",
"in",
"... | Decorate all urlpatterns by specified decorator | [
"Decorate",
"all",
"urlpatterns",
"by",
"specified",
"decorator"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/decorators.py#L53-L68 |
22,418 | django-leonardo/django-leonardo | leonardo/decorators.py | catch_result | def catch_result(task_func):
"""Catch printed result from Celery Task and return it in task response
"""
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
task_response = task_func(*args, **kwargs)
# catch
sys.stdout = orig_stdout
content.seek(0)
# propagate to the response
task_response['stdout'] = content.read()
return task_response
return dec | python | def catch_result(task_func):
@functools.wraps(task_func, assigned=available_attrs(task_func))
def dec(*args, **kwargs):
# inicialize
orig_stdout = sys.stdout
sys.stdout = content = StringIO()
task_response = task_func(*args, **kwargs)
# catch
sys.stdout = orig_stdout
content.seek(0)
# propagate to the response
task_response['stdout'] = content.read()
return task_response
return dec | [
"def",
"catch_result",
"(",
"task_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"task_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"task_func",
")",
")",
"def",
"dec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# inicialize",
... | Catch printed result from Celery Task and return it in task response | [
"Catch",
"printed",
"result",
"from",
"Celery",
"Task",
"and",
"return",
"it",
"in",
"task",
"response"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/decorators.py#L74-L90 |
22,419 | django-leonardo/django-leonardo | leonardo/utils/compress_patch.py | compress_monkey_patch | def compress_monkey_patch():
"""patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file
"""
from compressor.templatetags import compress as compress_tags
from compressor import base as compress_base
compress_base.Compressor.filter_input = filter_input
compress_base.Compressor.output = output
compress_base.Compressor.hunks = hunks
compress_base.Compressor.precompile = precompile
compress_tags.CompressorMixin.render_compressed = render_compressed
from django_pyscss import compressor as pyscss_compressor
pyscss_compressor.DjangoScssFilter.input = input | python | def compress_monkey_patch():
from compressor.templatetags import compress as compress_tags
from compressor import base as compress_base
compress_base.Compressor.filter_input = filter_input
compress_base.Compressor.output = output
compress_base.Compressor.hunks = hunks
compress_base.Compressor.precompile = precompile
compress_tags.CompressorMixin.render_compressed = render_compressed
from django_pyscss import compressor as pyscss_compressor
pyscss_compressor.DjangoScssFilter.input = input | [
"def",
"compress_monkey_patch",
"(",
")",
":",
"from",
"compressor",
".",
"templatetags",
"import",
"compress",
"as",
"compress_tags",
"from",
"compressor",
"import",
"base",
"as",
"compress_base",
"compress_base",
".",
"Compressor",
".",
"filter_input",
"=",
"filte... | patch all compress
we need access to variables from widget scss
for example we have::
/themes/bootswatch/cyborg/_variables
but only if is cyborg active for this reasone we need
dynamically append import to every scss file | [
"patch",
"all",
"compress"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L37-L62 |
22,420 | django-leonardo/django-leonardo | leonardo/utils/compress_patch.py | output | def output(self, mode='file', forced=False, context=None):
"""
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
"""
output = '\n'.join(self.filter_input(forced, context=context))
if not output:
return ''
if settings.COMPRESS_ENABLED or forced:
filtered_output = self.filter_output(output)
return self.handle_output(mode, filtered_output, forced)
return output | python | def output(self, mode='file', forced=False, context=None):
output = '\n'.join(self.filter_input(forced, context=context))
if not output:
return ''
if settings.COMPRESS_ENABLED or forced:
filtered_output = self.filter_output(output)
return self.handle_output(mode, filtered_output, forced)
return output | [
"def",
"output",
"(",
"self",
",",
"mode",
"=",
"'file'",
",",
"forced",
"=",
"False",
",",
"context",
"=",
"None",
")",
":",
"output",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"filter_input",
"(",
"forced",
",",
"context",
"=",
"context",
")",
... | The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly. | [
"The",
"general",
"output",
"method",
"override",
"in",
"subclass",
"if",
"you",
"need",
"to",
"do",
"any",
"custom",
"modification",
".",
"Calls",
"other",
"mode",
"specific",
"methods",
"or",
"simply",
"returns",
"the",
"content",
"directly",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L165-L180 |
22,421 | django-leonardo/django-leonardo | leonardo/utils/compress_patch.py | precompile | def precompile(self, content, kind=None, elem=None, filename=None,
charset=None, **kwargs):
"""
Processes file using a pre compiler.
This is the place where files like coffee script are processed.
"""
if not kind:
return False, content
attrs = self.parser.elem_attribs(elem)
mimetype = attrs.get("type", None)
if mimetype is None:
return False, content
filter_or_command = self.precompiler_mimetypes.get(mimetype)
if filter_or_command is None:
if mimetype in ("text/css", "text/javascript"):
return False, content
raise CompressorError("Couldn't find any precompiler in "
"COMPRESS_PRECOMPILERS setting for "
"mimetype '%s'." % mimetype)
mod_name, cls_name = get_mod_func(filter_or_command)
try:
mod = import_module(mod_name)
except (ImportError, TypeError):
filter = CachedCompilerFilter(
content=content, filter_type=self.type, filename=filename,
charset=charset, command=filter_or_command, mimetype=mimetype)
return True, filter.input(**kwargs)
try:
precompiler_class = getattr(mod, cls_name)
except AttributeError:
raise FilterDoesNotExist('Could not find "%s".' % filter_or_command)
filter = precompiler_class(
content, attrs=attrs, filter_type=self.type, charset=charset,
filename=filename, **kwargs)
return True, filter.input(**kwargs) | python | def precompile(self, content, kind=None, elem=None, filename=None,
charset=None, **kwargs):
if not kind:
return False, content
attrs = self.parser.elem_attribs(elem)
mimetype = attrs.get("type", None)
if mimetype is None:
return False, content
filter_or_command = self.precompiler_mimetypes.get(mimetype)
if filter_or_command is None:
if mimetype in ("text/css", "text/javascript"):
return False, content
raise CompressorError("Couldn't find any precompiler in "
"COMPRESS_PRECOMPILERS setting for "
"mimetype '%s'." % mimetype)
mod_name, cls_name = get_mod_func(filter_or_command)
try:
mod = import_module(mod_name)
except (ImportError, TypeError):
filter = CachedCompilerFilter(
content=content, filter_type=self.type, filename=filename,
charset=charset, command=filter_or_command, mimetype=mimetype)
return True, filter.input(**kwargs)
try:
precompiler_class = getattr(mod, cls_name)
except AttributeError:
raise FilterDoesNotExist('Could not find "%s".' % filter_or_command)
filter = precompiler_class(
content, attrs=attrs, filter_type=self.type, charset=charset,
filename=filename, **kwargs)
return True, filter.input(**kwargs) | [
"def",
"precompile",
"(",
"self",
",",
"content",
",",
"kind",
"=",
"None",
",",
"elem",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"charset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kind",
":",
"return",
"False",
",",
... | Processes file using a pre compiler.
This is the place where files like coffee script are processed. | [
"Processes",
"file",
"using",
"a",
"pre",
"compiler",
".",
"This",
"is",
"the",
"place",
"where",
"files",
"like",
"coffee",
"script",
"are",
"processed",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L194-L230 |
22,422 | frawau/aioblescan | aioblescan/aioblescan.py | MACAddr.decode | def decode(self,data):
"""Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes
"""
self.val=':'.join("%02x" % x for x in reversed(data[:6]))
return data[6:] | python | def decode(self,data):
self.val=':'.join("%02x" % x for x in reversed(data[:6]))
return data[6:] | [
"def",
"decode",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"val",
"=",
"':'",
".",
"join",
"(",
"\"%02x\"",
"%",
"x",
"for",
"x",
"in",
"reversed",
"(",
"data",
"[",
":",
"6",
"]",
")",
")",
"return",
"data",
"[",
"6",
":",
"]"
] | Decode the MAC address from a byte array.
This will take the first 6 bytes from data and transform them into a MAC address
string representation. This will be assigned to the attribute "val". It then returns
the data stream minus the bytes consumed
:param data: The data stream containing the value to decode at its head
:type data: bytes
:returns: The datastream minus the bytes consumed
:rtype: bytes | [
"Decode",
"the",
"MAC",
"address",
"from",
"a",
"byte",
"array",
"."
] | 02d12e90db3ee6df7be6513fec171f20dc533de3 | https://github.com/frawau/aioblescan/blob/02d12e90db3ee6df7be6513fec171f20dc533de3/aioblescan/aioblescan.py#L75-L88 |
22,423 | django-leonardo/django-leonardo | leonardo/templatetags/thumbnail.py | thumbnail | def thumbnail(parser, token):
'''
This template tag supports both syntax for declare thumbanil in template
'''
thumb = None
if SORL:
try:
thumb = sorl_thumb(parser, token)
except Exception:
thumb = False
if EASY and not thumb:
thumb = easy_thumb(parser, token)
return thumb | python | def thumbnail(parser, token):
'''
This template tag supports both syntax for declare thumbanil in template
'''
thumb = None
if SORL:
try:
thumb = sorl_thumb(parser, token)
except Exception:
thumb = False
if EASY and not thumb:
thumb = easy_thumb(parser, token)
return thumb | [
"def",
"thumbnail",
"(",
"parser",
",",
"token",
")",
":",
"thumb",
"=",
"None",
"if",
"SORL",
":",
"try",
":",
"thumb",
"=",
"sorl_thumb",
"(",
"parser",
",",
"token",
")",
"except",
"Exception",
":",
"thumb",
"=",
"False",
"if",
"EASY",
"and",
"not... | This template tag supports both syntax for declare thumbanil in template | [
"This",
"template",
"tag",
"supports",
"both",
"syntax",
"for",
"declare",
"thumbanil",
"in",
"template"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/templatetags/thumbnail.py#L18-L34 |
22,424 | django-leonardo/django-leonardo | leonardo/module/media/utils.py | handle_uploaded_file | def handle_uploaded_file(file, folder=None, is_public=True):
'''handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
'''
_folder = None
if folder and isinstance(folder, Folder):
_folder = folder
elif folder:
_folder, folder_created = Folder.objects.get_or_create(
name=folder)
for cls in MEDIA_MODELS:
if cls.matches_file_type(file.name):
obj, created = cls.objects.get_or_create(
original_filename=file.name,
file=file,
folder=_folder,
is_public=is_public)
if created:
return obj
return None | python | def handle_uploaded_file(file, folder=None, is_public=True):
'''handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
'''
_folder = None
if folder and isinstance(folder, Folder):
_folder = folder
elif folder:
_folder, folder_created = Folder.objects.get_or_create(
name=folder)
for cls in MEDIA_MODELS:
if cls.matches_file_type(file.name):
obj, created = cls.objects.get_or_create(
original_filename=file.name,
file=file,
folder=_folder,
is_public=is_public)
if created:
return obj
return None | [
"def",
"handle_uploaded_file",
"(",
"file",
",",
"folder",
"=",
"None",
",",
"is_public",
"=",
"True",
")",
":",
"_folder",
"=",
"None",
"if",
"folder",
"and",
"isinstance",
"(",
"folder",
",",
"Folder",
")",
":",
"_folder",
"=",
"folder",
"elif",
"folde... | handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean | [
"handle",
"uploaded",
"file",
"to",
"folder",
"match",
"first",
"media",
"type",
"and",
"create",
"media",
"object",
"and",
"returns",
"it"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/utils.py#L5-L33 |
22,425 | django-leonardo/django-leonardo | leonardo/module/media/utils.py | handle_uploaded_files | def handle_uploaded_files(files, folder=None, is_public=True):
'''handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean
'''
results = []
for f in files:
result = handle_uploaded_file(f, folder, is_public)
results.append(result)
return results | python | def handle_uploaded_files(files, folder=None, is_public=True):
'''handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean
'''
results = []
for f in files:
result = handle_uploaded_file(f, folder, is_public)
results.append(result)
return results | [
"def",
"handle_uploaded_files",
"(",
"files",
",",
"folder",
"=",
"None",
",",
"is_public",
"=",
"True",
")",
":",
"results",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"result",
"=",
"handle_uploaded_file",
"(",
"f",
",",
"folder",
",",
"is_public",... | handle uploaded files to folder
files: array of File objects or single object
folder: str or Folder isinstance
is_public: boolean | [
"handle",
"uploaded",
"files",
"to",
"folder"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/utils.py#L36-L48 |
22,426 | django-leonardo/django-leonardo | leonardo/module/media/server/views.py | serve_protected_file | def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
return server.serve(request, file_obj=file_obj.file, save_as=False) | python | def serve_protected_file(request, path):
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
return server.serve(request, file_obj=file_obj.file, save_as=False) | [
"def",
"serve_protected_file",
"(",
"request",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"try",
":",
"file_obj",
"=",
"File",
".",
"objects",
".",
"get",
"(",
"file",
"=",
"path",
")",
"except",
"File",
".",
"DoesNot... | Serve protected files to authenticated users with read permissions. | [
"Serve",
"protected",
"files",
"to",
"authenticated",
"users",
"with",
"read",
"permissions",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/server/views.py#L14-L28 |
22,427 | django-leonardo/django-leonardo | leonardo/module/media/server/views.py | serve_protected_thumbnail | def serve_protected_thumbnail(request, path):
"""
Serve protected thumbnails to authenticated users.
If the user doesn't have read permissions, redirect to a static image.
"""
source_path = thumbnail_to_original_filename(path)
if not source_path:
raise Http404('File not found')
try:
file_obj = File.objects.get(file=source_path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
try:
thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage)
return thumbnail_server.serve(request, thumbnail, save_as=False)
except Exception:
raise Http404('File not found %s' % path) | python | def serve_protected_thumbnail(request, path):
source_path = thumbnail_to_original_filename(path)
if not source_path:
raise Http404('File not found')
try:
file_obj = File.objects.get(file=source_path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_read_permission(request):
if settings.DEBUG:
raise PermissionDenied
else:
raise Http404('File not found %s' % path)
try:
thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage)
return thumbnail_server.serve(request, thumbnail, save_as=False)
except Exception:
raise Http404('File not found %s' % path) | [
"def",
"serve_protected_thumbnail",
"(",
"request",
",",
"path",
")",
":",
"source_path",
"=",
"thumbnail_to_original_filename",
"(",
"path",
")",
"if",
"not",
"source_path",
":",
"raise",
"Http404",
"(",
"'File not found'",
")",
"try",
":",
"file_obj",
"=",
"Fi... | Serve protected thumbnails to authenticated users.
If the user doesn't have read permissions, redirect to a static image. | [
"Serve",
"protected",
"thumbnails",
"to",
"authenticated",
"users",
".",
"If",
"the",
"user",
"doesn",
"t",
"have",
"read",
"permissions",
"redirect",
"to",
"a",
"static",
"image",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/server/views.py#L31-L52 |
22,428 | django-leonardo/django-leonardo | leonardo/base.py | Leonardo.get_app_modules | def get_app_modules(self, apps):
"""return array of imported leonardo modules for apps
"""
modules = getattr(self, "_modules", [])
if not modules:
from django.utils.module_loading import module_has_submodule
# Try importing a modules from the module package
package_string = '.'.join(['leonardo', 'module'])
for app in apps:
exc = '...'
try:
# check if is not full app
_app = import_module(app)
except Exception as e:
_app = False
exc = e
if module_has_submodule(
import_module(package_string), app) or _app:
if _app:
mod = _app
else:
mod = import_module('.{0}'.format(app), package_string)
if mod:
modules.append(mod)
continue
warnings.warn('%s was skipped because %s ' % (app, exc))
self._modules = modules
return self._modules | python | def get_app_modules(self, apps):
modules = getattr(self, "_modules", [])
if not modules:
from django.utils.module_loading import module_has_submodule
# Try importing a modules from the module package
package_string = '.'.join(['leonardo', 'module'])
for app in apps:
exc = '...'
try:
# check if is not full app
_app = import_module(app)
except Exception as e:
_app = False
exc = e
if module_has_submodule(
import_module(package_string), app) or _app:
if _app:
mod = _app
else:
mod = import_module('.{0}'.format(app), package_string)
if mod:
modules.append(mod)
continue
warnings.warn('%s was skipped because %s ' % (app, exc))
self._modules = modules
return self._modules | [
"def",
"get_app_modules",
"(",
"self",
",",
"apps",
")",
":",
"modules",
"=",
"getattr",
"(",
"self",
",",
"\"_modules\"",
",",
"[",
"]",
")",
"if",
"not",
"modules",
":",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodu... | return array of imported leonardo modules for apps | [
"return",
"array",
"of",
"imported",
"leonardo",
"modules",
"for",
"apps"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/base.py#L47-L80 |
22,429 | django-leonardo/django-leonardo | leonardo/base.py | Leonardo.urlpatterns | def urlpatterns(self):
'''load and decorate urls from all modules
then store it as cached property for less loading
'''
if not hasattr(self, '_urlspatterns'):
urlpatterns = []
# load all urls
# support .urls file and urls_conf = 'elephantblog.urls' on default module
# decorate all url patterns if is not explicitly excluded
for mod in leonardo.modules:
# TODO this not work
if is_leonardo_module(mod):
conf = get_conf_from_module(mod)
if module_has_submodule(mod, 'urls'):
urls_mod = import_module('.urls', mod.__name__)
if hasattr(urls_mod, 'urlpatterns'):
# if not public decorate all
if conf['public']:
urlpatterns += urls_mod.urlpatterns
else:
_decorate_urlconf(urls_mod.urlpatterns,
require_auth)
urlpatterns += urls_mod.urlpatterns
# avoid circural dependency
# TODO use our loaded modules instead this property
from django.conf import settings
for urls_conf, conf in six.iteritems(getattr(settings, 'MODULE_URLS', {})):
# is public ?
try:
if conf['is_public']:
urlpatterns += \
patterns('',
url(r'', include(urls_conf)),
)
else:
_decorate_urlconf(
url(r'', include(urls_conf)),
require_auth)
urlpatterns += patterns('',
url(r'', include(urls_conf)))
except Exception as e:
raise Exception('raised %s during loading %s' %
(str(e), urls_conf))
self._urlpatterns = urlpatterns
return self._urlpatterns | python | def urlpatterns(self):
'''load and decorate urls from all modules
then store it as cached property for less loading
'''
if not hasattr(self, '_urlspatterns'):
urlpatterns = []
# load all urls
# support .urls file and urls_conf = 'elephantblog.urls' on default module
# decorate all url patterns if is not explicitly excluded
for mod in leonardo.modules:
# TODO this not work
if is_leonardo_module(mod):
conf = get_conf_from_module(mod)
if module_has_submodule(mod, 'urls'):
urls_mod = import_module('.urls', mod.__name__)
if hasattr(urls_mod, 'urlpatterns'):
# if not public decorate all
if conf['public']:
urlpatterns += urls_mod.urlpatterns
else:
_decorate_urlconf(urls_mod.urlpatterns,
require_auth)
urlpatterns += urls_mod.urlpatterns
# avoid circural dependency
# TODO use our loaded modules instead this property
from django.conf import settings
for urls_conf, conf in six.iteritems(getattr(settings, 'MODULE_URLS', {})):
# is public ?
try:
if conf['is_public']:
urlpatterns += \
patterns('',
url(r'', include(urls_conf)),
)
else:
_decorate_urlconf(
url(r'', include(urls_conf)),
require_auth)
urlpatterns += patterns('',
url(r'', include(urls_conf)))
except Exception as e:
raise Exception('raised %s during loading %s' %
(str(e), urls_conf))
self._urlpatterns = urlpatterns
return self._urlpatterns | [
"def",
"urlpatterns",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_urlspatterns'",
")",
":",
"urlpatterns",
"=",
"[",
"]",
"# load all urls",
"# support .urls file and urls_conf = 'elephantblog.urls' on default module",
"# decorate all url patterns if... | load and decorate urls from all modules
then store it as cached property for less loading | [
"load",
"and",
"decorate",
"urls",
"from",
"all",
"modules",
"then",
"store",
"it",
"as",
"cached",
"property",
"for",
"less",
"loading"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/base.py#L83-L132 |
22,430 | django-leonardo/django-leonardo | leonardo/module/web/widget/application/reverse.py | cycle_app_reverse_cache | def cycle_app_reverse_cache(*args, **kwargs):
"""Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys"""
value = '%07x' % (SystemRandom().randint(0, 0x10000000))
cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value)
return value | python | def cycle_app_reverse_cache(*args, **kwargs):
value = '%07x' % (SystemRandom().randint(0, 0x10000000))
cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value)
return value | [
"def",
"cycle_app_reverse_cache",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"'%07x'",
"%",
"(",
"SystemRandom",
"(",
")",
".",
"randint",
"(",
"0",
",",
"0x10000000",
")",
")",
"cache",
".",
"set",
"(",
"APP_REVERSE_CACHE_GENERAT... | Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys | [
"Does",
"not",
"really",
"empty",
"the",
"cache",
";",
"instead",
"it",
"adds",
"a",
"random",
"element",
"to",
"the",
"cache",
"key",
"generation",
"which",
"guarantees",
"that",
"the",
"cache",
"does",
"not",
"yet",
"contain",
"values",
"for",
"all",
"ne... | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widget/application/reverse.py#L31-L37 |
22,431 | django-leonardo/django-leonardo | leonardo/module/web/widget/application/reverse.py | reverse | def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent !
"""
if not urlconf:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view = viewname
else:
parts = viewname.split(':')
parts.reverse()
view = parts[0]
path = parts[1:]
resolved_path = []
ns_pattern = ''
while path:
ns = path.pop()
# Lookup the name to see if it could be an app identifier
try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver
if current_app and current_app in app_list:
# If we are reversing for a particular app,
# use that namespace
ns = current_app
elif ns not in app_list:
# The name isn't shared by one of the instances
# (i.e., the default) so just pick the first instance
# as the default.
ns = app_list[0]
except KeyError:
pass
try:
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError as key:
for urlconf, config in six.iteritems(
ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG):
partials = viewname.split(':')
app = partials[0]
partials = partials[1:]
# check if namespace is same as app name and try resolve
if urlconf.split(".")[-1] == app:
try:
return app_reverse(
':'.join(partials),
urlconf, args=args, kwargs=kwargs,
current_app=current_app)
except NoReverseMatch:
pass
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
(key, ':'.join(resolved_path)))
else:
raise NoReverseMatch("%s is not a registered namespace" %
key)
if ns_pattern:
resolver = get_ns_resolver(ns_pattern, resolver)
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) | python | def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
if not urlconf:
urlconf = get_urlconf()
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
prefix = get_script_prefix()
if not isinstance(viewname, six.string_types):
view = viewname
else:
parts = viewname.split(':')
parts.reverse()
view = parts[0]
path = parts[1:]
resolved_path = []
ns_pattern = ''
while path:
ns = path.pop()
# Lookup the name to see if it could be an app identifier
try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver
if current_app and current_app in app_list:
# If we are reversing for a particular app,
# use that namespace
ns = current_app
elif ns not in app_list:
# The name isn't shared by one of the instances
# (i.e., the default) so just pick the first instance
# as the default.
ns = app_list[0]
except KeyError:
pass
try:
extra, resolver = resolver.namespace_dict[ns]
resolved_path.append(ns)
ns_pattern = ns_pattern + extra
except KeyError as key:
for urlconf, config in six.iteritems(
ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG):
partials = viewname.split(':')
app = partials[0]
partials = partials[1:]
# check if namespace is same as app name and try resolve
if urlconf.split(".")[-1] == app:
try:
return app_reverse(
':'.join(partials),
urlconf, args=args, kwargs=kwargs,
current_app=current_app)
except NoReverseMatch:
pass
if resolved_path:
raise NoReverseMatch(
"%s is not a registered namespace inside '%s'" %
(key, ':'.join(resolved_path)))
else:
raise NoReverseMatch("%s is not a registered namespace" %
key)
if ns_pattern:
resolver = get_ns_resolver(ns_pattern, resolver)
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) | [
"def",
"reverse",
"(",
"viewname",
",",
"urlconf",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"current_app",
"=",
"None",
")",
":",
"if",
"not",
"urlconf",
":",
"urlconf",
"=",
"get_urlconf",
"(",
")",
"resolver",
"=",
"g... | monkey patched reverse
path supports easy patching 3rd party urls
if 3rd party app has namespace for example ``catalogue`` and
you create FeinCMS plugin with same name as this namespace reverse
returns url from ApplicationContent ! | [
"monkey",
"patched",
"reverse"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widget/application/reverse.py#L128-L209 |
22,432 | django-leonardo/django-leonardo | leonardo/module/web/processors/page.py | add_page_if_missing | def add_page_if_missing(request):
"""
Returns ``feincms_page`` for request.
"""
try:
page = Page.objects.for_request(request, best_match=True)
return {
'leonardo_page': page,
# DEPRECATED
'feincms_page': page,
}
except Page.DoesNotExist:
return {} | python | def add_page_if_missing(request):
try:
page = Page.objects.for_request(request, best_match=True)
return {
'leonardo_page': page,
# DEPRECATED
'feincms_page': page,
}
except Page.DoesNotExist:
return {} | [
"def",
"add_page_if_missing",
"(",
"request",
")",
":",
"try",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"for_request",
"(",
"request",
",",
"best_match",
"=",
"True",
")",
"return",
"{",
"'leonardo_page'",
":",
"page",
",",
"# DEPRECATED",
"'feincms_pa... | Returns ``feincms_page`` for request. | [
"Returns",
"feincms_page",
"for",
"request",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/page.py#L5-L18 |
22,433 | django-leonardo/django-leonardo | leonardo/views/defaults.py | render_in_page | def render_in_page(request, template):
"""return rendered template in standalone mode or ``False``
"""
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
slug = None
try:
body = render_to_string(template, RequestContext(request, {
'request_path': request.path,
'feincms_page': page,
'slug': slug,
'standalone': True}))
response = http.HttpResponseNotFound(
body, content_type=CONTENT_TYPE)
except TemplateDoesNotExist:
response = False
return response
return False | python | def render_in_page(request, template):
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
slug = None
try:
body = render_to_string(template, RequestContext(request, {
'request_path': request.path,
'feincms_page': page,
'slug': slug,
'standalone': True}))
response = http.HttpResponseNotFound(
body, content_type=CONTENT_TYPE)
except TemplateDoesNotExist:
response = False
return response
return False | [
"def",
"render_in_page",
"(",
"request",
",",
"template",
")",
":",
"from",
"leonardo",
".",
"module",
".",
"web",
".",
"models",
"import",
"Page",
"page",
"=",
"request",
".",
"leonardo_page",
"if",
"hasattr",
"(",
"request",
",",
"'leonardo_page'",
")",
... | return rendered template in standalone mode or ``False`` | [
"return",
"rendered",
"template",
"in",
"standalone",
"mode",
"or",
"False"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L11-L38 |
22,434 | django-leonardo/django-leonardo | leonardo/views/defaults.py | page_not_found | def page_not_found(request, template_name='404.html'):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
response = render_in_page(request, template_name)
if response:
return response
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(RequestContext(
request, {'request_path': request.path}))
return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE) | python | def page_not_found(request, template_name='404.html'):
response = render_in_page(request, template_name)
if response:
return response
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(RequestContext(
request, {'request_path': request.path}))
return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE) | [
"def",
"page_not_found",
"(",
"request",
",",
"template_name",
"=",
"'404.html'",
")",
":",
"response",
"=",
"render_in_page",
"(",
"request",
",",
"template_name",
")",
"if",
"response",
":",
"return",
"response",
"template",
"=",
"Template",
"(",
"'<h1>Not Fou... | Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/') | [
"Default",
"404",
"handler",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L45-L64 |
22,435 | django-leonardo/django-leonardo | leonardo/views/defaults.py | bad_request | def bad_request(request, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render(Context({}))) | python | def bad_request(request, template_name='400.html'):
response = render_in_page(request, template_name)
if response:
return response
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
return http.HttpResponseBadRequest(template.render(Context({}))) | [
"def",
"bad_request",
"(",
"request",
",",
"template_name",
"=",
"'400.html'",
")",
":",
"response",
"=",
"render_in_page",
"(",
"request",
",",
"template_name",
")",
"if",
"response",
":",
"return",
"response",
"try",
":",
"template",
"=",
"loader",
".",
"g... | 400 error handler.
Templates: :template:`400.html`
Context: None | [
"400",
"error",
"handler",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L89-L106 |
22,436 | django-leonardo/django-leonardo | leonardo/module/web/middlewares/horizon.py | HorizonMiddleware.process_response | def process_response(self, request, response):
"""Convert HttpResponseRedirect to HttpResponse if request is via ajax
to allow ajax request to redirect url
"""
if request.is_ajax() and hasattr(request, 'horizon'):
queued_msgs = request.horizon['async_messages']
if type(response) == http.HttpResponseRedirect:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
# if response['location'].startswith(settings.LOGOUT_URL):
# redirect_response = http.HttpResponse(status=401)
# # This header is used for handling the logout in JS
# redirect_response['logout'] = True
# if self.logout_reason is not None:
# utils.add_logout_reason(
# request, redirect_response, self.logout_reason)
# else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = set(('max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'))
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in six.iteritems(response.cookies):
cookie_kwargs = dict((
(key, value) for key, value in six.iteritems(cookie)
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self.copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response | python | def process_response(self, request, response):
if request.is_ajax() and hasattr(request, 'horizon'):
queued_msgs = request.horizon['async_messages']
if type(response) == http.HttpResponseRedirect:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
# if response['location'].startswith(settings.LOGOUT_URL):
# redirect_response = http.HttpResponse(status=401)
# # This header is used for handling the logout in JS
# redirect_response['logout'] = True
# if self.logout_reason is not None:
# utils.add_logout_reason(
# request, redirect_response, self.logout_reason)
# else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = set(('max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'))
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in six.iteritems(response.cookies):
cookie_kwargs = dict((
(key, value) for key, value in six.iteritems(cookie)
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self.copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
"and",
"hasattr",
"(",
"request",
",",
"'horizon'",
")",
":",
"queued_msgs",
"=",
"request",
".",
"horizon",
"[",
"'async_messages... | Convert HttpResponseRedirect to HttpResponse if request is via ajax
to allow ajax request to redirect url | [
"Convert",
"HttpResponseRedirect",
"to",
"HttpResponse",
"if",
"request",
"is",
"via",
"ajax",
"to",
"allow",
"ajax",
"request",
"to",
"redirect",
"url"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/middlewares/horizon.py#L96-L143 |
22,437 | django-leonardo/django-leonardo | leonardo/module/web/middlewares/horizon.py | HorizonMiddleware.process_exception | def process_exception(self, request, exception):
"""Catches internal Horizon exception classes such as NotAuthorized,
NotFound and Http302 and handles them gracefully.
"""
if isinstance(exception, (exceptions.NotAuthorized,
exceptions.NotAuthenticated)):
auth_url = settings.LOGIN_URL
next_url = None
# prevent submiting forms after login and
# use http referer
if request.method in ("POST", "PUT"):
referrer = request.META.get('HTTP_REFERER')
if referrer and is_safe_url(referrer, request.get_host()):
next_url = referrer
if not next_url:
next_url = iri_to_uri(request.get_full_path())
if next_url != auth_url:
field_name = REDIRECT_FIELD_NAME
else:
field_name = None
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
logout_reason = _("Unauthorized. Please try logging in again.")
utils.add_logout_reason(request, response, logout_reason)
# delete messages, created in get_data() method
# since we are going to redirect user to the login page
response.delete_cookie('messages')
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location) | python | def process_exception(self, request, exception):
if isinstance(exception, (exceptions.NotAuthorized,
exceptions.NotAuthenticated)):
auth_url = settings.LOGIN_URL
next_url = None
# prevent submiting forms after login and
# use http referer
if request.method in ("POST", "PUT"):
referrer = request.META.get('HTTP_REFERER')
if referrer and is_safe_url(referrer, request.get_host()):
next_url = referrer
if not next_url:
next_url = iri_to_uri(request.get_full_path())
if next_url != auth_url:
field_name = REDIRECT_FIELD_NAME
else:
field_name = None
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
logout_reason = _("Unauthorized. Please try logging in again.")
utils.add_logout_reason(request, response, logout_reason)
# delete messages, created in get_data() method
# since we are going to redirect user to the login page
response.delete_cookie('messages')
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location) | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"exceptions",
".",
"NotAuthorized",
",",
"exceptions",
".",
"NotAuthenticated",
")",
")",
":",
"auth_url",
"=",
"settings",
"... | Catches internal Horizon exception classes such as NotAuthorized,
NotFound and Http302 and handles them gracefully. | [
"Catches",
"internal",
"Horizon",
"exception",
"classes",
"such",
"as",
"NotAuthorized",
"NotFound",
"and",
"Http302",
"and",
"handles",
"them",
"gracefully",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/middlewares/horizon.py#L145-L195 |
22,438 | django-leonardo/django-leonardo | leonardo/module/media/views.py | canonical | def canonical(request, uploaded_at, file_id):
"""
Redirect to the current url of a public file
"""
filer_file = get_object_or_404(File, pk=file_id, is_public=True)
if (uploaded_at != filer_file.uploaded_at.strftime('%s') or
not filer_file.file):
raise Http404('No %s matches the given query.' %
File._meta.object_name)
return redirect(filer_file.url) | python | def canonical(request, uploaded_at, file_id):
filer_file = get_object_or_404(File, pk=file_id, is_public=True)
if (uploaded_at != filer_file.uploaded_at.strftime('%s') or
not filer_file.file):
raise Http404('No %s matches the given query.' %
File._meta.object_name)
return redirect(filer_file.url) | [
"def",
"canonical",
"(",
"request",
",",
"uploaded_at",
",",
"file_id",
")",
":",
"filer_file",
"=",
"get_object_or_404",
"(",
"File",
",",
"pk",
"=",
"file_id",
",",
"is_public",
"=",
"True",
")",
"if",
"(",
"uploaded_at",
"!=",
"filer_file",
".",
"upload... | Redirect to the current url of a public file | [
"Redirect",
"to",
"the",
"current",
"url",
"of",
"a",
"public",
"file"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/views.py#L77-L86 |
22,439 | django-leonardo/django-leonardo | leonardo/exceptions.py | check_message | def check_message(keywords, message):
"""Checks an exception for given keywords and raises a new ``ActionError``
with the desired message if the keywords are found. This allows selective
control over API error messages.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
if set(str(exc_value).split(" ")).issuperset(set(keywords)):
exc_value.message = message
raise | python | def check_message(keywords, message):
exc_type, exc_value, exc_traceback = sys.exc_info()
if set(str(exc_value).split(" ")).issuperset(set(keywords)):
exc_value.message = message
raise | [
"def",
"check_message",
"(",
"keywords",
",",
"message",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"set",
"(",
"str",
"(",
"exc_value",
")",
".",
"split",
"(",
"\" \"",
")",
")",
".",
"... | Checks an exception for given keywords and raises a new ``ActionError``
with the desired message if the keywords are found. This allows selective
control over API error messages. | [
"Checks",
"an",
"exception",
"for",
"given",
"keywords",
"and",
"raises",
"a",
"new",
"ActionError",
"with",
"the",
"desired",
"message",
"if",
"the",
"keywords",
"are",
"found",
".",
"This",
"allows",
"selective",
"control",
"over",
"API",
"error",
"messages"... | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/exceptions.py#L142-L150 |
22,440 | django-leonardo/django-leonardo | leonardo/module/web/page/forms.py | SwitchableFormFieldMixin.get_switched_form_field_attrs | def get_switched_form_field_attrs(self, prefix, input_type, name):
"""Creates attribute dicts for the switchable theme form
"""
attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}
attributes['data-' + prefix + 'field-' + input_type] = name
return attributes | python | def get_switched_form_field_attrs(self, prefix, input_type, name):
attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'}
attributes['data-' + prefix + 'field-' + input_type] = name
return attributes | [
"def",
"get_switched_form_field_attrs",
"(",
"self",
",",
"prefix",
",",
"input_type",
",",
"name",
")",
":",
"attributes",
"=",
"{",
"'class'",
":",
"'switched'",
",",
"'data-switch-on'",
":",
"prefix",
"+",
"'field'",
"}",
"attributes",
"[",
"'data-'",
"+",
... | Creates attribute dicts for the switchable theme form | [
"Creates",
"attribute",
"dicts",
"for",
"the",
"switchable",
"theme",
"form"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/forms.py#L23-L28 |
22,441 | django-leonardo/django-leonardo | leonardo/module/web/page/forms.py | PageCreateForm.clean_slug | def clean_slug(self):
"""slug title if is not provided
"""
slug = self.cleaned_data.get('slug', None)
if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
slug = slugify(self.cleaned_data['title'])
return slug | python | def clean_slug(self):
slug = self.cleaned_data.get('slug', None)
if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
slug = slugify(self.cleaned_data['title'])
return slug | [
"def",
"clean_slug",
"(",
"self",
")",
":",
"slug",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'slug'",
",",
"None",
")",
"if",
"slug",
"is",
"None",
"or",
"len",
"(",
"slug",
")",
"==",
"0",
"and",
"'title'",
"in",
"self",
".",
"cleaned_d... | slug title if is not provided | [
"slug",
"title",
"if",
"is",
"not",
"provided"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/page/forms.py#L90-L96 |
22,442 | django-leonardo/django-leonardo | leonardo/module/web/widgets/utils.py | get_widget_from_id | def get_widget_from_id(id):
"""returns widget object by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[0], res[1])
obj = model_cls.objects.get(parent=res[2], id=res[3])
except:
obj = None
return obj | python | def get_widget_from_id(id):
res = id.split('-')
try:
model_cls = apps.get_model(res[0], res[1])
obj = model_cls.objects.get(parent=res[2], id=res[3])
except:
obj = None
return obj | [
"def",
"get_widget_from_id",
"(",
"id",
")",
":",
"res",
"=",
"id",
".",
"split",
"(",
"'-'",
")",
"try",
":",
"model_cls",
"=",
"apps",
".",
"get_model",
"(",
"res",
"[",
"0",
"]",
",",
"res",
"[",
"1",
"]",
")",
"obj",
"=",
"model_cls",
".",
... | returns widget object by id
example web-htmltextwidget-2-2 | [
"returns",
"widget",
"object",
"by",
"id"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/utils.py#L4-L16 |
22,443 | django-leonardo/django-leonardo | leonardo/module/web/widgets/utils.py | get_widget_class_from_id | def get_widget_class_from_id(id):
"""returns widget class by id
example web-htmltextwidget-2-2
"""
res = id.split('-')
try:
model_cls = apps.get_model(res[1], res[2])
except:
model_cls = None
return model_cls | python | def get_widget_class_from_id(id):
res = id.split('-')
try:
model_cls = apps.get_model(res[1], res[2])
except:
model_cls = None
return model_cls | [
"def",
"get_widget_class_from_id",
"(",
"id",
")",
":",
"res",
"=",
"id",
".",
"split",
"(",
"'-'",
")",
"try",
":",
"model_cls",
"=",
"apps",
".",
"get_model",
"(",
"res",
"[",
"1",
"]",
",",
"res",
"[",
"2",
"]",
")",
"except",
":",
"model_cls",
... | returns widget class by id
example web-htmltextwidget-2-2 | [
"returns",
"widget",
"class",
"by",
"id"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/widgets/utils.py#L19-L30 |
22,444 | django-leonardo/django-leonardo | leonardo/module/web/processors/edit.py | frontendediting_request_processor | def frontendediting_request_processor(page, request):
"""
Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions.
"""
if 'frontend_editing' not in request.GET:
return
response = HttpResponseRedirect(request.path)
if request.user.has_module_perms('page'):
if 'frontend_editing' in request.GET:
try:
enable_fe = int(request.GET['frontend_editing']) > 0
except ValueError:
enable_fe = False
if enable_fe:
response.set_cookie(str('frontend_editing'), enable_fe)
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
# Redirect to cleanup URLs
return response | python | def frontendediting_request_processor(page, request):
if 'frontend_editing' not in request.GET:
return
response = HttpResponseRedirect(request.path)
if request.user.has_module_perms('page'):
if 'frontend_editing' in request.GET:
try:
enable_fe = int(request.GET['frontend_editing']) > 0
except ValueError:
enable_fe = False
if enable_fe:
response.set_cookie(str('frontend_editing'), enable_fe)
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
clear_cache()
else:
response.delete_cookie(str('frontend_editing'))
# Redirect to cleanup URLs
return response | [
"def",
"frontendediting_request_processor",
"(",
"page",
",",
"request",
")",
":",
"if",
"'frontend_editing'",
"not",
"in",
"request",
".",
"GET",
":",
"return",
"response",
"=",
"HttpResponseRedirect",
"(",
"request",
".",
"path",
")",
"if",
"request",
".",
"... | Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions. | [
"Sets",
"the",
"frontend",
"editing",
"state",
"in",
"the",
"cookie",
"depending",
"on",
"the",
"frontend_editing",
"GET",
"parameter",
"and",
"the",
"user",
"s",
"permissions",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/processors/edit.py#L11-L40 |
22,445 | django-leonardo/django-leonardo | leonardo/module/web/__init__.py | Default.extra_context | def extra_context(self):
"""Add site_name to context
"""
from django.conf import settings
return {
"site_name": (lambda r: settings.LEONARDO_SITE_NAME
if getattr(settings, 'LEONARDO_SITE_NAME', '') != ''
else settings.SITE_NAME),
"debug": lambda r: settings.TEMPLATE_DEBUG
} | python | def extra_context(self):
from django.conf import settings
return {
"site_name": (lambda r: settings.LEONARDO_SITE_NAME
if getattr(settings, 'LEONARDO_SITE_NAME', '') != ''
else settings.SITE_NAME),
"debug": lambda r: settings.TEMPLATE_DEBUG
} | [
"def",
"extra_context",
"(",
"self",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"return",
"{",
"\"site_name\"",
":",
"(",
"lambda",
"r",
":",
"settings",
".",
"LEONARDO_SITE_NAME",
"if",
"getattr",
"(",
"settings",
",",
"'LEONARDO_SITE_NAME... | Add site_name to context | [
"Add",
"site_name",
"to",
"context"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/web/__init__.py#L113-L123 |
22,446 | django-leonardo/django-leonardo | leonardo/conf/base.py | ModuleConfig.get_property | def get_property(self, key):
"""Expect Django Conf property"""
_key = DJANGO_CONF[key]
return getattr(self, _key, CONF_SPEC[_key]) | python | def get_property(self, key):
_key = DJANGO_CONF[key]
return getattr(self, _key, CONF_SPEC[_key]) | [
"def",
"get_property",
"(",
"self",
",",
"key",
")",
":",
"_key",
"=",
"DJANGO_CONF",
"[",
"key",
"]",
"return",
"getattr",
"(",
"self",
",",
"_key",
",",
"CONF_SPEC",
"[",
"_key",
"]",
")"
] | Expect Django Conf property | [
"Expect",
"Django",
"Conf",
"property"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L21-L24 |
22,447 | django-leonardo/django-leonardo | leonardo/conf/base.py | ModuleConfig.needs_sync | def needs_sync(self):
"""Indicates whater module needs templates, static etc."""
affected_attributes = [
'css_files', 'js_files',
'scss_files', 'widgets']
for attr in affected_attributes:
if len(getattr(self, attr)) > 0:
return True
return False | python | def needs_sync(self):
affected_attributes = [
'css_files', 'js_files',
'scss_files', 'widgets']
for attr in affected_attributes:
if len(getattr(self, attr)) > 0:
return True
return False | [
"def",
"needs_sync",
"(",
"self",
")",
":",
"affected_attributes",
"=",
"[",
"'css_files'",
",",
"'js_files'",
",",
"'scss_files'",
",",
"'widgets'",
"]",
"for",
"attr",
"in",
"affected_attributes",
":",
"if",
"len",
"(",
"getattr",
"(",
"self",
",",
"attr",... | Indicates whater module needs templates, static etc. | [
"Indicates",
"whater",
"module",
"needs",
"templates",
"static",
"etc",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L60-L70 |
22,448 | django-leonardo/django-leonardo | leonardo/conf/base.py | LeonardoConfig.get_attr | def get_attr(self, name, default=None, fail_silently=True):
"""try extra context
"""
try:
return getattr(self, name)
except KeyError:
extra_context = getattr(self, "extra_context")
if name in extra_context:
value = extra_context[name]
if callable(value):
return value(request=None)
return default | python | def get_attr(self, name, default=None, fail_silently=True):
try:
return getattr(self, name)
except KeyError:
extra_context = getattr(self, "extra_context")
if name in extra_context:
value = extra_context[name]
if callable(value):
return value(request=None)
return default | [
"def",
"get_attr",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"fail_silently",
"=",
"True",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
",",
"name",
")",
"except",
"KeyError",
":",
"extra_context",
"=",
"getattr",
"(",
"sel... | try extra context | [
"try",
"extra",
"context"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/conf/base.py#L93-L107 |
22,449 | django-leonardo/django-leonardo | leonardo/utils/templates.py | find_all_templates | def find_all_templates(pattern='*.html', ignore_private=True):
"""
Finds all Django templates matching given glob in all TEMPLATE_LOADERS
:param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
to match
.. important:: At the moment egg loader is not supported.
"""
templates = []
template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
for loader_name in template_loaders:
module, klass = loader_name.rsplit('.', 1)
if loader_name in (
'django.template.loaders.app_directories.Loader',
'django.template.loaders.filesystem.Loader',
):
loader_class = getattr(import_module(module), klass)
if getattr(loader_class, '_accepts_engine_in_init', False):
loader = loader_class(Engine.get_default())
else:
loader = loader_class()
for dir in loader.get_template_sources(''):
for root, dirnames, filenames in os.walk(dir):
for basename in filenames:
if ignore_private and basename.startswith("_"):
continue
filename = os.path.join(root, basename)
rel_filename = filename[len(dir)+1:]
if fnmatch.fnmatch(filename, pattern) or \
fnmatch.fnmatch(basename, pattern) or \
fnmatch.fnmatch(rel_filename, pattern):
templates.append(rel_filename)
else:
LOGGER.debug('%s is not supported' % loader_name)
return sorted(set(templates)) | python | def find_all_templates(pattern='*.html', ignore_private=True):
templates = []
template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
for loader_name in template_loaders:
module, klass = loader_name.rsplit('.', 1)
if loader_name in (
'django.template.loaders.app_directories.Loader',
'django.template.loaders.filesystem.Loader',
):
loader_class = getattr(import_module(module), klass)
if getattr(loader_class, '_accepts_engine_in_init', False):
loader = loader_class(Engine.get_default())
else:
loader = loader_class()
for dir in loader.get_template_sources(''):
for root, dirnames, filenames in os.walk(dir):
for basename in filenames:
if ignore_private and basename.startswith("_"):
continue
filename = os.path.join(root, basename)
rel_filename = filename[len(dir)+1:]
if fnmatch.fnmatch(filename, pattern) or \
fnmatch.fnmatch(basename, pattern) or \
fnmatch.fnmatch(rel_filename, pattern):
templates.append(rel_filename)
else:
LOGGER.debug('%s is not supported' % loader_name)
return sorted(set(templates)) | [
"def",
"find_all_templates",
"(",
"pattern",
"=",
"'*.html'",
",",
"ignore_private",
"=",
"True",
")",
":",
"templates",
"=",
"[",
"]",
"template_loaders",
"=",
"flatten_template_loaders",
"(",
"settings",
".",
"TEMPLATE_LOADERS",
")",
"for",
"loader_name",
"in",
... | Finds all Django templates matching given glob in all TEMPLATE_LOADERS
:param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
to match
.. important:: At the moment egg loader is not supported. | [
"Finds",
"all",
"Django",
"templates",
"matching",
"given",
"glob",
"in",
"all",
"TEMPLATE_LOADERS"
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/templates.py#L40-L75 |
22,450 | django-leonardo/django-leonardo | leonardo/utils/templates.py | flatten_template_loaders | def flatten_template_loaders(templates):
"""
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
"""
for loader in templates:
if not isinstance(loader, string_types):
for subloader in flatten_template_loaders(loader):
yield subloader
else:
yield loader | python | def flatten_template_loaders(templates):
for loader in templates:
if not isinstance(loader, string_types):
for subloader in flatten_template_loaders(loader):
yield subloader
else:
yield loader | [
"def",
"flatten_template_loaders",
"(",
"templates",
")",
":",
"for",
"loader",
"in",
"templates",
":",
"if",
"not",
"isinstance",
"(",
"loader",
",",
"string_types",
")",
":",
"for",
"subloader",
"in",
"flatten_template_loaders",
"(",
"loader",
")",
":",
"yie... | Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression | [
"Given",
"a",
"collection",
"of",
"template",
"loaders",
"unwrap",
"them",
"into",
"one",
"flat",
"iterable",
"."
] | 4b933e1792221a13b4028753d5f1d3499b0816d4 | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/templates.py#L78-L91 |
22,451 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/file.py | SeekableFileProxy.seek | def seek(self, offset, whence=os.SEEK_SET):
"""Sets the file's current position.
:param offset: the offset to set
:type offset: :class:`numbers.Integral`
:param whence: see the docs of :meth:`file.seek()`.
default is :const:`os.SEEK_SET`
"""
self.wrapped.seek(offset, whence) | python | def seek(self, offset, whence=os.SEEK_SET):
self.wrapped.seek(offset, whence) | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"self",
".",
"wrapped",
".",
"seek",
"(",
"offset",
",",
"whence",
")"
] | Sets the file's current position.
:param offset: the offset to set
:type offset: :class:`numbers.Integral`
:param whence: see the docs of :meth:`file.seek()`.
default is :const:`os.SEEK_SET` | [
"Sets",
"the",
"file",
"s",
"current",
"position",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/file.py#L138-L147 |
22,452 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/store.py | Store.put_file | def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
"""Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object identifier number of the image to put
:type object_id: :class:`numbers.Integral`
:param width: the width of the image to put
:type width: :class:`numbers.Integral`
:param height: the height of the image to put
:type height: :class:`numbers.Integral`
:param mimetype: the mimetype of the image to put
e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:param reproducible: :const:`True` only if it's reproducible by
computing e.g. resized thumbnails.
:const:`False` if it cannot be reproduced
e.g. original images
:type reproducible: :class:`bool`
.. note::
This is an abstract method which has to be implemented
(overridden) by subclasses.
It's not for consumers but implementations, so consumers
should use :meth:`store()` method instead of this.
"""
raise NotImplementedError('put_file() has to be implemented') | python | def put_file(self, file, object_type, object_id, width, height, mimetype,
reproducible):
raise NotImplementedError('put_file() has to be implemented') | [
"def",
"put_file",
"(",
"self",
",",
"file",
",",
"object_type",
",",
"object_id",
",",
"width",
",",
"height",
",",
"mimetype",
",",
"reproducible",
")",
":",
"raise",
"NotImplementedError",
"(",
"'put_file() has to be implemented'",
")"
] | Puts the ``file`` of the image.
:param file: the image file to put
:type file: file-like object, :class:`file`
:param object_type: the object type of the image to put
e.g. ``'comics.cover'``
:type object_type: :class:`str`
:param object_id: the object identifier number of the image to put
:type object_id: :class:`numbers.Integral`
:param width: the width of the image to put
:type width: :class:`numbers.Integral`
:param height: the height of the image to put
:type height: :class:`numbers.Integral`
:param mimetype: the mimetype of the image to put
e.g. ``'image/jpeg'``
:type mimetype: :class:`str`
:param reproducible: :const:`True` only if it's reproducible by
computing e.g. resized thumbnails.
:const:`False` if it cannot be reproduced
e.g. original images
:type reproducible: :class:`bool`
.. note::
This is an abstract method which has to be implemented
(overridden) by subclasses.
It's not for consumers but implementations, so consumers
should use :meth:`store()` method instead of this. | [
"Puts",
"the",
"file",
"of",
"the",
"image",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L29-L62 |
22,453 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/store.py | Store.delete | def delete(self, image):
"""Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
self.delete_file(image.object_type, image.object_id,
image.width, image.height, image.mimetype) | python | def delete(self, image):
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
self.delete_file(image.object_type, image.object_id,
image.width, image.height, image.mimetype) | [
"def",
"delete",
"(",
"self",
",",
"image",
")",
":",
"from",
".",
"entity",
"import",
"Image",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
")",
":",
"raise",
"TypeError",
"(",
"'image must be a sqlalchemy_imageattach.entity.'",
"'Image instance, not '"... | Delete the file of the given ``image``.
:param image: the image to delete
:type image: :class:`sqlalchemy_imageattach.entity.Image` | [
"Delete",
"the",
"file",
"of",
"the",
"given",
"image",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L167-L179 |
22,454 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/store.py | Store.locate | def locate(self, image):
"""Gets the URL of the given ``image``.
:param image: the image to get its url
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:returns: the url of the image
:rtype: :class:`str`
"""
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
url = self.get_url(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
if '?' in url:
fmt = '{0}&_ts={1}'
else:
fmt = '{0}?_ts={1}'
return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f')) | python | def locate(self, image):
from .entity import Image
if not isinstance(image, Image):
raise TypeError('image must be a sqlalchemy_imageattach.entity.'
'Image instance, not ' + repr(image))
url = self.get_url(image.object_type, image.object_id,
image.width, image.height, image.mimetype)
if '?' in url:
fmt = '{0}&_ts={1}'
else:
fmt = '{0}?_ts={1}'
return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f')) | [
"def",
"locate",
"(",
"self",
",",
"image",
")",
":",
"from",
".",
"entity",
"import",
"Image",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
")",
":",
"raise",
"TypeError",
"(",
"'image must be a sqlalchemy_imageattach.entity.'",
"'Image instance, not '"... | Gets the URL of the given ``image``.
:param image: the image to get its url
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:returns: the url of the image
:rtype: :class:`str` | [
"Gets",
"the",
"URL",
"of",
"the",
"given",
"image",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L256-L275 |
22,455 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | Image.identity_attributes | def identity_attributes(cls):
"""A list of the names of primary key fields.
:returns: A list of the names of primary key fields
:rtype: :class:`typing.Sequence`\ [:class:`str`]
.. versionadded:: 1.0.0
"""
columns = inspect(cls).primary_key
names = [c.name for c in columns if c.name not in ('width', 'height')]
return names | python | def identity_attributes(cls):
columns = inspect(cls).primary_key
names = [c.name for c in columns if c.name not in ('width', 'height')]
return names | [
"def",
"identity_attributes",
"(",
"cls",
")",
":",
"columns",
"=",
"inspect",
"(",
"cls",
")",
".",
"primary_key",
"names",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"columns",
"if",
"c",
".",
"name",
"not",
"in",
"(",
"'width'",
",",
"'height'"... | A list of the names of primary key fields.
:returns: A list of the names of primary key fields
:rtype: :class:`typing.Sequence`\ [:class:`str`]
.. versionadded:: 1.0.0 | [
"A",
"list",
"of",
"the",
"names",
"of",
"primary",
"key",
"fields",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L215-L226 |
22,456 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | Image.make_blob | def make_blob(self, store=current_store):
"""Gets the byte string of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the binary data of the image
:rtype: :class:`str`
"""
with self.open_file(store) as f:
return f.read() | python | def make_blob(self, store=current_store):
with self.open_file(store) as f:
return f.read() | [
"def",
"make_blob",
"(",
"self",
",",
"store",
"=",
"current_store",
")",
":",
"with",
"self",
".",
"open_file",
"(",
"store",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Gets the byte string of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the binary data of the image
:rtype: :class:`str` | [
"Gets",
"the",
"byte",
"string",
"of",
"the",
"image",
"from",
"the",
"store",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L275-L287 |
22,457 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | Image.locate | def locate(self, store=current_store):
"""Gets the URL of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the url of the image
:rtype: :class:`str`
"""
if not isinstance(store, Store):
raise TypeError('store must be an instance of '
'sqlalchemy_imageattach.store.Store, not ' +
repr(store))
return store.locate(self) | python | def locate(self, store=current_store):
if not isinstance(store, Store):
raise TypeError('store must be an instance of '
'sqlalchemy_imageattach.store.Store, not ' +
repr(store))
return store.locate(self) | [
"def",
"locate",
"(",
"self",
",",
"store",
"=",
"current_store",
")",
":",
"if",
"not",
"isinstance",
"(",
"store",
",",
"Store",
")",
":",
"raise",
"TypeError",
"(",
"'store must be an instance of '",
"'sqlalchemy_imageattach.store.Store, not '",
"+",
"repr",
"(... | Gets the URL of the image from the ``store``.
:param store: the storage which contains the image.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:returns: the url of the image
:rtype: :class:`str` | [
"Gets",
"the",
"URL",
"of",
"the",
"image",
"from",
"the",
"store",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L323-L338 |
22,458 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | BaseImageQuery._original_images | def _original_images(self, **kwargs):
"""A list of the original images.
:returns: A list of the original images.
:rtype: :class:`typing.Sequence`\ [:class:`Image`]
"""
def test(image):
if not image.original:
return False
for filter, value in kwargs.items():
if getattr(image, filter) != value:
return False
return True
if Session.object_session(self.instance) is None:
images = []
for image, store in self._stored_images:
if test(image):
images.append(image)
state = instance_state(self.instance)
try:
added = state.committed_state[self.attr.key].added_items
except KeyError:
pass
else:
for image in added:
if test(image):
images.append(image)
if self.session:
for image in self.session.new:
if test(image):
images.append(image)
else:
query = self.filter_by(original=True, **kwargs)
images = query.all()
return images | python | def _original_images(self, **kwargs):
def test(image):
if not image.original:
return False
for filter, value in kwargs.items():
if getattr(image, filter) != value:
return False
return True
if Session.object_session(self.instance) is None:
images = []
for image, store in self._stored_images:
if test(image):
images.append(image)
state = instance_state(self.instance)
try:
added = state.committed_state[self.attr.key].added_items
except KeyError:
pass
else:
for image in added:
if test(image):
images.append(image)
if self.session:
for image in self.session.new:
if test(image):
images.append(image)
else:
query = self.filter_by(original=True, **kwargs)
images = query.all()
return images | [
"def",
"_original_images",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"test",
"(",
"image",
")",
":",
"if",
"not",
"image",
".",
"original",
":",
"return",
"False",
"for",
"filter",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
... | A list of the original images.
:returns: A list of the original images.
:rtype: :class:`typing.Sequence`\ [:class:`Image`] | [
"A",
"list",
"of",
"the",
"original",
"images",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L457-L494 |
22,459 | dahlia/sqlalchemy-imageattach | sqlalchemy_imageattach/entity.py | BaseImageSet.from_file | def from_file(self, file, store=current_store,
extra_args=None, extra_kwargs=None):
"""Stores the ``file`` for the image into the ``store``.
:param file: the readable file of the image
:type file: file-like object, :class:`file`
:param store: the storage to store the file.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:param extra_args: additional arguments to pass to the model's
constructor.
:type extra_args: :class:`collections.abc.Sequence`
:param extra_kwargs: additional keyword arguments to pass to the
model's constructor.
:type extra_kwargs: :class:`typing.Mapping`\ [:class:`str`,
:class:`object`]
:returns: the created image instance
:rtype: :class:`Image`
.. versionadded:: 1.0.0
The ``extra_args`` and ``extra_kwargs`` options.
"""
if isinstance(file, cgi.FieldStorage):
file = file.file
data = io.BytesIO()
shutil.copyfileobj(file, data)
data.seek(0)
return self.from_raw_file(data, store, original=True,
extra_args=extra_args,
extra_kwargs=extra_kwargs) | python | def from_file(self, file, store=current_store,
extra_args=None, extra_kwargs=None):
if isinstance(file, cgi.FieldStorage):
file = file.file
data = io.BytesIO()
shutil.copyfileobj(file, data)
data.seek(0)
return self.from_raw_file(data, store, original=True,
extra_args=extra_args,
extra_kwargs=extra_kwargs) | [
"def",
"from_file",
"(",
"self",
",",
"file",
",",
"store",
"=",
"current_store",
",",
"extra_args",
"=",
"None",
",",
"extra_kwargs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"cgi",
".",
"FieldStorage",
")",
":",
"file",
"=",
"file... | Stores the ``file`` for the image into the ``store``.
:param file: the readable file of the image
:type file: file-like object, :class:`file`
:param store: the storage to store the file.
:data:`~sqlalchemy_imageattach.context.current_store`
by default
:type store: :class:`~sqlalchemy_imageattach.store.Store`
:param extra_args: additional arguments to pass to the model's
constructor.
:type extra_args: :class:`collections.abc.Sequence`
:param extra_kwargs: additional keyword arguments to pass to the
model's constructor.
:type extra_kwargs: :class:`typing.Mapping`\ [:class:`str`,
:class:`object`]
:returns: the created image instance
:rtype: :class:`Image`
.. versionadded:: 1.0.0
The ``extra_args`` and ``extra_kwargs`` options. | [
"Stores",
"the",
"file",
"for",
"the",
"image",
"into",
"the",
"store",
"."
] | b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8 | https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L655-L688 |
22,460 | benmoran56/esper | esper.py | World.clear_database | def clear_database(self) -> None:
"""Remove all Entities and Components from the World."""
self._next_entity_id = 0
self._dead_entities.clear()
self._components.clear()
self._entities.clear()
self.clear_cache() | python | def clear_database(self) -> None:
self._next_entity_id = 0
self._dead_entities.clear()
self._components.clear()
self._entities.clear()
self.clear_cache() | [
"def",
"clear_database",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_next_entity_id",
"=",
"0",
"self",
".",
"_dead_entities",
".",
"clear",
"(",
")",
"self",
".",
"_components",
".",
"clear",
"(",
")",
"self",
".",
"_entities",
".",
"clear",
"... | Remove all Entities and Components from the World. | [
"Remove",
"all",
"Entities",
"and",
"Components",
"from",
"the",
"World",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L46-L52 |
22,461 | benmoran56/esper | esper.py | World.add_processor | def add_processor(self, processor_instance: Processor, priority=0) -> None:
"""Add a Processor instance to the World.
:param processor_instance: An instance of a Processor,
subclassed from the Processor class
:param priority: A higher number is processed first.
"""
assert issubclass(processor_instance.__class__, Processor)
processor_instance.priority = priority
processor_instance.world = self
self._processors.append(processor_instance)
self._processors.sort(key=lambda proc: proc.priority, reverse=True) | python | def add_processor(self, processor_instance: Processor, priority=0) -> None:
assert issubclass(processor_instance.__class__, Processor)
processor_instance.priority = priority
processor_instance.world = self
self._processors.append(processor_instance)
self._processors.sort(key=lambda proc: proc.priority, reverse=True) | [
"def",
"add_processor",
"(",
"self",
",",
"processor_instance",
":",
"Processor",
",",
"priority",
"=",
"0",
")",
"->",
"None",
":",
"assert",
"issubclass",
"(",
"processor_instance",
".",
"__class__",
",",
"Processor",
")",
"processor_instance",
".",
"priority"... | Add a Processor instance to the World.
:param processor_instance: An instance of a Processor,
subclassed from the Processor class
:param priority: A higher number is processed first. | [
"Add",
"a",
"Processor",
"instance",
"to",
"the",
"World",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L54-L65 |
22,462 | benmoran56/esper | esper.py | World.remove_processor | def remove_processor(self, processor_type: Processor) -> None:
"""Remove a Processor from the World, by type.
:param processor_type: The class type of the Processor to remove.
"""
for processor in self._processors:
if type(processor) == processor_type:
processor.world = None
self._processors.remove(processor) | python | def remove_processor(self, processor_type: Processor) -> None:
for processor in self._processors:
if type(processor) == processor_type:
processor.world = None
self._processors.remove(processor) | [
"def",
"remove_processor",
"(",
"self",
",",
"processor_type",
":",
"Processor",
")",
"->",
"None",
":",
"for",
"processor",
"in",
"self",
".",
"_processors",
":",
"if",
"type",
"(",
"processor",
")",
"==",
"processor_type",
":",
"processor",
".",
"world",
... | Remove a Processor from the World, by type.
:param processor_type: The class type of the Processor to remove. | [
"Remove",
"a",
"Processor",
"from",
"the",
"World",
"by",
"type",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L67-L75 |
22,463 | benmoran56/esper | esper.py | World.get_processor | def get_processor(self, processor_type: Type[P]) -> P:
"""Get a Processor instance, by type.
This method returns a Processor instance by type. This could be
useful in certain situations, such as wanting to call a method on a
Processor, from within another Processor.
:param processor_type: The type of the Processor you wish to retrieve.
:return: A Processor instance that has previously been added to the World.
"""
for processor in self._processors:
if type(processor) == processor_type:
return processor | python | def get_processor(self, processor_type: Type[P]) -> P:
for processor in self._processors:
if type(processor) == processor_type:
return processor | [
"def",
"get_processor",
"(",
"self",
",",
"processor_type",
":",
"Type",
"[",
"P",
"]",
")",
"->",
"P",
":",
"for",
"processor",
"in",
"self",
".",
"_processors",
":",
"if",
"type",
"(",
"processor",
")",
"==",
"processor_type",
":",
"return",
"processor... | Get a Processor instance, by type.
This method returns a Processor instance by type. This could be
useful in certain situations, such as wanting to call a method on a
Processor, from within another Processor.
:param processor_type: The type of the Processor you wish to retrieve.
:return: A Processor instance that has previously been added to the World. | [
"Get",
"a",
"Processor",
"instance",
"by",
"type",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L77-L89 |
22,464 | benmoran56/esper | esper.py | World.create_entity | def create_entity(self, *components) -> int:
"""Create a new Entity.
This method returns an Entity ID, which is just a plain integer.
You can optionally pass one or more Component instances to be
assigned to the Entity.
:param components: Optional components to be assigned to the
entity on creation.
:return: The next Entity ID in sequence.
"""
self._next_entity_id += 1
# TODO: duplicate add_component code here for performance
for component in components:
self.add_component(self._next_entity_id, component)
# self.clear_cache()
return self._next_entity_id | python | def create_entity(self, *components) -> int:
self._next_entity_id += 1
# TODO: duplicate add_component code here for performance
for component in components:
self.add_component(self._next_entity_id, component)
# self.clear_cache()
return self._next_entity_id | [
"def",
"create_entity",
"(",
"self",
",",
"*",
"components",
")",
"->",
"int",
":",
"self",
".",
"_next_entity_id",
"+=",
"1",
"# TODO: duplicate add_component code here for performance",
"for",
"component",
"in",
"components",
":",
"self",
".",
"add_component",
"("... | Create a new Entity.
This method returns an Entity ID, which is just a plain integer.
You can optionally pass one or more Component instances to be
assigned to the Entity.
:param components: Optional components to be assigned to the
entity on creation.
:return: The next Entity ID in sequence. | [
"Create",
"a",
"new",
"Entity",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L91-L109 |
22,465 | benmoran56/esper | esper.py | World.delete_entity | def delete_entity(self, entity: int, immediate=False) -> None:
"""Delete an Entity from the World.
Delete an Entity and all of it's assigned Component instances from
the world. By default, Entity deletion is delayed until the next call
to *World.process*. You can request immediate deletion, however, by
passing the "immediate=True" parameter. This should generally not be
done during Entity iteration (calls to World.get_component/s).
Raises a KeyError if the given entity does not exist in the database.
:param entity: The Entity ID you wish to delete.
:param immediate: If True, delete the Entity immediately.
"""
if immediate:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity]
self.clear_cache()
else:
self._dead_entities.add(entity) | python | def delete_entity(self, entity: int, immediate=False) -> None:
if immediate:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity]
self.clear_cache()
else:
self._dead_entities.add(entity) | [
"def",
"delete_entity",
"(",
"self",
",",
"entity",
":",
"int",
",",
"immediate",
"=",
"False",
")",
"->",
"None",
":",
"if",
"immediate",
":",
"for",
"component_type",
"in",
"self",
".",
"_entities",
"[",
"entity",
"]",
":",
"self",
".",
"_components",
... | Delete an Entity from the World.
Delete an Entity and all of it's assigned Component instances from
the world. By default, Entity deletion is delayed until the next call
to *World.process*. You can request immediate deletion, however, by
passing the "immediate=True" parameter. This should generally not be
done during Entity iteration (calls to World.get_component/s).
Raises a KeyError if the given entity does not exist in the database.
:param entity: The Entity ID you wish to delete.
:param immediate: If True, delete the Entity immediately. | [
"Delete",
"an",
"Entity",
"from",
"the",
"World",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L111-L135 |
22,466 | benmoran56/esper | esper.py | World.component_for_entity | def component_for_entity(self, entity: int, component_type: Type[C]) -> C:
"""Retrieve a Component instance for a specific Entity.
Retrieve a Component instance for a specific Entity. In some cases,
it may be necessary to access a specific Component instance.
For example: directly modifying a Component to handle user input.
Raises a KeyError if the given Entity and Component do not exist.
:param entity: The Entity ID to retrieve the Component for.
:param component_type: The Component instance you wish to retrieve.
:return: The Component instance requested for the given Entity ID.
"""
return self._entities[entity][component_type] | python | def component_for_entity(self, entity: int, component_type: Type[C]) -> C:
return self._entities[entity][component_type] | [
"def",
"component_for_entity",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_type",
":",
"Type",
"[",
"C",
"]",
")",
"->",
"C",
":",
"return",
"self",
".",
"_entities",
"[",
"entity",
"]",
"[",
"component_type",
"]"
] | Retrieve a Component instance for a specific Entity.
Retrieve a Component instance for a specific Entity. In some cases,
it may be necessary to access a specific Component instance.
For example: directly modifying a Component to handle user input.
Raises a KeyError if the given Entity and Component do not exist.
:param entity: The Entity ID to retrieve the Component for.
:param component_type: The Component instance you wish to retrieve.
:return: The Component instance requested for the given Entity ID. | [
"Retrieve",
"a",
"Component",
"instance",
"for",
"a",
"specific",
"Entity",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L137-L149 |
22,467 | benmoran56/esper | esper.py | World.components_for_entity | def components_for_entity(self, entity: int) -> Tuple[C, ...]:
"""Retrieve all Components for a specific Entity, as a Tuple.
Retrieve all Components for a specific Entity. The method is probably
not appropriate to use in your Processors, but might be useful for
saving state, or passing specific Components between World instances.
Unlike most other methods, this returns all of the Components as a
Tuple in one batch, instead of returning a Generator for iteration.
Raises a KeyError if the given entity does not exist in the database.
:param entity: The Entity ID to retrieve the Components for.
:return: A tuple of all Component instances that have been
assigned to the passed Entity ID.
"""
return tuple(self._entities[entity].values()) | python | def components_for_entity(self, entity: int) -> Tuple[C, ...]:
return tuple(self._entities[entity].values()) | [
"def",
"components_for_entity",
"(",
"self",
",",
"entity",
":",
"int",
")",
"->",
"Tuple",
"[",
"C",
",",
"...",
"]",
":",
"return",
"tuple",
"(",
"self",
".",
"_entities",
"[",
"entity",
"]",
".",
"values",
"(",
")",
")"
] | Retrieve all Components for a specific Entity, as a Tuple.
Retrieve all Components for a specific Entity. The method is probably
not appropriate to use in your Processors, but might be useful for
saving state, or passing specific Components between World instances.
Unlike most other methods, this returns all of the Components as a
Tuple in one batch, instead of returning a Generator for iteration.
Raises a KeyError if the given entity does not exist in the database.
:param entity: The Entity ID to retrieve the Components for.
:return: A tuple of all Component instances that have been
assigned to the passed Entity ID. | [
"Retrieve",
"all",
"Components",
"for",
"a",
"specific",
"Entity",
"as",
"a",
"Tuple",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L151-L165 |
22,468 | benmoran56/esper | esper.py | World.has_component | def has_component(self, entity: int, component_type: Any) -> bool:
"""Check if a specific Entity has a Component of a certain type.
:param entity: The Entity you are querying.
:param component_type: The type of Component to check for.
:return: True if the Entity has a Component of this type,
otherwise False
"""
return component_type in self._entities[entity] | python | def has_component(self, entity: int, component_type: Any) -> bool:
return component_type in self._entities[entity] | [
"def",
"has_component",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_type",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"component_type",
"in",
"self",
".",
"_entities",
"[",
"entity",
"]"
] | Check if a specific Entity has a Component of a certain type.
:param entity: The Entity you are querying.
:param component_type: The type of Component to check for.
:return: True if the Entity has a Component of this type,
otherwise False | [
"Check",
"if",
"a",
"specific",
"Entity",
"has",
"a",
"Component",
"of",
"a",
"certain",
"type",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L167-L175 |
22,469 | benmoran56/esper | esper.py | World.add_component | def add_component(self, entity: int, component_instance: Any) -> None:
"""Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the Component with.
:param component_instance: A Component instance.
"""
component_type = type(component_instance)
if component_type not in self._components:
self._components[component_type] = set()
self._components[component_type].add(entity)
if entity not in self._entities:
self._entities[entity] = {}
self._entities[entity][component_type] = component_instance
self.clear_cache() | python | def add_component(self, entity: int, component_instance: Any) -> None:
component_type = type(component_instance)
if component_type not in self._components:
self._components[component_type] = set()
self._components[component_type].add(entity)
if entity not in self._entities:
self._entities[entity] = {}
self._entities[entity][component_type] = component_instance
self.clear_cache() | [
"def",
"add_component",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_instance",
":",
"Any",
")",
"->",
"None",
":",
"component_type",
"=",
"type",
"(",
"component_instance",
")",
"if",
"component_type",
"not",
"in",
"self",
".",
"_components",
":"... | Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the Component with.
:param component_instance: A Component instance. | [
"Add",
"a",
"new",
"Component",
"instance",
"to",
"an",
"Entity",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L177-L197 |
22,470 | benmoran56/esper | esper.py | World.remove_component | def remove_component(self, entity: int, component_type: Any) -> int:
"""Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Entity enemy_a.
Raises a KeyError if either the given entity or Component type does
not exist in the database.
:param entity: The Entity to remove the Component from.
:param component_type: The type of the Component to remove.
"""
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity][component_type]
if not self._entities[entity]:
del self._entities[entity]
self.clear_cache()
return entity | python | def remove_component(self, entity: int, component_type: Any) -> int:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity][component_type]
if not self._entities[entity]:
del self._entities[entity]
self.clear_cache()
return entity | [
"def",
"remove_component",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_type",
":",
"Any",
")",
"->",
"int",
":",
"self",
".",
"_components",
"[",
"component_type",
"]",
".",
"discard",
"(",
"entity",
")",
"if",
"not",
"self",
".",
"_component... | Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Entity enemy_a.
Raises a KeyError if either the given entity or Component type does
not exist in the database.
:param entity: The Entity to remove the Component from.
:param component_type: The type of the Component to remove. | [
"Remove",
"a",
"Component",
"instance",
"from",
"an",
"Entity",
"by",
"type",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L199-L222 |
22,471 | benmoran56/esper | esper.py | World._get_component | def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]:
"""Get an iterator for Entity, Component pairs.
:param component_type: The Component type to retrieve.
:return: An iterator for (Entity, Component) tuples.
"""
entity_db = self._entities
for entity in self._components.get(component_type, []):
yield entity, entity_db[entity][component_type] | python | def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]:
entity_db = self._entities
for entity in self._components.get(component_type, []):
yield entity, entity_db[entity][component_type] | [
"def",
"_get_component",
"(",
"self",
",",
"component_type",
":",
"Type",
"[",
"C",
"]",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"C",
"]",
"]",
":",
"entity_db",
"=",
"self",
".",
"_entities",
"for",
"entity",
"in",
"self",
".",
"_compo... | Get an iterator for Entity, Component pairs.
:param component_type: The Component type to retrieve.
:return: An iterator for (Entity, Component) tuples. | [
"Get",
"an",
"iterator",
"for",
"Entity",
"Component",
"pairs",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L224-L233 |
22,472 | benmoran56/esper | esper.py | World._get_components | def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]:
"""Get an iterator for Entity and multiple Component sets.
:param component_types: Two or more Component types.
:return: An iterator for Entity, (Component1, Component2, etc)
tuples.
"""
entity_db = self._entities
comp_db = self._components
try:
for entity in set.intersection(*[comp_db[ct] for ct in component_types]):
yield entity, [entity_db[entity][ct] for ct in component_types]
except KeyError:
pass | python | def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]:
entity_db = self._entities
comp_db = self._components
try:
for entity in set.intersection(*[comp_db[ct] for ct in component_types]):
yield entity, [entity_db[entity][ct] for ct in component_types]
except KeyError:
pass | [
"def",
"_get_components",
"(",
"self",
",",
"*",
"component_types",
":",
"Type",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"...",
"]",
"]",
":",
"entity_db",
"=",
"self",
".",
"_entities",
"comp_db",
"=",
"self",
".",
"_components",
"try",
... | Get an iterator for Entity and multiple Component sets.
:param component_types: Two or more Component types.
:return: An iterator for Entity, (Component1, Component2, etc)
tuples. | [
"Get",
"an",
"iterator",
"for",
"Entity",
"and",
"multiple",
"Component",
"sets",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L235-L249 |
22,473 | benmoran56/esper | esper.py | World.try_component | def try_component(self, entity: int, component_type: Type):
"""Try to get a single component type for an Entity.
This method will return the requested Component if it exists, but
will pass silently if it does not. This allows a way to access optional
Components that may or may not exist.
:param entity: The Entity ID to retrieve the Component for.
:param component_type: The Component instance you wish to retrieve.
:return: A iterator containg the single Component instance requested,
which is empty if the component doesn't exist.
"""
if component_type in self._entities[entity]:
yield self._entities[entity][component_type]
else:
return None | python | def try_component(self, entity: int, component_type: Type):
if component_type in self._entities[entity]:
yield self._entities[entity][component_type]
else:
return None | [
"def",
"try_component",
"(",
"self",
",",
"entity",
":",
"int",
",",
"component_type",
":",
"Type",
")",
":",
"if",
"component_type",
"in",
"self",
".",
"_entities",
"[",
"entity",
"]",
":",
"yield",
"self",
".",
"_entities",
"[",
"entity",
"]",
"[",
"... | Try to get a single component type for an Entity.
This method will return the requested Component if it exists, but
will pass silently if it does not. This allows a way to access optional
Components that may or may not exist.
:param entity: The Entity ID to retrieve the Component for.
:param component_type: The Component instance you wish to retrieve.
:return: A iterator containg the single Component instance requested,
which is empty if the component doesn't exist. | [
"Try",
"to",
"get",
"a",
"single",
"component",
"type",
"for",
"an",
"Entity",
".",
"This",
"method",
"will",
"return",
"the",
"requested",
"Component",
"if",
"it",
"exists",
"but",
"will",
"pass",
"silently",
"if",
"it",
"does",
"not",
".",
"This",
"all... | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L259-L274 |
22,474 | benmoran56/esper | esper.py | World._clear_dead_entities | def _clear_dead_entities(self):
"""Finalize deletion of any Entities that are marked dead.
In the interest of performance, this method duplicates code from the
`delete_entity` method. If that method is changed, those changes should
be duplicated here as well.
"""
for entity in self._dead_entities:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity]
self._dead_entities.clear()
self.clear_cache() | python | def _clear_dead_entities(self):
for entity in self._dead_entities:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity]
self._dead_entities.clear()
self.clear_cache() | [
"def",
"_clear_dead_entities",
"(",
"self",
")",
":",
"for",
"entity",
"in",
"self",
".",
"_dead_entities",
":",
"for",
"component_type",
"in",
"self",
".",
"_entities",
"[",
"entity",
"]",
":",
"self",
".",
"_components",
"[",
"component_type",
"]",
".",
... | Finalize deletion of any Entities that are marked dead.
In the interest of performance, this method duplicates code from the
`delete_entity` method. If that method is changed, those changes should
be duplicated here as well. | [
"Finalize",
"deletion",
"of",
"any",
"Entities",
"that",
"are",
"marked",
"dead",
".",
"In",
"the",
"interest",
"of",
"performance",
"this",
"method",
"duplicates",
"code",
"from",
"the",
"delete_entity",
"method",
".",
"If",
"that",
"method",
"is",
"changed",... | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L276-L294 |
22,475 | benmoran56/esper | esper.py | World._timed_process | def _timed_process(self, *args, **kwargs):
"""Track Processor execution time for benchmarking."""
for processor in self._processors:
start_time = _time.process_time()
processor.process(*args, **kwargs)
process_time = int(round((_time.process_time() - start_time) * 1000, 2))
self.process_times[processor.__class__.__name__] = process_time | python | def _timed_process(self, *args, **kwargs):
for processor in self._processors:
start_time = _time.process_time()
processor.process(*args, **kwargs)
process_time = int(round((_time.process_time() - start_time) * 1000, 2))
self.process_times[processor.__class__.__name__] = process_time | [
"def",
"_timed_process",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"processor",
"in",
"self",
".",
"_processors",
":",
"start_time",
"=",
"_time",
".",
"process_time",
"(",
")",
"processor",
".",
"process",
"(",
"*",
"arg... | Track Processor execution time for benchmarking. | [
"Track",
"Processor",
"execution",
"time",
"for",
"benchmarking",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L300-L306 |
22,476 | benmoran56/esper | esper.py | World.process | def process(self, *args, **kwargs):
"""Call the process method on all Processors, in order of their priority.
Call the *process* method on all assigned Processors, respecting their
optional priority setting. In addition, any Entities that were marked
for deletion since the last call to *World.process*, will be deleted
at the start of this method call.
:param args: Optional arguments that will be passed through to the
*process* method of all Processors.
"""
self._clear_dead_entities()
self._process(*args, **kwargs) | python | def process(self, *args, **kwargs):
self._clear_dead_entities()
self._process(*args, **kwargs) | [
"def",
"process",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_clear_dead_entities",
"(",
")",
"self",
".",
"_process",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call the process method on all Processors, in order of their priority.
Call the *process* method on all assigned Processors, respecting their
optional priority setting. In addition, any Entities that were marked
for deletion since the last call to *World.process*, will be deleted
at the start of this method call.
:param args: Optional arguments that will be passed through to the
*process* method of all Processors. | [
"Call",
"the",
"process",
"method",
"on",
"all",
"Processors",
"in",
"order",
"of",
"their",
"priority",
"."
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L308-L320 |
22,477 | benmoran56/esper | examples/pysdl2_example.py | texture_from_image | def texture_from_image(renderer, image_name):
"""Create an SDL2 Texture from an image file"""
soft_surface = ext.load_image(image_name)
texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface)
SDL_FreeSurface(soft_surface)
return texture | python | def texture_from_image(renderer, image_name):
soft_surface = ext.load_image(image_name)
texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface)
SDL_FreeSurface(soft_surface)
return texture | [
"def",
"texture_from_image",
"(",
"renderer",
",",
"image_name",
")",
":",
"soft_surface",
"=",
"ext",
".",
"load_image",
"(",
"image_name",
")",
"texture",
"=",
"SDL_CreateTextureFromSurface",
"(",
"renderer",
".",
"renderer",
",",
"soft_surface",
")",
"SDL_FreeS... | Create an SDL2 Texture from an image file | [
"Create",
"an",
"SDL2",
"Texture",
"from",
"an",
"image",
"file"
] | 5b6cd0c51718d5dcfa0e5613f824b5251cf092ac | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/examples/pysdl2_example.py#L76-L81 |
22,478 | sdss/tree | tasks.py | setup_tree | def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None):
''' Sets up the SDSS tree enviroment '''
print('Setting up the tree')
ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir)) | python | def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None):
''' Sets up the SDSS tree enviroment '''
print('Setting up the tree')
ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir)) | [
"def",
"setup_tree",
"(",
"ctx",
",",
"verbose",
"=",
"None",
",",
"root",
"=",
"None",
",",
"tree_dir",
"=",
"None",
",",
"modules_dir",
"=",
"None",
")",
":",
"print",
"(",
"'Setting up the tree'",
")",
"ctx",
".",
"run",
"(",
"'python bin/setup_tree.py ... | Sets up the SDSS tree enviroment | [
"Sets",
"up",
"the",
"SDSS",
"tree",
"enviroment"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/tasks.py#L61-L64 |
22,479 | sdss/tree | python/tree/tree.py | Tree.set_roots | def set_roots(self, uproot_with=None):
''' Set the roots of the tree in the os environment
Parameters:
uproot_with (str):
A new TREE_DIR path used to override an existing TREE_DIR environment variable
'''
# Check for TREE_DIR
self.treedir = os.environ.get('TREE_DIR', None) if not uproot_with else uproot_with
if not self.treedir:
treefilepath = os.path.dirname(os.path.abspath(__file__))
if 'python/' in treefilepath:
self.treedir = treefilepath.rsplit('/', 2)[0]
else:
self.treedir = treefilepath
self.treedir = treefilepath
os.environ['TREE_DIR'] = self.treedir
# Check sas_base_dir
if 'SAS_BASE_DIR' in os.environ:
self.sasbasedir = os.environ["SAS_BASE_DIR"]
else:
self.sasbasedir = os.path.expanduser('~/sas')
# make the directories
if not os.path.isdir(self.sasbasedir):
os.makedirs(self.sasbasedir) | python | def set_roots(self, uproot_with=None):
''' Set the roots of the tree in the os environment
Parameters:
uproot_with (str):
A new TREE_DIR path used to override an existing TREE_DIR environment variable
'''
# Check for TREE_DIR
self.treedir = os.environ.get('TREE_DIR', None) if not uproot_with else uproot_with
if not self.treedir:
treefilepath = os.path.dirname(os.path.abspath(__file__))
if 'python/' in treefilepath:
self.treedir = treefilepath.rsplit('/', 2)[0]
else:
self.treedir = treefilepath
self.treedir = treefilepath
os.environ['TREE_DIR'] = self.treedir
# Check sas_base_dir
if 'SAS_BASE_DIR' in os.environ:
self.sasbasedir = os.environ["SAS_BASE_DIR"]
else:
self.sasbasedir = os.path.expanduser('~/sas')
# make the directories
if not os.path.isdir(self.sasbasedir):
os.makedirs(self.sasbasedir) | [
"def",
"set_roots",
"(",
"self",
",",
"uproot_with",
"=",
"None",
")",
":",
"# Check for TREE_DIR",
"self",
".",
"treedir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TREE_DIR'",
",",
"None",
")",
"if",
"not",
"uproot_with",
"else",
"uproot_with",
"if",... | Set the roots of the tree in the os environment
Parameters:
uproot_with (str):
A new TREE_DIR path used to override an existing TREE_DIR environment variable | [
"Set",
"the",
"roots",
"of",
"the",
"tree",
"in",
"the",
"os",
"environment"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L75-L103 |
22,480 | sdss/tree | python/tree/tree.py | Tree.load_config | def load_config(self, config=None):
''' loads a config file
Parameters:
config (str):
Optional name of manual config file to load
'''
# Read the config file
cfgname = (config or self.config_name)
cfgname = 'sdsswork' if cfgname is None else cfgname
assert isinstance(cfgname, six.string_types), 'config name must be a string'
config_name = cfgname if cfgname.endswith('.cfg') else '{0}.cfg'.format(cfgname)
self.configfile = os.path.join(self.treedir, 'data', config_name)
assert os.path.isfile(self.configfile) is True, 'configfile {0} must exist in the proper directory'.format(self.configfile)
self._cfg = SafeConfigParser()
try:
self._cfg.read(self.configfile.decode('utf-8'))
except AttributeError:
self._cfg.read(self.configfile)
# create the local tree environment
self.environ = OrderedDict()
self.environ['default'] = self._cfg.defaults()
# set the filesystem envvar to sas_base_dir
self._file_replace = '@FILESYSTEM@'
if self.environ['default']['filesystem'] == self._file_replace:
self.environ['default']['filesystem'] = self.sasbasedir | python | def load_config(self, config=None):
''' loads a config file
Parameters:
config (str):
Optional name of manual config file to load
'''
# Read the config file
cfgname = (config or self.config_name)
cfgname = 'sdsswork' if cfgname is None else cfgname
assert isinstance(cfgname, six.string_types), 'config name must be a string'
config_name = cfgname if cfgname.endswith('.cfg') else '{0}.cfg'.format(cfgname)
self.configfile = os.path.join(self.treedir, 'data', config_name)
assert os.path.isfile(self.configfile) is True, 'configfile {0} must exist in the proper directory'.format(self.configfile)
self._cfg = SafeConfigParser()
try:
self._cfg.read(self.configfile.decode('utf-8'))
except AttributeError:
self._cfg.read(self.configfile)
# create the local tree environment
self.environ = OrderedDict()
self.environ['default'] = self._cfg.defaults()
# set the filesystem envvar to sas_base_dir
self._file_replace = '@FILESYSTEM@'
if self.environ['default']['filesystem'] == self._file_replace:
self.environ['default']['filesystem'] = self.sasbasedir | [
"def",
"load_config",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"# Read the config file",
"cfgname",
"=",
"(",
"config",
"or",
"self",
".",
"config_name",
")",
"cfgname",
"=",
"'sdsswork'",
"if",
"cfgname",
"is",
"None",
"else",
"cfgname",
"assert",... | loads a config file
Parameters:
config (str):
Optional name of manual config file to load | [
"loads",
"a",
"config",
"file"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L105-L135 |
22,481 | sdss/tree | python/tree/tree.py | Tree.branch_out | def branch_out(self, limb=None):
''' Set the individual section branches
This adds the various sections of the config file into the
tree environment for access later. Optically can specify a specific
branch. This does not yet load them into the os environment.
Parameters:
limb (str/list):
The name of the section of the config to add into the environ
or a list of strings
'''
# Filter on sections
if not limb:
limbs = self._cfg.sections()
else:
# we must have the general always + secton
limb = limb if isinstance(limb, list) else [limb]
limbs = ['general']
limbs.extend(limb)
# add all limbs into the tree environ
for leaf in limbs:
leaf = leaf if leaf in self._cfg.sections() else leaf.upper()
self.environ[leaf] = OrderedDict()
options = self._cfg.options(leaf)
for opt in options:
if opt in self.environ['default']:
continue
val = self._cfg.get(leaf, opt)
if val.find(self._file_replace) == 0:
val = val.replace(self._file_replace, self.sasbasedir)
self.environ[leaf][opt] = val | python | def branch_out(self, limb=None):
''' Set the individual section branches
This adds the various sections of the config file into the
tree environment for access later. Optically can specify a specific
branch. This does not yet load them into the os environment.
Parameters:
limb (str/list):
The name of the section of the config to add into the environ
or a list of strings
'''
# Filter on sections
if not limb:
limbs = self._cfg.sections()
else:
# we must have the general always + secton
limb = limb if isinstance(limb, list) else [limb]
limbs = ['general']
limbs.extend(limb)
# add all limbs into the tree environ
for leaf in limbs:
leaf = leaf if leaf in self._cfg.sections() else leaf.upper()
self.environ[leaf] = OrderedDict()
options = self._cfg.options(leaf)
for opt in options:
if opt in self.environ['default']:
continue
val = self._cfg.get(leaf, opt)
if val.find(self._file_replace) == 0:
val = val.replace(self._file_replace, self.sasbasedir)
self.environ[leaf][opt] = val | [
"def",
"branch_out",
"(",
"self",
",",
"limb",
"=",
"None",
")",
":",
"# Filter on sections",
"if",
"not",
"limb",
":",
"limbs",
"=",
"self",
".",
"_cfg",
".",
"sections",
"(",
")",
"else",
":",
"# we must have the general always + secton",
"limb",
"=",
"lim... | Set the individual section branches
This adds the various sections of the config file into the
tree environment for access later. Optically can specify a specific
branch. This does not yet load them into the os environment.
Parameters:
limb (str/list):
The name of the section of the config to add into the environ
or a list of strings | [
"Set",
"the",
"individual",
"section",
"branches"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L137-L172 |
22,482 | sdss/tree | python/tree/tree.py | Tree.add_limbs | def add_limbs(self, key=None):
''' Add a new section from the tree into the existing os environment
Parameters:
key (str):
The section name to grab from the environment
'''
self.branch_out(limb=key)
self.add_paths_to_os(key=key) | python | def add_limbs(self, key=None):
''' Add a new section from the tree into the existing os environment
Parameters:
key (str):
The section name to grab from the environment
'''
self.branch_out(limb=key)
self.add_paths_to_os(key=key) | [
"def",
"add_limbs",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"self",
".",
"branch_out",
"(",
"limb",
"=",
"key",
")",
"self",
".",
"add_paths_to_os",
"(",
"key",
"=",
"key",
")"
] | Add a new section from the tree into the existing os environment
Parameters:
key (str):
The section name to grab from the environment | [
"Add",
"a",
"new",
"section",
"from",
"the",
"tree",
"into",
"the",
"existing",
"os",
"environment"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L174-L183 |
22,483 | sdss/tree | python/tree/tree.py | Tree.get_paths | def get_paths(self, key):
''' Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the paths from the
specified section, as key:val = name:path
'''
newkey = key if key in self.environ else key.upper() if key.upper() \
in self.environ else None
if newkey:
return self.environ[newkey]
else:
raise KeyError('Key {0} not found in tree environment'.format(key)) | python | def get_paths(self, key):
''' Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the paths from the
specified section, as key:val = name:path
'''
newkey = key if key in self.environ else key.upper() if key.upper() \
in self.environ else None
if newkey:
return self.environ[newkey]
else:
raise KeyError('Key {0} not found in tree environment'.format(key)) | [
"def",
"get_paths",
"(",
"self",
",",
"key",
")",
":",
"newkey",
"=",
"key",
"if",
"key",
"in",
"self",
".",
"environ",
"else",
"key",
".",
"upper",
"(",
")",
"if",
"key",
".",
"upper",
"(",
")",
"in",
"self",
".",
"environ",
"else",
"None",
"if"... | Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the paths from the
specified section, as key:val = name:path | [
"Retrieve",
"a",
"set",
"of",
"environment",
"paths",
"from",
"the",
"config"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L185-L202 |
22,484 | sdss/tree | python/tree/tree.py | Tree.add_paths_to_os | def add_paths_to_os(self, key=None, update=None):
''' Add the paths in tree environ into the os environ
This code goes through the tree environ and checks
for existence in the os environ, then adds them
Parameters:
key (str):
The section name to check against / add
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False.
'''
if key is not None:
allpaths = key if isinstance(key, list) else [key]
else:
allpaths = [k for k in self.environ.keys() if 'default' not in k]
for key in allpaths:
paths = self.get_paths(key)
self.check_paths(paths, update=update) | python | def add_paths_to_os(self, key=None, update=None):
''' Add the paths in tree environ into the os environ
This code goes through the tree environ and checks
for existence in the os environ, then adds them
Parameters:
key (str):
The section name to check against / add
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False.
'''
if key is not None:
allpaths = key if isinstance(key, list) else [key]
else:
allpaths = [k for k in self.environ.keys() if 'default' not in k]
for key in allpaths:
paths = self.get_paths(key)
self.check_paths(paths, update=update) | [
"def",
"add_paths_to_os",
"(",
"self",
",",
"key",
"=",
"None",
",",
"update",
"=",
"None",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"allpaths",
"=",
"key",
"if",
"isinstance",
"(",
"key",
",",
"list",
")",
"else",
"[",
"key",
"]",
"else",
... | Add the paths in tree environ into the os environ
This code goes through the tree environ and checks
for existence in the os environ, then adds them
Parameters:
key (str):
The section name to check against / add
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False. | [
"Add",
"the",
"paths",
"in",
"tree",
"environ",
"into",
"the",
"os",
"environ"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L204-L225 |
22,485 | sdss/tree | python/tree/tree.py | Tree.check_paths | def check_paths(self, paths, update=None):
''' Check if the path is in the os environ, and if not add it
Paramters:
paths (OrderedDict):
An ordered dict containing all of the paths from the
a given section, as key:val = name:path
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False.
'''
# set up the exclusion list
exclude = [] if not self.exclude else self.exclude \
if isinstance(self.exclude, list) else [self.exclude]
# check the path names
for pathname, path in paths.items():
if update and pathname.upper() not in exclude:
os.environ[pathname.upper()] = os.path.normpath(path)
elif pathname.upper() not in os.environ:
os.environ[pathname.upper()] = os.path.normpath(path) | python | def check_paths(self, paths, update=None):
''' Check if the path is in the os environ, and if not add it
Paramters:
paths (OrderedDict):
An ordered dict containing all of the paths from the
a given section, as key:val = name:path
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False.
'''
# set up the exclusion list
exclude = [] if not self.exclude else self.exclude \
if isinstance(self.exclude, list) else [self.exclude]
# check the path names
for pathname, path in paths.items():
if update and pathname.upper() not in exclude:
os.environ[pathname.upper()] = os.path.normpath(path)
elif pathname.upper() not in os.environ:
os.environ[pathname.upper()] = os.path.normpath(path) | [
"def",
"check_paths",
"(",
"self",
",",
"paths",
",",
"update",
"=",
"None",
")",
":",
"# set up the exclusion list",
"exclude",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"exclude",
"else",
"self",
".",
"exclude",
"if",
"isinstance",
"(",
"self",
".",
"ex... | Check if the path is in the os environ, and if not add it
Paramters:
paths (OrderedDict):
An ordered dict containing all of the paths from the
a given section, as key:val = name:path
update (bool):
If True, overwrites existing tree environment variables in your
local environment. Default is False. | [
"Check",
"if",
"the",
"path",
"is",
"in",
"the",
"os",
"environ",
"and",
"if",
"not",
"add",
"it"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L227-L248 |
22,486 | sdss/tree | python/tree/tree.py | Tree.replant_tree | def replant_tree(self, config=None, exclude=None):
''' Replant the tree with a different config setup
Parameters:
config (str):
The config name to reload
exclude (list):
A list of environment variables to exclude
from forced updates
'''
# reinitialize a new Tree with a new config
self.__init__(key=self.key, config=config, update=True, exclude=exclude) | python | def replant_tree(self, config=None, exclude=None):
''' Replant the tree with a different config setup
Parameters:
config (str):
The config name to reload
exclude (list):
A list of environment variables to exclude
from forced updates
'''
# reinitialize a new Tree with a new config
self.__init__(key=self.key, config=config, update=True, exclude=exclude) | [
"def",
"replant_tree",
"(",
"self",
",",
"config",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"# reinitialize a new Tree with a new config",
"self",
".",
"__init__",
"(",
"key",
"=",
"self",
".",
"key",
",",
"config",
"=",
"config",
",",
"update",
... | Replant the tree with a different config setup
Parameters:
config (str):
The config name to reload
exclude (list):
A list of environment variables to exclude
from forced updates | [
"Replant",
"the",
"tree",
"with",
"a",
"different",
"config",
"setup"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/tree.py#L250-L262 |
22,487 | sdss/tree | python/tree/misc/logger.py | print_exception_formatted | def print_exception_formatted(type, value, tb):
"""A custom hook for printing tracebacks with colours."""
tbtext = ''.join(traceback.format_exception(type, value, tb))
lexer = get_lexer_by_name('pytb', stripall=True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext, lexer, formatter)) | python | def print_exception_formatted(type, value, tb):
tbtext = ''.join(traceback.format_exception(type, value, tb))
lexer = get_lexer_by_name('pytb', stripall=True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext, lexer, formatter)) | [
"def",
"print_exception_formatted",
"(",
"type",
",",
"value",
",",
"tb",
")",
":",
"tbtext",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"type",
",",
"value",
",",
"tb",
")",
")",
"lexer",
"=",
"get_lexer_by_name",
"(",
"'pyt... | A custom hook for printing tracebacks with colours. | [
"A",
"custom",
"hook",
"for",
"printing",
"tracebacks",
"with",
"colours",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L49-L55 |
22,488 | sdss/tree | python/tree/misc/logger.py | colored_formatter | def colored_formatter(record):
"""Prints log messages with colours."""
colours = {'info': ('blue', 'normal'),
'debug': ('magenta', 'normal'),
'warning': ('yellow', 'normal'),
'print': ('green', 'normal'),
'error': ('red', 'bold')}
levelname = record.levelname.lower()
if levelname == 'error':
return
if levelname.lower() in colours:
levelname_color = colours[levelname][0]
header = color_text('[{}]: '.format(levelname.upper()), levelname_color)
message = '{0}'.format(record.msg)
warning_category = re.match(r'^(\w+Warning:).*', message)
if warning_category is not None:
warning_category_colour = color_text(warning_category.groups()[0], 'cyan')
message = message.replace(warning_category.groups()[0], warning_category_colour)
sub_level = re.match(r'(\[.+\]:)(.*)', message)
if sub_level is not None:
sub_level_name = color_text(sub_level.groups()[0], 'red')
message = '{}{}'.format(sub_level_name, ''.join(sub_level.groups()[1:]))
# if len(message) > 79:
# tw = TextWrapper()
# tw.width = 79
# tw.subsequent_indent = ' ' * (len(record.levelname) + 2)
# tw.break_on_hyphens = False
# message = '\n'.join(tw.wrap(message))
sys.__stdout__.write('{}{}\n'.format(header, message))
sys.__stdout__.flush()
return | python | def colored_formatter(record):
colours = {'info': ('blue', 'normal'),
'debug': ('magenta', 'normal'),
'warning': ('yellow', 'normal'),
'print': ('green', 'normal'),
'error': ('red', 'bold')}
levelname = record.levelname.lower()
if levelname == 'error':
return
if levelname.lower() in colours:
levelname_color = colours[levelname][0]
header = color_text('[{}]: '.format(levelname.upper()), levelname_color)
message = '{0}'.format(record.msg)
warning_category = re.match(r'^(\w+Warning:).*', message)
if warning_category is not None:
warning_category_colour = color_text(warning_category.groups()[0], 'cyan')
message = message.replace(warning_category.groups()[0], warning_category_colour)
sub_level = re.match(r'(\[.+\]:)(.*)', message)
if sub_level is not None:
sub_level_name = color_text(sub_level.groups()[0], 'red')
message = '{}{}'.format(sub_level_name, ''.join(sub_level.groups()[1:]))
# if len(message) > 79:
# tw = TextWrapper()
# tw.width = 79
# tw.subsequent_indent = ' ' * (len(record.levelname) + 2)
# tw.break_on_hyphens = False
# message = '\n'.join(tw.wrap(message))
sys.__stdout__.write('{}{}\n'.format(header, message))
sys.__stdout__.flush()
return | [
"def",
"colored_formatter",
"(",
"record",
")",
":",
"colours",
"=",
"{",
"'info'",
":",
"(",
"'blue'",
",",
"'normal'",
")",
",",
"'debug'",
":",
"(",
"'magenta'",
",",
"'normal'",
")",
",",
"'warning'",
":",
"(",
"'yellow'",
",",
"'normal'",
")",
","... | Prints log messages with colours. | [
"Prints",
"log",
"messages",
"with",
"colours",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L58-L98 |
22,489 | sdss/tree | python/tree/misc/logger.py | MyLogger._catch_exceptions | def _catch_exceptions(self, exctype, value, tb):
"""Catches all exceptions and logs them."""
# Now we log it.
self.error('Uncaught exception', exc_info=(exctype, value, tb))
# First, we print to stdout with some colouring.
print_exception_formatted(exctype, value, tb) | python | def _catch_exceptions(self, exctype, value, tb):
# Now we log it.
self.error('Uncaught exception', exc_info=(exctype, value, tb))
# First, we print to stdout with some colouring.
print_exception_formatted(exctype, value, tb) | [
"def",
"_catch_exceptions",
"(",
"self",
",",
"exctype",
",",
"value",
",",
"tb",
")",
":",
"# Now we log it.",
"self",
".",
"error",
"(",
"'Uncaught exception'",
",",
"exc_info",
"=",
"(",
"exctype",
",",
"value",
",",
"tb",
")",
")",
"# First, we print to ... | Catches all exceptions and logs them. | [
"Catches",
"all",
"exceptions",
"and",
"logs",
"them",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L205-L212 |
22,490 | sdss/tree | python/tree/misc/logger.py | MyLogger._set_defaults | def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False):
"""Reset logger to its initial state."""
# Remove all previous handlers
for handler in self.handlers[:]:
self.removeHandler(handler)
# Set levels
self.setLevel(logging.DEBUG)
# Set up the stdout handler
self.fh = None
self.sh = logging.StreamHandler()
self.sh.emit = colored_formatter
self.addHandler(self.sh)
self.sh.setLevel(log_level)
# warnings.showwarning = self._show_warning
# Redirects all stdout to the logger
if redirect_stdout:
sys.stdout = LoggerStdout(self._print)
# Catches exceptions
sys.excepthook = self._catch_exceptions | python | def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False):
# Remove all previous handlers
for handler in self.handlers[:]:
self.removeHandler(handler)
# Set levels
self.setLevel(logging.DEBUG)
# Set up the stdout handler
self.fh = None
self.sh = logging.StreamHandler()
self.sh.emit = colored_formatter
self.addHandler(self.sh)
self.sh.setLevel(log_level)
# warnings.showwarning = self._show_warning
# Redirects all stdout to the logger
if redirect_stdout:
sys.stdout = LoggerStdout(self._print)
# Catches exceptions
sys.excepthook = self._catch_exceptions | [
"def",
"_set_defaults",
"(",
"self",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"redirect_stdout",
"=",
"False",
")",
":",
"# Remove all previous handlers",
"for",
"handler",
"in",
"self",
".",
"handlers",
"[",
":",
"]",
":",
"self",
".",
"removeHan... | Reset logger to its initial state. | [
"Reset",
"logger",
"to",
"its",
"initial",
"state",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L214-L239 |
22,491 | sdss/tree | python/tree/misc/logger.py | MyLogger.start_file_logger | def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
"""Start file logging."""
log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
logdir = log_file_path.parent
try:
logdir.mkdir(parents=True, exist_ok=True)
# If the log file exists, backs it up before creating a new file handler
if log_file_path.exists():
strtime = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S')
shutil.move(log_file_path, log_file_path + '.' + strtime)
self.fh = TimedRotatingFileHandler(str(log_file_path), when='midnight', utc=True)
self.fh.suffix = '%Y-%m-%d_%H:%M:%S'
except (IOError, OSError) as ee:
warnings.warn('log file {0!r} could not be opened for writing: '
'{1}'.format(log_file_path, ee), RuntimeWarning)
else:
self.fh.setFormatter(fmt)
self.addHandler(self.fh)
self.fh.setLevel(log_file_level)
self.log_filename = log_file_path | python | def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
logdir = log_file_path.parent
try:
logdir.mkdir(parents=True, exist_ok=True)
# If the log file exists, backs it up before creating a new file handler
if log_file_path.exists():
strtime = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S')
shutil.move(log_file_path, log_file_path + '.' + strtime)
self.fh = TimedRotatingFileHandler(str(log_file_path), when='midnight', utc=True)
self.fh.suffix = '%Y-%m-%d_%H:%M:%S'
except (IOError, OSError) as ee:
warnings.warn('log file {0!r} could not be opened for writing: '
'{1}'.format(log_file_path, ee), RuntimeWarning)
else:
self.fh.setFormatter(fmt)
self.addHandler(self.fh)
self.fh.setLevel(log_file_level)
self.log_filename = log_file_path | [
"def",
"start_file_logger",
"(",
"self",
",",
"name",
",",
"log_file_level",
"=",
"logging",
".",
"DEBUG",
",",
"log_file_path",
"=",
"'./'",
")",
":",
"log_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"log_file_path",
")",
"/",
"'{}.log'",
... | Start file logging. | [
"Start",
"file",
"logging",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/logger.py#L241-L265 |
22,492 | sdss/tree | bin/setup_tree.py | create_index_page | def create_index_page(environ, defaults, envdir):
''' create the env index html page
Builds the index.html page containing a table of symlinks
to datamodel directories
Parameters:
environ (dict):
A tree environment dictionary
defaults (dict):
The defaults dictionary from environ['default']
envdir (str):
The filepath for the env directory
Returns:
A string defintion of an html page
'''
# header of index file
header = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta name="viewport" content="width=device-width"/><meta http-equiv="content-type" content="text/html; charset=utf-8"/><style type="text/css">body,html {{background:#fff;font-family:"Bitstream Vera Sans","Lucida Grande","Lucida Sans Unicode",Lucidux,Verdana,Lucida,sans-serif;}}tr:nth-child(even) {{background:#f4f4f4;}}th,td {{padding:0.1em 0.5em;}}th {{text-align:left;font-weight:bold;background:#eee;border-bottom:1px solid #aaa;}}#list {{border:1px solid #aaa;width:100%%;}}a {{color:#a33;}}a:hover {{color:#e33;}}</style>
<link rel="stylesheet" href="{url}/css/sas.css" type="text/css"/>
<title>Index of /sas/{name}/env/</title>
</head><body><h1>Index of /sas/{name}/env/</h1>
"""
# footer of index file
footer = """<h3><a href='{url}/sas/'>{location}</a></h3>
<p>This directory contains links to the contents of
environment variables defined by the tree product, version {name}.
To examine the <em>types</em> of files contained in each environment variable
directory, visit <a href="/datamodel/files/">the datamodel.</a></p>
</body></html>
"""
# create index html file
index = header.format(**defaults)
index += create_index_table(environ, envdir)
index += footer.format(**defaults)
return index | python | def create_index_page(environ, defaults, envdir):
''' create the env index html page
Builds the index.html page containing a table of symlinks
to datamodel directories
Parameters:
environ (dict):
A tree environment dictionary
defaults (dict):
The defaults dictionary from environ['default']
envdir (str):
The filepath for the env directory
Returns:
A string defintion of an html page
'''
# header of index file
header = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta name="viewport" content="width=device-width"/><meta http-equiv="content-type" content="text/html; charset=utf-8"/><style type="text/css">body,html {{background:#fff;font-family:"Bitstream Vera Sans","Lucida Grande","Lucida Sans Unicode",Lucidux,Verdana,Lucida,sans-serif;}}tr:nth-child(even) {{background:#f4f4f4;}}th,td {{padding:0.1em 0.5em;}}th {{text-align:left;font-weight:bold;background:#eee;border-bottom:1px solid #aaa;}}#list {{border:1px solid #aaa;width:100%%;}}a {{color:#a33;}}a:hover {{color:#e33;}}</style>
<link rel="stylesheet" href="{url}/css/sas.css" type="text/css"/>
<title>Index of /sas/{name}/env/</title>
</head><body><h1>Index of /sas/{name}/env/</h1>
"""
# footer of index file
footer = """<h3><a href='{url}/sas/'>{location}</a></h3>
<p>This directory contains links to the contents of
environment variables defined by the tree product, version {name}.
To examine the <em>types</em> of files contained in each environment variable
directory, visit <a href="/datamodel/files/">the datamodel.</a></p>
</body></html>
"""
# create index html file
index = header.format(**defaults)
index += create_index_table(environ, envdir)
index += footer.format(**defaults)
return index | [
"def",
"create_index_page",
"(",
"environ",
",",
"defaults",
",",
"envdir",
")",
":",
"# header of index file",
"header",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"... | create the env index html page
Builds the index.html page containing a table of symlinks
to datamodel directories
Parameters:
environ (dict):
A tree environment dictionary
defaults (dict):
The defaults dictionary from environ['default']
envdir (str):
The filepath for the env directory
Returns:
A string defintion of an html page | [
"create",
"the",
"env",
"index",
"html",
"page",
"Builds",
"the",
"index",
".",
"html",
"page",
"containing",
"a",
"table",
"of",
"symlinks",
"to",
"datamodel",
"directories"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L113-L153 |
22,493 | sdss/tree | bin/setup_tree.py | create_env | def create_env(environ, mirror=None, verbose=None):
''' create the env symlink directory structure
Creates the env folder filled with symlinks to datamodel directories
for a given tree config file.
Parameters:
environ (dict):
A tree environment dictionary
mirror (bool):
If True, use the SAM url location
verbose (bool):
If True, print more information
'''
defaults = environ['default'].copy()
defaults['url'] = "https://data.mirror.sdss.org" if mirror else "https://data.sdss.org"
defaults['location'] = "SDSS-IV Science Archive Mirror (SAM)" if mirror else "SDSS-IV Science Archive Server (SAS)"
if not os.path.exists(environ['general']['sas_root']):
if verbose:
print("{0} doesn't exist, skipping env link creation.".format(environ['general']['sas_root']))
return
if verbose:
print("Found {0}.".format(environ['general']['sas_root']))
# sets and creates envdir
envdir = os.path.join(environ['general']['sas_root'], 'env')
if not os.path.exists(envdir):
os.makedirs(envdir)
if not os.access(envdir, os.W_OK):
return
# create index html
index = create_index_page(environ, defaults, envdir)
# write the index file
indexfile = os.path.join(envdir, 'index.html')
with open(indexfile, 'w') as f:
f.write(index) | python | def create_env(environ, mirror=None, verbose=None):
''' create the env symlink directory structure
Creates the env folder filled with symlinks to datamodel directories
for a given tree config file.
Parameters:
environ (dict):
A tree environment dictionary
mirror (bool):
If True, use the SAM url location
verbose (bool):
If True, print more information
'''
defaults = environ['default'].copy()
defaults['url'] = "https://data.mirror.sdss.org" if mirror else "https://data.sdss.org"
defaults['location'] = "SDSS-IV Science Archive Mirror (SAM)" if mirror else "SDSS-IV Science Archive Server (SAS)"
if not os.path.exists(environ['general']['sas_root']):
if verbose:
print("{0} doesn't exist, skipping env link creation.".format(environ['general']['sas_root']))
return
if verbose:
print("Found {0}.".format(environ['general']['sas_root']))
# sets and creates envdir
envdir = os.path.join(environ['general']['sas_root'], 'env')
if not os.path.exists(envdir):
os.makedirs(envdir)
if not os.access(envdir, os.W_OK):
return
# create index html
index = create_index_page(environ, defaults, envdir)
# write the index file
indexfile = os.path.join(envdir, 'index.html')
with open(indexfile, 'w') as f:
f.write(index) | [
"def",
"create_env",
"(",
"environ",
",",
"mirror",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"defaults",
"=",
"environ",
"[",
"'default'",
"]",
".",
"copy",
"(",
")",
"defaults",
"[",
"'url'",
"]",
"=",
"\"https://data.mirror.sdss.org\"",
"if",
... | create the env symlink directory structure
Creates the env folder filled with symlinks to datamodel directories
for a given tree config file.
Parameters:
environ (dict):
A tree environment dictionary
mirror (bool):
If True, use the SAM url location
verbose (bool):
If True, print more information | [
"create",
"the",
"env",
"symlink",
"directory",
"structure",
"Creates",
"the",
"env",
"folder",
"filled",
"with",
"symlinks",
"to",
"datamodel",
"directories",
"for",
"a",
"given",
"tree",
"config",
"file",
"."
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L156-L196 |
22,494 | sdss/tree | bin/setup_tree.py | check_sas_base_dir | def check_sas_base_dir(root=None):
''' Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar
'''
sasbasedir = root or os.getenv("SAS_BASE_DIR")
if not sasbasedir:
sasbasedir = input('Enter a path for SAS_BASE_DIR: ')
os.environ['SAS_BASE_DIR'] = sasbasedir | python | def check_sas_base_dir(root=None):
''' Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar
'''
sasbasedir = root or os.getenv("SAS_BASE_DIR")
if not sasbasedir:
sasbasedir = input('Enter a path for SAS_BASE_DIR: ')
os.environ['SAS_BASE_DIR'] = sasbasedir | [
"def",
"check_sas_base_dir",
"(",
"root",
"=",
"None",
")",
":",
"sasbasedir",
"=",
"root",
"or",
"os",
".",
"getenv",
"(",
"\"SAS_BASE_DIR\"",
")",
"if",
"not",
"sasbasedir",
":",
"sasbasedir",
"=",
"input",
"(",
"'Enter a path for SAS_BASE_DIR: '",
")",
"os"... | Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar | [
"Check",
"for",
"the",
"SAS_BASE_DIR",
"environment",
"variable"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L199-L213 |
22,495 | sdss/tree | bin/setup_tree.py | write_file | def write_file(environ, term='bash', out_dir=None, tree_dir=None):
''' Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
out_dir (str):
The output path to write the files (default is etc/)
'''
# get the proper name, header and file extension
name = environ['default']['name']
header = write_header(term=term, name=name, tree_dir=tree_dir)
exts = {'bash': '.sh', 'tsch': '.csh', 'modules': '.module'}
ext = exts[term]
# shell command
if term == 'bash':
cmd = 'export {0}={1}\n'
else:
cmd = 'setenv {0} {1}\n'
# write the environment config files
filename = os.path.join(out_dir, name + ext)
with open(filename, 'w') as f:
f.write(header + '\n')
for key, values in environ.items():
if key != 'default':
# write separator
f.write('#\n# {0}\n#\n'.format(key))
# write tree names and paths
for tree_name, tree_path in values.items():
f.write(cmd.format(tree_name.upper(), tree_path))
# write default .version file for modules
modules_version = write_version(name)
if term == 'modules' and environ['default']['current']:
version_name = os.path.join(out_dir, '.version')
with open(version_name, 'w') as f:
f.write(modules_version) | python | def write_file(environ, term='bash', out_dir=None, tree_dir=None):
''' Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
out_dir (str):
The output path to write the files (default is etc/)
'''
# get the proper name, header and file extension
name = environ['default']['name']
header = write_header(term=term, name=name, tree_dir=tree_dir)
exts = {'bash': '.sh', 'tsch': '.csh', 'modules': '.module'}
ext = exts[term]
# shell command
if term == 'bash':
cmd = 'export {0}={1}\n'
else:
cmd = 'setenv {0} {1}\n'
# write the environment config files
filename = os.path.join(out_dir, name + ext)
with open(filename, 'w') as f:
f.write(header + '\n')
for key, values in environ.items():
if key != 'default':
# write separator
f.write('#\n# {0}\n#\n'.format(key))
# write tree names and paths
for tree_name, tree_path in values.items():
f.write(cmd.format(tree_name.upper(), tree_path))
# write default .version file for modules
modules_version = write_version(name)
if term == 'modules' and environ['default']['current']:
version_name = os.path.join(out_dir, '.version')
with open(version_name, 'w') as f:
f.write(modules_version) | [
"def",
"write_file",
"(",
"environ",
",",
"term",
"=",
"'bash'",
",",
"out_dir",
"=",
"None",
",",
"tree_dir",
"=",
"None",
")",
":",
"# get the proper name, header and file extension",
"name",
"=",
"environ",
"[",
"'default'",
"]",
"[",
"'name'",
"]",
"header... | Write a tree environment file
Loops over the tree environ and writes them out to a bash, tsch, or
modules file
Parameters:
environ (dict):
The tree dictionary environment
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
out_dir (str):
The output path to write the files (default is etc/) | [
"Write",
"a",
"tree",
"environment",
"file"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L272-L319 |
22,496 | sdss/tree | bin/setup_tree.py | get_tree | def get_tree(config=None):
''' Get the tree for a given config
Parameters:
config (str):
The name of the tree config to load
Returns:
a Python Tree instance
'''
path = os.path.dirname(os.path.abspath(__file__))
pypath = os.path.realpath(os.path.join(path, '..', 'python'))
if pypath not in sys.path:
sys.path.append(pypath)
os.chdir(pypath)
from tree.tree import Tree
tree = Tree(config=config)
return tree | python | def get_tree(config=None):
''' Get the tree for a given config
Parameters:
config (str):
The name of the tree config to load
Returns:
a Python Tree instance
'''
path = os.path.dirname(os.path.abspath(__file__))
pypath = os.path.realpath(os.path.join(path, '..', 'python'))
if pypath not in sys.path:
sys.path.append(pypath)
os.chdir(pypath)
from tree.tree import Tree
tree = Tree(config=config)
return tree | [
"def",
"get_tree",
"(",
"config",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"pypath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",... | Get the tree for a given config
Parameters:
config (str):
The name of the tree config to load
Returns:
a Python Tree instance | [
"Get",
"the",
"tree",
"for",
"a",
"given",
"config"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L322-L339 |
22,497 | sdss/tree | bin/setup_tree.py | copy_modules | def copy_modules(filespath=None, modules_path=None, verbose=None):
''' Copy over the tree module files into your path '''
# find or define a modules path
if not modules_path:
modulepath = os.getenv("MODULEPATH")
if not modulepath:
modules_path = input('Enter the root path for your module files:')
else:
split_mods = modulepath.split(':')
if len(split_mods) > 1:
if verbose:
print('Multiple module paths found. Finding all that contain a tree directory.')
for mfile in split_mods:
if os.path.exists(os.path.join(mfile, 'tree')):
copy_modules(filespath=filespath, modules_path=mfile, verbose=verbose)
else:
return
else:
modules_path = split_mods[0]
# check for the tree module directory
tree_mod = os.path.join(modules_path, 'tree')
if not os.path.isdir(tree_mod):
os.makedirs(tree_mod)
# copy the modules into the tree
if verbose:
print('Copying modules from etc/ into {0}'.format(tree_mod))
module_files = glob.glob(os.path.join(filespath, '*.module'))
for mfile in module_files:
base = os.path.splitext(os.path.basename(mfile))[0]
tree_out = os.path.join(tree_mod, base)
shutil.copy2(mfile, tree_out)
# copy the default version into the tree
version = os.path.join(filespath, '.version')
if os.path.isfile(version):
shutil.copy2(version, tree_mod) | python | def copy_modules(filespath=None, modules_path=None, verbose=None):
''' Copy over the tree module files into your path '''
# find or define a modules path
if not modules_path:
modulepath = os.getenv("MODULEPATH")
if not modulepath:
modules_path = input('Enter the root path for your module files:')
else:
split_mods = modulepath.split(':')
if len(split_mods) > 1:
if verbose:
print('Multiple module paths found. Finding all that contain a tree directory.')
for mfile in split_mods:
if os.path.exists(os.path.join(mfile, 'tree')):
copy_modules(filespath=filespath, modules_path=mfile, verbose=verbose)
else:
return
else:
modules_path = split_mods[0]
# check for the tree module directory
tree_mod = os.path.join(modules_path, 'tree')
if not os.path.isdir(tree_mod):
os.makedirs(tree_mod)
# copy the modules into the tree
if verbose:
print('Copying modules from etc/ into {0}'.format(tree_mod))
module_files = glob.glob(os.path.join(filespath, '*.module'))
for mfile in module_files:
base = os.path.splitext(os.path.basename(mfile))[0]
tree_out = os.path.join(tree_mod, base)
shutil.copy2(mfile, tree_out)
# copy the default version into the tree
version = os.path.join(filespath, '.version')
if os.path.isfile(version):
shutil.copy2(version, tree_mod) | [
"def",
"copy_modules",
"(",
"filespath",
"=",
"None",
",",
"modules_path",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"# find or define a modules path",
"if",
"not",
"modules_path",
":",
"modulepath",
"=",
"os",
".",
"getenv",
"(",
"\"MODULEPATH\"",
"... | Copy over the tree module files into your path | [
"Copy",
"over",
"the",
"tree",
"module",
"files",
"into",
"your",
"path"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/bin/setup_tree.py#L342-L380 |
22,498 | sdss/tree | python/tree/misc/docutree.py | _indent | def _indent(text, level=1):
''' Does a proper indenting for Sphinx rst '''
prefix = ' ' * (4 * level)
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return ''.join(prefixed_lines()) | python | def _indent(text, level=1):
''' Does a proper indenting for Sphinx rst '''
prefix = ' ' * (4 * level)
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return ''.join(prefixed_lines()) | [
"def",
"_indent",
"(",
"text",
",",
"level",
"=",
"1",
")",
":",
"prefix",
"=",
"' '",
"*",
"(",
"4",
"*",
"level",
")",
"def",
"prefixed_lines",
"(",
")",
":",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
"True",
")",
":",
"yield",
"(",
... | Does a proper indenting for Sphinx rst | [
"Does",
"a",
"proper",
"indenting",
"for",
"Sphinx",
"rst"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/python/tree/misc/docutree.py#L22-L31 |
22,499 | sdss/tree | setup.py | get_requirements | def get_requirements(opts):
''' Get the proper requirements file based on the optional argument '''
if opts.dev:
name = 'requirements_dev.txt'
elif opts.doc:
name = 'requirements_doc.txt'
else:
name = 'requirements.txt'
requirements_file = os.path.join(os.path.dirname(__file__), name)
install_requires = [line.strip().replace('==', '>=') for line in open(requirements_file)
if not line.strip().startswith('#') and line.strip() != '']
return install_requires | python | def get_requirements(opts):
''' Get the proper requirements file based on the optional argument '''
if opts.dev:
name = 'requirements_dev.txt'
elif opts.doc:
name = 'requirements_doc.txt'
else:
name = 'requirements.txt'
requirements_file = os.path.join(os.path.dirname(__file__), name)
install_requires = [line.strip().replace('==', '>=') for line in open(requirements_file)
if not line.strip().startswith('#') and line.strip() != '']
return install_requires | [
"def",
"get_requirements",
"(",
"opts",
")",
":",
"if",
"opts",
".",
"dev",
":",
"name",
"=",
"'requirements_dev.txt'",
"elif",
"opts",
".",
"doc",
":",
"name",
"=",
"'requirements_doc.txt'",
"else",
":",
"name",
"=",
"'requirements.txt'",
"requirements_file",
... | Get the proper requirements file based on the optional argument | [
"Get",
"the",
"proper",
"requirements",
"file",
"based",
"on",
"the",
"optional",
"argument"
] | f61fe0876c138ccb61874912d4b8590dadfa835c | https://github.com/sdss/tree/blob/f61fe0876c138ccb61874912d4b8590dadfa835c/setup.py#L54-L67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.