code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Store the stored instance
self._ipopo_instance = stored_instance
# Public flags to generate (True for public accessors)
flags_to_generate = set()
if stored_instance.context.properties:
flags_to_generate.add(True)
# (False for hidden ones)
... | def manipulate(self, stored_instance, component_instance) | Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | 4.786159 | 4.709577 | 1.016261 |
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__ | def _full_class_name(obj) | Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible) | 1.923578 | 2.363708 | 0.813797 |
if prompt:
# Print the prompt
self.write(prompt)
self.output.flush()
# Read the line
return to_str(self.input.readline()) | def _prompt(self, prompt=None) | Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str | 6.35043 | 6.984248 | 0.90925 |
with self.__lock:
self.output.write(to_bytes(data, self.encoding)) | def _write_bytes(self, data) | Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()`` | 7.317892 | 6.563219 | 1.114985 |
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode()
.decode(self.out_encoding, errors="replace")
) | def _write_str(self, data) | Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()`` | 5.664919 | 5.800135 | 0.976688 |
if line is None:
# Empty line
self.write("\n")
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
with self.__lock:
# Write it
s... | def write_line(self, line=None, *args, **kwargs) | Formats and writes a line to the output | 3.574214 | 3.46684 | 1.030972 |
if line is None:
# Empty line
line = ""
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
# Remove the trailing line feed
if line[-1] == "\n":
... | def write_line_no_feed(self, line=None, *args, **kwargs) | Formats and writes a line to the output | 3.427225 | 3.22365 | 1.063151 |
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find ... | 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
(never None) | 10.772782 | 10.796039 | 0.997846 |
# Create the logger for this component instance
self._logger = logging.getLogger(self._name)
# Inject it
setattr(component_instance, self._field, self._logger) | def manipulate(self, stored_instance, component_instance) | Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | 7.688756 | 7.401538 | 1.038805 |
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
self._logger = None | def clear(self) | Cleans up the handler. The handler can't be used after this method has
been called | 16.086535 | 14.769722 | 1.089156 |
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
if not current:
# No word yet, so the current position is after the existing ones
arg_idx = len(arguments)
else:
# Find the current word position
arg_idx = arguments.index(current)
... | def completion_hints(config, prompt, session, context, current, arguments) | Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The shell prompt string
:param session: Current shell session
:param context: Context of the shell UI bundle
:param current: Current argument (to be completed)
:param a... | 3.39206 | 3.603381 | 0.941355 |
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find ... | 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
(never None) | 8.326932 | 8.322026 | 1.000589 |
if not file_name:
return None
path = os.path.realpath(file_name)
if os.path.isfile(path):
return path
return None | def _resolve_file(file_name) | Checks if the file exists.
If the file exists, the method returns its absolute path.
Else, it returns None
:param file_name: The name of the file to check
:return: An absolute path, or None | 2.840393 | 3.295687 | 0.861851 |
parser = argparse.ArgumentParser(add_help=False)
# Version number
parser.add_argument(
"--version",
action="version",
version="Pelix {0} from {1}".format(pelix.__version__, pelix.__file__),
)
# Framework options
group = parser.add_argument_group("Framework options"... | def make_common_parser() | Creates an argument parser (argparse module) with the options that should
be common to all shells.
The result can be used as a parent parser (``parents`` argument in
``argparse.ArgumentParser``)
:return: An ArgumentParser object | 2.318613 | 2.400895 | 0.965728 |
# Setup the logger
logging.basicConfig(
level=logging.DEBUG if parsed_args.verbose else logging.WARNING
)
# Framework properties dictionary
props = {}
# Read the initial configuration script
init = InitFileHandler()
if not parsed_args.init_empty:
if not parsed_args... | def handle_common_arguments(parsed_args) | Handles the arguments defined by :meth:`~make_common_parser`
:param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
:return: An :class:`~InitFileHandler` object
:raise IOError: Initial or run script not found | 3.276034 | 3.044938 | 1.075895 |
# Parse arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.console",
parents=[make_common_parser()],
description="Pelix Shell Console",
)
# Parse arguments
args = parser.parse_args(argv)
# Handle arguments
init = handle_common_arguments(args)
# ... | def main(argv=None) | Entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None | 3.761345 | 3.834013 | 0.981046 |
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input() | def _normal_prompt(self) | Flushes the prompt before requesting the input
:return: The command line | 7.311009 | 10.352024 | 0.70624 |
# Start the init script
self._run_script(
self.__session, self._context.get_property(PROP_INIT_FILE)
)
# Run the script
script_file = self._context.get_property(PROP_RUN_FILE)
if script_file:
self._run_script(self.__session, script_file)
... | def loop_input(self, on_quit=None) | Reads the standard input until the shell session is stopped
:param on_quit: A call back method, called without argument when the
shell session has ended | 4.228209 | 4.375198 | 0.966404 |
if file_path:
# The 'run' command returns False in case of error
# The 'execute' method returns False if the run command fails
return self._shell.execute('run "{0}"'.format(file_path), session)
return None | def _run_script(self, session, file_path) | Runs the given script file
:param session: Current shell session
:param file_path: Path to the file to execute
:return: True if a file has been execute | 8.035368 | 8.281463 | 0.970284 |
try:
first_prompt = True
# Set up the prompt
prompt = (
self._readline_prompt
if readline is not None
else self._normal_prompt
)
while not self._stop_event.is_set():
# Wait for ... | def _run_loop(self, session) | Runs the main input loop
:param session: Current shell session | 4.606766 | 4.609544 | 0.999397 |
if state == 0:
# New completion, reset the list of matches and the display hook
self._readline_matches = []
try:
readline.set_completion_display_matches_hook(None)
except AttributeError:
pass
# Get the full lin... | def readline_completer(self, text, state) | A completer for the readline library | 3.334804 | 3.307678 | 1.008201 |
with self._lock:
if self._shell is not None:
# A shell is already there
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not None:
self.set_shell(reference) | def search_shell(self) | Looks for a shell service | 5.063065 | 4.180335 | 1.211163 |
kind = event.get_kind()
reference = event.get_service_reference()
if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED):
# A service matches our filter
self.set_shell(reference)
else:
with self._lock:
# Serv... | def service_changed(self, event) | Called by Pelix when an events changes | 6.369383 | 5.532628 | 1.15124 |
if svc_ref is None:
return
with self._lock:
# Get the service
self._shell_ref = svc_ref
self._shell = self._context.get_service(self._shell_ref)
# Set the readline completer
if readline is not None:
readli... | def set_shell(self, svc_ref) | Binds the given shell service.
:param svc_ref: A service reference | 3.753224 | 4.142968 | 0.905926 |
with self._lock:
# Clear the flag
self._shell_event.clear()
# Clear the readline completer
if readline is not None:
readline.set_completer(None)
del self._readline_matches[:]
if self._shell_ref is not None:
... | def clear_shell(self) | Unbinds the active shell service | 4.929169 | 4.389902 | 1.122843 |
# Exit the loop
with self._lock:
self._stop_event.set()
self._shell_event.clear()
if self._context is not None:
# Unregister from events
self._context.remove_service_listener(self)
# Release the shell
self.clear_s... | def stop(self) | Clears all members | 5.763147 | 5.945883 | 0.969267 |
# pylint: disable=C0103
try:
# Get the request content
data = to_str(request.read_data())
# Dispatch
result = self._marshaled_dispatch(data, self._simple_dispatch)
# Send the result
response.send_content(200, result, "app... | def do_POST(self, request, response) | Handles a HTTP POST request
:param request: The HTTP request bean
:param response: The HTTP response handler | 4.100244 | 4.452324 | 0.920922 |
if not requires_filters or not isinstance(requires_filters, dict):
# No explicit filter configured
return requirements
# We need to change a part of the requirements
new_requirements = {}
for field, requirement in requirements.items():
try:
... | def _prepare_requirements(requirements, requires_filters) | Overrides the filters specified in the decorator with the given ones
:param requirements: Dictionary of requirements (field → Requirement)
:param requires_filters: Content of the 'requires.filter' component
property (field → string)
:return: The new requirements | 4.491693 | 3.968785 | 1.131755 |
# Extract information from the context
requirements = component_context.get_handler(
ipopo_constants.HANDLER_REQUIRES
)
requires_filters = component_context.properties.get(
ipopo_constants.IPOPO_REQUIRES_FILTERS, None
)
# Prepare requirem... | 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.765525 | 5.084244 | 0.937313 |
# Store the stored instance...
self._ipopo_instance = stored_instance
# ... and the bundle context
self._context = stored_instance.bundle_context | def manipulate(self, stored_instance, component_instance) | Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | 11.09504 | 8.181306 | 1.356145 |
self._lock = None
self._ipopo_instance = None
self._context = None
self.requirement = None
self._value = None
self._field = None | def clear(self) | Cleans up the manager. The manager can't be used after this method has
been called | 11.039505 | 10.993656 | 1.00417 |
if (
self._ipopo_instance is None
or not self._ipopo_instance.check_event(event)
):
# stop() and clean() may have been called after we have been put
# inside a listener list copy...
# or we've been told to ignore this event
... | def service_changed(self, event) | Called by the framework when a service event occurs | 5.179352 | 5.043248 | 1.026987 |
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
) | def start(self) | Starts the dependency manager | 24.367905 | 21.189396 | 1.150005 |
self.reference = None
self._pending_ref = None
super(SimpleDependency, self).clear() | def clear(self) | Cleans up the manager. The manager can't be used after this method has
been called | 14.664822 | 16.548037 | 0.886197 |
with self._lock:
if self._value is None:
# Inject the service
self.reference = svc_ref
self._value = self._context.get_service(svc_ref)
self._ipopo_instance.bind(self, self._value, self.reference)
return 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.334745 | 7.65893 | 0.827106 |
with self._lock:
if self.reference is None:
# A previously registered service now matches our filter
self.on_service_arrival(svc_ref)
elif svc_ref is self.reference:
# Notify the property modification
self._ipopo_in... | def on_service_modify(self, svc_ref, old_properties) | Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values | 9.205134 | 11.033264 | 0.834307 |
super(SimpleDependency, self).stop()
if self.reference is not None:
# Return a tuple of tuple
return ((self._value, self.reference),)
return None | def stop(self) | Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None | 12.2234 | 11.224298 | 1.089012 |
return super(SimpleDependency, self).is_valid() or (
self.requirement.immediate_rebind and self._pending_ref is not None
) | def is_valid(self) | Tests if the dependency is in a valid state | 19.572908 | 15.114303 | 1.294992 |
with self._lock:
if self.reference is not None:
# Already bound
return
if self._pending_ref is not None:
# Get the reference we chose to keep this component valid
ref = self._pending_ref
self._pendi... | def try_binding(self) | Searches for the required service if needed
:raise BundleException: Invalid ServiceReference found | 5.635182 | 4.974917 | 1.132719 |
self.services.clear()
self.services = None
self._future_value = None
super(AggregateDependency, self).clear() | def clear(self) | Cleans up the manager. The manager can't be used after this method has
been called | 14.049703 | 14.777168 | 0.950771 |
with self._lock:
if svc_ref not in self.services:
# Get the new service
service = self._context.get_service(svc_ref)
if self._future_value is None:
# First value
self._future_value = []
... | def on_service_arrival(self, svc_ref) | Called when a service has been registered in the framework
:param svc_ref: A service reference | 4.550678 | 5.112885 | 0.890041 |
with self._lock:
try:
# Get the service instance
service = self.services.pop(svc_ref)
except KeyError:
# Not a known service reference: ignore
pass
else:
# Clean the instance values
... | def on_service_departure(self, svc_ref) | Called when a service has been unregistered from the framework
:param svc_ref: A service reference
:return: A tuple (service, reference) if the service has been lost,
else None | 5.823357 | 5.320346 | 1.094545 |
with self._lock:
try:
# Look for the service
service = self.services[svc_ref]
except KeyError:
# A previously registered service now matches our filter
return self.on_service_arrival(svc_ref)
else:
... | def on_service_modify(self, svc_ref, old_properties) | Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
been changed, else None | 7.412531 | 7.25212 | 1.022119 |
super(AggregateDependency, self).stop()
if self.services:
return [
(service, reference)
for reference, service in self.services.items()
]
return None | def stop(self) | Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None | 10.053861 | 7.626681 | 1.318249 |
# Get the logger and log the message
self.__logs.append(entry)
# Notify listeners
for listener in self.__listeners.copy():
try:
listener.logged(entry)
except Exception as ex:
# Create a new log entry, without using logging... | def _store_entry(self, entry) | Stores a new log entry and notifies listeners
:param entry: A LogEntry object | 4.992299 | 4.747936 | 1.051467 |
# pylint: disable=W0212
if not isinstance(reference, pelix.framework.ServiceReference):
# Ensure we have a clean Service Reference
reference = None
if exc_info is not None:
# Format the exception to avoid memory leaks
try:
... | def log(self, level, message, exc_info=None, reference=None) | Logs a message, possibly with an exception
:param level: Severity of the message (Python logging level)
:param message: Human readable message
:param exc_info: The exception context (sys.exc_info()), if any
:param reference: The ServiceReference associated to the log | 3.879491 | 4.027661 | 0.963212 |
try:
# Get the module name
module_object = module_object.__name__
except AttributeError:
# We got a string
pass
return self._framework.get_bundle_by_name(module_object) | def _bundle_from_module(self, module_object) | Find the bundle associated to a module
:param module_object: A Python module object
:return: The Bundle object associated to the module, or None | 5.09959 | 4.97433 | 1.025181 |
# pylint: disable=W0212
# Get the bundle
bundle = self._bundle_from_module(record.module)
# Convert to a LogEntry
entry = LogEntry(
record.levelno, record.getMessage(), None, bundle, None
)
self._reader._store_entry(entry) | def emit(self, record) | Handle a message logged with the logger
:param record: A log record | 5.840797 | 6.579805 | 0.887685 |
# TODO: check (full transmission) success
return self._client.publish(topic, payload, qos, retain) | def publish(self, topic, payload, qos=0, retain=False) | Publishes an MQTT message | 11.871498 | 16.325567 | 0.727172 |
if not requires_filters or not isinstance(requires_filters, dict):
# No explicit filter configured
return configs
# We need to change a part of the requirements
new_requirements = {}
for field, config in configs.items():
# Extract values from... | def _prepare_requirements(configs, requires_filters) | 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)
:return: The new configuration di... | 5.196094 | 4.107142 | 1.265136 |
# Extract information from the context
configs = component_context.get_handler(
ipopo_constants.HANDLER_REQUIRES_MAP
)
requires_filters = component_context.properties.get(
ipopo_constants.IPOPO_REQUIRES_FILTERS, None
)
# Prepare requireme... | 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 | 5.18193 | 5.475157 | 0.946444 |
# Store the stored instance...
self._ipopo_instance = stored_instance
# ... and the bundle context
self._context = stored_instance.bundle_context
# Set the default value for the field: an empty dictionary
setattr(component_instance, self._field, {}) | def manipulate(self, stored_instance, component_instance) | Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | 8.888971 | 7.73668 | 1.148939 |
self.services.clear()
self._future_value.clear()
self.services = None
self._lock = None
self._ipopo_instance = None
self._context = None
self.requirement = None
self._key = None
self._allow_none = None
self._future_value = None
... | def clear(self) | Cleans up the manager. The manager can't be used after this method has
been called | 6.926977 | 6.698055 | 1.034177 |
return (
self.requirement is not None and self.requirement.optional
) or bool(self._future_value) | def is_valid(self) | Tests if the dependency is in a valid state | 17.703888 | 15.943297 | 1.110428 |
self._context.remove_service_listener(self)
if self.services:
return [
(service, reference)
for reference, service in self.services.items()
]
return None | def stop(self) | Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None | 6.972862 | 6.47649 | 1.076642 |
with self._lock:
if self.services:
# We already are alive (not our first call)
# => we are updated through service events
return
# Get all matching services
refs = self._context.get_all_service_references(
... | def try_binding(self) | Searches for the required service if needed
:raise BundleException: Invalid ServiceReference found | 6.860288 | 6.204218 | 1.105746 |
with self._lock:
if svc_ref not in self.services:
# Get the key property
prop_value = svc_ref.get_property(self._key)
if (
prop_value not in self._future_value
and prop_value is not None
... | def on_service_arrival(self, svc_ref) | Called when a service has been registered in the framework
:param svc_ref: A service reference | 5.04032 | 5.530551 | 0.911359 |
self._future_value.setdefault(key, []).append(service) | def __store_service(self, key, service) | Stores the given service in the dictionary
:param key: Dictionary key
:param service: Service to add to the dictionary | 20.652573 | 23.992945 | 0.860777 |
try:
# Remove the injected service
prop_services = self._future_value[key]
prop_services.remove(service)
# Clean up
if not prop_services:
del self._future_value[key]
except KeyError:
# Ignore: can occur wh... | def __remove_service(self, key, service) | Removes the given service from the future dictionary
:param key: Dictionary key
:param service: Service to remove from the dictionary | 7.138587 | 7.297588 | 0.978212 |
with self._lock:
# The value field must be a deep copy of our dictionary
if self._future_value is not None:
return {
key: value[:] for key, value in self._future_value.items()
}
return None | def get_value(self) | Retrieves the value to inject in the component
:return: The value to inject | 7.303048 | 7.77954 | 0.938751 |
with self._lock:
if svc_ref in self.services:
# Get the service instance
service = self.services.pop(svc_ref)
# Get the key property
prop_value = svc_ref.get_property(self._key)
# Remove the injected service
... | def on_service_departure(self, svc_ref) | Called when a service has been unregistered from the framework
:param svc_ref: A service reference
:return: A tuple (service, reference) if the service has been lost,
else None | 5.372447 | 4.83989 | 1.110035 |
with self._lock:
if svc_ref not in self.services:
# A previously registered service now matches our filter
return self.on_service_arrival(svc_ref)
else:
# Get the property values
service = self.services[svc_ref]
... | def on_service_modify(self, svc_ref, old_properties) | Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
been changed, else None | 3.582197 | 3.557912 | 1.006826 |
# type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool
with self.__lock:
our_sr = self.get_reference()
if our_sr is None:
return False
sr_compare = our_sr == svc_ref
if cid is None:
return sr_compare
... | def match_sr(self, svc_ref, cid=None) | Checks if this export registration matches the given service reference
:param svc_ref: A service reference
:param cid: A container ID
:return: True if the service matches this export registration | 3.509216 | 3.769054 | 0.93106 |
# type: () -> Optional[Tuple[Any, Any, Any]]
with self.__lock:
return (
self.__updateexception
if self.__updateexception or self.__closed
else self.__exportref.get_exception()
) | def get_exception(self) | Returns the exception associated to the export
:return: An exception tuple, if any | 9.003948 | 9.44818 | 0.952982 |
publish = False
exporterid = rsid = exception = export_ref = ed = None
with self.__lock:
if not self.__closed:
exporterid = self.__exportref.get_export_container_id()
export_ref = self.__exportref
rsid = self.__exportref.get_re... | def close(self) | Cleans up the export endpoint | 5.469794 | 5.121827 | 1.067938 |
endpoint_id = endpoint_description.get_id()
with self._published_endpoints_lock:
if self.get_advertised_endpoint(endpoint_id) is not None:
return False
advertise_result = self._advertise(endpoint_description)
if advertise_result:
... | def advertise_endpoint(self, endpoint_description) | Advertise and endpoint_description for remote discovery.
If it hasn't already been a endpoint_description will be advertised via
a some protocol.
:param endpoint_description: an instance of EndpointDescription to
advertise. Must not be None.
:return: True if advertised, False if... | 3.042752 | 3.083416 | 0.986812 |
endpoint_id = updated_ed.get_id()
with self._published_endpoints_lock:
if self.get_advertised_endpoint(endpoint_id) is None:
return False
advertise_result = self._update(updated_ed)
if advertise_result:
self._remove_advertised... | def update_endpoint(self, updated_ed) | Update a previously advertised endpoint_description.
:param endpoint_description: an instance of EndpointDescription to
update. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised) | 3.489114 | 3.181283 | 1.096763 |
with self._published_endpoints_lock:
with self._published_endpoints_lock:
advertised = self.get_advertised_endpoint(endpointid)
if not advertised:
return None
unadvertise_result = self._unadvertise(advertised)
... | def unadvertise_endpoint(self, endpointid) | Unadvertise a previously-advertised endpointid (string).
:param endpointid. The string returned from ed.get_id() or
the value of property endpoint.id. Should not be None
:return True if removed, False if not removed (hasn't been previously advertised
by this advertiser | 3.380035 | 3.878921 | 0.871386 |
# Retrieve the handler configuration
provides = component_context.get_handler(
ipopo_constants.HANDLER_PROVIDES
)
if not provides:
# Nothing to do
return ()
# 1 handler per provided service
return [
ServiceRegistra... | 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 | 8.957621 | 9.038808 | 0.991018 |
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
return stored_instance.get_controller_state(name)
def set_value(self, name, new_value):
# p... | def _field_controller_generator(self) | Generates the methods called by the injected controller | 3.231894 | 3.159901 | 1.022783 |
# Store the stored instance
self._ipopo_instance = stored_instance
if self.__controller is None:
# No controller: do nothing
return
# Get the current value of the member (True by default)
controller_value = getattr(component_instance, self.__con... | def manipulate(self, stored_instance, component_instance) | Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | 3.464039 | 3.325491 | 1.041662 |
if self.__controller != name:
# Nothing to do
return
# Update the controller value
self.__controller_on = value
if value:
# Controller switched to "ON"
self._register_service()
else:
# Controller switched to "O... | def on_controller_change(self, name, value) | Called by the instance manager when a controller value has been
modified
:param name: The name of the controller
:param value: The new value of the controller | 5.018259 | 6.279949 | 0.799092 |
if self._registration is not None:
# use the registration to trigger the service event
self._registration.set_properties({name: new_value}) | def on_property_change(self, name, old_value, new_value) | Called by the instance manager when a component property is modified
:param name: The changed property name
:param old_value: The previous property value
:param new_value: The new property value | 7.678299 | 9.743699 | 0.788027 |
if (
self._registration is None
and self.specifications
and self.__validated
and self.__controller_on
):
# Use a copy of component properties
properties = self._ipopo_instance.context.properties.copy()
bundle_co... | def _register_service(self) | Registers the provided service, if possible | 5.180144 | 4.963804 | 1.043584 |
if self._registration is not None:
# Ignore error
try:
self._registration.unregister()
except BundleException as ex:
# Only log the error at this level
logger = logging.getLogger(
"-".join((self._ipo... | def _unregister_service(self) | Unregisters the provided service, if needed | 5.161572 | 4.955027 | 1.041684 |
if svc_reference is None:
raise TypeError("Invalid ServiceReference")
try:
# Give the service
yield bundle_context.get_service(svc_reference)
finally:
try:
# Release it
bundle_context.unget_service(svc_reference)
except pelix.constants.Bu... | def use_service(bundle_context, svc_reference) | Utility context to safely use a service in a "with" block.
It looks after the the given service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:param svc_reference: The reference of the service to use
:return: The requested service
:raise ... | 3.427308 | 3.923028 | 0.873638 |
# pylint: disable=C1801
# Filter the names (remove empty ones)
locks_attr_names = [
lock_name for lock_name in locks_attr_names if lock_name
]
if not locks_attr_names:
raise ValueError("The lock names list can't be empty")
if "sorted" not in kwargs or kwargs["sorted"]:
... | def SynchronizedClassMethod(*locks_attr_names, **kwargs) | A synchronizer decorator for class methods. An AttributeError can be raised
at runtime if the given lock attribute doesn't exist or if it is None.
If a parameter ``sorted`` is found in ``kwargs`` and its value is True,
then the list of locks names will be sorted before locking.
:param locks_attr_names... | 3.301362 | 3.262717 | 1.011844 |
if lock is None:
# Don't do useless tests
return False
for attr in "acquire", "release", "__enter__", "__exit__":
if not hasattr(lock, attr):
# Missing something
return False
# Same API as a lock
return True | def is_lock(lock) | Tests if the given lock is an instance of a lock class | 7.339797 | 7.227567 | 1.015528 |
if items is None:
return items
new_list = []
for item in items:
if item not in new_list:
new_list.append(item)
return new_list | def remove_duplicates(items) | Returns a list without duplicates, keeping elements order
:param items: A list of items
:return: The list without duplicates, in the same order | 2.135204 | 2.328864 | 0.916844 |
if listener is None or listener in registry:
return False
registry.append(listener)
return True | def add_listener(registry, listener) | Adds a listener in the registry, if it is not yet in
:param registry: A registry (a list)
:param listener: The listener to register
:return: True if the listener has been added | 4.630804 | 5.97716 | 0.77475 |
if listener is not None and listener in registry:
registry.remove(listener)
return True
return False | def remove_listener(registry, listener) | Removes a listener from the registry
:param registry: A registry (a list)
:param listener: The listener to remove
:return: True if the listener was in the list | 3.907562 | 5.746304 | 0.680013 |
if value is None:
# None given
if allow_none:
return None
return []
elif isinstance(value, (list, tuple, set, frozenset)):
# Iterable given, return it as-is
return value
# Return a one-value list
return [value] | def to_iterable(value, allow_none=True) | Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns None if value is None, else
it... | 3.886333 | 5.027776 | 0.772973 |
if not self.__already_logged:
# Print only if not already done
stack = "\n\t".join(traceback.format_stack())
logging.getLogger(self.__logger).warning(
"%s: %s\n%s", method_name, self.__message, stack
)
self.__already_logged = ... | def __log(self, method_name) | Logs the deprecation message on first call, does nothing after
:param method_name: Name of the deprecated method | 4.467266 | 4.981277 | 0.896811 |
# type: () -> bool
with self.__lock:
self.__value -= 1
if self.__value == 0:
# All done
self.__event.set()
return True
elif self.__value < 0:
# Gone too far
raise ValueError("The ... | def step(self) | Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0 | 5.0242 | 4.552052 | 1.103722 |
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# Prepare a line pattern for each match
match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)
# Sort matching IDs
matches = sorted(int(match) for match in matches)
# Print the match and ... | def display_hook(prompt, session, context, matches, longest_match_len) | Displays the available bundle matches and the bundle name
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Length of... | 4.688455 | 5.138512 | 0.912415 |
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of bundle IDs (strings) matching the current value
... | def complete(
self, config, prompt, session, context, current_arguments, current
) | Returns the list of bundle IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_arg... | 5.917331 | 6.01532 | 0.98371 |
# type: (str, ShellSession, BundleContext, List[str], int) -> None
try:
# Prepare a line pattern for each match
match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)
# Sort matching IDs
matches = sorted(int(match) for match in matches)
... | def display_hook(prompt, session, context, matches, longest_match_len) | Displays the available services matches and the service details
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Len... | 4.681937 | 4.857542 | 0.963849 |
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of bundle IDs (strings) matching the current value
... | def complete(
self, config, prompt, session, context, current_arguments, current
) | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... | 5.757986 | 5.996981 | 0.960147 |
return self._get_or_create_container(
exported_configs, service_intents, export_props
) | def supports_export(self, exported_configs, service_intents, export_props) | Method called by rsa.export_service to ask if this
ExportDistributionProvider supports export for given
exported_configs (list), service_intents (list), and
export_props (dict).
If a ExportContainer instance is returned then it is used to export
the service. If None is returned... | 5.504657 | 2.631171 | 2.092094 |
return self._get_or_create_container(
exported_configs, service_intents, endpoint_props
) | def supports_import(
self, exported_configs, service_intents, endpoint_props
) | Method called by rsa.export_service to ask if this
ImportDistributionProvider supports import for given
exported_configs (list), service_intents (list), and
export_props (dict).
If a ImportContainer instance is returned then it is used to import
the service. If None is returned... | 5.874161 | 2.295377 | 2.559127 |
# type: () -> bool
assert self._bundle_context
assert self._container_props is not None
assert self._get_distribution_provider()
assert self.get_config_name()
assert self.get_namespace()
return True | def is_valid(self) | Checks if the component is valid
:return: Always True if it doesn't raise an exception
:raises AssertionError: Invalid properties | 8.599449 | 11.27264 | 0.76286 |
# type: (BundleContext, Dict[str, Any]) -> None
self._bundle_context = bundle_context
self._container_props = container_props
self.is_valid() | def _validate_component(self, bundle_context, container_props) | Component validated
:param bundle_context: Bundle context
:param container_props: Instance properties
:raises AssertionError: Invalid properties | 3.415376 | 4.213621 | 0.810556 |
# type: (str, Tuple[Any, EndpointDescription]) -> None
with self._exported_instances_lock:
self._exported_services[ed_id] = inst | def _add_export(self, ed_id, inst) | Keeps track of an exported service
:param ed_id: ID of the endpoint description
:param inst: A tuple: (service instance, endpoint description) | 7.045197 | 6.086895 | 1.157437 |
# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
with self._exported_instances_lock:
for val in self._exported_services.values():
if func(val):
return val
return None | def _find_export(self, func) | Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service instance and endpoint description.
:param func: A function to look for the excepted export
:return: The found tuple or None | 5.661911 | 6.023246 | 0.94001 |
# type: (Any, EndpointDescription) -> None
self._add_export(ed.get_id(), (svc, ed)) | def _export_service(self, svc, ed) | Registers a service export
:param svc: Service instance
:param ed: Endpoint description | 9.013359 | 10.600035 | 0.850314 |
# type: (List[str], ServiceReference, Dict[str, Any]) -> Dict[str, Any]
pkg_vers = rsa.get_package_versions(intfs, export_props)
exported_configs = get_string_plus_property_value(
svc_ref.get_property(SERVICE_EXPORTED_CONFIGS)
)
if not exported_configs:
... | def prepare_endpoint_props(self, intfs, svc_ref, export_props) | Sets up the properties of an endpoint
:param intfs: Specifications to export
:param svc_ref: Reference of the exported service
:param export_props: Export properties
:return: The properties of the endpoint | 2.729606 | 2.995277 | 0.911304 |
# type: (ServiceReference, Dict[str, Any]) -> EndpointDescription
ed = EndpointDescription.fromprops(export_props)
self._export_service(
self._get_bundle_context().get_service(svc_ref), ed
)
return ed | def export_service(self, svc_ref, export_props) | Exports the given service
:param svc_ref: Reference to the service to export
:param export_props: Export properties
:return: The endpoint description | 4.881235 | 7.138043 | 0.683834 |
# Prepare arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.xmpp",
parents=[make_common_parser()],
description="Pelix XMPP Shell",
)
group = parser.add_argument_group("XMPP options")
group.add_argument("-j", "--jid", dest="jid", help="Jabber ID")
group.a... | def main(argv=None) | Entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None | 2.468724 | 2.486563 | 0.992826 |
# Flush buffer
content = self._buffer.getvalue()
self._buffer = StringIO()
if content:
# Send message
self._client.send_message(self._target, content, mtype="chat") | def flush(self) | Sends buffered data to the target | 5.58314 | 5.79153 | 0.964018 |
# type: (Any, ServiceRegistration) -> Any
svc_ref = svc_registration.get_reference()
try:
# Use the existing service
service, counter = self.__factored[svc_ref]
counter.inc()
except KeyError:
# Create the service
servic... | def _get_from_factory(self, factory, svc_registration) | Returns a service instance from a Prototype Service Factory
:param factory: The prototype service factory
:param svc_registration: The ServiceRegistration object
:return: The requested service instance returned by the factory | 4.030685 | 5.07743 | 0.793844 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.