_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q240700 | BaseField.describe | train | def describe(self, **kwargs):
"""
Describe this field instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
... | python | {
"resource": ""
} |
q240701 | BoolField.from_representation | train | def from_representation(self, data):
"""Convert representation value to ``bool`` if it has expected form."""
if data in self._TRUE_VALUES:
return True
elif data in self._FALSE_VALUES:
return False
else:
raise ValueError(
"{type} type va... | python | {
"resource": ""
} |
q240702 | MetaSerializer._get_fields | train | def _get_fields(mcs, bases, namespace):
"""Create fields dictionary to be used in resource class namespace.
Pop all field objects from attributes dict (namespace) and store them
under _field_storage_key atrribute. Also collect all fields from base
classes in order that ensures fields ca... | python | {
"resource": ""
} |
q240703 | BaseSerializer.to_representation | train | def to_representation(self, obj):
"""Convert given internal object instance into representation dict.
Representation dict may be later serialized to the content-type
of choice in the resource HTTP method handler.
This loops over all fields and retrieves source keys/attributes as
... | python | {
"resource": ""
} |
q240704 | BaseSerializer.from_representation | train | def from_representation(self, representation):
"""Convert given representation dict into internal object.
Internal object is simply a dictionary of values with respect to field
sources.
This does not check if all required fields exist or values are
valid in terms of value valid... | python | {
"resource": ""
} |
q240705 | BaseSerializer.get_attribute | train | def get_attribute(self, obj, attr):
"""Get attribute of given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also object's key from if is a dict or any other kind of mapping.
Note: it will return None if attribute key does not exist
A... | python | {
"resource": ""
} |
q240706 | BaseSerializer.set_attribute | train | def set_attribute(self, obj, attr, value):
"""Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to mo... | python | {
"resource": ""
} |
q240707 | BaseSerializer.describe | train | def describe(self):
"""Describe all serialized fields.
It returns dictionary of all fields description defined for this
serializer using their own ``describe()`` methods with respect to order
in which they are defined as class attributes.
Returns:
OrderedDict: seria... | python | {
"resource": ""
} |
q240708 | _join_host_port | train | def _join_host_port(host, port):
"""Adapted golang's net.JoinHostPort"""
template = "%s:%s"
host_requires_bracketing = ':' in host or '%' in host
if host_requires_bracketing:
template = "[%s]:%s"
return template % (host, port) | python | {
"resource": ""
} |
q240709 | BaseMixin.handle | train | def handle(self, handler, req, resp, **kwargs):
"""Handle given resource manipulation flow in consistent manner.
This mixin is intended to be used only as a base class in new flow
mixin classes. It ensures that regardless of resource manunipulation
semantics (retrieve, get, delete etc.)... | python | {
"resource": ""
} |
q240710 | RetrieveMixin.on_get | train | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource retrieval flow.
This request handler assumes that GET requests are associated with
single resource instance retrieval. Thus default flow for such requests
is:
* Retrieve single... | python | {
"resource": ""
} |
q240711 | ListMixin.on_get | train | def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource list retrieval flow.
This request handler assumes that GET requests are associated with
resource list retrieval. Thus default flow for such requests is:
* Retrieve list of existing res... | python | {
"resource": ""
} |
q240712 | DeleteMixin.on_delete | train | def on_delete(self, req, resp, handler=None, **kwargs):
"""Respond on DELETE HTTP request assuming resource deletion flow.
This request handler assumes that DELETE requests are associated with
resource deletion. Thus default flow for such requests is:
* Delete existing resource instanc... | python | {
"resource": ""
} |
q240713 | UpdateMixin.on_put | train | def on_put(self, req, resp, handler=None, **kwargs):
"""Respond on PUT HTTP request assuming resource update flow.
This request handler assumes that PUT requests are associated with
resource update/modification. Thus default flow for such requests is:
* Modify existing resource instanc... | python | {
"resource": ""
} |
q240714 | PaginatedMixin.add_pagination_meta | train | def add_pagination_meta(self, params, meta):
"""Extend default meta dictionary value with pagination hints.
Note:
This method handler attaches values to ``meta`` dictionary without
changing it's reference. This means that you should never replace
``meta`` dictionary ... | python | {
"resource": ""
} |
q240715 | MetaResource._get_params | train | def _get_params(mcs, bases, namespace):
"""Create params dictionary to be used in resource class namespace.
Pop all parameter objects from attributes dict (namespace)
and store them under _params_storage_key atrribute.
Also collect all params from base classes in order that ensures
... | python | {
"resource": ""
} |
q240716 | BaseResource.make_body | train | def make_body(self, resp, params, meta, content):
"""Construct response body in ``resp`` object using JSON serialization.
Args:
resp (falcon.Response): response object where to include
serialized body
params (dict): dictionary of parsed parameters
met... | python | {
"resource": ""
} |
q240717 | BaseResource.allowed_methods | train | def allowed_methods(self):
"""Return list of allowed HTTP methods on this resource.
This is only for purpose of making resource description.
Returns:
list: list of allowed HTTP method names (uppercase)
"""
return [
method
for method, allowed... | python | {
"resource": ""
} |
q240718 | BaseResource.describe | train | def describe(self, req=None, resp=None, **kwargs):
"""Describe API resource using resource introspection.
Additional description on derrived resource class can be added using
keyword arguments and calling ``super().decribe()`` method call
like following:
.. code-block:: python
... | python | {
"resource": ""
} |
q240719 | BaseResource.on_options | train | def on_options(self, req, resp, **kwargs):
"""Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict)... | python | {
"resource": ""
} |
q240720 | BaseResource.require_params | train | def require_params(self, req):
"""Require all defined parameters from request query string.
Raises ``falcon.errors.HTTPMissingParam`` exception if any of required
parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any
of parameters could not be understood (wrong format).
... | python | {
"resource": ""
} |
q240721 | BaseResource.require_meta_and_content | train | def require_meta_and_content(self, content_handler, params, **kwargs):
"""Require 'meta' and 'content' dictionaries using proper hander.
Args:
content_handler (callable): function that accepts
``params, meta, **kwargs`` argument and returns dictionary
for ``c... | python | {
"resource": ""
} |
q240722 | BaseResource.require_representation | train | def require_representation(self, req):
"""Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as c... | python | {
"resource": ""
} |
q240723 | BaseResource.require_validated | train | def require_validated(self, req, partial=False, bulk=False):
"""Require fully validated internal object dictionary.
Internal object dictionary creation is based on content-decoded
representation retrieved from request body. Internal object validation
is performed using resource serializ... | python | {
"resource": ""
} |
q240724 | AdmissionregistrationV1beta1WebhookClientConfig.ca_bundle | train | def ca_bundle(self, ca_bundle):
"""Sets the ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig.
`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used. # noqa: E501
:par... | python | {
"resource": ""
} |
q240725 | V1beta1CertificateSigningRequestStatus.certificate | train | def certificate(self, certificate):
"""Sets the certificate of this V1beta1CertificateSigningRequestStatus.
If request was approved, the controller will place the issued certificate here. # noqa: E501
:param certificate: The certificate of this V1beta1CertificateSigningRequestStatus. # noqa:... | python | {
"resource": ""
} |
q240726 | ListAPI.describe | train | def describe(self, req=None, resp=None, **kwargs):
"""Extend default endpoint description with serializer description."""
return super().describe(
req, resp,
type='list',
fields=self.serializer.describe() if self.serializer else None,
**kwargs
) | python | {
"resource": ""
} |
q240727 | DummyUserStorage.get_user | train | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user | python | {
"resource": ""
} |
q240728 | KeyValueUserStorage._get_storage_key | train | def _get_storage_key(self, identified_with, identifier):
"""Get key string for given user identifier in consistent manner."""
return ':'.join((
self.key_prefix, identified_with.name,
self.hash_identifier(identified_with, identifier),
)) | python | {
"resource": ""
} |
q240729 | KeyValueUserStorage.get_user | train | def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Get user object for given identifier.
Args:
identified_with (object): authentication middleware used
to identify the user.
identifier: middleware specifix user iden... | python | {
"resource": ""
} |
q240730 | KeyValueUserStorage.register | train | def register(self, identified_with, identifier, user):
"""Register new key for given client identifier.
This is only a helper method that allows to register new
user objects for client identities (keys, tokens, addresses etc.).
Args:
identified_with (object): authentication... | python | {
"resource": ""
} |
q240731 | BaseAuthenticationMiddleware.process_resource | train | def process_resource(self, req, resp, resource, uri_kwargs=None):
"""Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource... | python | {
"resource": ""
} |
q240732 | BaseAuthenticationMiddleware.try_storage | train | def try_storage(self, identifier, req, resp, resource, uri_kwargs):
"""Try to find user in configured user storage object.
Args:
identifier: User identifier.
Returns:
user object.
"""
if identifier is None:
user = None
# note: if use... | python | {
"resource": ""
} |
q240733 | Basic.identify | train | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Basic auth."""
header = req.get_header("Authorization", False)
auth = header.split(" ") if header else None
if auth is None or auth[0].lower() != 'basic':
return None
... | python | {
"resource": ""
} |
q240734 | XAPIKey.identify | train | def identify(self, req, resp, resource, uri_kwargs):
"""Initialize X-Api-Key authentication middleware."""
try:
return req.get_header('X-Api-Key', True)
except (KeyError, HTTPMissingHeader):
pass | python | {
"resource": ""
} |
q240735 | Token.identify | train | def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Token auth."""
header = req.get_header('Authorization', False)
auth = header.split(' ') if header else None
if auth is None or auth[0].lower() != 'token':
return None
... | python | {
"resource": ""
} |
q240736 | XForwardedFor._get_client_address | train | def _get_client_address(self, req):
"""Get address from ``X-Forwarded-For`` header or use remote address.
Remote address is used if the ``X-Forwarded-For`` header is not
available. Note that this may not be safe to depend on both without
proper authorization backend.
Args:
... | python | {
"resource": ""
} |
q240737 | DeserializationError._get_description | train | def _get_description(self):
"""Return human readable description error description.
This description should explain everything that went wrong during
deserialization.
"""
return ", ".join([
part for part in [
"missing: {}".format(self.missing) if sel... | python | {
"resource": ""
} |
q240738 | load_kube_config | train | async def load_kube_config(config_file=None, context=None,
client_configuration=None,
persist_config=True):
"""Loads authentication and cluster information from kube-config file
and stores them in kubernetes.client.configuration.
:param config_file: Nam... | python | {
"resource": ""
} |
q240739 | refresh_token | train | async def refresh_token(loader, client_configuration=None, interval=60):
"""Refresh token if necessary, updates the token in client configurarion
:param loader: KubeConfigLoader returned by load_kube_config
:param client_configuration: The kubernetes.client.Configuration to
set configs to.
... | python | {
"resource": ""
} |
q240740 | new_client_from_config | train | async def new_client_from_config(config_file=None, context=None, persist_config=True):
"""Loads configuration the same as load_kube_config but returns an ApiClient
to be used with any API object. This will allow the caller to concurrently
talk with multiple clusters."""
client_config = type.__call__(Con... | python | {
"resource": ""
} |
q240741 | KubeConfigLoader._load_authentication | train | async def _load_authentication(self):
"""Read authentication from kube-config user section if exists.
This function goes through various authentication methods in user
section of kube-config and stops if it finds a valid authentication
method. The order of authentication methods is:
... | python | {
"resource": ""
} |
q240742 | min_validator | train | def min_validator(min_value):
"""Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator
"""
def valida... | python | {
"resource": ""
} |
q240743 | max_validator | train | def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def valid... | python | {
"resource": ""
} |
q240744 | choices_validator | train | def choices_validator(choices):
"""Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator
"""
def validator(value):
if value not in choices:
# note: make it a list for consistent representatio... | python | {
"resource": ""
} |
q240745 | match_validator | train | def match_validator(expression):
"""Return validator function that will check if matches given expression.
Args:
match: if string then this will be converted to regular expression
using ``re.compile``. Can be also any object that has ``match()``
method like already compiled regula... | python | {
"resource": ""
} |
q240746 | BaseParam.validated_value | train | def validated_value(self, raw_value):
"""Return parsed parameter value and run validation handlers.
Error message included in exception will be included in http error
response
Args:
value: raw parameter value to parse validate
Returns:
None
Not... | python | {
"resource": ""
} |
q240747 | BaseParam.describe | train | def describe(self, **kwargs):
"""Describe this parameter instance for purpose of self-documentation.
Args:
kwargs (dict): dictionary of additional description items for
extending default description
Returns:
dict: dictionary of description items
... | python | {
"resource": ""
} |
q240748 | Base64EncodedParam.value | train | def value(self, raw_value):
"""Decode param with Base64."""
try:
return base64.b64decode(bytes(raw_value, 'utf-8')).decode('utf-8')
except binascii.Error as err:
raise ValueError(str(err)) | python | {
"resource": ""
} |
q240749 | DecimalParam.value | train | def value(self, raw_value):
"""Decode param as decimal value."""
try:
return decimal.Decimal(raw_value)
except decimal.InvalidOperation:
raise ValueError(
"Could not parse '{}' value as decimal".format(raw_value)
) | python | {
"resource": ""
} |
q240750 | BoolParam.value | train | def value(self, raw_value):
"""Decode param as bool value."""
if raw_value in self._FALSE_VALUES:
return False
elif raw_value in self._TRUE_VALUES:
return True
else:
raise ValueError(
"Could not parse '{}' value as boolean".format(raw_v... | python | {
"resource": ""
} |
q240751 | V1beta1CertificateSigningRequestSpec.request | train | def request(self, request):
"""Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str
"""
if request is None:
... | python | {
"resource": ""
} |
q240752 | project | train | def project(dataIn, projectionScript):
'''Programs may make use of data in the `dataIn` variable and should
produce data on the `dataOut` variable.'''
# We don't really need to initialize it, but we do it to avoid linter errors
dataOut = {}
try:
projectionScript = str(projectionScript)
... | python | {
"resource": ""
} |
q240753 | grlcPROV.init_prov_graph | train | def init_prov_graph(self):
"""
Initialize PROV graph with all we know at the start of the recording
"""
try:
# Use git2prov to get prov on the repo
repo_prov = check_output(
['node_modules/git2prov/bin/git2prov', 'https://github.com/{}/{}/'.format... | python | {
"resource": ""
} |
q240754 | grlcPROV.add_used_entity | train | def add_used_entity(self, entity_uri):
"""
Add the provided URI as a used entity by the logged activity
"""
entity_o = URIRef(entity_uri)
self.prov_g.add((entity_o, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, self.prov.used, entity_o)) | python | {
"resource": ""
} |
q240755 | grlcPROV.end_prov_graph | train | def end_prov_graph(self):
"""
Finalize prov recording with end time
"""
endTime = Literal(datetime.now())
self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime))
self.prov_g.add((self.activity, self.prov.endedAtTime, endTime)) | python | {
"resource": ""
} |
q240756 | grlcPROV.log_prov_graph | train | def log_prov_graph(self):
"""
Log provenance graph so far
"""
glogger.debug("Spec generation provenance graph:")
glogger.debug(self.prov_g.serialize(format='turtle')) | python | {
"resource": ""
} |
q240757 | grlcPROV.serialize | train | def serialize(self, format):
"""
Serialize provenance graph in the specified format
"""
if PY3:
return self.prov_g.serialize(format=format).decode('utf-8')
else:
return self.prov_g.serialize(format=format) | python | {
"resource": ""
} |
q240758 | get_defaults | train | def get_defaults(rq, v, metadata):
"""
Returns the default value for a parameter or None
"""
glogger.debug("Metadata with defaults: {}".format(metadata))
if 'defaults' not in metadata:
return None
defaultsDict = _getDictWithKey(v, metadata['defaults'])
if defaultsDict:
return... | python | {
"resource": ""
} |
q240759 | LocalLoader.fetchFiles | train | def fetchFiles(self):
"""Returns a list of file items contained on the local repo."""
print("Fetching files from {}".format(self.baseDir))
files = glob(path.join(self.baseDir, '*'))
filesDef = []
for f in files:
print("Found SPARQL file {}".format(f))
rela... | python | {
"resource": ""
} |
q240760 | get_repo_info | train | def get_repo_info(loader, sha, prov_g):
"""Generate swagger information from the repo being used."""
user_repo = loader.getFullName()
repo_title = loader.getRepoTitle()
contact_name = loader.getContactName()
contact_url = loader.getContactUrl()
commit_list = loader.getCommitList()
licence_ur... | python | {
"resource": ""
} |
q240761 | buildPaginationHeader | train | def buildPaginationHeader(resultCount, resultsPerPage, pageArg, url):
'''Build link header for result pagination'''
lastPage = resultCount / resultsPerPage
if pageArg:
page = int(pageArg)
next_url = re.sub("page=[0-9]+", "page={}".format(page + 1), url)
prev_url = re.sub("page=[0-9]... | python | {
"resource": ""
} |
q240762 | format_directive | train | def format_directive(module, package=None):
# type: (unicode, unicode) -> unicode
"""Create the automodule directive and add the options."""
directive = '.. automodule:: %s\n' % makename(package, module)
for option in OPTIONS:
directive += ' :%s:\n' % option
return directive | python | {
"resource": ""
} |
q240763 | extract_summary | train | def extract_summary(obj):
# type: (List[unicode], Any) -> unicode
"""Extract summary from docstring."""
try:
doc = inspect.getdoc(obj).split("\n")
except AttributeError:
doc = ''
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If ther... | python | {
"resource": ""
} |
q240764 | _get_member_ref_str | train | def _get_member_ref_str(name, obj, role='obj', known_refs=None):
"""generate a ReST-formmated reference link to the given `obj` of type
`role`, using `name` as the link text"""
if known_refs is not None:
if name in known_refs:
return known_refs[name]
ref = _get_fullname(name, obj)
... | python | {
"resource": ""
} |
q240765 | _get_mod_ns | train | def _get_mod_ns(name, fullname, includeprivate):
"""Return the template context of module identified by `fullname` as a
dict"""
ns = { # template variables
'name': name, 'fullname': fullname, 'members': [], 'functions': [],
'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [... | python | {
"resource": ""
} |
q240766 | VDFDict.get_all_for | train | def get_all_for(self, key):
""" Returns all values of the given key """
if not isinstance(key, _string_type):
raise TypeError("Key needs to be a string.")
return [self[(idx, key)] for idx in _range(self.__kcount[key])] | python | {
"resource": ""
} |
q240767 | VDFDict.remove_all_for | train | def remove_all_for(self, key):
""" Removes all items with the given key """
if not isinstance(key, _string_type):
raise TypeError("Key need to be a string.")
for idx in _range(self.__kcount[key]):
super(VDFDict, self).__delitem__((idx, key))
self.__omap = list(f... | python | {
"resource": ""
} |
q240768 | VDFDict.has_duplicates | train | def has_duplicates(self):
"""
Returns ``True`` if the dict contains keys with duplicates.
Recurses through any all keys with value that is ``VDFDict``.
"""
for n in getattr(self.__kcount, _iter_values)():
if n != 1:
return True
def dict_recurs... | python | {
"resource": ""
} |
q240769 | dumps | train | def dumps(obj, pretty=False, escaped=True):
"""
Serialize ``obj`` to a VDF formatted ``str``.
"""
if not isinstance(obj, dict):
raise TypeError("Expected data to be an instance of``dict``")
if not isinstance(pretty, bool):
raise TypeError("Expected pretty to be of type bool")
if ... | python | {
"resource": ""
} |
q240770 | binary_dumps | train | def binary_dumps(obj, alt_format=False):
"""
Serialize ``obj`` to a binary VDF formatted ``bytes``.
"""
return b''.join(_binary_dump_gen(obj, alt_format=alt_format)) | python | {
"resource": ""
} |
q240771 | vbkv_loads | train | def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True):
"""
Deserialize ``s`` (``bytes`` containing a VBKV to a Python object.
``mapper`` specifies the Python object used after deserializetion. ``dict` is
used by default. Alternatively, ``collections.OrderedDict`` can be used if you
wish to pres... | python | {
"resource": ""
} |
q240772 | vbkv_dumps | train | def vbkv_dumps(obj):
"""
Serialize ``obj`` to a VBKV formatted ``bytes``.
"""
data = b''.join(_binary_dump_gen(obj, alt_format=True))
checksum = crc32(data)
return b'VBKV' + struct.pack('<i', checksum) + data | python | {
"resource": ""
} |
q240773 | signature_validate | train | def signature_validate(signature, error = None) :
"is signature a valid sequence of zero or more complete types."
error, my_error = _get_error(error)
result = dbus.dbus_signature_validate(signature.encode(), error._dbobj) != 0
my_error.raise_if_set()
return \
result | python | {
"resource": ""
} |
q240774 | unparse_signature | train | def unparse_signature(signature) :
"converts a signature from parsed form to string form."
signature = parse_signature(signature)
if not isinstance(signature, (tuple, list)) :
signature = [signature]
#end if
return \
DBUS.Signature("".join(t.signature for t in signature)) | python | {
"resource": ""
} |
q240775 | signature_validate_single | train | def signature_validate_single(signature, error = None) :
"is signature a single valid type."
error, my_error = _get_error(error)
result = dbus.dbus_signature_validate_single(signature.encode(), error._dbobj) != 0
my_error.raise_if_set()
return \
result | python | {
"resource": ""
} |
q240776 | split_path | train | def split_path(path) :
"convenience routine for splitting a path into a list of components."
if isinstance(path, (tuple, list)) :
result = path # assume already split
elif path == "/" :
result = []
else :
if not path.startswith("/") or path.endswith("/") :
raise DBusE... | python | {
"resource": ""
} |
q240777 | validate_utf8 | train | def validate_utf8(alleged_utf8, error = None) :
"alleged_utf8 must be null-terminated bytes."
error, my_error = _get_error(error)
result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0
my_error.raise_if_set()
return \
result | python | {
"resource": ""
} |
q240778 | DBUS.int_subtype | train | def int_subtype(i, bits, signed) :
"returns integer i after checking that it fits in the given number of bits."
if not isinstance(i, int) :
raise TypeError("value is not int: %s" % repr(i))
#end if
if signed :
lo = - 1 << bits - 1
hi = (1 << bits - 1) ... | python | {
"resource": ""
} |
q240779 | Connection.server_id | train | def server_id(self) :
"asks the server at the other end for its unique id."
c_result = dbus.dbus_connection_get_server_id(self._dbobj)
result = ct.cast(c_result, ct.c_char_p).value.decode()
dbus.dbus_free(c_result)
return \
result | python | {
"resource": ""
} |
q240780 | Connection.send | train | def send(self, message) :
"puts a message in the outgoing queue."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
serial = ct.c_uint()
if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) :
... | python | {
"resource": ""
} |
q240781 | Connection.send_with_reply_and_block | train | def send_with_reply_and_block(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT, error = None) :
"sends a message, blocks the thread until the reply is available, and returns it."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
error... | python | {
"resource": ""
} |
q240782 | Connection.list_registered | train | def list_registered(self, parent_path) :
"lists all the object paths for which you have ObjectPathVTable handlers registered."
child_entries = ct.POINTER(ct.c_char_p)()
if not dbus.dbus_connection_list_registered(self._dbobj, parent_path.encode(), ct.byref(child_entries)) :
raise Cal... | python | {
"resource": ""
} |
q240783 | Connection.bus_get | train | def bus_get(celf, type, private, error = None) :
"returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value."
error, my_error = _get_error(error)
result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj)
my_error.raise_if_set()
... | python | {
"resource": ""
} |
q240784 | Connection.become_monitor | train | def become_monitor(self, rules) :
"turns the connection into one that can only receive monitoring messages."
message = Message.new_method_call \
(
destination = DBUS.SERVICE_DBUS,
path = DBUS.PATH_DBUS,
iface = DBUS.INTERFACE_MONITORING,
method =... | python | {
"resource": ""
} |
q240785 | PreallocatedSend.send | train | def send(self, message) :
"alternative to Connection.send_preallocated."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
assert not self._sent, "preallocated has already been sent"
serial = ct.c_uint()
dbus.dbus_conne... | python | {
"resource": ""
} |
q240786 | Message.new_error | train | def new_error(self, name, message) :
"creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message."
result = dbus.dbus_message_new_error(self._dbobj, name.encode(), (lambda : None, lambda : message.encode())[message != None]())
if result == None :
raise CallFailed("... | python | {
"resource": ""
} |
q240787 | Message.new_method_call | train | def new_method_call(celf, destination, path, iface, method) :
"creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message."
result = dbus.dbus_message_new_method_call \
(
(lambda : None, lambda : destination.encode())[destination != None](),
path.encode(),
(lambda ... | python | {
"resource": ""
} |
q240788 | Message.new_method_return | train | def new_method_return(self) :
"creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message."
result = dbus.dbus_message_new_method_return(self._dbobj)
if result == None :
raise CallFailed("dbus_message_new_method_return")
#end if
return \
... | python | {
"resource": ""
} |
q240789 | Message.new_signal | train | def new_signal(celf, path, iface, name) :
"creates a new DBUS.MESSAGE_TYPE_SIGNAL message."
result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode())
if result == None :
raise CallFailed("dbus_message_new_signal")
#end if
return \
... | python | {
"resource": ""
} |
q240790 | Message.copy | train | def copy(self) :
"creates a copy of this Message."
result = dbus.dbus_message_copy(self._dbobj)
if result == None :
raise CallFailed("dbus_message_copy")
#end if
return \
type(self)(result) | python | {
"resource": ""
} |
q240791 | Message.iter_init | train | def iter_init(self) :
"creates an iterator for extracting the arguments of the Message."
iter = self.ExtractIter(None)
if dbus.dbus_message_iter_init(self._dbobj, iter._dbobj) == 0 :
iter._nulliter = True
#end if
return \
iter | python | {
"resource": ""
} |
q240792 | Message.iter_init_append | train | def iter_init_append(self) :
"creates a Message.AppendIter for appending arguments to the Message."
iter = self.AppendIter(None)
dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj)
return \
iter | python | {
"resource": ""
} |
q240793 | Message.error_name | train | def error_name(self) :
"the error name for a DBUS.MESSAGE_TYPE_ERROR message."
result = dbus.dbus_message_get_error_name(self._dbobj)
if result != None :
result = result.decode()
#end if
return \
result | python | {
"resource": ""
} |
q240794 | Message.destination | train | def destination(self) :
"the bus name that the message is to be sent to."
result = dbus.dbus_message_get_destination(self._dbobj)
if result != None :
result = result.decode()
#end if
return \
result | python | {
"resource": ""
} |
q240795 | Message.marshal | train | def marshal(self) :
"serializes this Message into the wire protocol format and returns a bytes object."
buf = ct.POINTER(ct.c_ubyte)()
nr_bytes = ct.c_int()
if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) :
raise CallFailed("dbus_message_marsh... | python | {
"resource": ""
} |
q240796 | PendingCall.cancel | train | def cancel(self) :
"tells libdbus you no longer care about the pending incoming message."
dbus.dbus_pending_call_cancel(self._dbobj)
if self._awaiting != None :
# This probably shouldn’t occur. Looking at the source of libdbus,
# it doesn’t keep track of any “cancelled” s... | python | {
"resource": ""
} |
q240797 | Error.set | train | def set(self, name, msg) :
"fills in the error name and message."
dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode()) | python | {
"resource": ""
} |
q240798 | Introspection.parse | train | def parse(celf, s) :
"generates an Introspection tree from the given XML string description."
def from_string_elts(celf, attrs, tree) :
elts = dict((k, attrs[k]) for k in attrs)
child_tags = dict \
(
(childclass.tag_name, childclass)
... | python | {
"resource": ""
} |
q240799 | Introspection.unparse | train | def unparse(self, indent_step = 4, max_linelen = 72) :
"returns an XML string description of this Introspection tree."
out = io.StringIO()
def to_string(obj, indent) :
tag_name = obj.tag_name
attrs = []
for attrname in obj.tag_attrs :
attr = ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.