_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q9400
Bot.transmit
train
def transmit(self, channel, message): """ Send the message to Slack. :param channel: channel or user to whom the message should be sent. If a ``thread`` attribute is present, that thread ID is used. :param str message: message to send. """ target = ( self.slack.server.channels.find(channel) or self._find_user_channel(username=channel) ) message = self._expand_references(message) target.send_message(message, thread=getattr(channel, 'thread', None))
python
{ "resource": "" }
q9401
splitem
train
def splitem(query): """ Split a query into choices >>> splitem('dog, cat') ['dog', 'cat'] Disregards trailing punctuation. >>> splitem('dogs, cats???') ['dogs', 'cats'] >>> splitem('cats!!!') ['cats'] Allow or >>> splitem('dogs, cats or prarie dogs?') ['dogs', 'cats', 'prarie dogs'] Honors serial commas >>> splitem('dogs, cats, or prarie dogs?') ['dogs', 'cats', 'prarie dogs'] Allow choices to be prefixed by some ignored prompt. >>> splitem('stuff: a, b, c') ['a', 'b', 'c'] """ prompt, sep, query = query.rstrip('?.!').rpartition(':') choices = query.split(',') choices[-1:] = choices[-1].split(' or ') return [choice.strip() for choice in choices if choice.strip()]
python
{ "resource": "" }
q9402
urban_lookup
train
def urban_lookup(word): ''' Return a Urban Dictionary definition for a word or None if no result was found. ''' url = "http://api.urbandictionary.com/v0/define" params = dict(term=word) resp = requests.get(url, params=params) resp.raise_for_status() res = resp.json() if not res['list']: return return res['list'][0]['definition']
python
{ "resource": "" }
q9403
passagg
train
def passagg(recipient, sender): """ Generate a passive-aggressive statement to recipient from sender. """ adj = random.choice(pmxbot.phrases.adjs) if random.choice([False, True]): # address the recipient last lead = "" trail = recipient if not recipient else ", %s" % recipient else: # address the recipient first lead = recipient if not recipient else "%s, " % recipient trail = "" body = random.choice(pmxbot.phrases.adj_intros) % adj if not lead: body = body.capitalize() msg = "{lead}{body}{trail}.".format(**locals()) fw = random.choice(pmxbot.phrases.farewells) return "{msg} {fw}, {sender}.".format(**locals())
python
{ "resource": "" }
q9404
config
train
def config(client, event, channel, nick, rest): "Change the running config, something like a=b or a+=b or a-=b" pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$') match = pattern.match(rest) if not match: return "Command not recognized" res = match.groupdict() key = res['key'] op = res['op'] value = yaml.safe_load(res['value']) if op in ('+=', '-='): # list operation op_name = {'+=': 'append', '-=': 'remove'}[op] op_name if key not in pmxbot.config: msg = "{key} not found in config. Can't {op_name}." return msg.format(**locals()) if not isinstance(pmxbot.config[key], (list, tuple)): msg = "{key} is not list or tuple. Can't {op_name}." return msg.format(**locals()) op = getattr(pmxbot.config[key], op_name) op(value) else: # op is '=' pmxbot.config[key] = value
python
{ "resource": "" }
q9405
trap_exceptions
train
def trap_exceptions(results, handler, exceptions=Exception): """ Iterate through the results, but if an exception occurs, stop processing the results and instead replace the results with the output from the exception handler. """ try: for result in results: yield result except exceptions as exc: for result in always_iterable(handler(exc)): yield result
python
{ "resource": "" }
q9406
MongoDBQuotes.delete
train
def delete(self, lookup): """ If exactly one quote matches, delete it. Otherwise, raise a ValueError. """ lookup, num = self.split_num(lookup) if num: result = self.find_matches(lookup)[num - 1] else: result, = self.find_matches(lookup) self.db.delete_one(result)
python
{ "resource": "" }
q9407
LoggingCommandBot._get_wrapper
train
def _get_wrapper(): """ Get a socket wrapper based on SSL config. """ if not pmxbot.config.get('use_ssl', False): return lambda x: x return importlib.import_module('ssl').wrap_socket
python
{ "resource": "" }
q9408
Response.getStatusCode
train
def getStatusCode(self): """ Returns the code of the status or None if it does not exist :return: Status code of the response """ if 'status' in self._response.keys(): if (self._response['status'] is not None) and ('code' in self._response['status'].keys()) and (self._response['status']['code'] is not None): return self._response['status']['code'] else: return None else: return None
python
{ "resource": "" }
q9409
Response.getStatusMsg
train
def getStatusMsg(self): """ Returns the message of the status or an empty string if it does not exist :return: Status message of the response """ if 'status' in self._response.keys(): if (self._response['status'] is not None) and ('msg' in self._response['status'].keys()) and (self._response['status']['msg'] is not None): return self._response['status']['msg'] else: return ''
python
{ "resource": "" }
q9410
Response.getConsumedCredits
train
def getConsumedCredits(self): """ Returns the credit consumed by the request made :return: String with the number of credits consumed """ if 'status' in self._response.keys(): if (self._response['status'] is not None) and ('credits' in self._response['status'].keys()): if self._response['status']['credits'] is not None: return self._response['status']['credits'] else: return '0' else: print("Not credits field\n") else: return None
python
{ "resource": "" }
q9411
Response.getRemainingCredits
train
def getRemainingCredits(self): """ Returns the remaining credits for the license key used after the request was made :return: String with remaining credits """ if 'status' in self._response.keys(): if (self._response['status'] is not None) and ('remaining_credits' in self._response['status'].keys()): if self._response['status']['remaining_credits'] is not None: return self._response['status']['remaining_credits'] else: return '' else: print("Not remaining credits field\n") else: return None
python
{ "resource": "" }
q9412
Response.getResults
train
def getResults(self): """ Returns the results from the API without the status of the request :return: Dictionary with the results """ results = self._response.copy() if 'status' in self._response.keys(): if results['status'] is not None: del results['status'] return results else: return None
python
{ "resource": "" }
q9413
PoliceAPI.get_forces
train
def get_forces(self): """ Get a list of all police forces. Uses the forces_ API call. .. _forces: https://data.police.uk/docs/method/forces/ :rtype: list :return: A list of :class:`forces.Force` objects (one for each police force represented in the API) """ forces = [] for f in self.service.request('GET', 'forces'): forces.append(Force(self, id=f['id'], name=f['name'])) return forces
python
{ "resource": "" }
q9414
PoliceAPI.get_neighbourhoods
train
def get_neighbourhoods(self, force): """ Get a list of all neighbourhoods for a force. Uses the neighbourhoods_ API call. .. _neighbourhoods: https://data.police.uk/docs/method/neighbourhoods/ :param force: The force to get neighbourhoods for (either by ID or :class:`forces.Force` object) :type force: str or :class:`forces.Force` :rtype: list :return: A ``list`` of :class:`neighbourhoods.Neighbourhood` objects (one for each Neighbourhood Policing Team in the given force). """ if not isinstance(force, Force): force = Force(self, id=force) neighbourhoods = [] for n in self.service.request('GET', '%s/neighbourhoods' % force.id): neighbourhoods.append( Neighbourhood(self, force=force, id=n['id'], name=n['name'])) return sorted(neighbourhoods, key=lambda n: n.name)
python
{ "resource": "" }
q9415
PoliceAPI.get_neighbourhood
train
def get_neighbourhood(self, force, id, **attrs): """ Get a specific neighbourhood. Uses the neighbourhood_ API call. .. _neighbourhood: https://data.police.uk/docs/method/neighbourhood/ :param force: The force within which the neighbourhood resides (either by ID or :class:`forces.Force` object) :type force: str or Force :param str neighbourhood: The ID of the neighbourhood to fetch. :rtype: Neighbourhood :return: The Neighbourhood object for the given force/ID. """ if not isinstance(force, Force): force = Force(self, id=force, **attrs) return Neighbourhood(self, force=force, id=id, **attrs)
python
{ "resource": "" }
q9416
PoliceAPI.locate_neighbourhood
train
def locate_neighbourhood(self, lat, lng): """ Find a neighbourhood by location. Uses the locate-neighbourhood_ API call. .. _locate-neighbourhood: https://data.police.uk/docs/method/neighbourhood-locate/ :param lat: The latitude of the location. :type lat: float or str :param lng: The longitude of the location. :type lng: float or str :rtype: Neighbourhood or None :return: The Neighbourhood object representing the Neighbourhood Policing Team responsible for the given location. """ method = 'locate-neighbourhood' q = '%s,%s' % (lat, lng) try: result = self.service.request('GET', method, q=q) return self.get_neighbourhood(result['force'], result['neighbourhood']) except APIError: pass
python
{ "resource": "" }
q9417
PoliceAPI.get_crime_categories
train
def get_crime_categories(self, date=None): """ Get a list of crime categories, valid for a particular date. Uses the crime-categories_ API call. .. _crime-categories: https://data.police.uk/docs/method/crime-categories/ :rtype: list :param date: The date of the crime categories to get. :type date: str or None :return: A ``list`` of crime categories which are valid at the specified date (or at the latest date, if ``None``). """ return sorted(self._get_crime_categories(date=date).values(), key=lambda c: c.name)
python
{ "resource": "" }
q9418
PoliceAPI.get_crime_category
train
def get_crime_category(self, id, date=None): """ Get a particular crime category by ID, valid at a particular date. Uses the crime-categories_ API call. :rtype: CrimeCategory :param str id: The ID of the crime category to get. :param date: The date that the given crime category is valid for (the latest date is used if ``None``). :type date: str or None :return: A crime category with the given ID which is valid for the specified date (or at the latest date, if ``None``). """ try: return self._get_crime_categories(date=date)[id] except KeyError: raise InvalidCategoryException( 'Category %s not found for %s' % (id, date))
python
{ "resource": "" }
q9419
PoliceAPI.get_crime
train
def get_crime(self, persistent_id): """ Get a particular crime by persistent ID. Uses the outcomes-for-crime_ API call. .. _outcomes-for-crime: https://data.police.uk/docs/method/outcomes-for-crime/ :rtype: Crime :param str persistent_id: The persistent ID of the crime to get. :return: The ``Crime`` with the given persistent ID. """ method = 'outcomes-for-crime/%s' % persistent_id response = self.service.request('GET', method) crime = Crime(self, data=response['crime']) crime._outcomes = [] outcomes = response['outcomes'] if outcomes is not None: for o in outcomes: o.update({ 'crime': crime, }) crime._outcomes.append(crime.Outcome(self, o)) return crime
python
{ "resource": "" }
q9420
PoliceAPI.get_crimes_point
train
def get_crimes_point(self, lat, lng, date=None, category=None): """ Get crimes within a 1-mile radius of a location. Uses the crime-street_ API call. .. _crime-street: https//data.police.uk/docs/method/crime-street/ :rtype: list :param lat: The latitude of the location. :type lat: float or str :param lng: The longitude of the location. :type lng: float or str :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either by ID or CrimeCategory object) :type category: str or CrimeCategory :return: A ``list`` of crimes which were reported within 1 mile of the specified location, in the given month (optionally filtered by category). """ if isinstance(category, CrimeCategory): category = category.id method = 'crimes-street/%s' % (category or 'all-crime') kwargs = { 'lat': lat, 'lng': lng, } crimes = [] if date is not None: kwargs['date'] = date for c in self.service.request('GET', method, **kwargs): crimes.append(Crime(self, data=c)) return crimes
python
{ "resource": "" }
q9421
PoliceAPI.get_crimes_area
train
def get_crimes_area(self, points, date=None, category=None): """ Get crimes within a custom area. Uses the crime-street_ API call. .. _crime-street: https//data.police.uk/docs/method/crime-street/ :rtype: list :param list points: A ``list`` of ``(lat, lng)`` tuples. :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either by ID or CrimeCategory object) :type category: str or CrimeCategory :return: A ``list`` of crimes which were reported within the specified boundary, in the given month (optionally filtered by category). """ if isinstance(category, CrimeCategory): category = category.id method = 'crimes-street/%s' % (category or 'all-crime') kwargs = { 'poly': encode_polygon(points), } crimes = [] if date is not None: kwargs['date'] = date for c in self.service.request('POST', method, **kwargs): crimes.append(Crime(self, data=c)) return crimes
python
{ "resource": "" }
q9422
PoliceAPI.get_crimes_location
train
def get_crimes_location(self, location_id, date=None): """ Get crimes at a particular snap-point location. Uses the crimes-at-location_ API call. .. _crimes-at-location: https://data.police.uk/docs/method/crimes-at-location/ :rtype: list :param int location_id: The ID of the location to get crimes for. :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :return: A ``list`` of :class:`Crime` objects which were snapped to the :class:`Location` with the specified ID in the given month. """ kwargs = { 'location_id': location_id, } crimes = [] if date is not None: kwargs['date'] = date for c in self.service.request('GET', 'crimes-at-location', **kwargs): crimes.append(Crime(self, data=c)) return crimes
python
{ "resource": "" }
q9423
PoliceAPI.get_crimes_no_location
train
def get_crimes_no_location(self, force, date=None, category=None): """ Get crimes with no location for a force. Uses the crimes-no-location_ API call. .. _crimes-no-location: https://data.police.uk/docs/method/crimes-no-location/ :rtype: list :param force: The force to get no-location crimes for. :type force: str or Force :param date: The month in which the crimes were reported in the format ``YYYY-MM`` (the latest date is used if ``None``). :type date: str or None :param category: The category of the crimes to filter by (either by ID or CrimeCategory object) :type category: str or CrimeCategory :return: A ``list`` of :class:`crime.NoLocationCrime` objects which were reported in the given month, by the specified force, but which don't have a location. """ if not isinstance(force, Force): force = Force(self, id=force) if isinstance(category, CrimeCategory): category = category.id kwargs = { 'force': force.id, 'category': category or 'all-crime', } crimes = [] if date is not None: kwargs['date'] = date for c in self.service.request('GET', 'crimes-no-location', **kwargs): crimes.append(NoLocationCrime(self, data=c)) return crimes
python
{ "resource": "" }
q9424
_retrocom
train
def _retrocom(rx, tx, game, kwargs): """ This function is the target for RetroWrapper's internal process and does all the work of communicating with the environment. """ env = RetroWrapper.retro_make_func(game, **kwargs) # Sit around on the queue, waiting for calls from RetroWrapper while True: attr, args, kwargs = rx.get() # First, handle special case where the wrapper is asking if attr is callable. # In this case, we actually have RetroWrapper.symbol, attr, and {}. if attr == RetroWrapper.symbol: result = env.__getattribute__(args) tx.put(callable(result)) elif attr == "close": env.close() break else: # Otherwise, handle the request result = getattr(env, attr) if callable(result): result = result(*args, **kwargs) tx.put(result)
python
{ "resource": "" }
q9425
RetroWrapper._ask_if_attr_is_callable
train
def _ask_if_attr_is_callable(self, attr): """ Returns whether or not the attribute is a callable. """ self._tx.put((RetroWrapper.symbol, attr, {})) return self._rx.get()
python
{ "resource": "" }
q9426
RetroWrapper.close
train
def close(self): """ Shutdown the environment. """ if "_tx" in self.__dict__ and "_proc" in self.__dict__: self._tx.put(("close", (), {})) self._proc.join()
python
{ "resource": "" }
q9427
Request.addParam
train
def addParam(self, paramName, paramValue): """ Add a parameter to the request :param paramName: Name of the parameter :param paramValue: Value of the parameter """ if not paramName: raise ValueError('paramName cannot be empty') self._params[paramName] = paramValue
python
{ "resource": "" }
q9428
Request.setContent
train
def setContent(self, type_, value): """ Sets the content that's going to be sent to analyze according to its type :param type_: Type of the content (text, file or url) :param value: Value of the content """ if type_ in [self.CONTENT_TYPE_TXT, self.CONTENT_TYPE_URL, self.CONTENT_TYPE_FILE]: if type_ == self.CONTENT_TYPE_FILE: self._file = {} self._file = {'doc': open(value, 'rb')} else: self.addParam(type_, value)
python
{ "resource": "" }
q9429
Request.sendRequest
train
def sendRequest(self, extraHeaders=""): """ Sends a request to the URL specified and returns a response only if the HTTP code returned is OK :param extraHeaders: Allows to configure additional headers in the request :return: Response object set to None if there is an error """ self.addParam('src', 'mc-python') params = urlencode(self._params) url = self._url if 'doc' in self._file.keys(): headers = {} if (extraHeaders is not None) and (extraHeaders is dict): headers = headers.update(extraHeaders) result = requests.post(url=url, data=self._params, files=self._file, headers=headers) result.encoding = 'utf-8' return result else: headers = {'Content-Type': 'application/x-www-form-urlencoded'} if (extraHeaders is not None) and (extraHeaders is dict): headers = headers.update(extraHeaders) result = requests.request("POST", url=url, data=params, headers=headers) result.encoding = 'utf-8' return result
python
{ "resource": "" }
q9430
ParserResponse.getLemmatization
train
def getLemmatization(self, fullPOSTag=False): """ This function obtains the lemmas and PoS for the text sent :param fullPOSTag: Set to true to obtain the complete PoS tag :return: Dictionary of tokens from the syntactic tree with their lemmas and PoS """ leaves = self._getTreeLeaves() lemmas = {} for leaf in leaves: analyses = [] if 'analysis_list' in leaf.keys(): for analysis in leaf['analysis_list']: analyses.append({ 'lemma': analysis['lemma'], 'pos': analysis['tag'] if fullPOSTag else analysis['tag'][:2] }) lemmas[leaf['form']] = analyses return lemmas
python
{ "resource": "" }
q9431
TopicsResponse.getTypeLastNode
train
def getTypeLastNode(self, type_): """ Obtains the last node or leaf of the type specified :param type_: Type we want to analize (sementity, semtheme) :return: Last node of the type """ lastNode = "" if type_ and (type(type_) is not list) and (type(type_) is not dict): aType = type_.split('>') lastNode = aType[len(aType) - 1] return lastNode
python
{ "resource": "" }
q9432
ZooKeeperClient.__conn_listener
train
def __conn_listener(self, state): """ Connection event listener :param state: The new connection state """ if state == KazooState.CONNECTED: self.__online = True if not self.__connected: self.__connected = True self._logger.info("Connected to ZooKeeper") self._queue.enqueue(self.on_first_connection) else: self._logger.warning("Re-connected to ZooKeeper") self._queue.enqueue(self.on_client_reconnection) elif state == KazooState.SUSPENDED: self._logger.warning("Connection suspended") self.__online = False elif state == KazooState.LOST: self.__online = False self.__connected = False if self.__stop: self._logger.info("Disconnected from ZooKeeper (requested)") else: self._logger.warning("Connection lost")
python
{ "resource": "" }
q9433
ZooKeeperClient.start
train
def start(self): """ Starts the connection """ self.__stop = False self._queue.start() self._zk.start()
python
{ "resource": "" }
q9434
ZooKeeperClient.stop
train
def stop(self): """ Stops the connection """ self.__stop = True self._queue.stop() self._zk.stop()
python
{ "resource": "" }
q9435
ZooKeeperClient.__path
train
def __path(self, path): """ Adds the prefix to the given path :param path: Z-Path :return: Prefixed Z-Path """ if path.startswith(self.__prefix): return path return "{}{}".format(self.__prefix, path)
python
{ "resource": "" }
q9436
ZooKeeperClient.create
train
def create(self, path, data, ephemeral=False, sequence=False): """ Creates a ZooKeeper node :param path: Z-Path :param data: Node Content :param ephemeral: Ephemeral flag :param sequence: Sequential flag """ return self._zk.create( self.__path(path), data, ephemeral=ephemeral, sequence=sequence )
python
{ "resource": "" }
q9437
ZooKeeperClient.get
train
def get(self, path, watch=None): """ Gets the content of a ZooKeeper node :param path: Z-Path :param watch: Watch method """ return self._zk.get(self.__path(path), watch=watch)
python
{ "resource": "" }
q9438
ZooKeeperClient.get_children
train
def get_children(self, path, watch=None): """ Gets the list of children of a node :param path: Z-Path :param watch: Watch method """ return self._zk.get_children(self.__path(path), watch=watch)
python
{ "resource": "" }
q9439
ZooKeeperClient.set
train
def set(self, path, data): """ Sets the content of a ZooKeeper node :param path: Z-Path :param data: New content """ return self._zk.set(self.__path(path), data)
python
{ "resource": "" }
q9440
get_ipopo_svc_ref
train
def get_ipopo_svc_ref(bundle_context): # type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]] """ Retrieves a tuple containing the service reference to iPOPO and the service itself :param bundle_context: The calling bundle context :return: The reference to the iPOPO service and the service itself, None if not available """ # Look after the service ref = bundle_context.get_service_reference(SERVICE_IPOPO) if ref is None: return None try: # Get it svc = bundle_context.get_service(ref) except BundleException: # Service reference has been invalidated return None # Return both the reference (to call unget_service()) and the service return ref, svc
python
{ "resource": "" }
q9441
use_ipopo
train
def use_ipopo(bundle_context): # type: (BundleContext) -> Any """ Utility context to use the iPOPO service safely in a "with" block. It looks after the the iPOPO service and releases its reference when exiting the context. :param bundle_context: The calling bundle context :return: The iPOPO service :raise BundleException: Service not found """ # Get the service and its reference ref_svc = get_ipopo_svc_ref(bundle_context) if ref_svc is None: raise BundleException("No iPOPO service available") try: # Give the service yield ref_svc[1] finally: try: # Release it bundle_context.unget_service(ref_svc[0]) except BundleException: # Service might have already been unregistered pass
python
{ "resource": "" }
q9442
use_waiting_list
train
def use_waiting_list(bundle_context): # type: (BundleContext) -> Any """ Utility context to use the iPOPO waiting list safely in a "with" block. It looks after the the iPOPO waiting list service and releases its reference when exiting the context. :param bundle_context: The calling bundle context :return: The iPOPO waiting list service :raise BundleException: Service not found """ # Get the service and its reference ref = bundle_context.get_service_reference(SERVICE_IPOPO_WAITING_LIST) if ref is None: raise BundleException("No iPOPO waiting list service available") try: # Give the service yield bundle_context.get_service(ref) finally: try: # Release it bundle_context.unget_service(ref) except BundleException: # Service might have already been unregistered pass
python
{ "resource": "" }
q9443
_is_builtin
train
def _is_builtin(obj): """ Checks if the type of the given object is a built-in one or not :param obj: An object :return: True if the object is of a built-in type """ module_ = inspect.getmodule(obj) if module_ in (None, builtins): return True return module_.__name__ in ("", "__main__")
python
{ "resource": "" }
q9444
to_jabsorb
train
def to_jabsorb(value): """ Adds information for Jabsorb, if needed. Converts maps and lists to a jabsorb form. Keeps tuples as is, to let them be considered as arrays. :param value: A Python result to send to Jabsorb :return: The result in a Jabsorb map format (not a JSON object) """ # None ? if value is None: return None # Map ? elif isinstance(value, dict): if JAVA_CLASS in value or JSON_CLASS in value: if not _is_converted_class(value.get(JAVA_CLASS)): # Bean representation converted_result = {} for key, content in value.items(): converted_result[key] = to_jabsorb(content) try: # Keep the raw jsonrpclib information converted_result[JSON_CLASS] = value[JSON_CLASS] except KeyError: pass else: # We already worked on this value converted_result = value else: # Needs the whole transformation converted_result = {JAVA_CLASS: "java.util.HashMap"} converted_result["map"] = map_pairs = {} for key, content in value.items(): map_pairs[key] = to_jabsorb(content) try: # Keep the raw jsonrpclib information map_pairs[JSON_CLASS] = value[JSON_CLASS] except KeyError: pass # List ? (consider tuples as an array) elif isinstance(value, list): converted_result = { JAVA_CLASS: "java.util.ArrayList", "list": [to_jabsorb(entry) for entry in value], } # Set ? elif isinstance(value, (set, frozenset)): converted_result = { JAVA_CLASS: "java.util.HashSet", "set": [to_jabsorb(entry) for entry in value], } # Tuple ? (used as array, except if it is empty) elif isinstance(value, tuple): converted_result = [to_jabsorb(entry) for entry in value] elif hasattr(value, JAVA_CLASS): # Class with a Java class hint: convert into a dictionary class_members = { name: getattr(value, name) for name in dir(value) if not name.startswith("_") } converted_result = HashableDict( (name, to_jabsorb(content)) for name, content in class_members.items() if not inspect.ismethod(content) ) # Do not forget the Java class converted_result[JAVA_CLASS] = getattr(value, JAVA_CLASS) # Also add a __jsonclass__ entry converted_result[JSON_CLASS] = _compute_jsonclass(value) # Other ? else: converted_result = value return converted_result
python
{ "resource": "" }
q9445
Requirement.copy
train
def copy(self): # type: () -> Requirement """ Returns a copy of this instance :return: A copy of this instance """ return Requirement( self.specification, self.aggregate, self.optional, self.__original_filter, self.immediate_rebind, )
python
{ "resource": "" }
q9446
Requirement.set_filter
train
def set_filter(self, props_filter): """ Changes the current filter for the given one :param props_filter: The new requirement filter on service properties :raise TypeError: Unknown filter type """ if props_filter is not None and not ( is_string(props_filter) or isinstance( props_filter, (ldapfilter.LDAPFilter, ldapfilter.LDAPCriteria) ) ): # Unknown type raise TypeError( "Invalid filter type {0}".format(type(props_filter).__name__) ) if props_filter is not None: # Filter given, keep its string form self.__original_filter = str(props_filter) else: # No filter self.__original_filter = None # Parse the filter self.filter = ldapfilter.get_ldap_filter(props_filter) # Prepare the full filter spec_filter = "({0}={1})".format(OBJECTCLASS, self.specification) self.__full_filter = ldapfilter.combine_filters( (spec_filter, self.filter) )
python
{ "resource": "" }
q9447
FactoryContext._deepcopy
train
def _deepcopy(self, data): """ Deep copies the given object :param data: Data to copy :return: A copy of the data, if supported, else the data itself """ if isinstance(data, dict): # Copy dictionary values return {key: self._deepcopy(value) for key, value in data.items()} elif isinstance(data, (list, tuple, set, frozenset)): # Copy sequence types values return type(data)(self._deepcopy(value) for value in data) try: # Try to use a copy() method, if any return data.copy() except AttributeError: # Can't copy the data, return it as is return data
python
{ "resource": "" }
q9448
FactoryContext.copy
train
def copy(self, inheritance=False): # type: (bool) -> FactoryContext """ Returns a deep copy of the current FactoryContext instance :param inheritance: If True, current handlers configurations are stored as inherited ones """ # Create a new factory context and duplicate its values new_context = FactoryContext() for field in self.__slots__: if not field.startswith("_"): setattr( new_context, field, self._deepcopy(getattr(self, field)) ) if inheritance: # Store configuration as inherited one new_context.__inherited_configuration = self.__handlers.copy() new_context.__handlers = {} # Remove instances in any case new_context.__instances.clear() new_context.is_singleton_active = False return new_context
python
{ "resource": "" }
q9449
FactoryContext.inherit_handlers
train
def inherit_handlers(self, excluded_handlers): # type: (Iterable[str]) -> None """ Merges the inherited configuration with the current ones :param excluded_handlers: Excluded handlers """ if not excluded_handlers: excluded_handlers = tuple() for handler, configuration in self.__inherited_configuration.items(): if handler in excluded_handlers: # Excluded handler continue elif handler not in self.__handlers: # Fully inherited configuration self.__handlers[handler] = configuration # Merge configuration... elif isinstance(configuration, dict): # Dictionary self.__handlers.setdefault(handler, {}).update(configuration) elif isinstance(configuration, list): # List handler_conf = self.__handlers.setdefault(handler, []) for item in configuration: if item not in handler_conf: handler_conf.append(item) # Clear the inherited configuration dictionary self.__inherited_configuration.clear()
python
{ "resource": "" }
q9450
FactoryContext.add_instance
train
def add_instance(self, name, properties): # type: (str, dict) -> None """ Stores the description of a component instance. The given properties are stored as is. :param name: Instance name :param properties: Instance properties :raise NameError: Already known instance name """ if name in self.__instances: raise NameError(name) # Store properties "as-is" self.__instances[name] = properties
python
{ "resource": "" }
q9451
ComponentContext.get_field_callback
train
def get_field_callback(self, field, event): # type: (str, str) -> Optional[Tuple[Callable, bool]] """ Retrieves the registered method for the given event. Returns None if not found :param field: Name of the dependency field :param event: A component life cycle event :return: A 2-tuple containing the callback associated to the given event and flag indicating if the callback must be called in valid state only """ try: return self.factory_context.field_callbacks[field][event] except KeyError: return None
python
{ "resource": "" }
q9452
PropertiesHandler._field_property_generator
train
def _field_property_generator(self, public_properties): """ Generates the methods called by the injected class properties :param public_properties: If True, create a public property accessor, else an hidden property accessor :return: getter and setter methods """ # Local variable, to avoid messing with "self" stored_instance = self._ipopo_instance # Choose public or hidden properties # and select the method to call to notify about the property update if public_properties: properties = stored_instance.context.properties update_notifier = stored_instance.update_property else: # Copy Hidden properties and remove them from the context properties = stored_instance.context.grab_hidden_properties() update_notifier = stored_instance.update_hidden_property def get_value(_, name): """ Retrieves the property value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return properties.get(name) def set_value(_, name, new_value): """ Sets the property value and trigger an update event :param name: The property name :param new_value: The new property value """ assert stored_instance.context is not None # Get the previous value old_value = properties.get(name) if new_value != old_value: # Change the property properties[name] = new_value # New value is different of the old one, trigger an event update_notifier(name, old_value, new_value) return new_value return get_value, set_value
python
{ "resource": "" }
q9453
PropertiesHandler.get_methods_names
train
def get_methods_names(public_properties): """ Generates the names of the fields where to inject the getter and setter methods :param public_properties: If True, returns the names of public property accessors, else of hidden property ones :return: getter and a setter field names """ if public_properties: prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX else: prefix = ipopo_constants.IPOPO_HIDDEN_PROPERTY_PREFIX return ( "{0}{1}".format(prefix, ipopo_constants.IPOPO_GETTER_SUFFIX), "{0}{1}".format(prefix, ipopo_constants.IPOPO_SETTER_SUFFIX), )
python
{ "resource": "" }
q9454
_full_class_name
train
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) """ module = obj.__class__.__module__ if module is None or module == str.__class__.__module__: return obj.__class__.__name__ return module + "." + obj.__class__.__name__
python
{ "resource": "" }
q9455
IOHandler._prompt
train
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 """ if prompt: # Print the prompt self.write(prompt) self.output.flush() # Read the line return to_str(self.input.readline())
python
{ "resource": "" }
q9456
_LoggerHandler.manipulate
train
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 """ # Create the logger for this component instance self._logger = logging.getLogger(self._name) # Inject it setattr(component_instance, self._field, self._logger)
python
{ "resource": "" }
q9457
_LoggerHandler.clear
train
def clear(self): """ Cleans up the handler. The handler can't be used after this method has been called """ self._logger.debug("Component handlers are cleared") # Clean up everything to avoid stale references, ... self._field = None self._name = None self._logger = None
python
{ "resource": "" }
q9458
completion_hints
train
def completion_hints(config, prompt, session, context, current, arguments): # type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str] """ 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 arguments: List of all arguments in their current state :return: A list of possible completions """ 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) # Find the ID of the next completer completers = config.completers if arg_idx > len(completers) - 1: # Argument is too far to be positional, try if config.multiple: # Multiple calls allowed for the last completer completer_id = completers[-1] else: # Nothing to return return [] else: completer_id = completers[arg_idx] if completer_id == DUMMY: # Dummy completer: do nothing return [] # Find the matching service svc_ref = context.get_service_reference( SVC_COMPLETER, "({}={})".format(PROP_COMPLETER_ID, completer_id) ) if svc_ref is None: # Handler not found _logger.debug("Unknown shell completer ID: %s", completer_id) return [] # Call the completer try: with use_service(context, svc_ref) as completer: matches = completer.complete( config, prompt, session, context, arguments, current ) if not matches: return [] return matches except Exception as ex: _logger.exception("Error calling completer %s: %s", completer_id, ex) return []
python
{ "resource": "" }
q9459
_resolve_file
train
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 """ if not file_name: return None path = os.path.realpath(file_name) if os.path.isfile(path): return path return None
python
{ "resource": "" }
q9460
InteractiveShell._normal_prompt
train
def _normal_prompt(self): """ Flushes the prompt before requesting the input :return: The command line """ sys.stdout.write(self.__get_ps1()) sys.stdout.flush() return safe_input()
python
{ "resource": "" }
q9461
InteractiveShell.loop_input
train
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 """ # 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) else: # No script: run the main loop (blocking) self._run_loop(self.__session) # Nothing more to do self._stop_event.set() sys.stdout.write("Bye !\n") sys.stdout.flush() if on_quit is not None: # Call a handler if needed on_quit()
python
{ "resource": "" }
q9462
InteractiveShell._run_loop
train
def _run_loop(self, session): """ Runs the main input loop :param session: Current shell session """ 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 the shell to be there # Before Python 2.7, wait() doesn't return a result if self._shell_event.wait(.2) or self._shell_event.is_set(): # Shell present if first_prompt: # Show the banner on first prompt sys.stdout.write(self._shell.get_banner()) first_prompt = False # Read the next line line = prompt() with self._lock: if self._shell_event.is_set(): # Execute it self._shell.execute(line, session) elif not self._stop_event.is_set(): # Shell service lost while not stopping sys.stdout.write("Shell service lost.") sys.stdout.flush() except (EOFError, KeyboardInterrupt, SystemExit): # Input closed or keyboard interruption pass
python
{ "resource": "" }
q9463
InteractiveShell.readline_completer
train
def readline_completer(self, text, state): """ A completer for the readline library """ 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 line full_line = readline.get_line_buffer() begin_idx = readline.get_begidx() # Parse arguments as best as we can try: arguments = shlex.split(full_line) except ValueError: arguments = full_line.split() # Extract the command (maybe with its namespace) command = arguments.pop(0) if begin_idx > 0: # We're completing after the command (and maybe some args) try: # Find the command ns, command = self._shell.get_ns_command(command) except ValueError: # Ambiguous command: ignore return None # Use the completer associated to the command, if any try: configuration = self._shell.get_command_completers( ns, command ) if configuration is not None: self._readline_matches = completion_hints( configuration, self.__get_ps1(), self.__session, self._context, text, arguments, ) except KeyError: # Unknown command pass elif "." in command: # Completing the command, and a name space is given namespace, prefix = text.split(".", 2) commands = self._shell.get_commands(namespace) # Filter methods according to the prefix self._readline_matches = [ "{0}.{1}".format(namespace, command) for command in commands if command.startswith(prefix) ] else: # Completing a command or namespace prefix = command # Default commands goes first... possibilities = [ "{0} ".format(command) for command in self._shell.get_commands(None) if command.startswith(prefix) ] # ... then name spaces namespaces = self._shell.get_namespaces() possibilities.extend( "{0}.".format(namespace) for namespace in namespaces if namespace.startswith(prefix) ) # ... then commands in those name spaces possibilities.extend( "{0} ".format(command) for namespace in namespaces if namespace is not None for command in self._shell.get_commands(namespace) if command.startswith(prefix) ) # Filter methods according to the prefix self._readline_matches = possibilities if not self._readline_matches: return None # Return the first possibility return self._readline_matches[0] elif state < len(self._readline_matches): # Next try return self._readline_matches[state] return None
python
{ "resource": "" }
q9464
InteractiveShell.search_shell
train
def search_shell(self): """ Looks for a shell service """ 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)
python
{ "resource": "" }
q9465
InteractiveShell.service_changed
train
def service_changed(self, event): """ Called by Pelix when an events changes """ 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: # Service is not matching our filter anymore self.clear_shell() # Request for a new binding self.search_shell()
python
{ "resource": "" }
q9466
InteractiveShell.set_shell
train
def set_shell(self, svc_ref): """ Binds the given shell service. :param svc_ref: A service reference """ 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: readline.set_completer(self.readline_completer) # Set the flag self._shell_event.set()
python
{ "resource": "" }
q9467
InteractiveShell.clear_shell
train
def clear_shell(self): """ Unbinds the active shell service """ 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: # Release the service self._context.unget_service(self._shell_ref) self._shell_ref = None self._shell = None
python
{ "resource": "" }
q9468
InteractiveShell.stop
train
def stop(self): """ Clears all members """ # 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_shell() self._context = None
python
{ "resource": "" }
q9469
_JsonRpcServlet.do_POST
train
def do_POST(self, request, response): # pylint: disable=C0103 """ Handles a HTTP POST request :param request: The HTTP request bean :param response: The HTTP response handler """ 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, "application/json-rpc") except Exception as ex: response.send_content( 500, "Internal error:\n{0}\n".format(ex), "text/plain" )
python
{ "resource": "" }
q9470
_RuntimeDependency.service_changed
train
def service_changed(self, event): """ Called by the framework when a service event occurs """ 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 return # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming self.on_service_arrival(svc_ref) elif kind in ( ServiceEvent.UNREGISTERING, ServiceEvent.MODIFIED_ENDMATCH, ): # Service gone or not matching anymore self.on_service_departure(svc_ref) elif kind == ServiceEvent.MODIFIED: # Modified properties (can be a new injection) self.on_service_modify(svc_ref, event.get_previous_properties())
python
{ "resource": "" }
q9471
_RuntimeDependency.start
train
def start(self): """ Starts the dependency manager """ self._context.add_service_listener( self, self.requirement.filter, self.requirement.specification )
python
{ "resource": "" }
q9472
LogReaderService._store_entry
train
def _store_entry(self, entry): """ Stores a new log entry and notifies listeners :param entry: A LogEntry object """ # 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 nor notifying # listener (to avoid a recursion) err_entry = LogEntry( logging.WARNING, "Error notifying logging listener {0}: {1}".format( listener, ex ), sys.exc_info(), self._context.get_bundle(), None, ) # Insert the new entry before the real one self.__logs.pop() self.__logs.append(err_entry) self.__logs.append(entry)
python
{ "resource": "" }
q9473
LogServiceInstance.log
train
def log(self, level, message, exc_info=None, reference=None): # pylint: disable=W0212 """ 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 """ 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: exception_str = "\n".join(traceback.format_exception(*exc_info)) except (TypeError, ValueError, AttributeError): exception_str = "<Invalid exc_info>" else: exception_str = None # Store the LogEntry entry = LogEntry( level, message, exception_str, self.__bundle, reference ) self.__reader._store_entry(entry)
python
{ "resource": "" }
q9474
LogServiceFactory._bundle_from_module
train
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 """ 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)
python
{ "resource": "" }
q9475
LogServiceFactory.emit
train
def emit(self, record): # pylint: disable=W0212 """ Handle a message logged with the logger :param record: A log record """ # 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)
python
{ "resource": "" }
q9476
_MqttConnection.publish
train
def publish(self, topic, payload, qos=0, retain=False): """ Publishes an MQTT message """ # TODO: check (full transmission) success return self._client.publish(topic, payload, qos, retain)
python
{ "resource": "" }
q9477
AggregateDependency.__store_service
train
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 """ self._future_value.setdefault(key, []).append(service)
python
{ "resource": "" }
q9478
AggregateDependency.__remove_service
train
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 """ 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 when removing a service with a None property, # if allow_none is False pass
python
{ "resource": "" }
q9479
AggregateDependency.get_value
train
def get_value(self): """ Retrieves the value to inject in the component :return: The value to inject """ 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
python
{ "resource": "" }
q9480
ExportRegistrationImpl.match_sr
train
def match_sr(self, svc_ref, cid=None): # type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool """ 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 """ 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 our_cid = self.get_export_container_id() if our_cid is None: return False return sr_compare and our_cid == cid
python
{ "resource": "" }
q9481
ExportRegistrationImpl.get_exception
train
def get_exception(self): # type: () -> Optional[Tuple[Any, Any, Any]] """ Returns the exception associated to the export :return: An exception tuple, if any """ with self.__lock: return ( self.__updateexception if self.__updateexception or self.__closed else self.__exportref.get_exception() )
python
{ "resource": "" }
q9482
ExportRegistrationImpl.close
train
def close(self): """ Cleans up the export endpoint """ 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_remoteservice_id() ed = self.__exportref.get_description() exception = self.__exportref.get_exception() self.__closed = True publish = self.__exportref.close(self) self.__exportref = None # pylint: disable=W0212 if publish and export_ref and self.__rsa: self.__rsa._publish_event( RemoteServiceAdminEvent.fromexportunreg( self.__rsa._get_bundle(), exporterid, rsid, export_ref, exception, ed, ) ) self.__rsa = None
python
{ "resource": "" }
q9483
EndpointAdvertiser.advertise_endpoint
train
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 not (e.g. it's already been advertised) """ 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: self._add_advertised(endpoint_description, advertise_result) return True return False
python
{ "resource": "" }
q9484
EndpointAdvertiser.update_endpoint
train
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) """ 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(endpoint_id) self._add_advertised(updated_ed, advertise_result) return True return False
python
{ "resource": "" }
q9485
ServiceRegistrationHandler._field_controller_generator
train
def _field_controller_generator(self): """ Generates the methods called by the injected controller """ # Local variable, to avoid messing with "self" stored_instance = self._ipopo_instance def get_value(self, name): # pylint: disable=W0613 """ Retrieves the controller value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return stored_instance.get_controller_state(name) def set_value(self, name, new_value): # pylint: disable=W0613 """ Sets the property value and trigger an update event :param name: The property name :param new_value: The new property value """ # Get the previous value old_value = stored_instance.get_controller_state(name) if new_value != old_value: # Update the controller state stored_instance.set_controller_state(name, new_value) return new_value return get_value, set_value
python
{ "resource": "" }
q9486
ServiceRegistrationHandler.on_controller_change
train
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 """ 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 "OFF" self._unregister_service()
python
{ "resource": "" }
q9487
ServiceRegistrationHandler.on_property_change
train
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 """ if self._registration is not None: # use the registration to trigger the service event self._registration.set_properties({name: new_value})
python
{ "resource": "" }
q9488
ServiceRegistrationHandler._register_service
train
def _register_service(self): """ Registers the provided service, if possible """ 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_context = self._ipopo_instance.bundle_context # Register the service self._registration = bundle_context.register_service( self.specifications, self._ipopo_instance.instance, properties, factory=self.__is_factory, prototype=self.__is_prototype, ) self._svc_reference = self._registration.get_reference() # Notify the component self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION, self._svc_reference, )
python
{ "resource": "" }
q9489
ServiceRegistrationHandler._unregister_service
train
def _unregister_service(self): """ Unregisters the provided service, if needed """ 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._ipopo_instance.name, "ServiceRegistration")) ) logger.error("Error unregistering a service: %s", ex) # Notify the component (even in case of error) self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_UNREGISTRATION, self._svc_reference, ) self._registration = None self._svc_reference = None
python
{ "resource": "" }
q9490
use_service
train
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 BundleException: Service not found :raise TypeError: Invalid service reference """ 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.BundleException: # Service might have already been unregistered pass
python
{ "resource": "" }
q9491
SynchronizedClassMethod
train
def SynchronizedClassMethod(*locks_attr_names, **kwargs): # pylint: disable=C1801 """ 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: A list of the lock(s) attribute(s) name(s) to be used for synchronization :return: The decorator method, surrounded with the lock """ # 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"]: # Sort the lock names if requested # (locking always in the same order reduces the risk of dead lock) locks_attr_names = list(locks_attr_names) locks_attr_names.sort() def wrapped(method): """ The wrapping method :param method: The wrapped method :return: The wrapped method :raise AttributeError: The given attribute name doesn't exist """ @functools.wraps(method) def synchronized(self, *args, **kwargs): """ Calls the wrapped method with a lock """ # Raises an AttributeError if needed locks = [getattr(self, attr_name) for attr_name in locks_attr_names] locked = collections.deque() i = 0 try: # Lock for lock in locks: if lock is None: # No lock... raise AttributeError( "Lock '{0}' can't be None in class {1}".format( locks_attr_names[i], type(self).__name__ ) ) # Get the lock i += 1 lock.acquire() locked.appendleft(lock) # Use the method return method(self, *args, **kwargs) finally: # Unlock what has been locked in all cases for lock in locked: lock.release() locked.clear() del locks[:] return synchronized # Return the wrapped method return wrapped
python
{ "resource": "" }
q9492
is_lock
train
def is_lock(lock): """ Tests if the given lock is an instance of a lock class """ 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
python
{ "resource": "" }
q9493
remove_duplicates
train
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 """ 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
python
{ "resource": "" }
q9494
add_listener
train
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 """ if listener is None or listener in registry: return False registry.append(listener) return True
python
{ "resource": "" }
q9495
remove_listener
train
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 """ if listener is not None and listener in registry: registry.remove(listener) return True return False
python
{ "resource": "" }
q9496
to_iterable
train
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 returns an empty list :return: A list containing the given string, or the given value """ 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]
python
{ "resource": "" }
q9497
Deprecated.__log
train
def __log(self, method_name): """ Logs the deprecation message on first call, does nothing after :param method_name: Name of the deprecated method """ 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 = True
python
{ "resource": "" }
q9498
CountdownEvent.step
train
def step(self): # type: () -> bool """ 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 """ 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 counter has gone below 0") return False
python
{ "resource": "" }
q9499
BundleCompleter.display_hook
train
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ 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 the largest match """ # 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 the associated name session.write_line() for bnd_id in matches: bnd = context.get_bundle(bnd_id) session.write_line(match_pattern, bnd_id, bnd.get_symbolic_name()) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
python
{ "resource": "" }