id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9,400 | yougov/pmxbot | pmxbot/slack.py | Bot.transmit | 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 | def transmit(self, channel, message):
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)) | [
"def",
"transmit",
"(",
"self",
",",
"channel",
",",
"message",
")",
":",
"target",
"=",
"(",
"self",
".",
"slack",
".",
"server",
".",
"channels",
".",
"find",
"(",
"channel",
")",
"or",
"self",
".",
"_find_user_channel",
"(",
"username",
"=",
"channe... | 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. | [
"Send",
"the",
"message",
"to",
"Slack",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/slack.py#L73-L87 |
9,401 | yougov/pmxbot | pmxbot/util.py | splitem | 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 | def splitem(query):
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()] | [
"def",
"splitem",
"(",
"query",
")",
":",
"prompt",
",",
"sep",
",",
"query",
"=",
"query",
".",
"rstrip",
"(",
"'?.!'",
")",
".",
"rpartition",
"(",
"':'",
")",
"choices",
"=",
"query",
".",
"split",
"(",
"','",
")",
"choices",
"[",
"-",
"1",
":... | 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'] | [
"Split",
"a",
"query",
"into",
"choices"
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L44-L75 |
9,402 | yougov/pmxbot | pmxbot/util.py | urban_lookup | 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 | 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'] | [
"def",
"urban_lookup",
"(",
"word",
")",
":",
"url",
"=",
"\"http://api.urbandictionary.com/v0/define\"",
"params",
"=",
"dict",
"(",
"term",
"=",
"word",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"resp",
".",... | Return a Urban Dictionary definition for a word or None if no result was
found. | [
"Return",
"a",
"Urban",
"Dictionary",
"definition",
"for",
"a",
"word",
"or",
"None",
"if",
"no",
"result",
"was",
"found",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L126-L138 |
9,403 | yougov/pmxbot | pmxbot/util.py | passagg | 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 | def passagg(recipient, 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()) | [
"def",
"passagg",
"(",
"recipient",
",",
"sender",
")",
":",
"adj",
"=",
"random",
".",
"choice",
"(",
"pmxbot",
".",
"phrases",
".",
"adjs",
")",
"if",
"random",
".",
"choice",
"(",
"[",
"False",
",",
"True",
"]",
")",
":",
"# address the recipient la... | Generate a passive-aggressive statement to recipient from sender. | [
"Generate",
"a",
"passive",
"-",
"aggressive",
"statement",
"to",
"recipient",
"from",
"sender",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/util.py#L165-L183 |
9,404 | yougov/pmxbot | pmxbot/config_.py | config | 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 | 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 | [
"def",
"config",
"(",
"client",
",",
"event",
",",
"channel",
",",
"nick",
",",
"rest",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'(?P<key>\\w+)\\s*(?P<op>[+-]?=)\\s*(?P<value>.*)$'",
")",
"match",
"=",
"pattern",
".",
"match",
"(",
"rest",
")",... | Change the running config, something like a=b or a+=b or a-=b | [
"Change",
"the",
"running",
"config",
"something",
"like",
"a",
"=",
"b",
"or",
"a",
"+",
"=",
"b",
"or",
"a",
"-",
"=",
"b"
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/config_.py#L10-L33 |
9,405 | yougov/pmxbot | pmxbot/itertools.py | trap_exceptions | 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 | def trap_exceptions(results, handler, exceptions=Exception):
try:
for result in results:
yield result
except exceptions as exc:
for result in always_iterable(handler(exc)):
yield result | [
"def",
"trap_exceptions",
"(",
"results",
",",
"handler",
",",
"exceptions",
"=",
"Exception",
")",
":",
"try",
":",
"for",
"result",
"in",
"results",
":",
"yield",
"result",
"except",
"exceptions",
"as",
"exc",
":",
"for",
"result",
"in",
"always_iterable",... | 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. | [
"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",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/itertools.py#L13-L24 |
9,406 | yougov/pmxbot | pmxbot/quotes.py | MongoDBQuotes.delete | 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 | def delete(self, lookup):
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) | [
"def",
"delete",
"(",
"self",
",",
"lookup",
")",
":",
"lookup",
",",
"num",
"=",
"self",
".",
"split_num",
"(",
"lookup",
")",
"if",
"num",
":",
"result",
"=",
"self",
".",
"find_matches",
"(",
"lookup",
")",
"[",
"num",
"-",
"1",
"]",
"else",
"... | If exactly one quote matches, delete it. Otherwise,
raise a ValueError. | [
"If",
"exactly",
"one",
"quote",
"matches",
"delete",
"it",
".",
"Otherwise",
"raise",
"a",
"ValueError",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/quotes.py#L153-L163 |
9,407 | yougov/pmxbot | pmxbot/irc.py | LoggingCommandBot._get_wrapper | 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 | def _get_wrapper():
if not pmxbot.config.get('use_ssl', False):
return lambda x: x
return importlib.import_module('ssl').wrap_socket | [
"def",
"_get_wrapper",
"(",
")",
":",
"if",
"not",
"pmxbot",
".",
"config",
".",
"get",
"(",
"'use_ssl'",
",",
"False",
")",
":",
"return",
"lambda",
"x",
":",
"x",
"return",
"importlib",
".",
"import_module",
"(",
"'ssl'",
")",
".",
"wrap_socket"
] | Get a socket wrapper based on SSL config. | [
"Get",
"a",
"socket",
"wrapper",
"based",
"on",
"SSL",
"config",
"."
] | 5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7 | https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/irc.py#L79-L85 |
9,408 | MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getStatusCode | 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 | def getStatusCode(self):
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 | [
"def",
"getStatusCode",
"(",
"self",
")",
":",
"if",
"'status'",
"in",
"self",
".",
"_response",
".",
"keys",
"(",
")",
":",
"if",
"(",
"self",
".",
"_response",
"[",
"'status'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"'code'",
"in",
"self",
".... | Returns the code of the status or None if it does not exist
:return:
Status code of the response | [
"Returns",
"the",
"code",
"of",
"the",
"status",
"or",
"None",
"if",
"it",
"does",
"not",
"exist"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L37-L52 |
9,409 | MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getStatusMsg | 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 | def getStatusMsg(self):
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 '' | [
"def",
"getStatusMsg",
"(",
"self",
")",
":",
"if",
"'status'",
"in",
"self",
".",
"_response",
".",
"keys",
"(",
")",
":",
"if",
"(",
"self",
".",
"_response",
"[",
"'status'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"'msg'",
"in",
"self",
".",... | Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response | [
"Returns",
"the",
"message",
"of",
"the",
"status",
"or",
"an",
"empty",
"string",
"if",
"it",
"does",
"not",
"exist"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L54-L66 |
9,410 | MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getConsumedCredits | 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 | def getConsumedCredits(self):
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 | [
"def",
"getConsumedCredits",
"(",
"self",
")",
":",
"if",
"'status'",
"in",
"self",
".",
"_response",
".",
"keys",
"(",
")",
":",
"if",
"(",
"self",
".",
"_response",
"[",
"'status'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"'credits'",
"in",
"sel... | Returns the credit consumed by the request made
:return:
String with the number of credits consumed | [
"Returns",
"the",
"credit",
"consumed",
"by",
"the",
"request",
"made"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L68-L85 |
9,411 | MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getRemainingCredits | 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 | def getRemainingCredits(self):
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 | [
"def",
"getRemainingCredits",
"(",
"self",
")",
":",
"if",
"'status'",
"in",
"self",
".",
"_response",
".",
"keys",
"(",
")",
":",
"if",
"(",
"self",
".",
"_response",
"[",
"'status'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"'remaining_credits'",
"... | Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits | [
"Returns",
"the",
"remaining",
"credits",
"for",
"the",
"license",
"key",
"used",
"after",
"the",
"request",
"was",
"made"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L87-L104 |
9,412 | MeaningCloud/meaningcloud-python | meaningcloud/Response.py | Response.getResults | 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 | def getResults(self):
results = self._response.copy()
if 'status' in self._response.keys():
if results['status'] is not None:
del results['status']
return results
else:
return None | [
"def",
"getResults",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"_response",
".",
"copy",
"(",
")",
"if",
"'status'",
"in",
"self",
".",
"_response",
".",
"keys",
"(",
")",
":",
"if",
"results",
"[",
"'status'",
"]",
"is",
"not",
"None",
"... | Returns the results from the API without the status of the request
:return:
Dictionary with the results | [
"Returns",
"the",
"results",
"from",
"the",
"API",
"without",
"the",
"status",
"of",
"the",
"request"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Response.py#L106-L120 |
9,413 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_forces | 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 | def get_forces(self):
forces = []
for f in self.service.request('GET', 'forces'):
forces.append(Force(self, id=f['id'], name=f['name']))
return forces | [
"def",
"get_forces",
"(",
"self",
")",
":",
"forces",
"=",
"[",
"]",
"for",
"f",
"in",
"self",
".",
"service",
".",
"request",
"(",
"'GET'",
",",
"'forces'",
")",
":",
"forces",
".",
"append",
"(",
"Force",
"(",
"self",
",",
"id",
"=",
"f",
"[",
... | 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) | [
"Get",
"a",
"list",
"of",
"all",
"police",
"forces",
".",
"Uses",
"the",
"forces_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L31-L45 |
9,414 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_neighbourhoods | 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 | def get_neighbourhoods(self, 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) | [
"def",
"get_neighbourhoods",
"(",
"self",
",",
"force",
")",
":",
"if",
"not",
"isinstance",
"(",
"force",
",",
"Force",
")",
":",
"force",
"=",
"Force",
"(",
"self",
",",
"id",
"=",
"force",
")",
"neighbourhoods",
"=",
"[",
"]",
"for",
"n",
"in",
... | 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). | [
"Get",
"a",
"list",
"of",
"all",
"neighbourhoods",
"for",
"a",
"force",
".",
"Uses",
"the",
"neighbourhoods_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L60-L82 |
9,415 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_neighbourhood | 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 | def get_neighbourhood(self, force, id, **attrs):
if not isinstance(force, Force):
force = Force(self, id=force, **attrs)
return Neighbourhood(self, force=force, id=id, **attrs) | [
"def",
"get_neighbourhood",
"(",
"self",
",",
"force",
",",
"id",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"not",
"isinstance",
"(",
"force",
",",
"Force",
")",
":",
"force",
"=",
"Force",
"(",
"self",
",",
"id",
"=",
"force",
",",
"*",
"*",
"attr... | 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. | [
"Get",
"a",
"specific",
"neighbourhood",
".",
"Uses",
"the",
"neighbourhood_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L84-L101 |
9,416 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.locate_neighbourhood | 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 | def locate_neighbourhood(self, lat, lng):
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 | [
"def",
"locate_neighbourhood",
"(",
"self",
",",
"lat",
",",
"lng",
")",
":",
"method",
"=",
"'locate-neighbourhood'",
"q",
"=",
"'%s,%s'",
"%",
"(",
"lat",
",",
"lng",
")",
"try",
":",
"result",
"=",
"self",
".",
"service",
".",
"request",
"(",
"'GET'... | 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. | [
"Find",
"a",
"neighbourhood",
"by",
"location",
".",
"Uses",
"the",
"locate",
"-",
"neighbourhood_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L103-L127 |
9,417 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime_categories | 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 | def get_crime_categories(self, date=None):
return sorted(self._get_crime_categories(date=date).values(),
key=lambda c: c.name) | [
"def",
"get_crime_categories",
"(",
"self",
",",
"date",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"_get_crime_categories",
"(",
"date",
"=",
"date",
")",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"c",
":",
"c",
".",
"nam... | 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``). | [
"Get",
"a",
"list",
"of",
"crime",
"categories",
"valid",
"for",
"a",
"particular",
"date",
".",
"Uses",
"the",
"crime",
"-",
"categories_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L171-L187 |
9,418 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime_category | 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 | def get_crime_category(self, id, date=None):
try:
return self._get_crime_categories(date=date)[id]
except KeyError:
raise InvalidCategoryException(
'Category %s not found for %s' % (id, date)) | [
"def",
"get_crime_category",
"(",
"self",
",",
"id",
",",
"date",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_get_crime_categories",
"(",
"date",
"=",
"date",
")",
"[",
"id",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidCategoryExceptio... | 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``). | [
"Get",
"a",
"particular",
"crime",
"category",
"by",
"ID",
"valid",
"at",
"a",
"particular",
"date",
".",
"Uses",
"the",
"crime",
"-",
"categories_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L189-L207 |
9,419 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crime | 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 | def get_crime(self, 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 | [
"def",
"get_crime",
"(",
"self",
",",
"persistent_id",
")",
":",
"method",
"=",
"'outcomes-for-crime/%s'",
"%",
"persistent_id",
"response",
"=",
"self",
".",
"service",
".",
"request",
"(",
"'GET'",
",",
"method",
")",
"crime",
"=",
"Crime",
"(",
"self",
... | 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. | [
"Get",
"a",
"particular",
"crime",
"by",
"persistent",
"ID",
".",
"Uses",
"the",
"outcomes",
"-",
"for",
"-",
"crime_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L209-L233 |
9,420 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_point | 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 | def get_crimes_point(self, lat, lng, date=None, category=None):
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 | [
"def",
"get_crimes_point",
"(",
"self",
",",
"lat",
",",
"lng",
",",
"date",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"category",
",",
"CrimeCategory",
")",
":",
"category",
"=",
"category",
".",
"id",
"method",
"="... | 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). | [
"Get",
"crimes",
"within",
"a",
"1",
"-",
"mile",
"radius",
"of",
"a",
"location",
".",
"Uses",
"the",
"crime",
"-",
"street_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L235-L270 |
9,421 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_area | 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 | def get_crimes_area(self, points, date=None, category=None):
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 | [
"def",
"get_crimes_area",
"(",
"self",
",",
"points",
",",
"date",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"category",
",",
"CrimeCategory",
")",
":",
"category",
"=",
"category",
".",
"id",
"method",
"=",
"'crimes-s... | 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). | [
"Get",
"crimes",
"within",
"a",
"custom",
"area",
".",
"Uses",
"the",
"crime",
"-",
"street_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L272-L302 |
9,422 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_location | 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 | def get_crimes_location(self, location_id, date=None):
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 | [
"def",
"get_crimes_location",
"(",
"self",
",",
"location_id",
",",
"date",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'location_id'",
":",
"location_id",
",",
"}",
"crimes",
"=",
"[",
"]",
"if",
"date",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'date... | 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. | [
"Get",
"crimes",
"at",
"a",
"particular",
"snap",
"-",
"point",
"location",
".",
"Uses",
"the",
"crimes",
"-",
"at",
"-",
"location_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L304-L329 |
9,423 | rkhleics/police-api-client-python | police_api/__init__.py | PoliceAPI.get_crimes_no_location | 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 | def get_crimes_no_location(self, force, date=None, category=None):
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 | [
"def",
"get_crimes_no_location",
"(",
"self",
",",
"force",
",",
"date",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"force",
",",
"Force",
")",
":",
"force",
"=",
"Force",
"(",
"self",
",",
"id",
"=",
"force"... | 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. | [
"Get",
"crimes",
"with",
"no",
"location",
"for",
"a",
"force",
".",
"Uses",
"the",
"crimes",
"-",
"no",
"-",
"location_",
"API",
"call",
"."
] | b5c1e493487eb2409e2c04ed9fbd304f73d89fdc | https://github.com/rkhleics/police-api-client-python/blob/b5c1e493487eb2409e2c04ed9fbd304f73d89fdc/police_api/__init__.py#L331-L368 |
9,424 | MaxStrange/retrowrapper | retrowrapper.py | _retrocom | 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 | def _retrocom(rx, tx, game, kwargs):
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) | [
"def",
"_retrocom",
"(",
"rx",
",",
"tx",
",",
"game",
",",
"kwargs",
")",
":",
"env",
"=",
"RetroWrapper",
".",
"retro_make_func",
"(",
"game",
",",
"*",
"*",
"kwargs",
")",
"# Sit around on the queue, waiting for calls from RetroWrapper",
"while",
"True",
":",... | This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment. | [
"This",
"function",
"is",
"the",
"target",
"for",
"RetroWrapper",
"s",
"internal",
"process",
"and",
"does",
"all",
"the",
"work",
"of",
"communicating",
"with",
"the",
"environment",
"."
] | f9a112e07ee432d5f34b3a167902e808cfb0e84f | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L13-L38 |
9,425 | MaxStrange/retrowrapper | retrowrapper.py | RetroWrapper._ask_if_attr_is_callable | 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 | def _ask_if_attr_is_callable(self, attr):
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get() | [
"def",
"_ask_if_attr_is_callable",
"(",
"self",
",",
"attr",
")",
":",
"self",
".",
"_tx",
".",
"put",
"(",
"(",
"RetroWrapper",
".",
"symbol",
",",
"attr",
",",
"{",
"}",
")",
")",
"return",
"self",
".",
"_rx",
".",
"get",
"(",
")"
] | Returns whether or not the attribute is a callable. | [
"Returns",
"whether",
"or",
"not",
"the",
"attribute",
"is",
"a",
"callable",
"."
] | f9a112e07ee432d5f34b3a167902e808cfb0e84f | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L133-L138 |
9,426 | MaxStrange/retrowrapper | retrowrapper.py | RetroWrapper.close | def close(self):
"""
Shutdown the environment.
"""
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join() | python | def close(self):
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"\"_tx\"",
"in",
"self",
".",
"__dict__",
"and",
"\"_proc\"",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"_tx",
".",
"put",
"(",
"(",
"\"close\"",
",",
"(",
")",
",",
"{",
"}",
")",
")",
"self",
... | Shutdown the environment. | [
"Shutdown",
"the",
"environment",
"."
] | f9a112e07ee432d5f34b3a167902e808cfb0e84f | https://github.com/MaxStrange/retrowrapper/blob/f9a112e07ee432d5f34b3a167902e808cfb0e84f/retrowrapper.py#L140-L146 |
9,427 | MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.addParam | 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 | def addParam(self, paramName, paramValue):
if not paramName:
raise ValueError('paramName cannot be empty')
self._params[paramName] = paramValue | [
"def",
"addParam",
"(",
"self",
",",
"paramName",
",",
"paramValue",
")",
":",
"if",
"not",
"paramName",
":",
"raise",
"ValueError",
"(",
"'paramName cannot be empty'",
")",
"self",
".",
"_params",
"[",
"paramName",
"]",
"=",
"paramValue"
] | Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter | [
"Add",
"a",
"parameter",
"to",
"the",
"request"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L37-L49 |
9,428 | MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.setContent | 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 | def setContent(self, type_, value):
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) | [
"def",
"setContent",
"(",
"self",
",",
"type_",
",",
"value",
")",
":",
"if",
"type_",
"in",
"[",
"self",
".",
"CONTENT_TYPE_TXT",
",",
"self",
".",
"CONTENT_TYPE_URL",
",",
"self",
".",
"CONTENT_TYPE_FILE",
"]",
":",
"if",
"type_",
"==",
"self",
".",
... | 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 | [
"Sets",
"the",
"content",
"that",
"s",
"going",
"to",
"be",
"sent",
"to",
"analyze",
"according",
"to",
"its",
"type"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L51-L67 |
9,429 | MeaningCloud/meaningcloud-python | meaningcloud/Request.py | Request.sendRequest | 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 | def sendRequest(self, extraHeaders=""):
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 | [
"def",
"sendRequest",
"(",
"self",
",",
"extraHeaders",
"=",
"\"\"",
")",
":",
"self",
".",
"addParam",
"(",
"'src'",
",",
"'mc-python'",
")",
"params",
"=",
"urlencode",
"(",
"self",
".",
"_params",
")",
"url",
"=",
"self",
".",
"_url",
"if",
"'doc'",... | 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 | [
"Sends",
"a",
"request",
"to",
"the",
"URL",
"specified",
"and",
"returns",
"a",
"response",
"only",
"if",
"the",
"HTTP",
"code",
"returned",
"is",
"OK"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L99-L130 |
9,430 | MeaningCloud/meaningcloud-python | meaningcloud/ParserResponse.py | ParserResponse.getLemmatization | 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 | def getLemmatization(self, fullPOSTag=False):
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 | [
"def",
"getLemmatization",
"(",
"self",
",",
"fullPOSTag",
"=",
"False",
")",
":",
"leaves",
"=",
"self",
".",
"_getTreeLeaves",
"(",
")",
"lemmas",
"=",
"{",
"}",
"for",
"leaf",
"in",
"leaves",
":",
"analyses",
"=",
"[",
"]",
"if",
"'analysis_list'",
... | 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 | [
"This",
"function",
"obtains",
"the",
"lemmas",
"and",
"PoS",
"for",
"the",
"text",
"sent"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/ParserResponse.py#L22-L44 |
9,431 | MeaningCloud/meaningcloud-python | meaningcloud/TopicsResponse.py | TopicsResponse.getTypeLastNode | 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 | def getTypeLastNode(self, 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 | [
"def",
"getTypeLastNode",
"(",
"self",
",",
"type_",
")",
":",
"lastNode",
"=",
"\"\"",
"if",
"type_",
"and",
"(",
"type",
"(",
"type_",
")",
"is",
"not",
"list",
")",
"and",
"(",
"type",
"(",
"type_",
")",
"is",
"not",
"dict",
")",
":",
"aType",
... | 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 | [
"Obtains",
"the",
"last",
"node",
"or",
"leaf",
"of",
"the",
"type",
"specified"
] | 1dd76ecabeedd80c9bb14a1716d39657d645775f | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/TopicsResponse.py#L161-L175 |
9,432 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.__conn_listener | 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 | def __conn_listener(self, 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") | [
"def",
"__conn_listener",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"KazooState",
".",
"CONNECTED",
":",
"self",
".",
"__online",
"=",
"True",
"if",
"not",
"self",
".",
"__connected",
":",
"self",
".",
"__connected",
"=",
"True",
"self",
... | Connection event listener
:param state: The new connection state | [
"Connection",
"event",
"listener"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L135-L160 |
9,433 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.start | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() | python | def start(self):
self.__stop = False
self._queue.start()
self._zk.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"__stop",
"=",
"False",
"self",
".",
"_queue",
".",
"start",
"(",
")",
"self",
".",
"_zk",
".",
"start",
"(",
")"
] | Starts the connection | [
"Starts",
"the",
"connection"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L162-L168 |
9,434 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.stop | def stop(self):
"""
Stops the connection
"""
self.__stop = True
self._queue.stop()
self._zk.stop() | python | def stop(self):
self.__stop = True
self._queue.stop()
self._zk.stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"__stop",
"=",
"True",
"self",
".",
"_queue",
".",
"stop",
"(",
")",
"self",
".",
"_zk",
".",
"stop",
"(",
")"
] | Stops the connection | [
"Stops",
"the",
"connection"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L170-L176 |
9,435 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.__path | 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 | def __path(self, path):
if path.startswith(self.__prefix):
return path
return "{}{}".format(self.__prefix, path) | [
"def",
"__path",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"self",
".",
"__prefix",
")",
":",
"return",
"path",
"return",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"__prefix",
",",
"path",
")"
] | Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path | [
"Adds",
"the",
"prefix",
"to",
"the",
"given",
"path"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L192-L202 |
9,436 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.create | 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 | def create(self, path, data, ephemeral=False, sequence=False):
return self._zk.create(
self.__path(path), data, ephemeral=ephemeral, sequence=sequence
) | [
"def",
"create",
"(",
"self",
",",
"path",
",",
"data",
",",
"ephemeral",
"=",
"False",
",",
"sequence",
"=",
"False",
")",
":",
"return",
"self",
".",
"_zk",
".",
"create",
"(",
"self",
".",
"__path",
"(",
"path",
")",
",",
"data",
",",
"ephemeral... | Creates a ZooKeeper node
:param path: Z-Path
:param data: Node Content
:param ephemeral: Ephemeral flag
:param sequence: Sequential flag | [
"Creates",
"a",
"ZooKeeper",
"node"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L204-L215 |
9,437 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.get | 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 | def get(self, path, watch=None):
return self._zk.get(self.__path(path), watch=watch) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"watch",
"=",
"None",
")",
":",
"return",
"self",
".",
"_zk",
".",
"get",
"(",
"self",
".",
"__path",
"(",
"path",
")",
",",
"watch",
"=",
"watch",
")"
] | Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method | [
"Gets",
"the",
"content",
"of",
"a",
"ZooKeeper",
"node"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L225-L232 |
9,438 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.get_children | 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 | def get_children(self, path, watch=None):
return self._zk.get_children(self.__path(path), watch=watch) | [
"def",
"get_children",
"(",
"self",
",",
"path",
",",
"watch",
"=",
"None",
")",
":",
"return",
"self",
".",
"_zk",
".",
"get_children",
"(",
"self",
".",
"__path",
"(",
"path",
")",
",",
"watch",
"=",
"watch",
")"
] | Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method | [
"Gets",
"the",
"list",
"of",
"children",
"of",
"a",
"node"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L234-L241 |
9,439 | tcalmant/ipopo | pelix/remote/discovery/zookeeper.py | ZooKeeperClient.set | 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 | def set(self, path, data):
return self._zk.set(self.__path(path), data) | [
"def",
"set",
"(",
"self",
",",
"path",
",",
"data",
")",
":",
"return",
"self",
".",
"_zk",
".",
"set",
"(",
"self",
".",
"__path",
"(",
"path",
")",
",",
"data",
")"
] | Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content | [
"Sets",
"the",
"content",
"of",
"a",
"ZooKeeper",
"node"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/zookeeper.py#L243-L250 |
9,440 | tcalmant/ipopo | pelix/ipopo/constants.py | get_ipopo_svc_ref | 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 | def get_ipopo_svc_ref(bundle_context):
# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
# 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 | [
"def",
"get_ipopo_svc_ref",
"(",
"bundle_context",
")",
":",
"# type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]",
"# Look after the service",
"ref",
"=",
"bundle_context",
".",
"get_service_reference",
"(",
"SERVICE_IPOPO",
")",
"if",
"ref",
"is",
"None",
":",... | 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 | [
"Retrieves",
"a",
"tuple",
"containing",
"the",
"service",
"reference",
"to",
"iPOPO",
"and",
"the",
"service",
"itself"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L189-L212 |
9,441 | tcalmant/ipopo | pelix/ipopo/constants.py | use_ipopo | 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 | def use_ipopo(bundle_context):
# type: (BundleContext) -> Any
# 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 | [
"def",
"use_ipopo",
"(",
"bundle_context",
")",
":",
"# type: (BundleContext) -> Any",
"# Get the service and its reference",
"ref_svc",
"=",
"get_ipopo_svc_ref",
"(",
"bundle_context",
")",
"if",
"ref_svc",
"is",
"None",
":",
"raise",
"BundleException",
"(",
"\"No iPOPO ... | 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 | [
"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",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L216-L241 |
9,442 | tcalmant/ipopo | pelix/ipopo/constants.py | use_waiting_list | 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 | def use_waiting_list(bundle_context):
# type: (BundleContext) -> Any
# 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 | [
"def",
"use_waiting_list",
"(",
"bundle_context",
")",
":",
"# type: (BundleContext) -> Any",
"# Get the service and its reference",
"ref",
"=",
"bundle_context",
".",
"get_service_reference",
"(",
"SERVICE_IPOPO_WAITING_LIST",
")",
"if",
"ref",
"is",
"None",
":",
"raise",
... | 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 | [
"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",
"... | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L245-L270 |
9,443 | tcalmant/ipopo | pelix/misc/jabsorb.py | _is_builtin | 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 | def _is_builtin(obj):
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__main__") | [
"def",
"_is_builtin",
"(",
"obj",
")",
":",
"module_",
"=",
"inspect",
".",
"getmodule",
"(",
"obj",
")",
"if",
"module_",
"in",
"(",
"None",
",",
"builtins",
")",
":",
"return",
"True",
"return",
"module_",
".",
"__name__",
"in",
"(",
"\"\"",
",",
"... | 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 | [
"Checks",
"if",
"the",
"type",
"of",
"the",
"given",
"object",
"is",
"a",
"built",
"-",
"in",
"one",
"or",
"not"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L157-L168 |
9,444 | tcalmant/ipopo | pelix/misc/jabsorb.py | to_jabsorb | 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 | def to_jabsorb(value):
# 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 | [
"def",
"to_jabsorb",
"(",
"value",
")",
":",
"# None ?",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# Map ?",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"JAVA_CLASS",
"in",
"value",
"or",
"JSON_CLASS",
"in",
"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) | [
"Adds",
"information",
"for",
"Jabsorb",
"if",
"needed",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/jabsorb.py#L188-L277 |
9,445 | tcalmant/ipopo | pelix/ipopo/contexts.py | Requirement.copy | 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 | def copy(self):
# type: () -> Requirement
return Requirement(
self.specification,
self.aggregate,
self.optional,
self.__original_filter,
self.immediate_rebind,
) | [
"def",
"copy",
"(",
"self",
")",
":",
"# type: () -> Requirement",
"return",
"Requirement",
"(",
"self",
".",
"specification",
",",
"self",
".",
"aggregate",
",",
"self",
".",
"optional",
",",
"self",
".",
"__original_filter",
",",
"self",
".",
"immediate_rebi... | Returns a copy of this instance
:return: A copy of this instance | [
"Returns",
"a",
"copy",
"of",
"this",
"instance"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L146-L159 |
9,446 | tcalmant/ipopo | pelix/ipopo/contexts.py | Requirement.set_filter | 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 | def set_filter(self, props_filter):
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)
) | [
"def",
"set_filter",
"(",
"self",
",",
"props_filter",
")",
":",
"if",
"props_filter",
"is",
"not",
"None",
"and",
"not",
"(",
"is_string",
"(",
"props_filter",
")",
"or",
"isinstance",
"(",
"props_filter",
",",
"(",
"ldapfilter",
".",
"LDAPFilter",
",",
"... | Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type | [
"Changes",
"the",
"current",
"filter",
"for",
"the",
"given",
"one"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L195-L227 |
9,447 | tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext._deepcopy | 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 | def _deepcopy(self, data):
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 | [
"def",
"_deepcopy",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"# Copy dictionary values",
"return",
"{",
"key",
":",
"self",
".",
"_deepcopy",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"data"... | Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself | [
"Deep",
"copies",
"the",
"given",
"object"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L318-L337 |
9,448 | tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.copy | 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 | def copy(self, inheritance=False):
# type: (bool) -> FactoryContext
# 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 | [
"def",
"copy",
"(",
"self",
",",
"inheritance",
"=",
"False",
")",
":",
"# type: (bool) -> FactoryContext",
"# Create a new factory context and duplicate its values",
"new_context",
"=",
"FactoryContext",
"(",
")",
"for",
"field",
"in",
"self",
".",
"__slots__",
":",
... | Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones | [
"Returns",
"a",
"deep",
"copy",
"of",
"the",
"current",
"FactoryContext",
"instance"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L339-L363 |
9,449 | tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.inherit_handlers | 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 | def inherit_handlers(self, excluded_handlers):
# type: (Iterable[str]) -> None
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() | [
"def",
"inherit_handlers",
"(",
"self",
",",
"excluded_handlers",
")",
":",
"# type: (Iterable[str]) -> None",
"if",
"not",
"excluded_handlers",
":",
"excluded_handlers",
"=",
"tuple",
"(",
")",
"for",
"handler",
",",
"configuration",
"in",
"self",
".",
"__inherited... | Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers | [
"Merges",
"the",
"inherited",
"configuration",
"with",
"the",
"current",
"ones"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L365-L397 |
9,450 | tcalmant/ipopo | pelix/ipopo/contexts.py | FactoryContext.add_instance | 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 | def add_instance(self, name, properties):
# type: (str, dict) -> None
if name in self.__instances:
raise NameError(name)
# Store properties "as-is"
self.__instances[name] = properties | [
"def",
"add_instance",
"(",
"self",
",",
"name",
",",
"properties",
")",
":",
"# type: (str, dict) -> None",
"if",
"name",
"in",
"self",
".",
"__instances",
":",
"raise",
"NameError",
"(",
"name",
")",
"# Store properties \"as-is\"",
"self",
".",
"__instances",
... | 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 | [
"Stores",
"the",
"description",
"of",
"a",
"component",
"instance",
".",
"The",
"given",
"properties",
"are",
"stored",
"as",
"is",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L399-L413 |
9,451 | tcalmant/ipopo | pelix/ipopo/contexts.py | ComponentContext.get_field_callback | 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 | def get_field_callback(self, field, event):
# type: (str, str) -> Optional[Tuple[Callable, bool]]
try:
return self.factory_context.field_callbacks[field][event]
except KeyError:
return None | [
"def",
"get_field_callback",
"(",
"self",
",",
"field",
",",
"event",
")",
":",
"# type: (str, str) -> Optional[Tuple[Callable, bool]]",
"try",
":",
"return",
"self",
".",
"factory_context",
".",
"field_callbacks",
"[",
"field",
"]",
"[",
"event",
"]",
"except",
"... | 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 | [
"Retrieves",
"the",
"registered",
"method",
"for",
"the",
"given",
"event",
".",
"Returns",
"None",
"if",
"not",
"found"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L546-L561 |
9,452 | tcalmant/ipopo | pelix/ipopo/handlers/properties.py | PropertiesHandler._field_property_generator | 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 | def _field_property_generator(self, public_properties):
# 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 | [
"def",
"_field_property_generator",
"(",
"self",
",",
"public_properties",
")",
":",
"# 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 ... | 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 | [
"Generates",
"the",
"methods",
"called",
"by",
"the",
"injected",
"class",
"properties"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/properties.py#L116-L166 |
9,453 | tcalmant/ipopo | pelix/ipopo/handlers/properties.py | PropertiesHandler.get_methods_names | 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 | def get_methods_names(public_properties):
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),
) | [
"def",
"get_methods_names",
"(",
"public_properties",
")",
":",
"if",
"public_properties",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_PROPERTY_PREFIX",
"else",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_HIDDEN_PROPERTY_PREFIX",
"return",
"(",
"\"{0}{1}\"... | 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 | [
"Generates",
"the",
"names",
"of",
"the",
"fields",
"where",
"to",
"inject",
"the",
"getter",
"and",
"setter",
"methods"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/properties.py#L169-L186 |
9,454 | tcalmant/ipopo | pelix/rsa/shell.py | _full_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)
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__ | python | def _full_class_name(obj):
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",
")",
":",
"module",
"=",
"obj",
".",
"__class__",
".",
"__module__",
"if",
"module",
"is",
"None",
"or",
"module",
"==",
"str",
".",
"__class__",
".",
"__module__",
":",
"return",
"obj",
".",
"__class__",
".",
"__na... | 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) | [
"Returns",
"the",
"full",
"name",
"of",
"the",
"class",
"of",
"the",
"given",
"object"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/shell.py#L87-L97 |
9,455 | tcalmant/ipopo | pelix/shell/beans.py | IOHandler._prompt | 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 | def _prompt(self, prompt=None):
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",
")",
":",
"if",
"prompt",
":",
"# Print the prompt",
"self",
".",
"write",
"(",
"prompt",
")",
"self",
".",
"output",
".",
"flush",
"(",
")",
"# Read the line",
"return",
"to_str",
"(",
"self",
... | Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str | [
"Reads",
"a",
"line",
"written",
"by",
"the",
"user"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/beans.py#L195-L208 |
9,456 | tcalmant/ipopo | samples/handler/logger.py | _LoggerHandler.manipulate | 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 | def manipulate(self, stored_instance, component_instance):
# 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",
")",
":",
"# Create the logger for this component instance",
"self",
".",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"_name",
")",
"# Inject it",
"setattr",
"(",... | 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 | [
"Called",
"by",
"iPOPO",
"right",
"after",
"the",
"instantiation",
"of",
"the",
"component",
".",
"This",
"is",
"the",
"last",
"chance",
"to",
"manipulate",
"the",
"component",
"before",
"the",
"other",
"handlers",
"start",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger.py#L140-L153 |
9,457 | tcalmant/ipopo | samples/handler/logger.py | _LoggerHandler.clear | 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 | def clear(self):
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",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Component handlers are cleared\"",
")",
"# Clean up everything to avoid stale references, ...",
"self",
".",
"_field",
"=",
"None",
"self",
".",
"_name",
"=",
"None",
"self",
".",... | Cleans up the handler. The handler can't be used after this method has
been called | [
"Cleans",
"up",
"the",
"handler",
".",
"The",
"handler",
"can",
"t",
"be",
"used",
"after",
"this",
"method",
"has",
"been",
"called"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger.py#L189-L199 |
9,458 | tcalmant/ipopo | pelix/shell/completion/core.py | completion_hints | 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 | def completion_hints(config, prompt, session, context, current, arguments):
# 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)
# 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 [] | [
"def",
"completion_hints",
"(",
"config",
",",
"prompt",
",",
"session",
",",
"context",
",",
"current",
",",
"arguments",
")",
":",
"# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]",
"if",
"not",
"current",
":",
"# No word yet, so th... | 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 | [
"Returns",
"the",
"possible",
"completions",
"of",
"the",
"current",
"argument"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/core.py#L105-L163 |
9,459 | tcalmant/ipopo | pelix/shell/console.py | _resolve_file | 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 | def _resolve_file(file_name):
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",
")",
":",
"if",
"not",
"file_name",
":",
"return",
"None",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"file_name",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"pat... | 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 | [
"Checks",
"if",
"the",
"file",
"exists",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L497-L514 |
9,460 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell._normal_prompt | 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 | def _normal_prompt(self):
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input() | [
"def",
"_normal_prompt",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"__get_ps1",
"(",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"safe_input",
"(",
")"
] | Flushes the prompt before requesting the input
:return: The command line | [
"Flushes",
"the",
"prompt",
"before",
"requesting",
"the",
"input"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L137-L145 |
9,461 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.loop_input | 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 | def loop_input(self, on_quit=None):
# 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() | [
"def",
"loop_input",
"(",
"self",
",",
"on_quit",
"=",
"None",
")",
":",
"# Start the init script",
"self",
".",
"_run_script",
"(",
"self",
".",
"__session",
",",
"self",
".",
"_context",
".",
"get_property",
"(",
"PROP_INIT_FILE",
")",
")",
"# Run the script... | 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 | [
"Reads",
"the",
"standard",
"input",
"until",
"the",
"shell",
"session",
"is",
"stopped"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L147-L173 |
9,462 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell._run_loop | 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 | def _run_loop(self, 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 | [
"def",
"_run_loop",
"(",
"self",
",",
"session",
")",
":",
"try",
":",
"first_prompt",
"=",
"True",
"# Set up the prompt",
"prompt",
"=",
"(",
"self",
".",
"_readline_prompt",
"if",
"readline",
"is",
"not",
"None",
"else",
"self",
".",
"_normal_prompt",
")",... | Runs the main input loop
:param session: Current shell session | [
"Runs",
"the",
"main",
"input",
"loop"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L190-L230 |
9,463 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.readline_completer | 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 | def readline_completer(self, text, state):
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 | [
"def",
"readline_completer",
"(",
"self",
",",
"text",
",",
"state",
")",
":",
"if",
"state",
"==",
"0",
":",
"# New completion, reset the list of matches and the display hook",
"self",
".",
"_readline_matches",
"=",
"[",
"]",
"try",
":",
"readline",
".",
"set_com... | A completer for the readline library | [
"A",
"completer",
"for",
"the",
"readline",
"library"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L232-L336 |
9,464 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.search_shell | 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 | def search_shell(self):
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",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_shell",
"is",
"not",
"None",
":",
"# A shell is already there",
"return",
"reference",
"=",
"self",
".",
"_context",
".",
"get_service_reference",
"(",
"SER... | Looks for a shell service | [
"Looks",
"for",
"a",
"shell",
"service"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L338-L349 |
9,465 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.service_changed | 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 | def service_changed(self, event):
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() | [
"def",
"service_changed",
"(",
"self",
",",
"event",
")",
":",
"kind",
"=",
"event",
".",
"get_kind",
"(",
")",
"reference",
"=",
"event",
".",
"get_service_reference",
"(",
")",
"if",
"kind",
"in",
"(",
"pelix",
".",
"ServiceEvent",
".",
"REGISTERED",
"... | Called by Pelix when an events changes | [
"Called",
"by",
"Pelix",
"when",
"an",
"events",
"changes"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L351-L368 |
9,466 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.set_shell | 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 | def set_shell(self, svc_ref):
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() | [
"def",
"set_shell",
"(",
"self",
",",
"svc_ref",
")",
":",
"if",
"svc_ref",
"is",
"None",
":",
"return",
"with",
"self",
".",
"_lock",
":",
"# Get the service",
"self",
".",
"_shell_ref",
"=",
"svc_ref",
"self",
".",
"_shell",
"=",
"self",
".",
"_context... | Binds the given shell service.
:param svc_ref: A service reference | [
"Binds",
"the",
"given",
"shell",
"service",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L370-L389 |
9,467 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.clear_shell | 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 | def clear_shell(self):
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 | [
"def",
"clear_shell",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"# Clear the flag",
"self",
".",
"_shell_event",
".",
"clear",
"(",
")",
"# Clear the readline completer",
"if",
"readline",
"is",
"not",
"None",
":",
"readline",
".",
"set_complet... | Unbinds the active shell service | [
"Unbinds",
"the",
"active",
"shell",
"service"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L391-L409 |
9,468 | tcalmant/ipopo | pelix/shell/console.py | InteractiveShell.stop | 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 | def stop(self):
# 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 | [
"def",
"stop",
"(",
"self",
")",
":",
"# Exit the loop",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_stop_event",
".",
"set",
"(",
")",
"self",
".",
"_shell_event",
".",
"clear",
"(",
")",
"if",
"self",
".",
"_context",
"is",
"not",
"None",
":"... | Clears all members | [
"Clears",
"all",
"members"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L411-L426 |
9,469 | tcalmant/ipopo | pelix/remote/json_rpc.py | _JsonRpcServlet.do_POST | 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 | def do_POST(self, request, response):
# 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, "application/json-rpc")
except Exception as ex:
response.send_content(
500, "Internal error:\n{0}\n".format(ex), "text/plain"
) | [
"def",
"do_POST",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# pylint: disable=C0103",
"try",
":",
"# Get the request content",
"data",
"=",
"to_str",
"(",
"request",
".",
"read_data",
"(",
")",
")",
"# Dispatch",
"result",
"=",
"self",
".",
"_... | Handles a HTTP POST request
:param request: The HTTP request bean
:param response: The HTTP response handler | [
"Handles",
"a",
"HTTP",
"POST",
"request"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/json_rpc.py#L115-L135 |
9,470 | tcalmant/ipopo | pelix/ipopo/handlers/requires.py | _RuntimeDependency.service_changed | 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 | def service_changed(self, event):
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()) | [
"def",
"service_changed",
"(",
"self",
",",
"event",
")",
":",
"if",
"(",
"self",
".",
"_ipopo_instance",
"is",
"None",
"or",
"not",
"self",
".",
"_ipopo_instance",
".",
"check_event",
"(",
"event",
")",
")",
":",
"# stop() and clean() may have been called after... | Called by the framework when a service event occurs | [
"Called",
"by",
"the",
"framework",
"when",
"a",
"service",
"event",
"occurs"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L282-L312 |
9,471 | tcalmant/ipopo | pelix/ipopo/handlers/requires.py | _RuntimeDependency.start | def start(self):
"""
Starts the dependency manager
"""
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
) | python | def start(self):
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_context",
".",
"add_service_listener",
"(",
"self",
",",
"self",
".",
"requirement",
".",
"filter",
",",
"self",
".",
"requirement",
".",
"specification",
")"
] | Starts the dependency manager | [
"Starts",
"the",
"dependency",
"manager"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L314-L320 |
9,472 | tcalmant/ipopo | pelix/misc/log.py | LogReaderService._store_entry | 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 | def _store_entry(self, entry):
# 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) | [
"def",
"_store_entry",
"(",
"self",
",",
"entry",
")",
":",
"# Get the logger and log the message",
"self",
".",
"__logs",
".",
"append",
"(",
"entry",
")",
"# Notify listeners",
"for",
"listener",
"in",
"self",
".",
"__listeners",
".",
"copy",
"(",
")",
":",
... | Stores a new log entry and notifies listeners
:param entry: A LogEntry object | [
"Stores",
"a",
"new",
"log",
"entry",
"and",
"notifies",
"listeners"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L241-L270 |
9,473 | tcalmant/ipopo | pelix/misc/log.py | LogServiceInstance.log | 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 | def log(self, level, message, exc_info=None, reference=None):
# 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:
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) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"message",
",",
"exc_info",
"=",
"None",
",",
"reference",
"=",
"None",
")",
":",
"# pylint: disable=W0212",
"if",
"not",
"isinstance",
"(",
"reference",
",",
"pelix",
".",
"framework",
".",
"ServiceReference",
... | 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 | [
"Logs",
"a",
"message",
"possibly",
"with",
"an",
"exception"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L289-L316 |
9,474 | tcalmant/ipopo | pelix/misc/log.py | LogServiceFactory._bundle_from_module | 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 | def _bundle_from_module(self, module_object):
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",
")",
":",
"try",
":",
"# Get the module name",
"module_object",
"=",
"module_object",
".",
"__name__",
"except",
"AttributeError",
":",
"# We got a string",
"pass",
"return",
"self",
".",
"_framework",
... | Find the bundle associated to a module
:param module_object: A Python module object
:return: The Bundle object associated to the module, or None | [
"Find",
"the",
"bundle",
"associated",
"to",
"a",
"module"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L334-L348 |
9,475 | tcalmant/ipopo | pelix/misc/log.py | LogServiceFactory.emit | 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 | def emit(self, record):
# 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",
")",
":",
"# pylint: disable=W0212",
"# Get the bundle",
"bundle",
"=",
"self",
".",
"_bundle_from_module",
"(",
"record",
".",
"module",
")",
"# Convert to a LogEntry",
"entry",
"=",
"LogEntry",
"(",
"record",
".",
"le... | Handle a message logged with the logger
:param record: A log record | [
"Handle",
"a",
"message",
"logged",
"with",
"the",
"logger"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L350-L364 |
9,476 | tcalmant/ipopo | pelix/services/mqtt.py | _MqttConnection.publish | 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 | def publish(self, topic, payload, qos=0, retain=False):
# TODO: check (full transmission) success
return self._client.publish(topic, payload, qos, retain) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"payload",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"# TODO: check (full transmission) success",
"return",
"self",
".",
"_client",
".",
"publish",
"(",
"topic",
",",
"payload",
",",
"qos... | Publishes an MQTT message | [
"Publishes",
"an",
"MQTT",
"message"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/mqtt.py#L487-L492 |
9,477 | tcalmant/ipopo | pelix/ipopo/handlers/requiresmap.py | AggregateDependency.__store_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
"""
self._future_value.setdefault(key, []).append(service) | python | def __store_service(self, key, service):
self._future_value.setdefault(key, []).append(service) | [
"def",
"__store_service",
"(",
"self",
",",
"key",
",",
"service",
")",
":",
"self",
".",
"_future_value",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
".",
"append",
"(",
"service",
")"
] | Stores the given service in the dictionary
:param key: Dictionary key
:param service: Service to add to the dictionary | [
"Stores",
"the",
"given",
"service",
"in",
"the",
"dictionary"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L521-L528 |
9,478 | tcalmant/ipopo | pelix/ipopo/handlers/requiresmap.py | AggregateDependency.__remove_service | 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 | def __remove_service(self, key, service):
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 | [
"def",
"__remove_service",
"(",
"self",
",",
"key",
",",
"service",
")",
":",
"try",
":",
"# Remove the injected service",
"prop_services",
"=",
"self",
".",
"_future_value",
"[",
"key",
"]",
"prop_services",
".",
"remove",
"(",
"service",
")",
"# Clean up",
"... | Removes the given service from the future dictionary
:param key: Dictionary key
:param service: Service to remove from the dictionary | [
"Removes",
"the",
"given",
"service",
"from",
"the",
"future",
"dictionary"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L530-L549 |
9,479 | tcalmant/ipopo | pelix/ipopo/handlers/requiresmap.py | AggregateDependency.get_value | 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 | def get_value(self):
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",
")",
":",
"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",
"... | Retrieves the value to inject in the component
:return: The value to inject | [
"Retrieves",
"the",
"value",
"to",
"inject",
"in",
"the",
"component"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L551-L564 |
9,480 | tcalmant/ipopo | pelix/rsa/remoteserviceadmin.py | ExportRegistrationImpl.match_sr | 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 | def match_sr(self, svc_ref, cid=None):
# 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
our_cid = self.get_export_container_id()
if our_cid is None:
return False
return sr_compare and our_cid == cid | [
"def",
"match_sr",
"(",
"self",
",",
"svc_ref",
",",
"cid",
"=",
"None",
")",
":",
"# type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool",
"with",
"self",
".",
"__lock",
":",
"our_sr",
"=",
"self",
".",
"get_reference",
"(",
")",
"if",
"our_sr",
"is",
... | 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 | [
"Checks",
"if",
"this",
"export",
"registration",
"matches",
"the",
"given",
"service",
"reference"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L886-L908 |
9,481 | tcalmant/ipopo | pelix/rsa/remoteserviceadmin.py | ExportRegistrationImpl.get_exception | 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 | def get_exception(self):
# 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",
")",
":",
"# type: () -> Optional[Tuple[Any, Any, Any]]",
"with",
"self",
".",
"__lock",
":",
"return",
"(",
"self",
".",
"__updateexception",
"if",
"self",
".",
"__updateexception",
"or",
"self",
".",
"__closed",
"else",
"self... | Returns the exception associated to the export
:return: An exception tuple, if any | [
"Returns",
"the",
"exception",
"associated",
"to",
"the",
"export"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L970-L982 |
9,482 | tcalmant/ipopo | pelix/rsa/remoteserviceadmin.py | ExportRegistrationImpl.close | 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 | def close(self):
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 | [
"def",
"close",
"(",
"self",
")",
":",
"publish",
"=",
"False",
"exporterid",
"=",
"rsid",
"=",
"exception",
"=",
"export_ref",
"=",
"ed",
"=",
"None",
"with",
"self",
".",
"__lock",
":",
"if",
"not",
"self",
".",
"__closed",
":",
"exporterid",
"=",
... | Cleans up the export endpoint | [
"Cleans",
"up",
"the",
"export",
"endpoint"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L1026-L1055 |
9,483 | tcalmant/ipopo | pelix/rsa/providers/discovery/__init__.py | EndpointAdvertiser.advertise_endpoint | 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 | def advertise_endpoint(self, endpoint_description):
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 | [
"def",
"advertise_endpoint",
"(",
"self",
",",
"endpoint_description",
")",
":",
"endpoint_id",
"=",
"endpoint_description",
".",
"get_id",
"(",
")",
"with",
"self",
".",
"_published_endpoints_lock",
":",
"if",
"self",
".",
"get_advertised_endpoint",
"(",
"endpoint_... | 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) | [
"Advertise",
"and",
"endpoint_description",
"for",
"remote",
"discovery",
".",
"If",
"it",
"hasn",
"t",
"already",
"been",
"a",
"endpoint_description",
"will",
"be",
"advertised",
"via",
"a",
"some",
"protocol",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/discovery/__init__.py#L77-L98 |
9,484 | tcalmant/ipopo | pelix/rsa/providers/discovery/__init__.py | EndpointAdvertiser.update_endpoint | 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 | def update_endpoint(self, updated_ed):
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 | [
"def",
"update_endpoint",
"(",
"self",
",",
"updated_ed",
")",
":",
"endpoint_id",
"=",
"updated_ed",
".",
"get_id",
"(",
")",
"with",
"self",
".",
"_published_endpoints_lock",
":",
"if",
"self",
".",
"get_advertised_endpoint",
"(",
"endpoint_id",
")",
"is",
"... | 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) | [
"Update",
"a",
"previously",
"advertised",
"endpoint_description",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/discovery/__init__.py#L100-L120 |
9,485 | tcalmant/ipopo | pelix/ipopo/handlers/provides.py | ServiceRegistrationHandler._field_controller_generator | 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 | def _field_controller_generator(self):
# 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 | [
"def",
"_field_controller_generator",
"(",
"self",
")",
":",
"# Local variable, to avoid messing with \"self\"",
"stored_instance",
"=",
"self",
".",
"_ipopo_instance",
"def",
"get_value",
"(",
"self",
",",
"name",
")",
":",
"# pylint: disable=W0613",
"\"\"\"\n R... | Generates the methods called by the injected controller | [
"Generates",
"the",
"methods",
"called",
"by",
"the",
"injected",
"controller"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L154-L187 |
9,486 | tcalmant/ipopo | pelix/ipopo/handlers/provides.py | ServiceRegistrationHandler.on_controller_change | 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 | def on_controller_change(self, name, value):
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() | [
"def",
"on_controller_change",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"__controller",
"!=",
"name",
":",
"# Nothing to do",
"return",
"# Update the controller value",
"self",
".",
"__controller_on",
"=",
"value",
"if",
"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 | [
"Called",
"by",
"the",
"instance",
"manager",
"when",
"a",
"controller",
"value",
"has",
"been",
"modified"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L251-L270 |
9,487 | tcalmant/ipopo | pelix/ipopo/handlers/provides.py | ServiceRegistrationHandler.on_property_change | 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 | def on_property_change(self, name, old_value, new_value):
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",
")",
":",
"if",
"self",
".",
"_registration",
"is",
"not",
"None",
":",
"# use the registration to trigger the service event",
"self",
".",
"_registration",
".",
"set_properti... | 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 | [
"Called",
"by",
"the",
"instance",
"manager",
"when",
"a",
"component",
"property",
"is",
"modified"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L272-L282 |
9,488 | tcalmant/ipopo | pelix/ipopo/handlers/provides.py | ServiceRegistrationHandler._register_service | 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 | def _register_service(self):
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,
) | [
"def",
"_register_service",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_registration",
"is",
"None",
"and",
"self",
".",
"specifications",
"and",
"self",
".",
"__validated",
"and",
"self",
".",
"__controller_on",
")",
":",
"# Use a copy of component propert... | Registers the provided service, if possible | [
"Registers",
"the",
"provided",
"service",
"if",
"possible"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L302-L330 |
9,489 | tcalmant/ipopo | pelix/ipopo/handlers/provides.py | ServiceRegistrationHandler._unregister_service | 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 | def _unregister_service(self):
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 | [
"def",
"_unregister_service",
"(",
"self",
")",
":",
"if",
"self",
".",
"_registration",
"is",
"not",
"None",
":",
"# Ignore error",
"try",
":",
"self",
".",
"_registration",
".",
"unregister",
"(",
")",
"except",
"BundleException",
"as",
"ex",
":",
"# Only ... | Unregisters the provided service, if needed | [
"Unregisters",
"the",
"provided",
"service",
"if",
"needed"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L332-L354 |
9,490 | tcalmant/ipopo | pelix/utilities.py | use_service | 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 | def use_service(bundle_context, svc_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 | [
"def",
"use_service",
"(",
"bundle_context",
",",
"svc_reference",
")",
":",
"if",
"svc_reference",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Invalid ServiceReference\"",
")",
"try",
":",
"# Give the service",
"yield",
"bundle_context",
".",
"get_service",
"(... | 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 | [
"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",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L64-L88 |
9,491 | tcalmant/ipopo | pelix/utilities.py | SynchronizedClassMethod | 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 | def SynchronizedClassMethod(*locks_attr_names, **kwargs):
# 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"]:
# 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 | [
"def",
"SynchronizedClassMethod",
"(",
"*",
"locks_attr_names",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C1801",
"# Filter the names (remove empty ones)",
"locks_attr_names",
"=",
"[",
"lock_name",
"for",
"lock_name",
"in",
"locks_attr_names",
"if",
"lock_nam... | 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 | [
"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",
"."
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L250-L326 |
9,492 | tcalmant/ipopo | pelix/utilities.py | is_lock | 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 | def is_lock(lock):
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",
")",
":",
"if",
"lock",
"is",
"None",
":",
"# Don't do useless tests",
"return",
"False",
"for",
"attr",
"in",
"\"acquire\"",
",",
"\"release\"",
",",
"\"__enter__\"",
",",
"\"__exit__\"",
":",
"if",
"not",
"hasattr",
"(",
"loc... | Tests if the given lock is an instance of a lock class | [
"Tests",
"if",
"the",
"given",
"lock",
"is",
"an",
"instance",
"of",
"a",
"lock",
"class"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L329-L343 |
9,493 | tcalmant/ipopo | pelix/utilities.py | remove_duplicates | 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 | def remove_duplicates(items):
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",
")",
":",
"if",
"items",
"is",
"None",
":",
"return",
"items",
"new_list",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"not",
"in",
"new_list",
":",
"new_list",
".",
"append",
"(",
"item",
... | Returns a list without duplicates, keeping elements order
:param items: A list of items
:return: The list without duplicates, in the same order | [
"Returns",
"a",
"list",
"without",
"duplicates",
"keeping",
"elements",
"order"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L373-L387 |
9,494 | tcalmant/ipopo | pelix/utilities.py | add_listener | 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 | def add_listener(registry, listener):
if listener is None or listener in registry:
return False
registry.append(listener)
return True | [
"def",
"add_listener",
"(",
"registry",
",",
"listener",
")",
":",
"if",
"listener",
"is",
"None",
"or",
"listener",
"in",
"registry",
":",
"return",
"False",
"registry",
".",
"append",
"(",
"listener",
")",
"return",
"True"
] | 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 | [
"Adds",
"a",
"listener",
"in",
"the",
"registry",
"if",
"it",
"is",
"not",
"yet",
"in"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L393-L405 |
9,495 | tcalmant/ipopo | pelix/utilities.py | remove_listener | 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 | def remove_listener(registry, listener):
if listener is not None and listener in registry:
registry.remove(listener)
return True
return False | [
"def",
"remove_listener",
"(",
"registry",
",",
"listener",
")",
":",
"if",
"listener",
"is",
"not",
"None",
"and",
"listener",
"in",
"registry",
":",
"registry",
".",
"remove",
"(",
"listener",
")",
"return",
"True",
"return",
"False"
] | 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 | [
"Removes",
"a",
"listener",
"from",
"the",
"registry"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L408-L420 |
9,496 | tcalmant/ipopo | pelix/utilities.py | to_iterable | 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 | def to_iterable(value, allow_none=True):
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",
")",
":",
"if",
"value",
"is",
"None",
":",
"# None given",
"if",
"allow_none",
":",
"return",
"None",
"return",
"[",
"]",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"t... | 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 | [
"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",
... | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L551-L574 |
9,497 | tcalmant/ipopo | pelix/utilities.py | Deprecated.__log | 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 | def __log(self, method_name):
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 | [
"def",
"__log",
"(",
"self",
",",
"method_name",
")",
":",
"if",
"not",
"self",
".",
"__already_logged",
":",
"# Print only if not already done",
"stack",
"=",
"\"\\n\\t\"",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
")",
")",
"logging",
".",
"... | Logs the deprecation message on first call, does nothing after
:param method_name: Name of the deprecated method | [
"Logs",
"the",
"deprecation",
"message",
"on",
"first",
"call",
"does",
"nothing",
"after"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L177-L190 |
9,498 | tcalmant/ipopo | pelix/utilities.py | CountdownEvent.step | 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 | def step(self):
# 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 counter has gone below 0")
return False | [
"def",
"step",
"(",
"self",
")",
":",
"# type: () -> bool",
"with",
"self",
".",
"__lock",
":",
"self",
".",
"__value",
"-=",
"1",
"if",
"self",
".",
"__value",
"==",
"0",
":",
"# All done",
"self",
".",
"__event",
".",
"set",
"(",
")",
"return",
"Tr... | 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 | [
"Decreases",
"the",
"internal",
"counter",
".",
"Raises",
"an",
"error",
"if",
"the",
"counter",
"goes",
"below",
"0"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L692-L711 |
9,499 | tcalmant/ipopo | pelix/shell/completion/pelix.py | BundleCompleter.display_hook | 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 | def display_hook(prompt, session, context, matches, longest_match_len):
# 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 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() | [
"def",
"display_hook",
"(",
"prompt",
",",
"session",
",",
"context",
",",
"matches",
",",
"longest_match_len",
")",
":",
"# type: (str, ShellSession, BundleContext, List[str], int) -> None",
"# Prepare a line pattern for each match",
"match_pattern",
"=",
"\"{{0: >{}}}: {{1}}\""... | 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 | [
"Displays",
"the",
"available",
"bundle",
"matches",
"and",
"the",
"bundle",
"name"
] | 2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/pelix.py#L71-L97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.