id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,600
swistakm/graceful
src/graceful/serializers.py
BaseSerializer.to_representation
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 field values with respect to optional field sources and converts each one using ``field.to_representation()`` method. Args: obj (object): internal object that needs to be represented Returns: dict: representation dictionary """ representation = {} for name, field in self.fields.items(): if field.write_only: continue # note fields do not know their names in source representation # but may know what attribute they target from source object attribute = self.get_attribute(obj, field.source or name) if attribute is None: # Skip none attributes so fields do not have to deal with them representation[name] = [] if field.many else None elif field.many: representation[name] = [ field.to_representation(item) for item in attribute ] else: representation[name] = field.to_representation(attribute) return representation
python
def to_representation(self, obj): representation = {} for name, field in self.fields.items(): if field.write_only: continue # note fields do not know their names in source representation # but may know what attribute they target from source object attribute = self.get_attribute(obj, field.source or name) if attribute is None: # Skip none attributes so fields do not have to deal with them representation[name] = [] if field.many else None elif field.many: representation[name] = [ field.to_representation(item) for item in attribute ] else: representation[name] = field.to_representation(attribute) return representation
[ "def", "to_representation", "(", "self", ",", "obj", ")", ":", "representation", "=", "{", "}", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "field", ".", "write_only", ":", "continue", "# note fields do no...
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 field values with respect to optional field sources and converts each one using ``field.to_representation()`` method. Args: obj (object): internal object that needs to be represented Returns: dict: representation dictionary
[ "Convert", "given", "internal", "object", "instance", "into", "representation", "dict", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L101-L138
25,601
swistakm/graceful
src/graceful/serializers.py
BaseSerializer.from_representation
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 validation (see: :meth:`BaseField.validate()`) but still requires all of passed representation values to be well formed representation (success call to ``field.from_representation``). In case of malformed representation it will run additional validation only to provide a full detailed exception about all that might be wrong with provided representation. Args: representation (dict): dictionary with field representation values Raises: DeserializationError: when at least one representation field is not formed as expected by field object. Information about additional forbidden/missing/invalid fields is provided as well. """ object_dict = {} failed = {} for name, field in self.fields.items(): if name not in representation: continue try: if ( # note: we cannot check for any sequence or iterable # because of strings and nested dicts. not isinstance(representation[name], (list, tuple)) and field.many ): raise ValueError("field should be sequence") source = _source(name, field) value = representation[name] if field.many: if not field.allow_null: object_dict[source] = [ field.from_representation(single_value) for single_value in value ] else: object_dict[source] = [ field.from_representation(single_value) if single_value is not None else None for single_value in value ] else: if not field.allow_null: object_dict[source] = field.from_representation(value) else: object_dict[source] = field.from_representation( value) if value else None except ValueError as err: failed[name] = str(err) if failed: # if failed to parse we eagerly perform validation so full # information about what is wrong will be returned try: self.validate(object_dict) # note: this exception can be reached with partial==True # since do not support partial updates yet this has 'no cover' raise DeserializationError() # pragma: no cover except DeserializationError as err: err.failed = failed raise return object_dict
python
def from_representation(self, representation): object_dict = {} failed = {} for name, field in self.fields.items(): if name not in representation: continue try: if ( # note: we cannot check for any sequence or iterable # because of strings and nested dicts. not isinstance(representation[name], (list, tuple)) and field.many ): raise ValueError("field should be sequence") source = _source(name, field) value = representation[name] if field.many: if not field.allow_null: object_dict[source] = [ field.from_representation(single_value) for single_value in value ] else: object_dict[source] = [ field.from_representation(single_value) if single_value is not None else None for single_value in value ] else: if not field.allow_null: object_dict[source] = field.from_representation(value) else: object_dict[source] = field.from_representation( value) if value else None except ValueError as err: failed[name] = str(err) if failed: # if failed to parse we eagerly perform validation so full # information about what is wrong will be returned try: self.validate(object_dict) # note: this exception can be reached with partial==True # since do not support partial updates yet this has 'no cover' raise DeserializationError() # pragma: no cover except DeserializationError as err: err.failed = failed raise return object_dict
[ "def", "from_representation", "(", "self", ",", "representation", ")", ":", "object_dict", "=", "{", "}", "failed", "=", "{", "}", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "if", "name", "not", "in", "repr...
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 validation (see: :meth:`BaseField.validate()`) but still requires all of passed representation values to be well formed representation (success call to ``field.from_representation``). In case of malformed representation it will run additional validation only to provide a full detailed exception about all that might be wrong with provided representation. Args: representation (dict): dictionary with field representation values Raises: DeserializationError: when at least one representation field is not formed as expected by field object. Information about additional forbidden/missing/invalid fields is provided as well.
[ "Convert", "given", "representation", "dict", "into", "internal", "object", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L140-L218
25,602
swistakm/graceful
src/graceful/serializers.py
BaseSerializer.get_attribute
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 Args: obj (object): internal object to retrieve data from Returns: internal object's key value or attribute """ # '*' is a special wildcard character that means whole object # is passed if attr == '*': return obj # if this is any mapping then instead of attributes use keys if isinstance(obj, Mapping): return obj.get(attr, None) return getattr(obj, attr, None)
python
def get_attribute(self, obj, attr): # '*' is a special wildcard character that means whole object # is passed if attr == '*': return obj # if this is any mapping then instead of attributes use keys if isinstance(obj, Mapping): return obj.get(attr, None) return getattr(obj, attr, None)
[ "def", "get_attribute", "(", "self", ",", "obj", ",", "attr", ")", ":", "# '*' is a special wildcard character that means whole object", "# is passed", "if", "attr", "==", "'*'", ":", "return", "obj", "# if this is any mapping then instead of attributes use keys", "if", "is...
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 Args: obj (object): internal object to retrieve data from Returns: internal object's key value or attribute
[ "Get", "attribute", "of", "given", "object", "instance", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L299-L323
25,603
swistakm/graceful
src/graceful/serializers.py
BaseSerializer.set_attribute
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 modify attr (str): attribute (or key) to change value: value to set """ # if this is any mutable mapping then instead of attributes use keys if isinstance(obj, MutableMapping): obj[attr] = value else: setattr(obj, attr, value)
python
def set_attribute(self, obj, attr, value): # if this is any mutable mapping then instead of attributes use keys if isinstance(obj, MutableMapping): obj[attr] = value else: setattr(obj, attr, value)
[ "def", "set_attribute", "(", "self", ",", "obj", ",", "attr", ",", "value", ")", ":", "# if this is any mutable mapping then instead of attributes use keys", "if", "isinstance", "(", "obj", ",", "MutableMapping", ")", ":", "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 modify attr (str): attribute (or key) to change value: value to set
[ "Set", "value", "of", "attribute", "in", "given", "object", "instance", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L325-L341
25,604
swistakm/graceful
src/graceful/serializers.py
BaseSerializer.describe
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: serializer description """ return OrderedDict([ (name, field.describe()) for name, field in self.fields.items() ])
python
def describe(self): return OrderedDict([ (name, field.describe()) for name, field in self.fields.items() ])
[ "def", "describe", "(", "self", ")", ":", "return", "OrderedDict", "(", "[", "(", "name", ",", "field", ".", "describe", "(", ")", ")", "for", "name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", "]", ")" ]
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: serializer description
[ "Describe", "all", "serialized", "fields", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L343-L357
25,605
tomplus/kubernetes_asyncio
kubernetes_asyncio/config/incluster_config.py
_join_host_port
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
def _join_host_port(host, port): template = "%s:%s" host_requires_bracketing = ':' in host or '%' in host if host_requires_bracketing: template = "[%s]:%s" return template % (host, port)
[ "def", "_join_host_port", "(", "host", ",", "port", ")", ":", "template", "=", "\"%s:%s\"", "host_requires_bracketing", "=", "':'", "in", "host", "or", "'%'", "in", "host", "if", "host_requires_bracketing", ":", "template", "=", "\"[%s]:%s\"", "return", "templat...
Adapted golang's net.JoinHostPort
[ "Adapted", "golang", "s", "net", ".", "JoinHostPort" ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/incluster_config.py#L27-L33
25,606
swistakm/graceful
src/graceful/resources/mixins.py
BaseMixin.handle
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.) the flow is always the same: 1. Decode and validate all request parameters from the query string using ``self.require_params()`` method. 2. Use ``self.require_meta_and_content()`` method to construct ``meta`` and ``content`` dictionaries that will be later used to create serialized response body. 3. Construct serialized response body using ``self.body()`` method. Args: handler (method): resource manipulation method handler. req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified. **kwargs: additional keyword arguments retrieved from url template. Returns: Content dictionary (preferably resource representation). """ params = self.require_params(req) # future: remove in 1.x if getattr(self, '_with_context', False): handler = partial(handler, context=req.context) meta, content = self.require_meta_and_content( handler, params, **kwargs ) self.make_body(resp, params, meta, content) return content
python
def handle(self, handler, req, resp, **kwargs): params = self.require_params(req) # future: remove in 1.x if getattr(self, '_with_context', False): handler = partial(handler, context=req.context) meta, content = self.require_meta_and_content( handler, params, **kwargs ) self.make_body(resp, params, meta, content) return content
[ "def", "handle", "(", "self", ",", "handler", ",", "req", ",", "resp", ",", "*", "*", "kwargs", ")", ":", "params", "=", "self", ".", "require_params", "(", "req", ")", "# future: remove in 1.x", "if", "getattr", "(", "self", ",", "'_with_context'", ",",...
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.) the flow is always the same: 1. Decode and validate all request parameters from the query string using ``self.require_params()`` method. 2. Use ``self.require_meta_and_content()`` method to construct ``meta`` and ``content`` dictionaries that will be later used to create serialized response body. 3. Construct serialized response body using ``self.body()`` method. Args: handler (method): resource manipulation method handler. req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified. **kwargs: additional keyword arguments retrieved from url template. Returns: Content dictionary (preferably resource representation).
[ "Handle", "given", "resource", "manipulation", "flow", "in", "consistent", "manner", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L11-L45
25,607
swistakm/graceful
src/graceful/resources/mixins.py
RetrieveMixin.on_get
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 resource instance of prepare its representation by calling retrieve method handler. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): list method handler to be called. Defaults to ``self.list``. **kwargs: additional keyword arguments retrieved from url template. """ self.handle( handler or self.retrieve, req, resp, **kwargs )
python
def on_get(self, req, resp, handler=None, **kwargs): self.handle( handler or self.retrieve, req, resp, **kwargs )
[ "def", "on_get", "(", "self", ",", "req", ",", "resp", ",", "handler", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle", "(", "handler", "or", "self", ".", "retrieve", ",", "req", ",", "resp", ",", "*", "*", "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 resource instance of prepare its representation by calling retrieve method handler. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): list method handler to be called. Defaults to ``self.list``. **kwargs: additional keyword arguments retrieved from url template.
[ "Respond", "on", "GET", "HTTP", "request", "assuming", "resource", "retrieval", "flow", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L75-L94
25,608
swistakm/graceful
src/graceful/resources/mixins.py
ListMixin.on_get
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 resource instances and prepare their representations by calling list retrieval method handler. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): list method handler to be called. Defaults to ``self.list``. **kwargs: additional keyword arguments retrieved from url template. """ self.handle( handler or self.list, req, resp, **kwargs )
python
def on_get(self, req, resp, handler=None, **kwargs): self.handle( handler or self.list, req, resp, **kwargs )
[ "def", "on_get", "(", "self", ",", "req", ",", "resp", ",", "handler", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle", "(", "handler", "or", "self", ".", "list", ",", "req", ",", "resp", ",", "*", "*", "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 resource instances and prepare their representations by calling list retrieval method handler. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): list method handler to be called. Defaults to ``self.list``. **kwargs: additional keyword arguments retrieved from url template.
[ "Respond", "on", "GET", "HTTP", "request", "assuming", "resource", "list", "retrieval", "flow", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L124-L142
25,609
swistakm/graceful
src/graceful/resources/mixins.py
DeleteMixin.on_delete
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 instance. * Set response status code to ``202 Accepted``. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): deletion method handler to be called. Defaults to ``self.delete``. **kwargs: additional keyword arguments retrieved from url template. """ self.handle( handler or self.delete, req, resp, **kwargs ) resp.status = falcon.HTTP_ACCEPTED
python
def on_delete(self, req, resp, handler=None, **kwargs): self.handle( handler or self.delete, req, resp, **kwargs ) resp.status = falcon.HTTP_ACCEPTED
[ "def", "on_delete", "(", "self", ",", "req", ",", "resp", ",", "handler", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle", "(", "handler", "or", "self", ".", "delete", ",", "req", ",", "resp", ",", "*", "*", "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 instance. * Set response status code to ``202 Accepted``. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): deletion method handler to be called. Defaults to ``self.delete``. **kwargs: additional keyword arguments retrieved from url template.
[ "Respond", "on", "DELETE", "HTTP", "request", "assuming", "resource", "deletion", "flow", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L168-L188
25,610
swistakm/graceful
src/graceful/resources/mixins.py
UpdateMixin.on_put
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 instance and prepare its representation by calling its update method handler. * Set response status code to ``202 Accepted``. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): update method handler to be called. Defaults to ``self.update``. **kwargs: additional keyword arguments retrieved from url template. """ self.handle( handler or self.update, req, resp, **kwargs ) resp.status = falcon.HTTP_ACCEPTED
python
def on_put(self, req, resp, handler=None, **kwargs): self.handle( handler or self.update, req, resp, **kwargs ) resp.status = falcon.HTTP_ACCEPTED
[ "def", "on_put", "(", "self", ",", "req", ",", "resp", ",", "handler", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle", "(", "handler", "or", "self", ".", "update", ",", "req", ",", "resp", ",", "*", "*", "kwargs", ")", "r...
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 instance and prepare its representation by calling its update method handler. * Set response status code to ``202 Accepted``. Args: req (falcon.Request): request object instance. resp (falcon.Response): response object instance to be modified handler (method): update method handler to be called. Defaults to ``self.update``. **kwargs: additional keyword arguments retrieved from url template.
[ "Respond", "on", "PUT", "HTTP", "request", "assuming", "resource", "update", "flow", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L217-L237
25,611
swistakm/graceful
src/graceful/resources/mixins.py
PaginatedMixin.add_pagination_meta
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 with any other dict instance but simply modify its content. Args: params (dict): dictionary of decoded parameter values meta (dict): dictionary of meta values attached to response """ meta['page_size'] = params['page_size'] meta['page'] = params['page'] meta['prev'] = "page={0}&page_size={1}".format( params['page'] - 1, params['page_size'] ) if meta['page'] > 0 else None meta['next'] = "page={0}&page_size={1}".format( params['page'] + 1, params['page_size'] ) if meta.get('has_more', True) else None
python
def add_pagination_meta(self, params, meta): meta['page_size'] = params['page_size'] meta['page'] = params['page'] meta['prev'] = "page={0}&page_size={1}".format( params['page'] - 1, params['page_size'] ) if meta['page'] > 0 else None meta['next'] = "page={0}&page_size={1}".format( params['page'] + 1, params['page_size'] ) if meta.get('has_more', True) else None
[ "def", "add_pagination_meta", "(", "self", ",", "params", ",", "meta", ")", ":", "meta", "[", "'page_size'", "]", "=", "params", "[", "'page_size'", "]", "meta", "[", "'page'", "]", "=", "params", "[", "'page'", "]", "meta", "[", "'prev'", "]", "=", ...
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 with any other dict instance but simply modify its content. Args: params (dict): dictionary of decoded parameter values meta (dict): dictionary of meta values attached to response
[ "Extend", "default", "meta", "dictionary", "value", "with", "pagination", "hints", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/mixins.py#L396-L418
25,612
swistakm/graceful
src/graceful/resources/base.py
MetaResource._get_params
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 params can be overriden. Args: bases: all base classes of created resource class namespace (dict): namespace as dictionary of attributes """ params = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseParam) ] for base in reversed(bases): if hasattr(base, mcs._params_storage_key): params = list( getattr(base, mcs._params_storage_key).items() ) + params return OrderedDict(params)
python
def _get_params(mcs, bases, namespace): params = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseParam) ] for base in reversed(bases): if hasattr(base, mcs._params_storage_key): params = list( getattr(base, mcs._params_storage_key).items() ) + params return OrderedDict(params)
[ "def", "_get_params", "(", "mcs", ",", "bases", ",", "namespace", ")", ":", "params", "=", "[", "(", "name", ",", "namespace", ".", "pop", "(", "name", ")", ")", "for", "name", ",", "attribute", "in", "list", "(", "namespace", ".", "items", "(", ")...
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 params can be overriden. Args: bases: all base classes of created resource class namespace (dict): namespace as dictionary of attributes
[ "Create", "params", "dictionary", "to", "be", "used", "in", "resource", "class", "namespace", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L35-L61
25,613
swistakm/graceful
src/graceful/resources/base.py
BaseResource.make_body
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 meta (dict): dictionary of metadata to be included in 'meta' section of response content (dict): dictionary of response content (resource representation) to be included in 'content' section of response Returns: None """ response = { 'meta': meta, 'content': content } resp.content_type = 'application/json' resp.body = json.dumps( response, indent=params['indent'] or None if 'indent' in params else None )
python
def make_body(self, resp, params, meta, content): response = { 'meta': meta, 'content': content } resp.content_type = 'application/json' resp.body = json.dumps( response, indent=params['indent'] or None if 'indent' in params else None )
[ "def", "make_body", "(", "self", ",", "resp", ",", "params", ",", "meta", ",", "content", ")", ":", "response", "=", "{", "'meta'", ":", "meta", ",", "'content'", ":", "content", "}", "resp", ".", "content_type", "=", "'application/json'", "resp", ".", ...
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 meta (dict): dictionary of metadata to be included in 'meta' section of response content (dict): dictionary of response content (resource representation) to be included in 'content' section of response Returns: None
[ "Construct", "response", "body", "in", "resp", "object", "using", "JSON", "serialization", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L153-L177
25,614
swistakm/graceful
src/graceful/resources/base.py
BaseResource.allowed_methods
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 in ( ('GET', hasattr(self, 'on_get')), ('POST', hasattr(self, 'on_post')), ('PUT', hasattr(self, 'on_put')), ('PATCH', hasattr(self, 'on_patch')), ('DELETE', hasattr(self, 'on_delete')), ('HEAD', hasattr(self, 'on_head')), ('OPTIONS', hasattr(self, 'on_options')), ) if allowed ]
python
def allowed_methods(self): return [ method for method, allowed in ( ('GET', hasattr(self, 'on_get')), ('POST', hasattr(self, 'on_post')), ('PUT', hasattr(self, 'on_put')), ('PATCH', hasattr(self, 'on_patch')), ('DELETE', hasattr(self, 'on_delete')), ('HEAD', hasattr(self, 'on_head')), ('OPTIONS', hasattr(self, 'on_options')), ) if allowed ]
[ "def", "allowed_methods", "(", "self", ")", ":", "return", "[", "method", "for", "method", ",", "allowed", "in", "(", "(", "'GET'", ",", "hasattr", "(", "self", ",", "'on_get'", ")", ")", ",", "(", "'POST'", ",", "hasattr", "(", "self", ",", "'on_pos...
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", "list", "of", "allowed", "HTTP", "methods", "on", "this", "resource", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L179-L199
25,615
swistakm/graceful
src/graceful/resources/base.py
BaseResource.describe
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 class SomeResource(BaseResource): def describe(req, resp, **kwargs): return super().describe( req, resp, type='list', **kwargs ) Args: req (falcon.Request): request object resp (falcon.Response): response object kwargs (dict): dictionary of values created from resource url template Returns: dict: dictionary with resource descritpion information .. versionchanged:: 0.2.0 The `req` and `resp` parameters became optional to ease the implementation of application-level documentation generators. """ description = { 'params': OrderedDict([ (name, param.describe()) for name, param in self.params.items() ]), 'details': inspect.cleandoc( self.__class__.__doc__ or "This resource does not have description yet" ), 'name': self.__class__.__name__, 'methods': self.allowed_methods() } # note: add path to resource description only if request object was # provided in order to make auto-documentation engines simpler if req: description['path'] = req.path description.update(**kwargs) return description
python
def describe(self, req=None, resp=None, **kwargs): description = { 'params': OrderedDict([ (name, param.describe()) for name, param in self.params.items() ]), 'details': inspect.cleandoc( self.__class__.__doc__ or "This resource does not have description yet" ), 'name': self.__class__.__name__, 'methods': self.allowed_methods() } # note: add path to resource description only if request object was # provided in order to make auto-documentation engines simpler if req: description['path'] = req.path description.update(**kwargs) return description
[ "def", "describe", "(", "self", ",", "req", "=", "None", ",", "resp", "=", "None", ",", "*", "*", "kwargs", ")", ":", "description", "=", "{", "'params'", ":", "OrderedDict", "(", "[", "(", "name", ",", "param", ".", "describe", "(", ")", ")", "f...
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 class SomeResource(BaseResource): def describe(req, resp, **kwargs): return super().describe( req, resp, type='list', **kwargs ) Args: req (falcon.Request): request object resp (falcon.Response): response object kwargs (dict): dictionary of values created from resource url template Returns: dict: dictionary with resource descritpion information .. versionchanged:: 0.2.0 The `req` and `resp` parameters became optional to ease the implementation of application-level documentation generators.
[ "Describe", "API", "resource", "using", "resource", "introspection", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L201-L248
25,616
swistakm/graceful
src/graceful/resources/base.py
BaseResource.on_options
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): Dictionary of values created by falcon from resource uri template. Returns: None .. versionchanged:: 0.2.0 Default ``OPTIONS`` responses include ``Allow`` header with list of allowed HTTP methods. """ resp.set_header('Allow', ', '.join(self.allowed_methods())) resp.body = json.dumps(self.describe(req, resp)) resp.content_type = 'application/json'
python
def on_options(self, req, resp, **kwargs): resp.set_header('Allow', ', '.join(self.allowed_methods())) resp.body = json.dumps(self.describe(req, resp)) resp.content_type = 'application/json'
[ "def", "on_options", "(", "self", ",", "req", ",", "resp", ",", "*", "*", "kwargs", ")", ":", "resp", ".", "set_header", "(", "'Allow'", ",", "', '", ".", "join", "(", "self", ".", "allowed_methods", "(", ")", ")", ")", "resp", ".", "body", "=", ...
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): Dictionary of values created by falcon from resource uri template. Returns: None .. versionchanged:: 0.2.0 Default ``OPTIONS`` responses include ``Allow`` header with list of allowed HTTP methods.
[ "Respond", "with", "JSON", "formatted", "resource", "description", "on", "OPTIONS", "request", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L250-L269
25,617
swistakm/graceful
src/graceful/resources/base.py
BaseResource.require_params
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). Args: req (falcon.Request): request object """ params = {} for name, param in self.params.items(): if name not in req.params and param.required: # we could simply raise with this single param or use get_param # with required=True parameter but for client convenience # we prefer to list all missing params that are required missing = set( p for p in self.params if self.params[p].required ) - set(req.params.keys()) raise errors.HTTPMissingParam(", ".join(missing)) elif name in req.params or param.default: # Note: lack of key in req.params means it was not specified # so unless there is default value it will not be included in # output params dict. # This way we have explicit information that param was # not specified. Using None would not be as good because param # class can also return None from `.value()` method as a valid # translated value. try: if param.many: # params with "many" enabled need special care values = req.get_param_as_list( # note: falcon allows to pass value handler using # `transform` param so we do not need to # iterate through list manually name, param.validated_value ) or [ param.default and param.validated_value(param.default) ] params[name] = param.container(values) else: # note that if many==False and query parameter # occurs multiple times in qs then it is # **unspecified** which one will be used. See: # http://falcon.readthedocs.org/en/latest/api/request_and_response.html#falcon.Request.get_param # noqa params[name] = param.validated_value( req.get_param(name, default=param.default) ) except ValidationError as err: # ValidationError allows to easily translate itself to # to falcon's HTTPInvalidParam (Bad Request HTTP response) raise err.as_invalid_param(name) except ValueError as err: # Other parsing issues are expected to raise ValueError raise errors.HTTPInvalidParam(str(err), name) return params
python
def require_params(self, req): params = {} for name, param in self.params.items(): if name not in req.params and param.required: # we could simply raise with this single param or use get_param # with required=True parameter but for client convenience # we prefer to list all missing params that are required missing = set( p for p in self.params if self.params[p].required ) - set(req.params.keys()) raise errors.HTTPMissingParam(", ".join(missing)) elif name in req.params or param.default: # Note: lack of key in req.params means it was not specified # so unless there is default value it will not be included in # output params dict. # This way we have explicit information that param was # not specified. Using None would not be as good because param # class can also return None from `.value()` method as a valid # translated value. try: if param.many: # params with "many" enabled need special care values = req.get_param_as_list( # note: falcon allows to pass value handler using # `transform` param so we do not need to # iterate through list manually name, param.validated_value ) or [ param.default and param.validated_value(param.default) ] params[name] = param.container(values) else: # note that if many==False and query parameter # occurs multiple times in qs then it is # **unspecified** which one will be used. See: # http://falcon.readthedocs.org/en/latest/api/request_and_response.html#falcon.Request.get_param # noqa params[name] = param.validated_value( req.get_param(name, default=param.default) ) except ValidationError as err: # ValidationError allows to easily translate itself to # to falcon's HTTPInvalidParam (Bad Request HTTP response) raise err.as_invalid_param(name) except ValueError as err: # Other parsing issues are expected to raise ValueError raise errors.HTTPInvalidParam(str(err), name) return params
[ "def", "require_params", "(", "self", ",", "req", ")", ":", "params", "=", "{", "}", "for", "name", ",", "param", "in", "self", ".", "params", ".", "items", "(", ")", ":", "if", "name", "not", "in", "req", ".", "params", "and", "param", ".", "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). Args: req (falcon.Request): request object
[ "Require", "all", "defined", "parameters", "from", "request", "query", "string", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L271-L335
25,618
swistakm/graceful
src/graceful/resources/base.py
BaseResource.require_meta_and_content
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 ``content`` response section params (dict): dictionary of parsed resource parameters kwargs (dict): dictionary of values created from resource url template Returns: tuple (meta, content): two-tuple with dictionaries of ``meta`` and ``content`` response sections """ meta = { 'params': params } content = content_handler(params, meta, **kwargs) meta['params'] = params return meta, content
python
def require_meta_and_content(self, content_handler, params, **kwargs): meta = { 'params': params } content = content_handler(params, meta, **kwargs) meta['params'] = params return meta, content
[ "def", "require_meta_and_content", "(", "self", ",", "content_handler", ",", "params", ",", "*", "*", "kwargs", ")", ":", "meta", "=", "{", "'params'", ":", "params", "}", "content", "=", "content_handler", "(", "params", ",", "meta", ",", "*", "*", "kwa...
Require 'meta' and 'content' dictionaries using proper hander. Args: content_handler (callable): function that accepts ``params, meta, **kwargs`` argument and returns dictionary for ``content`` response section params (dict): dictionary of parsed resource parameters kwargs (dict): dictionary of values created from resource url template Returns: tuple (meta, content): two-tuple with dictionaries of ``meta`` and ``content`` response sections
[ "Require", "meta", "and", "content", "dictionaries", "using", "proper", "hander", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L337-L358
25,619
swistakm/graceful
src/graceful/resources/base.py
BaseResource.require_representation
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 content type. Args: req (falcon.Request): request object Returns: dict: raw dictionary of representation supplied in request body """ try: type_, subtype, _ = parse_mime_type(req.content_type) content_type = '/'.join((type_, subtype)) except: raise falcon.HTTPUnsupportedMediaType( description="Invalid Content-Type header: {}".format( req.content_type ) ) if content_type == 'application/json': body = req.stream.read() return json.loads(body.decode('utf-8')) else: raise falcon.HTTPUnsupportedMediaType( description="only JSON supported, got: {}".format(content_type) )
python
def require_representation(self, req): try: type_, subtype, _ = parse_mime_type(req.content_type) content_type = '/'.join((type_, subtype)) except: raise falcon.HTTPUnsupportedMediaType( description="Invalid Content-Type header: {}".format( req.content_type ) ) if content_type == 'application/json': body = req.stream.read() return json.loads(body.decode('utf-8')) else: raise falcon.HTTPUnsupportedMediaType( description="only JSON supported, got: {}".format(content_type) )
[ "def", "require_representation", "(", "self", ",", "req", ")", ":", "try", ":", "type_", ",", "subtype", ",", "_", "=", "parse_mime_type", "(", "req", ".", "content_type", ")", "content_type", "=", "'/'", ".", "join", "(", "(", "type_", ",", "subtype", ...
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 content type. Args: req (falcon.Request): request object Returns: dict: raw dictionary of representation supplied in request body
[ "Require", "raw", "representation", "dictionary", "from", "falcon", "request", "object", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L360-L392
25,620
swistakm/graceful
src/graceful/resources/base.py
BaseResource.require_validated
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 serializer. Args: req (falcon.Request): request object partial (bool): set to True if partially complete representation is accepted (e.g. for patching instead of full update). Missing fields in representation will be skiped. bulk (bool): set to True if request payload represents multiple resources instead of single one. Returns: dict: dictionary of fields and values representing internal object. Each value is a result of ``field.from_representation`` call. """ representations = [ self.require_representation(req) ] if not bulk else self.require_representation(req) if bulk and not isinstance(representations, list): raise ValidationError( "Request payload should represent a list of resources." ).as_bad_request() object_dicts = [] try: for representation in representations: object_dict = self.serializer.from_representation( representation ) self.serializer.validate(object_dict, partial) object_dicts.append(object_dict) except DeserializationError as err: # when working on Resource we know that we can finally raise # bad request exceptions raise err.as_bad_request() except ValidationError as err: # ValidationError is a suggested way to validate whole resource # so we also are prepared to catch it raise err.as_bad_request() return object_dicts if bulk else object_dicts[0]
python
def require_validated(self, req, partial=False, bulk=False): representations = [ self.require_representation(req) ] if not bulk else self.require_representation(req) if bulk and not isinstance(representations, list): raise ValidationError( "Request payload should represent a list of resources." ).as_bad_request() object_dicts = [] try: for representation in representations: object_dict = self.serializer.from_representation( representation ) self.serializer.validate(object_dict, partial) object_dicts.append(object_dict) except DeserializationError as err: # when working on Resource we know that we can finally raise # bad request exceptions raise err.as_bad_request() except ValidationError as err: # ValidationError is a suggested way to validate whole resource # so we also are prepared to catch it raise err.as_bad_request() return object_dicts if bulk else object_dicts[0]
[ "def", "require_validated", "(", "self", ",", "req", ",", "partial", "=", "False", ",", "bulk", "=", "False", ")", ":", "representations", "=", "[", "self", ".", "require_representation", "(", "req", ")", "]", "if", "not", "bulk", "else", "self", ".", ...
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 serializer. Args: req (falcon.Request): request object partial (bool): set to True if partially complete representation is accepted (e.g. for patching instead of full update). Missing fields in representation will be skiped. bulk (bool): set to True if request payload represents multiple resources instead of single one. Returns: dict: dictionary of fields and values representing internal object. Each value is a result of ``field.from_representation`` call.
[ "Require", "fully", "validated", "internal", "object", "dictionary", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/base.py#L394-L443
25,621
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py
AdmissionregistrationV1beta1WebhookClientConfig.ca_bundle
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 :param ca_bundle: The ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. # noqa: E501 :type: str """ if ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle): # noqa: E501 raise ValueError(r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._ca_bundle = ca_bundle
python
def ca_bundle(self, ca_bundle): if ca_bundle is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', ca_bundle): # noqa: E501 raise ValueError(r"Invalid value for `ca_bundle`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._ca_bundle = ca_bundle
[ "def", "ca_bundle", "(", "self", ",", "ca_bundle", ")", ":", "if", "ca_bundle", "is", "not", "None", "and", "not", "re", ".", "search", "(", "r'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'", ",", "ca_bundle", ")", ":", "# noqa: E501", "rai...
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 :param ca_bundle: The ca_bundle of this AdmissionregistrationV1beta1WebhookClientConfig. # noqa: E501 :type: str
[ "Sets", "the", "ca_bundle", "of", "this", "AdmissionregistrationV1beta1WebhookClientConfig", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/admissionregistration_v1beta1_webhook_client_config.py#L72-L83
25,622
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_status.py
V1beta1CertificateSigningRequestStatus.certificate
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: E501 :type: str """ if certificate is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', certificate): # noqa: E501 raise ValueError(r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._certificate = certificate
python
def certificate(self, certificate): if certificate is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', certificate): # noqa: E501 raise ValueError(r"Invalid value for `certificate`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._certificate = certificate
[ "def", "certificate", "(", "self", ",", "certificate", ")", ":", "if", "certificate", "is", "not", "None", "and", "not", "re", ".", "search", "(", "r'^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$'", ",", "certificate", ")", ":", "# noqa: E501"...
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: E501 :type: str
[ "Sets", "the", "certificate", "of", "this", "V1beta1CertificateSigningRequestStatus", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_status.py#L67-L78
25,623
swistakm/graceful
src/graceful/resources/generic.py
ListAPI.describe
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
def describe(self, req=None, resp=None, **kwargs): return super().describe( req, resp, type='list', fields=self.serializer.describe() if self.serializer else None, **kwargs )
[ "def", "describe", "(", "self", ",", "req", "=", "None", ",", "resp", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", ")", ".", "describe", "(", "req", ",", "resp", ",", "type", "=", "'list'", ",", "fields", "=", "self", ...
Extend default endpoint description with serializer description.
[ "Extend", "default", "endpoint", "description", "with", "serializer", "description", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/resources/generic.py#L163-L170
25,624
swistakm/graceful
src/graceful/authentication.py
DummyUserStorage.get_user
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): """Return default user object.""" return self.user
python
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): return self.user
[ "def", "get_user", "(", "self", ",", "identified_with", ",", "identifier", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "return", "self", ".", "user" ]
Return default user object.
[ "Return", "default", "user", "object", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L77-L81
25,625
swistakm/graceful
src/graceful/authentication.py
KeyValueUserStorage._get_storage_key
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
def _get_storage_key(self, identified_with, identifier): return ':'.join(( self.key_prefix, identified_with.name, self.hash_identifier(identified_with, identifier), ))
[ "def", "_get_storage_key", "(", "self", ",", "identified_with", ",", "identifier", ")", ":", "return", "':'", ".", "join", "(", "(", "self", ".", "key_prefix", ",", "identified_with", ".", "name", ",", "self", ".", "hash_identifier", "(", "identified_with", ...
Get key string for given user identifier in consistent manner.
[ "Get", "key", "string", "for", "given", "user", "identifier", "in", "consistent", "manner", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L166-L171
25,626
swistakm/graceful
src/graceful/authentication.py
KeyValueUserStorage.get_user
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 identifier (string or tuple in case of all built in authentication middleware classes). Returns: dict: user object stored in Redis if it exists, otherwise ``None`` """ stored_value = self.kv_store.get( self._get_storage_key(identified_with, identifier) ) if stored_value is not None: user = self.serialization.loads(stored_value.decode()) else: user = None return user
python
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): stored_value = self.kv_store.get( self._get_storage_key(identified_with, identifier) ) if stored_value is not None: user = self.serialization.loads(stored_value.decode()) else: user = None return user
[ "def", "get_user", "(", "self", ",", "identified_with", ",", "identifier", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "stored_value", "=", "self", ".", "kv_store", ".", "get", "(", "self", ".", "_get_storage_key", "(", "identifi...
Get user object for given identifier. Args: identified_with (object): authentication middleware used to identify the user. identifier: middleware specifix user identifier (string or tuple in case of all built in authentication middleware classes). Returns: dict: user object stored in Redis if it exists, otherwise ``None``
[ "Get", "user", "object", "for", "given", "identifier", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L209-L231
25,627
swistakm/graceful
src/graceful/authentication.py
KeyValueUserStorage.register
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 middleware used to identify the user. identifier (str): user identifier. user (str): user object to be stored in the backend. """ self.kv_store.set( self._get_storage_key(identified_with, identifier), self.serialization.dumps(user).encode(), )
python
def register(self, identified_with, identifier, user): self.kv_store.set( self._get_storage_key(identified_with, identifier), self.serialization.dumps(user).encode(), )
[ "def", "register", "(", "self", ",", "identified_with", ",", "identifier", ",", "user", ")", ":", "self", ".", "kv_store", ".", "set", "(", "self", ".", "_get_storage_key", "(", "identified_with", ",", "identifier", ")", ",", "self", ".", "serialization", ...
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 middleware used to identify the user. identifier (str): user identifier. user (str): user object to be stored in the backend.
[ "Register", "new", "key", "for", "given", "client", "identifier", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L233-L248
25,628
swistakm/graceful
src/graceful/authentication.py
BaseAuthenticationMiddleware.process_resource
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 object matched by falcon router uri_kwargs (dict): additional keyword argument from uri template. For ``falcon<1.0.0`` this is always ``None`` """ if 'user' in req.context: return identifier = self.identify(req, resp, resource, uri_kwargs) user = self.try_storage(identifier, req, resp, resource, uri_kwargs) if user is not None: req.context['user'] = user # if did not succeed then we need to add this to list of available # challenges. elif self.challenge is not None: req.context.setdefault( 'challenges', list() ).append(self.challenge)
python
def process_resource(self, req, resp, resource, uri_kwargs=None): if 'user' in req.context: return identifier = self.identify(req, resp, resource, uri_kwargs) user = self.try_storage(identifier, req, resp, resource, uri_kwargs) if user is not None: req.context['user'] = user # if did not succeed then we need to add this to list of available # challenges. elif self.challenge is not None: req.context.setdefault( 'challenges', list() ).append(self.challenge)
[ "def", "process_resource", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", "=", "None", ")", ":", "if", "'user'", "in", "req", ".", "context", ":", "return", "identifier", "=", "self", ".", "identify", "(", "req", ",", "resp",...
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 object matched by falcon router uri_kwargs (dict): additional keyword argument from uri template. For ``falcon<1.0.0`` this is always ``None``
[ "Process", "resource", "after", "routing", "to", "it", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L288-L314
25,629
swistakm/graceful
src/graceful/authentication.py
BaseAuthenticationMiddleware.try_storage
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 user_storage is defined, always use it in order to # authenticate user. elif self.user_storage is not None: user = self.user_storage.get_user( self, identifier, req, resp, resource, uri_kwargs ) # note: some authentication middleware classes may not require # to be initialized with their own user_storage. In such # case this will always authenticate with "syntetic user" # if there is a valid indentity. elif self.user_storage is None and not self.only_with_storage: user = { 'identified_with': self, 'identifier': identifier } else: # pragma: nocover # note: this should not happen if the base class is properly # initialized. Still, user can skip super().__init__() call. user = None return user
python
def try_storage(self, identifier, req, resp, resource, uri_kwargs): if identifier is None: user = None # note: if user_storage is defined, always use it in order to # authenticate user. elif self.user_storage is not None: user = self.user_storage.get_user( self, identifier, req, resp, resource, uri_kwargs ) # note: some authentication middleware classes may not require # to be initialized with their own user_storage. In such # case this will always authenticate with "syntetic user" # if there is a valid indentity. elif self.user_storage is None and not self.only_with_storage: user = { 'identified_with': self, 'identifier': identifier } else: # pragma: nocover # note: this should not happen if the base class is properly # initialized. Still, user can skip super().__init__() call. user = None return user
[ "def", "try_storage", "(", "self", ",", "identifier", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "if", "identifier", "is", "None", ":", "user", "=", "None", "# note: if user_storage is defined, always use it in order to", "# authent...
Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object.
[ "Try", "to", "find", "user", "in", "configured", "user", "storage", "object", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L331-L365
25,630
swistakm/graceful
src/graceful/authentication.py
Basic.identify
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 if len(auth) != 2: raise HTTPBadRequest( "Invalid Authorization header", "The Authorization header for Basic auth should be in form:\n" "Authorization: Basic <base64-user-pass>" ) user_pass = auth[1] try: decoded = base64.b64decode(user_pass).decode() except (TypeError, UnicodeDecodeError, binascii.Error): raise HTTPBadRequest( "Invalid Authorization header", "Credentials for Basic auth not correctly base64 encoded." ) username, _, password = decoded.partition(":") return username, password
python
def identify(self, req, resp, resource, uri_kwargs): header = req.get_header("Authorization", False) auth = header.split(" ") if header else None if auth is None or auth[0].lower() != 'basic': return None if len(auth) != 2: raise HTTPBadRequest( "Invalid Authorization header", "The Authorization header for Basic auth should be in form:\n" "Authorization: Basic <base64-user-pass>" ) user_pass = auth[1] try: decoded = base64.b64decode(user_pass).decode() except (TypeError, UnicodeDecodeError, binascii.Error): raise HTTPBadRequest( "Invalid Authorization header", "Credentials for Basic auth not correctly base64 encoded." ) username, _, password = decoded.partition(":") return username, password
[ "def", "identify", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "header", "=", "req", ".", "get_header", "(", "\"Authorization\"", ",", "False", ")", "auth", "=", "header", ".", "split", "(", "\" \"", ")", "if", ...
Identify user using Authenticate header with Basic auth.
[ "Identify", "user", "using", "Authenticate", "header", "with", "Basic", "auth", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L426-L453
25,631
swistakm/graceful
src/graceful/authentication.py
XAPIKey.identify
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
def identify(self, req, resp, resource, uri_kwargs): try: return req.get_header('X-Api-Key', True) except (KeyError, HTTPMissingHeader): pass
[ "def", "identify", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "try", ":", "return", "req", ".", "get_header", "(", "'X-Api-Key'", ",", "True", ")", "except", "(", "KeyError", ",", "HTTPMissingHeader", ")", ":", ...
Initialize X-Api-Key authentication middleware.
[ "Initialize", "X", "-", "Api", "-", "Key", "authentication", "middleware", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L490-L495
25,632
swistakm/graceful
src/graceful/authentication.py
Token.identify
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 if len(auth) != 2: raise HTTPBadRequest( "Invalid Authorization header", "The Authorization header for Token auth should be in form:\n" "Authorization: Token <token_value>" ) return auth[1]
python
def identify(self, req, resp, resource, uri_kwargs): header = req.get_header('Authorization', False) auth = header.split(' ') if header else None if auth is None or auth[0].lower() != 'token': return None if len(auth) != 2: raise HTTPBadRequest( "Invalid Authorization header", "The Authorization header for Token auth should be in form:\n" "Authorization: Token <token_value>" ) return auth[1]
[ "def", "identify", "(", "self", ",", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "header", "=", "req", ".", "get_header", "(", "'Authorization'", ",", "False", ")", "auth", "=", "header", ".", "split", "(", "' '", ")", "if", "he...
Identify user using Authenticate header with Token auth.
[ "Identify", "user", "using", "Authenticate", "header", "with", "Token", "auth", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L524-L539
25,633
swistakm/graceful
src/graceful/authentication.py
XForwardedFor._get_client_address
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: req (falcon.Request): falcon.Request object. Returns: str: client address. """ try: forwarded_for = req.get_header('X-Forwarded-For', True) return forwarded_for.split(',')[0].strip() except (KeyError, HTTPMissingHeader): return ( req.env.get('REMOTE_ADDR') if self.remote_address_fallback else None )
python
def _get_client_address(self, req): try: forwarded_for = req.get_header('X-Forwarded-For', True) return forwarded_for.split(',')[0].strip() except (KeyError, HTTPMissingHeader): return ( req.env.get('REMOTE_ADDR') if self.remote_address_fallback else None )
[ "def", "_get_client_address", "(", "self", ",", "req", ")", ":", "try", ":", "forwarded_for", "=", "req", ".", "get_header", "(", "'X-Forwarded-For'", ",", "True", ")", "return", "forwarded_for", ".", "split", "(", "','", ")", "[", "0", "]", ".", "strip"...
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: req (falcon.Request): falcon.Request object. Returns: str: client address.
[ "Get", "address", "from", "X", "-", "Forwarded", "-", "For", "header", "or", "use", "remote", "address", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authentication.py#L595-L615
25,634
swistakm/graceful
src/graceful/errors.py
DeserializationError._get_description
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 self.missing else "", ( "forbidden: {}".format(self.forbidden) if self.forbidden else "" ), "invalid: {}:".format(self.invalid) if self.invalid else "", ( "failed to parse: {}".format(self.failed) if self.failed else "" ) ] if part ])
python
def _get_description(self): return ", ".join([ part for part in [ "missing: {}".format(self.missing) if self.missing else "", ( "forbidden: {}".format(self.forbidden) if self.forbidden else "" ), "invalid: {}:".format(self.invalid) if self.invalid else "", ( "failed to parse: {}".format(self.failed) if self.failed else "" ) ] if part ])
[ "def", "_get_description", "(", "self", ")", ":", "return", "\", \"", ".", "join", "(", "[", "part", "for", "part", "in", "[", "\"missing: {}\"", ".", "format", "(", "self", ".", "missing", ")", "if", "self", ".", "missing", "else", "\"\"", ",", "(", ...
Return human readable description error description. This description should explain everything that went wrong during deserialization.
[ "Return", "human", "readable", "description", "error", "description", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/errors.py#L23-L43
25,635
tomplus/kubernetes_asyncio
kubernetes_asyncio/config/kube_config.py
load_kube_config
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: Name of the kube-config file. :param context: set the active context. If is set to None, current_context from config file will be used. :param client_configuration: The kubernetes.client.Configuration to set configs to. :param persist_config: If True, config file will be updated when changed (e.g GCP token refresh). """ if config_file is None: config_file = KUBE_CONFIG_DEFAULT_LOCATION loader = _get_kube_config_loader_for_yaml_file( config_file, active_context=context, persist_config=persist_config) if client_configuration is None: config = type.__call__(Configuration) await loader.load_and_set(config) Configuration.set_default(config) else: await loader.load_and_set(client_configuration) return loader
python
async def load_kube_config(config_file=None, context=None, client_configuration=None, persist_config=True): if config_file is None: config_file = KUBE_CONFIG_DEFAULT_LOCATION loader = _get_kube_config_loader_for_yaml_file( config_file, active_context=context, persist_config=persist_config) if client_configuration is None: config = type.__call__(Configuration) await loader.load_and_set(config) Configuration.set_default(config) else: await loader.load_and_set(client_configuration) return loader
[ "async", "def", "load_kube_config", "(", "config_file", "=", "None", ",", "context", "=", "None", ",", "client_configuration", "=", "None", ",", "persist_config", "=", "True", ")", ":", "if", "config_file", "is", "None", ":", "config_file", "=", "KUBE_CONFIG_D...
Loads authentication and cluster information from kube-config file and stores them in kubernetes.client.configuration. :param config_file: Name of the kube-config file. :param context: set the active context. If is set to None, current_context from config file will be used. :param client_configuration: The kubernetes.client.Configuration to set configs to. :param persist_config: If True, config file will be updated when changed (e.g GCP token refresh).
[ "Loads", "authentication", "and", "cluster", "information", "from", "kube", "-", "config", "file", "and", "stores", "them", "in", "kubernetes", ".", "client", ".", "configuration", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L533-L561
25,636
tomplus/kubernetes_asyncio
kubernetes_asyncio/config/kube_config.py
refresh_token
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. :param interval: how often check if token is up-to-date """ if loader.provider != 'gcp': return if client_configuration is None: client_configuration = Configuration() while 1: await asyncio.sleep(interval) await loader.load_gcp_token() client_configuration.api_key['authorization'] = loader.token
python
async def refresh_token(loader, client_configuration=None, interval=60): if loader.provider != 'gcp': return if client_configuration is None: client_configuration = Configuration() while 1: await asyncio.sleep(interval) await loader.load_gcp_token() client_configuration.api_key['authorization'] = loader.token
[ "async", "def", "refresh_token", "(", "loader", ",", "client_configuration", "=", "None", ",", "interval", "=", "60", ")", ":", "if", "loader", ".", "provider", "!=", "'gcp'", ":", "return", "if", "client_configuration", "is", "None", ":", "client_configuratio...
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. :param interval: how often check if token is up-to-date
[ "Refresh", "token", "if", "necessary", "updates", "the", "token", "in", "client", "configurarion" ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L564-L582
25,637
tomplus/kubernetes_asyncio
kubernetes_asyncio/config/kube_config.py
new_client_from_config
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__(Configuration) await load_kube_config(config_file=config_file, context=context, client_configuration=client_config, persist_config=persist_config) return ApiClient(configuration=client_config)
python
async def new_client_from_config(config_file=None, context=None, persist_config=True): client_config = type.__call__(Configuration) await load_kube_config(config_file=config_file, context=context, client_configuration=client_config, persist_config=persist_config) return ApiClient(configuration=client_config)
[ "async", "def", "new_client_from_config", "(", "config_file", "=", "None", ",", "context", "=", "None", ",", "persist_config", "=", "True", ")", ":", "client_config", "=", "type", ".", "__call__", "(", "Configuration", ")", "await", "load_kube_config", "(", "c...
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.
[ "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", "cluste...
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L585-L595
25,638
tomplus/kubernetes_asyncio
kubernetes_asyncio/config/kube_config.py
KubeConfigLoader._load_authentication
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: 1. GCP auth-provider 2. token field (point to a token file) 3. oidc auth-provider 4. exec provided plugin 5. username/password """ if not self._user: logging.debug('No user section in current context.') return if self.provider == 'gcp': await self.load_gcp_token() return if self.provider == PROVIDER_TYPE_OIDC: await self._load_oid_token() return if 'exec' in self._user: logging.debug('Try to use exec provider') res_exec_plugin = await self._load_from_exec_plugin() if res_exec_plugin: return logging.debug('Try to load user token') if self._load_user_token(): return logging.debug('Try to use username and password') self._load_user_pass_token()
python
async def _load_authentication(self): if not self._user: logging.debug('No user section in current context.') return if self.provider == 'gcp': await self.load_gcp_token() return if self.provider == PROVIDER_TYPE_OIDC: await self._load_oid_token() return if 'exec' in self._user: logging.debug('Try to use exec provider') res_exec_plugin = await self._load_from_exec_plugin() if res_exec_plugin: return logging.debug('Try to load user token') if self._load_user_token(): return logging.debug('Try to use username and password') self._load_user_pass_token()
[ "async", "def", "_load_authentication", "(", "self", ")", ":", "if", "not", "self", ".", "_user", ":", "logging", ".", "debug", "(", "'No user section in current context.'", ")", "return", "if", "self", ".", "provider", "==", "'gcp'", ":", "await", "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: 1. GCP auth-provider 2. token field (point to a token file) 3. oidc auth-provider 4. exec provided plugin 5. username/password
[ "Read", "authentication", "from", "kube", "-", "config", "user", "section", "if", "exists", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/config/kube_config.py#L178-L215
25,639
swistakm/graceful
src/graceful/validators.py
min_validator
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 validator(value): if value < min_value: raise ValidationError("{} is not >= {}".format(value, min_value)) return validator
python
def min_validator(min_value): def validator(value): if value < min_value: raise ValidationError("{} is not >= {}".format(value, min_value)) return validator
[ "def", "min_validator", "(", "min_value", ")", ":", "def", "validator", "(", "value", ")", ":", "if", "value", "<", "min_value", ":", "raise", "ValidationError", "(", "\"{} is not >= {}\"", ".", "format", "(", "value", ",", "min_value", ")", ")", "return", ...
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
[ "Return", "validator", "function", "that", "ensures", "lower", "bound", "of", "a", "number", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L14-L28
25,640
swistakm/graceful
src/graceful/validators.py
max_validator
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 validator(value): if value > max_value: raise ValidationError("{} is not <= {}".format(value, max_value)) return validator
python
def max_validator(max_value): def validator(value): if value > max_value: raise ValidationError("{} is not <= {}".format(value, max_value)) return validator
[ "def", "max_validator", "(", "max_value", ")", ":", "def", "validator", "(", "value", ")", ":", "if", "value", ">", "max_value", ":", "raise", "ValidationError", "(", "\"{} is not <= {}\"", ".", "format", "(", "value", ",", "max_value", ")", ")", "return", ...
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
[ "Return", "validator", "function", "that", "ensures", "upper", "bound", "of", "a", "number", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L31-L45
25,641
swistakm/graceful
src/graceful/validators.py
choices_validator
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 representation raise ValidationError( "{} is not in {}".format(value, list(choices)) ) return validator
python
def choices_validator(choices): def validator(value): if value not in choices: # note: make it a list for consistent representation raise ValidationError( "{} is not in {}".format(value, list(choices)) ) return validator
[ "def", "choices_validator", "(", "choices", ")", ":", "def", "validator", "(", "value", ")", ":", "if", "value", "not", "in", "choices", ":", "# note: make it a list for consistent representation", "raise", "ValidationError", "(", "\"{} is not in {}\"", ".", "format",...
Return validator function that will check if ``value in choices``. Args: max_value (list, set, tuple): allowed choices for new validator
[ "Return", "validator", "function", "that", "will", "check", "if", "value", "in", "choices", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L48-L62
25,642
swistakm/graceful
src/graceful/validators.py
match_validator
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 regular regular expression or custom matching object/class. """ if isinstance(expression, str): compiled = re.compile(expression) elif hasattr(expression, 'match'): # check it early so we could say something is wrong early compiled = expression else: raise TypeError( 'Provided match is nor a string nor has a match method ' '(like re expressions)' ) def validator(value): if not compiled.match(value): # note: make it a list for consistent representation raise ValidationError( "{} does not match pattern: {}".format( value, compiled.pattern if hasattr(compiled, 'pattern') else compiled ) ) return validator
python
def match_validator(expression): if isinstance(expression, str): compiled = re.compile(expression) elif hasattr(expression, 'match'): # check it early so we could say something is wrong early compiled = expression else: raise TypeError( 'Provided match is nor a string nor has a match method ' '(like re expressions)' ) def validator(value): if not compiled.match(value): # note: make it a list for consistent representation raise ValidationError( "{} does not match pattern: {}".format( value, compiled.pattern if hasattr(compiled, 'pattern') else compiled ) ) return validator
[ "def", "match_validator", "(", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "str", ")", ":", "compiled", "=", "re", ".", "compile", "(", "expression", ")", "elif", "hasattr", "(", "expression", ",", "'match'", ")", ":", "# check it e...
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 regular regular expression or custom matching object/class.
[ "Return", "validator", "function", "that", "will", "check", "if", "matches", "given", "expression", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L65-L98
25,643
swistakm/graceful
src/graceful/parameters.py
BaseParam.validated_value
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 Note: Concept of validation for params is understood here as a process of checking if data of valid type (successfully parsed/processed by ``.value()`` handler) does meet some other constraints (lenght, bounds, uniqueness, etc.). It will internally call its ``value()`` handler. """ value = self.value(raw_value) try: for validator in self.validators: validator(value) except: raise else: return value
python
def validated_value(self, raw_value): value = self.value(raw_value) try: for validator in self.validators: validator(value) except: raise else: return value
[ "def", "validated_value", "(", "self", ",", "raw_value", ")", ":", "value", "=", "self", ".", "value", "(", "raw_value", ")", "try", ":", "for", "validator", "in", "self", ".", "validators", ":", "validator", "(", "value", ")", "except", ":", "raise", ...
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 Note: Concept of validation for params is understood here as a process of checking if data of valid type (successfully parsed/processed by ``.value()`` handler) does meet some other constraints (lenght, bounds, uniqueness, etc.). It will internally call its ``value()`` handler.
[ "Return", "parsed", "parameter", "value", "and", "run", "validation", "handlers", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L122-L149
25,644
swistakm/graceful
src/graceful/parameters.py
BaseParam.describe
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 Suggested way for overriding description fields or extending it with additional items is calling super class method with new/overriden fields passed as keyword arguments like following: .. code-block:: python class DummyParam(BaseParam): def description(self, **kwargs): super().describe(is_dummy=True, **kwargs) """ description = { 'label': self.label, # note: details are expected to be large so it should # be reformatted 'details': inspect.cleandoc(self.details), 'required': self.required, 'many': self.many, 'spec': self.spec, 'default': self.default, 'type': self.type or 'unspecified' } description.update(kwargs) return description
python
def describe(self, **kwargs): description = { 'label': self.label, # note: details are expected to be large so it should # be reformatted 'details': inspect.cleandoc(self.details), 'required': self.required, 'many': self.many, 'spec': self.spec, 'default': self.default, 'type': self.type or 'unspecified' } description.update(kwargs) return description
[ "def", "describe", "(", "self", ",", "*", "*", "kwargs", ")", ":", "description", "=", "{", "'label'", ":", "self", ".", "label", ",", "# note: details are expected to be large so it should", "# be reformatted", "'details'", ":", "inspect", ".", "cleandoc", ...
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 Suggested way for overriding description fields or extending it with additional items is calling super class method with new/overriden fields passed as keyword arguments like following: .. code-block:: python class DummyParam(BaseParam): def description(self, **kwargs): super().describe(is_dummy=True, **kwargs)
[ "Describe", "this", "parameter", "instance", "for", "purpose", "of", "self", "-", "documentation", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L164-L199
25,645
swistakm/graceful
src/graceful/parameters.py
Base64EncodedParam.value
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
def value(self, raw_value): try: return base64.b64decode(bytes(raw_value, 'utf-8')).decode('utf-8') except binascii.Error as err: raise ValueError(str(err))
[ "def", "value", "(", "self", ",", "raw_value", ")", ":", "try", ":", "return", "base64", ".", "b64decode", "(", "bytes", "(", "raw_value", ",", "'utf-8'", ")", ")", ".", "decode", "(", "'utf-8'", ")", "except", "binascii", ".", "Error", "as", "err", ...
Decode param with Base64.
[ "Decode", "param", "with", "Base64", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L237-L242
25,646
swistakm/graceful
src/graceful/parameters.py
DecimalParam.value
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
def value(self, raw_value): try: return decimal.Decimal(raw_value) except decimal.InvalidOperation: raise ValueError( "Could not parse '{}' value as decimal".format(raw_value) )
[ "def", "value", "(", "self", ",", "raw_value", ")", ":", "try", ":", "return", "decimal", ".", "Decimal", "(", "raw_value", ")", "except", "decimal", ".", "InvalidOperation", ":", "raise", "ValueError", "(", "\"Could not parse '{}' value as decimal\"", ".", "for...
Decode param as decimal value.
[ "Decode", "param", "as", "decimal", "value", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L270-L277
25,647
swistakm/graceful
src/graceful/parameters.py
BoolParam.value
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_value) )
python
def value(self, raw_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_value) )
[ "def", "value", "(", "self", ",", "raw_value", ")", ":", "if", "raw_value", "in", "self", ".", "_FALSE_VALUES", ":", "return", "False", "elif", "raw_value", "in", "self", ".", "_TRUE_VALUES", ":", "return", "True", "else", ":", "raise", "ValueError", "(", ...
Decode param as bool value.
[ "Decode", "param", "as", "bool", "value", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/parameters.py#L300-L309
25,648
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_spec.py
V1beta1CertificateSigningRequestSpec.request
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: raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501 if request is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request): # noqa: E501 raise ValueError(r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._request = request
python
def request(self, request): if request is None: raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501 if request is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request): # noqa: E501 raise ValueError(r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._request = request
[ "def", "request", "(", "self", ",", "request", ")", ":", "if", "request", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `request`, must not be `None`\"", ")", "# noqa: E501", "if", "request", "is", "not", "None", "and", "not", "re", ".", ...
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
[ "Sets", "the", "request", "of", "this", "V1beta1CertificateSigningRequestSpec", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_spec.py#L132-L145
25,649
CLARIAH/grlc
src/projection.py
project
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) program = makeProgramFromString(projectionScript) if PY3: loc = { 'dataIn': dataIn, 'dataOut': dataOut } exec(program, {}, loc) dataOut = loc['dataOut'] else: exec(program) except Exception as e: glogger.error("Error while executing SPARQL projection") glogger.error(projectionScript) glogger.error("Encountered exception: ") glogger.error(e) dataOut = { 'status': 'error', 'message': e.message } return dataOut
python
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) program = makeProgramFromString(projectionScript) if PY3: loc = { 'dataIn': dataIn, 'dataOut': dataOut } exec(program, {}, loc) dataOut = loc['dataOut'] else: exec(program) except Exception as e: glogger.error("Error while executing SPARQL projection") glogger.error(projectionScript) glogger.error("Encountered exception: ") glogger.error(e) dataOut = { 'status': 'error', 'message': e.message } return dataOut
[ "def", "project", "(", "dataIn", ",", "projectionScript", ")", ":", "# We don't really need to initialize it, but we do it to avoid linter errors", "dataOut", "=", "{", "}", "try", ":", "projectionScript", "=", "str", "(", "projectionScript", ")", "program", "=", "makeP...
Programs may make use of data in the `dataIn` variable and should produce data on the `dataOut` variable.
[ "Programs", "may", "make", "use", "of", "data", "in", "the", "dataIn", "variable", "and", "should", "produce", "data", "on", "the", "dataOut", "variable", "." ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/projection.py#L7-L33
25,650
CLARIAH/grlc
src/prov.py
grlcPROV.init_prov_graph
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(self.user, self.repo), 'PROV-O']).decode("utf-8") repo_prov = repo_prov[repo_prov.find('@'):] # glogger.debug('Git2PROV output: {}'.format(repo_prov)) glogger.debug('Ingesting Git2PROV output into RDF graph') with open('temp.prov.ttl', 'w') as temp_prov: temp_prov.write(repo_prov) self.prov_g.parse('temp.prov.ttl', format='turtle') except Exception as e: glogger.error(e) glogger.error("Couldn't parse Git2PROV graph, continuing without repo PROV") pass self.prov_g.add((self.agent, RDF.type, self.prov.Agent)) self.prov_g.add((self.entity_d, RDF.type, self.prov.Entity)) self.prov_g.add((self.activity, RDF.type, self.prov.Activity)) # entity_d self.prov_g.add((self.entity_d, self.prov.wasGeneratedBy, self.activity)) self.prov_g.add((self.entity_d, self.prov.wasAttributedTo, self.agent)) # later: entity_d genereated at time (when we know the end time) # activity self.prov_g.add((self.activity, self.prov.wasAssociatedWith, self.agent)) self.prov_g.add((self.activity, self.prov.startedAtTime, Literal(datetime.now())))
python
def init_prov_graph(self): try: # Use git2prov to get prov on the repo repo_prov = check_output( ['node_modules/git2prov/bin/git2prov', 'https://github.com/{}/{}/'.format(self.user, self.repo), 'PROV-O']).decode("utf-8") repo_prov = repo_prov[repo_prov.find('@'):] # glogger.debug('Git2PROV output: {}'.format(repo_prov)) glogger.debug('Ingesting Git2PROV output into RDF graph') with open('temp.prov.ttl', 'w') as temp_prov: temp_prov.write(repo_prov) self.prov_g.parse('temp.prov.ttl', format='turtle') except Exception as e: glogger.error(e) glogger.error("Couldn't parse Git2PROV graph, continuing without repo PROV") pass self.prov_g.add((self.agent, RDF.type, self.prov.Agent)) self.prov_g.add((self.entity_d, RDF.type, self.prov.Entity)) self.prov_g.add((self.activity, RDF.type, self.prov.Activity)) # entity_d self.prov_g.add((self.entity_d, self.prov.wasGeneratedBy, self.activity)) self.prov_g.add((self.entity_d, self.prov.wasAttributedTo, self.agent)) # later: entity_d genereated at time (when we know the end time) # activity self.prov_g.add((self.activity, self.prov.wasAssociatedWith, self.agent)) self.prov_g.add((self.activity, self.prov.startedAtTime, Literal(datetime.now())))
[ "def", "init_prov_graph", "(", "self", ")", ":", "try", ":", "# Use git2prov to get prov on the repo", "repo_prov", "=", "check_output", "(", "[", "'node_modules/git2prov/bin/git2prov'", ",", "'https://github.com/{}/{}/'", ".", "format", "(", "self", ".", "user", ",", ...
Initialize PROV graph with all we know at the start of the recording
[ "Initialize", "PROV", "graph", "with", "all", "we", "know", "at", "the", "start", "of", "the", "recording" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L35-L68
25,651
CLARIAH/grlc
src/prov.py
grlcPROV.add_used_entity
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
def add_used_entity(self, entity_uri): 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))
[ "def", "add_used_entity", "(", "self", ",", "entity_uri", ")", ":", "entity_o", "=", "URIRef", "(", "entity_uri", ")", "self", ".", "prov_g", ".", "add", "(", "(", "entity_o", ",", "RDF", ".", "type", ",", "self", ".", "prov", ".", "Entity", ")", ")"...
Add the provided URI as a used entity by the logged activity
[ "Add", "the", "provided", "URI", "as", "a", "used", "entity", "by", "the", "logged", "activity" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L72-L78
25,652
CLARIAH/grlc
src/prov.py
grlcPROV.end_prov_graph
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
def end_prov_graph(self): 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))
[ "def", "end_prov_graph", "(", "self", ")", ":", "endTime", "=", "Literal", "(", "datetime", ".", "now", "(", ")", ")", "self", ".", "prov_g", ".", "add", "(", "(", "self", ".", "entity_d", ",", "self", ".", "prov", ".", "generatedAtTime", ",", "endTi...
Finalize prov recording with end time
[ "Finalize", "prov", "recording", "with", "end", "time" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L80-L86
25,653
CLARIAH/grlc
src/prov.py
grlcPROV.log_prov_graph
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
def log_prov_graph(self): glogger.debug("Spec generation provenance graph:") glogger.debug(self.prov_g.serialize(format='turtle'))
[ "def", "log_prov_graph", "(", "self", ")", ":", "glogger", ".", "debug", "(", "\"Spec generation provenance graph:\"", ")", "glogger", ".", "debug", "(", "self", ".", "prov_g", ".", "serialize", "(", "format", "=", "'turtle'", ")", ")" ]
Log provenance graph so far
[ "Log", "provenance", "graph", "so", "far" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L88-L93
25,654
CLARIAH/grlc
src/prov.py
grlcPROV.serialize
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
def serialize(self, format): if PY3: return self.prov_g.serialize(format=format).decode('utf-8') else: return self.prov_g.serialize(format=format)
[ "def", "serialize", "(", "self", ",", "format", ")", ":", "if", "PY3", ":", "return", "self", ".", "prov_g", ".", "serialize", "(", "format", "=", "format", ")", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "self", ".", "prov_g", ".", ...
Serialize provenance graph in the specified format
[ "Serialize", "provenance", "graph", "in", "the", "specified", "format" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/prov.py#L95-L102
25,655
CLARIAH/grlc
src/gquery.py
get_defaults
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 defaultsDict[v] return None
python
def get_defaults(rq, v, metadata): glogger.debug("Metadata with defaults: {}".format(metadata)) if 'defaults' not in metadata: return None defaultsDict = _getDictWithKey(v, metadata['defaults']) if defaultsDict: return defaultsDict[v] return None
[ "def", "get_defaults", "(", "rq", ",", "v", ",", "metadata", ")", ":", "glogger", ".", "debug", "(", "\"Metadata with defaults: {}\"", ".", "format", "(", "metadata", ")", ")", "if", "'defaults'", "not", "in", "metadata", ":", "return", "None", "defaultsDict...
Returns the default value for a parameter or None
[ "Returns", "the", "default", "value", "for", "a", "parameter", "or", "None" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/gquery.py#L183-L193
25,656
CLARIAH/grlc
src/fileLoaders.py
LocalLoader.fetchFiles
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)) relative = f.replace(self.baseDir, '') filesDef.append({ 'download_url': relative, 'name': relative }) return filesDef
python
def fetchFiles(self): print("Fetching files from {}".format(self.baseDir)) files = glob(path.join(self.baseDir, '*')) filesDef = [] for f in files: print("Found SPARQL file {}".format(f)) relative = f.replace(self.baseDir, '') filesDef.append({ 'download_url': relative, 'name': relative }) return filesDef
[ "def", "fetchFiles", "(", "self", ")", ":", "print", "(", "\"Fetching files from {}\"", ".", "format", "(", "self", ".", "baseDir", ")", ")", "files", "=", "glob", "(", "path", ".", "join", "(", "self", ".", "baseDir", ",", "'*'", ")", ")", "filesDef",...
Returns a list of file items contained on the local repo.
[ "Returns", "a", "list", "of", "file", "items", "contained", "on", "the", "local", "repo", "." ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/fileLoaders.py#L125-L137
25,657
CLARIAH/grlc
src/swagger.py
get_repo_info
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_url = loader.getLicenceURL() # Add the API URI as a used entity by the activity if prov_g: prov_g.add_used_entity(loader.getRepoURI()) prev_commit = None next_commit = None version = sha if sha else commit_list[0] if commit_list.index(version) < len(commit_list) - 1: prev_commit = commit_list[commit_list.index(version) + 1] if commit_list.index(version) > 0: next_commit = commit_list[commit_list.index(version) - 1] info = { 'version': version, 'title': repo_title, 'contact': { 'name': contact_name, 'url': contact_url }, 'license': { 'name': 'License', 'url': licence_url } } basePath = '/api/' + user_repo + '/' basePath += ('commit/' + sha + '/') if sha else '' return prev_commit, next_commit, info, basePath
python
def get_repo_info(loader, sha, prov_g): user_repo = loader.getFullName() repo_title = loader.getRepoTitle() contact_name = loader.getContactName() contact_url = loader.getContactUrl() commit_list = loader.getCommitList() licence_url = loader.getLicenceURL() # Add the API URI as a used entity by the activity if prov_g: prov_g.add_used_entity(loader.getRepoURI()) prev_commit = None next_commit = None version = sha if sha else commit_list[0] if commit_list.index(version) < len(commit_list) - 1: prev_commit = commit_list[commit_list.index(version) + 1] if commit_list.index(version) > 0: next_commit = commit_list[commit_list.index(version) - 1] info = { 'version': version, 'title': repo_title, 'contact': { 'name': contact_name, 'url': contact_url }, 'license': { 'name': 'License', 'url': licence_url } } basePath = '/api/' + user_repo + '/' basePath += ('commit/' + sha + '/') if sha else '' return prev_commit, next_commit, info, basePath
[ "def", "get_repo_info", "(", "loader", ",", "sha", ",", "prov_g", ")", ":", "user_repo", "=", "loader", ".", "getFullName", "(", ")", "repo_title", "=", "loader", ".", "getRepoTitle", "(", ")", "contact_name", "=", "loader", ".", "getContactName", "(", ")"...
Generate swagger information from the repo being used.
[ "Generate", "swagger", "information", "from", "the", "repo", "being", "used", "." ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/swagger.py#L24-L61
25,658
CLARIAH/grlc
src/pagination.py
buildPaginationHeader
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]+", "page={}".format(page - 1), url) first_url = re.sub("page=[0-9]+", "page=1", url) last_url = re.sub("page=[0-9]+", "page={}".format(lastPage), url) else: page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}".format(lastPage) if page == 1: headerLink = "<{}>; rel=next, <{}>; rel=last".format(next_url, last_url) elif page == lastPage: headerLink = "<{}>; rel=prev, <{}>; rel=first".format(prev_url, first_url) else: headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last".format(next_url, prev_url, first_url, last_url) return headerLink
python
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]+", "page={}".format(page - 1), url) first_url = re.sub("page=[0-9]+", "page=1", url) last_url = re.sub("page=[0-9]+", "page={}".format(lastPage), url) else: page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}".format(lastPage) if page == 1: headerLink = "<{}>; rel=next, <{}>; rel=last".format(next_url, last_url) elif page == lastPage: headerLink = "<{}>; rel=prev, <{}>; rel=first".format(prev_url, first_url) else: headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last".format(next_url, prev_url, first_url, last_url) return headerLink
[ "def", "buildPaginationHeader", "(", "resultCount", ",", "resultsPerPage", ",", "pageArg", ",", "url", ")", ":", "lastPage", "=", "resultCount", "/", "resultsPerPage", "if", "pageArg", ":", "page", "=", "int", "(", "pageArg", ")", "next_url", "=", "re", ".",...
Build link header for result pagination
[ "Build", "link", "header", "for", "result", "pagination" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/pagination.py#L12-L35
25,659
goerz/better-apidoc
better_apidoc.py
format_directive
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
def format_directive(module, package=None): # type: (unicode, unicode) -> unicode directive = '.. automodule:: %s\n' % makename(package, module) for option in OPTIONS: directive += ' :%s:\n' % option return directive
[ "def", "format_directive", "(", "module", ",", "package", "=", "None", ")", ":", "# type: (unicode, unicode) -> unicode", "directive", "=", "'.. automodule:: %s\\n'", "%", "makename", "(", "package", ",", "module", ")", "for", "option", "in", "OPTIONS", ":", "dire...
Create the automodule directive and add the options.
[ "Create", "the", "automodule", "directive", "and", "add", "the", "options", "." ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L116-L122
25,660
goerz/better-apidoc
better_apidoc.py
extract_summary
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 there's a blank line, then we can assume the first sentence / # paragraph has ended, so anything after shouldn't be part of the # summary for i, piece in enumerate(doc): if not piece.strip(): doc = doc[:i] break # Try to find the "first sentence", which may span multiple lines sentences = periods_re.split(" ".join(doc)) # type: ignore if len(sentences) == 1: summary = sentences[0].strip() else: summary = '' state_machine = RSTStateMachine(state_classes, 'Body') while sentences: summary += sentences.pop(0) + '.' node = new_document('') node.reporter = NullReporter('', 999, 4) node.settings.pep_references = None node.settings.rfc_references = None state_machine.run([summary], node) if not node.traverse(nodes.system_message): # considered as that splitting by period does not break inline # markups break return summary
python
def extract_summary(obj): # type: (List[unicode], Any) -> unicode 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 there's a blank line, then we can assume the first sentence / # paragraph has ended, so anything after shouldn't be part of the # summary for i, piece in enumerate(doc): if not piece.strip(): doc = doc[:i] break # Try to find the "first sentence", which may span multiple lines sentences = periods_re.split(" ".join(doc)) # type: ignore if len(sentences) == 1: summary = sentences[0].strip() else: summary = '' state_machine = RSTStateMachine(state_classes, 'Body') while sentences: summary += sentences.pop(0) + '.' node = new_document('') node.reporter = NullReporter('', 999, 4) node.settings.pep_references = None node.settings.rfc_references = None state_machine.run([summary], node) if not node.traverse(nodes.system_message): # considered as that splitting by period does not break inline # markups break return summary
[ "def", "extract_summary", "(", "obj", ")", ":", "# type: (List[unicode], Any) -> unicode", "try", ":", "doc", "=", "inspect", ".", "getdoc", "(", "obj", ")", ".", "split", "(", "\"\\n\"", ")", "except", "AttributeError", ":", "doc", "=", "''", "# Skip a blank ...
Extract summary from docstring.
[ "Extract", "summary", "from", "docstring", "." ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L272-L312
25,661
goerz/better-apidoc
better_apidoc.py
_get_member_ref_str
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) return ":%s:`%s <%s>`" % (role, name, ref)
python
def _get_member_ref_str(name, obj, role='obj', known_refs=None): if known_refs is not None: if name in known_refs: return known_refs[name] ref = _get_fullname(name, obj) return ":%s:`%s <%s>`" % (role, name, ref)
[ "def", "_get_member_ref_str", "(", "name", ",", "obj", ",", "role", "=", "'obj'", ",", "known_refs", "=", "None", ")", ":", "if", "known_refs", "is", "not", "None", ":", "if", "name", "in", "known_refs", ":", "return", "known_refs", "[", "name", "]", "...
generate a ReST-formmated reference link to the given `obj` of type `role`, using `name` as the link text
[ "generate", "a", "ReST", "-", "formmated", "reference", "link", "to", "the", "given", "obj", "of", "type", "role", "using", "name", "as", "the", "link", "text" ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L315-L322
25,662
goerz/better-apidoc
better_apidoc.py
_get_mod_ns
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': [], 'doc': None} p = 0 if includeprivate: p = 1 mod = importlib.import_module(fullname) ns['members'] = _get_members(mod)[p] ns['functions'] = _get_members(mod, typ='function')[p] ns['classes'] = _get_members(mod, typ='class')[p] ns['exceptions'] = _get_members(mod, typ='exception')[p] ns['data'] = _get_members(mod, typ='data')[p] ns['doc'] = mod.__doc__ return ns
python
def _get_mod_ns(name, fullname, includeprivate): ns = { # template variables 'name': name, 'fullname': fullname, 'members': [], 'functions': [], 'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [], 'doc': None} p = 0 if includeprivate: p = 1 mod = importlib.import_module(fullname) ns['members'] = _get_members(mod)[p] ns['functions'] = _get_members(mod, typ='function')[p] ns['classes'] = _get_members(mod, typ='class')[p] ns['exceptions'] = _get_members(mod, typ='exception')[p] ns['data'] = _get_members(mod, typ='data')[p] ns['doc'] = mod.__doc__ return ns
[ "def", "_get_mod_ns", "(", "name", ",", "fullname", ",", "includeprivate", ")", ":", "ns", "=", "{", "# template variables", "'name'", ":", "name", ",", "'fullname'", ":", "fullname", ",", "'members'", ":", "[", "]", ",", "'functions'", ":", "[", "]", ",...
Return the template context of module identified by `fullname` as a dict
[ "Return", "the", "template", "context", "of", "module", "identified", "by", "fullname", "as", "a", "dict" ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L345-L362
25,663
ValvePython/vdf
vdf/vdict.py
VDFDict.get_all_for
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
def get_all_for(self, 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])]
[ "def", "get_all_for", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "_string_type", ")", ":", "raise", "TypeError", "(", "\"Key needs to be a string.\"", ")", "return", "[", "self", "[", "(", "idx", ",", "key", ")", "]", ...
Returns all values of the given key
[ "Returns", "all", "values", "of", "the", "given", "key" ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L186-L190
25,664
ValvePython/vdf
vdf/vdict.py
VDFDict.remove_all_for
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(filter(lambda x: x[1] != key, self.__omap)) del self.__kcount[key]
python
def remove_all_for(self, 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(filter(lambda x: x[1] != key, self.__omap)) del self.__kcount[key]
[ "def", "remove_all_for", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "_string_type", ")", ":", "raise", "TypeError", "(", "\"Key need to be a string.\"", ")", "for", "idx", "in", "_range", "(", "self", ".", "__kcount", "[...
Removes all items with the given key
[ "Removes", "all", "items", "with", "the", "given", "key" ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L192-L202
25,665
ValvePython/vdf
vdf/vdict.py
VDFDict.has_duplicates
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_recurse(obj): for v in getattr(obj, _iter_values)(): if isinstance(v, VDFDict) and v.has_duplicates(): return True elif isinstance(v, dict): return dict_recurse(v) return False return dict_recurse(self)
python
def has_duplicates(self): for n in getattr(self.__kcount, _iter_values)(): if n != 1: return True def dict_recurse(obj): for v in getattr(obj, _iter_values)(): if isinstance(v, VDFDict) and v.has_duplicates(): return True elif isinstance(v, dict): return dict_recurse(v) return False return dict_recurse(self)
[ "def", "has_duplicates", "(", "self", ")", ":", "for", "n", "in", "getattr", "(", "self", ".", "__kcount", ",", "_iter_values", ")", "(", ")", ":", "if", "n", "!=", "1", ":", "return", "True", "def", "dict_recurse", "(", "obj", ")", ":", "for", "v"...
Returns ``True`` if the dict contains keys with duplicates. Recurses through any all keys with value that is ``VDFDict``.
[ "Returns", "True", "if", "the", "dict", "contains", "keys", "with", "duplicates", ".", "Recurses", "through", "any", "all", "keys", "with", "value", "that", "is", "VDFDict", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L204-L221
25,666
ValvePython/vdf
vdf/__init__.py
dumps
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 not isinstance(escaped, bool): raise TypeError("Expected escaped to be of type bool") return ''.join(_dump_gen(obj, pretty, escaped))
python
def dumps(obj, pretty=False, escaped=True): 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 not isinstance(escaped, bool): raise TypeError("Expected escaped to be of type bool") return ''.join(_dump_gen(obj, pretty, escaped))
[ "def", "dumps", "(", "obj", ",", "pretty", "=", "False", ",", "escaped", "=", "True", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Expected data to be an instance of``dict``\"", ")", "if", "not", "is...
Serialize ``obj`` to a VDF formatted ``str``.
[ "Serialize", "obj", "to", "a", "VDF", "formatted", "str", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L189-L200
25,667
ValvePython/vdf
vdf/__init__.py
binary_dumps
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
def binary_dumps(obj, alt_format=False): return b''.join(_binary_dump_gen(obj, alt_format=alt_format))
[ "def", "binary_dumps", "(", "obj", ",", "alt_format", "=", "False", ")", ":", "return", "b''", ".", "join", "(", "_binary_dump_gen", "(", "obj", ",", "alt_format", "=", "alt_format", ")", ")" ]
Serialize ``obj`` to a binary VDF formatted ``bytes``.
[ "Serialize", "obj", "to", "a", "binary", "VDF", "formatted", "bytes", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L367-L371
25,668
ValvePython/vdf
vdf/__init__.py
vbkv_loads
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 preserve key order. Or any object that acts like a ``dict``. ``merge_duplicate_keys`` when ``True`` will merge multiple KeyValue lists with the same key into one instead of overwriting. You can se this to ``False`` if you are using ``VDFDict`` and need to preserve the duplicates. """ if s[:4] != b'VBKV': raise ValueError("Invalid header") checksum, = struct.unpack('<i', s[4:8]) if checksum != crc32(s[8:]): raise ValueError("Invalid checksum") return binary_loads(s[8:], mapper, merge_duplicate_keys, alt_format=True)
python
def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True): if s[:4] != b'VBKV': raise ValueError("Invalid header") checksum, = struct.unpack('<i', s[4:8]) if checksum != crc32(s[8:]): raise ValueError("Invalid checksum") return binary_loads(s[8:], mapper, merge_duplicate_keys, alt_format=True)
[ "def", "vbkv_loads", "(", "s", ",", "mapper", "=", "dict", ",", "merge_duplicate_keys", "=", "True", ")", ":", "if", "s", "[", ":", "4", "]", "!=", "b'VBKV'", ":", "raise", "ValueError", "(", "\"Invalid header\"", ")", "checksum", ",", "=", "struct", "...
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 preserve key order. Or any object that acts like a ``dict``. ``merge_duplicate_keys`` when ``True`` will merge multiple KeyValue lists with the same key into one instead of overwriting. You can se this to ``False`` if you are using ``VDFDict`` and need to preserve the duplicates.
[ "Deserialize", "s", "(", "bytes", "containing", "a", "VBKV", "to", "a", "Python", "object", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L421-L441
25,669
ValvePython/vdf
vdf/__init__.py
vbkv_dumps
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
def vbkv_dumps(obj): data = b''.join(_binary_dump_gen(obj, alt_format=True)) checksum = crc32(data) return b'VBKV' + struct.pack('<i', checksum) + data
[ "def", "vbkv_dumps", "(", "obj", ")", ":", "data", "=", "b''", ".", "join", "(", "_binary_dump_gen", "(", "obj", ",", "alt_format", "=", "True", ")", ")", "checksum", "=", "crc32", "(", "data", ")", "return", "b'VBKV'", "+", "struct", ".", "pack", "(...
Serialize ``obj`` to a VBKV formatted ``bytes``.
[ "Serialize", "obj", "to", "a", "VBKV", "formatted", "bytes", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L443-L450
25,670
ldo/dbussy
dbussy.py
signature_validate
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
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
[ "def", "signature_validate", "(", "signature", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_signature_validate", "(", "signature", ".", "encode", "(", ")", ",", "erro...
is signature a valid sequence of zero or more complete types.
[ "is", "signature", "a", "valid", "sequence", "of", "zero", "or", "more", "complete", "types", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5539-L5545
25,671
ldo/dbussy
dbussy.py
unparse_signature
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
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))
[ "def", "unparse_signature", "(", "signature", ")", ":", "signature", "=", "parse_signature", "(", "signature", ")", "if", "not", "isinstance", "(", "signature", ",", "(", "tuple", ",", "list", ")", ")", ":", "signature", "=", "[", "signature", "]", "#end i...
converts a signature from parsed form to string form.
[ "converts", "a", "signature", "from", "parsed", "form", "to", "string", "form", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5616-L5623
25,672
ldo/dbussy
dbussy.py
signature_validate_single
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
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
[ "def", "signature_validate_single", "(", "signature", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_signature_validate_single", "(", "signature", ".", "encode", "(", ")", ...
is signature a single valid type.
[ "is", "signature", "a", "single", "valid", "type", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5626-L5632
25,673
ldo/dbussy
dbussy.py
split_path
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 DBusError(DBUS.ERROR_INVALID_ARGS, "invalid path %s" % repr(path)) #end if result = path.split("/")[1:] #end if return \ result
python
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 DBusError(DBUS.ERROR_INVALID_ARGS, "invalid path %s" % repr(path)) #end if result = path.split("/")[1:] #end if return \ result
[ "def", "split_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "(", "tuple", ",", "list", ")", ")", ":", "result", "=", "path", "# assume already split", "elif", "path", "==", "\"/\"", ":", "result", "=", "[", "]", "else", ":", "if...
convenience routine for splitting a path into a list of components.
[ "convenience", "routine", "for", "splitting", "a", "path", "into", "a", "list", "of", "components", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5672-L5685
25,674
ldo/dbussy
dbussy.py
validate_utf8
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
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
[ "def", "validate_utf8", "(", "alleged_utf8", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_validate_utf8", "(", "alleged_utf8", ",", "error", ".", "_dbobj", ")", "!=",...
alleged_utf8 must be null-terminated bytes.
[ "alleged_utf8", "must", "be", "null", "-", "terminated", "bytes", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5759-L5765
25,675
ldo/dbussy
dbussy.py
DBUS.int_subtype
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) - 1 else : lo = 0 hi = (1 << bits) - 1 #end if if i < lo or i > hi : raise ValueError \ ( "%d not in range of %s %d-bit value" % (i, ("unsigned", "signed")[signed], bits) ) #end if return \ i
python
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) - 1 else : lo = 0 hi = (1 << bits) - 1 #end if if i < lo or i > hi : raise ValueError \ ( "%d not in range of %s %d-bit value" % (i, ("unsigned", "signed")[signed], bits) ) #end if return \ i
[ "def", "int_subtype", "(", "i", ",", "bits", ",", "signed", ")", ":", "if", "not", "isinstance", "(", "i", ",", "int", ")", ":", "raise", "TypeError", "(", "\"value is not int: %s\"", "%", "repr", "(", "i", ")", ")", "#end if", "if", "signed", ":", "...
returns integer i after checking that it fits in the given number of bits.
[ "returns", "integer", "i", "after", "checking", "that", "it", "fits", "in", "the", "given", "number", "of", "bits", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L88-L107
25,676
ldo/dbussy
dbussy.py
Connection.server_id
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
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
[ "def", "server_id", "(", "self", ")", ":", "c_result", "=", "dbus", ".", "dbus_connection_get_server_id", "(", "self", ".", "_dbobj", ")", "result", "=", "ct", ".", "cast", "(", "c_result", ",", "ct", ".", "c_char_p", ")", ".", "value", ".", "decode", ...
asks the server at the other end for its unique id.
[ "asks", "the", "server", "at", "the", "other", "end", "for", "its", "unique", "id", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2146-L2152
25,677
ldo/dbussy
dbussy.py
Connection.send
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)) : raise CallFailed("dbus_connection_send") #end if return \ serial.value
python
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)) : raise CallFailed("dbus_connection_send") #end if return \ serial.value
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "serial", "=", "ct", ".", "c_uint", "(", ")", "if", "no...
puts a message in the outgoing queue.
[ "puts", "a", "message", "in", "the", "outgoing", "queue", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2187-L2197
25,678
ldo/dbussy
dbussy.py
Connection.send_with_reply_and_block
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, my_error = _get_error(error) reply = dbus.dbus_connection_send_with_reply_and_block(self._dbobj, message._dbobj, _get_timeout(timeout), error._dbobj) my_error.raise_if_set() if reply != None : result = Message(reply) else : result = None #end if return \ result
python
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, my_error = _get_error(error) reply = dbus.dbus_connection_send_with_reply_and_block(self._dbobj, message._dbobj, _get_timeout(timeout), error._dbobj) my_error.raise_if_set() if reply != None : result = Message(reply) else : result = None #end if return \ result
[ "def", "send_with_reply_and_block", "(", "self", ",", "message", ",", "timeout", "=", "DBUS", ".", "TIMEOUT_USE_DEFAULT", ",", "error", "=", "None", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "...
sends a message, blocks the thread until the reply is available, and returns it.
[ "sends", "a", "message", "blocks", "the", "thread", "until", "the", "reply", "is", "available", "and", "returns", "it", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2219-L2233
25,679
ldo/dbussy
dbussy.py
Connection.list_registered
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 CallFailed("dbus_connection_list_registered") #end if result = [] i = 0 while True : entry = child_entries[i] if entry == None : break result.append(entry.decode()) i += 1 #end while dbus.dbus_free_string_array(child_entries) return \ result
python
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 CallFailed("dbus_connection_list_registered") #end if result = [] i = 0 while True : entry = child_entries[i] if entry == None : break result.append(entry.decode()) i += 1 #end while dbus.dbus_free_string_array(child_entries) return \ result
[ "def", "list_registered", "(", "self", ",", "parent_path", ")", ":", "child_entries", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_char_p", ")", "(", ")", "if", "not", "dbus", ".", "dbus_connection_list_registered", "(", "self", ".", "_dbobj", ",", "paren...
lists all the object paths for which you have ObjectPathVTable handlers registered.
[ "lists", "all", "the", "object", "paths", "for", "which", "you", "have", "ObjectPathVTable", "handlers", "registered", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2661-L2678
25,680
ldo/dbussy
dbussy.py
Connection.bus_get
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() if result != None : result = celf(result) #end if return \ result
python
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() if result != None : result = celf(result) #end if return \ result
[ "def", "bus_get", "(", "celf", ",", "type", ",", "private", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "(", "dbus", ".", "dbus_bus_get", ",", "dbus", ".", "dbus_bus_get_private", ...
returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value.
[ "returns", "a", "Connection", "to", "one", "of", "the", "predefined", "D", "-", "Bus", "buses", ";", "type", "is", "a", "BUS_xxx", "value", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2924-L2933
25,681
ldo/dbussy
dbussy.py
Connection.become_monitor
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 = "BecomeMonitor" ) message.append_objects("asu", (list(format_rule(rule) for rule in rules)), 0) self.send(message)
python
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 = "BecomeMonitor" ) message.append_objects("asu", (list(format_rule(rule) for rule in rules)), 0) self.send(message)
[ "def", "become_monitor", "(", "self", ",", "rules", ")", ":", "message", "=", "Message", ".", "new_method_call", "(", "destination", "=", "DBUS", ".", "SERVICE_DBUS", ",", "path", "=", "DBUS", ".", "PATH_DBUS", ",", "iface", "=", "DBUS", ".", "INTERFACE_MO...
turns the connection into one that can only receive monitoring messages.
[ "turns", "the", "connection", "into", "one", "that", "can", "only", "receive", "monitoring", "messages", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3371-L3381
25,682
ldo/dbussy
dbussy.py
PreallocatedSend.send
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_connection_send_preallocated(self._parent._dbobj, self._dbobj, message._dbobj, ct.byref(serial)) self._sent = True return \ serial.value
python
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_connection_send_preallocated(self._parent._dbobj, self._dbobj, message._dbobj, ct.byref(serial)) self._sent = True return \ serial.value
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "assert", "not", "self", ".", "_sent", ",", "\"preallocated...
alternative to Connection.send_preallocated.
[ "alternative", "to", "Connection", ".", "send_preallocated", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3869-L3879
25,683
ldo/dbussy
dbussy.py
Message.new_error
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("dbus_message_new_error") #end if return \ type(self)(result)
python
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("dbus_message_new_error") #end if return \ type(self)(result)
[ "def", "new_error", "(", "self", ",", "name", ",", "message", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_error", "(", "self", ".", "_dbobj", ",", "name", ".", "encode", "(", ")", ",", "(", "lambda", ":", "None", ",", "lambda", ":", "mess...
creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_ERROR", "message", "that", "is", "a", "reply", "to", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3930-L3937
25,684
ldo/dbussy
dbussy.py
Message.new_method_call
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 : None, lambda : iface.encode())[iface != None](), method.encode(), ) if result == None : raise CallFailed("dbus_message_new_method_call") #end if return \ celf(result)
python
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 : None, lambda : iface.encode())[iface != None](), method.encode(), ) if result == None : raise CallFailed("dbus_message_new_method_call") #end if return \ celf(result)
[ "def", "new_method_call", "(", "celf", ",", "destination", ",", "path", ",", "iface", ",", "method", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_method_call", "(", "(", "lambda", ":", "None", ",", "lambda", ":", "destination", ".", "encode", "(...
creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_METHOD_CALL", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3943-L3956
25,685
ldo/dbussy
dbussy.py
Message.new_method_return
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 \ type(self)(result)
python
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 \ type(self)(result)
[ "def", "new_method_return", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_method_return", "(", "self", ".", "_dbobj", ")", "if", "result", "==", "None", ":", "raise", "CallFailed", "(", "\"dbus_message_new_method_return\"", ")", "#end if", ...
creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_METHOD_RETURN", "that", "is", "a", "reply", "to", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3959-L3966
25,686
ldo/dbussy
dbussy.py
Message.new_signal
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 \ celf(result)
python
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 \ celf(result)
[ "def", "new_signal", "(", "celf", ",", "path", ",", "iface", ",", "name", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_signal", "(", "path", ".", "encode", "(", ")", ",", "iface", ".", "encode", "(", ")", ",", "name", ".", "encode", "(", ...
creates a new DBUS.MESSAGE_TYPE_SIGNAL message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_SIGNAL", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3970-L3977
25,687
ldo/dbussy
dbussy.py
Message.copy
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
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)
[ "def", "copy", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_copy", "(", "self", ".", "_dbobj", ")", "if", "result", "==", "None", ":", "raise", "CallFailed", "(", "\"dbus_message_copy\"", ")", "#end if", "return", "type", "(", "self", ...
creates a copy of this Message.
[ "creates", "a", "copy", "of", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3980-L3987
25,688
ldo/dbussy
dbussy.py
Message.iter_init
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
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
[ "def", "iter_init", "(", "self", ")", ":", "iter", "=", "self", ".", "ExtractIter", "(", "None", ")", "if", "dbus", ".", "dbus_message_iter_init", "(", "self", ".", "_dbobj", ",", "iter", ".", "_dbobj", ")", "==", "0", ":", "iter", ".", "_nulliter", ...
creates an iterator for extracting the arguments of the Message.
[ "creates", "an", "iterator", "for", "extracting", "the", "arguments", "of", "the", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4278-L4285
25,689
ldo/dbussy
dbussy.py
Message.iter_init_append
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
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
[ "def", "iter_init_append", "(", "self", ")", ":", "iter", "=", "self", ".", "AppendIter", "(", "None", ")", "dbus", ".", "dbus_message_iter_init_append", "(", "self", ".", "_dbobj", ",", "iter", ".", "_dbobj", ")", "return", "iter" ]
creates a Message.AppendIter for appending arguments to the Message.
[ "creates", "a", "Message", ".", "AppendIter", "for", "appending", "arguments", "to", "the", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4329-L4334
25,690
ldo/dbussy
dbussy.py
Message.error_name
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
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
[ "def", "error_name", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_error_name", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
the error name for a DBUS.MESSAGE_TYPE_ERROR message.
[ "the", "error", "name", "for", "a", "DBUS", ".", "MESSAGE_TYPE_ERROR", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4519-L4526
25,691
ldo/dbussy
dbussy.py
Message.destination
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
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
[ "def", "destination", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_destination", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
the bus name that the message is to be sent to.
[ "the", "bus", "name", "that", "the", "message", "is", "to", "be", "sent", "to", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4537-L4544
25,692
ldo/dbussy
dbussy.py
Message.marshal
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_marshal") #end if result = bytearray(nr_bytes.value) ct.memmove \ ( ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)), buf, nr_bytes.value ) dbus.dbus_free(buf) return \ result
python
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_marshal") #end if result = bytearray(nr_bytes.value) ct.memmove \ ( ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)), buf, nr_bytes.value ) dbus.dbus_free(buf) return \ result
[ "def", "marshal", "(", "self", ")", ":", "buf", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_ubyte", ")", "(", ")", "nr_bytes", "=", "ct", ".", "c_int", "(", ")", "if", "not", "dbus", ".", "dbus_message_marshal", "(", "self", ".", "_dbobj", ",", ...
serializes this Message into the wire protocol format and returns a bytes object.
[ "serializes", "this", "Message", "into", "the", "wire", "protocol", "format", "and", "returns", "a", "bytes", "object", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4690-L4706
25,693
ldo/dbussy
dbussy.py
PendingCall.cancel
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” state for the PendingCall, # it just detaches it from any notifications about an incoming reply. self._awaiting.cancel()
python
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” state for the PendingCall, # it just detaches it from any notifications about an incoming reply. self._awaiting.cancel()
[ "def", "cancel", "(", "self", ")", ":", "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 “canc...
tells libdbus you no longer care about the pending incoming message.
[ "tells", "libdbus", "you", "no", "longer", "care", "about", "the", "pending", "incoming", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4834-L4841
25,694
ldo/dbussy
dbussy.py
Error.set
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
def set(self, name, msg) : "fills in the error name and message." dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode())
[ "def", "set", "(", "self", ",", "name", ",", "msg", ")", ":", "dbus", ".", "dbus_set_error", "(", "self", ".", "_dbobj", ",", "name", ".", "encode", "(", ")", ",", "b\"%s\"", ",", "msg", ".", "encode", "(", ")", ")" ]
fills in the error name and message.
[ "fills", "in", "the", "error", "name", "and", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4927-L4929
25,695
ldo/dbussy
dbussy.py
Introspection.parse
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) for childclass in tuple(celf.tag_elts.values()) + (Introspection.Annotation,) ) children = [] for child in tree : if child.tag not in child_tags : raise KeyError("unrecognized tag %s" % child.tag) #end if childclass = child_tags[child.tag] childattrs = {} for attrname in childclass.tag_attrs : if hasattr(childclass, "tag_attrs_optional") and attrname in childclass.tag_attrs_optional : childattrs[attrname] = child.attrib.get(attrname, None) else : if attrname not in child.attrib : raise ValueError("missing %s attribute for %s tag" % (attrname, child.tag)) #end if childattrs[attrname] = child.attrib[attrname] #end if #end for if hasattr(childclass, "attr_convert") : for attr in childclass.attr_convert : if attr in childattrs : childattrs[attr] = childclass.attr_convert[attr](childattrs[attr]) #end if #end for #end if children.append(from_string_elts(childclass, childattrs, child)) #end for for child_tag, childclass in tuple(celf.tag_elts.items()) + ((), (("annotations", Introspection.Annotation),))[tree.tag != "annotation"] : for child in children : if isinstance(child, childclass) : if child_tag not in elts : elts[child_tag] = [] #end if elts[child_tag].append(child) #end if #end for #end for return \ celf(**elts) #end from_string_elts #begin parse tree = XMLElementTree.fromstring(s) assert tree.tag == "node", "root of introspection tree must be <node> tag" return \ from_string_elts(Introspection, {}, tree)
python
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) for childclass in tuple(celf.tag_elts.values()) + (Introspection.Annotation,) ) children = [] for child in tree : if child.tag not in child_tags : raise KeyError("unrecognized tag %s" % child.tag) #end if childclass = child_tags[child.tag] childattrs = {} for attrname in childclass.tag_attrs : if hasattr(childclass, "tag_attrs_optional") and attrname in childclass.tag_attrs_optional : childattrs[attrname] = child.attrib.get(attrname, None) else : if attrname not in child.attrib : raise ValueError("missing %s attribute for %s tag" % (attrname, child.tag)) #end if childattrs[attrname] = child.attrib[attrname] #end if #end for if hasattr(childclass, "attr_convert") : for attr in childclass.attr_convert : if attr in childattrs : childattrs[attr] = childclass.attr_convert[attr](childattrs[attr]) #end if #end for #end if children.append(from_string_elts(childclass, childattrs, child)) #end for for child_tag, childclass in tuple(celf.tag_elts.items()) + ((), (("annotations", Introspection.Annotation),))[tree.tag != "annotation"] : for child in children : if isinstance(child, childclass) : if child_tag not in elts : elts[child_tag] = [] #end if elts[child_tag].append(child) #end if #end for #end for return \ celf(**elts) #end from_string_elts #begin parse tree = XMLElementTree.fromstring(s) assert tree.tag == "node", "root of introspection tree must be <node> tag" return \ from_string_elts(Introspection, {}, tree)
[ "def", "parse", "(", "celf", ",", "s", ")", ":", "def", "from_string_elts", "(", "celf", ",", "attrs", ",", "tree", ")", ":", "elts", "=", "dict", "(", "(", "k", ",", "attrs", "[", "k", "]", ")", "for", "k", "in", "attrs", ")", "child_tags", "=...
generates an Introspection tree from the given XML string description.
[ "generates", "an", "Introspection", "tree", "from", "the", "given", "XML", "string", "description", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L6141-L6195
25,696
ldo/dbussy
dbussy.py
Introspection.unparse
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 = getattr(obj, attrname) if attr != None : if isinstance(attr, enum.Enum) : attr = attr.value elif isinstance(attr, Type) : attr = unparse_signature(attr) elif not isinstance(attr, str) : raise TypeError("unexpected attribute type %s for %s" % (type(attr).__name__, repr(attr))) #end if attrs.append("%s=%s" % (attrname, quote_xml_attr(attr))) #end if #end for has_elts = \ ( sum ( len(getattr(obj, attrname)) for attrname in tuple(obj.tag_elts.keys()) + ((), ("annotations",)) [not isinstance(obj, Introspection.Annotation)] ) != 0 ) out.write(" " * indent + "<" + tag_name) if ( max_linelen != None and indent + len(tag_name) + sum((len(s) + 1) for s in attrs) + 2 + int(has_elts) > max_linelen ) : out.write("\n") for attr in attrs : out.write(" " * (indent + indent_step)) out.write(attr) out.write("\n") #end for out.write(" " * indent) else : for attr in attrs : out.write(" ") out.write(attr) #end for #end if if not has_elts : out.write("/") #end if out.write(">\n") if has_elts : for attrname in sorted(obj.tag_elts.keys()) + ["annotations"] : for elt in getattr(obj, attrname) : to_string(elt, indent + indent_step) #end for #end for out.write(" " * indent + "</" + tag_name + ">\n") #end if #end to_string #begin unparse out.write(DBUS.INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE) out.write("<node") if self.name != None : out.write(" name=%s" % quote_xml_attr(self.name)) #end if out.write(">\n") for elt in self.interfaces : to_string(elt, indent_step) #end for for elt in self.nodes : to_string(elt, indent_step) #end for out.write("</node>\n") return \ out.getvalue()
python
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 = getattr(obj, attrname) if attr != None : if isinstance(attr, enum.Enum) : attr = attr.value elif isinstance(attr, Type) : attr = unparse_signature(attr) elif not isinstance(attr, str) : raise TypeError("unexpected attribute type %s for %s" % (type(attr).__name__, repr(attr))) #end if attrs.append("%s=%s" % (attrname, quote_xml_attr(attr))) #end if #end for has_elts = \ ( sum ( len(getattr(obj, attrname)) for attrname in tuple(obj.tag_elts.keys()) + ((), ("annotations",)) [not isinstance(obj, Introspection.Annotation)] ) != 0 ) out.write(" " * indent + "<" + tag_name) if ( max_linelen != None and indent + len(tag_name) + sum((len(s) + 1) for s in attrs) + 2 + int(has_elts) > max_linelen ) : out.write("\n") for attr in attrs : out.write(" " * (indent + indent_step)) out.write(attr) out.write("\n") #end for out.write(" " * indent) else : for attr in attrs : out.write(" ") out.write(attr) #end for #end if if not has_elts : out.write("/") #end if out.write(">\n") if has_elts : for attrname in sorted(obj.tag_elts.keys()) + ["annotations"] : for elt in getattr(obj, attrname) : to_string(elt, indent + indent_step) #end for #end for out.write(" " * indent + "</" + tag_name + ">\n") #end if #end to_string #begin unparse out.write(DBUS.INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE) out.write("<node") if self.name != None : out.write(" name=%s" % quote_xml_attr(self.name)) #end if out.write(">\n") for elt in self.interfaces : to_string(elt, indent_step) #end for for elt in self.nodes : to_string(elt, indent_step) #end for out.write("</node>\n") return \ out.getvalue()
[ "def", "unparse", "(", "self", ",", "indent_step", "=", "4", ",", "max_linelen", "=", "72", ")", ":", "out", "=", "io", ".", "StringIO", "(", ")", "def", "to_string", "(", "obj", ",", "indent", ")", ":", "tag_name", "=", "obj", ".", "tag_name", "at...
returns an XML string description of this Introspection tree.
[ "returns", "an", "XML", "string", "description", "of", "this", "Introspection", "tree", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L6198-L6291
25,697
ldo/dbussy
ravel.py
ErrorReturn.as_error
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
python
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
[ "def", "as_error", "(", "self", ")", ":", "result", "=", "dbus", ".", "Error", ".", "init", "(", ")", "result", ".", "set", "(", "self", ".", "args", "[", "0", "]", ",", "self", ".", "args", "[", "1", "]", ")", "return", "result" ]
fills in and returns an Error object that reports the specified error name and message.
[ "fills", "in", "and", "returns", "an", "Error", "object", "that", "reports", "the", "specified", "error", "name", "and", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/ravel.py#L37-L42
25,698
ldo/dbussy
ravel.py
Connection.release_name_async
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) : "releases a registered bus name." assert self.loop != None, "no event loop to attach coroutine to" return \ await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout)
python
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) : "releases a registered bus name." assert self.loop != None, "no event loop to attach coroutine to" return \ await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout)
[ "async", "def", "release_name_async", "(", "self", ",", "bus_name", ",", "error", "=", "None", ",", "timeout", "=", "DBUS", ".", "TIMEOUT_USE_DEFAULT", ")", ":", "assert", "self", ".", "loop", "!=", "None", ",", "\"no event loop to attach coroutine to\"", "retur...
releases a registered bus name.
[ "releases", "a", "registered", "bus", "name", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/ravel.py#L382-L386
25,699
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
DefaultAdapter
def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_level=1) else: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter')
python
def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_level=1) else: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter')
[ "def", "DefaultAdapter", "(", "self", ")", ":", "default_adapter", "=", "None", "for", "obj", "in", "mockobject", ".", "objects", ".", "keys", "(", ")", ":", "if", "obj", ".", "startswith", "(", "'/org/bluez/'", ")", "and", "'dev_'", "not", "in", "obj", ...
Retrieve the default adapter
[ "Retrieve", "the", "default", "adapter" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L155-L168