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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | MenuPageMixin.get_text_for_repeated_menu_item | def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
return self.repeated_item_text or getattr(
self, source_field_name, self.title
) | python | def get_text_for_repeated_menu_item(
self, request=None, current_site=None, original_menu_tag='', **kwargs
):
"""Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
return self.repeated_item_text or getattr(
self, source_field_name, self.title
) | [
"def",
"get_text_for_repeated_menu_item",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"source_field_name",
"=",
"settings",
".",
"PAGE_FIELD_FOR_MENU_ITEM_TEXT",
"return",
"self",
".",
"repeated_item_text",
"or",
"getattr",
"(",
"self",
",",
"source_field_name",
",",
"self",
".",
"title",
")"
] | Return the a string to use as 'text' for this page when it is being
included as a 'repeated' menu item in a menu. You might want to
override this method if you're creating a multilingual site and you
have different translations of 'repeated_item_text' that you wish to
surface. | [
"Return",
"the",
"a",
"string",
"to",
"use",
"as",
"text",
"for",
"this",
"page",
"when",
"it",
"is",
"being",
"included",
"as",
"a",
"repeated",
"menu",
"item",
"in",
"a",
"menu",
".",
"You",
"might",
"want",
"to",
"override",
"this",
"method",
"if",
"you",
"re",
"creating",
"a",
"multilingual",
"site",
"and",
"you",
"have",
"different",
"translations",
"of",
"repeated_item_text",
"that",
"you",
"wish",
"to",
"surface",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L82-L93 | train |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | MenuPageMixin.get_repeated_menu_item | def get_repeated_menu_item(
self, current_page, current_site, apply_active_classes,
original_menu_tag, request=None, use_absolute_page_urls=False,
):
"""Return something that can be used to display a 'repeated' menu item
for this specific page."""
menuitem = copy(self)
# Set/reset 'text'
menuitem.text = self.get_text_for_repeated_menu_item(
request, current_site, original_menu_tag
)
# Set/reset 'href'
if use_absolute_page_urls:
url = self.get_full_url(request=request)
else:
url = self.relative_url(current_site)
menuitem.href = url
# Set/reset 'active_class'
if apply_active_classes and self == current_page:
menuitem.active_class = settings.ACTIVE_CLASS
else:
menuitem.active_class = ''
# Set/reset 'has_children_in_menu' and 'sub_menu'
menuitem.has_children_in_menu = False
menuitem.sub_menu = None
return menuitem | python | def get_repeated_menu_item(
self, current_page, current_site, apply_active_classes,
original_menu_tag, request=None, use_absolute_page_urls=False,
):
"""Return something that can be used to display a 'repeated' menu item
for this specific page."""
menuitem = copy(self)
# Set/reset 'text'
menuitem.text = self.get_text_for_repeated_menu_item(
request, current_site, original_menu_tag
)
# Set/reset 'href'
if use_absolute_page_urls:
url = self.get_full_url(request=request)
else:
url = self.relative_url(current_site)
menuitem.href = url
# Set/reset 'active_class'
if apply_active_classes and self == current_page:
menuitem.active_class = settings.ACTIVE_CLASS
else:
menuitem.active_class = ''
# Set/reset 'has_children_in_menu' and 'sub_menu'
menuitem.has_children_in_menu = False
menuitem.sub_menu = None
return menuitem | [
"def",
"get_repeated_menu_item",
"(",
"self",
",",
"current_page",
",",
"current_site",
",",
"apply_active_classes",
",",
"original_menu_tag",
",",
"request",
"=",
"None",
",",
"use_absolute_page_urls",
"=",
"False",
",",
")",
":",
"menuitem",
"=",
"copy",
"(",
"self",
")",
"# Set/reset 'text'",
"menuitem",
".",
"text",
"=",
"self",
".",
"get_text_for_repeated_menu_item",
"(",
"request",
",",
"current_site",
",",
"original_menu_tag",
")",
"# Set/reset 'href'",
"if",
"use_absolute_page_urls",
":",
"url",
"=",
"self",
".",
"get_full_url",
"(",
"request",
"=",
"request",
")",
"else",
":",
"url",
"=",
"self",
".",
"relative_url",
"(",
"current_site",
")",
"menuitem",
".",
"href",
"=",
"url",
"# Set/reset 'active_class'",
"if",
"apply_active_classes",
"and",
"self",
"==",
"current_page",
":",
"menuitem",
".",
"active_class",
"=",
"settings",
".",
"ACTIVE_CLASS",
"else",
":",
"menuitem",
".",
"active_class",
"=",
"''",
"# Set/reset 'has_children_in_menu' and 'sub_menu'",
"menuitem",
".",
"has_children_in_menu",
"=",
"False",
"menuitem",
".",
"sub_menu",
"=",
"None",
"return",
"menuitem"
] | Return something that can be used to display a 'repeated' menu item
for this specific page. | [
"Return",
"something",
"that",
"can",
"be",
"used",
"to",
"display",
"a",
"repeated",
"menu",
"item",
"for",
"this",
"specific",
"page",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L95-L126 | train |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | AbstractLinkPage.menu_text | def menu_text(self, request=None):
"""Return a string to use as link text when this page appears in
menus."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
if(
source_field_name != 'menu_text' and
hasattr(self, source_field_name)
):
return getattr(self, source_field_name)
return self.title | python | def menu_text(self, request=None):
"""Return a string to use as link text when this page appears in
menus."""
source_field_name = settings.PAGE_FIELD_FOR_MENU_ITEM_TEXT
if(
source_field_name != 'menu_text' and
hasattr(self, source_field_name)
):
return getattr(self, source_field_name)
return self.title | [
"def",
"menu_text",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"source_field_name",
"=",
"settings",
".",
"PAGE_FIELD_FOR_MENU_ITEM_TEXT",
"if",
"(",
"source_field_name",
"!=",
"'menu_text'",
"and",
"hasattr",
"(",
"self",
",",
"source_field_name",
")",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"source_field_name",
")",
"return",
"self",
".",
"title"
] | Return a string to use as link text when this page appears in
menus. | [
"Return",
"a",
"string",
"to",
"use",
"as",
"link",
"text",
"when",
"this",
"page",
"appears",
"in",
"menus",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L184-L193 | train |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | AbstractLinkPage.link_page_is_suitable_for_display | def link_page_is_suitable_for_display(
self, request=None, current_site=None, menu_instance=None,
original_menu_tag=''
):
"""
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
"""
if self.link_page:
if(
not self.link_page.show_in_menus or
not self.link_page.live or
self.link_page.expired
):
return False
return True | python | def link_page_is_suitable_for_display(
self, request=None, current_site=None, menu_instance=None,
original_menu_tag=''
):
"""
Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much
"""
if self.link_page:
if(
not self.link_page.show_in_menus or
not self.link_page.live or
self.link_page.expired
):
return False
return True | [
"def",
"link_page_is_suitable_for_display",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"menu_instance",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
")",
":",
"if",
"self",
".",
"link_page",
":",
"if",
"(",
"not",
"self",
".",
"link_page",
".",
"show_in_menus",
"or",
"not",
"self",
".",
"link_page",
".",
"live",
"or",
"self",
".",
"link_page",
".",
"expired",
")",
":",
"return",
"False",
"return",
"True"
] | Like menu items, link pages linking to pages should only be included
in menus when the target page is live and is itself configured to
appear in menus. Returns a boolean indicating as much | [
"Like",
"menu",
"items",
"link",
"pages",
"linking",
"to",
"pages",
"should",
"only",
"be",
"included",
"in",
"menus",
"when",
"the",
"target",
"page",
"is",
"live",
"and",
"is",
"itself",
"configured",
"to",
"appear",
"in",
"menus",
".",
"Returns",
"a",
"boolean",
"indicating",
"as",
"much"
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L217-L233 | train |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | AbstractLinkPage.show_in_menus_custom | def show_in_menus_custom(self, request=None, current_site=None,
menu_instance=None, original_menu_tag=''):
"""
Return a boolean indicating whether this page should be included in
menus being rendered.
"""
if not self.show_in_menus:
return False
if self.link_page:
return self.link_page_is_suitable_for_display()
return True | python | def show_in_menus_custom(self, request=None, current_site=None,
menu_instance=None, original_menu_tag=''):
"""
Return a boolean indicating whether this page should be included in
menus being rendered.
"""
if not self.show_in_menus:
return False
if self.link_page:
return self.link_page_is_suitable_for_display()
return True | [
"def",
"show_in_menus_custom",
"(",
"self",
",",
"request",
"=",
"None",
",",
"current_site",
"=",
"None",
",",
"menu_instance",
"=",
"None",
",",
"original_menu_tag",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"show_in_menus",
":",
"return",
"False",
"if",
"self",
".",
"link_page",
":",
"return",
"self",
".",
"link_page_is_suitable_for_display",
"(",
")",
"return",
"True"
] | Return a boolean indicating whether this page should be included in
menus being rendered. | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"this",
"page",
"should",
"be",
"included",
"in",
"menus",
"being",
"rendered",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L235-L245 | train |
rkhleics/wagtailmenus | wagtailmenus/utils/inspection.py | accepts_kwarg | def accepts_kwarg(func, kwarg):
"""
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
"""
signature = inspect.signature(func)
try:
signature.bind_partial(**{kwarg: None})
return True
except TypeError:
return False | python | def accepts_kwarg(func, kwarg):
"""
Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg`
"""
signature = inspect.signature(func)
try:
signature.bind_partial(**{kwarg: None})
return True
except TypeError:
return False | [
"def",
"accepts_kwarg",
"(",
"func",
",",
"kwarg",
")",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"try",
":",
"signature",
".",
"bind_partial",
"(",
"*",
"*",
"{",
"kwarg",
":",
"None",
"}",
")",
"return",
"True",
"except",
"TypeError",
":",
"return",
"False"
] | Determine whether the callable `func` has a signature that accepts the
keyword argument `kwarg` | [
"Determine",
"whether",
"the",
"callable",
"func",
"has",
"a",
"signature",
"that",
"accepts",
"the",
"keyword",
"argument",
"kwarg"
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/utils/inspection.py#L10-L20 | train |
rkhleics/wagtailmenus | wagtailmenus/templatetags/menu_tags.py | section_menu | def section_menu(
context, show_section_root=True, show_multiple_levels=True,
apply_active_classes=True, allow_repeating_parents=True,
max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS,
template='', sub_menu_template='', sub_menu_templates=None,
use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECIFIC,
use_absolute_page_urls=False, add_sub_menus_inline=None, **kwargs
):
"""Render a section menu for the current section."""
validate_supplied_values('section_menu', max_levels=max_levels,
use_specific=use_specific)
if not show_multiple_levels:
max_levels = 1
menu_class = settings.objects.SECTION_MENU_CLASS
return menu_class.render_from_tag(
context=context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
sub_menu_template_name=sub_menu_template,
sub_menu_template_names=split_if_string(sub_menu_templates),
show_section_root=show_section_root,
**kwargs
) | python | def section_menu(
context, show_section_root=True, show_multiple_levels=True,
apply_active_classes=True, allow_repeating_parents=True,
max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS,
template='', sub_menu_template='', sub_menu_templates=None,
use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECIFIC,
use_absolute_page_urls=False, add_sub_menus_inline=None, **kwargs
):
"""Render a section menu for the current section."""
validate_supplied_values('section_menu', max_levels=max_levels,
use_specific=use_specific)
if not show_multiple_levels:
max_levels = 1
menu_class = settings.objects.SECTION_MENU_CLASS
return menu_class.render_from_tag(
context=context,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
sub_menu_template_name=sub_menu_template,
sub_menu_template_names=split_if_string(sub_menu_templates),
show_section_root=show_section_root,
**kwargs
) | [
"def",
"section_menu",
"(",
"context",
",",
"show_section_root",
"=",
"True",
",",
"show_multiple_levels",
"=",
"True",
",",
"apply_active_classes",
"=",
"True",
",",
"allow_repeating_parents",
"=",
"True",
",",
"max_levels",
"=",
"settings",
".",
"DEFAULT_SECTION_MENU_MAX_LEVELS",
",",
"template",
"=",
"''",
",",
"sub_menu_template",
"=",
"''",
",",
"sub_menu_templates",
"=",
"None",
",",
"use_specific",
"=",
"settings",
".",
"DEFAULT_SECTION_MENU_USE_SPECIFIC",
",",
"use_absolute_page_urls",
"=",
"False",
",",
"add_sub_menus_inline",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"validate_supplied_values",
"(",
"'section_menu'",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
")",
"if",
"not",
"show_multiple_levels",
":",
"max_levels",
"=",
"1",
"menu_class",
"=",
"settings",
".",
"objects",
".",
"SECTION_MENU_CLASS",
"return",
"menu_class",
".",
"render_from_tag",
"(",
"context",
"=",
"context",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"allow_repeating_parents",
"=",
"allow_repeating_parents",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"add_sub_menus_inline",
"=",
"add_sub_menus_inline",
",",
"template_name",
"=",
"template",
",",
"sub_menu_template_name",
"=",
"sub_menu_template",
",",
"sub_menu_template_names",
"=",
"split_if_string",
"(",
"sub_menu_templates",
")",
",",
"show_section_root",
"=",
"show_section_root",
",",
"*",
"*",
"kwargs",
")"
] | Render a section menu for the current section. | [
"Render",
"a",
"section",
"menu",
"for",
"the",
"current",
"section",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L84-L113 | train |
rkhleics/wagtailmenus | wagtailmenus/templatetags/menu_tags.py | sub_menu | def sub_menu(
context, menuitem_or_page, use_specific=None, allow_repeating_parents=None,
apply_active_classes=None, template='', use_absolute_page_urls=None,
add_sub_menus_inline=None, **kwargs
):
"""
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template.
"""
validate_supplied_values('sub_menu', use_specific=use_specific,
menuitem_or_page=menuitem_or_page)
max_levels = context.get(
'max_levels', settings.DEFAULT_CHILDREN_MENU_MAX_LEVELS
)
if use_specific is None:
use_specific = context.get(
'use_specific', constants.USE_SPECIFIC_AUTO)
if apply_active_classes is None:
apply_active_classes = context.get('apply_active_classes', True)
if allow_repeating_parents is None:
allow_repeating_parents = context.get('allow_repeating_parents', True)
if use_absolute_page_urls is None:
use_absolute_page_urls = context.get('use_absolute_page_urls', False)
if add_sub_menus_inline is None:
add_sub_menus_inline = context.get('add_sub_menus_inline', False)
if isinstance(menuitem_or_page, Page):
parent_page = menuitem_or_page
else:
parent_page = menuitem_or_page.link_page
original_menu = context.get('original_menu_instance')
if original_menu is None:
raise SubMenuUsageError()
menu_class = original_menu.get_sub_menu_class()
return menu_class.render_from_tag(
context=context,
parent_page=parent_page,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
**kwargs
) | python | def sub_menu(
context, menuitem_or_page, use_specific=None, allow_repeating_parents=None,
apply_active_classes=None, template='', use_absolute_page_urls=None,
add_sub_menus_inline=None, **kwargs
):
"""
Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template.
"""
validate_supplied_values('sub_menu', use_specific=use_specific,
menuitem_or_page=menuitem_or_page)
max_levels = context.get(
'max_levels', settings.DEFAULT_CHILDREN_MENU_MAX_LEVELS
)
if use_specific is None:
use_specific = context.get(
'use_specific', constants.USE_SPECIFIC_AUTO)
if apply_active_classes is None:
apply_active_classes = context.get('apply_active_classes', True)
if allow_repeating_parents is None:
allow_repeating_parents = context.get('allow_repeating_parents', True)
if use_absolute_page_urls is None:
use_absolute_page_urls = context.get('use_absolute_page_urls', False)
if add_sub_menus_inline is None:
add_sub_menus_inline = context.get('add_sub_menus_inline', False)
if isinstance(menuitem_or_page, Page):
parent_page = menuitem_or_page
else:
parent_page = menuitem_or_page.link_page
original_menu = context.get('original_menu_instance')
if original_menu is None:
raise SubMenuUsageError()
menu_class = original_menu.get_sub_menu_class()
return menu_class.render_from_tag(
context=context,
parent_page=parent_page,
max_levels=max_levels,
use_specific=use_specific,
apply_active_classes=apply_active_classes,
allow_repeating_parents=allow_repeating_parents,
use_absolute_page_urls=use_absolute_page_urls,
add_sub_menus_inline=add_sub_menus_inline,
template_name=template,
**kwargs
) | [
"def",
"sub_menu",
"(",
"context",
",",
"menuitem_or_page",
",",
"use_specific",
"=",
"None",
",",
"allow_repeating_parents",
"=",
"None",
",",
"apply_active_classes",
"=",
"None",
",",
"template",
"=",
"''",
",",
"use_absolute_page_urls",
"=",
"None",
",",
"add_sub_menus_inline",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"validate_supplied_values",
"(",
"'sub_menu'",
",",
"use_specific",
"=",
"use_specific",
",",
"menuitem_or_page",
"=",
"menuitem_or_page",
")",
"max_levels",
"=",
"context",
".",
"get",
"(",
"'max_levels'",
",",
"settings",
".",
"DEFAULT_CHILDREN_MENU_MAX_LEVELS",
")",
"if",
"use_specific",
"is",
"None",
":",
"use_specific",
"=",
"context",
".",
"get",
"(",
"'use_specific'",
",",
"constants",
".",
"USE_SPECIFIC_AUTO",
")",
"if",
"apply_active_classes",
"is",
"None",
":",
"apply_active_classes",
"=",
"context",
".",
"get",
"(",
"'apply_active_classes'",
",",
"True",
")",
"if",
"allow_repeating_parents",
"is",
"None",
":",
"allow_repeating_parents",
"=",
"context",
".",
"get",
"(",
"'allow_repeating_parents'",
",",
"True",
")",
"if",
"use_absolute_page_urls",
"is",
"None",
":",
"use_absolute_page_urls",
"=",
"context",
".",
"get",
"(",
"'use_absolute_page_urls'",
",",
"False",
")",
"if",
"add_sub_menus_inline",
"is",
"None",
":",
"add_sub_menus_inline",
"=",
"context",
".",
"get",
"(",
"'add_sub_menus_inline'",
",",
"False",
")",
"if",
"isinstance",
"(",
"menuitem_or_page",
",",
"Page",
")",
":",
"parent_page",
"=",
"menuitem_or_page",
"else",
":",
"parent_page",
"=",
"menuitem_or_page",
".",
"link_page",
"original_menu",
"=",
"context",
".",
"get",
"(",
"'original_menu_instance'",
")",
"if",
"original_menu",
"is",
"None",
":",
"raise",
"SubMenuUsageError",
"(",
")",
"menu_class",
"=",
"original_menu",
".",
"get_sub_menu_class",
"(",
")",
"return",
"menu_class",
".",
"render_from_tag",
"(",
"context",
"=",
"context",
",",
"parent_page",
"=",
"parent_page",
",",
"max_levels",
"=",
"max_levels",
",",
"use_specific",
"=",
"use_specific",
",",
"apply_active_classes",
"=",
"apply_active_classes",
",",
"allow_repeating_parents",
"=",
"allow_repeating_parents",
",",
"use_absolute_page_urls",
"=",
"use_absolute_page_urls",
",",
"add_sub_menus_inline",
"=",
"add_sub_menus_inline",
",",
"template_name",
"=",
"template",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve the children pages for the `menuitem_or_page` provided, turn them
into menu items, and render them to a template. | [
"Retrieve",
"the",
"children",
"pages",
"for",
"the",
"menuitem_or_page",
"provided",
"turn",
"them",
"into",
"menu",
"items",
"and",
"render",
"them",
"to",
"a",
"template",
"."
] | a41f240bed0d362e0d4dd4ef04a230f2b1827a93 | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/templatetags/menu_tags.py#L147-L200 | train |
opentracing-contrib/python-flask | flask_opentracing/tracing.py | FlaskTracing.trace | def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
def wrapper(*args, **kwargs):
if self._trace_all_requests:
return f(*args, **kwargs)
self._before_request_fn(list(attributes))
try:
r = f(*args, **kwargs)
self._after_request_fn()
except Exception as e:
self._after_request_fn(error=e)
raise
self._after_request_fn()
return r
wrapper.__name__ = f.__name__
return wrapper
return decorator | python | def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
def wrapper(*args, **kwargs):
if self._trace_all_requests:
return f(*args, **kwargs)
self._before_request_fn(list(attributes))
try:
r = f(*args, **kwargs)
self._after_request_fn()
except Exception as e:
self._after_request_fn(error=e)
raise
self._after_request_fn()
return r
wrapper.__name__ = f.__name__
return wrapper
return decorator | [
"def",
"trace",
"(",
"self",
",",
"*",
"attributes",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_trace_all_requests",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_before_request_fn",
"(",
"list",
"(",
"attributes",
")",
")",
"try",
":",
"r",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_after_request_fn",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_after_request_fn",
"(",
"error",
"=",
"e",
")",
"raise",
"self",
".",
"_after_request_fn",
"(",
")",
"return",
"r",
"wrapper",
".",
"__name__",
"=",
"f",
".",
"__name__",
"return",
"wrapper",
"return",
"decorator"
] | Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span | [
"Function",
"decorator",
"that",
"traces",
"functions"
] | 74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca | https://github.com/opentracing-contrib/python-flask/blob/74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca/flask_opentracing/tracing.py#L66-L93 | train |
opentracing-contrib/python-flask | flask_opentracing/tracing.py | FlaskTracing.get_span | def get_span(self, request=None):
"""
Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from
"""
if request is None and stack.top:
request = stack.top.request
scope = self._current_scopes.get(request, None)
return None if scope is None else scope.span | python | def get_span(self, request=None):
"""
Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from
"""
if request is None and stack.top:
request = stack.top.request
scope = self._current_scopes.get(request, None)
return None if scope is None else scope.span | [
"def",
"get_span",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"if",
"request",
"is",
"None",
"and",
"stack",
".",
"top",
":",
"request",
"=",
"stack",
".",
"top",
".",
"request",
"scope",
"=",
"self",
".",
"_current_scopes",
".",
"get",
"(",
"request",
",",
"None",
")",
"return",
"None",
"if",
"scope",
"is",
"None",
"else",
"scope",
".",
"span"
] | Returns the span tracing `request`, or the current request if
`request==None`.
If there is no such span, get_span returns None.
@param request the request to get the span from | [
"Returns",
"the",
"span",
"tracing",
"request",
"or",
"the",
"current",
"request",
"if",
"request",
"==",
"None",
"."
] | 74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca | https://github.com/opentracing-contrib/python-flask/blob/74bfe8bcd00eee9ce75a15c1634fda4c5d5f26ca/flask_opentracing/tracing.py#L95-L108 | train |
rsinger86/django-lifecycle | django_lifecycle/__init__.py | LifecycleModelMixin.initial_value | def initial_value(self, field_name: str = None):
"""
Get initial value of field when model was instantiated.
"""
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
attribute = self._diff_with_initial.get(field_name, None)
if not attribute:
return None
return attribute[0] | python | def initial_value(self, field_name: str = None):
"""
Get initial value of field when model was instantiated.
"""
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
attribute = self._diff_with_initial.get(field_name, None)
if not attribute:
return None
return attribute[0] | [
"def",
"initial_value",
"(",
"self",
",",
"field_name",
":",
"str",
"=",
"None",
")",
":",
"if",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
":",
"if",
"not",
"field_name",
".",
"endswith",
"(",
"'_id'",
")",
":",
"field_name",
"=",
"field_name",
"+",
"'_id'",
"attribute",
"=",
"self",
".",
"_diff_with_initial",
".",
"get",
"(",
"field_name",
",",
"None",
")",
"if",
"not",
"attribute",
":",
"return",
"None",
"return",
"attribute",
"[",
"0",
"]"
] | Get initial value of field when model was instantiated. | [
"Get",
"initial",
"value",
"of",
"field",
"when",
"model",
"was",
"instantiated",
"."
] | 2196908ef0e242e52aab5bfaa3d337930700c106 | https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L94-L107 | train |
rsinger86/django-lifecycle | django_lifecycle/__init__.py | LifecycleModelMixin.has_changed | def has_changed(self, field_name: str = None) -> bool:
"""
Check if a field has changed since the model was instantiated.
"""
changed = self._diff_with_initial.keys()
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
if field_name in changed:
return True
return False | python | def has_changed(self, field_name: str = None) -> bool:
"""
Check if a field has changed since the model was instantiated.
"""
changed = self._diff_with_initial.keys()
if self._meta.get_field(field_name).get_internal_type() == 'ForeignKey':
if not field_name.endswith('_id'):
field_name = field_name+'_id'
if field_name in changed:
return True
return False | [
"def",
"has_changed",
"(",
"self",
",",
"field_name",
":",
"str",
"=",
"None",
")",
"->",
"bool",
":",
"changed",
"=",
"self",
".",
"_diff_with_initial",
".",
"keys",
"(",
")",
"if",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
":",
"if",
"not",
"field_name",
".",
"endswith",
"(",
"'_id'",
")",
":",
"field_name",
"=",
"field_name",
"+",
"'_id'",
"if",
"field_name",
"in",
"changed",
":",
"return",
"True",
"return",
"False"
] | Check if a field has changed since the model was instantiated. | [
"Check",
"if",
"a",
"field",
"has",
"changed",
"since",
"the",
"model",
"was",
"instantiated",
"."
] | 2196908ef0e242e52aab5bfaa3d337930700c106 | https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L109-L122 | train |
rsinger86/django-lifecycle | django_lifecycle/__init__.py | LifecycleModelMixin._descriptor_names | def _descriptor_names(self):
"""
Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model.
"""
descriptor_names = []
for name in dir(self):
try:
attr = getattr(type(self), name)
if isinstance(attr, DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES):
descriptor_names.append(name)
except AttributeError:
pass
return descriptor_names | python | def _descriptor_names(self):
"""
Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model.
"""
descriptor_names = []
for name in dir(self):
try:
attr = getattr(type(self), name)
if isinstance(attr, DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES):
descriptor_names.append(name)
except AttributeError:
pass
return descriptor_names | [
"def",
"_descriptor_names",
"(",
"self",
")",
":",
"descriptor_names",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"self",
")",
":",
"try",
":",
"attr",
"=",
"getattr",
"(",
"type",
"(",
"self",
")",
",",
"name",
")",
"if",
"isinstance",
"(",
"attr",
",",
"DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES",
")",
":",
"descriptor_names",
".",
"append",
"(",
"name",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"descriptor_names"
] | Attributes which are Django descriptors. These represent a field
which is a one-to-many or many-to-many relationship that is
potentially defined in another model, and doesn't otherwise appear
as a field on this model. | [
"Attributes",
"which",
"are",
"Django",
"descriptors",
".",
"These",
"represent",
"a",
"field",
"which",
"is",
"a",
"one",
"-",
"to",
"-",
"many",
"or",
"many",
"-",
"to",
"-",
"many",
"relationship",
"that",
"is",
"potentially",
"defined",
"in",
"another",
"model",
"and",
"doesn",
"t",
"otherwise",
"appear",
"as",
"a",
"field",
"on",
"this",
"model",
"."
] | 2196908ef0e242e52aab5bfaa3d337930700c106 | https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L181-L201 | train |
rsinger86/django-lifecycle | django_lifecycle/__init__.py | LifecycleModelMixin._run_hooked_methods | def _run_hooked_methods(self, hook: str):
"""
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
"""
for method in self._potentially_hooked_methods:
for callback_specs in method._hooked:
if callback_specs['hook'] != hook:
continue
when = callback_specs.get('when')
if when:
if self._check_callback_conditions(callback_specs):
method()
else:
method() | python | def _run_hooked_methods(self, hook: str):
"""
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
"""
for method in self._potentially_hooked_methods:
for callback_specs in method._hooked:
if callback_specs['hook'] != hook:
continue
when = callback_specs.get('when')
if when:
if self._check_callback_conditions(callback_specs):
method()
else:
method() | [
"def",
"_run_hooked_methods",
"(",
"self",
",",
"hook",
":",
"str",
")",
":",
"for",
"method",
"in",
"self",
".",
"_potentially_hooked_methods",
":",
"for",
"callback_specs",
"in",
"method",
".",
"_hooked",
":",
"if",
"callback_specs",
"[",
"'hook'",
"]",
"!=",
"hook",
":",
"continue",
"when",
"=",
"callback_specs",
".",
"get",
"(",
"'when'",
")",
"if",
"when",
":",
"if",
"self",
".",
"_check_callback_conditions",
"(",
"callback_specs",
")",
":",
"method",
"(",
")",
"else",
":",
"method",
"(",
")"
] | Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run. | [
"Iterate",
"through",
"decorated",
"methods",
"to",
"find",
"those",
"that",
"should",
"be",
"triggered",
"by",
"the",
"current",
"hook",
".",
"If",
"conditions",
"exist",
"check",
"them",
"before",
"running",
"otherwise",
"go",
"ahead",
"and",
"run",
"."
] | 2196908ef0e242e52aab5bfaa3d337930700c106 | https://github.com/rsinger86/django-lifecycle/blob/2196908ef0e242e52aab5bfaa3d337930700c106/django_lifecycle/__init__.py#L228-L245 | train |
llimllib/limbo | limbo/limbo.py | loop | def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_activity += 1
events = server.slack.rtm_read()
for event in events:
loops_without_activity = 0
logger.debug("got {0}".format(event))
response = handle_event(event, server)
# The docs (https://api.slack.com/docs/message-threading)
# suggest looking for messages where `thread_ts` != `ts`,
# but I can't see anywhere that it would make a practical
# difference. If a message is part of a thread, respond to
# that thread.
thread_ts = None
if 'thread_ts' in event:
thread_ts = event['thread_ts']
while response:
# The Slack API documentation says:
#
# Clients should limit messages sent to channels to 4000
# characters, which will always be under 16k bytes even
# with a message comprised solely of non-BMP Unicode
# characters at 4 bytes each.
#
# but empirical testing shows that I'm getting disconnected
# at 4000 characters and even quite a bit lower. Use 1000
# to be safe
server.slack.rtm_send_message(event["channel"],
response[:1000], thread_ts)
response = response[1000:]
# Run the loop hook. This doesn't send messages it receives,
# because it doesn't know where to send them. Use
# server.slack.post_message to send messages from a loop hook
run_hook(server.hooks, "loop", server)
# The Slack RTM API docs say:
#
# > When there is no other activity clients should send a ping
# > every few seconds
#
# So, if we've gone >5 seconds without any activity, send a ping.
# If the connection has broken, this will reveal it so slack can
# quit
if loops_without_activity > 5:
server.slack.ping()
loops_without_activity = 0
end = time.time()
runtime = start - end
time.sleep(max(1 - runtime, 0))
if test_loop:
test_loop -= 1
except KeyboardInterrupt:
if os.environ.get("LIMBO_DEBUG"):
import ipdb
ipdb.set_trace()
raise | python | def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_activity += 1
events = server.slack.rtm_read()
for event in events:
loops_without_activity = 0
logger.debug("got {0}".format(event))
response = handle_event(event, server)
# The docs (https://api.slack.com/docs/message-threading)
# suggest looking for messages where `thread_ts` != `ts`,
# but I can't see anywhere that it would make a practical
# difference. If a message is part of a thread, respond to
# that thread.
thread_ts = None
if 'thread_ts' in event:
thread_ts = event['thread_ts']
while response:
# The Slack API documentation says:
#
# Clients should limit messages sent to channels to 4000
# characters, which will always be under 16k bytes even
# with a message comprised solely of non-BMP Unicode
# characters at 4 bytes each.
#
# but empirical testing shows that I'm getting disconnected
# at 4000 characters and even quite a bit lower. Use 1000
# to be safe
server.slack.rtm_send_message(event["channel"],
response[:1000], thread_ts)
response = response[1000:]
# Run the loop hook. This doesn't send messages it receives,
# because it doesn't know where to send them. Use
# server.slack.post_message to send messages from a loop hook
run_hook(server.hooks, "loop", server)
# The Slack RTM API docs say:
#
# > When there is no other activity clients should send a ping
# > every few seconds
#
# So, if we've gone >5 seconds without any activity, send a ping.
# If the connection has broken, this will reveal it so slack can
# quit
if loops_without_activity > 5:
server.slack.ping()
loops_without_activity = 0
end = time.time()
runtime = start - end
time.sleep(max(1 - runtime, 0))
if test_loop:
test_loop -= 1
except KeyboardInterrupt:
if os.environ.get("LIMBO_DEBUG"):
import ipdb
ipdb.set_trace()
raise | [
"def",
"loop",
"(",
"server",
",",
"test_loop",
"=",
"None",
")",
":",
"try",
":",
"loops_without_activity",
"=",
"0",
"while",
"test_loop",
"is",
"None",
"or",
"test_loop",
">",
"0",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"loops_without_activity",
"+=",
"1",
"events",
"=",
"server",
".",
"slack",
".",
"rtm_read",
"(",
")",
"for",
"event",
"in",
"events",
":",
"loops_without_activity",
"=",
"0",
"logger",
".",
"debug",
"(",
"\"got {0}\"",
".",
"format",
"(",
"event",
")",
")",
"response",
"=",
"handle_event",
"(",
"event",
",",
"server",
")",
"# The docs (https://api.slack.com/docs/message-threading)",
"# suggest looking for messages where `thread_ts` != `ts`,",
"# but I can't see anywhere that it would make a practical",
"# difference. If a message is part of a thread, respond to",
"# that thread.",
"thread_ts",
"=",
"None",
"if",
"'thread_ts'",
"in",
"event",
":",
"thread_ts",
"=",
"event",
"[",
"'thread_ts'",
"]",
"while",
"response",
":",
"# The Slack API documentation says:",
"#",
"# Clients should limit messages sent to channels to 4000",
"# characters, which will always be under 16k bytes even",
"# with a message comprised solely of non-BMP Unicode",
"# characters at 4 bytes each.",
"#",
"# but empirical testing shows that I'm getting disconnected",
"# at 4000 characters and even quite a bit lower. Use 1000",
"# to be safe",
"server",
".",
"slack",
".",
"rtm_send_message",
"(",
"event",
"[",
"\"channel\"",
"]",
",",
"response",
"[",
":",
"1000",
"]",
",",
"thread_ts",
")",
"response",
"=",
"response",
"[",
"1000",
":",
"]",
"# Run the loop hook. This doesn't send messages it receives,",
"# because it doesn't know where to send them. Use",
"# server.slack.post_message to send messages from a loop hook",
"run_hook",
"(",
"server",
".",
"hooks",
",",
"\"loop\"",
",",
"server",
")",
"# The Slack RTM API docs say:",
"#",
"# > When there is no other activity clients should send a ping",
"# > every few seconds",
"#",
"# So, if we've gone >5 seconds without any activity, send a ping.",
"# If the connection has broken, this will reveal it so slack can",
"# quit",
"if",
"loops_without_activity",
">",
"5",
":",
"server",
".",
"slack",
".",
"ping",
"(",
")",
"loops_without_activity",
"=",
"0",
"end",
"=",
"time",
".",
"time",
"(",
")",
"runtime",
"=",
"start",
"-",
"end",
"time",
".",
"sleep",
"(",
"max",
"(",
"1",
"-",
"runtime",
",",
"0",
")",
")",
"if",
"test_loop",
":",
"test_loop",
"-=",
"1",
"except",
"KeyboardInterrupt",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"LIMBO_DEBUG\"",
")",
":",
"import",
"ipdb",
"ipdb",
".",
"set_trace",
"(",
")",
"raise"
] | Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop | [
"Run",
"the",
"main",
"loop"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/limbo.py#L189-L258 | train |
llimllib/limbo | limbo/slack.py | SlackClient.post_message | def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username)
"""
params = {
"post_data": {
"text": message,
"channel": channel_id,
}
}
params["post_data"].update(kwargs)
return self.api_call("chat.postMessage", **params) | python | def post_message(self, channel_id, message, **kwargs):
"""
Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username)
"""
params = {
"post_data": {
"text": message,
"channel": channel_id,
}
}
params["post_data"].update(kwargs)
return self.api_call("chat.postMessage", **params) | [
"def",
"post_message",
"(",
"self",
",",
"channel_id",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"post_data\"",
":",
"{",
"\"text\"",
":",
"message",
",",
"\"channel\"",
":",
"channel_id",
",",
"}",
"}",
"params",
"[",
"\"post_data\"",
"]",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"api_call",
"(",
"\"chat.postMessage\"",
",",
"*",
"*",
"params",
")"
] | Send a message using the slack Event API.
Event messages should be used for more complex messages. See
https://api.slack.com/methods/chat.postMessage for details on arguments can be included
with your message.
When using the post_message API, to have your message look like it's sent from your bot
you'll need to include the `as_user` kwarg. Example of how to do this:
server.slack.post_message(msg['channel'], 'My message', as_user=server.slack.username) | [
"Send",
"a",
"message",
"using",
"the",
"slack",
"Event",
"API",
"."
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L99-L119 | train |
llimllib/limbo | limbo/slack.py | SlackClient.post_reaction | def post_reaction(self, channel_id, timestamp, reaction_name, **kwargs):
"""
Send a reaction to a message using slack Event API
"""
params = {
"post_data": {
"name": reaction_name,
"channel": channel_id,
"timestamp": timestamp,
}
}
params["post_data"].update(kwargs)
return self.api_call("reactions.add", **params) | python | def post_reaction(self, channel_id, timestamp, reaction_name, **kwargs):
"""
Send a reaction to a message using slack Event API
"""
params = {
"post_data": {
"name": reaction_name,
"channel": channel_id,
"timestamp": timestamp,
}
}
params["post_data"].update(kwargs)
return self.api_call("reactions.add", **params) | [
"def",
"post_reaction",
"(",
"self",
",",
"channel_id",
",",
"timestamp",
",",
"reaction_name",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"post_data\"",
":",
"{",
"\"name\"",
":",
"reaction_name",
",",
"\"channel\"",
":",
"channel_id",
",",
"\"timestamp\"",
":",
"timestamp",
",",
"}",
"}",
"params",
"[",
"\"post_data\"",
"]",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"api_call",
"(",
"\"reactions.add\"",
",",
"*",
"*",
"params",
")"
] | Send a reaction to a message using slack Event API | [
"Send",
"a",
"reaction",
"to",
"a",
"message",
"using",
"slack",
"Event",
"API"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L121-L134 | train |
llimllib/limbo | limbo/slack.py | SlackClient.get_all | def get_all(self, api_method, collection_name, **kwargs):
"""
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination
"""
objs = []
limit = 250
# if you don't provide a limit, the slack API won't return a cursor to you
page = json.loads(self.api_call(api_method, limit=limit, **kwargs))
while 1:
try:
for obj in page[collection_name]:
objs.append(obj)
except KeyError:
LOG.error("Unable to find key %s in page object: \n"
"%s", collection_name, page)
return objs
cursor = dig(page, "response_metadata", "next_cursor")
if cursor:
# In general we allow applications that integrate with Slack to send
# no more than one message per second
# https://api.slack.com/docs/rate-limits
time.sleep(1)
page = json.loads(
self.api_call(
api_method, cursor=cursor, limit=limit, **kwargs))
else:
break
return objs | python | def get_all(self, api_method, collection_name, **kwargs):
"""
Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination
"""
objs = []
limit = 250
# if you don't provide a limit, the slack API won't return a cursor to you
page = json.loads(self.api_call(api_method, limit=limit, **kwargs))
while 1:
try:
for obj in page[collection_name]:
objs.append(obj)
except KeyError:
LOG.error("Unable to find key %s in page object: \n"
"%s", collection_name, page)
return objs
cursor = dig(page, "response_metadata", "next_cursor")
if cursor:
# In general we allow applications that integrate with Slack to send
# no more than one message per second
# https://api.slack.com/docs/rate-limits
time.sleep(1)
page = json.loads(
self.api_call(
api_method, cursor=cursor, limit=limit, **kwargs))
else:
break
return objs | [
"def",
"get_all",
"(",
"self",
",",
"api_method",
",",
"collection_name",
",",
"*",
"*",
"kwargs",
")",
":",
"objs",
"=",
"[",
"]",
"limit",
"=",
"250",
"# if you don't provide a limit, the slack API won't return a cursor to you",
"page",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"api_call",
"(",
"api_method",
",",
"limit",
"=",
"limit",
",",
"*",
"*",
"kwargs",
")",
")",
"while",
"1",
":",
"try",
":",
"for",
"obj",
"in",
"page",
"[",
"collection_name",
"]",
":",
"objs",
".",
"append",
"(",
"obj",
")",
"except",
"KeyError",
":",
"LOG",
".",
"error",
"(",
"\"Unable to find key %s in page object: \\n\"",
"\"%s\"",
",",
"collection_name",
",",
"page",
")",
"return",
"objs",
"cursor",
"=",
"dig",
"(",
"page",
",",
"\"response_metadata\"",
",",
"\"next_cursor\"",
")",
"if",
"cursor",
":",
"# In general we allow applications that integrate with Slack to send",
"# no more than one message per second",
"# https://api.slack.com/docs/rate-limits",
"time",
".",
"sleep",
"(",
"1",
")",
"page",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"api_call",
"(",
"api_method",
",",
"cursor",
"=",
"cursor",
",",
"limit",
"=",
"limit",
",",
"*",
"*",
"kwargs",
")",
")",
"else",
":",
"break",
"return",
"objs"
] | Return all objects in an api_method, handle pagination, and pass
kwargs on to the method being called.
For example, "users.list" returns an object like:
{
"members": [{<member_obj>}, {<member_obj_2>}],
"response_metadata": {
"next_cursor": "cursor_id"
}
}
so if you call `get_all("users.list", "members")`, this function
will return all member objects to you while handling pagination | [
"Return",
"all",
"objects",
"in",
"an",
"api_method",
"handle",
"pagination",
"and",
"pass",
"kwargs",
"on",
"to",
"the",
"method",
"being",
"called",
"."
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/slack.py#L182-L225 | train |
llimllib/limbo | limbo/plugins/poll.py | poll | def poll(poll, msg, server):
"""Given a question and answers, present a poll"""
poll = remove_smart_quotes(poll.replace(u"\u2014", u"--"))
try:
args = ARGPARSE.parse_args(shlex.split(poll)).poll
except ValueError:
return ERROR_INVALID_FORMAT
if not 2 < len(args) < len(POLL_EMOJIS) + 1:
return ERROR_WRONG_NUMBER_OF_ARGUMENTS
result = ["Poll: {}\n".format(args[0])]
for emoji, answer in zip(POLL_EMOJIS, args[1:]):
result.append(":{}: {}\n".format(emoji, answer))
# for this we are going to need to post the message to Slack via Web API in order to
# get the TS and add reactions
msg_posted = server.slack.post_message(
msg['channel'], "".join(result), as_user=server.slack.username)
ts = json.loads(msg_posted)["ts"]
for i in range(len(args) - 1):
server.slack.post_reaction(msg['channel'], ts, POLL_EMOJIS[i]) | python | def poll(poll, msg, server):
"""Given a question and answers, present a poll"""
poll = remove_smart_quotes(poll.replace(u"\u2014", u"--"))
try:
args = ARGPARSE.parse_args(shlex.split(poll)).poll
except ValueError:
return ERROR_INVALID_FORMAT
if not 2 < len(args) < len(POLL_EMOJIS) + 1:
return ERROR_WRONG_NUMBER_OF_ARGUMENTS
result = ["Poll: {}\n".format(args[0])]
for emoji, answer in zip(POLL_EMOJIS, args[1:]):
result.append(":{}: {}\n".format(emoji, answer))
# for this we are going to need to post the message to Slack via Web API in order to
# get the TS and add reactions
msg_posted = server.slack.post_message(
msg['channel'], "".join(result), as_user=server.slack.username)
ts = json.loads(msg_posted)["ts"]
for i in range(len(args) - 1):
server.slack.post_reaction(msg['channel'], ts, POLL_EMOJIS[i]) | [
"def",
"poll",
"(",
"poll",
",",
"msg",
",",
"server",
")",
":",
"poll",
"=",
"remove_smart_quotes",
"(",
"poll",
".",
"replace",
"(",
"u\"\\u2014\"",
",",
"u\"--\"",
")",
")",
"try",
":",
"args",
"=",
"ARGPARSE",
".",
"parse_args",
"(",
"shlex",
".",
"split",
"(",
"poll",
")",
")",
".",
"poll",
"except",
"ValueError",
":",
"return",
"ERROR_INVALID_FORMAT",
"if",
"not",
"2",
"<",
"len",
"(",
"args",
")",
"<",
"len",
"(",
"POLL_EMOJIS",
")",
"+",
"1",
":",
"return",
"ERROR_WRONG_NUMBER_OF_ARGUMENTS",
"result",
"=",
"[",
"\"Poll: {}\\n\"",
".",
"format",
"(",
"args",
"[",
"0",
"]",
")",
"]",
"for",
"emoji",
",",
"answer",
"in",
"zip",
"(",
"POLL_EMOJIS",
",",
"args",
"[",
"1",
":",
"]",
")",
":",
"result",
".",
"append",
"(",
"\":{}: {}\\n\"",
".",
"format",
"(",
"emoji",
",",
"answer",
")",
")",
"# for this we are going to need to post the message to Slack via Web API in order to",
"# get the TS and add reactions",
"msg_posted",
"=",
"server",
".",
"slack",
".",
"post_message",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"\"\"",
".",
"join",
"(",
"result",
")",
",",
"as_user",
"=",
"server",
".",
"slack",
".",
"username",
")",
"ts",
"=",
"json",
".",
"loads",
"(",
"msg_posted",
")",
"[",
"\"ts\"",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"args",
")",
"-",
"1",
")",
":",
"server",
".",
"slack",
".",
"post_reaction",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"ts",
",",
"POLL_EMOJIS",
"[",
"i",
"]",
")"
] | Given a question and answers, present a poll | [
"Given",
"a",
"question",
"and",
"answers",
"present",
"a",
"poll"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/poll.py#L28-L50 | train |
llimllib/limbo | limbo/plugins/emoji.py | emoji_list | def emoji_list(server, n=1):
"""return a list of `n` random emoji"""
global EMOJI
if EMOJI is None:
EMOJI = EmojiCache(server)
return EMOJI.get(n) | python | def emoji_list(server, n=1):
"""return a list of `n` random emoji"""
global EMOJI
if EMOJI is None:
EMOJI = EmojiCache(server)
return EMOJI.get(n) | [
"def",
"emoji_list",
"(",
"server",
",",
"n",
"=",
"1",
")",
":",
"global",
"EMOJI",
"if",
"EMOJI",
"is",
"None",
":",
"EMOJI",
"=",
"EmojiCache",
"(",
"server",
")",
"return",
"EMOJI",
".",
"get",
"(",
"n",
")"
] | return a list of `n` random emoji | [
"return",
"a",
"list",
"of",
"n",
"random",
"emoji"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/emoji.py#L46-L51 | train |
llimllib/limbo | limbo/plugins/wiki.py | wiki | def wiki(searchterm):
"""return the top wiki search result for the term"""
searchterm = quote(searchterm)
url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
url = url.format(searchterm)
result = requests.get(url).json()
pages = result["query"]["search"]
# try to reject disambiguation pages
pages = [p for p in pages if 'may refer to' not in p["snippet"]]
if not pages:
return ""
page = quote(pages[0]["title"].encode("utf8"))
link = "http://en.wikipedia.org/wiki/{0}".format(page)
r = requests.get(
"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
format(page)).json()
soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
p = soup.find('p').get_text()
p = p[:8000]
return u"{0}\n{1}".format(p, link) | python | def wiki(searchterm):
"""return the top wiki search result for the term"""
searchterm = quote(searchterm)
url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
url = url.format(searchterm)
result = requests.get(url).json()
pages = result["query"]["search"]
# try to reject disambiguation pages
pages = [p for p in pages if 'may refer to' not in p["snippet"]]
if not pages:
return ""
page = quote(pages[0]["title"].encode("utf8"))
link = "http://en.wikipedia.org/wiki/{0}".format(page)
r = requests.get(
"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
format(page)).json()
soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
p = soup.find('p').get_text()
p = p[:8000]
return u"{0}\n{1}".format(p, link) | [
"def",
"wiki",
"(",
"searchterm",
")",
":",
"searchterm",
"=",
"quote",
"(",
"searchterm",
")",
"url",
"=",
"\"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json\"",
"url",
"=",
"url",
".",
"format",
"(",
"searchterm",
")",
"result",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"json",
"(",
")",
"pages",
"=",
"result",
"[",
"\"query\"",
"]",
"[",
"\"search\"",
"]",
"# try to reject disambiguation pages",
"pages",
"=",
"[",
"p",
"for",
"p",
"in",
"pages",
"if",
"'may refer to'",
"not",
"in",
"p",
"[",
"\"snippet\"",
"]",
"]",
"if",
"not",
"pages",
":",
"return",
"\"\"",
"page",
"=",
"quote",
"(",
"pages",
"[",
"0",
"]",
"[",
"\"title\"",
"]",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"link",
"=",
"\"http://en.wikipedia.org/wiki/{0}\"",
".",
"format",
"(",
"page",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"\"http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}\"",
".",
"format",
"(",
"page",
")",
")",
".",
"json",
"(",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"r",
"[",
"\"parse\"",
"]",
"[",
"\"text\"",
"]",
"[",
"\"*\"",
"]",
",",
"\"html5lib\"",
")",
"p",
"=",
"soup",
".",
"find",
"(",
"'p'",
")",
".",
"get_text",
"(",
")",
"p",
"=",
"p",
"[",
":",
"8000",
"]",
"return",
"u\"{0}\\n{1}\"",
".",
"format",
"(",
"p",
",",
"link",
")"
] | return the top wiki search result for the term | [
"return",
"the",
"top",
"wiki",
"search",
"result",
"for",
"the",
"term"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/wiki.py#L12-L39 | train |
llimllib/limbo | limbo/plugins/gif.py | gif | def gif(search, unsafe=False):
"""given a search string, return a gif URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
.format(searchb, safe)
# this is an old iphone user agent. Seems to make google return good results.
useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"
result = requests.get(searchurl, headers={"User-agent": useragent}).text
gifs = list(map(unescape, re.findall(r"var u='(.*?)'", result)))
shuffle(gifs)
if gifs:
return gifs[0]
return "" | python | def gif(search, unsafe=False):
"""given a search string, return a gif URL via google search"""
searchb = quote(search.encode("utf8"))
safe = "&safe=" if unsafe else "&safe=active"
searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" \
.format(searchb, safe)
# this is an old iphone user agent. Seems to make google return good results.
useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" \
" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"
result = requests.get(searchurl, headers={"User-agent": useragent}).text
gifs = list(map(unescape, re.findall(r"var u='(.*?)'", result)))
shuffle(gifs)
if gifs:
return gifs[0]
return "" | [
"def",
"gif",
"(",
"search",
",",
"unsafe",
"=",
"False",
")",
":",
"searchb",
"=",
"quote",
"(",
"search",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
"safe",
"=",
"\"&safe=\"",
"if",
"unsafe",
"else",
"\"&safe=active\"",
"searchurl",
"=",
"\"https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}\"",
".",
"format",
"(",
"searchb",
",",
"safe",
")",
"# this is an old iphone user agent. Seems to make google return good results.",
"useragent",
"=",
"\"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)\"",
"\" AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7\"",
"result",
"=",
"requests",
".",
"get",
"(",
"searchurl",
",",
"headers",
"=",
"{",
"\"User-agent\"",
":",
"useragent",
"}",
")",
".",
"text",
"gifs",
"=",
"list",
"(",
"map",
"(",
"unescape",
",",
"re",
".",
"findall",
"(",
"r\"var u='(.*?)'\"",
",",
"result",
")",
")",
")",
"shuffle",
"(",
"gifs",
")",
"if",
"gifs",
":",
"return",
"gifs",
"[",
"0",
"]",
"return",
"\"\""
] | given a search string, return a gif URL via google search | [
"given",
"a",
"search",
"string",
"return",
"a",
"gif",
"URL",
"via",
"google",
"search"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/gif.py#L19-L38 | train |
llimllib/limbo | limbo/plugins/gif.py | on_message | def on_message(msg, server):
"""handle a message and return an gif"""
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
}
server.slack.post_message(
msg['channel'],
'',
as_user=server.slack.username,
attachments=json.dumps([attachment])) | python | def on_message(msg, server):
"""handle a message and return an gif"""
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
}
server.slack.post_message(
msg['channel'],
'',
as_user=server.slack.username,
attachments=json.dumps([attachment])) | [
"def",
"on_message",
"(",
"msg",
",",
"server",
")",
":",
"text",
"=",
"msg",
".",
"get",
"(",
"\"text\"",
",",
"\"\"",
")",
"match",
"=",
"re",
".",
"findall",
"(",
"r\"!gif (.*)\"",
",",
"text",
")",
"if",
"not",
"match",
":",
"return",
"res",
"=",
"gif",
"(",
"match",
"[",
"0",
"]",
")",
"if",
"not",
"res",
":",
"return",
"attachment",
"=",
"{",
"\"fallback\"",
":",
"match",
"[",
"0",
"]",
",",
"\"title\"",
":",
"match",
"[",
"0",
"]",
",",
"\"title_link\"",
":",
"res",
",",
"\"image_url\"",
":",
"res",
"}",
"server",
".",
"slack",
".",
"post_message",
"(",
"msg",
"[",
"'channel'",
"]",
",",
"''",
",",
"as_user",
"=",
"server",
".",
"slack",
".",
"username",
",",
"attachments",
"=",
"json",
".",
"dumps",
"(",
"[",
"attachment",
"]",
")",
")"
] | handle a message and return an gif | [
"handle",
"a",
"message",
"and",
"return",
"an",
"gif"
] | f0980f20f733b670debcae454b167da32c57a044 | https://github.com/llimllib/limbo/blob/f0980f20f733b670debcae454b167da32c57a044/limbo/plugins/gif.py#L41-L62 | train |
btel/svg_utils | src/svgutils/transform.py | fromfile | def fromfile(fname):
"""Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content
"""
fig = SVGFigure()
with open(fname) as fid:
svg_file = etree.parse(fid)
fig.root = svg_file.getroot()
return fig | python | def fromfile(fname):
"""Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content
"""
fig = SVGFigure()
with open(fname) as fid:
svg_file = etree.parse(fid)
fig.root = svg_file.getroot()
return fig | [
"def",
"fromfile",
"(",
"fname",
")",
":",
"fig",
"=",
"SVGFigure",
"(",
")",
"with",
"open",
"(",
"fname",
")",
"as",
"fid",
":",
"svg_file",
"=",
"etree",
".",
"parse",
"(",
"fid",
")",
"fig",
".",
"root",
"=",
"svg_file",
".",
"getroot",
"(",
")",
"return",
"fig"
] | Open SVG figure from file.
Parameters
----------
fname : str
name of the SVG file
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the file content | [
"Open",
"SVG",
"figure",
"from",
"file",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L294-L312 | train |
btel/svg_utils | src/svgutils/transform.py | fromstring | def fromstring(text):
"""Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
"""
fig = SVGFigure()
svg = etree.fromstring(text.encode())
fig.root = svg
return fig | python | def fromstring(text):
"""Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
"""
fig = SVGFigure()
svg = etree.fromstring(text.encode())
fig.root = svg
return fig | [
"def",
"fromstring",
"(",
"text",
")",
":",
"fig",
"=",
"SVGFigure",
"(",
")",
"svg",
"=",
"etree",
".",
"fromstring",
"(",
"text",
".",
"encode",
"(",
")",
")",
"fig",
".",
"root",
"=",
"svg",
"return",
"fig"
] | Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content. | [
"Create",
"a",
"SVG",
"figure",
"from",
"a",
"string",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L315-L334 | train |
btel/svg_utils | src/svgutils/transform.py | from_mpl | def from_mpl(fig, savefig_kw=None):
"""Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...>
"""
fid = StringIO()
if savefig_kw is None:
savefig_kw = {}
try:
fig.savefig(fid, format='svg', **savefig_kw)
except ValueError:
raise(ValueError, "No matplotlib SVG backend")
fid.seek(0)
fig = fromstring(fid.read())
# workaround mpl units bug
w, h = fig.get_size()
fig.set_size((w.replace('pt', ''), h.replace('pt', '')))
return fig | python | def from_mpl(fig, savefig_kw=None):
"""Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...>
"""
fid = StringIO()
if savefig_kw is None:
savefig_kw = {}
try:
fig.savefig(fid, format='svg', **savefig_kw)
except ValueError:
raise(ValueError, "No matplotlib SVG backend")
fid.seek(0)
fig = fromstring(fid.read())
# workaround mpl units bug
w, h = fig.get_size()
fig.set_size((w.replace('pt', ''), h.replace('pt', '')))
return fig | [
"def",
"from_mpl",
"(",
"fig",
",",
"savefig_kw",
"=",
"None",
")",
":",
"fid",
"=",
"StringIO",
"(",
")",
"if",
"savefig_kw",
"is",
"None",
":",
"savefig_kw",
"=",
"{",
"}",
"try",
":",
"fig",
".",
"savefig",
"(",
"fid",
",",
"format",
"=",
"'svg'",
",",
"*",
"*",
"savefig_kw",
")",
"except",
"ValueError",
":",
"raise",
"(",
"ValueError",
",",
"\"No matplotlib SVG backend\"",
")",
"fid",
".",
"seek",
"(",
"0",
")",
"fig",
"=",
"fromstring",
"(",
"fid",
".",
"read",
"(",
")",
")",
"# workaround mpl units bug",
"w",
",",
"h",
"=",
"fig",
".",
"get_size",
"(",
")",
"fig",
".",
"set_size",
"(",
"(",
"w",
".",
"replace",
"(",
"'pt'",
",",
"''",
")",
",",
"h",
".",
"replace",
"(",
"'pt'",
",",
"''",
")",
")",
")",
"return",
"fig"
] | Create a SVG figure from a ``matplotlib`` figure.
Parameters
----------
fig : matplotlib.Figure instance
savefig_kw : dict
keyword arguments to be passed to matplotlib's
`savefig`
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
Examples
--------
If you want to overlay the figure on another SVG, you may want to pass
the `transparent` option:
>>> from svgutils import transform
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> line, = plt.plot([1,2])
>>> svgfig = transform.from_mpl(fig,
... savefig_kw=dict(transparent=True))
>>> svgfig.getroot()
<svgutils.transform.GroupElement object at ...> | [
"Create",
"a",
"SVG",
"figure",
"from",
"a",
"matplotlib",
"figure",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L337-L390 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.moveto | def moveto(self, x, y, scale=1):
"""Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1.
"""
self.root.set("transform", "translate(%s, %s) scale(%s) %s" %
(x, y, scale, self.root.get("transform") or '')) | python | def moveto(self, x, y, scale=1):
"""Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1.
"""
self.root.set("transform", "translate(%s, %s) scale(%s) %s" %
(x, y, scale, self.root.get("transform") or '')) | [
"def",
"moveto",
"(",
"self",
",",
"x",
",",
"y",
",",
"scale",
"=",
"1",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"translate(%s, %s) scale(%s) %s\"",
"%",
"(",
"x",
",",
"y",
",",
"scale",
",",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
")",
")"
] | Move and scale element.
Parameters
----------
x, y : float
displacement in x and y coordinates in user units ('px').
scale : float
scaling factor. To scale down scale < 1, scale up scale > 1.
For no scaling scale = 1. | [
"Move",
"and",
"scale",
"element",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L24-L36 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.rotate | def rotate(self, angle, x=0, y=0):
"""Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure)
"""
self.root.set("transform", "%s rotate(%f %f %f)" %
(self.root.get("transform") or '', angle, x, y)) | python | def rotate(self, angle, x=0, y=0):
"""Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure)
"""
self.root.set("transform", "%s rotate(%f %f %f)" %
(self.root.get("transform") or '', angle, x, y)) | [
"def",
"rotate",
"(",
"self",
",",
"angle",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s rotate(%f %f %f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"angle",
",",
"x",
",",
"y",
")",
")"
] | Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the figure) | [
"Rotate",
"element",
"by",
"given",
"angle",
"around",
"given",
"pivot",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L38-L50 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.skew | def skew(self, x=0, y=0):
"""Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted.
"""
if x is not 0:
self.skew_x(x)
if y is not 0:
self.skew_y(y)
return self | python | def skew(self, x=0, y=0):
"""Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted.
"""
if x is not 0:
self.skew_x(x)
if y is not 0:
self.skew_y(y)
return self | [
"def",
"skew",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"if",
"x",
"is",
"not",
"0",
":",
"self",
".",
"skew_x",
"(",
"x",
")",
"if",
"y",
"is",
"not",
"0",
":",
"self",
".",
"skew_y",
"(",
"y",
")",
"return",
"self"
] | Skew the element by x and y degrees
Convenience function which calls skew_x and skew_y
Parameters
----------
x,y : float, float
skew angle in degrees (default 0)
If an x/y angle is given as zero degrees, that transformation is omitted. | [
"Skew",
"the",
"element",
"by",
"x",
"and",
"y",
"degrees",
"Convenience",
"function",
"which",
"calls",
"skew_x",
"and",
"skew_y"
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L52-L68 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.skew_x | def skew_x(self, x):
"""Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees
"""
self.root.set("transform", "%s skewX(%f)" %
(self.root.get("transform") or '', x))
return self | python | def skew_x(self, x):
"""Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees
"""
self.root.set("transform", "%s skewX(%f)" %
(self.root.get("transform") or '', x))
return self | [
"def",
"skew_x",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewX(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"x",
")",
")",
"return",
"self"
] | Skew element along the x-axis by the given angle.
Parameters
----------
x : float
x-axis skew angle in degrees | [
"Skew",
"element",
"along",
"the",
"x",
"-",
"axis",
"by",
"the",
"given",
"angle",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L70-L80 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.skew_y | def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return self | python | def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return self | [
"def",
"skew_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewY(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"y",
")",
")",
"return",
"self"
] | Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees | [
"Skew",
"element",
"along",
"the",
"y",
"-",
"axis",
"by",
"the",
"given",
"angle",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L82-L92 | train |
btel/svg_utils | src/svgutils/transform.py | FigureElement.find_id | def find_id(self, element_id):
"""Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID."""
find = etree.XPath("//*[@id=$id]")
return FigureElement(find(self.root, id=element_id)[0]) | python | def find_id(self, element_id):
"""Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID."""
find = etree.XPath("//*[@id=$id]")
return FigureElement(find(self.root, id=element_id)[0]) | [
"def",
"find_id",
"(",
"self",
",",
"element_id",
")",
":",
"find",
"=",
"etree",
".",
"XPath",
"(",
"\"//*[@id=$id]\"",
")",
"return",
"FigureElement",
"(",
"find",
"(",
"self",
".",
"root",
",",
"id",
"=",
"element_id",
")",
"[",
"0",
"]",
")"
] | Find element by its id.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
FigureElement
one of the children element with the given ID. | [
"Find",
"element",
"by",
"its",
"id",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L122-L135 | train |
btel/svg_utils | src/svgutils/transform.py | SVGFigure.append | def append(self, element):
"""Append new element to the SVG figure"""
try:
self.root.append(element.root)
except AttributeError:
self.root.append(GroupElement(element).root) | python | def append(self, element):
"""Append new element to the SVG figure"""
try:
self.root.append(element.root)
except AttributeError:
self.root.append(GroupElement(element).root) | [
"def",
"append",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"self",
".",
"root",
".",
"append",
"(",
"element",
".",
"root",
")",
"except",
"AttributeError",
":",
"self",
".",
"root",
".",
"append",
"(",
"GroupElement",
"(",
"element",
")",
".",
"root",
")"
] | Append new element to the SVG figure | [
"Append",
"new",
"element",
"to",
"the",
"SVG",
"figure"
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L238-L243 | train |
btel/svg_utils | src/svgutils/transform.py | SVGFigure.getroot | def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class' in self.root.attrib:
attrib = {'class': self.root.attrib['class']}
else:
attrib = None
return GroupElement(self.root.getchildren(), attrib=attrib) | python | def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class' in self.root.attrib:
attrib = {'class': self.root.attrib['class']}
else:
attrib = None
return GroupElement(self.root.getchildren(), attrib=attrib) | [
"def",
"getroot",
"(",
"self",
")",
":",
"if",
"'class'",
"in",
"self",
".",
"root",
".",
"attrib",
":",
"attrib",
"=",
"{",
"'class'",
":",
"self",
".",
"root",
".",
"attrib",
"[",
"'class'",
"]",
"}",
"else",
":",
"attrib",
"=",
"None",
"return",
"GroupElement",
"(",
"self",
".",
"root",
".",
"getchildren",
"(",
")",
",",
"attrib",
"=",
"attrib",
")"
] | Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag. | [
"Return",
"the",
"root",
"element",
"of",
"the",
"figure",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L245-L260 | train |
btel/svg_utils | src/svgutils/transform.py | SVGFigure.to_str | def to_str(self):
"""
Returns a string of the SVG figure.
"""
return etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True) | python | def to_str(self):
"""
Returns a string of the SVG figure.
"""
return etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True) | [
"def",
"to_str",
"(",
"self",
")",
":",
"return",
"etree",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"xml_declaration",
"=",
"True",
",",
"standalone",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")"
] | Returns a string of the SVG figure. | [
"Returns",
"a",
"string",
"of",
"the",
"SVG",
"figure",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L262-L268 | train |
btel/svg_utils | src/svgutils/transform.py | SVGFigure.save | def save(self, fname):
"""Save figure to a file"""
out = etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
with open(fname, 'wb') as fid:
fid.write(out) | python | def save(self, fname):
"""Save figure to a file"""
out = etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True)
with open(fname, 'wb') as fid:
fid.write(out) | [
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"out",
"=",
"etree",
".",
"tostring",
"(",
"self",
".",
"root",
",",
"xml_declaration",
"=",
"True",
",",
"standalone",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"out",
")"
] | Save figure to a file | [
"Save",
"figure",
"to",
"a",
"file"
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L270-L276 | train |
btel/svg_utils | src/svgutils/transform.py | SVGFigure.set_size | def set_size(self, size):
"""Set figure size"""
w, h = size
self.root.set('width', w)
self.root.set('height', h) | python | def set_size(self, size):
"""Set figure size"""
w, h = size
self.root.set('width', w)
self.root.set('height', h) | [
"def",
"set_size",
"(",
"self",
",",
"size",
")",
":",
"w",
",",
"h",
"=",
"size",
"self",
".",
"root",
".",
"set",
"(",
"'width'",
",",
"w",
")",
"self",
".",
"root",
".",
"set",
"(",
"'height'",
",",
"h",
")"
] | Set figure size | [
"Set",
"figure",
"size"
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/transform.py#L287-L291 | train |
btel/svg_utils | src/svgutils/compose.py | Element.find_id | def find_id(self, element_id):
"""Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
"""
element = _transform.FigureElement.find_id(self, element_id)
return Element(element.root) | python | def find_id(self, element_id):
"""Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element
"""
element = _transform.FigureElement.find_id(self, element_id)
return Element(element.root) | [
"def",
"find_id",
"(",
"self",
",",
"element_id",
")",
":",
"element",
"=",
"_transform",
".",
"FigureElement",
".",
"find_id",
"(",
"self",
",",
"element_id",
")",
"return",
"Element",
"(",
"element",
".",
"root",
")"
] | Find a single element with the given ID.
Parameters
----------
element_id : str
ID of the element to find
Returns
-------
found element | [
"Find",
"a",
"single",
"element",
"with",
"the",
"given",
"ID",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L67-L80 | train |
btel/svg_utils | src/svgutils/compose.py | Element.find_ids | def find_ids(self, element_ids):
"""Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
"""
elements = [_transform.FigureElement.find_id(self, eid)
for eid in element_ids]
return Panel(*elements) | python | def find_ids(self, element_ids):
"""Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
"""
elements = [_transform.FigureElement.find_id(self, eid)
for eid in element_ids]
return Panel(*elements) | [
"def",
"find_ids",
"(",
"self",
",",
"element_ids",
")",
":",
"elements",
"=",
"[",
"_transform",
".",
"FigureElement",
".",
"find_id",
"(",
"self",
",",
"eid",
")",
"for",
"eid",
"in",
"element_ids",
"]",
"return",
"Panel",
"(",
"*",
"elements",
")"
] | Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements. | [
"Find",
"elements",
"with",
"given",
"IDs",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L82-L96 | train |
btel/svg_utils | src/svgutils/compose.py | Figure.save | def save(self, fname):
"""Save figure to SVG file.
Parameters
----------
fname : str
Full path to file.
"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
element.save(os.path.join(CONFIG['figure.save_path'], fname)) | python | def save(self, fname):
"""Save figure to SVG file.
Parameters
----------
fname : str
Full path to file.
"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
element.save(os.path.join(CONFIG['figure.save_path'], fname)) | [
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"element",
"=",
"_transform",
".",
"SVGFigure",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"element",
".",
"append",
"(",
"self",
")",
"element",
".",
"save",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CONFIG",
"[",
"'figure.save_path'",
"]",
",",
"fname",
")",
")"
] | Save figure to SVG file.
Parameters
----------
fname : str
Full path to file. | [
"Save",
"figure",
"to",
"SVG",
"file",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L292-L302 | train |
btel/svg_utils | src/svgutils/compose.py | Figure.tostr | def tostr(self):
"""Export SVG as a string"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
svgstr = element.to_str()
return svgstr | python | def tostr(self):
"""Export SVG as a string"""
element = _transform.SVGFigure(self.width, self.height)
element.append(self)
svgstr = element.to_str()
return svgstr | [
"def",
"tostr",
"(",
"self",
")",
":",
"element",
"=",
"_transform",
".",
"SVGFigure",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"element",
".",
"append",
"(",
"self",
")",
"svgstr",
"=",
"element",
".",
"to_str",
"(",
")",
"return",
"svgstr"
] | Export SVG as a string | [
"Export",
"SVG",
"as",
"a",
"string"
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L304-L309 | train |
btel/svg_utils | src/svgutils/compose.py | Figure.tile | def tile(self, ncols, nrows):
"""Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders.
"""
dx = (self.width/ncols).to('px').value
dy = (self.height/nrows).to('px').value
ix, iy = 0, 0
for el in self:
el.move(dx*ix, dy*iy)
ix += 1
if ix >= ncols:
ix = 0
iy += 1
if iy > nrows:
break
return self | python | def tile(self, ncols, nrows):
"""Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders.
"""
dx = (self.width/ncols).to('px').value
dy = (self.height/nrows).to('px').value
ix, iy = 0, 0
for el in self:
el.move(dx*ix, dy*iy)
ix += 1
if ix >= ncols:
ix = 0
iy += 1
if iy > nrows:
break
return self | [
"def",
"tile",
"(",
"self",
",",
"ncols",
",",
"nrows",
")",
":",
"dx",
"=",
"(",
"self",
".",
"width",
"/",
"ncols",
")",
".",
"to",
"(",
"'px'",
")",
".",
"value",
"dy",
"=",
"(",
"self",
".",
"height",
"/",
"nrows",
")",
".",
"to",
"(",
"'px'",
")",
".",
"value",
"ix",
",",
"iy",
"=",
"0",
",",
"0",
"for",
"el",
"in",
"self",
":",
"el",
".",
"move",
"(",
"dx",
"*",
"ix",
",",
"dy",
"*",
"iy",
")",
"ix",
"+=",
"1",
"if",
"ix",
">=",
"ncols",
":",
"ix",
"=",
"0",
"iy",
"+=",
"1",
"if",
"iy",
">",
"nrows",
":",
"break",
"return",
"self"
] | Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of columns and rows to arange the elements into.
Notes
-----
ncols * nrows must be larger or equal to number of
elements, otherwise some elements will go outside the figure borders. | [
"Automatically",
"tile",
"the",
"panels",
"of",
"the",
"figure",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L314-L342 | train |
btel/svg_utils | src/svgutils/compose.py | Unit.to | def to(self, unit):
"""Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
"""
u = Unit("0cm")
u.value = self.value/self.per_inch[self.unit]*self.per_inch[unit]
u.unit = unit
return u | python | def to(self, unit):
"""Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value.
"""
u = Unit("0cm")
u.value = self.value/self.per_inch[self.unit]*self.per_inch[unit]
u.unit = unit
return u | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"u",
"=",
"Unit",
"(",
"\"0cm\"",
")",
"u",
".",
"value",
"=",
"self",
".",
"value",
"/",
"self",
".",
"per_inch",
"[",
"self",
".",
"unit",
"]",
"*",
"self",
".",
"per_inch",
"[",
"unit",
"]",
"u",
".",
"unit",
"=",
"unit",
"return",
"u"
] | Convert to a given unit.
Parameters
----------
unit : str
Name of the unit to convert to.
Returns
-------
u : Unit
new Unit object with the requested unit and computed value. | [
"Convert",
"to",
"a",
"given",
"unit",
"."
] | ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3 | https://github.com/btel/svg_utils/blob/ee00726ebed1bd97fd496b15b6a8e7f233ebb5e3/src/svgutils/compose.py#L369-L385 | train |
Kozea/cairocffi | cairocffi/__init__.py | dlopen | def dlopen(ffi, *names):
"""Try various names for the same library, for different platforms."""
for name in names:
for lib_name in (name, 'lib' + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
return lib
except OSError:
pass
raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) | python | def dlopen(ffi, *names):
"""Try various names for the same library, for different platforms."""
for name in names:
for lib_name in (name, 'lib' + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
return lib
except OSError:
pass
raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) | [
"def",
"dlopen",
"(",
"ffi",
",",
"*",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"for",
"lib_name",
"in",
"(",
"name",
",",
"'lib'",
"+",
"name",
")",
":",
"try",
":",
"path",
"=",
"ctypes",
".",
"util",
".",
"find_library",
"(",
"lib_name",
")",
"lib",
"=",
"ffi",
".",
"dlopen",
"(",
"path",
"or",
"lib_name",
")",
"if",
"lib",
":",
"return",
"lib",
"except",
"OSError",
":",
"pass",
"raise",
"OSError",
"(",
"\"dlopen() failed to load a library: %s\"",
"%",
"' / '",
".",
"join",
"(",
"names",
")",
")"
] | Try various names for the same library, for different platforms. | [
"Try",
"various",
"names",
"for",
"the",
"same",
"library",
"for",
"different",
"platforms",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/__init__.py#L25-L36 | train |
Kozea/cairocffi | cairocffi/context.py | Context.set_source_rgba | def set_source_rgba(self, red, green, blue, alpha=1):
"""Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha)
self._check_status() | python | def set_source_rgba(self, red, green, blue, alpha=1):
"""Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha)
self._check_status() | [
"def",
"set_source_rgba",
"(",
"self",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"=",
"1",
")",
":",
"cairo",
".",
"cairo_set_source_rgba",
"(",
"self",
".",
"_pointer",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets the source pattern within this context to a solid color.
This color will then be used for any subsequent drawing operation
until a new source pattern is set.
The color and alpha components are
floating point numbers in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black,
(that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``).
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type red: float
:type green: float
:type blue: float
:type alpha: float | [
"Sets",
"the",
"source",
"pattern",
"within",
"this",
"context",
"to",
"a",
"solid",
"color",
".",
"This",
"color",
"will",
"then",
"be",
"used",
"for",
"any",
"subsequent",
"drawing",
"operation",
"until",
"a",
"new",
"source",
"pattern",
"is",
"set",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L306-L331 | train |
Kozea/cairocffi | cairocffi/context.py | Context.get_dash | def get_dash(self):
"""Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
"""
dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer))
offset = ffi.new('double *')
cairo.cairo_get_dash(self._pointer, dashes, offset)
self._check_status()
return list(dashes), offset[0] | python | def get_dash(self):
"""Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect.
"""
dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer))
offset = ffi.new('double *')
cairo.cairo_get_dash(self._pointer, dashes, offset)
self._check_status()
return list(dashes), offset[0] | [
"def",
"get_dash",
"(",
"self",
")",
":",
"dashes",
"=",
"ffi",
".",
"new",
"(",
"'double[]'",
",",
"cairo",
".",
"cairo_get_dash_count",
"(",
"self",
".",
"_pointer",
")",
")",
"offset",
"=",
"ffi",
".",
"new",
"(",
"'double *'",
")",
"cairo",
".",
"cairo_get_dash",
"(",
"self",
".",
"_pointer",
",",
"dashes",
",",
"offset",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"list",
"(",
"dashes",
")",
",",
"offset",
"[",
"0",
"]"
] | Return the current dash pattern.
:returns:
A ``(dashes, offset)`` tuple of a list and a float.
:obj:`dashes` is a list of floats,
empty if no dashing is in effect. | [
"Return",
"the",
"current",
"dash",
"pattern",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L472-L485 | train |
Kozea/cairocffi | cairocffi/context.py | Context.set_miter_limit | def set_miter_limit(self, limit):
"""Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
"""
cairo.cairo_set_miter_limit(self._pointer, limit)
self._check_status() | python | def set_miter_limit(self, limit):
"""Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float
"""
cairo.cairo_set_miter_limit(self._pointer, limit)
self._check_status() | [
"def",
"set_miter_limit",
"(",
"self",
",",
"limit",
")",
":",
"cairo",
".",
"cairo_set_miter_limit",
"(",
"self",
".",
"_pointer",
",",
"limit",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets the current miter limit within the cairo context.
If the current line join style is set to :obj:`MITER <LINE_JOIN_MITER>`
(see :meth:`set_line_join`),
the miter limit is used to determine
whether the lines should be joined with a bevel instead of a miter.
Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit,
the style is converted to a bevel.
As with the other stroke parameters,
the current line cap style is examined by
:meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`,
but does not have any effect during path construction.
The default miter limit value is 10.0,
which will convert joins with interior angles less than 11 degrees
to bevels instead of miters.
For reference,
a miter limit of 2.0 makes the miter cutoff at 60 degrees,
and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as:
``miter_limit = 1. / sin(angle / 2.)``
:param limit: The miter limit to set.
:type limit: float | [
"Sets",
"the",
"current",
"miter",
"limit",
"within",
"the",
"cairo",
"context",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L587-L618 | train |
Kozea/cairocffi | cairocffi/context.py | Context.get_current_point | def get_current_point(self):
"""Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
"""
# I’d prefer returning None if self.has_current_point() is False
# But keep (0, 0) for compat with pycairo.
xy = ffi.new('double[2]')
cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy) | python | def get_current_point(self):
"""Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point.
"""
# I’d prefer returning None if self.has_current_point() is False
# But keep (0, 0) for compat with pycairo.
xy = ffi.new('double[2]')
cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1)
self._check_status()
return tuple(xy) | [
"def",
"get_current_point",
"(",
"self",
")",
":",
"# I’d prefer returning None if self.has_current_point() is False",
"# But keep (0, 0) for compat with pycairo.",
"xy",
"=",
"ffi",
".",
"new",
"(",
"'double[2]'",
")",
"cairo",
".",
"cairo_get_current_point",
"(",
"self",
".",
"_pointer",
",",
"xy",
"+",
"0",
",",
"xy",
"+",
"1",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"tuple",
"(",
"xy",
")"
] | Return the current point of the current path,
which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate system.
If there is no defined current point
or if the context is in an error status,
``(0, 0)`` is returned.
It is possible to check this in advance with :meth:`has_current_point`.
Most path construction methods alter the current point.
See the following for details on how they affect the current point:
:meth:`new_path`,
:meth:`new_sub_path`,
:meth:`append_path`,
:meth:`close_path`,
:meth:`move_to`,
:meth:`line_to`,
:meth:`curve_to`,
:meth:`rel_move_to`,
:meth:`rel_line_to`,
:meth:`rel_curve_to`,
:meth:`arc`,
:meth:`arc_negative`,
:meth:`rectangle`,
:meth:`text_path`,
:meth:`glyph_path`,
:meth:`stroke_to_path`.
Some methods use and alter the current point
but do not otherwise change current path:
:meth:`show_text`,
:meth:`show_glyphs`,
:meth:`show_text_glyphs`.
Some methods unset the current path and as a result, current point:
:meth:`fill`,
:meth:`stroke`.
:returns:
A ``(x, y)`` tuple of floats, the coordinates of the current point. | [
"Return",
"the",
"current",
"point",
"of",
"the",
"current",
"path",
"which",
"is",
"conceptually",
"the",
"final",
"point",
"reached",
"by",
"the",
"path",
"so",
"far",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L850-L898 | train |
Kozea/cairocffi | cairocffi/context.py | Context.copy_path | def copy_path(self):
"""Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)
"""
path = cairo.cairo_copy_path(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result | python | def copy_path(self):
"""Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple)
"""
path = cairo.cairo_copy_path(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result | [
"def",
"copy_path",
"(",
"self",
")",
":",
"path",
"=",
"cairo",
".",
"cairo_copy_path",
"(",
"self",
".",
"_pointer",
")",
"result",
"=",
"list",
"(",
"_iter_path",
"(",
"path",
")",
")",
"cairo",
".",
"cairo_path_destroy",
"(",
"path",
")",
"return",
"result"
] | Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ``(x, y)``
* :obj:`LINE_TO <PATH_LINE_TO>`: 1 point ``(x, y)``
* :obj:`CURVE_TO <PATH_CURVE_TO>`: 3 points
``(x1, y1, x2, y2, x3, y3)``
* :obj:`CLOSE_PATH <PATH_CLOSE_PATH>` 0 points ``()`` (empty tuple) | [
"Return",
"a",
"copy",
"of",
"the",
"current",
"path",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1245-L1264 | train |
Kozea/cairocffi | cairocffi/context.py | Context.copy_path_flat | def copy_path_flat(self):
"""Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure.
"""
path = cairo.cairo_copy_path_flat(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result | python | def copy_path_flat(self):
"""Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure.
"""
path = cairo.cairo_copy_path_flat(self._pointer)
result = list(_iter_path(path))
cairo.cairo_path_destroy(path)
return result | [
"def",
"copy_path_flat",
"(",
"self",
")",
":",
"path",
"=",
"cairo",
".",
"cairo_copy_path_flat",
"(",
"self",
".",
"_pointer",
")",
"result",
"=",
"list",
"(",
"_iter_path",
"(",
"path",
")",
")",
"cairo",
".",
"cairo_path_destroy",
"(",
"path",
")",
"return",
"result"
] | Return a flattened copy of the current path
This method is like :meth:`copy_path`
except that any curves in the path will be approximated
with piecewise-linear approximations,
(accurate to within the current tolerance value,
see :meth:`set_tolerance`).
That is,
the result is guaranteed to not have any elements
of type :obj:`CURVE_TO <PATH_CURVE_TO>`
which will instead be replaced by
a series of :obj:`LINE_TO <PATH_LINE_TO>` elements.
:returns:
A list of ``(path_operation, coordinates)`` tuples.
See :meth:`copy_path` for the data structure. | [
"Return",
"a",
"flattened",
"copy",
"of",
"the",
"current",
"path"
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1266-L1288 | train |
Kozea/cairocffi | cairocffi/context.py | Context.clip_extents | def clip_extents(self):
"""Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
"""
extents = ffi.new('double[4]')
cairo.cairo_clip_extents(
self._pointer, extents + 0, extents + 1, extents + 2, extents + 3)
self._check_status()
return tuple(extents) | python | def clip_extents(self):
"""Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
"""
extents = ffi.new('double[4]')
cairo.cairo_clip_extents(
self._pointer, extents + 0, extents + 1, extents + 2, extents + 3)
self._check_status()
return tuple(extents) | [
"def",
"clip_extents",
"(",
"self",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'double[4]'",
")",
"cairo",
".",
"cairo_clip_extents",
"(",
"self",
".",
"_pointer",
",",
"extents",
"+",
"0",
",",
"extents",
"+",
"1",
",",
"extents",
"+",
"2",
",",
"extents",
"+",
"3",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"tuple",
"(",
"extents",
")"
] | Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively. | [
"Computes",
"a",
"bounding",
"box",
"in",
"user",
"coordinates",
"covering",
"the",
"area",
"inside",
"the",
"current",
"clip",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1629-L1643 | train |
Kozea/cairocffi | cairocffi/context.py | Context.copy_clip_rectangle_list | def copy_clip_rectangle_list(self):
"""Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles.
"""
rectangle_list = cairo.cairo_copy_clip_rectangle_list(self._pointer)
_check_status(rectangle_list.status)
rectangles = rectangle_list.rectangles
result = []
for i in range(rectangle_list.num_rectangles):
rect = rectangles[i]
result.append((rect.x, rect.y, rect.width, rect.height))
cairo.cairo_rectangle_list_destroy(rectangle_list)
return result | python | def copy_clip_rectangle_list(self):
"""Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles.
"""
rectangle_list = cairo.cairo_copy_clip_rectangle_list(self._pointer)
_check_status(rectangle_list.status)
rectangles = rectangle_list.rectangles
result = []
for i in range(rectangle_list.num_rectangles):
rect = rectangles[i]
result.append((rect.x, rect.y, rect.width, rect.height))
cairo.cairo_rectangle_list_destroy(rectangle_list)
return result | [
"def",
"copy_clip_rectangle_list",
"(",
"self",
")",
":",
"rectangle_list",
"=",
"cairo",
".",
"cairo_copy_clip_rectangle_list",
"(",
"self",
".",
"_pointer",
")",
"_check_status",
"(",
"rectangle_list",
".",
"status",
")",
"rectangles",
"=",
"rectangle_list",
".",
"rectangles",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"rectangle_list",
".",
"num_rectangles",
")",
":",
"rect",
"=",
"rectangles",
"[",
"i",
"]",
"result",
".",
"append",
"(",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
")",
"cairo",
".",
"cairo_rectangle_list_destroy",
"(",
"rectangle_list",
")",
"return",
"result"
] | Return the current clip region as a list of rectangles
in user coordinates.
:return:
A list of rectangles,
as ``(x, y, width, height)`` tuples of floats.
:raises:
:exc:`CairoError`
if the clip region cannot be represented as a list
of user-space rectangles. | [
"Return",
"the",
"current",
"clip",
"region",
"as",
"a",
"list",
"of",
"rectangles",
"in",
"user",
"coordinates",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1645-L1666 | train |
Kozea/cairocffi | cairocffi/context.py | Context.select_font_face | def select_font_face(self, family='', slant=constants.FONT_SLANT_NORMAL,
weight=constants.FONT_WEIGHT_NORMAL):
"""Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`.
"""
cairo.cairo_select_font_face(
self._pointer, _encode_string(family), slant, weight)
self._check_status() | python | def select_font_face(self, family='', slant=constants.FONT_SLANT_NORMAL,
weight=constants.FONT_WEIGHT_NORMAL):
"""Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`.
"""
cairo.cairo_select_font_face(
self._pointer, _encode_string(family), slant, weight)
self._check_status() | [
"def",
"select_font_face",
"(",
"self",
",",
"family",
"=",
"''",
",",
"slant",
"=",
"constants",
".",
"FONT_SLANT_NORMAL",
",",
"weight",
"=",
"constants",
".",
"FONT_WEIGHT_NORMAL",
")",
":",
"cairo",
".",
"cairo_select_font_face",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"family",
")",
",",
"slant",
",",
"weight",
")",
"self",
".",
"_check_status",
"(",
")"
] | Selects a family and style of font from a simplified description
as a family name, slant and weight.
.. note::
The :meth:`select_font_face` method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details.
Cairo provides no operation to list available family names
on the system (this is a "toy", remember),
but the standard CSS2 generic family names,
(``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``,
``"monospace"``),
are likely to work as expected.
If family starts with the string ``"cairo:"``,
or if no native font backends are compiled in,
cairo will use an internal font family.
The internal font family recognizes many modifiers
in the family string,
most notably, it recognizes the string ``"monospace"``.
That is, the family name ``"cairo:monospace"``
will use the monospace version of the internal font family.
If text is drawn without a call to :meth:`select_font_face`,
(nor :meth:`set_font_face` nor :meth:`set_scaled_font`),
the default family is platform-specific,
but is essentially ``"sans-serif"``.
Default slant is :obj:`NORMAL <FONT_SLANT_NORMAL>`,
and default weight is :obj:`NORMAL <FONT_WEIGHT_NORMAL>`.
This method is equivalent to a call to :class:`ToyFontFace`
followed by :meth:`set_font_face`. | [
"Selects",
"a",
"family",
"and",
"style",
"of",
"font",
"from",
"a",
"simplified",
"description",
"as",
"a",
"family",
"name",
"slant",
"and",
"weight",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1709-L1752 | train |
Kozea/cairocffi | cairocffi/context.py | Context.get_font_face | def get_font_face(self):
"""Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object.
"""
return FontFace._from_pointer(
cairo.cairo_get_font_face(self._pointer), incref=True) | python | def get_font_face(self):
"""Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object.
"""
return FontFace._from_pointer(
cairo.cairo_get_font_face(self._pointer), incref=True) | [
"def",
"get_font_face",
"(",
"self",
")",
":",
"return",
"FontFace",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_get_font_face",
"(",
"self",
".",
"_pointer",
")",
",",
"incref",
"=",
"True",
")"
] | Return the current font face.
:param font_face:
A new :class:`FontFace` object
wrapping an existing cairo object. | [
"Return",
"the",
"current",
"font",
"face",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1766-L1775 | train |
Kozea/cairocffi | cairocffi/context.py | Context.get_scaled_font | def get_scaled_font(self):
"""Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object.
"""
return ScaledFont._from_pointer(
cairo.cairo_get_scaled_font(self._pointer), incref=True) | python | def get_scaled_font(self):
"""Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object.
"""
return ScaledFont._from_pointer(
cairo.cairo_get_scaled_font(self._pointer), incref=True) | [
"def",
"get_scaled_font",
"(",
"self",
")",
":",
"return",
"ScaledFont",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_get_scaled_font",
"(",
"self",
".",
"_pointer",
")",
",",
"incref",
"=",
"True",
")"
] | Return the current scaled font.
:return:
A new :class:`ScaledFont` object,
wrapping an existing cairo object. | [
"Return",
"the",
"current",
"scaled",
"font",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1865-L1874 | train |
Kozea/cairocffi | cairocffi/context.py | Context.font_extents | def font_extents(self):
"""Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.)
"""
extents = ffi.new('cairo_font_extents_t *')
cairo.cairo_font_extents(self._pointer, extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.ascent, extents.descent, extents.height,
extents.max_x_advance, extents.max_y_advance) | python | def font_extents(self):
"""Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.)
"""
extents = ffi.new('cairo_font_extents_t *')
cairo.cairo_font_extents(self._pointer, extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.ascent, extents.descent, extents.height,
extents.max_x_advance, extents.max_y_advance) | [
"def",
"font_extents",
"(",
"self",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_font_extents_t *'",
")",
"cairo",
".",
"cairo_font_extents",
"(",
"self",
".",
"_pointer",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"# returning extents as is would be a nice API,",
"# but return a tuple for compat with pycairo.",
"return",
"(",
"extents",
".",
"ascent",
",",
"extents",
".",
"descent",
",",
"extents",
".",
"height",
",",
"extents",
".",
"max_x_advance",
",",
"extents",
".",
"max_y_advance",
")"
] | Return the extents of the currently selected font.
Values are given in the current user-space coordinate system.
Because font metrics are in user-space coordinates, they are mostly,
but not entirely, independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:returns:
A ``(ascent, descent, height, max_x_advance, max_y_advance)``
tuple of floats.
:obj:`ascent`
The distance that the font extends above the baseline.
Note that this is not always exactly equal to
the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements above it.
:obj:`descent`
The distance that the font extends below the baseline.
This value is positive for typical fonts
that include portions below the baseline.
Note that this is not always exactly equal
to the maximum of the extents of all the glyphs in the font,
but rather is picked to express the font designer's intent
as to how the font should align with elements below it.
:obj:`height`
The recommended vertical distance between baselines
when setting consecutive lines of text with the font.
This is greater than ``ascent + descent``
by a quantity known as the line spacing or external leading.
When space is at a premium, most fonts can be set
with only a distance of ``ascent + descent`` between lines.
:obj:`max_x_advance`
The maximum distance in the X direction
that the origin is advanced for any glyph in the font.
:obj:`max_y_advance`
The maximum distance in the Y direction
that the origin is advanced for any glyph in the font.
This will be zero for normal fonts used for horizontal writing.
(The scripts of East Asia are sometimes written vertically.) | [
"Return",
"the",
"extents",
"of",
"the",
"currently",
"selected",
"font",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1876-L1933 | train |
Kozea/cairocffi | cairocffi/context.py | Context.text_extents | def text_extents(self, text):
"""Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages.
"""
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_text_extents(self._pointer, _encode_string(text), extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance) | python | def text_extents(self, text):
"""Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages.
"""
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_text_extents(self._pointer, _encode_string(text), extents)
self._check_status()
# returning extents as is would be a nice API,
# but return a tuple for compat with pycairo.
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance) | [
"def",
"text_extents",
"(",
"self",
",",
"text",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_extents_t *'",
")",
"cairo",
".",
"cairo_text_extents",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"text",
")",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"# returning extents as is would be a nice API,",
"# but return a tuple for compat with pycairo.",
"return",
"(",
"extents",
".",
"x_bearing",
",",
"extents",
".",
"y_bearing",
",",
"extents",
".",
"width",
",",
"extents",
".",
"height",
",",
"extents",
".",
"x_advance",
",",
"extents",
".",
"y_advance",
")"
] | Returns the extents for a string of text.
The extents describe a user-space rectangle
that encloses the "inked" portion of the text,
(as it would be drawn by :meth:`show_text`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_text`.
Note that whitespace characters do not directly contribute
to the size of the rectangle (:obj:`width` and :obj:`height`).
They do contribute indirectly by changing the position
of non-whitespace characters.
In particular, trailing whitespace characters are likely
to not affect the size of the rectangle,
though they will affect the x_advance and y_advance values.
Because text extents are in user-space coordinates,
they are mostly, but not entirely,
independent of the current transformation matrix.
If you call :meth:`context.scale(2) <scale>`,
text will be drawn twice as big,
but the reported text extents will not be doubled.
They will change slightly due to hinting
(so you can't assume that metrics are independent
of the transformation matrix),
but otherwise will remain unchanged.
:param text: The text to measure, as an Unicode or UTF-8 string.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
:obj:`x_bearing`
The horizontal distance
from the origin to the leftmost part of the glyphs as drawn.
Positive if the glyphs lie entirely to the right of the origin.
:obj:`y_bearing`
The vertical distance
from the origin to the topmost part of the glyphs as drawn.
Positive only if the glyphs lie completely below the origin;
will usually be negative.
:obj:`width`
Width of the glyphs as drawn.
:obj:`height`
Height of the glyphs as drawn.
:obj:`x_advance`
Distance to advance in the X direction
after drawing these glyphs.
:obj:`y_advance`
Distance to advance in the Y direction
after drawing these glyphs.
Will typically be zero except for vertical text layout
as found in East-Asian languages. | [
"Returns",
"the",
"extents",
"for",
"a",
"string",
"of",
"text",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1939-L2009 | train |
Kozea/cairocffi | cairocffi/context.py | Context.glyph_extents | def glyph_extents(self, glyphs):
"""Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details.
"""
glyphs = ffi.new('cairo_glyph_t[]', glyphs)
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_glyph_extents(
self._pointer, glyphs, len(glyphs), extents)
self._check_status()
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance) | python | def glyph_extents(self, glyphs):
"""Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details.
"""
glyphs = ffi.new('cairo_glyph_t[]', glyphs)
extents = ffi.new('cairo_text_extents_t *')
cairo.cairo_glyph_extents(
self._pointer, glyphs, len(glyphs), extents)
self._check_status()
return (
extents.x_bearing, extents.y_bearing,
extents.width, extents.height,
extents.x_advance, extents.y_advance) | [
"def",
"glyph_extents",
"(",
"self",
",",
"glyphs",
")",
":",
"glyphs",
"=",
"ffi",
".",
"new",
"(",
"'cairo_glyph_t[]'",
",",
"glyphs",
")",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_extents_t *'",
")",
"cairo",
".",
"cairo_glyph_extents",
"(",
"self",
".",
"_pointer",
",",
"glyphs",
",",
"len",
"(",
"glyphs",
")",
",",
"extents",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"(",
"extents",
".",
"x_bearing",
",",
"extents",
".",
"y_bearing",
",",
"extents",
".",
"width",
",",
"extents",
".",
"height",
",",
"extents",
".",
"x_advance",
",",
"extents",
".",
"y_advance",
")"
] | Returns the extents for a list of glyphs.
The extents describe a user-space rectangle
that encloses the "inked" portion of the glyphs,
(as it would be drawn by :meth:`show_glyphs`).
Additionally, the :obj:`x_advance` and :obj:`y_advance` values
indicate the amount by which the current point would be advanced
by :meth:`show_glyphs`.
:param glyphs:
A list of glyphs.
See :meth:`show_text_glyphs` for the data structure.
:returns:
A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)``
tuple of floats.
See :meth:`text_extents` for details. | [
"Returns",
"the",
"extents",
"for",
"a",
"list",
"of",
"glyphs",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L2011-L2038 | train |
Kozea/cairocffi | cairocffi/context.py | Context.tag_begin | def tag_begin(self, tag_name, attributes=None):
"""Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Values may be boolean (true/false or 1/0), integer, float, string, or
an array.
String values are enclosed in single quotes ('). Single quotes and
backslashes inside the string should be escaped with a backslash.
Boolean values may be set to true by only specifying the key. eg the
attribute string "key" is the equivalent to "key=true".
Arrays are enclosed in '[]'. eg "rect=[1.2 4.3 2.0 3.0]".
If no attributes are required, ``attributes`` can be omitted, an empty
string or None.
See cairo's Tags and Links Description for the list of tags and
attributes.
Invalid nesting of tags or invalid attributes will cause the context to
shutdown with a status of ``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_end`.
:param tag_name: tag name
:param attributes: tag attributes
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if attributes is None:
attributes = ''
cairo.cairo_tag_begin(
self._pointer, _encode_string(tag_name),
_encode_string(attributes))
self._check_status() | python | def tag_begin(self, tag_name, attributes=None):
"""Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Values may be boolean (true/false or 1/0), integer, float, string, or
an array.
String values are enclosed in single quotes ('). Single quotes and
backslashes inside the string should be escaped with a backslash.
Boolean values may be set to true by only specifying the key. eg the
attribute string "key" is the equivalent to "key=true".
Arrays are enclosed in '[]'. eg "rect=[1.2 4.3 2.0 3.0]".
If no attributes are required, ``attributes`` can be omitted, an empty
string or None.
See cairo's Tags and Links Description for the list of tags and
attributes.
Invalid nesting of tags or invalid attributes will cause the context to
shutdown with a status of ``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_end`.
:param tag_name: tag name
:param attributes: tag attributes
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if attributes is None:
attributes = ''
cairo.cairo_tag_begin(
self._pointer, _encode_string(tag_name),
_encode_string(attributes))
self._check_status() | [
"def",
"tag_begin",
"(",
"self",
",",
"tag_name",
",",
"attributes",
"=",
"None",
")",
":",
"if",
"attributes",
"is",
"None",
":",
"attributes",
"=",
"''",
"cairo",
".",
"cairo_tag_begin",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"tag_name",
")",
",",
"_encode_string",
"(",
"attributes",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | Marks the beginning of the ``tag_name`` structure.
Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...".
Values may be boolean (true/false or 1/0), integer, float, string, or
an array.
String values are enclosed in single quotes ('). Single quotes and
backslashes inside the string should be escaped with a backslash.
Boolean values may be set to true by only specifying the key. eg the
attribute string "key" is the equivalent to "key=true".
Arrays are enclosed in '[]'. eg "rect=[1.2 4.3 2.0 3.0]".
If no attributes are required, ``attributes`` can be omitted, an empty
string or None.
See cairo's Tags and Links Description for the list of tags and
attributes.
Invalid nesting of tags or invalid attributes will cause the context to
shutdown with a status of ``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_end`.
:param tag_name: tag name
:param attributes: tag attributes
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Marks",
"the",
"beginning",
"of",
"the",
"tag_name",
"structure",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L2198-L2240 | train |
Kozea/cairocffi | cairocffi/context.py | Context.tag_end | def tag_end(self, tag_name):
"""Marks the end of the ``tag_name`` structure.
Invalid nesting of tags will cause @cr to shutdown with a status of
``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_begin`.
:param tag_name: tag name
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_tag_end(self._pointer, _encode_string(tag_name))
self._check_status() | python | def tag_end(self, tag_name):
"""Marks the end of the ``tag_name`` structure.
Invalid nesting of tags will cause @cr to shutdown with a status of
``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_begin`.
:param tag_name: tag name
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_tag_end(self._pointer, _encode_string(tag_name))
self._check_status() | [
"def",
"tag_end",
"(",
"self",
",",
"tag_name",
")",
":",
"cairo",
".",
"cairo_tag_end",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"tag_name",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | Marks the end of the ``tag_name`` structure.
Invalid nesting of tags will cause @cr to shutdown with a status of
``CAIRO_STATUS_TAG_ERROR``.
See :meth:`tag_begin`.
:param tag_name: tag name
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Marks",
"the",
"end",
"of",
"the",
"tag_name",
"structure",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L2242-L2258 | train |
Kozea/cairocffi | cairocffi/surfaces.py | _make_read_func | def _make_read_func(file_obj):
"""Return a CFFI callback that reads from a file-like object."""
@ffi.callback("cairo_read_func_t", error=constants.STATUS_READ_ERROR)
def read_func(_closure, data, length):
string = file_obj.read(length)
if len(string) < length: # EOF too early
return constants.STATUS_READ_ERROR
ffi.buffer(data, length)[:len(string)] = string
return constants.STATUS_SUCCESS
return read_func | python | def _make_read_func(file_obj):
"""Return a CFFI callback that reads from a file-like object."""
@ffi.callback("cairo_read_func_t", error=constants.STATUS_READ_ERROR)
def read_func(_closure, data, length):
string = file_obj.read(length)
if len(string) < length: # EOF too early
return constants.STATUS_READ_ERROR
ffi.buffer(data, length)[:len(string)] = string
return constants.STATUS_SUCCESS
return read_func | [
"def",
"_make_read_func",
"(",
"file_obj",
")",
":",
"@",
"ffi",
".",
"callback",
"(",
"\"cairo_read_func_t\"",
",",
"error",
"=",
"constants",
".",
"STATUS_READ_ERROR",
")",
"def",
"read_func",
"(",
"_closure",
",",
"data",
",",
"length",
")",
":",
"string",
"=",
"file_obj",
".",
"read",
"(",
"length",
")",
"if",
"len",
"(",
"string",
")",
"<",
"length",
":",
"# EOF too early",
"return",
"constants",
".",
"STATUS_READ_ERROR",
"ffi",
".",
"buffer",
"(",
"data",
",",
"length",
")",
"[",
":",
"len",
"(",
"string",
")",
"]",
"=",
"string",
"return",
"constants",
".",
"STATUS_SUCCESS",
"return",
"read_func"
] | Return a CFFI callback that reads from a file-like object. | [
"Return",
"a",
"CFFI",
"callback",
"that",
"reads",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L24-L33 | train |
Kozea/cairocffi | cairocffi/surfaces.py | _make_write_func | def _make_write_func(file_obj):
"""Return a CFFI callback that writes to a file-like object."""
if file_obj is None:
return ffi.NULL
@ffi.callback("cairo_write_func_t", error=constants.STATUS_WRITE_ERROR)
def write_func(_closure, data, length):
file_obj.write(ffi.buffer(data, length))
return constants.STATUS_SUCCESS
return write_func | python | def _make_write_func(file_obj):
"""Return a CFFI callback that writes to a file-like object."""
if file_obj is None:
return ffi.NULL
@ffi.callback("cairo_write_func_t", error=constants.STATUS_WRITE_ERROR)
def write_func(_closure, data, length):
file_obj.write(ffi.buffer(data, length))
return constants.STATUS_SUCCESS
return write_func | [
"def",
"_make_write_func",
"(",
"file_obj",
")",
":",
"if",
"file_obj",
"is",
"None",
":",
"return",
"ffi",
".",
"NULL",
"@",
"ffi",
".",
"callback",
"(",
"\"cairo_write_func_t\"",
",",
"error",
"=",
"constants",
".",
"STATUS_WRITE_ERROR",
")",
"def",
"write_func",
"(",
"_closure",
",",
"data",
",",
"length",
")",
":",
"file_obj",
".",
"write",
"(",
"ffi",
".",
"buffer",
"(",
"data",
",",
"length",
")",
")",
"return",
"constants",
".",
"STATUS_SUCCESS",
"return",
"write_func"
] | Return a CFFI callback that writes to a file-like object. | [
"Return",
"a",
"CFFI",
"callback",
"that",
"writes",
"to",
"a",
"file",
"-",
"like",
"object",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L36-L45 | train |
Kozea/cairocffi | cairocffi/surfaces.py | _encode_filename | def _encode_filename(filename): # pragma: no cover
"""Return a byte string suitable for a filename.
Unicode is encoded using an encoding adapted to what both cairo and the
filesystem want.
"""
# Don't replace unknown characters as '?' is forbidden in Windows filenames
errors = 'ignore' if os.name == 'nt' else 'replace'
if not isinstance(filename, bytes):
if os.name == 'nt' and cairo.cairo_version() >= 11510:
# Since 1.15.10, cairo uses utf-8 filenames on Windows
filename = filename.encode('utf-8', errors=errors)
else:
try:
filename = filename.encode(sys.getfilesystemencoding())
except UnicodeEncodeError:
# Use plain ASCII filenames as fallback
filename = filename.encode('ascii', errors=errors)
# TODO: avoid characters forbidden in filenames?
return ffi.new('char[]', filename) | python | def _encode_filename(filename): # pragma: no cover
"""Return a byte string suitable for a filename.
Unicode is encoded using an encoding adapted to what both cairo and the
filesystem want.
"""
# Don't replace unknown characters as '?' is forbidden in Windows filenames
errors = 'ignore' if os.name == 'nt' else 'replace'
if not isinstance(filename, bytes):
if os.name == 'nt' and cairo.cairo_version() >= 11510:
# Since 1.15.10, cairo uses utf-8 filenames on Windows
filename = filename.encode('utf-8', errors=errors)
else:
try:
filename = filename.encode(sys.getfilesystemencoding())
except UnicodeEncodeError:
# Use plain ASCII filenames as fallback
filename = filename.encode('ascii', errors=errors)
# TODO: avoid characters forbidden in filenames?
return ffi.new('char[]', filename) | [
"def",
"_encode_filename",
"(",
"filename",
")",
":",
"# pragma: no cover",
"# Don't replace unknown characters as '?' is forbidden in Windows filenames",
"errors",
"=",
"'ignore'",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"'replace'",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"bytes",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"cairo",
".",
"cairo_version",
"(",
")",
">=",
"11510",
":",
"# Since 1.15.10, cairo uses utf-8 filenames on Windows",
"filename",
"=",
"filename",
".",
"encode",
"(",
"'utf-8'",
",",
"errors",
"=",
"errors",
")",
"else",
":",
"try",
":",
"filename",
"=",
"filename",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
"except",
"UnicodeEncodeError",
":",
"# Use plain ASCII filenames as fallback",
"filename",
"=",
"filename",
".",
"encode",
"(",
"'ascii'",
",",
"errors",
"=",
"errors",
")",
"# TODO: avoid characters forbidden in filenames?",
"return",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"filename",
")"
] | Return a byte string suitable for a filename.
Unicode is encoded using an encoding adapted to what both cairo and the
filesystem want. | [
"Return",
"a",
"byte",
"string",
"suitable",
"for",
"a",
"filename",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L48-L70 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.create_similar_image | def create_similar_image(self, content, width, height):
"""
Create a new image surface that is as compatible as possible
for uploading to and the use in conjunction with this surface.
However, this surface can still be used like any normal image surface.
Initially the surface contents are all 0
(transparent if contents have transparency, black otherwise.)
Use :meth:`create_similar` if you don't need an image surface.
:param format: the :ref:`FORMAT` string for the new surface
:param width: width of the new surface, (in device-space units)
:param height: height of the new surface (in device-space units)
:type format: str
:type width: int
:type height: int
:returns: A new :class:`ImageSurface` instance.
"""
return Surface._from_pointer(
cairo.cairo_surface_create_similar_image(
self._pointer, content, width, height),
incref=False) | python | def create_similar_image(self, content, width, height):
"""
Create a new image surface that is as compatible as possible
for uploading to and the use in conjunction with this surface.
However, this surface can still be used like any normal image surface.
Initially the surface contents are all 0
(transparent if contents have transparency, black otherwise.)
Use :meth:`create_similar` if you don't need an image surface.
:param format: the :ref:`FORMAT` string for the new surface
:param width: width of the new surface, (in device-space units)
:param height: height of the new surface (in device-space units)
:type format: str
:type width: int
:type height: int
:returns: A new :class:`ImageSurface` instance.
"""
return Surface._from_pointer(
cairo.cairo_surface_create_similar_image(
self._pointer, content, width, height),
incref=False) | [
"def",
"create_similar_image",
"(",
"self",
",",
"content",
",",
"width",
",",
"height",
")",
":",
"return",
"Surface",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_surface_create_similar_image",
"(",
"self",
".",
"_pointer",
",",
"content",
",",
"width",
",",
"height",
")",
",",
"incref",
"=",
"False",
")"
] | Create a new image surface that is as compatible as possible
for uploading to and the use in conjunction with this surface.
However, this surface can still be used like any normal image surface.
Initially the surface contents are all 0
(transparent if contents have transparency, black otherwise.)
Use :meth:`create_similar` if you don't need an image surface.
:param format: the :ref:`FORMAT` string for the new surface
:param width: width of the new surface, (in device-space units)
:param height: height of the new surface (in device-space units)
:type format: str
:type width: int
:type height: int
:returns: A new :class:`ImageSurface` instance. | [
"Create",
"a",
"new",
"image",
"surface",
"that",
"is",
"as",
"compatible",
"as",
"possible",
"for",
"uploading",
"to",
"and",
"the",
"use",
"in",
"conjunction",
"with",
"this",
"surface",
".",
"However",
"this",
"surface",
"can",
"still",
"be",
"used",
"like",
"any",
"normal",
"image",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L209-L232 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.create_for_rectangle | def create_for_rectangle(self, x, y, width, height):
"""
Create a new surface that is a rectangle within this surface.
All operations drawn to this surface are then clipped and translated
onto the target surface.
Nothing drawn via this sub-surface outside of its bounds
is drawn onto the target surface,
making this a useful method for passing constrained child surfaces
to library routines that draw directly onto the parent surface,
i.e. with no further backend allocations,
double buffering or copies.
.. note::
As of cairo 1.12,
the semantics of subsurfaces have not been finalized yet
unless the rectangle is in full device units,
is contained within the extents of the target surface,
and the target or subsurface's device transforms are not changed.
:param x:
The x-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param y:
The y-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param width:
Width of the sub-surface (in device-space units)
:param height:
Height of the sub-surface (in device-space units)
:type x: float
:type y: float
:type width: float
:type height: float
:returns:
A new :class:`Surface` object.
*New in cairo 1.10.*
"""
return Surface._from_pointer(
cairo.cairo_surface_create_for_rectangle(
self._pointer, x, y, width, height),
incref=False) | python | def create_for_rectangle(self, x, y, width, height):
"""
Create a new surface that is a rectangle within this surface.
All operations drawn to this surface are then clipped and translated
onto the target surface.
Nothing drawn via this sub-surface outside of its bounds
is drawn onto the target surface,
making this a useful method for passing constrained child surfaces
to library routines that draw directly onto the parent surface,
i.e. with no further backend allocations,
double buffering or copies.
.. note::
As of cairo 1.12,
the semantics of subsurfaces have not been finalized yet
unless the rectangle is in full device units,
is contained within the extents of the target surface,
and the target or subsurface's device transforms are not changed.
:param x:
The x-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param y:
The y-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param width:
Width of the sub-surface (in device-space units)
:param height:
Height of the sub-surface (in device-space units)
:type x: float
:type y: float
:type width: float
:type height: float
:returns:
A new :class:`Surface` object.
*New in cairo 1.10.*
"""
return Surface._from_pointer(
cairo.cairo_surface_create_for_rectangle(
self._pointer, x, y, width, height),
incref=False) | [
"def",
"create_for_rectangle",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"return",
"Surface",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_surface_create_for_rectangle",
"(",
"self",
".",
"_pointer",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
",",
"incref",
"=",
"False",
")"
] | Create a new surface that is a rectangle within this surface.
All operations drawn to this surface are then clipped and translated
onto the target surface.
Nothing drawn via this sub-surface outside of its bounds
is drawn onto the target surface,
making this a useful method for passing constrained child surfaces
to library routines that draw directly onto the parent surface,
i.e. with no further backend allocations,
double buffering or copies.
.. note::
As of cairo 1.12,
the semantics of subsurfaces have not been finalized yet
unless the rectangle is in full device units,
is contained within the extents of the target surface,
and the target or subsurface's device transforms are not changed.
:param x:
The x-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param y:
The y-origin of the sub-surface
from the top-left of the target surface (in device-space units)
:param width:
Width of the sub-surface (in device-space units)
:param height:
Height of the sub-surface (in device-space units)
:type x: float
:type y: float
:type width: float
:type height: float
:returns:
A new :class:`Surface` object.
*New in cairo 1.10.* | [
"Create",
"a",
"new",
"surface",
"that",
"is",
"a",
"rectangle",
"within",
"this",
"surface",
".",
"All",
"operations",
"drawn",
"to",
"this",
"surface",
"are",
"then",
"clipped",
"and",
"translated",
"onto",
"the",
"target",
"surface",
".",
"Nothing",
"drawn",
"via",
"this",
"sub",
"-",
"surface",
"outside",
"of",
"its",
"bounds",
"is",
"drawn",
"onto",
"the",
"target",
"surface",
"making",
"this",
"a",
"useful",
"method",
"for",
"passing",
"constrained",
"child",
"surfaces",
"to",
"library",
"routines",
"that",
"draw",
"directly",
"onto",
"the",
"parent",
"surface",
"i",
".",
"e",
".",
"with",
"no",
"further",
"backend",
"allocations",
"double",
"buffering",
"or",
"copies",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L234-L277 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.set_fallback_resolution | def set_fallback_resolution(self, x_pixels_per_inch, y_pixels_per_inch):
"""
Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend,
cairo will fallback by rendering operations to an image
and then overlaying that image onto the output.
For backends that are natively vector-oriented,
this method can be used to set the resolution
used for these image fallbacks,
(larger values will result in more detailed images,
but also larger file sizes).
Some examples of natively vector-oriented backends are
the ps, pdf, and svg backends.
For backends that are natively raster-oriented,
image fallbacks are still possible,
but they are always performed at the native device resolution.
So this method has no effect on those backends.
.. note::
The fallback resolution only takes effect
at the time of completing a page
(with :meth:`show_page` or :meth:`copy_page`)
so there is currently no way to have
more than one fallback resolution in effect on a single page.
The default fallback resoultion is
300 pixels per inch in both dimensions.
:param x_pixels_per_inch: horizontal resolution in pixels per inch
:type x_pixels_per_inch: float
:param y_pixels_per_inch: vertical resolution in pixels per inch
:type y_pixels_per_inch: float
"""
cairo.cairo_surface_set_fallback_resolution(
self._pointer, x_pixels_per_inch, y_pixels_per_inch)
self._check_status() | python | def set_fallback_resolution(self, x_pixels_per_inch, y_pixels_per_inch):
"""
Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend,
cairo will fallback by rendering operations to an image
and then overlaying that image onto the output.
For backends that are natively vector-oriented,
this method can be used to set the resolution
used for these image fallbacks,
(larger values will result in more detailed images,
but also larger file sizes).
Some examples of natively vector-oriented backends are
the ps, pdf, and svg backends.
For backends that are natively raster-oriented,
image fallbacks are still possible,
but they are always performed at the native device resolution.
So this method has no effect on those backends.
.. note::
The fallback resolution only takes effect
at the time of completing a page
(with :meth:`show_page` or :meth:`copy_page`)
so there is currently no way to have
more than one fallback resolution in effect on a single page.
The default fallback resoultion is
300 pixels per inch in both dimensions.
:param x_pixels_per_inch: horizontal resolution in pixels per inch
:type x_pixels_per_inch: float
:param y_pixels_per_inch: vertical resolution in pixels per inch
:type y_pixels_per_inch: float
"""
cairo.cairo_surface_set_fallback_resolution(
self._pointer, x_pixels_per_inch, y_pixels_per_inch)
self._check_status() | [
"def",
"set_fallback_resolution",
"(",
"self",
",",
"x_pixels_per_inch",
",",
"y_pixels_per_inch",
")",
":",
"cairo",
".",
"cairo_surface_set_fallback_resolution",
"(",
"self",
".",
"_pointer",
",",
"x_pixels_per_inch",
",",
"y_pixels_per_inch",
")",
"self",
".",
"_check_status",
"(",
")"
] | Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend,
cairo will fallback by rendering operations to an image
and then overlaying that image onto the output.
For backends that are natively vector-oriented,
this method can be used to set the resolution
used for these image fallbacks,
(larger values will result in more detailed images,
but also larger file sizes).
Some examples of natively vector-oriented backends are
the ps, pdf, and svg backends.
For backends that are natively raster-oriented,
image fallbacks are still possible,
but they are always performed at the native device resolution.
So this method has no effect on those backends.
.. note::
The fallback resolution only takes effect
at the time of completing a page
(with :meth:`show_page` or :meth:`copy_page`)
so there is currently no way to have
more than one fallback resolution in effect on a single page.
The default fallback resoultion is
300 pixels per inch in both dimensions.
:param x_pixels_per_inch: horizontal resolution in pixels per inch
:type x_pixels_per_inch: float
:param y_pixels_per_inch: vertical resolution in pixels per inch
:type y_pixels_per_inch: float | [
"Set",
"the",
"horizontal",
"and",
"vertical",
"resolution",
"for",
"image",
"fallbacks",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L342-L382 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.get_font_options | def get_font_options(self):
"""Retrieves the default font rendering options for the surface.
This allows display surfaces to report the correct subpixel order
for rendering on them,
print surfaces to disable hinting of metrics and so forth.
The result can then be used with :class:`ScaledFont`.
:returns: A new :class:`FontOptions` object.
"""
font_options = FontOptions()
cairo.cairo_surface_get_font_options(
self._pointer, font_options._pointer)
return font_options | python | def get_font_options(self):
"""Retrieves the default font rendering options for the surface.
This allows display surfaces to report the correct subpixel order
for rendering on them,
print surfaces to disable hinting of metrics and so forth.
The result can then be used with :class:`ScaledFont`.
:returns: A new :class:`FontOptions` object.
"""
font_options = FontOptions()
cairo.cairo_surface_get_font_options(
self._pointer, font_options._pointer)
return font_options | [
"def",
"get_font_options",
"(",
"self",
")",
":",
"font_options",
"=",
"FontOptions",
"(",
")",
"cairo",
".",
"cairo_surface_get_font_options",
"(",
"self",
".",
"_pointer",
",",
"font_options",
".",
"_pointer",
")",
"return",
"font_options"
] | Retrieves the default font rendering options for the surface.
This allows display surfaces to report the correct subpixel order
for rendering on them,
print surfaces to disable hinting of metrics and so forth.
The result can then be used with :class:`ScaledFont`.
:returns: A new :class:`FontOptions` object. | [
"Retrieves",
"the",
"default",
"font",
"rendering",
"options",
"for",
"the",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L397-L411 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.set_device_scale | def set_device_scale(self, x_scale, y_scale):
"""Sets a scale that is multiplied to the device coordinates determined
by the CTM when drawing to surface.
One common use for this is to render to very high resolution display
devices at a scale factor, so that code that assumes 1 pixel will be a
certain size will still work. Setting a transformation via
cairo_translate() isn't sufficient to do this, since functions like
cairo_device_to_user() will expose the hidden scale.
Note that the scale affects drawing to the surface as well as using the
surface in a source pattern.
:param x_scale: the scale in the X direction, in device units.
:param y_scale: the scale in the Y direction, in device units.
*New in cairo 1.14.*
*New in cairocffi 0.9.*
"""
cairo.cairo_surface_set_device_scale(self._pointer, x_scale, y_scale)
self._check_status() | python | def set_device_scale(self, x_scale, y_scale):
"""Sets a scale that is multiplied to the device coordinates determined
by the CTM when drawing to surface.
One common use for this is to render to very high resolution display
devices at a scale factor, so that code that assumes 1 pixel will be a
certain size will still work. Setting a transformation via
cairo_translate() isn't sufficient to do this, since functions like
cairo_device_to_user() will expose the hidden scale.
Note that the scale affects drawing to the surface as well as using the
surface in a source pattern.
:param x_scale: the scale in the X direction, in device units.
:param y_scale: the scale in the Y direction, in device units.
*New in cairo 1.14.*
*New in cairocffi 0.9.*
"""
cairo.cairo_surface_set_device_scale(self._pointer, x_scale, y_scale)
self._check_status() | [
"def",
"set_device_scale",
"(",
"self",
",",
"x_scale",
",",
"y_scale",
")",
":",
"cairo",
".",
"cairo_surface_set_device_scale",
"(",
"self",
".",
"_pointer",
",",
"x_scale",
",",
"y_scale",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets a scale that is multiplied to the device coordinates determined
by the CTM when drawing to surface.
One common use for this is to render to very high resolution display
devices at a scale factor, so that code that assumes 1 pixel will be a
certain size will still work. Setting a transformation via
cairo_translate() isn't sufficient to do this, since functions like
cairo_device_to_user() will expose the hidden scale.
Note that the scale affects drawing to the surface as well as using the
surface in a source pattern.
:param x_scale: the scale in the X direction, in device units.
:param y_scale: the scale in the Y direction, in device units.
*New in cairo 1.14.*
*New in cairocffi 0.9.* | [
"Sets",
"a",
"scale",
"that",
"is",
"multiplied",
"to",
"the",
"device",
"coordinates",
"determined",
"by",
"the",
"CTM",
"when",
"drawing",
"to",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L413-L435 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.get_mime_data | def get_mime_data(self, mime_type):
"""Return mime data previously attached to surface
using the specified mime type.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
:returns:
A CFFI buffer object, or :obj:`None`
if no data has been attached with the given mime type.
*New in cairo 1.10.*
"""
buffer_address = ffi.new('unsigned char **')
buffer_length = ffi.new('unsigned long *')
mime_type = ffi.new('char[]', mime_type.encode('utf8'))
cairo.cairo_surface_get_mime_data(
self._pointer, mime_type, buffer_address, buffer_length)
return (ffi.buffer(buffer_address[0], buffer_length[0])
if buffer_address[0] != ffi.NULL else None) | python | def get_mime_data(self, mime_type):
"""Return mime data previously attached to surface
using the specified mime type.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
:returns:
A CFFI buffer object, or :obj:`None`
if no data has been attached with the given mime type.
*New in cairo 1.10.*
"""
buffer_address = ffi.new('unsigned char **')
buffer_length = ffi.new('unsigned long *')
mime_type = ffi.new('char[]', mime_type.encode('utf8'))
cairo.cairo_surface_get_mime_data(
self._pointer, mime_type, buffer_address, buffer_length)
return (ffi.buffer(buffer_address[0], buffer_length[0])
if buffer_address[0] != ffi.NULL else None) | [
"def",
"get_mime_data",
"(",
"self",
",",
"mime_type",
")",
":",
"buffer_address",
"=",
"ffi",
".",
"new",
"(",
"'unsigned char **'",
")",
"buffer_length",
"=",
"ffi",
".",
"new",
"(",
"'unsigned long *'",
")",
"mime_type",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"mime_type",
".",
"encode",
"(",
"'utf8'",
")",
")",
"cairo",
".",
"cairo_surface_get_mime_data",
"(",
"self",
".",
"_pointer",
",",
"mime_type",
",",
"buffer_address",
",",
"buffer_length",
")",
"return",
"(",
"ffi",
".",
"buffer",
"(",
"buffer_address",
"[",
"0",
"]",
",",
"buffer_length",
"[",
"0",
"]",
")",
"if",
"buffer_address",
"[",
"0",
"]",
"!=",
"ffi",
".",
"NULL",
"else",
"None",
")"
] | Return mime data previously attached to surface
using the specified mime type.
:param mime_type: The MIME type of the image data.
:type mime_type: ASCII string
:returns:
A CFFI buffer object, or :obj:`None`
if no data has been attached with the given mime type.
*New in cairo 1.10.* | [
"Return",
"mime",
"data",
"previously",
"attached",
"to",
"surface",
"using",
"the",
"specified",
"mime",
"type",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L504-L523 | train |
Kozea/cairocffi | cairocffi/surfaces.py | Surface.write_to_png | def write_to_png(self, target=None):
"""Writes the contents of surface as a PNG image.
:param target:
A filename,
a binary mode file-like object with a :meth:`~file.write` method,
or :obj:`None`.
:returns:
If :obj:`target` is :obj:`None`,
return the PNG contents as a byte string.
"""
return_bytes = target is None
if return_bytes:
target = io.BytesIO()
if hasattr(target, 'write'):
write_func = _make_write_func(target)
_check_status(cairo.cairo_surface_write_to_png_stream(
self._pointer, write_func, ffi.NULL))
else:
_check_status(cairo.cairo_surface_write_to_png(
self._pointer, _encode_filename(target)))
if return_bytes:
return target.getvalue() | python | def write_to_png(self, target=None):
"""Writes the contents of surface as a PNG image.
:param target:
A filename,
a binary mode file-like object with a :meth:`~file.write` method,
or :obj:`None`.
:returns:
If :obj:`target` is :obj:`None`,
return the PNG contents as a byte string.
"""
return_bytes = target is None
if return_bytes:
target = io.BytesIO()
if hasattr(target, 'write'):
write_func = _make_write_func(target)
_check_status(cairo.cairo_surface_write_to_png_stream(
self._pointer, write_func, ffi.NULL))
else:
_check_status(cairo.cairo_surface_write_to_png(
self._pointer, _encode_filename(target)))
if return_bytes:
return target.getvalue() | [
"def",
"write_to_png",
"(",
"self",
",",
"target",
"=",
"None",
")",
":",
"return_bytes",
"=",
"target",
"is",
"None",
"if",
"return_bytes",
":",
"target",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"hasattr",
"(",
"target",
",",
"'write'",
")",
":",
"write_func",
"=",
"_make_write_func",
"(",
"target",
")",
"_check_status",
"(",
"cairo",
".",
"cairo_surface_write_to_png_stream",
"(",
"self",
".",
"_pointer",
",",
"write_func",
",",
"ffi",
".",
"NULL",
")",
")",
"else",
":",
"_check_status",
"(",
"cairo",
".",
"cairo_surface_write_to_png",
"(",
"self",
".",
"_pointer",
",",
"_encode_filename",
"(",
"target",
")",
")",
")",
"if",
"return_bytes",
":",
"return",
"target",
".",
"getvalue",
"(",
")"
] | Writes the contents of surface as a PNG image.
:param target:
A filename,
a binary mode file-like object with a :meth:`~file.write` method,
or :obj:`None`.
:returns:
If :obj:`target` is :obj:`None`,
return the PNG contents as a byte string. | [
"Writes",
"the",
"contents",
"of",
"surface",
"as",
"a",
"PNG",
"image",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L630-L653 | train |
Kozea/cairocffi | cairocffi/surfaces.py | ImageSurface.create_from_png | def create_from_png(cls, source):
"""Decode a PNG file into a new image surface.
:param source:
A filename or
a binary mode file-like object with a :meth:`~file.read` method.
If you already have a byte string in memory,
use :class:`io.BytesIO`.
:returns: A new :class:`ImageSurface` instance.
"""
if hasattr(source, 'read'):
read_func = _make_read_func(source)
pointer = cairo.cairo_image_surface_create_from_png_stream(
read_func, ffi.NULL)
else:
pointer = cairo.cairo_image_surface_create_from_png(
_encode_filename(source))
self = object.__new__(cls)
Surface.__init__(self, pointer) # Skip ImageSurface.__init__
return self | python | def create_from_png(cls, source):
"""Decode a PNG file into a new image surface.
:param source:
A filename or
a binary mode file-like object with a :meth:`~file.read` method.
If you already have a byte string in memory,
use :class:`io.BytesIO`.
:returns: A new :class:`ImageSurface` instance.
"""
if hasattr(source, 'read'):
read_func = _make_read_func(source)
pointer = cairo.cairo_image_surface_create_from_png_stream(
read_func, ffi.NULL)
else:
pointer = cairo.cairo_image_surface_create_from_png(
_encode_filename(source))
self = object.__new__(cls)
Surface.__init__(self, pointer) # Skip ImageSurface.__init__
return self | [
"def",
"create_from_png",
"(",
"cls",
",",
"source",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"'read'",
")",
":",
"read_func",
"=",
"_make_read_func",
"(",
"source",
")",
"pointer",
"=",
"cairo",
".",
"cairo_image_surface_create_from_png_stream",
"(",
"read_func",
",",
"ffi",
".",
"NULL",
")",
"else",
":",
"pointer",
"=",
"cairo",
".",
"cairo_image_surface_create_from_png",
"(",
"_encode_filename",
"(",
"source",
")",
")",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"Surface",
".",
"__init__",
"(",
"self",
",",
"pointer",
")",
"# Skip ImageSurface.__init__",
"return",
"self"
] | Decode a PNG file into a new image surface.
:param source:
A filename or
a binary mode file-like object with a :meth:`~file.read` method.
If you already have a byte string in memory,
use :class:`io.BytesIO`.
:returns: A new :class:`ImageSurface` instance. | [
"Decode",
"a",
"PNG",
"file",
"into",
"a",
"new",
"image",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L742-L762 | train |
Kozea/cairocffi | cairocffi/surfaces.py | PDFSurface.add_outline | def add_outline(self, parent_id, utf8, link_attribs, flags=None):
"""Add an item to the document outline hierarchy.
The outline has the ``utf8`` name and links to the location specified
by ``link_attribs``. Link attributes have the same keys and values as
the Link Tag, excluding the ``rect`` attribute. The item will be a
child of the item with id ``parent_id``. Use ``PDF_OUTLINE_ROOT`` as
the parent id of top level items.
:param parent_id:
the id of the parent item or ``PDF_OUTLINE_ROOT`` if this is a
top level item.
:param utf8: the name of the outline.
:param link_attribs:
the link attributes specifying where this outline links to.
:param flags: outline item flags.
:return: the id for the added item.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if flags is None:
flags = 0
value = cairo.cairo_pdf_surface_add_outline(
self._pointer, parent_id, _encode_string(utf8),
_encode_string(link_attribs), flags)
self._check_status()
return value | python | def add_outline(self, parent_id, utf8, link_attribs, flags=None):
"""Add an item to the document outline hierarchy.
The outline has the ``utf8`` name and links to the location specified
by ``link_attribs``. Link attributes have the same keys and values as
the Link Tag, excluding the ``rect`` attribute. The item will be a
child of the item with id ``parent_id``. Use ``PDF_OUTLINE_ROOT`` as
the parent id of top level items.
:param parent_id:
the id of the parent item or ``PDF_OUTLINE_ROOT`` if this is a
top level item.
:param utf8: the name of the outline.
:param link_attribs:
the link attributes specifying where this outline links to.
:param flags: outline item flags.
:return: the id for the added item.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if flags is None:
flags = 0
value = cairo.cairo_pdf_surface_add_outline(
self._pointer, parent_id, _encode_string(utf8),
_encode_string(link_attribs), flags)
self._check_status()
return value | [
"def",
"add_outline",
"(",
"self",
",",
"parent_id",
",",
"utf8",
",",
"link_attribs",
",",
"flags",
"=",
"None",
")",
":",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
"0",
"value",
"=",
"cairo",
".",
"cairo_pdf_surface_add_outline",
"(",
"self",
".",
"_pointer",
",",
"parent_id",
",",
"_encode_string",
"(",
"utf8",
")",
",",
"_encode_string",
"(",
"link_attribs",
")",
",",
"flags",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"value"
] | Add an item to the document outline hierarchy.
The outline has the ``utf8`` name and links to the location specified
by ``link_attribs``. Link attributes have the same keys and values as
the Link Tag, excluding the ``rect`` attribute. The item will be a
child of the item with id ``parent_id``. Use ``PDF_OUTLINE_ROOT`` as
the parent id of top level items.
:param parent_id:
the id of the parent item or ``PDF_OUTLINE_ROOT`` if this is a
top level item.
:param utf8: the name of the outline.
:param link_attribs:
the link attributes specifying where this outline links to.
:param flags: outline item flags.
:return: the id for the added item.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Add",
"an",
"item",
"to",
"the",
"document",
"outline",
"hierarchy",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L873-L903 | train |
Kozea/cairocffi | cairocffi/surfaces.py | PDFSurface.set_metadata | def set_metadata(self, metadata, utf8):
"""Sets document metadata.
The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE``
values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional
timezone of the form "[+/-]hh:mm" or "Z" for UTC time can be appended.
All other metadata values can be any UTF-8 string.
:param metadata: the metadata item to set.
:param utf8: metadata value.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_pdf_surface_set_metadata(
self._pointer, metadata, _encode_string(utf8))
self._check_status() | python | def set_metadata(self, metadata, utf8):
"""Sets document metadata.
The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE``
values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional
timezone of the form "[+/-]hh:mm" or "Z" for UTC time can be appended.
All other metadata values can be any UTF-8 string.
:param metadata: the metadata item to set.
:param utf8: metadata value.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_pdf_surface_set_metadata(
self._pointer, metadata, _encode_string(utf8))
self._check_status() | [
"def",
"set_metadata",
"(",
"self",
",",
"metadata",
",",
"utf8",
")",
":",
"cairo",
".",
"cairo_pdf_surface_set_metadata",
"(",
"self",
".",
"_pointer",
",",
"metadata",
",",
"_encode_string",
"(",
"utf8",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets document metadata.
The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE``
values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional
timezone of the form "[+/-]hh:mm" or "Z" for UTC time can be appended.
All other metadata values can be any UTF-8 string.
:param metadata: the metadata item to set.
:param utf8: metadata value.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Sets",
"document",
"metadata",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L905-L923 | train |
Kozea/cairocffi | cairocffi/surfaces.py | PDFSurface.set_thumbnail_size | def set_thumbnail_size(self, width, height):
"""Set thumbnail image size for the current and all subsequent pages.
Setting a width or height of 0 disables thumbnails for the current and
subsequent pages.
:param width: thumbnail width.
:param height: thumbnail height.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_pdf_surface_set_thumbnail_size(
self._pointer, width, height) | python | def set_thumbnail_size(self, width, height):
"""Set thumbnail image size for the current and all subsequent pages.
Setting a width or height of 0 disables thumbnails for the current and
subsequent pages.
:param width: thumbnail width.
:param height: thumbnail height.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_pdf_surface_set_thumbnail_size(
self._pointer, width, height) | [
"def",
"set_thumbnail_size",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"cairo",
".",
"cairo_pdf_surface_set_thumbnail_size",
"(",
"self",
".",
"_pointer",
",",
"width",
",",
"height",
")"
] | Set thumbnail image size for the current and all subsequent pages.
Setting a width or height of 0 disables thumbnails for the current and
subsequent pages.
:param width: thumbnail width.
:param height: thumbnail height.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Set",
"thumbnail",
"image",
"size",
"for",
"the",
"current",
"and",
"all",
"subsequent",
"pages",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L938-L953 | train |
Kozea/cairocffi | cairocffi/surfaces.py | PSSurface.dsc_comment | def dsc_comment(self, comment):
""" Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to
the PostScript Language Document Structuring Conventions (DSC).
Please see that manual for details on the available comments
and their meanings.
In particular, the ``%%IncludeFeature`` comment allows
a device-independent means of controlling printer device features.
So the PostScript Printer Description Files Specification
will also be a useful reference.
The comment string must begin with a percent character (%)
and the total length of the string
(including any initial percent characters)
must not exceed 255 bytes.
Violating either of these conditions will
place surface into an error state.
But beyond these two conditions,
this method will not enforce conformance of the comment
with any particular specification.
The comment string should not have a trailing newline.
The DSC specifies different sections
in which particular comments can appear.
This method provides for comments to be emitted
within three sections:
the header, the Setup section, and the PageSetup section.
Comments appearing in the first two sections
apply to the entire document
while comments in the BeginPageSetup section
apply only to a single page.
For comments to appear in the header section,
this method should be called after the surface is created,
but before a call to :meth:`dsc_begin_setup`.
For comments to appear in the Setup section,
this method should be called after a call to :meth:`dsc_begin_setup`
but before a call to :meth:`dsc_begin_page_setup`.
For comments to appear in the PageSetup section,
this method should be called after a call to
:meth:`dsc_begin_page_setup`.
Note that it is only necessary to call :meth:`dsc_begin_page_setup`
for the first page of any surface.
After a call to :meth:`~Surface.show_page`
or :meth:`~Surface.copy_page`
comments are unambiguously directed
to the PageSetup section of the current page.
But it doesn't hurt to call this method
at the beginning of every page
as that consistency may make the calling code simpler.
As a final note,
cairo automatically generates several comments on its own.
As such, applications must not manually generate
any of the following comments:
Header section: ``%!PS-Adobe-3.0``, ``%%Creator``, ``%%CreationDate``,
``%%Pages``, ``%%BoundingBox``, ``%%DocumentData``,
``%%LanguageLevel``, ``%%EndComments``.
Setup section: ``%%BeginSetup``, ``%%EndSetup``.
PageSetup section: ``%%BeginPageSetup``, ``%%PageBoundingBox``,
``%%EndPageSetup``.
Other sections: ``%%BeginProlog``, ``%%EndProlog``, ``%%Page``,
``%%Trailer``, ``%%EOF``.
"""
cairo.cairo_ps_surface_dsc_comment(
self._pointer, _encode_string(comment))
self._check_status() | python | def dsc_comment(self, comment):
""" Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to
the PostScript Language Document Structuring Conventions (DSC).
Please see that manual for details on the available comments
and their meanings.
In particular, the ``%%IncludeFeature`` comment allows
a device-independent means of controlling printer device features.
So the PostScript Printer Description Files Specification
will also be a useful reference.
The comment string must begin with a percent character (%)
and the total length of the string
(including any initial percent characters)
must not exceed 255 bytes.
Violating either of these conditions will
place surface into an error state.
But beyond these two conditions,
this method will not enforce conformance of the comment
with any particular specification.
The comment string should not have a trailing newline.
The DSC specifies different sections
in which particular comments can appear.
This method provides for comments to be emitted
within three sections:
the header, the Setup section, and the PageSetup section.
Comments appearing in the first two sections
apply to the entire document
while comments in the BeginPageSetup section
apply only to a single page.
For comments to appear in the header section,
this method should be called after the surface is created,
but before a call to :meth:`dsc_begin_setup`.
For comments to appear in the Setup section,
this method should be called after a call to :meth:`dsc_begin_setup`
but before a call to :meth:`dsc_begin_page_setup`.
For comments to appear in the PageSetup section,
this method should be called after a call to
:meth:`dsc_begin_page_setup`.
Note that it is only necessary to call :meth:`dsc_begin_page_setup`
for the first page of any surface.
After a call to :meth:`~Surface.show_page`
or :meth:`~Surface.copy_page`
comments are unambiguously directed
to the PageSetup section of the current page.
But it doesn't hurt to call this method
at the beginning of every page
as that consistency may make the calling code simpler.
As a final note,
cairo automatically generates several comments on its own.
As such, applications must not manually generate
any of the following comments:
Header section: ``%!PS-Adobe-3.0``, ``%%Creator``, ``%%CreationDate``,
``%%Pages``, ``%%BoundingBox``, ``%%DocumentData``,
``%%LanguageLevel``, ``%%EndComments``.
Setup section: ``%%BeginSetup``, ``%%EndSetup``.
PageSetup section: ``%%BeginPageSetup``, ``%%PageBoundingBox``,
``%%EndPageSetup``.
Other sections: ``%%BeginProlog``, ``%%EndProlog``, ``%%Page``,
``%%Trailer``, ``%%EOF``.
"""
cairo.cairo_ps_surface_dsc_comment(
self._pointer, _encode_string(comment))
self._check_status() | [
"def",
"dsc_comment",
"(",
"self",
",",
"comment",
")",
":",
"cairo",
".",
"cairo_ps_surface_dsc_comment",
"(",
"self",
".",
"_pointer",
",",
"_encode_string",
"(",
"comment",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to
the PostScript Language Document Structuring Conventions (DSC).
Please see that manual for details on the available comments
and their meanings.
In particular, the ``%%IncludeFeature`` comment allows
a device-independent means of controlling printer device features.
So the PostScript Printer Description Files Specification
will also be a useful reference.
The comment string must begin with a percent character (%)
and the total length of the string
(including any initial percent characters)
must not exceed 255 bytes.
Violating either of these conditions will
place surface into an error state.
But beyond these two conditions,
this method will not enforce conformance of the comment
with any particular specification.
The comment string should not have a trailing newline.
The DSC specifies different sections
in which particular comments can appear.
This method provides for comments to be emitted
within three sections:
the header, the Setup section, and the PageSetup section.
Comments appearing in the first two sections
apply to the entire document
while comments in the BeginPageSetup section
apply only to a single page.
For comments to appear in the header section,
this method should be called after the surface is created,
but before a call to :meth:`dsc_begin_setup`.
For comments to appear in the Setup section,
this method should be called after a call to :meth:`dsc_begin_setup`
but before a call to :meth:`dsc_begin_page_setup`.
For comments to appear in the PageSetup section,
this method should be called after a call to
:meth:`dsc_begin_page_setup`.
Note that it is only necessary to call :meth:`dsc_begin_page_setup`
for the first page of any surface.
After a call to :meth:`~Surface.show_page`
or :meth:`~Surface.copy_page`
comments are unambiguously directed
to the PageSetup section of the current page.
But it doesn't hurt to call this method
at the beginning of every page
as that consistency may make the calling code simpler.
As a final note,
cairo automatically generates several comments on its own.
As such, applications must not manually generate
any of the following comments:
Header section: ``%!PS-Adobe-3.0``, ``%%Creator``, ``%%CreationDate``,
``%%Pages``, ``%%BoundingBox``, ``%%DocumentData``,
``%%LanguageLevel``, ``%%EndComments``.
Setup section: ``%%BeginSetup``, ``%%EndSetup``.
PageSetup section: ``%%BeginPageSetup``, ``%%PageBoundingBox``,
``%%EndPageSetup``.
Other sections: ``%%BeginProlog``, ``%%EndProlog``, ``%%Page``,
``%%Trailer``, ``%%EOF``. | [
"Emit",
"a",
"comment",
"into",
"the",
"PostScript",
"output",
"for",
"the",
"given",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1047-L1123 | train |
Kozea/cairocffi | cairocffi/surfaces.py | SVGSurface.set_document_unit | def set_document_unit(self, unit):
"""Use specified unit for width and height of generated SVG file.
See ``SVG_UNIT_*`` enumerated values for a list of available unit
values that can be used here.
This function can be called at any time before generating the SVG file.
However to minimize the risk of ambiguities it's recommended to call it
before any drawing operations have been performed on the given surface,
to make it clearer what the unit used in the drawing operations is.
The simplest way to do this is to call this function immediately after
creating the SVG surface.
Note if this function is never called, the default unit for SVG
documents generated by cairo will be "pt". This is for historical
reasons.
:param unit: SVG unit.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_svg_surface_set_document_unit(self._pointer, unit)
self._check_status() | python | def set_document_unit(self, unit):
"""Use specified unit for width and height of generated SVG file.
See ``SVG_UNIT_*`` enumerated values for a list of available unit
values that can be used here.
This function can be called at any time before generating the SVG file.
However to minimize the risk of ambiguities it's recommended to call it
before any drawing operations have been performed on the given surface,
to make it clearer what the unit used in the drawing operations is.
The simplest way to do this is to call this function immediately after
creating the SVG surface.
Note if this function is never called, the default unit for SVG
documents generated by cairo will be "pt". This is for historical
reasons.
:param unit: SVG unit.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
cairo.cairo_svg_surface_set_document_unit(self._pointer, unit)
self._check_status() | [
"def",
"set_document_unit",
"(",
"self",
",",
"unit",
")",
":",
"cairo",
".",
"cairo_svg_surface_set_document_unit",
"(",
"self",
".",
"_pointer",
",",
"unit",
")",
"self",
".",
"_check_status",
"(",
")"
] | Use specified unit for width and height of generated SVG file.
See ``SVG_UNIT_*`` enumerated values for a list of available unit
values that can be used here.
This function can be called at any time before generating the SVG file.
However to minimize the risk of ambiguities it's recommended to call it
before any drawing operations have been performed on the given surface,
to make it clearer what the unit used in the drawing operations is.
The simplest way to do this is to call this function immediately after
creating the SVG surface.
Note if this function is never called, the default unit for SVG
documents generated by cairo will be "pt". This is for historical
reasons.
:param unit: SVG unit.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Use",
"specified",
"unit",
"for",
"width",
"and",
"height",
"of",
"generated",
"SVG",
"file",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1309-L1336 | train |
Kozea/cairocffi | cairocffi/surfaces.py | SVGSurface.get_document_unit | def get_document_unit(self):
"""Get the unit of the SVG surface.
If the surface passed as an argument is not a SVG surface, the function
sets the error status to ``STATUS_SURFACE_TYPE_MISMATCH`` and
returns :ref:`SVG_UNIT_USER`.
:return: The SVG unit of the SVG surface.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
unit = cairo.cairo_svg_surface_get_document_unit(self._pointer)
self._check_status()
return unit | python | def get_document_unit(self):
"""Get the unit of the SVG surface.
If the surface passed as an argument is not a SVG surface, the function
sets the error status to ``STATUS_SURFACE_TYPE_MISMATCH`` and
returns :ref:`SVG_UNIT_USER`.
:return: The SVG unit of the SVG surface.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
unit = cairo.cairo_svg_surface_get_document_unit(self._pointer)
self._check_status()
return unit | [
"def",
"get_document_unit",
"(",
"self",
")",
":",
"unit",
"=",
"cairo",
".",
"cairo_svg_surface_get_document_unit",
"(",
"self",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")",
"return",
"unit"
] | Get the unit of the SVG surface.
If the surface passed as an argument is not a SVG surface, the function
sets the error status to ``STATUS_SURFACE_TYPE_MISMATCH`` and
returns :ref:`SVG_UNIT_USER`.
:return: The SVG unit of the SVG surface.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Get",
"the",
"unit",
"of",
"the",
"SVG",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1338-L1354 | train |
Kozea/cairocffi | cairocffi/surfaces.py | RecordingSurface.get_extents | def get_extents(self):
"""Return the extents of the recording-surface.
:returns:
A ``(x, y, width, height)`` tuple of floats,
or :obj:`None` if the surface is unbounded.
*New in cairo 1.12*
"""
extents = ffi.new('cairo_rectangle_t *')
if cairo.cairo_recording_surface_get_extents(self._pointer, extents):
return (extents.x, extents.y, extents.width, extents.height) | python | def get_extents(self):
"""Return the extents of the recording-surface.
:returns:
A ``(x, y, width, height)`` tuple of floats,
or :obj:`None` if the surface is unbounded.
*New in cairo 1.12*
"""
extents = ffi.new('cairo_rectangle_t *')
if cairo.cairo_recording_surface_get_extents(self._pointer, extents):
return (extents.x, extents.y, extents.width, extents.height) | [
"def",
"get_extents",
"(",
"self",
")",
":",
"extents",
"=",
"ffi",
".",
"new",
"(",
"'cairo_rectangle_t *'",
")",
"if",
"cairo",
".",
"cairo_recording_surface_get_extents",
"(",
"self",
".",
"_pointer",
",",
"extents",
")",
":",
"return",
"(",
"extents",
".",
"x",
",",
"extents",
".",
"y",
",",
"extents",
".",
"width",
",",
"extents",
".",
"height",
")"
] | Return the extents of the recording-surface.
:returns:
A ``(x, y, width, height)`` tuple of floats,
or :obj:`None` if the surface is unbounded.
*New in cairo 1.12* | [
"Return",
"the",
"extents",
"of",
"the",
"recording",
"-",
"surface",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1430-L1442 | train |
Kozea/cairocffi | cairocffi/patterns.py | Gradient.add_color_stop_rgba | def add_color_stop_rgba(self, offset, red, green, blue, alpha=1):
"""Adds a translucent color stop to a gradient pattern.
The offset specifies the location along the gradient's control vector.
For example,
a linear gradient's control vector is from (x0,y0) to (x1,y1)
while a radial gradient's control vector is
from any point on the start circle
to the corresponding point on the end circle.
If two (or more) stops are specified with identical offset values,
they will be sorted
according to the order in which the stops are added
(stops added earlier before stops added later).
This can be useful for reliably making sharp color transitions
instead of the typical blend.
The color components and offset are in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
:param offset: Location along the gradient's control vector
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type offset: float
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_pattern_add_color_stop_rgba(
self._pointer, offset, red, green, blue, alpha)
self._check_status() | python | def add_color_stop_rgba(self, offset, red, green, blue, alpha=1):
"""Adds a translucent color stop to a gradient pattern.
The offset specifies the location along the gradient's control vector.
For example,
a linear gradient's control vector is from (x0,y0) to (x1,y1)
while a radial gradient's control vector is
from any point on the start circle
to the corresponding point on the end circle.
If two (or more) stops are specified with identical offset values,
they will be sorted
according to the order in which the stops are added
(stops added earlier before stops added later).
This can be useful for reliably making sharp color transitions
instead of the typical blend.
The color components and offset are in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
:param offset: Location along the gradient's control vector
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type offset: float
:type red: float
:type green: float
:type blue: float
:type alpha: float
"""
cairo.cairo_pattern_add_color_stop_rgba(
self._pointer, offset, red, green, blue, alpha)
self._check_status() | [
"def",
"add_color_stop_rgba",
"(",
"self",
",",
"offset",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"=",
"1",
")",
":",
"cairo",
".",
"cairo_pattern_add_color_stop_rgba",
"(",
"self",
".",
"_pointer",
",",
"offset",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
"self",
".",
"_check_status",
"(",
")"
] | Adds a translucent color stop to a gradient pattern.
The offset specifies the location along the gradient's control vector.
For example,
a linear gradient's control vector is from (x0,y0) to (x1,y1)
while a radial gradient's control vector is
from any point on the start circle
to the corresponding point on the end circle.
If two (or more) stops are specified with identical offset values,
they will be sorted
according to the order in which the stops are added
(stops added earlier before stops added later).
This can be useful for reliably making sharp color transitions
instead of the typical blend.
The color components and offset are in the range 0 to 1.
If the values passed in are outside that range, they will be clamped.
:param offset: Location along the gradient's control vector
:param red: Red component of the color.
:param green: Green component of the color.
:param blue: Blue component of the color.
:param alpha:
Alpha component of the color.
1 (the default) is opaque, 0 fully transparent.
:type offset: float
:type red: float
:type green: float
:type blue: float
:type alpha: float | [
"Adds",
"a",
"translucent",
"color",
"stop",
"to",
"a",
"gradient",
"pattern",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L219-L255 | train |
Kozea/cairocffi | cairocffi/fonts.py | _encode_string | def _encode_string(string):
"""Return a byte string, encoding Unicode with UTF-8."""
if not isinstance(string, bytes):
string = string.encode('utf8')
return ffi.new('char[]', string) | python | def _encode_string(string):
"""Return a byte string, encoding Unicode with UTF-8."""
if not isinstance(string, bytes):
string = string.encode('utf8')
return ffi.new('char[]', string) | [
"def",
"_encode_string",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"string",
"=",
"string",
".",
"encode",
"(",
"'utf8'",
")",
"return",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"string",
")"
] | Return a byte string, encoding Unicode with UTF-8. | [
"Return",
"a",
"byte",
"string",
"encoding",
"Unicode",
"with",
"UTF",
"-",
"8",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L16-L20 | train |
Kozea/cairocffi | cairocffi/fonts.py | ScaledFont.text_to_glyphs | def text_to_glyphs(self, x, y, text, with_clusters):
"""Converts a string of text to a list of glyphs,
optionally with cluster mapping,
that can be used to render later using this scaled font.
The output values can be readily passed to
:meth:`Context.show_text_glyphs`, :meth:`Context.show_glyphs`
or related methods,
assuming that the exact same :class:`ScaledFont`
is used for the operation.
:type x: float
:type y: float
:type with_clusters: bool
:param x: X position to place first glyph.
:param y: Y position to place first glyph.
:param text: The text to convert, as an Unicode or UTF-8 string.
:param with_clusters: Whether to compute the cluster mapping.
:returns:
A ``(glyphs, clusters, clusters_flags)`` tuple
if :obj:`with_clusters` is true, otherwise just :obj:`glyphs`.
See :meth:`Context.show_text_glyphs` for the data structure.
.. note::
This method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details
and :meth:`Context.show_glyphs`
for the "real" text display API in cairo.
"""
glyphs = ffi.new('cairo_glyph_t **', ffi.NULL)
num_glyphs = ffi.new('int *')
if with_clusters:
clusters = ffi.new('cairo_text_cluster_t **', ffi.NULL)
num_clusters = ffi.new('int *')
cluster_flags = ffi.new('cairo_text_cluster_flags_t *')
else:
clusters = ffi.NULL
num_clusters = ffi.NULL
cluster_flags = ffi.NULL
# TODO: Pass len_utf8 explicitly to support NULL bytes?
status = cairo.cairo_scaled_font_text_to_glyphs(
self._pointer, x, y, _encode_string(text), -1,
glyphs, num_glyphs, clusters, num_clusters, cluster_flags)
glyphs = ffi.gc(glyphs[0], _keepref(cairo, cairo.cairo_glyph_free))
if with_clusters:
clusters = ffi.gc(
clusters[0], _keepref(cairo, cairo.cairo_text_cluster_free))
_check_status(status)
glyphs = [
(glyph.index, glyph.x, glyph.y)
for i in range(num_glyphs[0])
for glyph in [glyphs[i]]]
if with_clusters:
clusters = [
(cluster.num_bytes, cluster.num_glyphs)
for i in range(num_clusters[0])
for cluster in [clusters[i]]]
return glyphs, clusters, cluster_flags[0]
else:
return glyphs | python | def text_to_glyphs(self, x, y, text, with_clusters):
"""Converts a string of text to a list of glyphs,
optionally with cluster mapping,
that can be used to render later using this scaled font.
The output values can be readily passed to
:meth:`Context.show_text_glyphs`, :meth:`Context.show_glyphs`
or related methods,
assuming that the exact same :class:`ScaledFont`
is used for the operation.
:type x: float
:type y: float
:type with_clusters: bool
:param x: X position to place first glyph.
:param y: Y position to place first glyph.
:param text: The text to convert, as an Unicode or UTF-8 string.
:param with_clusters: Whether to compute the cluster mapping.
:returns:
A ``(glyphs, clusters, clusters_flags)`` tuple
if :obj:`with_clusters` is true, otherwise just :obj:`glyphs`.
See :meth:`Context.show_text_glyphs` for the data structure.
.. note::
This method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details
and :meth:`Context.show_glyphs`
for the "real" text display API in cairo.
"""
glyphs = ffi.new('cairo_glyph_t **', ffi.NULL)
num_glyphs = ffi.new('int *')
if with_clusters:
clusters = ffi.new('cairo_text_cluster_t **', ffi.NULL)
num_clusters = ffi.new('int *')
cluster_flags = ffi.new('cairo_text_cluster_flags_t *')
else:
clusters = ffi.NULL
num_clusters = ffi.NULL
cluster_flags = ffi.NULL
# TODO: Pass len_utf8 explicitly to support NULL bytes?
status = cairo.cairo_scaled_font_text_to_glyphs(
self._pointer, x, y, _encode_string(text), -1,
glyphs, num_glyphs, clusters, num_clusters, cluster_flags)
glyphs = ffi.gc(glyphs[0], _keepref(cairo, cairo.cairo_glyph_free))
if with_clusters:
clusters = ffi.gc(
clusters[0], _keepref(cairo, cairo.cairo_text_cluster_free))
_check_status(status)
glyphs = [
(glyph.index, glyph.x, glyph.y)
for i in range(num_glyphs[0])
for glyph in [glyphs[i]]]
if with_clusters:
clusters = [
(cluster.num_bytes, cluster.num_glyphs)
for i in range(num_clusters[0])
for cluster in [clusters[i]]]
return glyphs, clusters, cluster_flags[0]
else:
return glyphs | [
"def",
"text_to_glyphs",
"(",
"self",
",",
"x",
",",
"y",
",",
"text",
",",
"with_clusters",
")",
":",
"glyphs",
"=",
"ffi",
".",
"new",
"(",
"'cairo_glyph_t **'",
",",
"ffi",
".",
"NULL",
")",
"num_glyphs",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"if",
"with_clusters",
":",
"clusters",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_cluster_t **'",
",",
"ffi",
".",
"NULL",
")",
"num_clusters",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"cluster_flags",
"=",
"ffi",
".",
"new",
"(",
"'cairo_text_cluster_flags_t *'",
")",
"else",
":",
"clusters",
"=",
"ffi",
".",
"NULL",
"num_clusters",
"=",
"ffi",
".",
"NULL",
"cluster_flags",
"=",
"ffi",
".",
"NULL",
"# TODO: Pass len_utf8 explicitly to support NULL bytes?",
"status",
"=",
"cairo",
".",
"cairo_scaled_font_text_to_glyphs",
"(",
"self",
".",
"_pointer",
",",
"x",
",",
"y",
",",
"_encode_string",
"(",
"text",
")",
",",
"-",
"1",
",",
"glyphs",
",",
"num_glyphs",
",",
"clusters",
",",
"num_clusters",
",",
"cluster_flags",
")",
"glyphs",
"=",
"ffi",
".",
"gc",
"(",
"glyphs",
"[",
"0",
"]",
",",
"_keepref",
"(",
"cairo",
",",
"cairo",
".",
"cairo_glyph_free",
")",
")",
"if",
"with_clusters",
":",
"clusters",
"=",
"ffi",
".",
"gc",
"(",
"clusters",
"[",
"0",
"]",
",",
"_keepref",
"(",
"cairo",
",",
"cairo",
".",
"cairo_text_cluster_free",
")",
")",
"_check_status",
"(",
"status",
")",
"glyphs",
"=",
"[",
"(",
"glyph",
".",
"index",
",",
"glyph",
".",
"x",
",",
"glyph",
".",
"y",
")",
"for",
"i",
"in",
"range",
"(",
"num_glyphs",
"[",
"0",
"]",
")",
"for",
"glyph",
"in",
"[",
"glyphs",
"[",
"i",
"]",
"]",
"]",
"if",
"with_clusters",
":",
"clusters",
"=",
"[",
"(",
"cluster",
".",
"num_bytes",
",",
"cluster",
".",
"num_glyphs",
")",
"for",
"i",
"in",
"range",
"(",
"num_clusters",
"[",
"0",
"]",
")",
"for",
"cluster",
"in",
"[",
"clusters",
"[",
"i",
"]",
"]",
"]",
"return",
"glyphs",
",",
"clusters",
",",
"cluster_flags",
"[",
"0",
"]",
"else",
":",
"return",
"glyphs"
] | Converts a string of text to a list of glyphs,
optionally with cluster mapping,
that can be used to render later using this scaled font.
The output values can be readily passed to
:meth:`Context.show_text_glyphs`, :meth:`Context.show_glyphs`
or related methods,
assuming that the exact same :class:`ScaledFont`
is used for the operation.
:type x: float
:type y: float
:type with_clusters: bool
:param x: X position to place first glyph.
:param y: Y position to place first glyph.
:param text: The text to convert, as an Unicode or UTF-8 string.
:param with_clusters: Whether to compute the cluster mapping.
:returns:
A ``(glyphs, clusters, clusters_flags)`` tuple
if :obj:`with_clusters` is true, otherwise just :obj:`glyphs`.
See :meth:`Context.show_text_glyphs` for the data structure.
.. note::
This method is part of
what the cairo designers call the "toy" text API.
It is convenient for short demos and simple programs,
but it is not expected to be adequate
for serious text-using applications.
See :ref:`fonts` for details
and :meth:`Context.show_glyphs`
for the "real" text display API in cairo. | [
"Converts",
"a",
"string",
"of",
"text",
"to",
"a",
"list",
"of",
"glyphs",
"optionally",
"with",
"cluster",
"mapping",
"that",
"can",
"be",
"used",
"to",
"render",
"later",
"using",
"this",
"scaled",
"font",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L301-L366 | train |
Kozea/cairocffi | cairocffi/fonts.py | FontOptions.set_variations | def set_variations(self, variations):
"""Sets the OpenType font variations for the font options object.
Font variations are specified as a string with a format that is similar
to the CSS font-variation-settings. The string contains a
comma-separated list of axis assignments, which each assignment
consists of a 4-character axis name and a value, separated by
whitespace and optional equals sign.
:param variations: the new font variations, or ``None``.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if variations is None:
variations = ffi.NULL
else:
variations = _encode_string(variations)
cairo.cairo_font_options_set_variations(self._pointer, variations)
self._check_status() | python | def set_variations(self, variations):
"""Sets the OpenType font variations for the font options object.
Font variations are specified as a string with a format that is similar
to the CSS font-variation-settings. The string contains a
comma-separated list of axis assignments, which each assignment
consists of a 4-character axis name and a value, separated by
whitespace and optional equals sign.
:param variations: the new font variations, or ``None``.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
if variations is None:
variations = ffi.NULL
else:
variations = _encode_string(variations)
cairo.cairo_font_options_set_variations(self._pointer, variations)
self._check_status() | [
"def",
"set_variations",
"(",
"self",
",",
"variations",
")",
":",
"if",
"variations",
"is",
"None",
":",
"variations",
"=",
"ffi",
".",
"NULL",
"else",
":",
"variations",
"=",
"_encode_string",
"(",
"variations",
")",
"cairo",
".",
"cairo_font_options_set_variations",
"(",
"self",
".",
"_pointer",
",",
"variations",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets the OpenType font variations for the font options object.
Font variations are specified as a string with a format that is similar
to the CSS font-variation-settings. The string contains a
comma-separated list of axis assignments, which each assignment
consists of a 4-character axis name and a value, separated by
whitespace and optional equals sign.
:param variations: the new font variations, or ``None``.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Sets",
"the",
"OpenType",
"font",
"variations",
"for",
"the",
"font",
"options",
"object",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L494-L515 | train |
Kozea/cairocffi | cairocffi/fonts.py | FontOptions.get_variations | def get_variations(self):
"""Gets the OpenType font variations for the font options object.
See :meth:`set_variations` for details about the
string format.
:return: the font variations for the font options object. The
returned string belongs to the ``options`` and must not be modified.
It is valid until either the font options object is destroyed or the
font variations in this object is modified with :meth:`set_variations`.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
variations = cairo.cairo_font_options_get_variations(self._pointer)
if variations != ffi.NULL:
return ffi.string(variations).decode('utf8', 'replace') | python | def get_variations(self):
"""Gets the OpenType font variations for the font options object.
See :meth:`set_variations` for details about the
string format.
:return: the font variations for the font options object. The
returned string belongs to the ``options`` and must not be modified.
It is valid until either the font options object is destroyed or the
font variations in this object is modified with :meth:`set_variations`.
*New in cairo 1.16.*
*New in cairocffi 0.9.*
"""
variations = cairo.cairo_font_options_get_variations(self._pointer)
if variations != ffi.NULL:
return ffi.string(variations).decode('utf8', 'replace') | [
"def",
"get_variations",
"(",
"self",
")",
":",
"variations",
"=",
"cairo",
".",
"cairo_font_options_get_variations",
"(",
"self",
".",
"_pointer",
")",
"if",
"variations",
"!=",
"ffi",
".",
"NULL",
":",
"return",
"ffi",
".",
"string",
"(",
"variations",
")",
".",
"decode",
"(",
"'utf8'",
",",
"'replace'",
")"
] | Gets the OpenType font variations for the font options object.
See :meth:`set_variations` for details about the
string format.
:return: the font variations for the font options object. The
returned string belongs to the ``options`` and must not be modified.
It is valid until either the font options object is destroyed or the
font variations in this object is modified with :meth:`set_variations`.
*New in cairo 1.16.*
*New in cairocffi 0.9.* | [
"Gets",
"the",
"OpenType",
"font",
"variations",
"for",
"the",
"font",
"options",
"object",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L517-L535 | train |
Kozea/cairocffi | cairocffi/pixbuf.py | decode_to_pixbuf | def decode_to_pixbuf(image_data, width=None, height=None):
"""Decode an image from memory with GDK-PixBuf.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`PixBuf` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format.
"""
loader = ffi.gc(
gdk_pixbuf.gdk_pixbuf_loader_new(), gobject.g_object_unref)
error = ffi.new('GError **')
if width and height:
gdk_pixbuf.gdk_pixbuf_loader_set_size(loader, width, height)
handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_write(
loader, ffi.new('guchar[]', image_data), len(image_data), error))
handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_close(loader, error))
format_ = gdk_pixbuf.gdk_pixbuf_loader_get_format(loader)
format_name = (
ffi.string(gdk_pixbuf.gdk_pixbuf_format_get_name(format_))
.decode('ascii')
if format_ != ffi.NULL else None)
pixbuf = gdk_pixbuf.gdk_pixbuf_loader_get_pixbuf(loader)
if pixbuf == ffi.NULL: # pragma: no cover
raise ImageLoadingError('Not enough image data (got a NULL pixbuf.)')
return Pixbuf(pixbuf), format_name | python | def decode_to_pixbuf(image_data, width=None, height=None):
"""Decode an image from memory with GDK-PixBuf.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`PixBuf` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format.
"""
loader = ffi.gc(
gdk_pixbuf.gdk_pixbuf_loader_new(), gobject.g_object_unref)
error = ffi.new('GError **')
if width and height:
gdk_pixbuf.gdk_pixbuf_loader_set_size(loader, width, height)
handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_write(
loader, ffi.new('guchar[]', image_data), len(image_data), error))
handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_close(loader, error))
format_ = gdk_pixbuf.gdk_pixbuf_loader_get_format(loader)
format_name = (
ffi.string(gdk_pixbuf.gdk_pixbuf_format_get_name(format_))
.decode('ascii')
if format_ != ffi.NULL else None)
pixbuf = gdk_pixbuf.gdk_pixbuf_loader_get_pixbuf(loader)
if pixbuf == ffi.NULL: # pragma: no cover
raise ImageLoadingError('Not enough image data (got a NULL pixbuf.)')
return Pixbuf(pixbuf), format_name | [
"def",
"decode_to_pixbuf",
"(",
"image_data",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"loader",
"=",
"ffi",
".",
"gc",
"(",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_new",
"(",
")",
",",
"gobject",
".",
"g_object_unref",
")",
"error",
"=",
"ffi",
".",
"new",
"(",
"'GError **'",
")",
"if",
"width",
"and",
"height",
":",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_set_size",
"(",
"loader",
",",
"width",
",",
"height",
")",
"handle_g_error",
"(",
"error",
",",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_write",
"(",
"loader",
",",
"ffi",
".",
"new",
"(",
"'guchar[]'",
",",
"image_data",
")",
",",
"len",
"(",
"image_data",
")",
",",
"error",
")",
")",
"handle_g_error",
"(",
"error",
",",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_close",
"(",
"loader",
",",
"error",
")",
")",
"format_",
"=",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_get_format",
"(",
"loader",
")",
"format_name",
"=",
"(",
"ffi",
".",
"string",
"(",
"gdk_pixbuf",
".",
"gdk_pixbuf_format_get_name",
"(",
"format_",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"if",
"format_",
"!=",
"ffi",
".",
"NULL",
"else",
"None",
")",
"pixbuf",
"=",
"gdk_pixbuf",
".",
"gdk_pixbuf_loader_get_pixbuf",
"(",
"loader",
")",
"if",
"pixbuf",
"==",
"ffi",
".",
"NULL",
":",
"# pragma: no cover",
"raise",
"ImageLoadingError",
"(",
"'Not enough image data (got a NULL pixbuf.)'",
")",
"return",
"Pixbuf",
"(",
"pixbuf",
")",
",",
"format_name"
] | Decode an image from memory with GDK-PixBuf.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`PixBuf` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format. | [
"Decode",
"an",
"image",
"from",
"memory",
"with",
"GDK",
"-",
"PixBuf",
".",
"The",
"file",
"format",
"is",
"detected",
"automatically",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L69-L102 | train |
Kozea/cairocffi | cairocffi/pixbuf.py | decode_to_image_surface | def decode_to_image_surface(image_data, width=None, height=None):
"""Decode an image from memory into a cairo surface.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`~cairocffi.ImageSurface` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format.
"""
pixbuf, format_name = decode_to_pixbuf(image_data, width, height)
surface = (
pixbuf_to_cairo_gdk(pixbuf) if gdk is not None
else pixbuf_to_cairo_slices(pixbuf) if not pixbuf.get_has_alpha()
else pixbuf_to_cairo_png(pixbuf))
return surface, format_name | python | def decode_to_image_surface(image_data, width=None, height=None):
"""Decode an image from memory into a cairo surface.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`~cairocffi.ImageSurface` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format.
"""
pixbuf, format_name = decode_to_pixbuf(image_data, width, height)
surface = (
pixbuf_to_cairo_gdk(pixbuf) if gdk is not None
else pixbuf_to_cairo_slices(pixbuf) if not pixbuf.get_has_alpha()
else pixbuf_to_cairo_png(pixbuf))
return surface, format_name | [
"def",
"decode_to_image_surface",
"(",
"image_data",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"pixbuf",
",",
"format_name",
"=",
"decode_to_pixbuf",
"(",
"image_data",
",",
"width",
",",
"height",
")",
"surface",
"=",
"(",
"pixbuf_to_cairo_gdk",
"(",
"pixbuf",
")",
"if",
"gdk",
"is",
"not",
"None",
"else",
"pixbuf_to_cairo_slices",
"(",
"pixbuf",
")",
"if",
"not",
"pixbuf",
".",
"get_has_alpha",
"(",
")",
"else",
"pixbuf_to_cairo_png",
"(",
"pixbuf",
")",
")",
"return",
"surface",
",",
"format_name"
] | Decode an image from memory into a cairo surface.
The file format is detected automatically.
:param image_data: A byte string
:param width: Integer width in pixels or None
:param height: Integer height in pixels or None
:returns:
A tuple of a new :class:`~cairocffi.ImageSurface` object
and the name of the detected image format.
:raises:
:exc:`ImageLoadingError` if the image data is invalid
or in an unsupported format. | [
"Decode",
"an",
"image",
"from",
"memory",
"into",
"a",
"cairo",
"surface",
".",
"The",
"file",
"format",
"is",
"detected",
"automatically",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L105-L125 | train |
Kozea/cairocffi | cairocffi/pixbuf.py | pixbuf_to_cairo_gdk | def pixbuf_to_cairo_gdk(pixbuf):
"""Convert from PixBuf to ImageSurface, using GDK.
This method is fastest but GDK is not always available.
"""
dummy_context = Context(ImageSurface(constants.FORMAT_ARGB32, 1, 1))
gdk.gdk_cairo_set_source_pixbuf(
dummy_context._pointer, pixbuf._pointer, 0, 0)
return dummy_context.get_source().get_surface() | python | def pixbuf_to_cairo_gdk(pixbuf):
"""Convert from PixBuf to ImageSurface, using GDK.
This method is fastest but GDK is not always available.
"""
dummy_context = Context(ImageSurface(constants.FORMAT_ARGB32, 1, 1))
gdk.gdk_cairo_set_source_pixbuf(
dummy_context._pointer, pixbuf._pointer, 0, 0)
return dummy_context.get_source().get_surface() | [
"def",
"pixbuf_to_cairo_gdk",
"(",
"pixbuf",
")",
":",
"dummy_context",
"=",
"Context",
"(",
"ImageSurface",
"(",
"constants",
".",
"FORMAT_ARGB32",
",",
"1",
",",
"1",
")",
")",
"gdk",
".",
"gdk_cairo_set_source_pixbuf",
"(",
"dummy_context",
".",
"_pointer",
",",
"pixbuf",
".",
"_pointer",
",",
"0",
",",
"0",
")",
"return",
"dummy_context",
".",
"get_source",
"(",
")",
".",
"get_surface",
"(",
")"
] | Convert from PixBuf to ImageSurface, using GDK.
This method is fastest but GDK is not always available. | [
"Convert",
"from",
"PixBuf",
"to",
"ImageSurface",
"using",
"GDK",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L128-L137 | train |
Kozea/cairocffi | cairocffi/pixbuf.py | pixbuf_to_cairo_slices | def pixbuf_to_cairo_slices(pixbuf):
"""Convert from PixBuf to ImageSurface, using slice-based byte swapping.
This method is 2~5x slower than GDK but does not support an alpha channel.
(cairo uses pre-multiplied alpha, but not Pixbuf.)
"""
assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE_RGB
assert pixbuf.get_n_channels() == 3
assert pixbuf.get_bits_per_sample() == 8
width = pixbuf.get_width()
height = pixbuf.get_height()
rowstride = pixbuf.get_rowstride()
pixels = ffi.buffer(pixbuf.get_pixels(), pixbuf.get_byte_length())
# TODO: remove this when cffi buffers support slicing with a stride.
pixels = pixels[:]
# Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB
cairo_stride = ImageSurface.format_stride_for_width(
constants.FORMAT_RGB24, width)
data = bytearray(cairo_stride * height)
big_endian = sys.byteorder == 'big'
pixbuf_row_length = width * 3 # stride == row_length + padding
cairo_row_length = width * 4 # stride == row_length + padding
alpha = b'\xff' * width # opaque
for y in range(height):
offset = rowstride * y
end = offset + pixbuf_row_length
red = pixels[offset:end:3]
green = pixels[offset + 1:end:3]
blue = pixels[offset + 2:end:3]
offset = cairo_stride * y
end = offset + cairo_row_length
if big_endian: # pragma: no cover
data[offset:end:4] = alpha
data[offset + 1:end:4] = red
data[offset + 2:end:4] = green
data[offset + 3:end:4] = blue
else:
data[offset + 3:end:4] = alpha
data[offset + 2:end:4] = red
data[offset + 1:end:4] = green
data[offset:end:4] = blue
data = array('B', data)
return ImageSurface(constants.FORMAT_RGB24,
width, height, data, cairo_stride) | python | def pixbuf_to_cairo_slices(pixbuf):
"""Convert from PixBuf to ImageSurface, using slice-based byte swapping.
This method is 2~5x slower than GDK but does not support an alpha channel.
(cairo uses pre-multiplied alpha, but not Pixbuf.)
"""
assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE_RGB
assert pixbuf.get_n_channels() == 3
assert pixbuf.get_bits_per_sample() == 8
width = pixbuf.get_width()
height = pixbuf.get_height()
rowstride = pixbuf.get_rowstride()
pixels = ffi.buffer(pixbuf.get_pixels(), pixbuf.get_byte_length())
# TODO: remove this when cffi buffers support slicing with a stride.
pixels = pixels[:]
# Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB
cairo_stride = ImageSurface.format_stride_for_width(
constants.FORMAT_RGB24, width)
data = bytearray(cairo_stride * height)
big_endian = sys.byteorder == 'big'
pixbuf_row_length = width * 3 # stride == row_length + padding
cairo_row_length = width * 4 # stride == row_length + padding
alpha = b'\xff' * width # opaque
for y in range(height):
offset = rowstride * y
end = offset + pixbuf_row_length
red = pixels[offset:end:3]
green = pixels[offset + 1:end:3]
blue = pixels[offset + 2:end:3]
offset = cairo_stride * y
end = offset + cairo_row_length
if big_endian: # pragma: no cover
data[offset:end:4] = alpha
data[offset + 1:end:4] = red
data[offset + 2:end:4] = green
data[offset + 3:end:4] = blue
else:
data[offset + 3:end:4] = alpha
data[offset + 2:end:4] = red
data[offset + 1:end:4] = green
data[offset:end:4] = blue
data = array('B', data)
return ImageSurface(constants.FORMAT_RGB24,
width, height, data, cairo_stride) | [
"def",
"pixbuf_to_cairo_slices",
"(",
"pixbuf",
")",
":",
"assert",
"pixbuf",
".",
"get_colorspace",
"(",
")",
"==",
"gdk_pixbuf",
".",
"GDK_COLORSPACE_RGB",
"assert",
"pixbuf",
".",
"get_n_channels",
"(",
")",
"==",
"3",
"assert",
"pixbuf",
".",
"get_bits_per_sample",
"(",
")",
"==",
"8",
"width",
"=",
"pixbuf",
".",
"get_width",
"(",
")",
"height",
"=",
"pixbuf",
".",
"get_height",
"(",
")",
"rowstride",
"=",
"pixbuf",
".",
"get_rowstride",
"(",
")",
"pixels",
"=",
"ffi",
".",
"buffer",
"(",
"pixbuf",
".",
"get_pixels",
"(",
")",
",",
"pixbuf",
".",
"get_byte_length",
"(",
")",
")",
"# TODO: remove this when cffi buffers support slicing with a stride.",
"pixels",
"=",
"pixels",
"[",
":",
"]",
"# Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB",
"cairo_stride",
"=",
"ImageSurface",
".",
"format_stride_for_width",
"(",
"constants",
".",
"FORMAT_RGB24",
",",
"width",
")",
"data",
"=",
"bytearray",
"(",
"cairo_stride",
"*",
"height",
")",
"big_endian",
"=",
"sys",
".",
"byteorder",
"==",
"'big'",
"pixbuf_row_length",
"=",
"width",
"*",
"3",
"# stride == row_length + padding",
"cairo_row_length",
"=",
"width",
"*",
"4",
"# stride == row_length + padding",
"alpha",
"=",
"b'\\xff'",
"*",
"width",
"# opaque",
"for",
"y",
"in",
"range",
"(",
"height",
")",
":",
"offset",
"=",
"rowstride",
"*",
"y",
"end",
"=",
"offset",
"+",
"pixbuf_row_length",
"red",
"=",
"pixels",
"[",
"offset",
":",
"end",
":",
"3",
"]",
"green",
"=",
"pixels",
"[",
"offset",
"+",
"1",
":",
"end",
":",
"3",
"]",
"blue",
"=",
"pixels",
"[",
"offset",
"+",
"2",
":",
"end",
":",
"3",
"]",
"offset",
"=",
"cairo_stride",
"*",
"y",
"end",
"=",
"offset",
"+",
"cairo_row_length",
"if",
"big_endian",
":",
"# pragma: no cover",
"data",
"[",
"offset",
":",
"end",
":",
"4",
"]",
"=",
"alpha",
"data",
"[",
"offset",
"+",
"1",
":",
"end",
":",
"4",
"]",
"=",
"red",
"data",
"[",
"offset",
"+",
"2",
":",
"end",
":",
"4",
"]",
"=",
"green",
"data",
"[",
"offset",
"+",
"3",
":",
"end",
":",
"4",
"]",
"=",
"blue",
"else",
":",
"data",
"[",
"offset",
"+",
"3",
":",
"end",
":",
"4",
"]",
"=",
"alpha",
"data",
"[",
"offset",
"+",
"2",
":",
"end",
":",
"4",
"]",
"=",
"red",
"data",
"[",
"offset",
"+",
"1",
":",
"end",
":",
"4",
"]",
"=",
"green",
"data",
"[",
"offset",
":",
"end",
":",
"4",
"]",
"=",
"blue",
"data",
"=",
"array",
"(",
"'B'",
",",
"data",
")",
"return",
"ImageSurface",
"(",
"constants",
".",
"FORMAT_RGB24",
",",
"width",
",",
"height",
",",
"data",
",",
"cairo_stride",
")"
] | Convert from PixBuf to ImageSurface, using slice-based byte swapping.
This method is 2~5x slower than GDK but does not support an alpha channel.
(cairo uses pre-multiplied alpha, but not Pixbuf.) | [
"Convert",
"from",
"PixBuf",
"to",
"ImageSurface",
"using",
"slice",
"-",
"based",
"byte",
"swapping",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L140-L187 | train |
Kozea/cairocffi | cairocffi/pixbuf.py | pixbuf_to_cairo_png | def pixbuf_to_cairo_png(pixbuf):
"""Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works.
"""
buffer_pointer = ffi.new('gchar **')
buffer_size = ffi.new('gsize *')
error = ffi.new('GError **')
handle_g_error(error, pixbuf.save_to_buffer(
buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error,
ffi.new('char[]', b'compression'), ffi.new('char[]', b'0'),
ffi.NULL))
png_bytes = ffi.buffer(buffer_pointer[0], buffer_size[0])
return ImageSurface.create_from_png(BytesIO(png_bytes)) | python | def pixbuf_to_cairo_png(pixbuf):
"""Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works.
"""
buffer_pointer = ffi.new('gchar **')
buffer_size = ffi.new('gsize *')
error = ffi.new('GError **')
handle_g_error(error, pixbuf.save_to_buffer(
buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error,
ffi.new('char[]', b'compression'), ffi.new('char[]', b'0'),
ffi.NULL))
png_bytes = ffi.buffer(buffer_pointer[0], buffer_size[0])
return ImageSurface.create_from_png(BytesIO(png_bytes)) | [
"def",
"pixbuf_to_cairo_png",
"(",
"pixbuf",
")",
":",
"buffer_pointer",
"=",
"ffi",
".",
"new",
"(",
"'gchar **'",
")",
"buffer_size",
"=",
"ffi",
".",
"new",
"(",
"'gsize *'",
")",
"error",
"=",
"ffi",
".",
"new",
"(",
"'GError **'",
")",
"handle_g_error",
"(",
"error",
",",
"pixbuf",
".",
"save_to_buffer",
"(",
"buffer_pointer",
",",
"buffer_size",
",",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"b'png'",
")",
",",
"error",
",",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"b'compression'",
")",
",",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"b'0'",
")",
",",
"ffi",
".",
"NULL",
")",
")",
"png_bytes",
"=",
"ffi",
".",
"buffer",
"(",
"buffer_pointer",
"[",
"0",
"]",
",",
"buffer_size",
"[",
"0",
"]",
")",
"return",
"ImageSurface",
".",
"create_from_png",
"(",
"BytesIO",
"(",
"png_bytes",
")",
")"
] | Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works. | [
"Convert",
"from",
"PixBuf",
"to",
"ImageSurface",
"by",
"going",
"through",
"the",
"PNG",
"format",
"."
] | 450853add7e32eea20985b6aa5f54d9cb3cd04fe | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/pixbuf.py#L190-L204 | train |
coderholic/pyradio | pyradio/player.py | probePlayer | def probePlayer(requested_player=''):
""" Probes the multimedia players which are available on the host
system."""
ret_player = None
if logger.isEnabledFor(logging.INFO):
logger.info("Probing available multimedia players...")
implementedPlayers = Player.__subclasses__()
if logger.isEnabledFor(logging.INFO):
logger.info("Implemented players: " +
", ".join([player.PLAYER_CMD
for player in implementedPlayers]))
if requested_player:
req = requested_player.split(',')
for r_player in req:
if r_player == 'vlc':
r_player = 'cvlc'
for player in implementedPlayers:
if player.PLAYER_CMD == r_player:
ret_player = check_player(player)
if ret_player is not None:
return ret_player
if ret_player is None:
if logger.isEnabledFor(logging.INFO):
logger.info('Requested player "{}" not supported'.format(r_player))
else:
for player in implementedPlayers:
ret_player = check_player(player)
if ret_player is not None:
break
return ret_player | python | def probePlayer(requested_player=''):
""" Probes the multimedia players which are available on the host
system."""
ret_player = None
if logger.isEnabledFor(logging.INFO):
logger.info("Probing available multimedia players...")
implementedPlayers = Player.__subclasses__()
if logger.isEnabledFor(logging.INFO):
logger.info("Implemented players: " +
", ".join([player.PLAYER_CMD
for player in implementedPlayers]))
if requested_player:
req = requested_player.split(',')
for r_player in req:
if r_player == 'vlc':
r_player = 'cvlc'
for player in implementedPlayers:
if player.PLAYER_CMD == r_player:
ret_player = check_player(player)
if ret_player is not None:
return ret_player
if ret_player is None:
if logger.isEnabledFor(logging.INFO):
logger.info('Requested player "{}" not supported'.format(r_player))
else:
for player in implementedPlayers:
ret_player = check_player(player)
if ret_player is not None:
break
return ret_player | [
"def",
"probePlayer",
"(",
"requested_player",
"=",
"''",
")",
":",
"ret_player",
"=",
"None",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"\"Probing available multimedia players...\"",
")",
"implementedPlayers",
"=",
"Player",
".",
"__subclasses__",
"(",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"\"Implemented players: \"",
"+",
"\", \"",
".",
"join",
"(",
"[",
"player",
".",
"PLAYER_CMD",
"for",
"player",
"in",
"implementedPlayers",
"]",
")",
")",
"if",
"requested_player",
":",
"req",
"=",
"requested_player",
".",
"split",
"(",
"','",
")",
"for",
"r_player",
"in",
"req",
":",
"if",
"r_player",
"==",
"'vlc'",
":",
"r_player",
"=",
"'cvlc'",
"for",
"player",
"in",
"implementedPlayers",
":",
"if",
"player",
".",
"PLAYER_CMD",
"==",
"r_player",
":",
"ret_player",
"=",
"check_player",
"(",
"player",
")",
"if",
"ret_player",
"is",
"not",
"None",
":",
"return",
"ret_player",
"if",
"ret_player",
"is",
"None",
":",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"'Requested player \"{}\" not supported'",
".",
"format",
"(",
"r_player",
")",
")",
"else",
":",
"for",
"player",
"in",
"implementedPlayers",
":",
"ret_player",
"=",
"check_player",
"(",
"player",
")",
"if",
"ret_player",
"is",
"not",
"None",
":",
"break",
"return",
"ret_player"
] | Probes the multimedia players which are available on the host
system. | [
"Probes",
"the",
"multimedia",
"players",
"which",
"are",
"available",
"on",
"the",
"host",
"system",
"."
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L763-L793 | train |
coderholic/pyradio | pyradio/player.py | Player.play | def play(self, name, streamUrl, encoding = ''):
""" use a multimedia player to play a stream """
self.close()
self.name = name
self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''}
self.muted = False
self.show_volume = True
self.title_prefix = ''
self.playback_is_on = False
self.outputStream.write('Station: "{}"'.format(name), self.status_update_lock)
if logger.isEnabledFor(logging.INFO):
logger.info('Selected Station: "{}"'.format(name))
if encoding:
self._station_encoding = encoding
else:
self._station_encoding = 'utf-8'
opts = []
isPlayList = streamUrl.split("?")[0][-3:] in ['m3u', 'pls']
opts = self._buildStartOpts(streamUrl, isPlayList)
self.process = subprocess.Popen(opts, shell=False,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT)
t = threading.Thread(target=self.updateStatus, args=(self.status_update_lock, ))
t.start()
# start playback check timer thread
try:
self.connection_timeout_thread = threading.Timer(self.playback_timeout, self.playback_timeout_handler)
self.connection_timeout_thread.start()
except:
self.connection_timeout_thread = None
if (logger.isEnabledFor(logging.ERROR)):
logger.error("playback detection thread start failed")
if logger.isEnabledFor(logging.INFO):
logger.info("Player started") | python | def play(self, name, streamUrl, encoding = ''):
""" use a multimedia player to play a stream """
self.close()
self.name = name
self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''}
self.muted = False
self.show_volume = True
self.title_prefix = ''
self.playback_is_on = False
self.outputStream.write('Station: "{}"'.format(name), self.status_update_lock)
if logger.isEnabledFor(logging.INFO):
logger.info('Selected Station: "{}"'.format(name))
if encoding:
self._station_encoding = encoding
else:
self._station_encoding = 'utf-8'
opts = []
isPlayList = streamUrl.split("?")[0][-3:] in ['m3u', 'pls']
opts = self._buildStartOpts(streamUrl, isPlayList)
self.process = subprocess.Popen(opts, shell=False,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT)
t = threading.Thread(target=self.updateStatus, args=(self.status_update_lock, ))
t.start()
# start playback check timer thread
try:
self.connection_timeout_thread = threading.Timer(self.playback_timeout, self.playback_timeout_handler)
self.connection_timeout_thread.start()
except:
self.connection_timeout_thread = None
if (logger.isEnabledFor(logging.ERROR)):
logger.error("playback detection thread start failed")
if logger.isEnabledFor(logging.INFO):
logger.info("Player started") | [
"def",
"play",
"(",
"self",
",",
"name",
",",
"streamUrl",
",",
"encoding",
"=",
"''",
")",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"oldUserInput",
"=",
"{",
"'Input'",
":",
"''",
",",
"'Volume'",
":",
"''",
",",
"'Title'",
":",
"''",
"}",
"self",
".",
"muted",
"=",
"False",
"self",
".",
"show_volume",
"=",
"True",
"self",
".",
"title_prefix",
"=",
"''",
"self",
".",
"playback_is_on",
"=",
"False",
"self",
".",
"outputStream",
".",
"write",
"(",
"'Station: \"{}\"'",
".",
"format",
"(",
"name",
")",
",",
"self",
".",
"status_update_lock",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"'Selected Station: \"{}\"'",
".",
"format",
"(",
"name",
")",
")",
"if",
"encoding",
":",
"self",
".",
"_station_encoding",
"=",
"encoding",
"else",
":",
"self",
".",
"_station_encoding",
"=",
"'utf-8'",
"opts",
"=",
"[",
"]",
"isPlayList",
"=",
"streamUrl",
".",
"split",
"(",
"\"?\"",
")",
"[",
"0",
"]",
"[",
"-",
"3",
":",
"]",
"in",
"[",
"'m3u'",
",",
"'pls'",
"]",
"opts",
"=",
"self",
".",
"_buildStartOpts",
"(",
"streamUrl",
",",
"isPlayList",
")",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"opts",
",",
"shell",
"=",
"False",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"updateStatus",
",",
"args",
"=",
"(",
"self",
".",
"status_update_lock",
",",
")",
")",
"t",
".",
"start",
"(",
")",
"# start playback check timer thread",
"try",
":",
"self",
".",
"connection_timeout_thread",
"=",
"threading",
".",
"Timer",
"(",
"self",
".",
"playback_timeout",
",",
"self",
".",
"playback_timeout_handler",
")",
"self",
".",
"connection_timeout_thread",
".",
"start",
"(",
")",
"except",
":",
"self",
".",
"connection_timeout_thread",
"=",
"None",
"if",
"(",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"ERROR",
")",
")",
":",
"logger",
".",
"error",
"(",
"\"playback detection thread start failed\"",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"logger",
".",
"info",
"(",
"\"Player started\"",
")"
] | use a multimedia player to play a stream | [
"use",
"a",
"multimedia",
"player",
"to",
"play",
"a",
"stream"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L285-L319 | train |
coderholic/pyradio | pyradio/player.py | Player._sendCommand | def _sendCommand(self, command):
""" send keystroke command to player """
if(self.process is not None):
try:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Command: {}".format(command).strip())
self.process.stdin.write(command.encode('utf-8', 'replace'))
self.process.stdin.flush()
except:
msg = "Error when sending: {}"
if logger.isEnabledFor(logging.ERROR):
logger.error(msg.format(command).strip(), exc_info=True) | python | def _sendCommand(self, command):
""" send keystroke command to player """
if(self.process is not None):
try:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Command: {}".format(command).strip())
self.process.stdin.write(command.encode('utf-8', 'replace'))
self.process.stdin.flush()
except:
msg = "Error when sending: {}"
if logger.isEnabledFor(logging.ERROR):
logger.error(msg.format(command).strip(), exc_info=True) | [
"def",
"_sendCommand",
"(",
"self",
",",
"command",
")",
":",
"if",
"(",
"self",
".",
"process",
"is",
"not",
"None",
")",
":",
"try",
":",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"\"Command: {}\"",
".",
"format",
"(",
"command",
")",
".",
"strip",
"(",
")",
")",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"command",
".",
"encode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")",
"self",
".",
"process",
".",
"stdin",
".",
"flush",
"(",
")",
"except",
":",
"msg",
"=",
"\"Error when sending: {}\"",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"ERROR",
")",
":",
"logger",
".",
"error",
"(",
"msg",
".",
"format",
"(",
"command",
")",
".",
"strip",
"(",
")",
",",
"exc_info",
"=",
"True",
")"
] | send keystroke command to player | [
"send",
"keystroke",
"command",
"to",
"player"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L321-L333 | train |
coderholic/pyradio | pyradio/player.py | MpvPlayer._format_title_string | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) | python | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) | [
"def",
"_format_title_string",
"(",
"self",
",",
"title_string",
")",
":",
"return",
"self",
".",
"_title_string_format_text_tag",
"(",
"title_string",
".",
"replace",
"(",
"self",
".",
"icy_tokkens",
"[",
"0",
"]",
",",
"self",
".",
"icy_title_prefix",
")",
")"
] | format mpv's title | [
"format",
"mpv",
"s",
"title"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L529-L531 | train |
coderholic/pyradio | pyradio/player.py | MpPlayer._format_title_string | def _format_title_string(self, title_string):
""" format mplayer's title """
if "StreamTitle='" in title_string:
tmp = title_string[title_string.find("StreamTitle='"):].replace("StreamTitle='", self.icy_title_prefix)
ret_string = tmp[:tmp.find("';")]
else:
ret_string = title_string
if '"artist":"' in ret_string:
""" work on format:
ICY Info: START_SONG='{"artist":"Clelia Cafiero","title":"M. Mussorgsky-Quadri di un'esposizione"}';
Fund on "ClassicaViva Web Radio: Classical"
"""
ret_string = self.icy_title_prefix + ret_string[ret_string.find('"artist":')+10:].replace('","title":"', ' - ').replace('"}\';', '')
return self._title_string_format_text_tag(ret_string) | python | def _format_title_string(self, title_string):
""" format mplayer's title """
if "StreamTitle='" in title_string:
tmp = title_string[title_string.find("StreamTitle='"):].replace("StreamTitle='", self.icy_title_prefix)
ret_string = tmp[:tmp.find("';")]
else:
ret_string = title_string
if '"artist":"' in ret_string:
""" work on format:
ICY Info: START_SONG='{"artist":"Clelia Cafiero","title":"M. Mussorgsky-Quadri di un'esposizione"}';
Fund on "ClassicaViva Web Radio: Classical"
"""
ret_string = self.icy_title_prefix + ret_string[ret_string.find('"artist":')+10:].replace('","title":"', ' - ').replace('"}\';', '')
return self._title_string_format_text_tag(ret_string) | [
"def",
"_format_title_string",
"(",
"self",
",",
"title_string",
")",
":",
"if",
"\"StreamTitle='\"",
"in",
"title_string",
":",
"tmp",
"=",
"title_string",
"[",
"title_string",
".",
"find",
"(",
"\"StreamTitle='\"",
")",
":",
"]",
".",
"replace",
"(",
"\"StreamTitle='\"",
",",
"self",
".",
"icy_title_prefix",
")",
"ret_string",
"=",
"tmp",
"[",
":",
"tmp",
".",
"find",
"(",
"\"';\"",
")",
"]",
"else",
":",
"ret_string",
"=",
"title_string",
"if",
"'\"artist\":\"'",
"in",
"ret_string",
":",
"\"\"\" work on format:\n ICY Info: START_SONG='{\"artist\":\"Clelia Cafiero\",\"title\":\"M. Mussorgsky-Quadri di un'esposizione\"}';\n Fund on \"ClassicaViva Web Radio: Classical\"\n \"\"\"",
"ret_string",
"=",
"self",
".",
"icy_title_prefix",
"+",
"ret_string",
"[",
"ret_string",
".",
"find",
"(",
"'\"artist\":'",
")",
"+",
"10",
":",
"]",
".",
"replace",
"(",
"'\",\"title\":\"'",
",",
"' - '",
")",
".",
"replace",
"(",
"'\"}\\';'",
",",
"''",
")",
"return",
"self",
".",
"_title_string_format_text_tag",
"(",
"ret_string",
")"
] | format mplayer's title | [
"format",
"mplayer",
"s",
"title"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L625-L638 | train |
coderholic/pyradio | pyradio/player.py | MpPlayer._format_volume_string | def _format_volume_string(self, volume_string):
""" format mplayer's volume """
return '[' + volume_string[volume_string.find(self.volume_string):].replace(' %','%').replace('ume', '')+'] ' | python | def _format_volume_string(self, volume_string):
""" format mplayer's volume """
return '[' + volume_string[volume_string.find(self.volume_string):].replace(' %','%').replace('ume', '')+'] ' | [
"def",
"_format_volume_string",
"(",
"self",
",",
"volume_string",
")",
":",
"return",
"'['",
"+",
"volume_string",
"[",
"volume_string",
".",
"find",
"(",
"self",
".",
"volume_string",
")",
":",
"]",
".",
"replace",
"(",
"' %'",
",",
"'%'",
")",
".",
"replace",
"(",
"'ume'",
",",
"''",
")",
"+",
"'] '"
] | format mplayer's volume | [
"format",
"mplayer",
"s",
"volume"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L640-L642 | train |
coderholic/pyradio | pyradio/player.py | VlcPlayer._format_volume_string | def _format_volume_string(self, volume_string):
""" format vlc's volume """
self.actual_volume = int(volume_string.split(self.volume_string)[1].split(',')[0].split()[0])
return '[Vol: {}%] '.format(int(100 * self.actual_volume / self.max_volume)) | python | def _format_volume_string(self, volume_string):
""" format vlc's volume """
self.actual_volume = int(volume_string.split(self.volume_string)[1].split(',')[0].split()[0])
return '[Vol: {}%] '.format(int(100 * self.actual_volume / self.max_volume)) | [
"def",
"_format_volume_string",
"(",
"self",
",",
"volume_string",
")",
":",
"self",
".",
"actual_volume",
"=",
"int",
"(",
"volume_string",
".",
"split",
"(",
"self",
".",
"volume_string",
")",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"return",
"'[Vol: {}%] '",
".",
"format",
"(",
"int",
"(",
"100",
"*",
"self",
".",
"actual_volume",
"/",
"self",
".",
"max_volume",
")",
")"
] | format vlc's volume | [
"format",
"vlc",
"s",
"volume"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L706-L709 | train |
coderholic/pyradio | pyradio/player.py | VlcPlayer._format_title_string | def _format_title_string(self, title_string):
""" format vlc's title """
sp = title_string.split(self.icy_tokkens[0])
if sp[0] == title_string:
ret_string = title_string
else:
ret_string = self.icy_title_prefix + sp[1]
return self._title_string_format_text_tag(ret_string) | python | def _format_title_string(self, title_string):
""" format vlc's title """
sp = title_string.split(self.icy_tokkens[0])
if sp[0] == title_string:
ret_string = title_string
else:
ret_string = self.icy_title_prefix + sp[1]
return self._title_string_format_text_tag(ret_string) | [
"def",
"_format_title_string",
"(",
"self",
",",
"title_string",
")",
":",
"sp",
"=",
"title_string",
".",
"split",
"(",
"self",
".",
"icy_tokkens",
"[",
"0",
"]",
")",
"if",
"sp",
"[",
"0",
"]",
"==",
"title_string",
":",
"ret_string",
"=",
"title_string",
"else",
":",
"ret_string",
"=",
"self",
".",
"icy_title_prefix",
"+",
"sp",
"[",
"1",
"]",
"return",
"self",
".",
"_title_string_format_text_tag",
"(",
"ret_string",
")"
] | format vlc's title | [
"format",
"vlc",
"s",
"title"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L711-L718 | train |
coderholic/pyradio | pyradio/player.py | VlcPlayer._is_accepted_input | def _is_accepted_input(self, input_string):
""" vlc input filtering """
ret = False
accept_filter = (self.volume_string, "http stream debug: ")
reject_filter = ()
for n in accept_filter:
if n in input_string:
ret = True
break
if ret:
for n in reject_filter:
if n in input_string:
ret = False
break
return ret | python | def _is_accepted_input(self, input_string):
""" vlc input filtering """
ret = False
accept_filter = (self.volume_string, "http stream debug: ")
reject_filter = ()
for n in accept_filter:
if n in input_string:
ret = True
break
if ret:
for n in reject_filter:
if n in input_string:
ret = False
break
return ret | [
"def",
"_is_accepted_input",
"(",
"self",
",",
"input_string",
")",
":",
"ret",
"=",
"False",
"accept_filter",
"=",
"(",
"self",
".",
"volume_string",
",",
"\"http stream debug: \"",
")",
"reject_filter",
"=",
"(",
")",
"for",
"n",
"in",
"accept_filter",
":",
"if",
"n",
"in",
"input_string",
":",
"ret",
"=",
"True",
"break",
"if",
"ret",
":",
"for",
"n",
"in",
"reject_filter",
":",
"if",
"n",
"in",
"input_string",
":",
"ret",
"=",
"False",
"break",
"return",
"ret"
] | vlc input filtering | [
"vlc",
"input",
"filtering"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L720-L734 | train |
coderholic/pyradio | pyradio/player.py | VlcPlayer._no_mute_on_stop_playback | def _no_mute_on_stop_playback(self):
""" make sure vlc does not stop muted """
if self.ctrl_c_pressed:
return
if self.isPlaying():
if self.actual_volume == -1:
self._get_volume()
while self.actual_volume == -1:
pass
if self.actual_volume == 0:
self.actual_volume = int(self.max_volume*0.25)
self._sendCommand('volume {}\n'.format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Unmuting VLC on exit: {} (25%)'.format(self.actual_volume))
elif self.muted:
if self.actual_volume > 0:
self._sendCommand('volume {}\n'.format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('VLC volume restored on exit: {0} ({1}%)'.format(self.actual_volume, int(100 * self.actual_volume / self.max_volume)))
self.show_volume = True | python | def _no_mute_on_stop_playback(self):
""" make sure vlc does not stop muted """
if self.ctrl_c_pressed:
return
if self.isPlaying():
if self.actual_volume == -1:
self._get_volume()
while self.actual_volume == -1:
pass
if self.actual_volume == 0:
self.actual_volume = int(self.max_volume*0.25)
self._sendCommand('volume {}\n'.format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Unmuting VLC on exit: {} (25%)'.format(self.actual_volume))
elif self.muted:
if self.actual_volume > 0:
self._sendCommand('volume {}\n'.format(self.actual_volume))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('VLC volume restored on exit: {0} ({1}%)'.format(self.actual_volume, int(100 * self.actual_volume / self.max_volume)))
self.show_volume = True | [
"def",
"_no_mute_on_stop_playback",
"(",
"self",
")",
":",
"if",
"self",
".",
"ctrl_c_pressed",
":",
"return",
"if",
"self",
".",
"isPlaying",
"(",
")",
":",
"if",
"self",
".",
"actual_volume",
"==",
"-",
"1",
":",
"self",
".",
"_get_volume",
"(",
")",
"while",
"self",
".",
"actual_volume",
"==",
"-",
"1",
":",
"pass",
"if",
"self",
".",
"actual_volume",
"==",
"0",
":",
"self",
".",
"actual_volume",
"=",
"int",
"(",
"self",
".",
"max_volume",
"*",
"0.25",
")",
"self",
".",
"_sendCommand",
"(",
"'volume {}\\n'",
".",
"format",
"(",
"self",
".",
"actual_volume",
")",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"'Unmuting VLC on exit: {} (25%)'",
".",
"format",
"(",
"self",
".",
"actual_volume",
")",
")",
"elif",
"self",
".",
"muted",
":",
"if",
"self",
".",
"actual_volume",
">",
"0",
":",
"self",
".",
"_sendCommand",
"(",
"'volume {}\\n'",
".",
"format",
"(",
"self",
".",
"actual_volume",
")",
")",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"debug",
"(",
"'VLC volume restored on exit: {0} ({1}%)'",
".",
"format",
"(",
"self",
".",
"actual_volume",
",",
"int",
"(",
"100",
"*",
"self",
".",
"actual_volume",
"/",
"self",
".",
"max_volume",
")",
")",
")",
"self",
".",
"show_volume",
"=",
"True"
] | make sure vlc does not stop muted | [
"make",
"sure",
"vlc",
"does",
"not",
"stop",
"muted"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L741-L761 | train |
coderholic/pyradio | pyradio/config.py | PyRadioStations._check_stations_csv | def _check_stations_csv(self, usr, root):
''' Reclocate a stations.csv copy in user home for easy manage.
E.g. not need sudo when you add new station, etc '''
if path.exists(path.join(usr, 'stations.csv')):
return
else:
copyfile(root, path.join(usr, 'stations.csv')) | python | def _check_stations_csv(self, usr, root):
''' Reclocate a stations.csv copy in user home for easy manage.
E.g. not need sudo when you add new station, etc '''
if path.exists(path.join(usr, 'stations.csv')):
return
else:
copyfile(root, path.join(usr, 'stations.csv')) | [
"def",
"_check_stations_csv",
"(",
"self",
",",
"usr",
",",
"root",
")",
":",
"if",
"path",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"usr",
",",
"'stations.csv'",
")",
")",
":",
"return",
"else",
":",
"copyfile",
"(",
"root",
",",
"path",
".",
"join",
"(",
"usr",
",",
"'stations.csv'",
")",
")"
] | Reclocate a stations.csv copy in user home for easy manage.
E.g. not need sudo when you add new station, etc | [
"Reclocate",
"a",
"stations",
".",
"csv",
"copy",
"in",
"user",
"home",
"for",
"easy",
"manage",
".",
"E",
".",
"g",
".",
"not",
"need",
"sudo",
"when",
"you",
"add",
"new",
"station",
"etc"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/config.py#L89-L96 | train |
coderholic/pyradio | pyradio/config.py | PyRadioStations._is_playlist_in_config_dir | def _is_playlist_in_config_dir(self):
""" Check if a csv file is in the config dir """
if path.dirname(self.stations_file) == self.stations_dir:
self.foreign_file = False
self.foreign_filename_only_no_extension = ''
else:
self.foreign_file = True
self.foreign_filename_only_no_extension = self.stations_filename_only_no_extension
self.foreign_copy_asked = False | python | def _is_playlist_in_config_dir(self):
""" Check if a csv file is in the config dir """
if path.dirname(self.stations_file) == self.stations_dir:
self.foreign_file = False
self.foreign_filename_only_no_extension = ''
else:
self.foreign_file = True
self.foreign_filename_only_no_extension = self.stations_filename_only_no_extension
self.foreign_copy_asked = False | [
"def",
"_is_playlist_in_config_dir",
"(",
"self",
")",
":",
"if",
"path",
".",
"dirname",
"(",
"self",
".",
"stations_file",
")",
"==",
"self",
".",
"stations_dir",
":",
"self",
".",
"foreign_file",
"=",
"False",
"self",
".",
"foreign_filename_only_no_extension",
"=",
"''",
"else",
":",
"self",
".",
"foreign_file",
"=",
"True",
"self",
".",
"foreign_filename_only_no_extension",
"=",
"self",
".",
"stations_filename_only_no_extension",
"self",
".",
"foreign_copy_asked",
"=",
"False"
] | Check if a csv file is in the config dir | [
"Check",
"if",
"a",
"csv",
"file",
"is",
"in",
"the",
"config",
"dir"
] | c5219d350bccbccd49dbd627c1f886a952ea1963 | https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/config.py#L134-L142 | train |