repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
batiste/django-page-cms | pages/templatetags/pages_tags.py | has_content_in | def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False
return Content.objects.filter(page=page, language=language).count() > 0 | python | def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False
return Content.objects.filter(page=page, language=language).count() > 0 | [
"def",
"has_content_in",
"(",
"page",
",",
"language",
")",
":",
"if",
"page",
"is",
"None",
":",
"return",
"False",
"return",
"Content",
".",
"objects",
".",
"filter",
"(",
"page",
"=",
"page",
",",
"language",
"=",
"language",
")",
".",
"count",
"(",... | Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at | [
"Fitler",
"that",
"return",
"True",
"if",
"the",
"page",
"has",
"any",
"content",
"in",
"a",
"particular",
"language",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L60-L69 | train | 31,200 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | pages_menu | def pages_menu(context, page, url='/'):
"""Render a nested list of all the descendents of the given page,
including this page.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if page:
children = page.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | python | def pages_menu(context, page, url='/'):
"""Render a nested list of all the descendents of the given page,
including this page.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if page:
children = page.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | [
"def",
"pages_menu",
"(",
"context",
",",
"page",
",",
"url",
"=",
"'/'",
")",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_string_or_id",
"(",
"page",
",",
"l... | Render a nested list of all the descendents of the given page,
including this page.
:param page: the page where to start the menu from.
:param url: not used anymore. | [
"Render",
"a",
"nested",
"list",
"of",
"all",
"the",
"descendents",
"of",
"the",
"given",
"page",
"including",
"this",
"page",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L78-L90 | train | 31,201 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | pages_sub_menu | def pages_sub_menu(context, page, url='/'):
"""Get the root page of the given page and
render a nested list of all root's children pages.
Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if page:
root = page.get_root()
children = root.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | python | def pages_sub_menu(context, page, url='/'):
"""Get the root page of the given page and
render a nested list of all root's children pages.
Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if page:
root = page.get_root()
children = root.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | [
"def",
"pages_sub_menu",
"(",
"context",
",",
"page",
",",
"url",
"=",
"'/'",
")",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_string_or_id",
"(",
"page",
",",
... | Get the root page of the given page and
render a nested list of all root's children pages.
Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore. | [
"Get",
"the",
"root",
"page",
"of",
"the",
"given",
"page",
"and",
"render",
"a",
"nested",
"list",
"of",
"all",
"root",
"s",
"children",
"pages",
".",
"Good",
"for",
"rendering",
"a",
"secondary",
"menu",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L97-L111 | train | 31,202 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | show_content | def show_content(context, page, content_type, lang=None, fallback=True):
"""Display a content type from a page.
Example::
{% show_content page_object "title" %}
You can also use the slug of a page::
{% show_content "my-page-slug" "title" %}
Or even the id of a page::
{% show_content 10 "title" %}
:param page: the page object, slug or id
:param content_type: content_type used by a placeholder
:param lang: the wanted language
(default None, use the request object to know)
:param fallback: use fallback content from other language
"""
return {'content': _get_content(
context, page, content_type, lang, fallback)
} | python | def show_content(context, page, content_type, lang=None, fallback=True):
"""Display a content type from a page.
Example::
{% show_content page_object "title" %}
You can also use the slug of a page::
{% show_content "my-page-slug" "title" %}
Or even the id of a page::
{% show_content 10 "title" %}
:param page: the page object, slug or id
:param content_type: content_type used by a placeholder
:param lang: the wanted language
(default None, use the request object to know)
:param fallback: use fallback content from other language
"""
return {'content': _get_content(
context, page, content_type, lang, fallback)
} | [
"def",
"show_content",
"(",
"context",
",",
"page",
",",
"content_type",
",",
"lang",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"return",
"{",
"'content'",
":",
"_get_content",
"(",
"context",
",",
"page",
",",
"content_type",
",",
"lang",
","... | Display a content type from a page.
Example::
{% show_content page_object "title" %}
You can also use the slug of a page::
{% show_content "my-page-slug" "title" %}
Or even the id of a page::
{% show_content 10 "title" %}
:param page: the page object, slug or id
:param content_type: content_type used by a placeholder
:param lang: the wanted language
(default None, use the request object to know)
:param fallback: use fallback content from other language | [
"Display",
"a",
"content",
"type",
"from",
"a",
"page",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L162-L185 | train | 31,203 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | show_absolute_url | def show_absolute_url(context, page, lang=None):
"""
Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug or id
:param lang: the wanted language \
(defaults to `settings.PAGE_DEFAULT_LANGUAGE`)
"""
if not lang:
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return {'content': ''}
url = page.get_url_path(language=lang)
if url:
return {'content': url}
return {'content': ''} | python | def show_absolute_url(context, page, lang=None):
"""
Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug or id
:param lang: the wanted language \
(defaults to `settings.PAGE_DEFAULT_LANGUAGE`)
"""
if not lang:
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return {'content': ''}
url = page.get_url_path(language=lang)
if url:
return {'content': url}
return {'content': ''} | [
"def",
"show_absolute_url",
"(",
"context",
",",
"page",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"lang",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_... | Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug or id
:param lang: the wanted language \
(defaults to `settings.PAGE_DEFAULT_LANGUAGE`) | [
"Show",
"the",
"url",
"of",
"a",
"page",
"in",
"the",
"right",
"language"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L192-L217 | train | 31,204 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | pages_dynamic_tree_menu | def pages_dynamic_tree_menu(context, page, url='/'):
"""
Render a "dynamic" tree menu, with all nodes expanded which are either
ancestors or the current page itself.
Override ``pages/dynamic_tree_menu.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
children = None
if page and 'current_page' in context:
current_page = context['current_page']
# if this node is expanded, we also have to render its children
# a node is expanded if it is the current node or one of its ancestors
if(
page.tree_id == current_page.tree_id and
page.lft <= current_page.lft and
page.rght >= current_page.rght
):
children = page.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | python | def pages_dynamic_tree_menu(context, page, url='/'):
"""
Render a "dynamic" tree menu, with all nodes expanded which are either
ancestors or the current page itself.
Override ``pages/dynamic_tree_menu.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
children = None
if page and 'current_page' in context:
current_page = context['current_page']
# if this node is expanded, we also have to render its children
# a node is expanded if it is the current node or one of its ancestors
if(
page.tree_id == current_page.tree_id and
page.lft <= current_page.lft and
page.rght >= current_page.rght
):
children = page.get_children_for_frontend()
context.update({'children': children, 'page': page})
return context | [
"def",
"pages_dynamic_tree_menu",
"(",
"context",
",",
"page",
",",
"url",
"=",
"'/'",
")",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_string_or_id",
"(",
"page"... | Render a "dynamic" tree menu, with all nodes expanded which are either
ancestors or the current page itself.
Override ``pages/dynamic_tree_menu.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore | [
"Render",
"a",
"dynamic",
"tree",
"menu",
"with",
"all",
"nodes",
"expanded",
"which",
"are",
"either",
"ancestors",
"or",
"the",
"current",
"page",
"itself",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L244-L269 | train | 31,205 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | pages_breadcrumb | def pages_breadcrumb(context, page, url='/'):
"""
Render a breadcrumb like menu.
Override ``pages/breadcrumb.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
pages_navigation = None
if page:
pages_navigation = page.get_ancestors()
context.update({'pages_navigation': pages_navigation, 'page': page})
return context | python | def pages_breadcrumb(context, page, url='/'):
"""
Render a breadcrumb like menu.
Override ``pages/breadcrumb.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore
"""
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
pages_navigation = None
if page:
pages_navigation = page.get_ancestors()
context.update({'pages_navigation': pages_navigation, 'page': page})
return context | [
"def",
"pages_breadcrumb",
"(",
"context",
",",
"page",
",",
"url",
"=",
"'/'",
")",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_string_or_id",
"(",
"page",
","... | Render a breadcrumb like menu.
Override ``pages/breadcrumb.html`` if you want to change the
design.
:param page: the current page
:param url: not used anymore | [
"Render",
"a",
"breadcrumb",
"like",
"menu",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L278-L294 | train | 31,206 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_get_page | def do_get_page(parser, token):
"""Retrieve a page and insert into the template's context.
Example::
{% get_page "news" as news_page %}
:param page: the page object, slug or id
:param name: name of the context variable to store the page in
"""
bits = token.split_contents()
if 4 != len(bits):
raise TemplateSyntaxError('%r expects 4 arguments' % bits[0])
if bits[-2] != 'as':
raise TemplateSyntaxError(
'%r expects "as" as the second argument' % bits[0])
page_filter = parser.compile_filter(bits[1])
varname = bits[-1]
return GetPageNode(page_filter, varname) | python | def do_get_page(parser, token):
"""Retrieve a page and insert into the template's context.
Example::
{% get_page "news" as news_page %}
:param page: the page object, slug or id
:param name: name of the context variable to store the page in
"""
bits = token.split_contents()
if 4 != len(bits):
raise TemplateSyntaxError('%r expects 4 arguments' % bits[0])
if bits[-2] != 'as':
raise TemplateSyntaxError(
'%r expects "as" as the second argument' % bits[0])
page_filter = parser.compile_filter(bits[1])
varname = bits[-1]
return GetPageNode(page_filter, varname) | [
"def",
"do_get_page",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"4",
"!=",
"len",
"(",
"bits",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"'%r expects 4 arguments'",
"%",
"bits",
"[",
"0",
"]"... | Retrieve a page and insert into the template's context.
Example::
{% get_page "news" as news_page %}
:param page: the page object, slug or id
:param name: name of the context variable to store the page in | [
"Retrieve",
"a",
"page",
"and",
"insert",
"into",
"the",
"template",
"s",
"context",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L319-L337 | train | 31,207 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_get_content | def do_get_content(parser, token):
"""Retrieve a Content object and insert it into the template's context.
Example::
{% get_content page_object "title" as content %}
You can also use the slug of a page::
{% get_content "my-page-slug" "title" as content %}
Syntax::
{% get_content page type [lang] as name %}
:param page: the page object, slug or id
:param type: content_type used by a placeholder
:param name: name of the context variable to store the content in
:param lang: the wanted language
"""
bits = token.split_contents()
if not 5 <= len(bits) <= 6:
raise TemplateSyntaxError('%r expects 4 or 5 arguments' % bits[0])
if bits[-2] != 'as':
raise TemplateSyntaxError(
'%r expects "as" as the second last argument' % bits[0])
page = parser.compile_filter(bits[1])
content_type = parser.compile_filter(bits[2])
varname = bits[-1]
lang = None
lang_filter = None
if len(bits) == 6:
lang = bits[3]
else:
lang_filter = parser.compile_filter("lang")
return GetContentNode(page, content_type, varname, lang, lang_filter) | python | def do_get_content(parser, token):
"""Retrieve a Content object and insert it into the template's context.
Example::
{% get_content page_object "title" as content %}
You can also use the slug of a page::
{% get_content "my-page-slug" "title" as content %}
Syntax::
{% get_content page type [lang] as name %}
:param page: the page object, slug or id
:param type: content_type used by a placeholder
:param name: name of the context variable to store the content in
:param lang: the wanted language
"""
bits = token.split_contents()
if not 5 <= len(bits) <= 6:
raise TemplateSyntaxError('%r expects 4 or 5 arguments' % bits[0])
if bits[-2] != 'as':
raise TemplateSyntaxError(
'%r expects "as" as the second last argument' % bits[0])
page = parser.compile_filter(bits[1])
content_type = parser.compile_filter(bits[2])
varname = bits[-1]
lang = None
lang_filter = None
if len(bits) == 6:
lang = bits[3]
else:
lang_filter = parser.compile_filter("lang")
return GetContentNode(page, content_type, varname, lang, lang_filter) | [
"def",
"do_get_content",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"not",
"5",
"<=",
"len",
"(",
"bits",
")",
"<=",
"6",
":",
"raise",
"TemplateSyntaxError",
"(",
"'%r expects 4 or 5 arguments'",
"%... | Retrieve a Content object and insert it into the template's context.
Example::
{% get_content page_object "title" as content %}
You can also use the slug of a page::
{% get_content "my-page-slug" "title" as content %}
Syntax::
{% get_content page type [lang] as name %}
:param page: the page object, slug or id
:param type: content_type used by a placeholder
:param name: name of the context variable to store the content in
:param lang: the wanted language | [
"Retrieve",
"a",
"Content",
"object",
"and",
"insert",
"it",
"into",
"the",
"template",
"s",
"context",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L364-L399 | train | 31,208 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_placeholder | def do_placeholder(parser, token):
"""
Method that parse the placeholder template tag.
Syntax::
{% placeholder <name> [on <page>] [with <widget>] \
[parsed] [as <varname>] %}
Example usage::
{% placeholder about %}
{% placeholder body with TextArea as body_text %}
{% placeholder welcome with TextArea parsed as welcome_text %}
{% placeholder teaser on next_page with TextArea parsed %}
"""
name, params = parse_placeholder(parser, token)
return PlaceholderNode(name, **params) | python | def do_placeholder(parser, token):
"""
Method that parse the placeholder template tag.
Syntax::
{% placeholder <name> [on <page>] [with <widget>] \
[parsed] [as <varname>] %}
Example usage::
{% placeholder about %}
{% placeholder body with TextArea as body_text %}
{% placeholder welcome with TextArea parsed as welcome_text %}
{% placeholder teaser on next_page with TextArea parsed %}
"""
name, params = parse_placeholder(parser, token)
return PlaceholderNode(name, **params) | [
"def",
"do_placeholder",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"params",
"=",
"parse_placeholder",
"(",
"parser",
",",
"token",
")",
"return",
"PlaceholderNode",
"(",
"name",
",",
"*",
"*",
"params",
")"
] | Method that parse the placeholder template tag.
Syntax::
{% placeholder <name> [on <page>] [with <widget>] \
[parsed] [as <varname>] %}
Example usage::
{% placeholder about %}
{% placeholder body with TextArea as body_text %}
{% placeholder welcome with TextArea parsed as welcome_text %}
{% placeholder teaser on next_page with TextArea parsed %} | [
"Method",
"that",
"parse",
"the",
"placeholder",
"template",
"tag",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L504-L522 | train | 31,209 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_markdownlaceholder | def do_markdownlaceholder(parser, token):
"""
Method that parse the markdownplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return MarkdownPlaceholderNode(name, **params) | python | def do_markdownlaceholder(parser, token):
"""
Method that parse the markdownplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return MarkdownPlaceholderNode(name, **params) | [
"def",
"do_markdownlaceholder",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"params",
"=",
"parse_placeholder",
"(",
"parser",
",",
"token",
")",
"return",
"MarkdownPlaceholderNode",
"(",
"name",
",",
"*",
"*",
"params",
")"
] | Method that parse the markdownplaceholder template tag. | [
"Method",
"that",
"parse",
"the",
"markdownplaceholder",
"template",
"tag",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L526-L531 | train | 31,210 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_fileplaceholder | def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) | python | def do_fileplaceholder(parser, token):
"""
Method that parse the fileplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return FilePlaceholderNode(name, **params) | [
"def",
"do_fileplaceholder",
"(",
"parser",
",",
"token",
")",
":",
"name",
",",
"params",
"=",
"parse_placeholder",
"(",
"parser",
",",
"token",
")",
"return",
"FilePlaceholderNode",
"(",
"name",
",",
"*",
"*",
"params",
")"
] | Method that parse the fileplaceholder template tag. | [
"Method",
"that",
"parse",
"the",
"fileplaceholder",
"template",
"tag",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L544-L549 | train | 31,211 |
batiste/django-page-cms | pages/templatetags/pages_tags.py | do_page_has_content | def do_page_has_content(parser, token):
"""
Conditional tag that only renders its nodes if the page
has content for a particular content type. By default the
current page is used.
Syntax::
{% page_has_content <content_type> [<page var name>] %}
...
{%_end page_has_content %}
Example use::
{% page_has_content 'header-image' %}
<img src="{{ MEDIA_URL }}{% imageplaceholder 'header-image' %}">
{% end_page_has_content %}
"""
nodelist = parser.parse(('end_page_has_content',))
parser.delete_first_token()
args = token.split_contents()
try:
content_type = unescape_string_literal(args[1])
except IndexError:
raise template.TemplateSyntaxError(
"%r tag requires the argument content_type" % args[0]
)
if len(args) > 2:
page = args[2]
else:
page = None
return PageHasContentNode(page, content_type, nodelist) | python | def do_page_has_content(parser, token):
"""
Conditional tag that only renders its nodes if the page
has content for a particular content type. By default the
current page is used.
Syntax::
{% page_has_content <content_type> [<page var name>] %}
...
{%_end page_has_content %}
Example use::
{% page_has_content 'header-image' %}
<img src="{{ MEDIA_URL }}{% imageplaceholder 'header-image' %}">
{% end_page_has_content %}
"""
nodelist = parser.parse(('end_page_has_content',))
parser.delete_first_token()
args = token.split_contents()
try:
content_type = unescape_string_literal(args[1])
except IndexError:
raise template.TemplateSyntaxError(
"%r tag requires the argument content_type" % args[0]
)
if len(args) > 2:
page = args[2]
else:
page = None
return PageHasContentNode(page, content_type, nodelist) | [
"def",
"do_page_has_content",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'end_page_has_content'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"args",
"=",
"token",
".",
"split_contents",
"(",
... | Conditional tag that only renders its nodes if the page
has content for a particular content type. By default the
current page is used.
Syntax::
{% page_has_content <content_type> [<page var name>] %}
...
{%_end page_has_content %}
Example use::
{% page_has_content 'header-image' %}
<img src="{{ MEDIA_URL }}{% imageplaceholder 'header-image' %}">
{% end_page_has_content %} | [
"Conditional",
"tag",
"that",
"only",
"renders",
"its",
"nodes",
"if",
"the",
"page",
"has",
"content",
"for",
"a",
"particular",
"content",
"type",
".",
"By",
"default",
"the",
"current",
"page",
"is",
"used",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L602-L634 | train | 31,212 |
batiste/django-page-cms | pages/phttp.py | get_request_mock | def get_request_mock():
"""Build a ``request`` mock up for tests"""
from django.test.client import RequestFactory
from django.core.handlers.base import BaseHandler
factory = RequestFactory()
request = factory.get('/')
class FakeUser():
is_authenticated = False
is_staff = False
request.user = FakeUser()
request.session = {}
return request | python | def get_request_mock():
"""Build a ``request`` mock up for tests"""
from django.test.client import RequestFactory
from django.core.handlers.base import BaseHandler
factory = RequestFactory()
request = factory.get('/')
class FakeUser():
is_authenticated = False
is_staff = False
request.user = FakeUser()
request.session = {}
return request | [
"def",
"get_request_mock",
"(",
")",
":",
"from",
"django",
".",
"test",
".",
"client",
"import",
"RequestFactory",
"from",
"django",
".",
"core",
".",
"handlers",
".",
"base",
"import",
"BaseHandler",
"factory",
"=",
"RequestFactory",
"(",
")",
"request",
"... | Build a ``request`` mock up for tests | [
"Build",
"a",
"request",
"mock",
"up",
"for",
"tests"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/phttp.py#L8-L23 | train | 31,213 |
batiste/django-page-cms | pages/phttp.py | remove_slug | def remove_slug(path):
"""
Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some
"""
if path.endswith('/'):
path = path[:-1]
if path.startswith('/'):
path = path[1:]
if "/" not in path or not path:
return None
parts = path.split("/")[:-1]
return "/".join(parts) | python | def remove_slug(path):
"""
Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some
"""
if path.endswith('/'):
path = path[:-1]
if path.startswith('/'):
path = path[1:]
if "/" not in path or not path:
return None
parts = path.split("/")[:-1]
return "/".join(parts) | [
"def",
"remove_slug",
"(",
"path",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"path",
"=",
"path",
"[",
":",
"-",
"1",
"]",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"i... | Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some | [
"Return",
"the",
"remainin",
"part",
"of",
"the",
"path"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/phttp.py#L38-L52 | train | 31,214 |
batiste/django-page-cms | pages/phttp.py | get_language_from_request | def get_language_from_request(request):
"""Return the most obvious language according the request."""
language = request.GET.get('language', None)
if language:
return language
if hasattr(request, 'LANGUAGE_CODE'):
lang = settings.PAGE_LANGUAGE_MAPPING(str(request.LANGUAGE_CODE))
if lang not in LANGUAGE_KEYS:
return settings.PAGE_DEFAULT_LANGUAGE
else:
return lang
else:
return settings.PAGE_DEFAULT_LANGUAGE | python | def get_language_from_request(request):
"""Return the most obvious language according the request."""
language = request.GET.get('language', None)
if language:
return language
if hasattr(request, 'LANGUAGE_CODE'):
lang = settings.PAGE_LANGUAGE_MAPPING(str(request.LANGUAGE_CODE))
if lang not in LANGUAGE_KEYS:
return settings.PAGE_DEFAULT_LANGUAGE
else:
return lang
else:
return settings.PAGE_DEFAULT_LANGUAGE | [
"def",
"get_language_from_request",
"(",
"request",
")",
":",
"language",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'language'",
",",
"None",
")",
"if",
"language",
":",
"return",
"language",
"if",
"hasattr",
"(",
"request",
",",
"'LANGUAGE_CODE'",
")",
... | Return the most obvious language according the request. | [
"Return",
"the",
"most",
"obvious",
"language",
"according",
"the",
"request",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/phttp.py#L73-L86 | train | 31,215 |
batiste/django-page-cms | pages/managers.py | ContentManager.get_content | def get_content(self, page, language, ctype, language_fallback=False):
"""Gets the latest content string for a particular page, language and
placeholder.
:param page: the concerned page object.
:param language: the wanted language.
:param ctype: the content type.
:param language_fallback: fallback to another language if ``True``.
"""
if page is None:
page = fake_page
if " " in ctype:
raise ValueError("Ctype cannot contain spaces.")
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
frozen = int(bool(page.freeze_date))
key = self.PAGE_CONTENT_DICT_KEY % (page.id, ctype, frozen)
# Spaces do not work with memcache
key = key.replace(' ', '-')
if page._content_dict is None:
page._content_dict = dict()
if page._content_dict.get(key, None):
content_dict = page._content_dict.get(key)
else:
content_dict = cache.get(key)
# fill a dict object for each language, that will create
# P * L queries.
# L == number of language, P == number of placeholder in the page.
# Once generated the result is cached.
if not content_dict:
content_dict = {}
for lang in settings.PAGE_LANGUAGES:
try:
content = self.get_content_object(page, lang[0], ctype)
content_dict[lang[0]] = content.body
except self.model.DoesNotExist:
content_dict[lang[0]] = ''
page._content_dict[key] = content_dict
cache.set(key, content_dict)
if language in content_dict and content_dict[language]:
return content_dict[language]
if language_fallback:
for lang in settings.PAGE_LANGUAGES:
if lang[0] in content_dict and content_dict[lang[0]]:
return content_dict[lang[0]]
return '' | python | def get_content(self, page, language, ctype, language_fallback=False):
"""Gets the latest content string for a particular page, language and
placeholder.
:param page: the concerned page object.
:param language: the wanted language.
:param ctype: the content type.
:param language_fallback: fallback to another language if ``True``.
"""
if page is None:
page = fake_page
if " " in ctype:
raise ValueError("Ctype cannot contain spaces.")
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
frozen = int(bool(page.freeze_date))
key = self.PAGE_CONTENT_DICT_KEY % (page.id, ctype, frozen)
# Spaces do not work with memcache
key = key.replace(' ', '-')
if page._content_dict is None:
page._content_dict = dict()
if page._content_dict.get(key, None):
content_dict = page._content_dict.get(key)
else:
content_dict = cache.get(key)
# fill a dict object for each language, that will create
# P * L queries.
# L == number of language, P == number of placeholder in the page.
# Once generated the result is cached.
if not content_dict:
content_dict = {}
for lang in settings.PAGE_LANGUAGES:
try:
content = self.get_content_object(page, lang[0], ctype)
content_dict[lang[0]] = content.body
except self.model.DoesNotExist:
content_dict[lang[0]] = ''
page._content_dict[key] = content_dict
cache.set(key, content_dict)
if language in content_dict and content_dict[language]:
return content_dict[language]
if language_fallback:
for lang in settings.PAGE_LANGUAGES:
if lang[0] in content_dict and content_dict[lang[0]]:
return content_dict[lang[0]]
return '' | [
"def",
"get_content",
"(",
"self",
",",
"page",
",",
"language",
",",
"ctype",
",",
"language_fallback",
"=",
"False",
")",
":",
"if",
"page",
"is",
"None",
":",
"page",
"=",
"fake_page",
"if",
"\" \"",
"in",
"ctype",
":",
"raise",
"ValueError",
"(",
"... | Gets the latest content string for a particular page, language and
placeholder.
:param page: the concerned page object.
:param language: the wanted language.
:param ctype: the content type.
:param language_fallback: fallback to another language if ``True``. | [
"Gets",
"the",
"latest",
"content",
"string",
"for",
"a",
"particular",
"page",
"language",
"and",
"placeholder",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/managers.py#L220-L272 | train | 31,216 |
batiste/django-page-cms | pages/managers.py | ContentManager.get_page_ids_by_slug | def get_page_ids_by_slug(self, slug):
"""Return all page's id matching the given slug.
This function also returns pages that have an old slug
that match.
:param slug: the wanted slug.
"""
ids = self.filter(type='slug', body=slug).values('page_id').annotate(
max_creation_date=Max('creation_date')
)
return [content['page_id'] for content in ids] | python | def get_page_ids_by_slug(self, slug):
"""Return all page's id matching the given slug.
This function also returns pages that have an old slug
that match.
:param slug: the wanted slug.
"""
ids = self.filter(type='slug', body=slug).values('page_id').annotate(
max_creation_date=Max('creation_date')
)
return [content['page_id'] for content in ids] | [
"def",
"get_page_ids_by_slug",
"(",
"self",
",",
"slug",
")",
":",
"ids",
"=",
"self",
".",
"filter",
"(",
"type",
"=",
"'slug'",
",",
"body",
"=",
"slug",
")",
".",
"values",
"(",
"'page_id'",
")",
".",
"annotate",
"(",
"max_creation_date",
"=",
"Max"... | Return all page's id matching the given slug.
This function also returns pages that have an old slug
that match.
:param slug: the wanted slug. | [
"Return",
"all",
"page",
"s",
"id",
"matching",
"the",
"given",
"slug",
".",
"This",
"function",
"also",
"returns",
"pages",
"that",
"have",
"an",
"old",
"slug",
"that",
"match",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/managers.py#L290-L300 | train | 31,217 |
batiste/django-page-cms | pages/views.py | Details.resolve_page | def resolve_page(self, request, context, is_staff):
"""Return the appropriate page according to the path."""
path = context['path']
lang = context['lang']
page = Page.objects.from_path(
path, lang,
exclude_drafts=(not is_staff))
if page:
return page
# if the complete path didn't worked out properly
# and if didn't used PAGE_USE_STRICT_URL setting we gonna
# try to see if it might be a delegation page.
# To do that we remove the right part of the url and try again
# to find a page that match
if not settings.PAGE_USE_STRICT_URL:
path = remove_slug(path)
while path is not None:
page = Page.objects.from_path(
path, lang,
exclude_drafts=(not is_staff))
# find a match. Is the page delegating?
if page:
if page.delegate_to:
return page
path = remove_slug(path)
return None | python | def resolve_page(self, request, context, is_staff):
"""Return the appropriate page according to the path."""
path = context['path']
lang = context['lang']
page = Page.objects.from_path(
path, lang,
exclude_drafts=(not is_staff))
if page:
return page
# if the complete path didn't worked out properly
# and if didn't used PAGE_USE_STRICT_URL setting we gonna
# try to see if it might be a delegation page.
# To do that we remove the right part of the url and try again
# to find a page that match
if not settings.PAGE_USE_STRICT_URL:
path = remove_slug(path)
while path is not None:
page = Page.objects.from_path(
path, lang,
exclude_drafts=(not is_staff))
# find a match. Is the page delegating?
if page:
if page.delegate_to:
return page
path = remove_slug(path)
return None | [
"def",
"resolve_page",
"(",
"self",
",",
"request",
",",
"context",
",",
"is_staff",
")",
":",
"path",
"=",
"context",
"[",
"'path'",
"]",
"lang",
"=",
"context",
"[",
"'lang'",
"]",
"page",
"=",
"Page",
".",
"objects",
".",
"from_path",
"(",
"path",
... | Return the appropriate page according to the path. | [
"Return",
"the",
"appropriate",
"page",
"according",
"to",
"the",
"path",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/views.py#L99-L125 | train | 31,218 |
batiste/django-page-cms | pages/views.py | Details.resolve_redirection | def resolve_redirection(self, request, context):
"""Check for redirections."""
current_page = context['current_page']
lang = context['lang']
if current_page.redirect_to_url:
return HttpResponsePermanentRedirect(current_page.redirect_to_url)
if current_page.redirect_to:
return HttpResponsePermanentRedirect(
current_page.redirect_to.get_url_path(lang)) | python | def resolve_redirection(self, request, context):
"""Check for redirections."""
current_page = context['current_page']
lang = context['lang']
if current_page.redirect_to_url:
return HttpResponsePermanentRedirect(current_page.redirect_to_url)
if current_page.redirect_to:
return HttpResponsePermanentRedirect(
current_page.redirect_to.get_url_path(lang)) | [
"def",
"resolve_redirection",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"current_page",
"=",
"context",
"[",
"'current_page'",
"]",
"lang",
"=",
"context",
"[",
"'lang'",
"]",
"if",
"current_page",
".",
"redirect_to_url",
":",
"return",
"HttpRespo... | Check for redirections. | [
"Check",
"for",
"redirections",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/views.py#L134-L143 | train | 31,219 |
batiste/django-page-cms | pages/views.py | Details.choose_language | def choose_language(self, lang, request):
"""Deal with the multiple corner case of choosing the language."""
# Can be an empty string or None
if not lang:
lang = get_language_from_request(request)
# Raise a 404 if the language is not in not in the list
if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]:
raise Http404
# We're going to serve CMS pages in language lang;
# make django gettext use that language too
if lang and translation.check_for_language(lang):
translation.activate(lang)
return lang | python | def choose_language(self, lang, request):
"""Deal with the multiple corner case of choosing the language."""
# Can be an empty string or None
if not lang:
lang = get_language_from_request(request)
# Raise a 404 if the language is not in not in the list
if lang not in [key for (key, value) in settings.PAGE_LANGUAGES]:
raise Http404
# We're going to serve CMS pages in language lang;
# make django gettext use that language too
if lang and translation.check_for_language(lang):
translation.activate(lang)
return lang | [
"def",
"choose_language",
"(",
"self",
",",
"lang",
",",
"request",
")",
":",
"# Can be an empty string or None",
"if",
"not",
"lang",
":",
"lang",
"=",
"get_language_from_request",
"(",
"request",
")",
"# Raise a 404 if the language is not in not in the list",
"if",
"l... | Deal with the multiple corner case of choosing the language. | [
"Deal",
"with",
"the",
"multiple",
"corner",
"case",
"of",
"choosing",
"the",
"language",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/views.py#L149-L165 | train | 31,220 |
batiste/django-page-cms | pages/views.py | Details.extra_context | def extra_context(self, request, context):
"""Call the PAGE_EXTRA_CONTEXT function if there is one."""
if settings.PAGE_EXTRA_CONTEXT:
context.update(settings.PAGE_EXTRA_CONTEXT()) | python | def extra_context(self, request, context):
"""Call the PAGE_EXTRA_CONTEXT function if there is one."""
if settings.PAGE_EXTRA_CONTEXT:
context.update(settings.PAGE_EXTRA_CONTEXT()) | [
"def",
"extra_context",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"if",
"settings",
".",
"PAGE_EXTRA_CONTEXT",
":",
"context",
".",
"update",
"(",
"settings",
".",
"PAGE_EXTRA_CONTEXT",
"(",
")",
")"
] | Call the PAGE_EXTRA_CONTEXT function if there is one. | [
"Call",
"the",
"PAGE_EXTRA_CONTEXT",
"function",
"if",
"there",
"is",
"one",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/views.py#L175-L178 | train | 31,221 |
batiste/django-page-cms | pages/models.py | Page.get_children | def get_children(self):
"""Cache superclass result"""
key = self.CHILDREN_KEY % self.pk
#children = cache.get(key, None)
# if children is None:
children = super(Page, self).get_children()
#cache.set(key, children)
return children | python | def get_children(self):
"""Cache superclass result"""
key = self.CHILDREN_KEY % self.pk
#children = cache.get(key, None)
# if children is None:
children = super(Page, self).get_children()
#cache.set(key, children)
return children | [
"def",
"get_children",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"CHILDREN_KEY",
"%",
"self",
".",
"pk",
"#children = cache.get(key, None)",
"# if children is None:",
"children",
"=",
"super",
"(",
"Page",
",",
"self",
")",
".",
"get_children",
"(",
")",... | Cache superclass result | [
"Cache",
"superclass",
"result"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L181-L188 | train | 31,222 |
batiste/django-page-cms | pages/models.py | Page.move_to | def move_to(self, target, position='first-child'):
"""Invalidate cache when moving"""
# Invalidate both in case position matters,
# otherwise only target is needed.
self.invalidate()
target.invalidate()
super(Page, self).move_to(target, position=position) | python | def move_to(self, target, position='first-child'):
"""Invalidate cache when moving"""
# Invalidate both in case position matters,
# otherwise only target is needed.
self.invalidate()
target.invalidate()
super(Page, self).move_to(target, position=position) | [
"def",
"move_to",
"(",
"self",
",",
"target",
",",
"position",
"=",
"'first-child'",
")",
":",
"# Invalidate both in case position matters,",
"# otherwise only target is needed.",
"self",
".",
"invalidate",
"(",
")",
"target",
".",
"invalidate",
"(",
")",
"super",
"... | Invalidate cache when moving | [
"Invalidate",
"cache",
"when",
"moving"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L208-L215 | train | 31,223 |
batiste/django-page-cms | pages/models.py | Page.get_content | def get_content(self, language, ctype, language_fallback=False):
"""Shortcut method for retrieving a piece of page content
:param language: wanted language, if not defined default is used.
:param ctype: the type of content.
:param fallback: if ``True``, the content will also be searched in \
other languages.
"""
return Content.objects.get_content(self, language, ctype,
language_fallback) | python | def get_content(self, language, ctype, language_fallback=False):
"""Shortcut method for retrieving a piece of page content
:param language: wanted language, if not defined default is used.
:param ctype: the type of content.
:param fallback: if ``True``, the content will also be searched in \
other languages.
"""
return Content.objects.get_content(self, language, ctype,
language_fallback) | [
"def",
"get_content",
"(",
"self",
",",
"language",
",",
"ctype",
",",
"language_fallback",
"=",
"False",
")",
":",
"return",
"Content",
".",
"objects",
".",
"get_content",
"(",
"self",
",",
"language",
",",
"ctype",
",",
"language_fallback",
")"
] | Shortcut method for retrieving a piece of page content
:param language: wanted language, if not defined default is used.
:param ctype: the type of content.
:param fallback: if ``True``, the content will also be searched in \
other languages. | [
"Shortcut",
"method",
"for",
"retrieving",
"a",
"piece",
"of",
"page",
"content"
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L347-L356 | train | 31,224 |
batiste/django-page-cms | pages/models.py | Page.get_url_path | def get_url_path(self, language=None):
"""Return the URL's path component. Add the language prefix if
``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``.
:param language: the wanted url language.
"""
if self.is_first_root():
# this is used to allow users to change URL of the root
# page. The language prefix is not usable here.
try:
return reverse('pages-root')
except Exception:
pass
url = self.get_complete_slug(language)
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
if settings.PAGE_USE_LANGUAGE_PREFIX:
return reverse('pages-details-by-path',
args=[language, url])
else:
return reverse('pages-details-by-path', args=[url]) | python | def get_url_path(self, language=None):
"""Return the URL's path component. Add the language prefix if
``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``.
:param language: the wanted url language.
"""
if self.is_first_root():
# this is used to allow users to change URL of the root
# page. The language prefix is not usable here.
try:
return reverse('pages-root')
except Exception:
pass
url = self.get_complete_slug(language)
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
if settings.PAGE_USE_LANGUAGE_PREFIX:
return reverse('pages-details-by-path',
args=[language, url])
else:
return reverse('pages-details-by-path', args=[url]) | [
"def",
"get_url_path",
"(",
"self",
",",
"language",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_first_root",
"(",
")",
":",
"# this is used to allow users to change URL of the root",
"# page. The language prefix is not usable here.",
"try",
":",
"return",
"reverse",
... | Return the URL's path component. Add the language prefix if
``PAGE_USE_LANGUAGE_PREFIX`` setting is set to ``True``.
:param language: the wanted url language. | [
"Return",
"the",
"URL",
"s",
"path",
"component",
".",
"Add",
"the",
"language",
"prefix",
"if",
"PAGE_USE_LANGUAGE_PREFIX",
"setting",
"is",
"set",
"to",
"True",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L392-L412 | train | 31,225 |
batiste/django-page-cms | pages/models.py | Page.slug_with_level | def slug_with_level(self, language=None):
"""Display the slug of the page prepended with insecable
spaces to simluate the level of page in the hierarchy."""
level = ''
if self.level:
for n in range(0, self.level):
level += ' '
return mark_safe(level + self.slug(language)) | python | def slug_with_level(self, language=None):
"""Display the slug of the page prepended with insecable
spaces to simluate the level of page in the hierarchy."""
level = ''
if self.level:
for n in range(0, self.level):
level += ' '
return mark_safe(level + self.slug(language)) | [
"def",
"slug_with_level",
"(",
"self",
",",
"language",
"=",
"None",
")",
":",
"level",
"=",
"''",
"if",
"self",
".",
"level",
":",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"self",
".",
"level",
")",
":",
"level",
"+=",
"' '",
"retu... | Display the slug of the page prepended with insecable
spaces to simluate the level of page in the hierarchy. | [
"Display",
"the",
"slug",
"of",
"the",
"page",
"prepended",
"with",
"insecable",
"spaces",
"to",
"simluate",
"the",
"level",
"of",
"page",
"in",
"the",
"hierarchy",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L456-L463 | train | 31,226 |
batiste/django-page-cms | pages/models.py | Page.title | def title(self, language=None, fallback=True):
"""
Return the title of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in \
other languages.
"""
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
return self.get_content(language, 'title', language_fallback=fallback) | python | def title(self, language=None, fallback=True):
"""
Return the title of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in \
other languages.
"""
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
return self.get_content(language, 'title', language_fallback=fallback) | [
"def",
"title",
"(",
"self",
",",
"language",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"if",
"not",
"language",
":",
"language",
"=",
"settings",
".",
"PAGE_DEFAULT_LANGUAGE",
"return",
"self",
".",
"get_content",
"(",
"language",
",",
"'title'... | Return the title of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in \
other languages. | [
"Return",
"the",
"title",
"of",
"the",
"page",
"depending",
"on",
"the",
"given",
"language",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/models.py#L480-L491 | train | 31,227 |
batiste/django-page-cms | pages/admin/forms.py | unique_slug_required | def unique_slug_required(form, slug):
"""Enforce a unique slug accross all pages and websistes."""
if hasattr(form, 'instance') and form.instance.id:
if Content.objects.exclude(page=form.instance).filter(
body=slug, type="slug").count():
raise forms.ValidationError(error_dict['another_page_error'])
elif Content.objects.filter(body=slug, type="slug").count():
raise forms.ValidationError(error_dict['another_page_error'])
return slug | python | def unique_slug_required(form, slug):
"""Enforce a unique slug accross all pages and websistes."""
if hasattr(form, 'instance') and form.instance.id:
if Content.objects.exclude(page=form.instance).filter(
body=slug, type="slug").count():
raise forms.ValidationError(error_dict['another_page_error'])
elif Content.objects.filter(body=slug, type="slug").count():
raise forms.ValidationError(error_dict['another_page_error'])
return slug | [
"def",
"unique_slug_required",
"(",
"form",
",",
"slug",
")",
":",
"if",
"hasattr",
"(",
"form",
",",
"'instance'",
")",
"and",
"form",
".",
"instance",
".",
"id",
":",
"if",
"Content",
".",
"objects",
".",
"exclude",
"(",
"page",
"=",
"form",
".",
"... | Enforce a unique slug accross all pages and websistes. | [
"Enforce",
"a",
"unique",
"slug",
"accross",
"all",
"pages",
"and",
"websistes",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/forms.py#L39-L48 | train | 31,228 |
batiste/django-page-cms | pages/admin/forms.py | intersect_sites_method | def intersect_sites_method(form):
"""Return a method to intersect sites."""
if settings.PAGE_USE_SITE_ID:
if settings.PAGE_HIDE_SITES:
site_ids = [global_settings.SITE_ID]
else:
site_ids = [int(x) for x in form.data.getlist('sites')]
def intersects_sites(sibling):
return sibling.sites.filter(id__in=site_ids).count() > 0
else:
def intersects_sites(sibling):
return True
return intersects_sites | python | def intersect_sites_method(form):
"""Return a method to intersect sites."""
if settings.PAGE_USE_SITE_ID:
if settings.PAGE_HIDE_SITES:
site_ids = [global_settings.SITE_ID]
else:
site_ids = [int(x) for x in form.data.getlist('sites')]
def intersects_sites(sibling):
return sibling.sites.filter(id__in=site_ids).count() > 0
else:
def intersects_sites(sibling):
return True
return intersects_sites | [
"def",
"intersect_sites_method",
"(",
"form",
")",
":",
"if",
"settings",
".",
"PAGE_USE_SITE_ID",
":",
"if",
"settings",
".",
"PAGE_HIDE_SITES",
":",
"site_ids",
"=",
"[",
"global_settings",
".",
"SITE_ID",
"]",
"else",
":",
"site_ids",
"=",
"[",
"int",
"("... | Return a method to intersect sites. | [
"Return",
"a",
"method",
"to",
"intersect",
"sites",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/forms.py#L50-L62 | train | 31,229 |
batiste/django-page-cms | pages/widgets.py | PageLinkWidget._has_changed | def _has_changed(self, initial, data):
"""Need to be reimplemented to be correct."""
if data == initial:
return False
return bool(initial) != bool(data) | python | def _has_changed(self, initial, data):
"""Need to be reimplemented to be correct."""
if data == initial:
return False
return bool(initial) != bool(data) | [
"def",
"_has_changed",
"(",
"self",
",",
"initial",
",",
"data",
")",
":",
"if",
"data",
"==",
"initial",
":",
"return",
"False",
"return",
"bool",
"(",
"initial",
")",
"!=",
"bool",
"(",
"data",
")"
] | Need to be reimplemented to be correct. | [
"Need",
"to",
"be",
"reimplemented",
"to",
"be",
"correct",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/widgets.py#L196-L200 | train | 31,230 |
batiste/django-page-cms | pages/plugins/jsonexport/utils.py | update_redirect_to_from_json | def update_redirect_to_from_json(page, redirect_to_complete_slugs):
"""
The second pass of create_and_update_from_json_data
used to update the redirect_to field.
Returns a messages list to be appended to the messages from the
first pass.
"""
messages = []
s = ''
for lang, s in list(redirect_to_complete_slugs.items()):
r = Page.objects.from_path(s, lang, exclude_drafts=False)
if r:
page.redirect_to = r
page.save()
break
else:
messages.append(_("Could not find page for redirect-to field"
" '%s'") % (s,))
return messages | python | def update_redirect_to_from_json(page, redirect_to_complete_slugs):
"""
The second pass of create_and_update_from_json_data
used to update the redirect_to field.
Returns a messages list to be appended to the messages from the
first pass.
"""
messages = []
s = ''
for lang, s in list(redirect_to_complete_slugs.items()):
r = Page.objects.from_path(s, lang, exclude_drafts=False)
if r:
page.redirect_to = r
page.save()
break
else:
messages.append(_("Could not find page for redirect-to field"
" '%s'") % (s,))
return messages | [
"def",
"update_redirect_to_from_json",
"(",
"page",
",",
"redirect_to_complete_slugs",
")",
":",
"messages",
"=",
"[",
"]",
"s",
"=",
"''",
"for",
"lang",
",",
"s",
"in",
"list",
"(",
"redirect_to_complete_slugs",
".",
"items",
"(",
")",
")",
":",
"r",
"="... | The second pass of create_and_update_from_json_data
used to update the redirect_to field.
Returns a messages list to be appended to the messages from the
first pass. | [
"The",
"second",
"pass",
"of",
"create_and_update_from_json_data",
"used",
"to",
"update",
"the",
"redirect_to",
"field",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/plugins/jsonexport/utils.py#L109-L128 | train | 31,231 |
batiste/django-page-cms | pages/placeholders.py | get_filename | def get_filename(page, content_type, data):
"""
Generate a stable filename using the original filename of the type.
"""
avoid_collision = uuid.uuid4().hex[:8]
name_parts = data.name.split('.')
if len(name_parts) > 1:
name = slugify('.'.join(name_parts[:-1]), allow_unicode=True)
ext = slugify(name_parts[-1])
name = name + '.' + ext
else:
name = slugify(data.name)
filename = os.path.join(
settings.PAGE_UPLOAD_ROOT,
'page_' + str(page.id),
content_type + '-' + avoid_collision + '-' + name
)
return filename | python | def get_filename(page, content_type, data):
"""
Generate a stable filename using the original filename of the type.
"""
avoid_collision = uuid.uuid4().hex[:8]
name_parts = data.name.split('.')
if len(name_parts) > 1:
name = slugify('.'.join(name_parts[:-1]), allow_unicode=True)
ext = slugify(name_parts[-1])
name = name + '.' + ext
else:
name = slugify(data.name)
filename = os.path.join(
settings.PAGE_UPLOAD_ROOT,
'page_' + str(page.id),
content_type + '-' + avoid_collision + '-' + name
)
return filename | [
"def",
"get_filename",
"(",
"page",
",",
"content_type",
",",
"data",
")",
":",
"avoid_collision",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"[",
":",
"8",
"]",
"name_parts",
"=",
"data",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"if",
"le... | Generate a stable filename using the original filename of the type. | [
"Generate",
"a",
"stable",
"filename",
"using",
"the",
"original",
"filename",
"of",
"the",
"type",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/placeholders.py#L309-L329 | train | 31,232 |
batiste/django-page-cms | pages/placeholders.py | PlaceholderNode.get_field | def get_field(self, page, language, initial=None):
"""The field that will be shown within the admin."""
if self.parsed:
help_text = _('Note: This field is evaluated as template code.')
else:
help_text = ''
widget = self.get_widget(page, language)
return self.field(
widget=widget, initial=initial,
help_text=help_text, required=False) | python | def get_field(self, page, language, initial=None):
"""The field that will be shown within the admin."""
if self.parsed:
help_text = _('Note: This field is evaluated as template code.')
else:
help_text = ''
widget = self.get_widget(page, language)
return self.field(
widget=widget, initial=initial,
help_text=help_text, required=False) | [
"def",
"get_field",
"(",
"self",
",",
"page",
",",
"language",
",",
"initial",
"=",
"None",
")",
":",
"if",
"self",
".",
"parsed",
":",
"help_text",
"=",
"_",
"(",
"'Note: This field is evaluated as template code.'",
")",
"else",
":",
"help_text",
"=",
"''",... | The field that will be shown within the admin. | [
"The",
"field",
"that",
"will",
"be",
"shown",
"within",
"the",
"admin",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/placeholders.py#L162-L171 | train | 31,233 |
batiste/django-page-cms | pages/placeholders.py | PlaceholderNode.render | def render(self, context):
"""Output the content of the `PlaceholdeNode` as a template."""
content = self.get_render_content(context)
request = context.get('request')
render_edit_tag = False
if request and request.user.is_staff and request.COOKIES.get('enable_edit_mode'):
render_edit_tag = True
if not content:
if not render_edit_tag:
return ''
return self.edit_tag()
if self.parsed:
content = self.render_parsed(context, content)
if self.as_varname is None:
if not render_edit_tag:
return content
return content + self.edit_tag()
context[self.as_varname] = content
return '' | python | def render(self, context):
"""Output the content of the `PlaceholdeNode` as a template."""
content = self.get_render_content(context)
request = context.get('request')
render_edit_tag = False
if request and request.user.is_staff and request.COOKIES.get('enable_edit_mode'):
render_edit_tag = True
if not content:
if not render_edit_tag:
return ''
return self.edit_tag()
if self.parsed:
content = self.render_parsed(context, content)
if self.as_varname is None:
if not render_edit_tag:
return content
return content + self.edit_tag()
context[self.as_varname] = content
return '' | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"content",
"=",
"self",
".",
"get_render_content",
"(",
"context",
")",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
")",
"render_edit_tag",
"=",
"False",
"if",
"request",
"and",
"request"... | Output the content of the `PlaceholdeNode` as a template. | [
"Output",
"the",
"content",
"of",
"the",
"PlaceholdeNode",
"as",
"a",
"template",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/placeholders.py#L282-L303 | train | 31,234 |
batiste/django-page-cms | pages/placeholders.py | MarkdownPlaceholderNode.render | def render(self, context):
"""Render markdown."""
import markdown
content = self.get_content_from_context(context)
return markdown.markdown(content) | python | def render(self, context):
"""Render markdown."""
import markdown
content = self.get_content_from_context(context)
return markdown.markdown(content) | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"import",
"markdown",
"content",
"=",
"self",
".",
"get_content_from_context",
"(",
"context",
")",
"return",
"markdown",
".",
"markdown",
"(",
"content",
")"
] | Render markdown. | [
"Render",
"markdown",
"."
] | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/placeholders.py#L472-L476 | train | 31,235 |
batiste/django-page-cms | pages/plugins/jsonexport/management/commands/pages_import_json.py | Command.handle | def handle(self, user, **options):
"""
Import pages in JSON format. When creating a page and the original
author does not exist, use user as the new author. User may be
specified by username, id or email address.
"""
monkeypatch_remove_pages_site_restrictions()
user_model = get_user_model()
for match in ('username', 'pk', 'email'):
try:
u = user_model.objects.get(**{match: user})
break
except (user_model.DoesNotExist, ValueError):
continue
else:
raise CommandError(_("User with username/id/email = '%s' not found")
% user)
json = sys.stdin.read()
errors, pages_created = json_to_pages(json, u)
if errors:
for e in errors:
sys.stderr.write(e + '\n')
raise CommandError(_("Errors encountered while importing JSON"))
for page, created, messages in pages_created:
print((_("%s created.") if created else _("%s modified.")) % (
page.get_complete_slug()))
for m in messages:
print(" - " + m) | python | def handle(self, user, **options):
"""
Import pages in JSON format. When creating a page and the original
author does not exist, use user as the new author. User may be
specified by username, id or email address.
"""
monkeypatch_remove_pages_site_restrictions()
user_model = get_user_model()
for match in ('username', 'pk', 'email'):
try:
u = user_model.objects.get(**{match: user})
break
except (user_model.DoesNotExist, ValueError):
continue
else:
raise CommandError(_("User with username/id/email = '%s' not found")
% user)
json = sys.stdin.read()
errors, pages_created = json_to_pages(json, u)
if errors:
for e in errors:
sys.stderr.write(e + '\n')
raise CommandError(_("Errors encountered while importing JSON"))
for page, created, messages in pages_created:
print((_("%s created.") if created else _("%s modified.")) % (
page.get_complete_slug()))
for m in messages:
print(" - " + m) | [
"def",
"handle",
"(",
"self",
",",
"user",
",",
"*",
"*",
"options",
")",
":",
"monkeypatch_remove_pages_site_restrictions",
"(",
")",
"user_model",
"=",
"get_user_model",
"(",
")",
"for",
"match",
"in",
"(",
"'username'",
",",
"'pk'",
",",
"'email'",
")",
... | Import pages in JSON format. When creating a page and the original
author does not exist, use user as the new author. User may be
specified by username, id or email address. | [
"Import",
"pages",
"in",
"JSON",
"format",
".",
"When",
"creating",
"a",
"page",
"and",
"the",
"original",
"author",
"does",
"not",
"exist",
"use",
"user",
"as",
"the",
"new",
"author",
".",
"User",
"may",
"be",
"specified",
"by",
"username",
"id",
"or",... | 3c72111eb7c3997a63c462c1776ffd8ce8c50a5d | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/plugins/jsonexport/management/commands/pages_import_json.py#L13-L41 | train | 31,236 |
wbond/pybars3 | pybars/_compiler.py | prepare | def prepare(value, should_escape):
"""
Prepares a value to be added to the result
:param value:
The value to add to the result
:param should_escape:
If the string should be HTML-escaped
:return:
A unicode string or strlist
"""
if value is None:
return u''
type_ = type(value)
if type_ is not strlist:
if type_ is not str_class:
if type_ is bool:
value = u'true' if value else u'false'
else:
value = str_class(value)
if should_escape:
value = escape(value)
return value | python | def prepare(value, should_escape):
"""
Prepares a value to be added to the result
:param value:
The value to add to the result
:param should_escape:
If the string should be HTML-escaped
:return:
A unicode string or strlist
"""
if value is None:
return u''
type_ = type(value)
if type_ is not strlist:
if type_ is not str_class:
if type_ is bool:
value = u'true' if value else u'false'
else:
value = str_class(value)
if should_escape:
value = escape(value)
return value | [
"def",
"prepare",
"(",
"value",
",",
"should_escape",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"u''",
"type_",
"=",
"type",
"(",
"value",
")",
"if",
"type_",
"is",
"not",
"strlist",
":",
"if",
"type_",
"is",
"not",
"str_class",
":",
"if"... | Prepares a value to be added to the result
:param value:
The value to add to the result
:param should_escape:
If the string should be HTML-escaped
:return:
A unicode string or strlist | [
"Prepares",
"a",
"value",
"to",
"be",
"added",
"to",
"the",
"result"
] | 71f13d1012d3746e76099d8db141c43fc769cfed | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L330-L355 | train | 31,237 |
wbond/pybars3 | pybars/_compiler.py | strlist.grow | def grow(self, thing):
"""Make the list longer, appending for unicode, extending otherwise."""
if type(thing) == str_class:
self.append(thing)
# This will only ever match in Python 2 since str_class is str in
# Python 3.
elif type(thing) == str:
self.append(unicode(thing)) # noqa: F821 undefined name 'unicode'
else:
# Recursively expand to a flat list; may deserve a C accelerator at
# some point.
for element in thing:
self.grow(element) | python | def grow(self, thing):
"""Make the list longer, appending for unicode, extending otherwise."""
if type(thing) == str_class:
self.append(thing)
# This will only ever match in Python 2 since str_class is str in
# Python 3.
elif type(thing) == str:
self.append(unicode(thing)) # noqa: F821 undefined name 'unicode'
else:
# Recursively expand to a flat list; may deserve a C accelerator at
# some point.
for element in thing:
self.grow(element) | [
"def",
"grow",
"(",
"self",
",",
"thing",
")",
":",
"if",
"type",
"(",
"thing",
")",
"==",
"str_class",
":",
"self",
".",
"append",
"(",
"thing",
")",
"# This will only ever match in Python 2 since str_class is str in",
"# Python 3.",
"elif",
"type",
"(",
"thing... | Make the list longer, appending for unicode, extending otherwise. | [
"Make",
"the",
"list",
"longer",
"appending",
"for",
"unicode",
"extending",
"otherwise",
"."
] | 71f13d1012d3746e76099d8db141c43fc769cfed | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L189-L203 | train | 31,238 |
wbond/pybars3 | pybars/_compiler.py | Compiler._extract_word | def _extract_word(self, source, position):
"""
Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word
"""
boundry = re.search('{{|{|\s|$', source[:position][::-1])
start_offset = boundry.end() if boundry.group(0).startswith('{') else boundry.start()
boundry = re.search('}}|}|\s|$', source[position:])
end_offset = boundry.end() if boundry.group(0).startswith('}') else boundry.start()
return source[position - start_offset:position + end_offset] | python | def _extract_word(self, source, position):
"""
Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word
"""
boundry = re.search('{{|{|\s|$', source[:position][::-1])
start_offset = boundry.end() if boundry.group(0).startswith('{') else boundry.start()
boundry = re.search('}}|}|\s|$', source[position:])
end_offset = boundry.end() if boundry.group(0).startswith('}') else boundry.start()
return source[position - start_offset:position + end_offset] | [
"def",
"_extract_word",
"(",
"self",
",",
"source",
",",
"position",
")",
":",
"boundry",
"=",
"re",
".",
"search",
"(",
"'{{|{|\\s|$'",
",",
"source",
"[",
":",
"position",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"start_offset",
"=",
"boundry",
".",... | Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word | [
"Extracts",
"the",
"word",
"that",
"falls",
"at",
"or",
"around",
"a",
"specific",
"position"
] | 71f13d1012d3746e76099d8db141c43fc769cfed | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L779-L797 | train | 31,239 |
wbond/pybars3 | pybars/_compiler.py | Compiler.compile | def compile(self, source, path=None):
"""Compile source to a ready to run template.
:param source:
The template to compile - should be a unicode string
:return:
A template function ready to execute
"""
container = self._generate_code(source)
def make_module_name(name, suffix=None):
output = 'pybars._templates.%s' % name
if suffix:
output += '_%s' % suffix
return output
if not path:
path = '_template'
generate_name = True
else:
path = path.replace('\\', '/')
path = path.replace('/', '_')
mod_name = make_module_name(path)
generate_name = mod_name in sys.modules
if generate_name:
mod_name = make_module_name(path, self.template_counter)
while mod_name in sys.modules:
self.template_counter += 1
mod_name = make_module_name(path, self.template_counter)
mod = ModuleType(mod_name)
filename = '%s.py' % mod_name.replace('pybars.', '').replace('.', '/')
exec(compile(container.full_code, filename, 'exec', dont_inherit=True), mod.__dict__)
sys.modules[mod_name] = mod
linecache.getlines(filename, mod.__dict__)
return mod.__dict__[container.name] | python | def compile(self, source, path=None):
"""Compile source to a ready to run template.
:param source:
The template to compile - should be a unicode string
:return:
A template function ready to execute
"""
container = self._generate_code(source)
def make_module_name(name, suffix=None):
output = 'pybars._templates.%s' % name
if suffix:
output += '_%s' % suffix
return output
if not path:
path = '_template'
generate_name = True
else:
path = path.replace('\\', '/')
path = path.replace('/', '_')
mod_name = make_module_name(path)
generate_name = mod_name in sys.modules
if generate_name:
mod_name = make_module_name(path, self.template_counter)
while mod_name in sys.modules:
self.template_counter += 1
mod_name = make_module_name(path, self.template_counter)
mod = ModuleType(mod_name)
filename = '%s.py' % mod_name.replace('pybars.', '').replace('.', '/')
exec(compile(container.full_code, filename, 'exec', dont_inherit=True), mod.__dict__)
sys.modules[mod_name] = mod
linecache.getlines(filename, mod.__dict__)
return mod.__dict__[container.name] | [
"def",
"compile",
"(",
"self",
",",
"source",
",",
"path",
"=",
"None",
")",
":",
"container",
"=",
"self",
".",
"_generate_code",
"(",
"source",
")",
"def",
"make_module_name",
"(",
"name",
",",
"suffix",
"=",
"None",
")",
":",
"output",
"=",
"'pybars... | Compile source to a ready to run template.
:param source:
The template to compile - should be a unicode string
:return:
A template function ready to execute | [
"Compile",
"source",
"to",
"a",
"ready",
"to",
"run",
"template",
"."
] | 71f13d1012d3746e76099d8db141c43fc769cfed | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L852-L891 | train | 31,240 |
wbond/pybars3 | pybars/_compiler.py | Compiler.clean_whitespace | def clean_whitespace(self, tree):
"""
Cleans up whitespace around block open and close tags if they are the
only thing on the line
:param tree:
The AST - will be modified in place
"""
pointer = 0
end = len(tree)
while pointer < end:
piece = tree[pointer]
if piece[0] == 'block':
child_tree = piece[3]
# Look at open tag, if the only other thing on the line is whitespace
# then delete it so we don't introduce extra newlines to the output
open_pre_whitespace = False
open_pre_content = True
if pointer > 1 and tree[pointer - 1][0] == 'whitespace' and (tree[pointer - 2][0] == 'newline' or tree[pointer - 2] == 'template'):
open_pre_whitespace = True
open_pre_content = False
elif pointer > 0 and (tree[pointer - 1][0] == 'newline' or tree[pointer - 1] == 'template'):
open_pre_content = False
open_post_whitespace = False
open_post_content = True
child_len = len(child_tree)
if child_len > 2 and child_tree[1][0] == 'whitespace' and child_tree[2][0] == 'newline':
open_post_whitespace = True
open_post_content = False
elif child_len > 1 and child_tree[1][0] == 'newline':
open_post_content = False
if not open_pre_content and not open_post_content:
if open_pre_whitespace:
tree.pop(pointer - 1)
pointer -= 1
end -= 1
if open_post_whitespace:
child_tree.pop(1)
child_tree.pop(1) # trailing newline
# Do the same thing, but for the close tag
close_pre_whitespace = False
close_pre_content = True
child_len = len(child_tree)
if child_len > 2 and child_tree[child_len - 1][0] == 'whitespace' and child_tree[child_len - 2][0] == 'newline':
close_pre_whitespace = True
close_pre_content = False
elif child_len > 1 and child_tree[child_len - 1][0] == 'newline':
close_pre_content = False
close_post_whitespace = False
close_post_content = True
tree_len = len(tree)
if tree_len > pointer + 2 and tree[pointer + 1][0] == 'whitespace' and tree[pointer + 2][0] == 'newline':
close_post_whitespace = True
close_post_content = False
elif tree_len == pointer + 2 and tree[pointer + 1][0] == 'whitespace':
close_post_whitespace = True
close_post_content = False
elif tree_len > pointer + 1 and tree[pointer + 1][0] == 'newline':
close_post_content = False
elif tree_len == pointer + 1:
close_post_content = False
if not close_pre_content and not close_post_content:
if close_pre_whitespace:
child_tree.pop()
child_tree.pop() # preceeding newline
if close_post_whitespace:
tree.pop(pointer + 1)
end -= 1
self.clean_whitespace(child_tree)
pointer += 1 | python | def clean_whitespace(self, tree):
"""
Cleans up whitespace around block open and close tags if they are the
only thing on the line
:param tree:
The AST - will be modified in place
"""
pointer = 0
end = len(tree)
while pointer < end:
piece = tree[pointer]
if piece[0] == 'block':
child_tree = piece[3]
# Look at open tag, if the only other thing on the line is whitespace
# then delete it so we don't introduce extra newlines to the output
open_pre_whitespace = False
open_pre_content = True
if pointer > 1 and tree[pointer - 1][0] == 'whitespace' and (tree[pointer - 2][0] == 'newline' or tree[pointer - 2] == 'template'):
open_pre_whitespace = True
open_pre_content = False
elif pointer > 0 and (tree[pointer - 1][0] == 'newline' or tree[pointer - 1] == 'template'):
open_pre_content = False
open_post_whitespace = False
open_post_content = True
child_len = len(child_tree)
if child_len > 2 and child_tree[1][0] == 'whitespace' and child_tree[2][0] == 'newline':
open_post_whitespace = True
open_post_content = False
elif child_len > 1 and child_tree[1][0] == 'newline':
open_post_content = False
if not open_pre_content and not open_post_content:
if open_pre_whitespace:
tree.pop(pointer - 1)
pointer -= 1
end -= 1
if open_post_whitespace:
child_tree.pop(1)
child_tree.pop(1) # trailing newline
# Do the same thing, but for the close tag
close_pre_whitespace = False
close_pre_content = True
child_len = len(child_tree)
if child_len > 2 and child_tree[child_len - 1][0] == 'whitespace' and child_tree[child_len - 2][0] == 'newline':
close_pre_whitespace = True
close_pre_content = False
elif child_len > 1 and child_tree[child_len - 1][0] == 'newline':
close_pre_content = False
close_post_whitespace = False
close_post_content = True
tree_len = len(tree)
if tree_len > pointer + 2 and tree[pointer + 1][0] == 'whitespace' and tree[pointer + 2][0] == 'newline':
close_post_whitespace = True
close_post_content = False
elif tree_len == pointer + 2 and tree[pointer + 1][0] == 'whitespace':
close_post_whitespace = True
close_post_content = False
elif tree_len > pointer + 1 and tree[pointer + 1][0] == 'newline':
close_post_content = False
elif tree_len == pointer + 1:
close_post_content = False
if not close_pre_content and not close_post_content:
if close_pre_whitespace:
child_tree.pop()
child_tree.pop() # preceeding newline
if close_post_whitespace:
tree.pop(pointer + 1)
end -= 1
self.clean_whitespace(child_tree)
pointer += 1 | [
"def",
"clean_whitespace",
"(",
"self",
",",
"tree",
")",
":",
"pointer",
"=",
"0",
"end",
"=",
"len",
"(",
"tree",
")",
"while",
"pointer",
"<",
"end",
":",
"piece",
"=",
"tree",
"[",
"pointer",
"]",
"if",
"piece",
"[",
"0",
"]",
"==",
"'block'",
... | Cleans up whitespace around block open and close tags if they are the
only thing on the line
:param tree:
The AST - will be modified in place | [
"Cleans",
"up",
"whitespace",
"around",
"block",
"open",
"and",
"close",
"tags",
"if",
"they",
"are",
"the",
"only",
"thing",
"on",
"the",
"line"
] | 71f13d1012d3746e76099d8db141c43fc769cfed | https://github.com/wbond/pybars3/blob/71f13d1012d3746e76099d8db141c43fc769cfed/pybars/_compiler.py#L905-L984 | train | 31,241 |
Toilal/rebulk | rebulk/processors.py | _default_conflict_solver | def _default_conflict_solver(match, conflicting_match):
"""
Default conflict solver for matches, shorter matches if they conflicts with longer ones
:param conflicting_match:
:type conflicting_match:
:param match:
:type match:
:return:
:rtype:
"""
if len(conflicting_match.initiator) < len(match.initiator):
return conflicting_match
if len(match.initiator) < len(conflicting_match.initiator):
return match
return None | python | def _default_conflict_solver(match, conflicting_match):
"""
Default conflict solver for matches, shorter matches if they conflicts with longer ones
:param conflicting_match:
:type conflicting_match:
:param match:
:type match:
:return:
:rtype:
"""
if len(conflicting_match.initiator) < len(match.initiator):
return conflicting_match
if len(match.initiator) < len(conflicting_match.initiator):
return match
return None | [
"def",
"_default_conflict_solver",
"(",
"match",
",",
"conflicting_match",
")",
":",
"if",
"len",
"(",
"conflicting_match",
".",
"initiator",
")",
"<",
"len",
"(",
"match",
".",
"initiator",
")",
":",
"return",
"conflicting_match",
"if",
"len",
"(",
"match",
... | Default conflict solver for matches, shorter matches if they conflicts with longer ones
:param conflicting_match:
:type conflicting_match:
:param match:
:type match:
:return:
:rtype: | [
"Default",
"conflict",
"solver",
"for",
"matches",
"shorter",
"matches",
"if",
"they",
"conflicts",
"with",
"longer",
"ones"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/processors.py#L20-L35 | train | 31,242 |
Toilal/rebulk | rebulk/loose.py | call | def call(function, *args, **kwargs):
"""
Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: sale vakye as default function call
:rtype: object
"""
func = constructor_args if inspect.isclass(function) else function_args
call_args, call_kwargs = func(function, *args, **kwargs)
return function(*call_args, **call_kwargs) | python | def call(function, *args, **kwargs):
"""
Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: sale vakye as default function call
:rtype: object
"""
func = constructor_args if inspect.isclass(function) else function_args
call_args, call_kwargs = func(function, *args, **kwargs)
return function(*call_args, **call_kwargs) | [
"def",
"call",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"constructor_args",
"if",
"inspect",
".",
"isclass",
"(",
"function",
")",
"else",
"function_args",
"call_args",
",",
"call_kwargs",
"=",
"func",
"(",
"func... | Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: sale vakye as default function call
:rtype: object | [
"Call",
"a",
"function",
"or",
"constructor",
"with",
"given",
"args",
"and",
"kwargs",
"after",
"removing",
"args",
"and",
"kwargs",
"that",
"doesn",
"t",
"match",
"function",
"or",
"constructor",
"signature"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/loose.py#L44-L60 | train | 31,243 |
Toilal/rebulk | rebulk/loose.py | ensure_dict | def ensure_dict(param, default_value, default_key=None):
"""
Retrieves a dict and a default value from given parameter.
if parameter is not a dict, it will be promoted as the default value.
:param param:
:type param:
:param default_value:
:type default_value:
:param default_key:
:type default_key:
:return:
:rtype:
"""
if not param:
param = default_value
if not isinstance(param, dict):
if param:
default_value = param
return {default_key: param}, default_value
return param, default_value | python | def ensure_dict(param, default_value, default_key=None):
"""
Retrieves a dict and a default value from given parameter.
if parameter is not a dict, it will be promoted as the default value.
:param param:
:type param:
:param default_value:
:type default_value:
:param default_key:
:type default_key:
:return:
:rtype:
"""
if not param:
param = default_value
if not isinstance(param, dict):
if param:
default_value = param
return {default_key: param}, default_value
return param, default_value | [
"def",
"ensure_dict",
"(",
"param",
",",
"default_value",
",",
"default_key",
"=",
"None",
")",
":",
"if",
"not",
"param",
":",
"param",
"=",
"default_value",
"if",
"not",
"isinstance",
"(",
"param",
",",
"dict",
")",
":",
"if",
"param",
":",
"default_va... | Retrieves a dict and a default value from given parameter.
if parameter is not a dict, it will be promoted as the default value.
:param param:
:type param:
:param default_value:
:type default_value:
:param default_key:
:type default_key:
:return:
:rtype: | [
"Retrieves",
"a",
"dict",
"and",
"a",
"default",
"value",
"from",
"given",
"parameter",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/loose.py#L167-L188 | train | 31,244 |
Toilal/rebulk | rebulk/loose.py | filter_index | def filter_index(collection, predicate=None, index=None):
"""
Filter collection with predicate function and index.
If index is not found, returns None.
:param collection:
:type collection: collection supporting iteration and slicing
:param predicate: function to filter the collection with
:type predicate: function
:param index: position of a single element to retrieve
:type index: int
:return: filtered list, or single element of filtered list if index is defined
:rtype: list or object
"""
if index is None and isinstance(predicate, int):
index = predicate
predicate = None
if predicate:
collection = collection.__class__(filter(predicate, collection))
if index is not None:
try:
collection = collection[index]
except IndexError:
collection = None
return collection | python | def filter_index(collection, predicate=None, index=None):
"""
Filter collection with predicate function and index.
If index is not found, returns None.
:param collection:
:type collection: collection supporting iteration and slicing
:param predicate: function to filter the collection with
:type predicate: function
:param index: position of a single element to retrieve
:type index: int
:return: filtered list, or single element of filtered list if index is defined
:rtype: list or object
"""
if index is None and isinstance(predicate, int):
index = predicate
predicate = None
if predicate:
collection = collection.__class__(filter(predicate, collection))
if index is not None:
try:
collection = collection[index]
except IndexError:
collection = None
return collection | [
"def",
"filter_index",
"(",
"collection",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
"and",
"isinstance",
"(",
"predicate",
",",
"int",
")",
":",
"index",
"=",
"predicate",
"predicate",
"=",
"None",
... | Filter collection with predicate function and index.
If index is not found, returns None.
:param collection:
:type collection: collection supporting iteration and slicing
:param predicate: function to filter the collection with
:type predicate: function
:param index: position of a single element to retrieve
:type index: int
:return: filtered list, or single element of filtered list if index is defined
:rtype: list or object | [
"Filter",
"collection",
"with",
"predicate",
"function",
"and",
"index",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/loose.py#L191-L215 | train | 31,245 |
Toilal/rebulk | rebulk/rules.py | Rules.load | def load(self, *rules):
"""
Load rules from a Rule module, class or instance
:param rules:
:type rules:
:return:
:rtype:
"""
for rule in rules:
if inspect.ismodule(rule):
self.load_module(rule)
elif inspect.isclass(rule):
self.load_class(rule)
else:
self.append(rule) | python | def load(self, *rules):
"""
Load rules from a Rule module, class or instance
:param rules:
:type rules:
:return:
:rtype:
"""
for rule in rules:
if inspect.ismodule(rule):
self.load_module(rule)
elif inspect.isclass(rule):
self.load_class(rule)
else:
self.append(rule) | [
"def",
"load",
"(",
"self",
",",
"*",
"rules",
")",
":",
"for",
"rule",
"in",
"rules",
":",
"if",
"inspect",
".",
"ismodule",
"(",
"rule",
")",
":",
"self",
".",
"load_module",
"(",
"rule",
")",
"elif",
"inspect",
".",
"isclass",
"(",
"rule",
")",
... | Load rules from a Rule module, class or instance
:param rules:
:type rules:
:return:
:rtype: | [
"Load",
"rules",
"from",
"a",
"Rule",
"module",
"class",
"or",
"instance"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rules.py#L249-L264 | train | 31,246 |
Toilal/rebulk | rebulk/rules.py | Rules.load_module | def load_module(self, module):
"""
Load a rules module
:param module:
:type module:
:return:
:rtype:
"""
# pylint: disable=unused-variable
for name, obj in inspect.getmembers(module,
lambda member: hasattr(member, '__module__')
and member.__module__ == module.__name__
and inspect.isclass):
self.load_class(obj) | python | def load_module(self, module):
"""
Load a rules module
:param module:
:type module:
:return:
:rtype:
"""
# pylint: disable=unused-variable
for name, obj in inspect.getmembers(module,
lambda member: hasattr(member, '__module__')
and member.__module__ == module.__name__
and inspect.isclass):
self.load_class(obj) | [
"def",
"load_module",
"(",
"self",
",",
"module",
")",
":",
"# pylint: disable=unused-variable",
"for",
"name",
",",
"obj",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"lambda",
"member",
":",
"hasattr",
"(",
"member",
",",
"'__module__'",
")",
"... | Load a rules module
:param module:
:type module:
:return:
:rtype: | [
"Load",
"a",
"rules",
"module"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rules.py#L266-L280 | train | 31,247 |
Toilal/rebulk | rebulk/rules.py | Rules.execute_all_rules | def execute_all_rules(self, matches, context):
"""
Execute all rules from this rules list. All when condition with same priority will be performed before
calling then actions.
:param matches:
:type matches:
:param context:
:type context:
:return:
:rtype:
"""
ret = []
for priority, priority_rules in groupby(sorted(self), lambda rule: rule.priority):
sorted_rules = toposort_rules(list(priority_rules)) # Group by dependency graph toposort
for rules_group in sorted_rules:
rules_group = list(sorted(rules_group, key=self.index)) # Sort rules group based on initial ordering.
group_log_level = None
for rule in rules_group:
if group_log_level is None or group_log_level < rule.log_level:
group_log_level = rule.log_level
log(group_log_level, "%s independent rule(s) at priority %s.", len(rules_group), priority)
for rule in rules_group:
when_response = execute_rule(rule, matches, context)
if when_response is not None:
ret.append((rule, when_response))
return ret | python | def execute_all_rules(self, matches, context):
"""
Execute all rules from this rules list. All when condition with same priority will be performed before
calling then actions.
:param matches:
:type matches:
:param context:
:type context:
:return:
:rtype:
"""
ret = []
for priority, priority_rules in groupby(sorted(self), lambda rule: rule.priority):
sorted_rules = toposort_rules(list(priority_rules)) # Group by dependency graph toposort
for rules_group in sorted_rules:
rules_group = list(sorted(rules_group, key=self.index)) # Sort rules group based on initial ordering.
group_log_level = None
for rule in rules_group:
if group_log_level is None or group_log_level < rule.log_level:
group_log_level = rule.log_level
log(group_log_level, "%s independent rule(s) at priority %s.", len(rules_group), priority)
for rule in rules_group:
when_response = execute_rule(rule, matches, context)
if when_response is not None:
ret.append((rule, when_response))
return ret | [
"def",
"execute_all_rules",
"(",
"self",
",",
"matches",
",",
"context",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"priority",
",",
"priority_rules",
"in",
"groupby",
"(",
"sorted",
"(",
"self",
")",
",",
"lambda",
"rule",
":",
"rule",
".",
"priority",
")... | Execute all rules from this rules list. All when condition with same priority will be performed before
calling then actions.
:param matches:
:type matches:
:param context:
:type context:
:return:
:rtype: | [
"Execute",
"all",
"rules",
"from",
"this",
"rules",
"list",
".",
"All",
"when",
"condition",
"with",
"same",
"priority",
"will",
"be",
"performed",
"before",
"calling",
"then",
"actions",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rules.py#L293-L320 | train | 31,248 |
Toilal/rebulk | rebulk/match.py | _BaseMatches.at_match | def at_match(self, match, predicate=None, index=None):
"""
Retrieves a list of matches from given match.
"""
return self.at_span(match.span, predicate, index) | python | def at_match(self, match, predicate=None, index=None):
"""
Retrieves a list of matches from given match.
"""
return self.at_span(match.span, predicate, index) | [
"def",
"at_match",
"(",
"self",
",",
"match",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"return",
"self",
".",
"at_span",
"(",
"match",
".",
"span",
",",
"predicate",
",",
"index",
")"
] | Retrieves a list of matches from given match. | [
"Retrieves",
"a",
"list",
"of",
"matches",
"from",
"given",
"match",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/match.py#L458-L462 | train | 31,249 |
Toilal/rebulk | rebulk/match.py | _BaseMatches.at_index | def at_index(self, pos, predicate=None, index=None):
"""
Retrieves a list of matches from given position
"""
return filter_index(self._index_dict[pos], predicate, index) | python | def at_index(self, pos, predicate=None, index=None):
"""
Retrieves a list of matches from given position
"""
return filter_index(self._index_dict[pos], predicate, index) | [
"def",
"at_index",
"(",
"self",
",",
"pos",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"return",
"filter_index",
"(",
"self",
".",
"_index_dict",
"[",
"pos",
"]",
",",
"predicate",
",",
"index",
")"
] | Retrieves a list of matches from given position | [
"Retrieves",
"a",
"list",
"of",
"matches",
"from",
"given",
"position"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/match.py#L478-L482 | train | 31,250 |
Toilal/rebulk | rebulk/match.py | Match.children | def children(self):
"""
Children matches.
"""
if self._children is None:
self._children = Matches(None, self.input_string)
return self._children | python | def children(self):
"""
Children matches.
"""
if self._children is None:
self._children = Matches(None, self.input_string)
return self._children | [
"def",
"children",
"(",
"self",
")",
":",
"if",
"self",
".",
"_children",
"is",
"None",
":",
"self",
".",
"_children",
"=",
"Matches",
"(",
"None",
",",
"self",
".",
"input_string",
")",
"return",
"self",
".",
"_children"
] | Children matches. | [
"Children",
"matches",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/match.py#L639-L645 | train | 31,251 |
Toilal/rebulk | rebulk/pattern.py | filter_match_kwargs | def filter_match_kwargs(kwargs, children=False):
"""
Filters out kwargs for Match construction
:param kwargs:
:type kwargs: dict
:param children:
:type children: Flag to filter children matches
:return: A filtered dict
:rtype: dict
"""
kwargs = kwargs.copy()
for key in ('pattern', 'start', 'end', 'parent', 'formatter', 'value'):
if key in kwargs:
del kwargs[key]
if children:
for key in ('name',):
if key in kwargs:
del kwargs[key]
return kwargs | python | def filter_match_kwargs(kwargs, children=False):
"""
Filters out kwargs for Match construction
:param kwargs:
:type kwargs: dict
:param children:
:type children: Flag to filter children matches
:return: A filtered dict
:rtype: dict
"""
kwargs = kwargs.copy()
for key in ('pattern', 'start', 'end', 'parent', 'formatter', 'value'):
if key in kwargs:
del kwargs[key]
if children:
for key in ('name',):
if key in kwargs:
del kwargs[key]
return kwargs | [
"def",
"filter_match_kwargs",
"(",
"kwargs",
",",
"children",
"=",
"False",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"(",
"'pattern'",
",",
"'start'",
",",
"'end'",
",",
"'parent'",
",",
"'formatter'",
",",
"'value'",... | Filters out kwargs for Match construction
:param kwargs:
:type kwargs: dict
:param children:
:type children: Flag to filter children matches
:return: A filtered dict
:rtype: dict | [
"Filters",
"out",
"kwargs",
"for",
"Match",
"construction"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/pattern.py#L470-L489 | train | 31,252 |
Toilal/rebulk | rebulk/validators.py | chars_before | def chars_before(chars, match):
"""
Validate the match if left character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype:
"""
if match.start <= 0:
return True
return match.input_string[match.start - 1] in chars | python | def chars_before(chars, match):
"""
Validate the match if left character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype:
"""
if match.start <= 0:
return True
return match.input_string[match.start - 1] in chars | [
"def",
"chars_before",
"(",
"chars",
",",
"match",
")",
":",
"if",
"match",
".",
"start",
"<=",
"0",
":",
"return",
"True",
"return",
"match",
".",
"input_string",
"[",
"match",
".",
"start",
"-",
"1",
"]",
"in",
"chars"
] | Validate the match if left character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype: | [
"Validate",
"the",
"match",
"if",
"left",
"character",
"is",
"in",
"a",
"given",
"sequence",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/validators.py#L10-L23 | train | 31,253 |
Toilal/rebulk | rebulk/validators.py | chars_after | def chars_after(chars, match):
"""
Validate the match if right character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype:
"""
if match.end >= len(match.input_string):
return True
return match.input_string[match.end] in chars | python | def chars_after(chars, match):
"""
Validate the match if right character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype:
"""
if match.end >= len(match.input_string):
return True
return match.input_string[match.end] in chars | [
"def",
"chars_after",
"(",
"chars",
",",
"match",
")",
":",
"if",
"match",
".",
"end",
">=",
"len",
"(",
"match",
".",
"input_string",
")",
":",
"return",
"True",
"return",
"match",
".",
"input_string",
"[",
"match",
".",
"end",
"]",
"in",
"chars"
] | Validate the match if right character is in a given sequence.
:param chars:
:type chars:
:param match:
:type match:
:return:
:rtype: | [
"Validate",
"the",
"match",
"if",
"right",
"character",
"is",
"in",
"a",
"given",
"sequence",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/validators.py#L26-L39 | train | 31,254 |
Toilal/rebulk | rebulk/validators.py | validators | def validators(*chained_validators):
"""
Creates a validator chain from several validator functions.
:param chained_validators:
:type chained_validators:
:return:
:rtype:
"""
def validator_chain(match): # pylint:disable=missing-docstring
for chained_validator in chained_validators:
if not chained_validator(match):
return False
return True
return validator_chain | python | def validators(*chained_validators):
"""
Creates a validator chain from several validator functions.
:param chained_validators:
:type chained_validators:
:return:
:rtype:
"""
def validator_chain(match): # pylint:disable=missing-docstring
for chained_validator in chained_validators:
if not chained_validator(match):
return False
return True
return validator_chain | [
"def",
"validators",
"(",
"*",
"chained_validators",
")",
":",
"def",
"validator_chain",
"(",
"match",
")",
":",
"# pylint:disable=missing-docstring",
"for",
"chained_validator",
"in",
"chained_validators",
":",
"if",
"not",
"chained_validator",
"(",
"match",
")",
"... | Creates a validator chain from several validator functions.
:param chained_validators:
:type chained_validators:
:return:
:rtype: | [
"Creates",
"a",
"validator",
"chain",
"from",
"several",
"validator",
"functions",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/validators.py#L56-L70 | train | 31,255 |
Toilal/rebulk | rebulk/rebulk.py | Rebulk.build_re | def build_re(self, *pattern, **kwargs):
"""
Builds a new regular expression pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._regex_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return RePattern(*pattern, **kwargs) | python | def build_re(self, *pattern, **kwargs):
"""
Builds a new regular expression pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._regex_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return RePattern(*pattern, **kwargs) | [
"def",
"build_re",
"(",
"self",
",",
"*",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"set_defaults",
"(",
"self",
".",
"_regex_defaults",
",",
"kwargs",
")",
"set_defaults",
"(",
"self",
".",
"_defaults",
",",
"kwargs",
")",
"return",
"RePattern",
"("... | Builds a new regular expression pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | [
"Builds",
"a",
"new",
"regular",
"expression",
"pattern"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L120-L133 | train | 31,256 |
Toilal/rebulk | rebulk/rebulk.py | Rebulk.build_string | def build_string(self, *pattern, **kwargs):
"""
Builds a new string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._string_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return StringPattern(*pattern, **kwargs) | python | def build_string(self, *pattern, **kwargs):
"""
Builds a new string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._string_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return StringPattern(*pattern, **kwargs) | [
"def",
"build_string",
"(",
"self",
",",
"*",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"set_defaults",
"(",
"self",
".",
"_string_defaults",
",",
"kwargs",
")",
"set_defaults",
"(",
"self",
".",
"_defaults",
",",
"kwargs",
")",
"return",
"StringPatter... | Builds a new string pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | [
"Builds",
"a",
"new",
"string",
"pattern"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L158-L171 | train | 31,257 |
Toilal/rebulk | rebulk/rebulk.py | Rebulk.build_functional | def build_functional(self, *pattern, **kwargs):
"""
Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._functional_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return FunctionalPattern(*pattern, **kwargs) | python | def build_functional(self, *pattern, **kwargs):
"""
Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._functional_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return FunctionalPattern(*pattern, **kwargs) | [
"def",
"build_functional",
"(",
"self",
",",
"*",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"set_defaults",
"(",
"self",
".",
"_functional_defaults",
",",
"kwargs",
")",
"set_defaults",
"(",
"self",
".",
"_defaults",
",",
"kwargs",
")",
"return",
"Func... | Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | [
"Builds",
"a",
"new",
"functional",
"pattern"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L196-L209 | train | 31,258 |
Toilal/rebulk | rebulk/rebulk.py | Rebulk.chain | def chain(self, **kwargs):
"""
Add patterns chain, using configuration of this rebulk
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
chain = self.build_chain(**kwargs)
self._patterns.append(chain)
return chain | python | def chain(self, **kwargs):
"""
Add patterns chain, using configuration of this rebulk
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
chain = self.build_chain(**kwargs)
self._patterns.append(chain)
return chain | [
"def",
"chain",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"chain",
"=",
"self",
".",
"build_chain",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_patterns",
".",
"append",
"(",
"chain",
")",
"return",
"chain"
] | Add patterns chain, using configuration of this rebulk
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | [
"Add",
"patterns",
"chain",
"using",
"configuration",
"of",
"this",
"rebulk"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L222-L235 | train | 31,259 |
Toilal/rebulk | rebulk/rebulk.py | Rebulk.build_chain | def build_chain(self, **kwargs):
"""
Builds a new patterns chain
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._chain_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return Chain(self, **kwargs) | python | def build_chain(self, **kwargs):
"""
Builds a new patterns chain
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._chain_defaults, kwargs)
set_defaults(self._defaults, kwargs)
return Chain(self, **kwargs) | [
"def",
"build_chain",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"set_defaults",
"(",
"self",
".",
"_chain_defaults",
",",
"kwargs",
")",
"set_defaults",
"(",
"self",
".",
"_defaults",
",",
"kwargs",
")",
"return",
"Chain",
"(",
"self",
",",
"*",
... | Builds a new patterns chain
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype: | [
"Builds",
"a",
"new",
"patterns",
"chain"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L237-L250 | train | 31,260 |
Toilal/rebulk | rebulk/chain.py | Chain.chain | def chain(self):
"""
Add patterns chain, using configuration from this chain
:return:
:rtype:
"""
# pylint: disable=protected-access
chain = self.rebulk.chain(**self._kwargs)
chain._defaults = dict(self._defaults)
chain._regex_defaults = dict(self._regex_defaults)
chain._functional_defaults = dict(self._functional_defaults)
chain._string_defaults = dict(self._string_defaults)
return chain | python | def chain(self):
"""
Add patterns chain, using configuration from this chain
:return:
:rtype:
"""
# pylint: disable=protected-access
chain = self.rebulk.chain(**self._kwargs)
chain._defaults = dict(self._defaults)
chain._regex_defaults = dict(self._regex_defaults)
chain._functional_defaults = dict(self._functional_defaults)
chain._string_defaults = dict(self._string_defaults)
return chain | [
"def",
"chain",
"(",
"self",
")",
":",
"# pylint: disable=protected-access",
"chain",
"=",
"self",
".",
"rebulk",
".",
"chain",
"(",
"*",
"*",
"self",
".",
"_kwargs",
")",
"chain",
".",
"_defaults",
"=",
"dict",
"(",
"self",
".",
"_defaults",
")",
"chain... | Add patterns chain, using configuration from this chain
:return:
:rtype: | [
"Add",
"patterns",
"chain",
"using",
"configuration",
"from",
"this",
"chain"
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/chain.py#L86-L99 | train | 31,261 |
Toilal/rebulk | rebulk/chain.py | ChainPart.repeater | def repeater(self, value):
"""
Define the repeater of the current chain part.
:param value:
:type value:
:return:
:rtype:
"""
try:
value = int(value)
self.repeater_start = value
self.repeater_end = value
return self
except ValueError:
pass
if value == '+':
self.repeater_start = 1
self.repeater_end = None
if value == '*':
self.repeater_start = 0
self.repeater_end = None
elif value == '?':
self.repeater_start = 0
self.repeater_end = 1
else:
match = re.match(r'\{\s*(\d*)\s*,?\s*(\d*)\s*\}', value)
if match:
start = match.group(1)
end = match.group(2)
if start or end:
self.repeater_start = int(start) if start else 0
self.repeater_end = int(end) if end else None
return self | python | def repeater(self, value):
"""
Define the repeater of the current chain part.
:param value:
:type value:
:return:
:rtype:
"""
try:
value = int(value)
self.repeater_start = value
self.repeater_end = value
return self
except ValueError:
pass
if value == '+':
self.repeater_start = 1
self.repeater_end = None
if value == '*':
self.repeater_start = 0
self.repeater_end = None
elif value == '?':
self.repeater_start = 0
self.repeater_end = 1
else:
match = re.match(r'\{\s*(\d*)\s*,?\s*(\d*)\s*\}', value)
if match:
start = match.group(1)
end = match.group(2)
if start or end:
self.repeater_start = int(start) if start else 0
self.repeater_end = int(end) if end else None
return self | [
"def",
"repeater",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"self",
".",
"repeater_start",
"=",
"value",
"self",
".",
"repeater_end",
"=",
"value",
"return",
"self",
"except",
"ValueError",
":",
"pass",
"... | Define the repeater of the current chain part.
:param value:
:type value:
:return:
:rtype: | [
"Define",
"the",
"repeater",
"of",
"the",
"current",
"chain",
"part",
"."
] | 7511a4671f2fd9493e3df1e5177b7656789069e8 | https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/chain.py#L431-L464 | train | 31,262 |
Kinto/kinto-attachment | kinto_attachment/utils.py | delete_attachment | def delete_attachment(request, link_field=None, uri=None):
"""Delete existing file and link."""
if link_field is None:
link_field = "record_uri"
if uri is None:
uri = record_uri(request)
# Remove file.
filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)]
storage = request.registry.storage
file_links, _ = storage.get_all("", FILE_LINKS, filters=filters)
for link in file_links:
request.attachment.delete(link['location'])
# Remove link.
storage.delete_all("", FILE_LINKS, filters=filters, with_deleted=False) | python | def delete_attachment(request, link_field=None, uri=None):
"""Delete existing file and link."""
if link_field is None:
link_field = "record_uri"
if uri is None:
uri = record_uri(request)
# Remove file.
filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)]
storage = request.registry.storage
file_links, _ = storage.get_all("", FILE_LINKS, filters=filters)
for link in file_links:
request.attachment.delete(link['location'])
# Remove link.
storage.delete_all("", FILE_LINKS, filters=filters, with_deleted=False) | [
"def",
"delete_attachment",
"(",
"request",
",",
"link_field",
"=",
"None",
",",
"uri",
"=",
"None",
")",
":",
"if",
"link_field",
"is",
"None",
":",
"link_field",
"=",
"\"record_uri\"",
"if",
"uri",
"is",
"None",
":",
"uri",
"=",
"record_uri",
"(",
"req... | Delete existing file and link. | [
"Delete",
"existing",
"file",
"and",
"link",
"."
] | b040add3e3e1c3c4344e1112e65b2eae402020e2 | https://github.com/Kinto/kinto-attachment/blob/b040add3e3e1c3c4344e1112e65b2eae402020e2/kinto_attachment/utils.py#L107-L122 | train | 31,263 |
Kinto/kinto-attachment | kinto_attachment/listeners.py | on_delete_record | def on_delete_record(event):
"""When a resource record is deleted, delete all related attachments.
When a bucket or collection is deleted, it removes the attachments of
every underlying records.
"""
keep_old_files = asbool(utils.setting_value(event.request, 'keep_old_files', default=False))
if keep_old_files:
return
# Retrieve attachments for these records using links.
resource_name = event.payload['resource_name']
filter_field = '%s_uri' % resource_name
uri = event.payload['uri']
utils.delete_attachment(event.request, link_field=filter_field, uri=uri) | python | def on_delete_record(event):
"""When a resource record is deleted, delete all related attachments.
When a bucket or collection is deleted, it removes the attachments of
every underlying records.
"""
keep_old_files = asbool(utils.setting_value(event.request, 'keep_old_files', default=False))
if keep_old_files:
return
# Retrieve attachments for these records using links.
resource_name = event.payload['resource_name']
filter_field = '%s_uri' % resource_name
uri = event.payload['uri']
utils.delete_attachment(event.request, link_field=filter_field, uri=uri) | [
"def",
"on_delete_record",
"(",
"event",
")",
":",
"keep_old_files",
"=",
"asbool",
"(",
"utils",
".",
"setting_value",
"(",
"event",
".",
"request",
",",
"'keep_old_files'",
",",
"default",
"=",
"False",
")",
")",
"if",
"keep_old_files",
":",
"return",
"# R... | When a resource record is deleted, delete all related attachments.
When a bucket or collection is deleted, it removes the attachments of
every underlying records. | [
"When",
"a",
"resource",
"record",
"is",
"deleted",
"delete",
"all",
"related",
"attachments",
".",
"When",
"a",
"bucket",
"or",
"collection",
"is",
"deleted",
"it",
"removes",
"the",
"attachments",
"of",
"every",
"underlying",
"records",
"."
] | b040add3e3e1c3c4344e1112e65b2eae402020e2 | https://github.com/Kinto/kinto-attachment/blob/b040add3e3e1c3c4344e1112e65b2eae402020e2/kinto_attachment/listeners.py#L14-L27 | train | 31,264 |
brechtm/rinohtype | src/rinoh/frontend/sphinx/__init__.py | RinohBuilder.preprocess_tree | def preprocess_tree(self, tree):
"""Transform internal refuri targets in reference nodes to refids and
transform footnote rubrics so that they do not end up in the output"""
visitor = RinohTreePreprocessor(tree, self)
tree.walkabout(visitor) | python | def preprocess_tree(self, tree):
"""Transform internal refuri targets in reference nodes to refids and
transform footnote rubrics so that they do not end up in the output"""
visitor = RinohTreePreprocessor(tree, self)
tree.walkabout(visitor) | [
"def",
"preprocess_tree",
"(",
"self",
",",
"tree",
")",
":",
"visitor",
"=",
"RinohTreePreprocessor",
"(",
"tree",
",",
"self",
")",
"tree",
".",
"walkabout",
"(",
"visitor",
")"
] | Transform internal refuri targets in reference nodes to refids and
transform footnote rubrics so that they do not end up in the output | [
"Transform",
"internal",
"refuri",
"targets",
"in",
"reference",
"nodes",
"to",
"refids",
"and",
"transform",
"footnote",
"rubrics",
"so",
"that",
"they",
"do",
"not",
"end",
"up",
"in",
"the",
"output"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/frontend/sphinx/__init__.py#L108-L112 | train | 31,265 |
brechtm/rinohtype | src/rinoh/table.py | Table._vertically_size_cells | def _vertically_size_cells(rendered_rows):
"""Grow row heights to cater for vertically spanned cells that do not
fit in the available space."""
for r, rendered_row in enumerate(rendered_rows):
for rendered_cell in rendered_row:
if rendered_cell.rowspan > 1:
row_height = sum(row.height for row in
rendered_rows[r:r + rendered_cell.rowspan])
extra_height_needed = rendered_cell.height - row_height
if extra_height_needed > 0:
padding = extra_height_needed / rendered_cell.rowspan
for i in range(r, r + rendered_cell.rowspan):
rendered_rows[i].height += padding
return rendered_rows | python | def _vertically_size_cells(rendered_rows):
"""Grow row heights to cater for vertically spanned cells that do not
fit in the available space."""
for r, rendered_row in enumerate(rendered_rows):
for rendered_cell in rendered_row:
if rendered_cell.rowspan > 1:
row_height = sum(row.height for row in
rendered_rows[r:r + rendered_cell.rowspan])
extra_height_needed = rendered_cell.height - row_height
if extra_height_needed > 0:
padding = extra_height_needed / rendered_cell.rowspan
for i in range(r, r + rendered_cell.rowspan):
rendered_rows[i].height += padding
return rendered_rows | [
"def",
"_vertically_size_cells",
"(",
"rendered_rows",
")",
":",
"for",
"r",
",",
"rendered_row",
"in",
"enumerate",
"(",
"rendered_rows",
")",
":",
"for",
"rendered_cell",
"in",
"rendered_row",
":",
"if",
"rendered_cell",
".",
"rowspan",
">",
"1",
":",
"row_h... | Grow row heights to cater for vertically spanned cells that do not
fit in the available space. | [
"Grow",
"row",
"heights",
"to",
"cater",
"for",
"vertically",
"spanned",
"cells",
"that",
"do",
"not",
"fit",
"in",
"the",
"available",
"space",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/table.py#L287-L300 | train | 31,266 |
brechtm/rinohtype | src/rinoh/table.py | Table._place_rows_and_render_borders | def _place_rows_and_render_borders(container, rendered_rows):
"""Place the rendered cells onto the page canvas and draw borders around
them."""
def draw_cell_border(rendered_cell, cell_height, container):
cell_width = rendered_cell.width
background = TableCellBackground((0, 0), cell_width, cell_height,
parent=rendered_cell.cell)
background.render(container)
for position in ('top', 'right', 'bottom', 'left'):
border = TableCellBorder(rendered_cell, cell_height, position)
border.render(container)
return background
y_cursor = container.cursor
for r, rendered_row in enumerate(rendered_rows):
container.advance(rendered_row.height)
if rendered_row.index == 0:
container.register_styled(rendered_row.row.section)
container.register_styled(rendered_row.row)
for c, rendered_cell in enumerate(rendered_row):
cell_height = sum(rendered_row.height for rendered_row in
rendered_rows[r:r + rendered_cell.rowspan])
x_cursor = rendered_cell.x_position
y_pos = float(y_cursor + cell_height)
cell_container = VirtualContainer(container)
background = draw_cell_border(rendered_cell, cell_height,
cell_container)
cell_container.place_at(container, x_cursor, y_pos)
vertical_align = rendered_cell.cell.get_style('vertical_align',
container)
if vertical_align == VerticalAlign.TOP:
vertical_offset = 0
elif vertical_align == VerticalAlign.MIDDLE:
vertical_offset = (cell_height - rendered_cell.height) / 2
elif vertical_align == VerticalAlign.BOTTOM:
vertical_offset = (cell_height - rendered_cell.height)
y_offset = float(y_cursor + vertical_offset)
rendered_cell.container.place_at(container, x_cursor, y_offset)
container.register_styled(background)
y_cursor += rendered_row.height | python | def _place_rows_and_render_borders(container, rendered_rows):
"""Place the rendered cells onto the page canvas and draw borders around
them."""
def draw_cell_border(rendered_cell, cell_height, container):
cell_width = rendered_cell.width
background = TableCellBackground((0, 0), cell_width, cell_height,
parent=rendered_cell.cell)
background.render(container)
for position in ('top', 'right', 'bottom', 'left'):
border = TableCellBorder(rendered_cell, cell_height, position)
border.render(container)
return background
y_cursor = container.cursor
for r, rendered_row in enumerate(rendered_rows):
container.advance(rendered_row.height)
if rendered_row.index == 0:
container.register_styled(rendered_row.row.section)
container.register_styled(rendered_row.row)
for c, rendered_cell in enumerate(rendered_row):
cell_height = sum(rendered_row.height for rendered_row in
rendered_rows[r:r + rendered_cell.rowspan])
x_cursor = rendered_cell.x_position
y_pos = float(y_cursor + cell_height)
cell_container = VirtualContainer(container)
background = draw_cell_border(rendered_cell, cell_height,
cell_container)
cell_container.place_at(container, x_cursor, y_pos)
vertical_align = rendered_cell.cell.get_style('vertical_align',
container)
if vertical_align == VerticalAlign.TOP:
vertical_offset = 0
elif vertical_align == VerticalAlign.MIDDLE:
vertical_offset = (cell_height - rendered_cell.height) / 2
elif vertical_align == VerticalAlign.BOTTOM:
vertical_offset = (cell_height - rendered_cell.height)
y_offset = float(y_cursor + vertical_offset)
rendered_cell.container.place_at(container, x_cursor, y_offset)
container.register_styled(background)
y_cursor += rendered_row.height | [
"def",
"_place_rows_and_render_borders",
"(",
"container",
",",
"rendered_rows",
")",
":",
"def",
"draw_cell_border",
"(",
"rendered_cell",
",",
"cell_height",
",",
"container",
")",
":",
"cell_width",
"=",
"rendered_cell",
".",
"width",
"background",
"=",
"TableCel... | Place the rendered cells onto the page canvas and draw borders around
them. | [
"Place",
"the",
"rendered",
"cells",
"onto",
"the",
"page",
"canvas",
"and",
"draw",
"borders",
"around",
"them",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/table.py#L303-L342 | train | 31,267 |
brechtm/rinohtype | src/rinoh/table.py | TableRow.get_rowspanned_columns | def get_rowspanned_columns(self):
"""Return a dictionary mapping column indices to the number of columns
spanned."""
spanned_columns = {}
current_row_index = self._index
current_row_cols = sum(cell.colspan for cell in self)
prev_rows = iter(reversed(self.section[:current_row_index]))
while current_row_cols < self.section.num_columns:
row = next(prev_rows)
min_rowspan = current_row_index - int(row._index)
if row.maximum_rowspan > min_rowspan:
for cell in (c for c in row if c.rowspan > min_rowspan):
col_index = int(cell.column_index)
spanned_columns[col_index] = cell.colspan
current_row_cols += cell.colspan
return spanned_columns | python | def get_rowspanned_columns(self):
"""Return a dictionary mapping column indices to the number of columns
spanned."""
spanned_columns = {}
current_row_index = self._index
current_row_cols = sum(cell.colspan for cell in self)
prev_rows = iter(reversed(self.section[:current_row_index]))
while current_row_cols < self.section.num_columns:
row = next(prev_rows)
min_rowspan = current_row_index - int(row._index)
if row.maximum_rowspan > min_rowspan:
for cell in (c for c in row if c.rowspan > min_rowspan):
col_index = int(cell.column_index)
spanned_columns[col_index] = cell.colspan
current_row_cols += cell.colspan
return spanned_columns | [
"def",
"get_rowspanned_columns",
"(",
"self",
")",
":",
"spanned_columns",
"=",
"{",
"}",
"current_row_index",
"=",
"self",
".",
"_index",
"current_row_cols",
"=",
"sum",
"(",
"cell",
".",
"colspan",
"for",
"cell",
"in",
"self",
")",
"prev_rows",
"=",
"iter"... | Return a dictionary mapping column indices to the number of columns
spanned. | [
"Return",
"a",
"dictionary",
"mapping",
"column",
"indices",
"to",
"the",
"number",
"of",
"columns",
"spanned",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/table.py#L394-L409 | train | 31,268 |
brechtm/rinohtype | src/rinoh/number.py | romanize | def romanize(number):
"""Convert `number` to a Roman numeral."""
roman = []
for numeral, value in NUMERALS:
times, number = divmod(number, value)
roman.append(times * numeral)
return ''.join(roman) | python | def romanize(number):
"""Convert `number` to a Roman numeral."""
roman = []
for numeral, value in NUMERALS:
times, number = divmod(number, value)
roman.append(times * numeral)
return ''.join(roman) | [
"def",
"romanize",
"(",
"number",
")",
":",
"roman",
"=",
"[",
"]",
"for",
"numeral",
",",
"value",
"in",
"NUMERALS",
":",
"times",
",",
"number",
"=",
"divmod",
"(",
"number",
",",
"value",
")",
"roman",
".",
"append",
"(",
"times",
"*",
"numeral",
... | Convert `number` to a Roman numeral. | [
"Convert",
"number",
"to",
"a",
"Roman",
"numeral",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/number.py#L70-L76 | train | 31,269 |
brechtm/rinohtype | src/rinoh/layout.py | Container.render | def render(self, type, rerender=False):
"""Render the contents of this container to its canvas.
Note that the rendered contents need to be :meth:`place`d on the parent
container's canvas before they become visible."""
for child in self.children:
child.render(type, rerender) | python | def render(self, type, rerender=False):
"""Render the contents of this container to its canvas.
Note that the rendered contents need to be :meth:`place`d on the parent
container's canvas before they become visible."""
for child in self.children:
child.render(type, rerender) | [
"def",
"render",
"(",
"self",
",",
"type",
",",
"rerender",
"=",
"False",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"render",
"(",
"type",
",",
"rerender",
")"
] | Render the contents of this container to its canvas.
Note that the rendered contents need to be :meth:`place`d on the parent
container's canvas before they become visible. | [
"Render",
"the",
"contents",
"of",
"this",
"container",
"to",
"its",
"canvas",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/layout.py#L180-L186 | train | 31,270 |
brechtm/rinohtype | src/rinoh/layout.py | Container.place | def place(self):
"""Place this container's canvas onto the parent container's canvas."""
self.place_children()
self.canvas.append(self.parent.canvas,
float(self.left), float(self.top)) | python | def place(self):
"""Place this container's canvas onto the parent container's canvas."""
self.place_children()
self.canvas.append(self.parent.canvas,
float(self.left), float(self.top)) | [
"def",
"place",
"(",
"self",
")",
":",
"self",
".",
"place_children",
"(",
")",
"self",
".",
"canvas",
".",
"append",
"(",
"self",
".",
"parent",
".",
"canvas",
",",
"float",
"(",
"self",
".",
"left",
")",
",",
"float",
"(",
"self",
".",
"top",
"... | Place this container's canvas onto the parent container's canvas. | [
"Place",
"this",
"container",
"s",
"canvas",
"onto",
"the",
"parent",
"container",
"s",
"canvas",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/layout.py#L196-L200 | train | 31,271 |
brechtm/rinohtype | src/rinoh/layout.py | FlowablesContainerBase.advance2 | def advance2(self, height, ignore_overflow=False):
"""Advance the cursor by `height`. Returns `True` on success.
Returns `False` if this would cause the cursor to point beyond the
bottom of the container.
"""
if height <= self.remaining_height:
self._self_cursor.grow(height)
elif ignore_overflow:
self._self_cursor.grow(float(self.remaining_height))
else:
return False
return True | python | def advance2(self, height, ignore_overflow=False):
"""Advance the cursor by `height`. Returns `True` on success.
Returns `False` if this would cause the cursor to point beyond the
bottom of the container.
"""
if height <= self.remaining_height:
self._self_cursor.grow(height)
elif ignore_overflow:
self._self_cursor.grow(float(self.remaining_height))
else:
return False
return True | [
"def",
"advance2",
"(",
"self",
",",
"height",
",",
"ignore_overflow",
"=",
"False",
")",
":",
"if",
"height",
"<=",
"self",
".",
"remaining_height",
":",
"self",
".",
"_self_cursor",
".",
"grow",
"(",
"height",
")",
"elif",
"ignore_overflow",
":",
"self",... | Advance the cursor by `height`. Returns `True` on success.
Returns `False` if this would cause the cursor to point beyond the
bottom of the container. | [
"Advance",
"the",
"cursor",
"by",
"height",
".",
"Returns",
"True",
"on",
"success",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/layout.py#L268-L281 | train | 31,272 |
brechtm/rinohtype | src/rinoh/layout.py | Chain.render | def render(self, container, rerender=False):
"""Flow the flowables into the containers that have been added to this
chain."""
if rerender:
container.clear()
if not self._rerendering:
# restore saved state on this chain's 1st container on this page
self._state = copy(self._fresh_page_state)
self._rerendering = True
try:
self.done = False
self.flowables.flow(container, last_descender=None,
state=self._state)
# all flowables have been rendered
if container == self.last_container:
self._init_state() # reset state for the next rendering loop
self.done = True
except PageBreakException as exc:
self._state = exc.flowable_state
self._fresh_page_state = copy(self._state)
raise
except EndOfContainer as e:
self._state = e.flowable_state
if container == self.last_container:
# save state for when ReflowRequired occurs
self._fresh_page_state = copy(self._state)
except ReflowRequired:
self._rerendering = False
raise | python | def render(self, container, rerender=False):
"""Flow the flowables into the containers that have been added to this
chain."""
if rerender:
container.clear()
if not self._rerendering:
# restore saved state on this chain's 1st container on this page
self._state = copy(self._fresh_page_state)
self._rerendering = True
try:
self.done = False
self.flowables.flow(container, last_descender=None,
state=self._state)
# all flowables have been rendered
if container == self.last_container:
self._init_state() # reset state for the next rendering loop
self.done = True
except PageBreakException as exc:
self._state = exc.flowable_state
self._fresh_page_state = copy(self._state)
raise
except EndOfContainer as e:
self._state = e.flowable_state
if container == self.last_container:
# save state for when ReflowRequired occurs
self._fresh_page_state = copy(self._state)
except ReflowRequired:
self._rerendering = False
raise | [
"def",
"render",
"(",
"self",
",",
"container",
",",
"rerender",
"=",
"False",
")",
":",
"if",
"rerender",
":",
"container",
".",
"clear",
"(",
")",
"if",
"not",
"self",
".",
"_rerendering",
":",
"# restore saved state on this chain's 1st container on this page",
... | Flow the flowables into the containers that have been added to this
chain. | [
"Flow",
"the",
"flowables",
"into",
"the",
"containers",
"that",
"have",
"been",
"added",
"to",
"this",
"chain",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/layout.py#L576-L604 | train | 31,273 |
brechtm/rinohtype | src/rinoh/attribute.py | AttributesDictionary._get_default | def _get_default(cls, attribute):
"""Return the default value for `attribute`.
If no default is specified in this style, get the default from the
nearest superclass.
If `attribute` is not supported, raise a :class:`KeyError`."""
try:
for klass in cls.__mro__:
if attribute in klass._attributes:
return klass._attributes[attribute].default_value
except AttributeError:
raise KeyError("No attribute '{}' in {}".format(attribute, cls)) | python | def _get_default(cls, attribute):
"""Return the default value for `attribute`.
If no default is specified in this style, get the default from the
nearest superclass.
If `attribute` is not supported, raise a :class:`KeyError`."""
try:
for klass in cls.__mro__:
if attribute in klass._attributes:
return klass._attributes[attribute].default_value
except AttributeError:
raise KeyError("No attribute '{}' in {}".format(attribute, cls)) | [
"def",
"_get_default",
"(",
"cls",
",",
"attribute",
")",
":",
"try",
":",
"for",
"klass",
"in",
"cls",
".",
"__mro__",
":",
"if",
"attribute",
"in",
"klass",
".",
"_attributes",
":",
"return",
"klass",
".",
"_attributes",
"[",
"attribute",
"]",
".",
"... | Return the default value for `attribute`.
If no default is specified in this style, get the default from the
nearest superclass.
If `attribute` is not supported, raise a :class:`KeyError`. | [
"Return",
"the",
"default",
"value",
"for",
"attribute",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/attribute.py#L298-L309 | train | 31,274 |
brechtm/rinohtype | src/rinoh/highlight.py | get_pygments_style | def get_pygments_style(style):
"""Retrieve a Pygments style by name, by import path or, if `style` is
already Pygments style, simply return it."""
if isinstance(style, StyleMeta):
return style
if '.' in style: # by python package/module
module, name = style.rsplit('.', 1)
return getattr(__import__(module, None, None, ['__name__']), name)
else: # by name
if style == 'sphinx':
from sphinx.pygments_styles import SphinxStyle
return SphinxStyle
elif style == 'pyramid':
from sphinx.pygments_styles import PyramidStyle
return PyramidStyle
elif style == 'none':
from sphinx.pygments_styles import NoneStyle
return NoneStyle
else:
return get_style_by_name(style) | python | def get_pygments_style(style):
"""Retrieve a Pygments style by name, by import path or, if `style` is
already Pygments style, simply return it."""
if isinstance(style, StyleMeta):
return style
if '.' in style: # by python package/module
module, name = style.rsplit('.', 1)
return getattr(__import__(module, None, None, ['__name__']), name)
else: # by name
if style == 'sphinx':
from sphinx.pygments_styles import SphinxStyle
return SphinxStyle
elif style == 'pyramid':
from sphinx.pygments_styles import PyramidStyle
return PyramidStyle
elif style == 'none':
from sphinx.pygments_styles import NoneStyle
return NoneStyle
else:
return get_style_by_name(style) | [
"def",
"get_pygments_style",
"(",
"style",
")",
":",
"if",
"isinstance",
"(",
"style",
",",
"StyleMeta",
")",
":",
"return",
"style",
"if",
"'.'",
"in",
"style",
":",
"# by python package/module",
"module",
",",
"name",
"=",
"style",
".",
"rsplit",
"(",
"'... | Retrieve a Pygments style by name, by import path or, if `style` is
already Pygments style, simply return it. | [
"Retrieve",
"a",
"Pygments",
"style",
"by",
"name",
"by",
"import",
"path",
"or",
"if",
"style",
"is",
"already",
"Pygments",
"style",
"simply",
"return",
"it",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/highlight.py#L89-L108 | train | 31,275 |
brechtm/rinohtype | src/rinoh/flowable.py | Flowable.flow | def flow(self, container, last_descender, state=None, **kwargs):
"""Flow this flowable into `container` and return the vertical space
consumed.
The flowable's contents is preceded by a vertical space with a height
as specified in its style's `space_above` attribute. Similarly, the
flowed content is followed by a vertical space with a height given
by the `space_below` style attribute."""
top_to_baseline = 0
state = state or self.initial_state(container)
if state.initial:
space_above = self.get_style('space_above', container)
if not container.advance2(float(space_above)):
raise EndOfContainer(state)
top_to_baseline += float(space_above)
margin_left = self.get_style('margin_left', container)
margin_right = self.get_style('margin_right', container)
reference_id = self.get_id(container.document, create=False)
right = container.width - margin_right
container.register_styled(self, continued=not state.initial)
margin_container = InlineDownExpandingContainer('MARGIN', container,
left=margin_left,
right=right)
initial_before = state.initial
state, width, inner_top_to_baseline, descender = \
self.flow_inner(margin_container, last_descender,
state=state, **kwargs)
self._align(margin_container, width)
initial_after = state is not None and state.initial
top_to_baseline += inner_top_to_baseline
if self.annotation:
height = float(margin_container.height)
margin_container.canvas.annotate(self.annotation,
0, 0, width, height)
self.mark_page_nonempty(container)
if initial_before and not initial_after:
if reference_id:
self.create_destination(margin_container, True)
if state is not None:
raise EndOfContainer(state)
space_below = self.get_style('space_below', container)
container.advance2(float(space_below), ignore_overflow=True)
container.document.progress(self, container)
return margin_left + width + margin_right, top_to_baseline, descender | python | def flow(self, container, last_descender, state=None, **kwargs):
"""Flow this flowable into `container` and return the vertical space
consumed.
The flowable's contents is preceded by a vertical space with a height
as specified in its style's `space_above` attribute. Similarly, the
flowed content is followed by a vertical space with a height given
by the `space_below` style attribute."""
top_to_baseline = 0
state = state or self.initial_state(container)
if state.initial:
space_above = self.get_style('space_above', container)
if not container.advance2(float(space_above)):
raise EndOfContainer(state)
top_to_baseline += float(space_above)
margin_left = self.get_style('margin_left', container)
margin_right = self.get_style('margin_right', container)
reference_id = self.get_id(container.document, create=False)
right = container.width - margin_right
container.register_styled(self, continued=not state.initial)
margin_container = InlineDownExpandingContainer('MARGIN', container,
left=margin_left,
right=right)
initial_before = state.initial
state, width, inner_top_to_baseline, descender = \
self.flow_inner(margin_container, last_descender,
state=state, **kwargs)
self._align(margin_container, width)
initial_after = state is not None and state.initial
top_to_baseline += inner_top_to_baseline
if self.annotation:
height = float(margin_container.height)
margin_container.canvas.annotate(self.annotation,
0, 0, width, height)
self.mark_page_nonempty(container)
if initial_before and not initial_after:
if reference_id:
self.create_destination(margin_container, True)
if state is not None:
raise EndOfContainer(state)
space_below = self.get_style('space_below', container)
container.advance2(float(space_below), ignore_overflow=True)
container.document.progress(self, container)
return margin_left + width + margin_right, top_to_baseline, descender | [
"def",
"flow",
"(",
"self",
",",
"container",
",",
"last_descender",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"top_to_baseline",
"=",
"0",
"state",
"=",
"state",
"or",
"self",
".",
"initial_state",
"(",
"container",
")",
"if",
"sta... | Flow this flowable into `container` and return the vertical space
consumed.
The flowable's contents is preceded by a vertical space with a height
as specified in its style's `space_above` attribute. Similarly, the
flowed content is followed by a vertical space with a height given
by the `space_below` style attribute. | [
"Flow",
"this",
"flowable",
"into",
"container",
"and",
"return",
"the",
"vertical",
"space",
"consumed",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/flowable.py#L173-L219 | train | 31,276 |
brechtm/rinohtype | src/rinoh/resource.py | entry_point_name_to_identifier | def entry_point_name_to_identifier(entry_point_name):
"""Transform an entry point name into an identifier suitable for inclusion
in a PyPI package name."""
try:
entry_point_name.encode('ascii')
ascii_name = entry_point_name
except UnicodeEncodeError:
ascii_name = entry_point_name.encode('punycode').decode('ascii')
return ''.join(char for char in ascii_name
if char in string.ascii_lowercase + string.digits) | python | def entry_point_name_to_identifier(entry_point_name):
"""Transform an entry point name into an identifier suitable for inclusion
in a PyPI package name."""
try:
entry_point_name.encode('ascii')
ascii_name = entry_point_name
except UnicodeEncodeError:
ascii_name = entry_point_name.encode('punycode').decode('ascii')
return ''.join(char for char in ascii_name
if char in string.ascii_lowercase + string.digits) | [
"def",
"entry_point_name_to_identifier",
"(",
"entry_point_name",
")",
":",
"try",
":",
"entry_point_name",
".",
"encode",
"(",
"'ascii'",
")",
"ascii_name",
"=",
"entry_point_name",
"except",
"UnicodeEncodeError",
":",
"ascii_name",
"=",
"entry_point_name",
".",
"enc... | Transform an entry point name into an identifier suitable for inclusion
in a PyPI package name. | [
"Transform",
"an",
"entry",
"point",
"name",
"into",
"an",
"identifier",
"suitable",
"for",
"inclusion",
"in",
"a",
"PyPI",
"package",
"name",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/resource.py#L91-L100 | train | 31,277 |
brechtm/rinohtype | src/rinoh/paragraph.py | ParagraphBase.render | def render(self, container, descender, state, space_below=0,
first_line_only=False):
"""Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a new container.
Args:
container (Container): the container to render to
descender (float or None): descender height of the preceeding line
state (ParagraphState): the state where rendering will continue
first_line_only (bool): typeset only the first line
"""
indent_first = (float(self.get_style('indent_first', container))
if state.initial else 0)
line_width = float(container.width)
line_spacing = self.get_style('line_spacing', container)
text_align = self.get_style('text_align', container)
tab_stops = self.get_style('tab_stops', container)
if not tab_stops:
tab_width = 2 * self.get_style('font_size', container)
tab_stops = DefaultTabStops(tab_width)
# `saved_state` is updated after successfully rendering each line, so
# that when `container` overflows on rendering a line, the words in that
# line are yielded again on the next typeset() call.
saved_state = copy(state)
prev_state = copy(state)
max_line_width = 0
def typeset_line(line, last_line=False):
"""Typeset `line` and, if no exception is raised, update the
paragraph's internal rendering state."""
nonlocal state, saved_state, max_line_width, descender, space_below
max_line_width = max(max_line_width, line.cursor)
advance = (line.ascender(container) if descender is None
else line_spacing.advance(line, descender, container))
descender = line.descender(container) # descender <= 0
line.advance = advance
total_advance = advance + (space_below if last_line else 0) - descender
if container.remaining_height < total_advance:
raise EndOfContainer(saved_state)
assert container.advance2(advance)
line.typeset(container, text_align, last_line)
assert container.advance2(- descender)
state.initial = False
saved_state = copy(state)
return Line(tab_stops, line_width, container,
significant_whitespace=self.significant_whitespace)
first_line = line = Line(tab_stops, line_width, container,
indent_first, self.significant_whitespace)
while True:
try:
word = state.next_word()
except StopIteration:
break
try:
if not line.append_word(word):
for first, second in word.hyphenate(container):
if line.append_word(first):
state.prepend_word(second) # prepend second part
break
else:
state = prev_state
line = typeset_line(line)
if first_line_only:
break
continue
except NewLineException:
line.append(word.glyphs_span)
line = typeset_line(line, last_line=True)
if first_line_only:
break
prev_state = copy(state)
if line:
typeset_line(line, last_line=True)
# Correct the horizontal text placement for auto-width paragraphs
if self._width(container) == FlowableWidth.AUTO:
if text_align == TextAlign.CENTER:
container.left -= float(container.width - max_line_width) / 2
if text_align == TextAlign.RIGHT:
container.left -= float(container.width - max_line_width)
return max_line_width, first_line.advance, descender | python | def render(self, container, descender, state, space_below=0,
first_line_only=False):
"""Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a new container.
Args:
container (Container): the container to render to
descender (float or None): descender height of the preceeding line
state (ParagraphState): the state where rendering will continue
first_line_only (bool): typeset only the first line
"""
indent_first = (float(self.get_style('indent_first', container))
if state.initial else 0)
line_width = float(container.width)
line_spacing = self.get_style('line_spacing', container)
text_align = self.get_style('text_align', container)
tab_stops = self.get_style('tab_stops', container)
if not tab_stops:
tab_width = 2 * self.get_style('font_size', container)
tab_stops = DefaultTabStops(tab_width)
# `saved_state` is updated after successfully rendering each line, so
# that when `container` overflows on rendering a line, the words in that
# line are yielded again on the next typeset() call.
saved_state = copy(state)
prev_state = copy(state)
max_line_width = 0
def typeset_line(line, last_line=False):
"""Typeset `line` and, if no exception is raised, update the
paragraph's internal rendering state."""
nonlocal state, saved_state, max_line_width, descender, space_below
max_line_width = max(max_line_width, line.cursor)
advance = (line.ascender(container) if descender is None
else line_spacing.advance(line, descender, container))
descender = line.descender(container) # descender <= 0
line.advance = advance
total_advance = advance + (space_below if last_line else 0) - descender
if container.remaining_height < total_advance:
raise EndOfContainer(saved_state)
assert container.advance2(advance)
line.typeset(container, text_align, last_line)
assert container.advance2(- descender)
state.initial = False
saved_state = copy(state)
return Line(tab_stops, line_width, container,
significant_whitespace=self.significant_whitespace)
first_line = line = Line(tab_stops, line_width, container,
indent_first, self.significant_whitespace)
while True:
try:
word = state.next_word()
except StopIteration:
break
try:
if not line.append_word(word):
for first, second in word.hyphenate(container):
if line.append_word(first):
state.prepend_word(second) # prepend second part
break
else:
state = prev_state
line = typeset_line(line)
if first_line_only:
break
continue
except NewLineException:
line.append(word.glyphs_span)
line = typeset_line(line, last_line=True)
if first_line_only:
break
prev_state = copy(state)
if line:
typeset_line(line, last_line=True)
# Correct the horizontal text placement for auto-width paragraphs
if self._width(container) == FlowableWidth.AUTO:
if text_align == TextAlign.CENTER:
container.left -= float(container.width - max_line_width) / 2
if text_align == TextAlign.RIGHT:
container.left -= float(container.width - max_line_width)
return max_line_width, first_line.advance, descender | [
"def",
"render",
"(",
"self",
",",
"container",
",",
"descender",
",",
"state",
",",
"space_below",
"=",
"0",
",",
"first_line_only",
"=",
"False",
")",
":",
"indent_first",
"=",
"(",
"float",
"(",
"self",
".",
"get_style",
"(",
"'indent_first'",
",",
"c... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a new container.
Args:
container (Container): the container to render to
descender (float or None): descender height of the preceeding line
state (ParagraphState): the state where rendering will continue
first_line_only (bool): typeset only the first line | [
"Typeset",
"the",
"paragraph"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/paragraph.py#L608-L696 | train | 31,278 |
brechtm/rinohtype | src/rinoh/paragraph.py | Line.typeset | def typeset(self, container, text_align, last_line=False):
"""Typeset the line in `container` below its current cursor position.
Advances the container's cursor to below the descender of this line.
`justification` and `line_spacing` are passed on from the paragraph
style. `last_descender` is the previous line's descender, used in the
vertical positioning of this line. Finally, `last_line` specifies
whether this is the last line of the paragraph.
Returns the line's descender size."""
document = container.document
# drop spaces (and empty spans) at the end of the line
while len(self) > 0:
last_span = self[-1]
if last_span and last_span.ends_with_space:
self.cursor -= last_span.space.width
self.pop()
else:
break
else: # abort if the line is empty
return
for glyph_span in self:
glyph_span.span.before_placing(container)
# horizontal displacement
left = self.indent
if self._has_tab or text_align == TextAlign.JUSTIFY and last_line:
text_align = 'left'
extra_space = self.width - self.cursor
if text_align == TextAlign.JUSTIFY:
# TODO: padding added to spaces should be prop. to font size
nr_spaces = sum(glyph_span.number_of_spaces for glyph_span in self)
if nr_spaces > 0:
add_to_spaces = extra_space / nr_spaces
for glyph_span in self:
if glyph_span.number_of_spaces > 0:
glyph_span.space.width += add_to_spaces
elif text_align == TextAlign.CENTER:
left += extra_space / 2.0
elif text_align == TextAlign.RIGHT:
left += extra_space
canvas = container.canvas
cursor = container.cursor
current_annotation = AnnotationState(container)
for span, glyph_and_widths in group_spans(self):
try:
width = canvas.show_glyphs(left, cursor, span, glyph_and_widths,
container)
except InlineFlowableException:
ascender = span.ascender(document)
if ascender > 0:
top = cursor - ascender
else:
inline_height = span.virtual_container.height
top = cursor - span.descender(document) - inline_height
span.virtual_container.place_at(container, left, top)
width = span.width
current_annotation.update(span, left, width)
left += width
current_annotation.place_if_any() | python | def typeset(self, container, text_align, last_line=False):
"""Typeset the line in `container` below its current cursor position.
Advances the container's cursor to below the descender of this line.
`justification` and `line_spacing` are passed on from the paragraph
style. `last_descender` is the previous line's descender, used in the
vertical positioning of this line. Finally, `last_line` specifies
whether this is the last line of the paragraph.
Returns the line's descender size."""
document = container.document
# drop spaces (and empty spans) at the end of the line
while len(self) > 0:
last_span = self[-1]
if last_span and last_span.ends_with_space:
self.cursor -= last_span.space.width
self.pop()
else:
break
else: # abort if the line is empty
return
for glyph_span in self:
glyph_span.span.before_placing(container)
# horizontal displacement
left = self.indent
if self._has_tab or text_align == TextAlign.JUSTIFY and last_line:
text_align = 'left'
extra_space = self.width - self.cursor
if text_align == TextAlign.JUSTIFY:
# TODO: padding added to spaces should be prop. to font size
nr_spaces = sum(glyph_span.number_of_spaces for glyph_span in self)
if nr_spaces > 0:
add_to_spaces = extra_space / nr_spaces
for glyph_span in self:
if glyph_span.number_of_spaces > 0:
glyph_span.space.width += add_to_spaces
elif text_align == TextAlign.CENTER:
left += extra_space / 2.0
elif text_align == TextAlign.RIGHT:
left += extra_space
canvas = container.canvas
cursor = container.cursor
current_annotation = AnnotationState(container)
for span, glyph_and_widths in group_spans(self):
try:
width = canvas.show_glyphs(left, cursor, span, glyph_and_widths,
container)
except InlineFlowableException:
ascender = span.ascender(document)
if ascender > 0:
top = cursor - ascender
else:
inline_height = span.virtual_container.height
top = cursor - span.descender(document) - inline_height
span.virtual_container.place_at(container, left, top)
width = span.width
current_annotation.update(span, left, width)
left += width
current_annotation.place_if_any() | [
"def",
"typeset",
"(",
"self",
",",
"container",
",",
"text_align",
",",
"last_line",
"=",
"False",
")",
":",
"document",
"=",
"container",
".",
"document",
"# drop spaces (and empty spans) at the end of the line",
"while",
"len",
"(",
"self",
")",
">",
"0",
":"... | Typeset the line in `container` below its current cursor position.
Advances the container's cursor to below the descender of this line.
`justification` and `line_spacing` are passed on from the paragraph
style. `last_descender` is the previous line's descender, used in the
vertical positioning of this line. Finally, `last_line` specifies
whether this is the last line of the paragraph.
Returns the line's descender size. | [
"Typeset",
"the",
"line",
"in",
"container",
"below",
"its",
"current",
"cursor",
"position",
".",
"Advances",
"the",
"container",
"s",
"cursor",
"to",
"below",
"the",
"descender",
"of",
"this",
"line",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/paragraph.py#L921-L984 | train | 31,279 |
brechtm/rinohtype | src/rinoh/element.py | create_destination | def create_destination(flowable, container, at_top_of_container=False):
"""Create a destination anchor in the `container` to direct links to
`flowable` to."""
vertical_position = 0 if at_top_of_container else container.cursor
ids = flowable.get_ids(container.document)
destination = NamedDestination(*(str(id) for id in ids))
container.canvas.annotate(destination, 0, vertical_position,
container.width, None)
container.document.register_page_reference(container.page, flowable) | python | def create_destination(flowable, container, at_top_of_container=False):
"""Create a destination anchor in the `container` to direct links to
`flowable` to."""
vertical_position = 0 if at_top_of_container else container.cursor
ids = flowable.get_ids(container.document)
destination = NamedDestination(*(str(id) for id in ids))
container.canvas.annotate(destination, 0, vertical_position,
container.width, None)
container.document.register_page_reference(container.page, flowable) | [
"def",
"create_destination",
"(",
"flowable",
",",
"container",
",",
"at_top_of_container",
"=",
"False",
")",
":",
"vertical_position",
"=",
"0",
"if",
"at_top_of_container",
"else",
"container",
".",
"cursor",
"ids",
"=",
"flowable",
".",
"get_ids",
"(",
"cont... | Create a destination anchor in the `container` to direct links to
`flowable` to. | [
"Create",
"a",
"destination",
"anchor",
"in",
"the",
"container",
"to",
"direct",
"links",
"to",
"flowable",
"to",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/element.py#L99-L107 | train | 31,280 |
brechtm/rinohtype | src/rinoh/element.py | DocumentElement.source | def source(self):
"""The source element this document element was created from."""
if self._source is not None:
return self._source
elif self.parent is not None:
return self.parent.source
else:
return Location(self) | python | def source(self):
"""The source element this document element was created from."""
if self._source is not None:
return self._source
elif self.parent is not None:
return self.parent.source
else:
return Location(self) | [
"def",
"source",
"(",
"self",
")",
":",
"if",
"self",
".",
"_source",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_source",
"elif",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"return",
"self",
".",
"parent",
".",
"source",
"else",
":",
... | The source element this document element was created from. | [
"The",
"source",
"element",
"this",
"document",
"element",
"was",
"created",
"from",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/element.py#L54-L61 | train | 31,281 |
brechtm/rinohtype | src/rinoh/element.py | DocumentElement.prepare | def prepare(self, flowable_target):
"""Determine number labels and register references with the document"""
if self.get_id(flowable_target.document, create=False):
flowable_target.document.register_element(self) | python | def prepare(self, flowable_target):
"""Determine number labels and register references with the document"""
if self.get_id(flowable_target.document, create=False):
flowable_target.document.register_element(self) | [
"def",
"prepare",
"(",
"self",
",",
"flowable_target",
")",
":",
"if",
"self",
".",
"get_id",
"(",
"flowable_target",
".",
"document",
",",
"create",
"=",
"False",
")",
":",
"flowable_target",
".",
"document",
".",
"register_element",
"(",
"self",
")"
] | Determine number labels and register references with the document | [
"Determine",
"number",
"labels",
"and",
"register",
"references",
"with",
"the",
"document"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/element.py#L76-L79 | train | 31,282 |
brechtm/rinohtype | src/rinoh/element.py | DocumentElement.warn | def warn(self, message, container=None):
"""Present the warning `message` to the user, adding information on the
location of the related element in the input file."""
if self.source is not None:
message = '[{}] '.format(self.source.location) + message
if container is not None:
try:
message += ' (page {})'.format(container.page.formatted_number)
except AttributeError:
pass
warn(message) | python | def warn(self, message, container=None):
"""Present the warning `message` to the user, adding information on the
location of the related element in the input file."""
if self.source is not None:
message = '[{}] '.format(self.source.location) + message
if container is not None:
try:
message += ' (page {})'.format(container.page.formatted_number)
except AttributeError:
pass
warn(message) | [
"def",
"warn",
"(",
"self",
",",
"message",
",",
"container",
"=",
"None",
")",
":",
"if",
"self",
".",
"source",
"is",
"not",
"None",
":",
"message",
"=",
"'[{}] '",
".",
"format",
"(",
"self",
".",
"source",
".",
"location",
")",
"+",
"message",
... | Present the warning `message` to the user, adding information on the
location of the related element in the input file. | [
"Present",
"the",
"warning",
"message",
"to",
"the",
"user",
"adding",
"information",
"on",
"the",
"location",
"of",
"the",
"related",
"element",
"in",
"the",
"input",
"file",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/element.py#L86-L96 | train | 31,283 |
brechtm/rinohtype | src/rinoh/util.py | all_subclasses | def all_subclasses(cls):
"""Generator yielding all subclasses of `cls` recursively"""
for subcls in cls.__subclasses__():
yield subcls
for subsubcls in all_subclasses(subcls):
yield subsubcls | python | def all_subclasses(cls):
"""Generator yielding all subclasses of `cls` recursively"""
for subcls in cls.__subclasses__():
yield subcls
for subsubcls in all_subclasses(subcls):
yield subsubcls | [
"def",
"all_subclasses",
"(",
"cls",
")",
":",
"for",
"subcls",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"yield",
"subcls",
"for",
"subsubcls",
"in",
"all_subclasses",
"(",
"subcls",
")",
":",
"yield",
"subsubcls"
] | Generator yielding all subclasses of `cls` recursively | [
"Generator",
"yielding",
"all",
"subclasses",
"of",
"cls",
"recursively"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L42-L47 | train | 31,284 |
brechtm/rinohtype | src/rinoh/util.py | intersperse | def intersperse(iterable, element):
"""Generator yielding all elements of `iterable`, but with `element`
inserted between each two consecutive elements"""
iterable = iter(iterable)
yield next(iterable)
while True:
next_from_iterable = next(iterable)
yield element
yield next_from_iterable | python | def intersperse(iterable, element):
"""Generator yielding all elements of `iterable`, but with `element`
inserted between each two consecutive elements"""
iterable = iter(iterable)
yield next(iterable)
while True:
next_from_iterable = next(iterable)
yield element
yield next_from_iterable | [
"def",
"intersperse",
"(",
"iterable",
",",
"element",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"yield",
"next",
"(",
"iterable",
")",
"while",
"True",
":",
"next_from_iterable",
"=",
"next",
"(",
"iterable",
")",
"yield",
"element",
"yield... | Generator yielding all elements of `iterable`, but with `element`
inserted between each two consecutive elements | [
"Generator",
"yielding",
"all",
"elements",
"of",
"iterable",
"but",
"with",
"element",
"inserted",
"between",
"each",
"two",
"consecutive",
"elements"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L50-L58 | train | 31,285 |
brechtm/rinohtype | src/rinoh/util.py | unique | def unique(iterable):
"""Filter out duplicate items from an iterable"""
seen = set()
for item in iterable:
if item not in seen:
seen.add(item)
yield item | python | def unique(iterable):
"""Filter out duplicate items from an iterable"""
seen = set()
for item in iterable:
if item not in seen:
seen.add(item)
yield item | [
"def",
"unique",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"iterable",
":",
"if",
"item",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"item",
")",
"yield",
"item"
] | Filter out duplicate items from an iterable | [
"Filter",
"out",
"duplicate",
"items",
"from",
"an",
"iterable"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L69-L75 | train | 31,286 |
brechtm/rinohtype | src/rinoh/util.py | cached | def cached(function):
"""Method decorator caching a method's returned values."""
cache_variable = '_cached_' + function.__name__
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
# values are cached in a dict stored in the object
try:
cache = getattr(obj, cache_variable)
except AttributeError:
cache = {}
setattr(obj, cache_variable, cache)
args_kwargs = args + tuple(kwargs.values())
try:
return cache[args_kwargs]
except KeyError:
cache_value = function(obj, *args, **kwargs)
cache[args_kwargs] = cache_value
return cache_value
return function_wrapper | python | def cached(function):
"""Method decorator caching a method's returned values."""
cache_variable = '_cached_' + function.__name__
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
# values are cached in a dict stored in the object
try:
cache = getattr(obj, cache_variable)
except AttributeError:
cache = {}
setattr(obj, cache_variable, cache)
args_kwargs = args + tuple(kwargs.values())
try:
return cache[args_kwargs]
except KeyError:
cache_value = function(obj, *args, **kwargs)
cache[args_kwargs] = cache_value
return cache_value
return function_wrapper | [
"def",
"cached",
"(",
"function",
")",
":",
"cache_variable",
"=",
"'_cached_'",
"+",
"function",
".",
"__name__",
"@",
"wraps",
"(",
"function",
")",
"def",
"function_wrapper",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# values a... | Method decorator caching a method's returned values. | [
"Method",
"decorator",
"caching",
"a",
"method",
"s",
"returned",
"values",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L124-L142 | train | 31,287 |
brechtm/rinohtype | src/rinoh/util.py | cached_generator | def cached_generator(function):
"""Method decorator caching a generator's yielded items."""
cache_variable = '_cached_' + function.__name__
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
# values are cached in a list stored in the object
try:
for item in getattr(obj, cache_variable):
yield item
except AttributeError:
setattr(obj, cache_variable, [])
cache = getattr(obj, cache_variable)
for item in function(obj, *args, **kwargs):
cache.append(item)
yield item
return function_wrapper | python | def cached_generator(function):
"""Method decorator caching a generator's yielded items."""
cache_variable = '_cached_' + function.__name__
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
# values are cached in a list stored in the object
try:
for item in getattr(obj, cache_variable):
yield item
except AttributeError:
setattr(obj, cache_variable, [])
cache = getattr(obj, cache_variable)
for item in function(obj, *args, **kwargs):
cache.append(item)
yield item
return function_wrapper | [
"def",
"cached_generator",
"(",
"function",
")",
":",
"cache_variable",
"=",
"'_cached_'",
"+",
"function",
".",
"__name__",
"@",
"wraps",
"(",
"function",
")",
"def",
"function_wrapper",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Method decorator caching a generator's yielded items. | [
"Method",
"decorator",
"caching",
"a",
"generator",
"s",
"yielded",
"items",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L163-L178 | train | 31,288 |
brechtm/rinohtype | src/rinoh/util.py | timed | def timed(function):
"""Decorator timing the method call and printing the result to `stdout`"""
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
"""Wrapper function printing the time taken by the call to `function`"""
name = obj.__class__.__name__ + '.' + function.__name__
start = time.clock()
result = function(obj, *args, **kwargs)
print('{}: {:.4f} seconds'.format(name, time.clock() - start))
return result
return function_wrapper | python | def timed(function):
"""Decorator timing the method call and printing the result to `stdout`"""
@wraps(function)
def function_wrapper(obj, *args, **kwargs):
"""Wrapper function printing the time taken by the call to `function`"""
name = obj.__class__.__name__ + '.' + function.__name__
start = time.clock()
result = function(obj, *args, **kwargs)
print('{}: {:.4f} seconds'.format(name, time.clock() - start))
return result
return function_wrapper | [
"def",
"timed",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"function_wrapper",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper function printing the time taken by the call to `function`\"\"\"",
"name",
"="... | Decorator timing the method call and printing the result to `stdout` | [
"Decorator",
"timing",
"the",
"method",
"call",
"and",
"printing",
"the",
"result",
"to",
"stdout"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/util.py#L190-L200 | train | 31,289 |
brechtm/rinohtype | src/rinoh/hyphenator.py | Hyphenator.positions | def positions(self, word):
"""
Returns a list of positions where the word can be hyphenated.
See also Hyph_dict.positions. The points that are too far to
the left or right are removed.
"""
right = len(word) - self.right
return [i for i in self.hd.positions(word) if self.left <= i <= right] | python | def positions(self, word):
"""
Returns a list of positions where the word can be hyphenated.
See also Hyph_dict.positions. The points that are too far to
the left or right are removed.
"""
right = len(word) - self.right
return [i for i in self.hd.positions(word) if self.left <= i <= right] | [
"def",
"positions",
"(",
"self",
",",
"word",
")",
":",
"right",
"=",
"len",
"(",
"word",
")",
"-",
"self",
".",
"right",
"return",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"hd",
".",
"positions",
"(",
"word",
")",
"if",
"self",
".",
"left",
"<... | Returns a list of positions where the word can be hyphenated.
See also Hyph_dict.positions. The points that are too far to
the left or right are removed. | [
"Returns",
"a",
"list",
"of",
"positions",
"where",
"the",
"word",
"can",
"be",
"hyphenated",
".",
"See",
"also",
"Hyph_dict",
".",
"positions",
".",
"The",
"points",
"that",
"are",
"too",
"far",
"to",
"the",
"left",
"or",
"right",
"are",
"removed",
"."
... | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/hyphenator.py#L171-L178 | train | 31,290 |
brechtm/rinohtype | src/rinoh/hyphenator.py | Hyphenator.iterate | def iterate(self, word):
"""
Iterate over all hyphenation possibilities, the longest first.
"""
for p in reversed(self.positions(word)):
if p.data:
# get the nonstandard hyphenation data
change, index, cut = p.data
if word.isupper():
change = change.upper()
c1, c2 = change.split('=')
yield word[:p+index] + c1, c2 + word[p+index+cut:]
else:
yield word[:p], word[p:] | python | def iterate(self, word):
"""
Iterate over all hyphenation possibilities, the longest first.
"""
for p in reversed(self.positions(word)):
if p.data:
# get the nonstandard hyphenation data
change, index, cut = p.data
if word.isupper():
change = change.upper()
c1, c2 = change.split('=')
yield word[:p+index] + c1, c2 + word[p+index+cut:]
else:
yield word[:p], word[p:] | [
"def",
"iterate",
"(",
"self",
",",
"word",
")",
":",
"for",
"p",
"in",
"reversed",
"(",
"self",
".",
"positions",
"(",
"word",
")",
")",
":",
"if",
"p",
".",
"data",
":",
"# get the nonstandard hyphenation data",
"change",
",",
"index",
",",
"cut",
"=... | Iterate over all hyphenation possibilities, the longest first. | [
"Iterate",
"over",
"all",
"hyphenation",
"possibilities",
"the",
"longest",
"first",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/hyphenator.py#L180-L193 | train | 31,291 |
brechtm/rinohtype | src/rinoh/hyphenator.py | Hyphenator.wrap | def wrap(self, word, width, hyphen='-'):
"""
Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could not be hyphenated.
"""
width -= len(hyphen)
for w1, w2 in self.iterate(word):
if len(w1) <= width:
return w1 + hyphen, w2 | python | def wrap(self, word, width, hyphen='-'):
"""
Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could not be hyphenated.
"""
width -= len(hyphen)
for w1, w2 in self.iterate(word):
if len(w1) <= width:
return w1 + hyphen, w2 | [
"def",
"wrap",
"(",
"self",
",",
"word",
",",
"width",
",",
"hyphen",
"=",
"'-'",
")",
":",
"width",
"-=",
"len",
"(",
"hyphen",
")",
"for",
"w1",
",",
"w2",
"in",
"self",
".",
"iterate",
"(",
"word",
")",
":",
"if",
"len",
"(",
"w1",
")",
"<... | Return the longest possible first part and the last part of the
hyphenated word. The first part has the hyphen already attached.
Returns None, if there is no hyphenation point before width, or
if the word could not be hyphenated. | [
"Return",
"the",
"longest",
"possible",
"first",
"part",
"and",
"the",
"last",
"part",
"of",
"the",
"hyphenated",
"word",
".",
"The",
"first",
"part",
"has",
"the",
"hyphen",
"already",
"attached",
".",
"Returns",
"None",
"if",
"there",
"is",
"no",
"hyphen... | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/hyphenator.py#L195-L205 | train | 31,292 |
brechtm/rinohtype | src/rinoh/hyphenator.py | Hyphenator.inserted | def inserted(self, word, hyphen='-'):
"""
Returns the word as a string with all the possible hyphens inserted.
E.g. for the dutch word 'lettergrepen' this method returns
the string 'let-ter-gre-pen'. The hyphen string to use can be
given as the second parameter, that defaults to '-'.
"""
l = list(word)
for p in reversed(self.positions(word)):
if p.data:
# get the nonstandard hyphenation data
change, index, cut = p.data
if word.isupper():
change = change.upper()
l[p + index : p + index + cut] = change.replace('=', hyphen)
else:
l.insert(p, hyphen)
return ''.join(l) | python | def inserted(self, word, hyphen='-'):
"""
Returns the word as a string with all the possible hyphens inserted.
E.g. for the dutch word 'lettergrepen' this method returns
the string 'let-ter-gre-pen'. The hyphen string to use can be
given as the second parameter, that defaults to '-'.
"""
l = list(word)
for p in reversed(self.positions(word)):
if p.data:
# get the nonstandard hyphenation data
change, index, cut = p.data
if word.isupper():
change = change.upper()
l[p + index : p + index + cut] = change.replace('=', hyphen)
else:
l.insert(p, hyphen)
return ''.join(l) | [
"def",
"inserted",
"(",
"self",
",",
"word",
",",
"hyphen",
"=",
"'-'",
")",
":",
"l",
"=",
"list",
"(",
"word",
")",
"for",
"p",
"in",
"reversed",
"(",
"self",
".",
"positions",
"(",
"word",
")",
")",
":",
"if",
"p",
".",
"data",
":",
"# get t... | Returns the word as a string with all the possible hyphens inserted.
E.g. for the dutch word 'lettergrepen' this method returns
the string 'let-ter-gre-pen'. The hyphen string to use can be
given as the second parameter, that defaults to '-'. | [
"Returns",
"the",
"word",
"as",
"a",
"string",
"with",
"all",
"the",
"possible",
"hyphens",
"inserted",
".",
"E",
".",
"g",
".",
"for",
"the",
"dutch",
"word",
"lettergrepen",
"this",
"method",
"returns",
"the",
"string",
"let",
"-",
"ter",
"-",
"gre",
... | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/hyphenator.py#L207-L224 | train | 31,293 |
brechtm/rinohtype | src/rinoh/document.py | Document.render | def render(self, filename_root=None, file=None):
"""Render the document repeatedly until the output no longer changes due
to cross-references that need some iterations to converge."""
self.error = False
filename_root = Path(filename_root) if filename_root else None
if filename_root and file is None:
extension = self.backend_document.extension
filename = filename_root.with_suffix(extension)
file = filename.open('wb')
elif file and filename_root is None:
filename = getattr(file, 'name', None)
else:
raise ValueError("You need to specify either 'filename_root' or "
"'file'.")
def has_converged(part_page_counts):
"""Return `True` if the last rendering iteration converged to a
stable result.
Practically, this tests whether the total number of pages and page
references to document elements have changed since the previous
rendering iteration."""
nonlocal prev_number_of_pages, prev_page_references
return (part_page_counts == prev_number_of_pages and
self.page_references == prev_page_references)
fake_container = FakeContainer(self)
try:
self.document_tree.build_document(fake_container)
(prev_number_of_pages,
prev_page_references) = self._load_cache(filename_root)
self.part_page_counts = prev_number_of_pages
self.prepare(fake_container)
self.page_elements.clear()
self.page_references = prev_page_references.copy()
self.part_page_counts = self._render_pages()
while not has_converged(self.part_page_counts):
prev_number_of_pages = self.part_page_counts
prev_page_references = self.page_references.copy()
print('Not yet converged, rendering again...')
del self.backend_document
self.backend_document = self.backend.Document(self.CREATOR)
self.part_page_counts = self._render_pages()
self.create_outlines()
if filename:
self._save_cache(filename_root, self.part_page_counts,
self.page_references)
self.style_log.write_log(filename_root)
print('Writing output: {}'.format(filename))
self.backend_document.write(file)
finally:
if filename_root:
file.close()
return not self.error | python | def render(self, filename_root=None, file=None):
"""Render the document repeatedly until the output no longer changes due
to cross-references that need some iterations to converge."""
self.error = False
filename_root = Path(filename_root) if filename_root else None
if filename_root and file is None:
extension = self.backend_document.extension
filename = filename_root.with_suffix(extension)
file = filename.open('wb')
elif file and filename_root is None:
filename = getattr(file, 'name', None)
else:
raise ValueError("You need to specify either 'filename_root' or "
"'file'.")
def has_converged(part_page_counts):
"""Return `True` if the last rendering iteration converged to a
stable result.
Practically, this tests whether the total number of pages and page
references to document elements have changed since the previous
rendering iteration."""
nonlocal prev_number_of_pages, prev_page_references
return (part_page_counts == prev_number_of_pages and
self.page_references == prev_page_references)
fake_container = FakeContainer(self)
try:
self.document_tree.build_document(fake_container)
(prev_number_of_pages,
prev_page_references) = self._load_cache(filename_root)
self.part_page_counts = prev_number_of_pages
self.prepare(fake_container)
self.page_elements.clear()
self.page_references = prev_page_references.copy()
self.part_page_counts = self._render_pages()
while not has_converged(self.part_page_counts):
prev_number_of_pages = self.part_page_counts
prev_page_references = self.page_references.copy()
print('Not yet converged, rendering again...')
del self.backend_document
self.backend_document = self.backend.Document(self.CREATOR)
self.part_page_counts = self._render_pages()
self.create_outlines()
if filename:
self._save_cache(filename_root, self.part_page_counts,
self.page_references)
self.style_log.write_log(filename_root)
print('Writing output: {}'.format(filename))
self.backend_document.write(file)
finally:
if filename_root:
file.close()
return not self.error | [
"def",
"render",
"(",
"self",
",",
"filename_root",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"self",
".",
"error",
"=",
"False",
"filename_root",
"=",
"Path",
"(",
"filename_root",
")",
"if",
"filename_root",
"else",
"None",
"if",
"filename_root",
... | Render the document repeatedly until the output no longer changes due
to cross-references that need some iterations to converge. | [
"Render",
"the",
"document",
"repeatedly",
"until",
"the",
"output",
"no",
"longer",
"changes",
"due",
"to",
"cross",
"-",
"references",
"that",
"need",
"some",
"iterations",
"to",
"converge",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/document.py#L401-L455 | train | 31,294 |
brechtm/rinohtype | src/rinoh/document.py | Document.create_outlines | def create_outlines(self):
"""Create an outline in the output file that allows for easy navigation
of the document. The outline is a hierarchical tree of all the sections
in the document."""
sections = parent = []
current_level = 1
stack = []
fake_container = FakeContainer(self)
for section in self._sections:
if not section.show_in_toc(fake_container):
continue
section_id = section.get_id(self, create=False)
section_number = self.get_reference(section_id, 'number')
section_title = self.get_reference(section_id, 'title')
if section.level > current_level:
if section.level != current_level + 1:
warn("Your document section hierarchy is missing levels. "
"Please report this at https://github.com/brechtm"
"/rinohtype/pull/67")
break
stack.append(parent)
parent = current
elif section.level < current_level:
for i in range(current_level - section.level):
parent = stack.pop()
current = []
item = (str(section_id), section_number, section_title, current)
parent.append(item)
current_level = section.level
self.backend_document.create_outlines(sections) | python | def create_outlines(self):
"""Create an outline in the output file that allows for easy navigation
of the document. The outline is a hierarchical tree of all the sections
in the document."""
sections = parent = []
current_level = 1
stack = []
fake_container = FakeContainer(self)
for section in self._sections:
if not section.show_in_toc(fake_container):
continue
section_id = section.get_id(self, create=False)
section_number = self.get_reference(section_id, 'number')
section_title = self.get_reference(section_id, 'title')
if section.level > current_level:
if section.level != current_level + 1:
warn("Your document section hierarchy is missing levels. "
"Please report this at https://github.com/brechtm"
"/rinohtype/pull/67")
break
stack.append(parent)
parent = current
elif section.level < current_level:
for i in range(current_level - section.level):
parent = stack.pop()
current = []
item = (str(section_id), section_number, section_title, current)
parent.append(item)
current_level = section.level
self.backend_document.create_outlines(sections) | [
"def",
"create_outlines",
"(",
"self",
")",
":",
"sections",
"=",
"parent",
"=",
"[",
"]",
"current_level",
"=",
"1",
"stack",
"=",
"[",
"]",
"fake_container",
"=",
"FakeContainer",
"(",
"self",
")",
"for",
"section",
"in",
"self",
".",
"_sections",
":",... | Create an outline in the output file that allows for easy navigation
of the document. The outline is a hierarchical tree of all the sections
in the document. | [
"Create",
"an",
"outline",
"in",
"the",
"output",
"file",
"that",
"allows",
"for",
"easy",
"navigation",
"of",
"the",
"document",
".",
"The",
"outline",
"is",
"a",
"hierarchical",
"tree",
"of",
"all",
"the",
"sections",
"in",
"the",
"document",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/document.py#L457-L486 | train | 31,295 |
brechtm/rinohtype | src/rinoh/document.py | Document._render_pages | def _render_pages(self):
"""Render the complete document once and return the number of pages
rendered."""
self.style_log = StyleLog(self.stylesheet)
self.floats = set()
self.placed_footnotes = set()
self._start_time = time.time()
part_page_counts = {}
part_page_count = PartPageCount()
last_number_format = None
for part_template in self.part_templates:
part = part_template.document_part(self, part_page_count.count + 1)
if part is None:
continue
if part_template.page_number_format != last_number_format:
part_page_count = PartPageCount()
part_page_count += part.render(part_page_count.count + 1)
part_page_counts[part_template.name] = part_page_count
last_number_format = part_template.page_number_format
sys.stdout.write('\n') # for the progress indicator
return part_page_counts | python | def _render_pages(self):
"""Render the complete document once and return the number of pages
rendered."""
self.style_log = StyleLog(self.stylesheet)
self.floats = set()
self.placed_footnotes = set()
self._start_time = time.time()
part_page_counts = {}
part_page_count = PartPageCount()
last_number_format = None
for part_template in self.part_templates:
part = part_template.document_part(self, part_page_count.count + 1)
if part is None:
continue
if part_template.page_number_format != last_number_format:
part_page_count = PartPageCount()
part_page_count += part.render(part_page_count.count + 1)
part_page_counts[part_template.name] = part_page_count
last_number_format = part_template.page_number_format
sys.stdout.write('\n') # for the progress indicator
return part_page_counts | [
"def",
"_render_pages",
"(",
"self",
")",
":",
"self",
".",
"style_log",
"=",
"StyleLog",
"(",
"self",
".",
"stylesheet",
")",
"self",
".",
"floats",
"=",
"set",
"(",
")",
"self",
".",
"placed_footnotes",
"=",
"set",
"(",
")",
"self",
".",
"_start_time... | Render the complete document once and return the number of pages
rendered. | [
"Render",
"the",
"complete",
"document",
"once",
"and",
"return",
"the",
"number",
"of",
"pages",
"rendered",
"."
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/document.py#L488-L509 | train | 31,296 |
brechtm/rinohtype | doc/build.py | htmlhelp | def htmlhelp():
"""make HTML files and a HTML help project"""
build('htmlhelp', 'Now you can run HTML Help Workshop with the .hhp '
'project file in {}.')
print('Running HTML Help Workshop...')
builddir = os.path.join(BUILDDIR, 'htmlhelp')
rc = subprocess.call(['hhc', os.path.join(builddir, 'rinohtype.hhp')])
if rc != 1:
print('Error running HTML Help Workshop. Aborting.')
sys.exit(1)
print('HTML Help Workshop finished; the CHM file is in {}.'
.format(builddir)) | python | def htmlhelp():
"""make HTML files and a HTML help project"""
build('htmlhelp', 'Now you can run HTML Help Workshop with the .hhp '
'project file in {}.')
print('Running HTML Help Workshop...')
builddir = os.path.join(BUILDDIR, 'htmlhelp')
rc = subprocess.call(['hhc', os.path.join(builddir, 'rinohtype.hhp')])
if rc != 1:
print('Error running HTML Help Workshop. Aborting.')
sys.exit(1)
print('HTML Help Workshop finished; the CHM file is in {}.'
.format(builddir)) | [
"def",
"htmlhelp",
"(",
")",
":",
"build",
"(",
"'htmlhelp'",
",",
"'Now you can run HTML Help Workshop with the .hhp '",
"'project file in {}.'",
")",
"print",
"(",
"'Running HTML Help Workshop...'",
")",
"builddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BUILDDI... | make HTML files and a HTML help project | [
"make",
"HTML",
"files",
"and",
"a",
"HTML",
"help",
"project"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/doc/build.py#L109-L120 | train | 31,297 |
brechtm/rinohtype | doc/build.py | latexpdf | def latexpdf():
"""make LaTeX files and run them through pdflatex"""
rc = latex()
print('Running LaTeX files through pdflatex...')
builddir = os.path.join(BUILDDIR, 'latex')
subprocess.call(['make', '-C', builddir, 'all-pdf'])
print('pdflatex finished; the PDF files are in {}.'.format(builddir)) | python | def latexpdf():
"""make LaTeX files and run them through pdflatex"""
rc = latex()
print('Running LaTeX files through pdflatex...')
builddir = os.path.join(BUILDDIR, 'latex')
subprocess.call(['make', '-C', builddir, 'all-pdf'])
print('pdflatex finished; the PDF files are in {}.'.format(builddir)) | [
"def",
"latexpdf",
"(",
")",
":",
"rc",
"=",
"latex",
"(",
")",
"print",
"(",
"'Running LaTeX files through pdflatex...'",
")",
"builddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BUILDDIR",
",",
"'latex'",
")",
"subprocess",
".",
"call",
"(",
"[",
"'... | make LaTeX files and run them through pdflatex | [
"make",
"LaTeX",
"files",
"and",
"run",
"them",
"through",
"pdflatex"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/doc/build.py#L165-L171 | train | 31,298 |
brechtm/rinohtype | doc/build.py | info | def info():
"""make Texinfo files and run them through makeinfo"""
rc = texinfo()
print('Running Texinfo files through makeinfo...')
builddir = os.path.join(BUILDDIR, 'texinfo')
subprocess.call(['make', '-C', builddir, 'info'])
print('makeinfo finished; the Info files are in {}.'.format(builddir)) | python | def info():
"""make Texinfo files and run them through makeinfo"""
rc = texinfo()
print('Running Texinfo files through makeinfo...')
builddir = os.path.join(BUILDDIR, 'texinfo')
subprocess.call(['make', '-C', builddir, 'info'])
print('makeinfo finished; the Info files are in {}.'.format(builddir)) | [
"def",
"info",
"(",
")",
":",
"rc",
"=",
"texinfo",
"(",
")",
"print",
"(",
"'Running Texinfo files through makeinfo...'",
")",
"builddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BUILDDIR",
",",
"'texinfo'",
")",
"subprocess",
".",
"call",
"(",
"[",
... | make Texinfo files and run them through makeinfo | [
"make",
"Texinfo",
"files",
"and",
"run",
"them",
"through",
"makeinfo"
] | 40a63c4e5ad7550f62b6860f1812cb67cafb9dc7 | https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/doc/build.py#L206-L212 | train | 31,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.