sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def set_text(self, text, length=-1):
"""set_text(text, length=-1)
{{ all }}
"""
Gtk.TextBuffer.set_text(self, text, length) | set_text(text, length=-1)
{{ all }} | entailment |
def insert(self, iter, text, length=-1):
"""insert(iter, text, length=-1)
{{ all }}
"""
Gtk.TextBuffer.insert(self, iter, text, length) | insert(iter, text, length=-1)
{{ all }} | entailment |
def get_iter(self, path):
"""
:param path: the :obj:`Gtk.TreePath`-struct
:type path: :obj:`Gtk.TreePath`
:raises: :class:`ValueError` if `path` doesn't exist
:returns: a :obj:`Gtk.TreeIter`
:rtype: :obj:`Gtk.TreeIter`
Returns an iterator pointing to `path`. If ... | :param path: the :obj:`Gtk.TreePath`-struct
:type path: :obj:`Gtk.TreePath`
:raises: :class:`ValueError` if `path` doesn't exist
:returns: a :obj:`Gtk.TreeIter`
:rtype: :obj:`Gtk.TreeIter`
Returns an iterator pointing to `path`. If `path` does not exist
:class:`ValueErr... | entailment |
def iter_next(self, iter):
"""
:param iter: the :obj:`Gtk.TreeIter`-struct
:type iter: :obj:`Gtk.TreeIter`
:returns: a :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: :obj:`Gtk.TreeIter` or :obj:`None`
Returns an iterator pointing to the node following `iter` at the
... | :param iter: the :obj:`Gtk.TreeIter`-struct
:type iter: :obj:`Gtk.TreeIter`
:returns: a :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: :obj:`Gtk.TreeIter` or :obj:`None`
Returns an iterator pointing to the node following `iter` at the
current level.
If there is no next `it... | entailment |
def iter_previous(self, iter):
"""
:param iter: the :obj:`Gtk.TreeIter`-struct
:type iter: :obj:`Gtk.TreeIter`
:returns: a :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: :obj:`Gtk.TreeIter` or :obj:`None`
Returns an iterator pointing to the previous node at the current leve... | :param iter: the :obj:`Gtk.TreeIter`-struct
:type iter: :obj:`Gtk.TreeIter`
:returns: a :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: :obj:`Gtk.TreeIter` or :obj:`None`
Returns an iterator pointing to the previous node at the current level.
If there is no previous `iter`, :obj:`N... | entailment |
def set_row(self, treeiter, row):
"""
:param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param row: a list of values for each column
:type row: [:obj:`object`]
Sets all values of a row pointed to by `treeiter` from a list of
values pas... | :param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param row: a list of values for each column
:type row: [:obj:`object`]
Sets all values of a row pointed to by `treeiter` from a list of
values passes as `row`. The length of the row has to match the n... | entailment |
def _convert_value(self, column, value):
'''Convert value to a GObject.Value of the expected type'''
if isinstance(value, GObject.Value):
return value
return GObject.Value(self.get_column_type(column), value) | Convert value to a GObject.Value of the expected type | entailment |
def get(self, treeiter, *columns):
"""
:param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param \\*columns: a list of column indices to fetch
:type columns: (:obj:`int`)
Returns a tuple of all values specified by their indices in `columns`
... | :param treeiter: the :obj:`Gtk.TreeIter`
:type treeiter: :obj:`Gtk.TreeIter`
:param \\*columns: a list of column indices to fetch
:type columns: (:obj:`int`)
Returns a tuple of all values specified by their indices in `columns`
in the order the indices are contained in `columns... | entailment |
def append(self, row=None):
"""append(row=None)
:param row: a list of values to apply to the newly append row or :obj:`None`
:type row: [:obj:`object`] or :obj:`None`
:returns: :obj:`Gtk.TreeIter` of the appended row
:rtype: :obj:`Gtk.TreeIter`
If `row` is :obj:`None` ... | append(row=None)
:param row: a list of values to apply to the newly append row or :obj:`None`
:type row: [:obj:`object`] or :obj:`None`
:returns: :obj:`Gtk.TreeIter` of the appended row
:rtype: :obj:`Gtk.TreeIter`
If `row` is :obj:`None` the appended row will be empty and to f... | entailment |
def insert_before(self, sibling, row=None):
"""insert_before(sibling, row=None)
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling: :obj:`Gtk.TreeIter` or :obj:`None`
:param row: a list of values to apply to the newly inserted row or :obj:`None`
:type row... | insert_before(sibling, row=None)
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling: :obj:`Gtk.TreeIter` or :obj:`None`
:param row: a list of values to apply to the newly inserted row or :obj:`None`
:type row: [:obj:`object`] or :obj:`None`
:returns: :ob... | entailment |
def insert_after(self, sibling, row=None):
"""insert_after(sibling, row=None)
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling: :obj:`Gtk.TreeIter` or :obj:`None`
:param row: a list of values to apply to the newly inserted row or :obj:`None`
:type row: ... | insert_after(sibling, row=None)
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling: :obj:`Gtk.TreeIter` or :obj:`None`
:param row: a list of values to apply to the newly inserted row or :obj:`None`
:type row: [:obj:`object`] or :obj:`None`
:returns: :obj... | entailment |
def set_value(self, treeiter, column, value):
"""
{{ all }}
`value` can also be a Python value and will be converted to a
:obj:`GObject.Value` using the corresponding column type (See
:obj:`Gtk.ListStore.set_column_types`\\()).
"""
value = self._convert_value(co... | {{ all }}
`value` can also be a Python value and will be converted to a
:obj:`GObject.Value` using the corresponding column type (See
:obj:`Gtk.ListStore.set_column_types`\\()). | entailment |
def get_next(self):
"""Returns the next :obj:`Gtk.TreeModelRow` or None"""
next_iter = self.model.iter_next(self.iter)
if next_iter:
return TreeModelRow(self.model, next_iter) | Returns the next :obj:`Gtk.TreeModelRow` or None | entailment |
def get_previous(self):
"""Returns the previous :obj:`Gtk.TreeModelRow` or None"""
prev_iter = self.model.iter_previous(self.iter)
if prev_iter:
return TreeModelRow(self.model, prev_iter) | Returns the previous :obj:`Gtk.TreeModelRow` or None | entailment |
def get_parent(self):
"""Returns the parent :obj:`Gtk.TreeModelRow` or htis row or None"""
parent_iter = self.model.iter_parent(self.iter)
if parent_iter:
return TreeModelRow(self.model, parent_iter) | Returns the parent :obj:`Gtk.TreeModelRow` or htis row or None | entailment |
def iterchildren(self):
"""Returns a :obj:`Gtk.TreeModelRowIter` for the row's children"""
child_iter = self.model.iter_children(self.iter)
return TreeModelRowIter(self.model, child_iter) | Returns a :obj:`Gtk.TreeModelRowIter` for the row's children | entailment |
def insert(self, parent, position, row=None):
"""insert(parent, position, row=None)
:param parent:
A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type parent: :obj:`Gtk.TreeIter` or :obj:`None`
:param position:
position to insert the new row, or -1 for last
... | insert(parent, position, row=None)
:param parent:
A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type parent: :obj:`Gtk.TreeIter` or :obj:`None`
:param position:
position to insert the new row, or -1 for last
:type position: :obj:`int`
:param row: a list ... | entailment |
def insert_before(self, parent, sibling, row=None):
"""insert_before(parent, sibling, row=None)
:param parent: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type parent: :obj:`Gtk.TreeIter` or :obj:`None`
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling:... | insert_before(parent, sibling, row=None)
:param parent: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type parent: :obj:`Gtk.TreeIter` or :obj:`None`
:param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
:type sibling: :obj:`Gtk.TreeIter` or :obj:`None`
:param row: a list... | entailment |
def set_value(self, treeiter, column, value):
"""
{{ all }}
`value` can also be a Python value and will be converted to a
:obj:`GObject.Value` using the corresponding column type (See
:obj:`Gtk.ListStore.set_column_types`\\()).
"""
value = self._convert_value(co... | {{ all }}
`value` can also be a Python value and will be converted to a
:obj:`GObject.Value` using the corresponding column type (See
:obj:`Gtk.ListStore.set_column_types`\\()). | entailment |
def insert_column_with_attributes(self, position, title, cell, **kwargs):
"""
:param position: The position to insert the new column in
:type position: :obj:`int`
:param title: The title to set the header to
:type title: :obj:`str`
:param cell: The :obj:`Gtk.CellRendere... | :param position: The position to insert the new column in
:type position: :obj:`int`
:param title: The title to set the header to
:type title: :obj:`str`
:param cell: The :obj:`Gtk.CellRenderer`
:type cell: :obj:`Gtk.CellRenderer`
{{ docs }} | entailment |
def set_attributes(self, cell_renderer, **attributes):
"""
:param cell_renderer: the :obj:`Gtk.CellRenderer` we're setting the attributes of
:type cell_renderer: :obj:`Gtk.CellRenderer`
{{ docs }}
"""
Gtk.CellLayout.clear_attributes(self, cell_renderer)
for (na... | :param cell_renderer: the :obj:`Gtk.CellRenderer` we're setting the attributes of
:type cell_renderer: :obj:`Gtk.CellRenderer`
{{ docs }} | entailment |
def get_selected(self):
"""
:returns:
:model: the :obj:`Gtk.TreeModel`
:iter: The :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: (**model**: :obj:`Gtk.TreeModel`, **iter**: :obj:`Gtk.TreeIter` or :obj:`None`)
{{ docs }}
"""
success, model, aiter = s... | :returns:
:model: the :obj:`Gtk.TreeModel`
:iter: The :obj:`Gtk.TreeIter` or :obj:`None`
:rtype: (**model**: :obj:`Gtk.TreeModel`, **iter**: :obj:`Gtk.TreeIter` or :obj:`None`)
{{ docs }} | entailment |
def get_selected_rows(self):
"""
:returns:
A list containing a :obj:`Gtk.TreePath` for each selected row
and a :obj:`Gtk.TreeModel` or :obj:`None`.
:rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`])
{{ docs }}
"""
rows, model = super(TreeSele... | :returns:
A list containing a :obj:`Gtk.TreePath` for each selected row
and a :obj:`Gtk.TreeModel` or :obj:`None`.
:rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`])
{{ docs }} | entailment |
def set_value(self, iter, column, value):
"""Set the value of the child model"""
# Delegate to child model
iter = self.convert_iter_to_child_iter(iter)
self.get_model().set_value(iter, column, value) | Set the value of the child model | entailment |
def get_foreign_module(namespace):
"""Returns the module or raises ForeignError"""
if namespace not in _MODULES:
try:
module = importlib.import_module("." + namespace, __package__)
except ImportError:
module = None
_MODULES[namespace] = module
module = _MODU... | Returns the module or raises ForeignError | entailment |
def get_foreign_struct(namespace, name):
"""Returns a ForeignStruct implementation or raises ForeignError"""
get_foreign_module(namespace)
try:
return ForeignStruct.get(namespace, name)
except KeyError:
raise ForeignError("Foreign %s.%s not supported" % (namespace, name)) | Returns a ForeignStruct implementation or raises ForeignError | entailment |
def require_foreign(namespace, symbol=None):
"""Raises ImportError if the specified foreign module isn't supported or
the needed dependencies aren't installed.
e.g.: check_foreign('cairo', 'Context')
"""
try:
if symbol is None:
get_foreign_module(namespace)
else:
... | Raises ImportError if the specified foreign module isn't supported or
the needed dependencies aren't installed.
e.g.: check_foreign('cairo', 'Context') | entailment |
def io_add_watch(*args, **kwargs):
"""io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id"""
channel, priority, condition, func, user_data = _io_add_watch_get_args(*args, **kwargs)
return GLib.io_add_watch(channel, priority, condition, func, *user_data) | io_add_watch(channel, priority, condition, func, *user_data) -> event_source_id | entailment |
def child_watch_add(*args, **kwargs):
"""child_watch_add(priority, pid, function, *data)"""
priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs)
return GLib.child_watch_add(priority, pid, function, *data) | child_watch_add(priority, pid, function, *data) | entailment |
def _create(self, format, args):
"""Create a GVariant object from given format and argument list.
This method recursively calls itself for complex structures (arrays,
dictionaries, boxed).
Return a tuple (variant, rest_format, rest_args) with the generated
GVariant, the remaind... | Create a GVariant object from given format and argument list.
This method recursively calls itself for complex structures (arrays,
dictionaries, boxed).
Return a tuple (variant, rest_format, rest_args) with the generated
GVariant, the remainder of the format string, and the remainder o... | entailment |
def _create_tuple(self, format, args):
"""Handle the case where the outermost type of format is a tuple."""
format = format[1:] # eat the '('
if args is None:
# empty value: we need to call _create() to parse the subtype
rest_format = format
while rest_forma... | Handle the case where the outermost type of format is a tuple. | entailment |
def _create_dict(self, format, args):
"""Handle the case where the outermost type of format is a dict."""
builder = None
if args is None or not args[0]:
# empty value: we need to call _create() to parse the subtype,
# and specify the element type precisely
re... | Handle the case where the outermost type of format is a dict. | entailment |
def _create_array(self, format, args):
"""Handle the case where the outermost type of format is an array."""
builder = None
if args is None or not args[0]:
# empty value: we need to call _create() to parse the subtype,
# and specify the element type precisely
... | Handle the case where the outermost type of format is an array. | entailment |
def unpack(self):
"""Decompose a GVariant into a native Python object."""
LEAF_ACCESSORS = {
'b': self.get_boolean,
'y': self.get_byte,
'n': self.get_int16,
'q': self.get_uint16,
'i': self.get_int32,
'u': self.get_uint32,
... | Decompose a GVariant into a native Python object. | entailment |
def split_signature(klass, signature):
"""Return a list of the element signatures of the topmost signature tuple.
If the signature is not a tuple, it returns one element with the entire
signature. If the signature is an empty tuple, the result is [].
This is useful for e. g. iterating ... | Return a list of the element signatures of the topmost signature tuple.
If the signature is not a tuple, it returns one element with the entire
signature. If the signature is an empty tuple, the result is [].
This is useful for e. g. iterating over method parameters which are
passed as... | entailment |
def typeinfo_to_ctypes(info, return_value=False):
"""Maps a GITypeInfo() to a ctypes type.
The ctypes types have to be different in the case of return values
since ctypes does 'auto unboxing' in some cases which gives
us no chance to free memory if there is a ownership transfer.
"""
tag = info... | Maps a GITypeInfo() to a ctypes type.
The ctypes types have to be different in the case of return values
since ctypes does 'auto unboxing' in some cases which gives
us no chance to free memory if there is a ownership transfer. | entailment |
def pack_pointer(self, name):
"""Returns a pointer containing the value.
This only works for int32/uint32/utf-8..
"""
return self.parse("""
raise $_.TypeError('Can\\'t convert %(type_name)s to pointer: %%r' %% $in_)
""" % {"type_name": type(self).__name__}, in_=name)["in_"] | Returns a pointer containing the value.
This only works for int32/uint32/utf-8.. | entailment |
def new_from_memory(cls, data):
"""Takes bytes and returns a GITypelib, or raises GIError"""
size = len(data)
copy = g_memdup(data, size)
ptr = cast(copy, POINTER(guint8))
try:
with gerror(GIError) as error:
return GITypelib._new_from_memory(ptr, size... | Takes bytes and returns a GITypelib, or raises GIError | entailment |
def _get_type(cls, ptr):
"""Get the subtype class for a pointer"""
# fall back to the base class if unknown
return cls.__types.get(lib.g_base_info_get_type(ptr), cls) | Get the subtype class for a pointer | entailment |
def add_method(info, target_cls, virtual=False, dont_replace=False):
"""Add a method to the target class"""
# escape before prefixing, like pygobject
name = escape_identifier(info.name)
if virtual:
name = "do_" + name
attr = VirtualMethodAttribute(info, target_cls, name)
else:
... | Add a method to the target class | entailment |
def InterfaceAttribute(iface_info):
"""Creates a GInterface class"""
# Create a new class
cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__))
cls.__module__ = iface_info.namespace
# GType
cls.__gtype__ = PGType(iface_info.g_type)
# Properties
cls.props = PropertyA... | Creates a GInterface class | entailment |
def new_class_from_gtype(gtype):
"""Create a new class for a gtype not in the gir.
The caller is responsible for caching etc.
"""
if gtype.is_a(PGType.from_name("GObject")):
parent = gtype.parent.pytype
if parent is None or parent == PGType.from_name("void"):
return
... | Create a new class for a gtype not in the gir.
The caller is responsible for caching etc. | entailment |
def ObjectAttribute(obj_info):
"""Creates a GObject class.
It inherits from the base class and all interfaces it implements.
"""
if obj_info.name == "Object" and obj_info.namespace == "GObject":
cls = Object
else:
# Get the parent class
parent_obj = obj_info.get_parent()
... | Creates a GObject class.
It inherits from the base class and all interfaces it implements. | entailment |
def _generate_constructor(cls, names):
"""Get a hopefully cache constructor"""
cache = cls._constructors
if names in cache:
return cache[names]
elif len(cache) > 3:
cache.clear()
func = generate_constructor(cls, names)
cache[names] = func
... | Get a hopefully cache constructor | entailment |
def set_property(self, name, value):
"""set_property(property_name: str, value: object)
Set property *property_name* to *value*.
"""
if not hasattr(self.props, name):
raise TypeError("Unknown property: %r" % name)
setattr(self.props, name, value) | set_property(property_name: str, value: object)
Set property *property_name* to *value*. | entailment |
def get_property(self, name):
"""get_property(property_name: str) -> object
Retrieves a property value.
"""
if not hasattr(self.props, name):
raise TypeError("Unknown property: %r" % name)
return getattr(self.props, name) | get_property(property_name: str) -> object
Retrieves a property value. | entailment |
def connect(self, detailed_signal, handler, *args):
"""connect(detailed_signal: str, handler: function, *args) -> handler_id: int
The connect() method adds a function or method (handler) to the end
of the list of signal handlers for the named detailed_signal but
before the default class... | connect(detailed_signal: str, handler: function, *args) -> handler_id: int
The connect() method adds a function or method (handler) to the end
of the list of signal handlers for the named detailed_signal but
before the default class signal handler. An optional set of
parameters may be s... | entailment |
def connect_after(self, detailed_signal, handler, *args):
"""connect_after(detailed_signal: str, handler: function, *args) -> handler_id: int
The connect_after() method is similar to the connect() method
except that the handler is added to the signal handler list after
the default class... | connect_after(detailed_signal: str, handler: function, *args) -> handler_id: int
The connect_after() method is similar to the connect() method
except that the handler is added to the signal handler list after
the default class signal handler. Otherwise the details of handler
definition ... | entailment |
def _take_ownership(self):
"""Make the Python instance take ownership of the GIBaseInfo. i.e.
unref if the python instance gets gc'ed.
"""
if self:
ptr = cast(self.value, GIBaseInfo)
_UnrefFinalizer.track(self, ptr)
self.__owns = True | Make the Python instance take ownership of the GIBaseInfo. i.e.
unref if the python instance gets gc'ed. | entailment |
def _cast(cls, base_info, take_ownership=True):
"""Casts a GIBaseInfo instance to the right sub type.
The original GIBaseInfo can't have ownership.
Will take ownership.
"""
type_value = base_info.type.value
try:
new_obj = cast(base_info, cls.__types[type_val... | Casts a GIBaseInfo instance to the right sub type.
The original GIBaseInfo can't have ownership.
Will take ownership. | entailment |
def decode_return(codec="ascii"):
"""Decodes the return value of it isn't None"""
def outer(f):
def wrap(*args, **kwargs):
res = f(*args, **kwargs)
if res is not None:
return res.decode(codec)
return res
return wrap
return outer | Decodes the return value of it isn't None | entailment |
def load_ctypes_library(name):
"""Takes a library name and calls find_library in case loading fails,
since some girs don't include the real .so name.
Raises OSError like LoadLibrary if loading fails.
e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix
"""
try:
ret... | Takes a library name and calls find_library in case loading fails,
since some girs don't include the real .so name.
Raises OSError like LoadLibrary if loading fails.
e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix | entailment |
def escape_identifier(text, reg=KWD_RE):
"""Escape partial C identifiers so they can be used as
attributes/arguments"""
# see http://docs.python.org/reference/lexical_analysis.html#identifiers
if not text:
return "_"
if text[0].isdigit():
text = "_" + text
return reg.sub(r"\1_",... | Escape partial C identifiers so they can be used as
attributes/arguments | entailment |
def cache_return(func):
"""Cache the return value of a function without arguments"""
_cache = []
def wrap():
if not _cache:
_cache.append(func())
return _cache[0]
return wrap | Cache the return value of a function without arguments | entailment |
def lookup_name_fast(self, name):
"""Might return a struct"""
if name in self.__names:
return self.__names[name]
count = self.__get_count_cached()
lo = 0
hi = count
while lo < hi:
mid = (lo + hi) // 2
if self.__get_name_cached(mid) < ... | Might return a struct | entailment |
def lookup_name_slow(self, name):
"""Returns a struct if one exists"""
for index in xrange(self.__get_count_cached()):
if self.__get_name_cached(index) == name:
return self.__get_info_cached(index) | Returns a struct if one exists | entailment |
def lookup_name(self, name):
"""Returns a struct if one exists"""
try:
info = self._get_by_name(self._source, name)
except NotImplementedError:
pass
else:
if info:
return info
return
info = self.lookup_name_fast(na... | Returns a struct if one exists | entailment |
def _new_type(cls, args):
"""Creates a new class similar to namedtuple.
Pass a list of field names or None for no field name.
>>> x = ResultTuple._new_type([None, "bar"])
>>> x((1, 3))
ResultTuple(1, bar=3)
"""
fformat = ["%r" if f is None else "%s=%%r" % f for... | Creates a new class similar to namedtuple.
Pass a list of field names or None for no field name.
>>> x = ResultTuple._new_type([None, "bar"])
>>> x((1, 3))
ResultTuple(1, bar=3) | entailment |
def signal_list_names(type_):
"""Returns a list of signal names for the given type
:param type\\_:
:type type\\_: :obj:`GObject.GType`
:returns: A list of signal names
:rtype: :obj:`list`
"""
ids = signal_list_ids(type_)
return tuple(GObjectModule.signal_name(i) for i in ids) | Returns a list of signal names for the given type
:param type\\_:
:type type\\_: :obj:`GObject.GType`
:returns: A list of signal names
:rtype: :obj:`list` | entailment |
def signal_handler_block(obj, handler_id):
"""Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which opt... | Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblo... | entailment |
def signal_parse_name(detailed_signal, itype, force_detail_quark):
"""Parse a detailed signal name into (signal_id, detail).
:param str detailed_signal:
Signal name which can include detail.
For example: "notify:prop_name"
:returns:
Tuple of (signal_id, detail)
:raises ValueErro... | Parse a detailed signal name into (signal_id, detail).
:param str detailed_signal:
Signal name which can include detail.
For example: "notify:prop_name"
:returns:
Tuple of (signal_id, detail)
:raises ValueError:
If the given signal is unknown. | entailment |
def find_library(name, cached=True, internal=True):
"""
cached: Return a new instance
internal: return a shared instance that's not the ctypes cached one
"""
# a new one
if not cached:
return cdll.LoadLibrary(_so_mapping[name])
# from the shared internal set or a new one
... | cached: Return a new instance
internal: return a shared instance that's not the ctypes cached one | entailment |
def track(cls, obj, ptr):
"""
Track an object which needs destruction when it is garbage collected.
"""
cls._objects.add(cls(obj, ptr)) | Track an object which needs destruction when it is garbage collected. | entailment |
def _unpack_result(klass, result):
'''Convert a D-BUS return variant into an appropriate return value'''
result = result.unpack()
# to be compatible with standard Python behaviour, unbox
# single-element tuples and return None for empty result tuples
if len(result) == 1:
... | Convert a D-BUS return variant into an appropriate return value | entailment |
def list_properties(type):
"""
:param type: a Python GObject instance or type that the signal is associated with
:type type: :obj:`GObject.Object`
:returns: a list of :obj:`GObject.ParamSpec`
:rtype: [:obj:`GObject.ParamSpec`]
Takes a GObject/GInterface subclass or a GType and returns a list o... | :param type: a Python GObject instance or type that the signal is associated with
:type type: :obj:`GObject.Object`
:returns: a list of :obj:`GObject.ParamSpec`
:rtype: [:obj:`GObject.ParamSpec`]
Takes a GObject/GInterface subclass or a GType and returns a list of
GParamSpecs for all properties of... | entailment |
def load_overrides(introspection_module):
"""Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result.
"""
namespace = introspection_module.__name__.rsplit(".", 1)[-1]
module... | Loads overrides for an introspection module.
Either returns the same module again in case there are no overrides or a
proxy module including overrides. Doesn't cache the result. | entailment |
def override(klass):
"""Takes a override class or function and assigns it dunder arguments
form the overidden one.
"""
namespace = klass.__module__.rsplit(".", 1)[-1]
mod_name = const.PREFIX[-1] + "." + namespace
module = sys.modules[mod_name]
if isinstance(klass, types.FunctionType):
... | Takes a override class or function and assigns it dunder arguments
form the overidden one. | entailment |
def deprecated(function, instead):
"""Mark a function deprecated so calling it issues a warning"""
# skip for classes, breaks doc generation
if not isinstance(function, types.FunctionType):
return function
@wraps(function)
def wrap(*args, **kwargs):
warnings.warn("Deprecated, use %... | Mark a function deprecated so calling it issues a warning | entailment |
def deprecated_attr(namespace, attr, replacement):
"""Marks a module level attribute as deprecated. Accessing it will emit
a PyGIDeprecationWarning warning.
e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")``
accessing GObject.STATUS_FOO will emit:
"GObject.STATUS_FOO is d... | Marks a module level attribute as deprecated. Accessing it will emit
a PyGIDeprecationWarning warning.
e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")``
accessing GObject.STATUS_FOO will emit:
"GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead"
:param str na... | entailment |
def deprecated_init(super_init_func, arg_names, ignore=tuple(),
deprecated_aliases={}, deprecated_defaults={},
category=PyGIDeprecationWarning,
stacklevel=2):
"""Wrapper for deprecating GObject based __init__ methods which specify
defaults already avai... | Wrapper for deprecating GObject based __init__ methods which specify
defaults already available or non-standard defaults.
:param callable super_init_func:
Initializer to wrap.
:param list arg_names:
Ordered argument name list.
:param list ignore:
List of argument names to ignore... | entailment |
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
"""Translate method's return value for stripping off success flag.
There are a lot of methods which return a "success" boolean and have
several out arguments. Translate such a method to return the out arguments
on success and... | Translate method's return value for stripping off success flag.
There are a lot of methods which return a "success" boolean and have
several out arguments. Translate such a method to return the out arguments
on success and None on failure. | entailment |
def get_introspection_module(namespace):
"""Raises ImportError"""
if namespace in _introspection_modules:
return _introspection_modules[namespace]
from . import get_required_version
repository = GIRepository()
version = get_required_version(namespace)
try:
repository.require(... | Raises ImportError | entailment |
def get_param_type(self, index):
"""Returns a ReturnValue instance for param type 'index'"""
assert index in (0, 1)
type_info = self.type.get_param_type(index)
type_cls = get_return_class(type_info)
instance = type_cls(None, type_info, [], self.backend)
instance.setup()... | Returns a ReturnValue instance for param type 'index | entailment |
def parse_code(code, var_factory, **kwargs):
"""Parse a piece of text and substitude $var by either unique
variable names or by the given kwargs mapping. Use $$ to escape $.
Returns a CodeBlock and the resulting variable mapping.
parse("$foo = $foo + $bar", bar="1")
("t1 = t1 + 1", {'foo': 't1', '... | Parse a piece of text and substitude $var by either unique
variable names or by the given kwargs mapping. Use $$ to escape $.
Returns a CodeBlock and the resulting variable mapping.
parse("$foo = $foo + $bar", bar="1")
("t1 = t1 + 1", {'foo': 't1', 'bar': '1'}) | entailment |
def parse_with_objects(code, var, **kwargs):
"""Parse code and include non string/codeblock kwargs as
dependencies.
int/long will be inlined.
Returns a CodeBlock and the resulting variable mapping.
"""
deps = {}
for key, value in kwargs.items():
if isinstance(value, _compat.intege... | Parse code and include non string/codeblock kwargs as
dependencies.
int/long will be inlined.
Returns a CodeBlock and the resulting variable mapping. | entailment |
def request_name(self, name):
"""Request a name, might return the name or a similar one if already
used or reserved
"""
while name in self._blacklist:
name += "_"
self._blacklist.add(name)
return name | Request a name, might return the name or a similar one if already
used or reserved | entailment |
def add_dependency(self, name, obj):
"""Add a code dependency so it gets inserted into globals"""
if name in self._deps:
if self._deps[name] is obj:
return
raise ValueError(
"There exists a different dep with the same name : %r" % name)
se... | Add a code dependency so it gets inserted into globals | entailment |
def write_into(self, block, level=0):
"""Append this block to another one, passing all dependencies"""
for line, l in self._lines:
block.write_line(line, level + l)
for name, obj in _compat.iteritems(self._deps):
block.add_dependency(name, obj) | Append this block to another one, passing all dependencies | entailment |
def write_lines(self, lines, level=0):
"""Append multiple new lines"""
for line in lines:
self.write_line(line, level) | Append multiple new lines | entailment |
def compile(self, **kwargs):
"""Execute the python code and returns the global dict.
kwargs can contain extra dependencies that get only used
at compile time.
"""
code = compile(str(self), "<string>", "exec")
global_dict = dict(self._deps)
global_dict.update(kwar... | Execute the python code and returns the global dict.
kwargs can contain extra dependencies that get only used
at compile time. | entailment |
def pprint(self, file_=sys.stdout):
"""Print the code block to stdout.
Does syntax highlighting if possible.
"""
code = []
if self._deps:
code.append("# dependencies:")
for k, v in _compat.iteritems(self._deps):
code.append("# %s: %r" % (k, v))
... | Print the code block to stdout.
Does syntax highlighting if possible. | entailment |
def register(cls, namespace, name):
"""Class decorator"""
def func(kind):
cls._FOREIGN[(namespace, name)] = kind()
return kind
return func | Class decorator | entailment |
def may_be_null_is_nullable():
"""If may_be_null returns nullable or if NULL can be passed in.
This can still be wrong if the specific typelib is older than the linked
libgirepository.
https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47
"""
repo = GIRepository()
repo.require("GLib", "2.... | If may_be_null returns nullable or if NULL can be passed in.
This can still be wrong if the specific typelib is older than the linked
libgirepository.
https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47 | entailment |
def get_type_name(type_):
"""Gives a name for a type that is suitable for a docstring.
int -> "int"
Gtk.Window -> "Gtk.Window"
[int] -> "[int]"
{int: Gtk.Button} -> "{int: Gtk.Button}"
"""
if type_ is None:
return ""
if isinstance(type_, string_types):
return type_
... | Gives a name for a type that is suitable for a docstring.
int -> "int"
Gtk.Window -> "Gtk.Window"
[int] -> "[int]"
{int: Gtk.Button} -> "{int: Gtk.Button}" | entailment |
def build_docstring(func_name, args, ret, throws, signal_owner_type=None):
"""Create a docstring in the form:
name(in_name: type) -> (ret_type, out_name: type)
"""
out_args = []
if ret and not ret.ignore:
if ret.py_type is None:
out_args.append("unknown")
else:
... | Create a docstring in the form:
name(in_name: type) -> (ret_type, out_name: type) | entailment |
def generate_function(info, method=False):
"""Creates a Python callable for a GIFunctionInfo instance"""
assert isinstance(info, GIFunctionInfo)
arg_infos = list(info.get_args())
arg_types = [a.get_type() for a in arg_infos]
return_type = info.get_return_type()
func = None
messages = []
... | Creates a Python callable for a GIFunctionInfo instance | entailment |
def generate_dummy_callable(info, func_name, method=False,
signal_owner_type=None):
"""Takes a GICallableInfo and generates a dummy callback function which
just raises but has a correct docstring. They are mainly accessible for
documentation, so the API reference can reference a ... | Takes a GICallableInfo and generates a dummy callback function which
just raises but has a correct docstring. They are mainly accessible for
documentation, so the API reference can reference a real thing.
func_name can be different than info.name because vfuncs, for example,
get prefixed with 'do_' whe... | entailment |
def _create_enum_class(ffi, type_name, prefix, flags=False):
"""Returns a new shiny class for the given enum type"""
class _template(int):
_map = {}
@property
def value(self):
return int(self)
def __str__(self):
return self._map.get(self, "Unknown")
... | Returns a new shiny class for the given enum type | entailment |
def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")):
"""Converts some common enum expressions to constants"""
def repl_shift(match):
shift_by = int(match.group(2))
value = int(match.group(1))
int_value = ctypes.c_int(value << shift_by).value
return "= %s" % ... | Converts some common enum expressions to constants | entailment |
def unpack_glist(g, type_, transfer_full=True):
"""Takes a glist, copies the values casted to type_ in to a list
and frees all items and the list.
"""
values = []
item = g
while item:
ptr = item.contents.data
value = cast(ptr, type_).value
values.append(value)
if... | Takes a glist, copies the values casted to type_ in to a list
and frees all items and the list. | entailment |
def unpack_nullterm_array(array):
"""Takes a null terminated array, copies the values into a list
and frees each value and the list.
"""
addrs = cast(array, POINTER(ctypes.c_void_p))
l = []
i = 0
value = array[i]
while value:
l.append(value)
free(addrs[i])
i += 1... | Takes a null terminated array, copies the values into a list
and frees each value and the list. | entailment |
def require_version(namespace, version):
"""Set a version for the namespace to be loaded.
This needs to be called before importing the namespace or any
namespace that depends on it.
"""
global _versions
repo = GIRepository()
namespaces = repo.get_loaded_namespaces()
if namespace in na... | Set a version for the namespace to be loaded.
This needs to be called before importing the namespace or any
namespace that depends on it. | entailment |
def _check_require_version(namespace, stacklevel):
"""A context manager which tries to give helpful warnings
about missing gi.require_version() which could potentially
break code if only an older version than expected is installed
or a new version gets introduced.
::
with _check_require_ve... | A context manager which tries to give helpful warnings
about missing gi.require_version() which could potentially
break code if only an older version than expected is installed
or a new version gets introduced.
::
with _check_require_version("Gtk", stacklevel):
load_namespace_and_o... | entailment |
def get_import_stacklevel(import_hook):
"""Returns the stacklevel value for warnings.warn() for when the warning
gets emitted by an imported module, but the warning should point at the
code doing the import.
Pass import_hook=True if the warning gets generated by an import hook
(warn() gets called i... | Returns the stacklevel value for warnings.warn() for when the warning
gets emitted by an imported module, but the warning should point at the
code doing the import.
Pass import_hook=True if the warning gets generated by an import hook
(warn() gets called in load_module(), see PEP302) | entailment |
def unpack_glist(glist_ptr, cffi_type, transfer_full=True):
"""Takes a glist ptr, copies the values casted to type_ in to a list
and frees all items and the list.
If an item is returned all yielded before are invalid.
"""
current = glist_ptr
while current:
yield ffi.cast(cffi_type, cur... | Takes a glist ptr, copies the values casted to type_ in to a list
and frees all items and the list.
If an item is returned all yielded before are invalid. | entailment |
def unpack_zeroterm_array(ptr):
"""Converts a zero terminated array to a list and frees each element
and the list itself.
If an item is returned all yielded before are invalid.
"""
assert ptr
index = 0
current = ptr[index]
while current:
yield current
free(ffi.cast("gp... | Converts a zero terminated array to a list and frees each element
and the list itself.
If an item is returned all yielded before are invalid. | entailment |
def StructureAttribute(struct_info):
"""Creates a new struct class."""
# Copy the template and add the gtype
cls_dict = dict(_Structure.__dict__)
cls = type(struct_info.name, _Structure.__bases__, cls_dict)
cls.__module__ = struct_info.namespace
cls.__gtype__ = PGType(struct_info.g_type)
cl... | Creates a new struct class. | entailment |
def _from_gerror(cls, error, own=True):
"""Creates a GError exception and takes ownership if own is True"""
if not own:
error = error.copy()
self = cls()
self._error = error
return self | Creates a GError exception and takes ownership if own is True | entailment |
def check_version(version):
"""Takes a version string or tuple and raises ValueError in case
the passed version is newer than the current version of pgi.
Keep in mind that the pgi version is different from the pygobject one.
"""
if isinstance(version, string_types):
version = tuple(map(int... | Takes a version string or tuple and raises ValueError in case
the passed version is newer than the current version of pgi.
Keep in mind that the pgi version is different from the pygobject one. | entailment |
def install_as_gi():
"""Call before the first gi import to redirect gi imports to pgi"""
import sys
# check if gi has already been replaces
if "gi.repository" in const.PREFIX:
return
# make sure gi isn't loaded first
for mod in iterkeys(sys.modules):
if mod == "gi" or mod.star... | Call before the first gi import to redirect gi imports to pgi | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.