code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# type: (ExportEndpoint) -> EndpointDescription
assert isinstance(endpoint, ExportEndpoint)
# Service properties
properties = endpoint.get_properties()
# Set import keys
properties[pelix.remote.PROP_ENDPOINT_ID] = endpoint.uid
properties[pelix.remote.PR... | def from_export(cls, endpoint) | Converts an ExportEndpoint bean to an EndpointDescription
:param endpoint: An ExportEndpoint bean
:return: An EndpointDescription bean | 2.996789 | 3.007301 | 0.996505 |
# type: (ElementTree.Element) -> EndpointDescription
endpoint = {}
for prop_node in node.findall(TAG_PROPERTY):
name, value = self._parse_property(prop_node)
endpoint[name] = value
return EndpointDescription(None, endpoint) | def _parse_description(self, node) | Parse an endpoint description node
:param node: The endpoint description node
:return: The parsed EndpointDescription bean
:raise KeyError: Attribute missing
:raise ValueError: Invalid description | 4.30834 | 5.2388 | 0.822391 |
# type: (ElementTree.Element) -> Tuple[str, Any]
# Get information
name = node.attrib[ATTR_NAME]
vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING)
# Look for a value as a single child node
try:
value_node = next(iter(node))
value = se... | def _parse_property(self, node) | Parses a property node
:param node: The property node
:return: A (name, value) tuple
:raise KeyError: Attribute missing | 3.428633 | 3.945143 | 0.869077 |
# type: (str, ElementTree.Element) -> Any
kind = node.tag
if kind == TAG_XML:
# Raw XML value
return next(iter(node))
elif kind == TAG_LIST or kind == TAG_ARRAY:
# List
return [
self._convert_value(vtype, value_nod... | def _parse_value_node(self, vtype, node) | Parses a value node
:param vtype: The value type
:param node: The value node
:return: The parsed value | 2.749241 | 3.323089 | 0.827315 |
# type: (str) -> List[EndpointDescription]
# Parse the document
root = ElementTree.fromstring(xml_str)
if root.tag != TAG_ENDPOINT_DESCRIPTIONS:
raise ValueError("Not an EDEF XML: {0}".format(root.tag))
# Parse content
return [
self._pars... | def parse(self, xml_str) | Parses an EDEF XML string
:param xml_str: An XML string
:return: The list of parsed EndpointDescription | 4.009665 | 3.908797 | 1.025805 |
# type: (ElementTree.Element, EndpointDescription) -> None
endpoint_node = ElementTree.SubElement(
root_node, TAG_ENDPOINT_DESCRIPTION
)
for name, value in endpoint.get_properties().items():
# Compute value type
vtype = self._get_type(name, v... | def _make_endpoint(self, root_node, endpoint) | Converts the given endpoint bean to an XML Element
:param root_node: The XML root Element
:param endpoint: An EndpointDescription bean | 2.919719 | 3.059373 | 0.954352 |
# type: (List[EndpointDescription]) -> ElementTree.Element
root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS)
for endpoint in endpoints:
self._make_endpoint(root, endpoint)
# Prepare pretty-printing
self._indent(root)
return root | def _make_xml(self, endpoints) | Converts the given endpoint description beans into an XML Element
:param endpoints: A list of EndpointDescription beans
:return: A string containing an XML document | 4.59279 | 6.245275 | 0.735402 |
# type: (List[EndpointDescription]) -> str
# Make the ElementTree
root = self._make_xml(endpoints)
tree = ElementTree.ElementTree(root)
# Force the default name space
ElementTree.register_namespace("", EDEF_NAMESPACE)
# Make the XML
# Prepare a ... | def to_string(self, endpoints) | Converts the given endpoint description beans into a string
:param endpoints: A list of EndpointDescription beans
:return: A string containing an XML document | 5.372619 | 6.066901 | 0.885562 |
# type: (List[EndpointDescription], str) -> None
with open(filename, "w") as filep:
filep.write(self.to_string(endpoints)) | def write(self, endpoints, filename) | Writes the given endpoint descriptions to the given file
:param endpoints: A list of EndpointDescription beans
:param filename: Name of the file where to write the XML
:raise IOError: Error writing the file | 3.867022 | 5.72587 | 0.67536 |
# type: (type, str, bool) -> bool
if value is None:
try:
# Get the current value
value = getattr(cls, attribute_name)
except AttributeError:
# No need to go further: the attribute does not exist
return False
for base in cls.__bases__:
... | def is_from_parent(cls, attribute_name, value=None) | Tests if the current attribute value is shared by a parent of the given
class.
Returns None if the attribute value is None.
:param cls: Child class with the requested attribute
:param attribute_name: Name of the attribute to be tested
:param value: The exact value in the child class (optional)
... | 3.766902 | 4.070126 | 0.9255 |
# type: (type) -> FactoryContext
context = getattr(cls, constants.IPOPO_FACTORY_CONTEXT, None)
if context is None:
# Class not yet manipulated
context = FactoryContext()
elif is_from_parent(cls, constants.IPOPO_FACTORY_CONTEXT):
# Create a copy the context
context =... | def get_factory_context(cls) | Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context | 5.907162 | 6.570695 | 0.899016 |
# type: (Callable) -> str
try:
try:
line_no = inspect.getsourcelines(method)[1]
except IOError:
# Error reading the source file
line_no = -1
return "'{method}' ({file}:{line})".format(
method=method.__name__, file=inspect.getfile(meth... | def get_method_description(method) | Retrieves a description of the given method. If possible, the description
contains the source file name and line.
:param method: A method
:return: A description of the method (at least its name)
:raise AttributeError: Given object has no __name__ attribute | 3.059719 | 3.286229 | 0.931073 |
# type: (Callable, *str) -> None
nb_needed_args = len(needed_args)
# Test the number of parameters
arg_spec = get_method_arguments(method)
method_args = arg_spec.args
try:
# Remove the self argument when present
if method_args[0] == "self":
del method_args[0]
... | def validate_method_arity(method, *needed_args) | Tests if the decorated method has a sufficient number of parameters.
:param method: The method to be tested
:param needed_args: The name (for description only) of the needed
arguments, without "self".
:return: Nothing
:raise TypeError: Invalid number of parameter | 3.262647 | 3.346849 | 0.974841 |
# type: (type, FactoryContext) -> None
assert inspect.isclass(cls)
assert isinstance(context, FactoryContext)
if context.callbacks is not None:
callbacks = context.callbacks.copy()
else:
callbacks = {}
functions = inspect.getmembers(cls, inspect.isroutine)
for _, func... | def _ipopo_setup_callback(cls, context) | Sets up the class _callback dictionary
:param cls: The class to handle
:param context: The factory class context | 3.925859 | 4.038322 | 0.972151 |
# type: (type, FactoryContext) -> None
assert inspect.isclass(cls)
assert isinstance(context, FactoryContext)
if context.field_callbacks is not None:
callbacks = context.field_callbacks.copy()
else:
callbacks = {}
functions = inspect.getmembers(cls, inspect.isroutine)
... | def _ipopo_setup_field_callback(cls, context) | Sets up the class _field_callback dictionary
:param cls: The class to handle
:param context: The factory class context | 3.884554 | 4.027936 | 0.964403 |
# type: (Any, str, Any) -> None
# Get the list
obj_list = getattr(obj, list_name, None)
if obj_list is None:
# We'll have to create it
obj_list = []
setattr(obj, list_name, obj_list)
assert isinstance(obj_list, list)
# Set up the property, if needed
if entry no... | def _append_object_entry(obj, list_name, entry) | Appends the given entry in the given object list.
Creates the list field if needed.
:param obj: The object that contains the list
:param list_name: The name of the list member in *obj*
:param entry: The entry to be added to the list
:raise ValueError: Invalid attribute content | 2.732342 | 3.398192 | 0.804058 |
# type: (str, Any, str) -> property
# The property lock
lock = threading.RLock()
# Prepare the methods names
getter_name = "{0}{1}".format(methods_prefix, constants.IPOPO_GETTER_SUFFIX)
setter_name = "{0}{1}".format(methods_prefix, constants.IPOPO_SETTER_SUFFIX)
local_holder = Holder(... | def _ipopo_class_field_property(name, value, methods_prefix) | Sets up an iPOPO field property, using Python property() capabilities
:param name: The property name
:param value: The property default value
:param methods_prefix: The common prefix of the getter and setter injected
methods
:return: A generated Python property() | 2.45053 | 2.638578 | 0.928731 |
if not specifications or specifications is object:
raise ValueError("No specifications given")
elif inspect.isclass(specifications):
if Provides.USE_MODULE_QUALNAME:
if sys.version_info < (3, 3, 0):
raise ValueError(
"Qualified name capability... | def _get_specifications(specifications) | Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found | 3.40743 | 3.343994 | 1.01897 |
# pylint: disable=C0103
if not inspect.isroutine(method):
raise TypeError("@Bind can only be applied on functions")
# Tests the number of parameters
validate_method_arity(method, "service", "service_reference")
_append_object_entry(
method, constants.IPOPO_METHOD_CALLBACKS, co... | def Bind(method) | The ``@Bind`` callback decorator is called when a component is bound to a
dependency.
The decorated method must accept the injected service object and its
:class:`~pelix.framework.ServiceReference` as arguments::
@Bind
def bind_method(self, service, service_reference):
'''
... | 8.546082 | 8.814943 | 0.969499 |
# pylint: disable=C0103
if not isinstance(method, types.FunctionType):
raise TypeError("@Update can only be applied on functions")
# Tests the number of parameters
validate_method_arity(
method, "service", "service_reference", "old_properties"
)
_append_object_entry(
... | def Update(method) | The ``@Update`` callback decorator is called when the properties of an
injected service have been modified.
The decorated method must accept the injected service object and its
:class:`~pelix.framework.ServiceReference` and the previous properties
as arguments::
@Update
def update_method... | 8.250815 | 6.566526 | 1.256496 |
# pylint: disable=C0103
if not isinstance(method, types.FunctionType):
raise TypeError("@Unbind can only be applied on functions")
# Tests the number of parameters
validate_method_arity(method, "service", "service_reference")
_append_object_entry(
method,
constants.IPO... | def Unbind(method) | The ``@Unbind`` callback decorator is called when a component dependency is
unbound.
The decorated method must accept the injected service object and its
:class:`~pelix.framework.ServiceReference` as arguments::
@Unbind
def unbind_method(self, service, service_reference):
'''
... | 7.90724 | 7.760581 | 1.018898 |
# pylint: disable=C0103
if not isinstance(method, types.FunctionType):
raise TypeError("@PostRegistration can only be applied on functions")
# Tests the number of parameters
validate_method_arity(method, "service_reference")
_append_object_entry(
method,
constants.IPOPO... | def PostRegistration(method) | The service post-registration callback decorator is called after a service
of the component has been registered to the framework.
The decorated method must accept the
:class:`~pelix.framework.ServiceReference` of the registered
service as argument::
@PostRegistration
def callback_method(... | 7.645374 | 7.219228 | 1.059029 |
# pylint: disable=C0103
if not isinstance(method, types.FunctionType):
raise TypeError("@PostUnregistration can only be applied on functions")
# Tests the number of parameters
validate_method_arity(method, "service_reference")
_append_object_entry(
method,
constants.IPO... | def PostUnregistration(method) | The service post-unregistration callback decorator is called after a service
of the component has been unregistered from the framework.
The decorated method must accept the
:class:`~pelix.framework.ServiceReference` of the registered
service as argument::
@PostUnregistration
def callback... | 7.346143 | 6.853119 | 1.071942 |
states = {
pelix.Bundle.INSTALLED: "INSTALLED",
pelix.Bundle.ACTIVE: "ACTIVE",
pelix.Bundle.RESOLVED: "RESOLVED",
pelix.Bundle.STARTING: "STARTING",
pelix.Bundle.STOPPING: "STOPPING",
pelix.Bundle.UNINSTALLED: "UNINSTALLED",
... | def bundlestate_to_str(state) | Converts a bundle state integer to a string | 2.07497 | 1.978122 | 1.04896 |
# Normalize the prefix
prefix = str(prefix or "")
# Maximum lengths
lengths = [len(title) for title in headers]
# Store the number of columns (0-based)
nb_columns = len(lengths) - 1
# Lines
str_lines = []
for idx, line in enumerate(line... | def make_table(headers, lines, prefix=None) | Generates an ASCII table according to the given headers and lines
:param headers: List of table headers (N-tuple)
:param lines: List of table lines (N-tuples)
:param prefix: Optional prefix for each line
:return: The ASCII representation of the table
:raise ValueError: Different... | 3.280839 | 3.261831 | 1.005827 |
if svc_ref in self._bound_references:
# Already bound service
return False
# Get the service
handler = self._context.get_service(svc_ref)
# Get its name space
namespace = handler.get_namespace()
commands = []
# Register all serv... | def bind_handler(self, svc_ref) | Called if a command service has been found.
Registers the methods of this service.
:param svc_ref: A reference to the found service
:return: True if the commands have been registered | 3.945237 | 4.010014 | 0.983846 |
if svc_ref not in self._bound_references:
# Unknown reference
return False
# Unregister its commands
namespace, commands = self._reference_commands[svc_ref]
for command in commands:
self.unregister(namespace, command)
# Release the s... | def unbind_handler(self, svc_ref) | Called if a command service is gone.
Unregisters its commands.
:param svc_ref: A reference to the unbound service
:return: True if the commands have been unregistered | 3.576097 | 3.548484 | 1.007782 |
if not kwargs:
session.write_line(
self._utils.make_table(
("Name", "Value"), session.variables.items()
)
)
else:
for name, value in kwargs.items():
name = name.strip()
sessio... | def var_set(self, session, **kwargs) | Sets the given variables or prints the current ones. "set answer=42" | 4.426096 | 3.709345 | 1.193228 |
bundle = None
try:
# Convert the given ID into an integer
bundle_id = int(bundle_id)
except ValueError:
# Not an integer, suppose it's a bundle name
for bundle in self._context.get_bundles():
if bundle.get_symbolic_name() ... | def bundle_details(self, io_handler, bundle_id) | Prints the details of the bundle with the given ID or name | 2.244285 | 2.224118 | 1.009067 |
# Head of the table
headers = ("ID", "Name", "State", "Version")
# Get the bundles
bundles = self._context.get_bundles()
# The framework is not in the result of get_bundles()
bundles.insert(0, self._context.get_framework())
if name is not None:
... | def bundles_list(self, io_handler, name=None) | Lists the bundles in the framework and their state. Possibility to
filter on the bundle name. | 3.395652 | 3.363281 | 1.009625 |
svc_ref = self._context.get_service_reference(
None, "({0}={1})".format(constants.SERVICE_ID, service_id)
)
if svc_ref is None:
io_handler.write_line("Service not found: {0}", service_id)
return False
lines = [
"ID............: {0... | def service_details(self, io_handler, service_id) | Prints the details of the service with the given ID | 2.176093 | 2.152823 | 1.010809 |
# Head of the table
headers = ("ID", "Specifications", "Bundle", "Ranking")
# Lines
references = (
self._context.get_all_service_references(specification, None) or []
)
# Construct the list of services
lines = [
[
... | def services_list(self, io_handler, specification=None) | Lists the services in the framework. Possibility to filter on an exact
specification. | 4.410649 | 4.333559 | 1.017789 |
# Get the framework
framework = self._context.get_framework()
# Head of the table
headers = ("Property Name", "Value")
# Lines
lines = [item for item in framework.get_properties().items()]
# Sort lines
lines.sort()
# Print the table
... | def properties_list(self, io_handler) | Lists the properties of the framework | 5.458512 | 5.073151 | 1.075961 |
value = self._context.get_property(name)
if value is None:
# Avoid printing "None"
value = ""
io_handler.write_line(str(value)) | def property_value(self, io_handler, name) | Prints the value of the given property, looking into
framework properties then environment variables. | 5.331622 | 4.803357 | 1.109978 |
# Head of the table
headers = ("Environment Variable", "Value")
# Lines
lines = [item for item in os.environ.items()]
# Sort lines
lines.sort()
# Print the table
io_handler.write(self._utils.make_table(headers, lines)) | def environment_list(self, io_handler) | Lists the framework process environment variables | 6.54842 | 5.753609 | 1.138141 |
# Normalize maximum depth
try:
max_depth = int(max_depth)
if max_depth < 1:
max_depth = None
except (ValueError, TypeError):
max_depth = None
# pylint: disable=W0212
try:
# Extract frames
frames... | def threads_list(io_handler, max_depth=1) | Lists the active threads and their current code line | 2.979328 | 2.911352 | 1.023348 |
# Normalize maximum depth
try:
max_depth = int(max_depth)
if max_depth < 1:
max_depth = None
except (ValueError, TypeError):
max_depth = None
# pylint: disable=W0212
try:
# Get the stack
thread_... | def thread_details(io_handler, thread_id, max_depth=0) | Prints details about the thread with the given ID (not its name) | 2.500731 | 2.491432 | 1.003732 |
# Get the logger
logger = logging.getLogger(name)
# Normalize the name
if not name:
name = "Root"
if not level:
# Level not given: print the logger level
io_handler.write_line(
"{0} log level: {1} (real: {2})",
... | def log_level(io_handler, level=None, name=None) | Prints/Changes log level | 2.896904 | 2.757829 | 1.050429 |
if path == "-":
# Previous directory
path = self._previous_path or "."
try:
previous = os.getcwd()
os.chdir(path)
except IOError as ex:
# Can't change directory
session.write_line("Error changing directory: {0}", e... | def change_dir(self, session, path) | Changes the working directory | 4.457405 | 4.415625 | 1.009462 |
try:
bundle_id = int(bundle_id)
return self._context.get_bundle(bundle_id)
except (TypeError, ValueError):
io_handler.write_line("Invalid bundle ID: {0}", bundle_id)
except constants.BundleException:
io_handler.write_line("Unknown bundle: ... | def __get_bundle(self, io_handler, bundle_id) | Retrieves the Bundle object with the given bundle ID. Writes errors
through the I/O handler if any.
:param io_handler: I/O Handler
:param bundle_id: String or integer bundle ID
:return: The Bundle object matching the given ID, None if not found | 3.181617 | 3.171725 | 1.003119 |
for bid in (bundle_id,) + bundles_ids:
try:
# Got an int => it's a bundle ID
bid = int(bid)
except ValueError:
# Got something else, we will try to install it first
bid = self.install(io_handler, bid)
b... | def start(self, io_handler, bundle_id, *bundles_ids) | Starts the bundles with the given IDs. Stops on first failure. | 3.982248 | 3.997913 | 0.996082 |
for bid in (bundle_id,) + bundles_ids:
bundle = self.__get_bundle(io_handler, bid)
if bundle is not None:
io_handler.write_line(
"Stopping bundle {0} ({1})...",
bid,
bundle.get_symbolic_name(),
... | def stop(self, io_handler, bundle_id, *bundles_ids) | Stops the bundles with the given IDs. Stops on first failure. | 3.561026 | 3.472406 | 1.025521 |
bundle = self._context.install_bundle(module_name)
io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id())
return bundle.get_bundle_id() | def install(self, io_handler, module_name) | Installs the bundle with the given module name | 4.353471 | 3.996793 | 1.089241 |
if not isinstance(requires_filters, dict):
requires_filters = {}
if not isinstance(temporal_timeouts, dict):
temporal_timeouts = {}
if not requires_filters and not temporal_timeouts:
# No explicit configuration given
return configs
... | def _prepare_configs(configs, requires_filters, temporal_timeouts) | Overrides the filters specified in the decorator with the given ones
:param configs: Field → (Requirement, key, allow_none) dictionary
:param requires_filters: Content of the 'requires.filter' component
property (field → string)
:param temporal_timeouts: Content... | 3.026349 | 2.946151 | 1.027221 |
# Extract information from the context
configs = component_context.get_handler(
ipopo_constants.HANDLER_TEMPORAL
)
requires_filters = component_context.properties.get(
ipopo_constants.IPOPO_REQUIRES_FILTERS, None
)
temporal_timeouts = comp... | def get_handlers(self, component_context, instance) | Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component | 4.58064 | 4.804683 | 0.95337 |
# Cancel timer
self.__cancel_timer()
self.__timer = None
self.__timer_args = None
self.__still_valid = False
self._value = None
super(TemporalDependency, self).clear() | def clear(self) | Cleans up the manager. The manager can't be used after this method has
been called | 10.088049 | 10.306648 | 0.97879 |
with self._lock:
if self.reference is None:
# Inject the service
service = self._context.get_service(svc_ref)
self.reference = svc_ref
self._value.set_service(service)
self.__still_valid = True
... | def on_service_arrival(self, svc_ref) | Called when a service has been registered in the framework
:param svc_ref: A service reference | 6.110288 | 6.850502 | 0.891947 |
with self._lock:
if svc_ref is self.reference:
# Forget about the service
self._value.unset_service()
# Clear the reference
self.reference = None
# Look for a replacement
self._pending_ref = se... | def on_service_departure(self, svc_ref) | Called when a service has been unregistered from the framework
:param svc_ref: A service reference | 6.14657 | 6.818448 | 0.901462 |
if self.__timer is not None:
self.__timer.cancel()
self.__unbind_call(True)
self.__timer_args = None
self.__timer = None | def __cancel_timer(self) | Cancels the timer, and calls its target method immediately | 6.011561 | 5.299574 | 1.134348 |
with self._lock:
if self.__timer is not None:
# Timeout expired, we're not valid anymore
self.__timer = None
self.__still_valid = still_valid
self._ipopo_instance.unbind(
self, self.__timer_args[0], self.__t... | def __unbind_call(self, still_valid) | Calls the iPOPO unbind method | 5.106646 | 4.278018 | 1.193694 |
# pylint: disable=C0103
# Get the request JSON content
data = jsonrpclib.loads(to_str(request.read_data()))
# Convert from Jabsorb
data = jabsorb.from_jabsorb(data)
# Dispatch
try:
result = self._unmarshaled_dispatch(data, self._simple_dispa... | def do_POST(self, request, response) | Handle a POST request
:param request: The HTTP request bean
:param response: The HTTP response handler | 4.637986 | 4.796747 | 0.966902 |
# type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None
# Extract request information
http_verb = request.get_command()
sub_path = request.get_sub_path()
# Find the best matching method, according to the number of
# readable arguments
m... | def _rest_dispatch(self, request, response) | Dispatches the request
:param request: Request bean
:param response: Response bean | 3.16137 | 3.218374 | 0.982288 |
for _, method in inspect.getmembers(self, inspect.isroutine):
try:
config = getattr(method, HTTP_ROUTE_ATTRIBUTE)
except AttributeError:
# Not a REST method
continue
for route in config["routes"]:
patte... | def _setup_rest_dispatcher(self) | Finds all methods to call when handling a route | 4.782985 | 4.346686 | 1.100375 |
# type: (str) -> Tuple[Pattern[str], Dict[str, Callable[[str], Any]]]
arguments = {} # type: Dict[str, Callable[[str], Any]]
last_idx = 0
final_pattern = []
match_iter = _MARKER_PATTERN.finditer(route)
for match_pattern in match_iter:
# Copy intermed... | def __convert_route(route) | Converts a route pattern into a regex.
The result is a tuple containing the regex pattern to match and a
dictionary associating arguments names and their converter (if any)
A route can be: "/hello/<name>/<age:int>"
:param route: A route string, i.e. a path with type markers
:re... | 3.512443 | 3.365849 | 1.043553 |
# type: (ServiceEvent) -> bool
with self._lock:
if self.state == StoredInstance.KILLED:
# This call may have been blocked by the internal state lock,
# ignore it
return False
return self.__safe_handlers_callback("check_eve... | def check_event(self, event) | Tests if the given service event must be handled or ignored, based
on the state of the iPOPO service and on the content of the event.
:param event: A service event
:return: True if the event can be handled, False if it must be ignored | 13.533804 | 13.665184 | 0.990386 |
# type: (Any, Any, ServiceReference) -> None
with self._lock:
self.__set_binding(dependency, svc, svc_ref)
self.check_lifecycle() | def bind(self, dependency, svc, svc_ref) | Called by a dependency manager to inject a new service and update the
component life cycle. | 5.331689 | 5.23271 | 1.018915 |
# type: (Any, Any, ServiceReference, dict, bool) -> None
with self._lock:
self.__update_binding(
dependency, svc, svc_ref, old_properties, new_value
)
self.check_lifecycle() | def update(self, dependency, svc, svc_ref, old_properties, new_value=False) | Called by a dependency manager when the properties of an injected
dependency have been updated.
:param dependency: The dependency handler
:param svc: The injected service
:param svc_ref: The reference of the injected service
:param old_properties: Previous properties of the depe... | 4.632922 | 7.673109 | 0.603787 |
# type: (Any, Any, ServiceReference) -> None
with self._lock:
# Invalidate first (if needed)
self.check_lifecycle()
# Call unbind() and remove the injection
self.__unset_binding(dependency, svc, svc_ref)
# Try a new configuration
... | def unbind(self, dependency, svc, svc_ref) | Called by a dependency manager to remove an injected service and to
update the component life cycle. | 8.75852 | 7.907031 | 1.107688 |
# type: (str, bool) -> None
with self._lock:
self._controllers_state[name] = value
self.__safe_handlers_callback("on_controller_change", name, value) | def set_controller_state(self, name, value) | Sets the state of the controller with the given name
:param name: The name of the controller
:param value: The new value of the controller | 5.365284 | 9.300046 | 0.576909 |
# type: (str, Any, Any) -> None
with self._lock:
self.__safe_handlers_callback(
"on_property_change", name, old_value, new_value
) | def update_property(self, name, old_value, new_value) | Handles a property changed event
:param name: The changed property name
:param old_value: The previous property value
:param new_value: The new property value | 5.20697 | 7.349869 | 0.708444 |
# type: (str, Any, Any) -> None
with self._lock:
self.__safe_handlers_callback(
"on_hidden_property_change", name, old_value, new_value
) | def update_hidden_property(self, name, old_value, new_value) | Handles an hidden property changed event
:param name: The changed property name
:param old_value: The previous property value
:param new_value: The new property value | 4.983067 | 7.580613 | 0.657344 |
with self._lock:
if kind is not None:
try:
return self._handlers[kind][:]
except KeyError:
return []
return self.__all_handlers.copy() | def get_handlers(self, kind=None) | Retrieves the handlers of the given kind. If kind is None, all handlers
are returned.
:param kind: The kind of the handlers to return
:return: A list of handlers, or an empty list | 4.352099 | 6.20232 | 0.701689 |
with self._lock:
# Validation flags
was_valid = self.state == StoredInstance.VALID
can_validate = self.state not in (
StoredInstance.VALIDATING,
StoredInstance.VALID,
)
# Test the validity of all handlers
... | def check_lifecycle(self) | Tests if the state of the component must be updated, based on its own
state and on the state of its dependencies | 7.181755 | 6.857825 | 1.047235 |
# type: () -> bool
with self._lock:
all_valid = True
for handler in self.get_handlers(handlers_const.KIND_DEPENDENCY):
# Try to bind
self.__safe_handler_callback(handler, "try_binding")
# Update the validity flag
... | def update_bindings(self) | Updates the bindings of the given component
:return: True if the component can be validated | 8.039683 | 8.789843 | 0.914656 |
# type: (dict) -> int
with self._lock:
if self.state != StoredInstance.ERRONEOUS:
# Not in erroneous state: ignore
return self.state
# Update properties
if properties_update:
self.context.properties.update(prop... | def retry_erroneous(self, properties_update) | Removes the ERRONEOUS state from a component and retries a validation
:param properties_update: A dictionary to update component properties
:return: The new state of the component | 5.469012 | 5.41349 | 1.010256 |
# type: (bool) -> bool
with self._lock:
if self.state != StoredInstance.VALID:
# Instance is not running...
return False
# Change the state
self.state = StoredInstance.INVALID
# Call the handlers
self.... | def invalidate(self, callback=True) | Applies the component invalidation.
:param callback: If True, call back the component before the
invalidation
:return: False if the component wasn't valid | 5.639233 | 5.995256 | 0.940616 |
# type: () -> bool
with self._lock:
# Already dead...
if self.state == StoredInstance.KILLED:
return False
try:
self.invalidate(True)
except:
self._logger.exception(
"%s: Error i... | def kill(self) | This instance is killed : invalidate it if needed, clean up all members
When this method is called, this StoredInstance object must have
been removed from the registry
:return: True if the component has been killed, False if it already was | 4.979939 | 4.83707 | 1.029536 |
# type: (bool) -> bool
with self._lock:
if self.state in (
StoredInstance.VALID,
StoredInstance.VALIDATING,
StoredInstance.ERRONEOUS,
):
# No work to do (yet)
return False
if sel... | def validate(self, safe_callback=True) | Ends the component validation, registering services
:param safe_callback: If True, calls the component validation callback
:return: True if the component has been validated, else False
:raise RuntimeError: You try to awake a dead component | 5.860417 | 5.876755 | 0.99722 |
# type: (str, *Any, **Any) -> Any
comp_callback = self.context.get_callback(event)
if not comp_callback:
# No registered callback
return True
# Call it
result = comp_callback(self.instance, *args, **kwargs)
if result is None:
... | def __callback(self, event, *args, **kwargs) | Calls the registered method in the component for the given event
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The callback result, or None
:raise Exception: Something went wrong | 5.105889 | 6.190251 | 0.824827 |
# type: (str) -> Any
comp_callback = self.context.get_callback(event)
if not comp_callback:
# No registered callback
return True
# Get the list of arguments
try:
args = getattr(comp_callback, constants.IPOPO_VALIDATE_ARGS)
exc... | def __validation_callback(self, event) | Specific handling for the ``@ValidateComponent`` and
``@InvalidateComponent`` callback, as it requires checking arguments
count and order
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None
:raise Exception: Something went wrong | 5.460968 | 5.300649 | 1.030245 |
# type: (str, str, *Any, **Any) -> Any
# Get the field callback info
cb_info = self.context.get_field_callback(field, event)
if not cb_info:
# No registered callback
return True
# Extract information
callback, if_valid = cb_info
... | def __field_callback(self, field, event, *args, **kwargs) | Calls the registered method in the component for the given field event
:param field: A field name
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The callback result, or None
:raise Exception: Something went wrong | 5.716385 | 5.937277 | 0.962796 |
# type: (str, *Any, **Any) -> Any
if self.state == StoredInstance.KILLED:
# Invalid state
return None
try:
return self.__callback(event, *args, **kwargs)
except FrameworkException as ex:
# Important error
self._logger.... | def safe_callback(self, event, *args, **kwargs) | Calls the registered method in the component for the given event,
ignoring raised exceptions
:param event: An event (IPOPO_CALLBACK_VALIDATE, ...)
:return: The callback result, or None | 5.50919 | 5.64483 | 0.975971 |
# type: (str) -> Any
if self.state == StoredInstance.KILLED:
# Invalid state
return None
try:
return self.__validation_callback(event)
except FrameworkException as ex:
# Important error
self._logger.exception(
... | def __safe_validation_callback(self, event) | Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None | 5.874792 | 5.764462 | 1.01914 |
# type: (Any, str, *Any, **Any) -> Any
if handler is None or method_name is None:
return None
# Behavior flags
only_boolean = kwargs.pop("only_boolean", False)
none_as_true = kwargs.pop("none_as_true", False)
# Get the method for each handler
... | def __safe_handler_callback(self, handler, method_name, *args, **kwargs) | Calls the given method with the given arguments in the given handler.
Logs exceptions, but doesn't propagate them.
Special arguments can be given in kwargs:
* 'none_as_true': If set to True and the method returned None or
doesn't exist, the result is considered as Tru... | 3.140098 | 2.938435 | 1.068629 |
# type: (str, *Any, **Any) -> bool
if self.state == StoredInstance.KILLED:
# Nothing to do
return False
# Behavior flags
exception_as_error = kwargs.pop("exception_as_error", False)
break_on_false = kwargs.pop("break_on_false", False)
re... | def __safe_handlers_callback(self, method_name, *args, **kwargs) | Calls the given method with the given arguments in all handlers.
Logs exceptions, but doesn't propagate them.
Methods called in handlers must return None, True or False.
Special parameters can be given in kwargs:
* 'exception_as_error': if it is set to True and an exception is raised
... | 4.210737 | 3.734386 | 1.127558 |
# type: (Any, Any, ServiceReference) -> None
# Set the value
setattr(self.instance, dependency.get_field(), dependency.get_value())
# Call the component back
self.safe_callback(constants.IPOPO_CALLBACK_BIND, service, reference)
self.__safe_field_callback(
... | def __set_binding(self, dependency, service, reference) | Injects a service in the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service | 6.310238 | 8.16135 | 0.773186 |
# type: (Any, Any, ServiceReference, dict, bool) -> None
if new_value:
# Set the value
setattr(
self.instance, dependency.get_field(), dependency.get_value()
)
# Call the component back
self.__safe_field_callback(
... | def __update_binding(
self, dependency, service, reference, old_properties, new_value
) | Calls back component binding and field binding methods when the
properties of an injected dependency have been updated.
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
:param old_properties: P... | 5.311953 | 5.139286 | 1.033597 |
# type: (Any, Any, ServiceReference) -> None
# Call the component back
self.__safe_field_callback(
dependency.get_field(),
constants.IPOPO_CALLBACK_UNBIND_FIELD,
service,
reference,
)
self.safe_callback(constants.IPOPO_CAL... | def __unset_binding(self, dependency, service, reference) | Removes a service from the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service | 5.814037 | 6.629481 | 0.876997 |
if not value:
return False
try:
# Lower string to check known "false" value
value = value.lower()
return value not in ("none", "0", "false", "no")
except AttributeError:
# Not a string, but has a value
return True | def _parse_boolean(value) | Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value | 6.398297 | 7.206885 | 0.887803 |
formatter = string.Formatter()
return [
val[1] for val in formatter.parse(self._original_filter) if val[1]
] | def _find_keys(self) | Looks for the property keys in the filter string
:return: A list of property keys | 7.901054 | 7.795102 | 1.013592 |
# Consider the filter invalid
self.valid_filter = False
try:
# Format the new filter
filter_str = self._original_filter.format(
**self._component_context.properties
)
except KeyError as ex:
# An entry is missing: a... | def update_filter(self) | Update the filter according to the new properties
:return: True if the filter changed, else False
:raise ValueError: The filter is invalid | 4.698424 | 4.530523 | 1.03706 |
# pylint: disable=W0613
if name in self._keys:
try:
if self.update_filter():
# This is a key for the filter and the filter has changed
# => Force the handler to update its dependency
self._reset()
... | def on_property_change(self, name, old_value, new_value) | A component property has been updated
:param name: Name of the property
:param old_value: Previous value of the property
:param new_value: New value of the property | 9.47753 | 10.511215 | 0.901659 |
with self._lock:
# Start listening to services with the new filter
self.stop()
self.start()
for svc_ref in self.get_bindings():
# Check if the current reference matches the filter
if not self.requirement.filter.matches(
... | def _reset(self) | Called when the filter has been changed | 9.231913 | 8.5212 | 1.083405 |
self.__data = data
self.__exception = None
self.__event.set() | def set(self, data=None) | Sets the event | 10.118506 | 9.343308 | 1.082968 |
self.__data = None
self.__exception = exception
self.__event.set() | def raise_exception(self, exception) | Raises an exception in wait()
:param exception: An Exception object | 7.588844 | 9.787472 | 0.775363 |
# The 'or' part is for Python 2.6
result = self.__event.wait(timeout)
# pylint: disable=E0702
# Pylint seems to miss the "is None" check below
if self.__exception is None:
return result
else:
raise self.__exception | def wait(self, timeout=None) | Waits for the event or for the timeout
:param timeout: Wait timeout (in seconds)
:return: True if the event as been set, else False | 6.164673 | 6.27505 | 0.98241 |
if self.__callback is not None:
try:
self.__callback(
self._done_event.data,
self._done_event.exception,
self.__extra,
)
except Exception as ex:
self._logger.exception("Er... | def __notify(self) | Notify the given callback about the result of the execution | 5.053258 | 4.714098 | 1.071946 |
self.__callback = method
self.__extra = extra
if self._done_event.is_set():
# The execution has already finished
self.__notify() | def set_callback(self, method, extra=None) | Sets a callback method, called once the result has been computed or in
case of exception.
The callback method must have the following signature:
``callback(result, exception, extra)``.
:param method: The method to call back in the end of the execution
:param extra: Extra parame... | 7.396791 | 7.662979 | 0.965263 |
# Normalize arguments
if args is None:
args = []
if kwargs is None:
kwargs = {}
try:
# Call the method
result = method(*args, **kwargs)
except Exception as ex:
# Something went wrong: propagate to the event an... | def execute(self, method, args, kwargs) | Execute the given method and stores its result.
The result is considered "done" even if the method raises an exception
:param method: The method to execute
:param args: Method positional arguments
:param kwargs: Method keyword arguments
:raise Exception: The exception raised by ... | 4.12811 | 3.980738 | 1.037021 |
if self._done_event.wait(timeout):
return self._done_event.data
else:
raise OSError("Timeout raised") | def result(self, timeout=None) | Waits up to timeout for the result the threaded job.
Returns immediately the result if the job has already been done.
:param timeout: The maximum time to wait for a result (in seconds)
:raise OSError: The timeout raised before the job finished
:raise Exception: The exception encountered... | 7.226124 | 6.248502 | 1.156457 |
if not self._done_event.is_set():
# Stop event not set: we're running
return
# Clear the stop event
self._done_event.clear()
# Compute the number of threads to start to handle pending tasks
nb_pending_tasks = self._queue.qsize()
if nb_pe... | def start(self) | Starts the thread pool. Does nothing if the pool is already started. | 2.849825 | 2.685611 | 1.061146 |
with self.__lock:
if self.__nb_threads >= self._max_threads:
# Can't create more threads
return False
if self._done_event.is_set():
# We're stopped: do nothing
return False
# Prepare thread and start i... | def __start_thread(self) | Starts a new thread, if possible | 3.206816 | 3.051627 | 1.050855 |
if self._done_event.is_set():
# Stop event set: we're stopped
return
# Set the stop event
self._done_event.set()
with self.__lock:
# Add something in the queue (to unlock the join())
try:
for _ in self._threads:
... | def stop(self) | Stops the thread pool. Does nothing if the pool is already stopped. | 4.515344 | 4.313747 | 1.046734 |
if not hasattr(method, "__call__"):
raise ValueError(
"{0} has no __call__ member.".format(method.__name__)
)
# Prepare the future result object
future = FutureResult(self._logger)
# Use a lock, as we might be "resetting" the queue
... | def enqueue(self, method, *args, **kwargs) | Queues a task in the pool
:param method: Method to call
:return: A FutureResult object, to get the result of the task
:raise ValueError: Invalid method
:raise Full: The task queue is full | 4.511264 | 4.18858 | 1.077039 |
with self.__lock:
# Empty the current queue
try:
while True:
self._queue.get_nowait()
self._queue.task_done()
except queue.Empty:
# Queue is now empty
pass
# Wait for... | def clear(self) | Empties the current queue content.
Returns once the queue have been emptied. | 4.970848 | 4.56109 | 1.089838 |
if self._queue.empty():
# Nothing to wait for...
return True
elif timeout is None:
# Use the original join
self._queue.join()
return True
else:
# Wait for the condition
with self._queue.all_tasks_done:
... | def join(self, timeout=None) | Waits for all the tasks to be executed
:param timeout: Maximum time to wait (in seconds)
:return: True if the queue has been emptied, else False | 3.495356 | 3.391699 | 1.030562 |
already_cleaned = False
try:
while not self._done_event.is_set():
try:
# Wait for an action (blocking)
task = self._queue.get(True, self._timeout)
if task is self._done_event:
# Stop ... | def __run(self) | The main loop | 4.365304 | 4.255781 | 1.025735 |
if not isinstance(url, bytes):
url = url.encode(encoding)
parser = _URL_PARSER
idx = 0
for _c in url:
if _c not in _HEX:
if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH
or idx == _HOSTID_LENGTH + 1)):
retu... | def docid(url, encoding='ascii') | Get DocID from URL.
DocID generation depends on bytes of the URL string.
So, if non-ascii charactors in the URL, encoding should
be considered properly.
Args:
url (str or bytes): Pre-encoded bytes or string will be encoded with the
'encoding' argument.
encoding (str, option... | 4.099371 | 4.152299 | 0.987253 |
if record.exc_info:
if record.exc_text:
if "Stack frames (most recent call first)" not in record.exc_text:
record.exc_text = None
return super(LocalVarFormatter, self).format(record) | def format(self, record) | Format the specified record as text. Overrides
:meth:`logging.Formatter.format` to remove cache of
:attr:`record.exc_text` unless it was produced by this formatter. | 4.425233 | 4.410347 | 1.003375 |
return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip) | def sanitize_html(value, valid_tags=VALID_TAGS, strip=True) | Strips unwanted markup out of HTML. | 3.144118 | 3.07946 | 1.020997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.