code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
"You really ought to, ya know..."
suggestions = [
"Um, might I suggest working now",
"Get to work",
(
"Between the coffee break, the smoking break, the lunch break, "
"the tea break, the bagel break, and the water cooler break, "
"may I suggest a work break. It’s when you do some work"
),
"Work faster",
"I didn’t realize we paid people for doing that",
"You aren't being paid to believe in the power of your dreams",
]
suggestion = random.choice(suggestions)
rest = rest.strip()
if rest:
karma.Karma.store.change(rest, -1)
suggestion = suggestion + ', %s' % rest
else:
karma.Karma.store.change(channel, -1)
karma.Karma.store.change(nick, -1)
return suggestion
|
def gettowork(channel, nick, rest)
|
You really ought to, ya know...
| 7.794518
| 6.68408
| 1.166132
|
"It really is, ya know..."
rest = rest.strip()
if rest:
karma.Karma.store.change(rest, -1)
else:
karma.Karma.store.change(channel, -1)
rest = "foo'"
advice = 'Quiet bitching is useless, %s. Do something about it.' % rest
return advice
|
def bitchingisuseless(channel, rest)
|
It really is, ya know...
| 9.181503
| 6.948979
| 1.321274
|
"Curse the day!"
if rest:
cursee = rest
else:
cursee = 'the day'
karma.Karma.store.change(cursee, -1)
return "/me curses %s!" % cursee
|
def curse(rest)
|
Curse the day!
| 8.784603
| 7.136934
| 1.230865
|
"Stab, shank or shiv some(one|thing)!"
if rest:
stabee = rest
else:
stabee = 'wildly at anything'
if random.random() < 0.9:
karma.Karma.store.change(stabee, -1)
weapon = random.choice(phrases.weapon_opts)
weaponadj = random.choice(phrases.weapon_adjs)
violentact = random.choice(phrases.violent_acts)
return "/me grabs a %s %s and %s %s!" % (
weaponadj, weapon, violentact, stabee)
elif random.random() < 0.6:
karma.Karma.store.change(stabee, -1)
return (
"/me is going to become rich and famous after i invent a "
"device that allows you to stab people in the face over the "
"internet")
else:
karma.Karma.store.change(nick, -1)
return (
"/me turns on its master and shivs %s. This is reality man, "
"and you never know what you're going to get!" % nick)
|
def stab(nick, rest)
|
Stab, shank or shiv some(one|thing)!
| 6.669869
| 5.445014
| 1.22495
|
"Disembowel some(one|thing)!"
if rest:
stabee = rest
karma.Karma.store.change(stabee, -1)
else:
stabee = "someone nearby"
return (
"/me takes %s, brings them down to the basement, ties them to a "
"leaky pipe, and once bored of playing with them mercifully "
"ritually disembowels them..." % stabee)
|
def disembowel(rest)
|
Disembowel some(one|thing)!
| 16.730244
| 12.955549
| 1.291357
|
"Embowel some(one|thing)!"
if rest:
stabee = rest
karma.Karma.store.change(stabee, 1)
else:
stabee = "someone nearby"
return (
"/me (wearing a bright pink cape and yellow tights) swoops in "
"through an open window, snatches %s, races out of the basement, "
"takes them to the hospital with entrails on ice, and mercifully "
"embowels them, saving the day..." % stabee)
|
def embowel(rest)
|
Embowel some(one|thing)!
| 18.758465
| 15.098964
| 1.242368
|
"Chain some(one|thing) down."
chainee = rest or "someone nearby"
if chainee == 'cperry':
tmpl = "/me ties the chains extra tight around {chainee}"
elif random.random() < .9:
tmpl = (
"/me chains {chainee} to the nearest desk. "
"you ain't going home, buddy."
)
else:
karma.Karma.store.change(nick, -1)
tmpl = (
"/me spins violently around and chains {nick} to the nearest "
"desk. your days of chaining people down and stomping on their "
"dreams are over! get a life, you miserable beast."
)
return tmpl.format_map(locals())
|
def chain(rest, nick)
|
Chain some(one|thing) down.
| 12.644506
| 10.346512
| 1.222103
|
"Bless the day!"
if rest:
blesse = rest
else:
blesse = 'the day'
karma.Karma.store.change(blesse, 1)
return "/me blesses %s!" % blesse
|
def bless(rest)
|
Bless the day!
| 9.040388
| 7.487525
| 1.207393
|
"Pass the buck!"
if rest:
blamee = rest
else:
blamee = channel
karma.Karma.store.change(nick, -1)
if random.randint(1, 10) == 1:
yield "/me jumps atop the chair and points back at %s." % nick
yield (
"stop blaming the world for your problems, you bitter, "
"two-faced sissified monkey!"
)
else:
yield (
"I blame %s for everything! it's your fault! "
"it's all your fault!!" % blamee
)
yield "/me cries and weeps in despair"
|
def blame(channel, rest, nick)
|
Pass the buck!
| 10.697937
| 9.389543
| 1.139346
|
"Perform a basic calculation"
mo = calc_exp.match(rest)
if mo:
try:
return str(eval(rest))
except Exception:
return "eval failed... check your syntax"
else:
return "misformatted arithmetic!"
|
def calc(rest)
|
Perform a basic calculation
| 7.688112
| 6.897658
| 1.114597
|
"Define a word"
word = rest.strip()
res = util.lookup(word)
fmt = (
'{lookup.provider} says: {res}' if res else
"{lookup.provider} does not have a definition for that.")
return fmt.format(**dict(locals(), lookup=util.lookup))
|
def define(rest)
|
Define a word
| 8.479278
| 7.195489
| 1.178416
|
"Define a word with Urban Dictionary"
word = rest.strip()
definition = util.urban_lookup(word)
if not definition:
return "Arg! I didn't find a definition for that."
return 'Urban Dictionary says {word}: {definition}'.format(**locals())
|
def urbandict(rest)
|
Define a word with Urban Dictionary
| 6.334006
| 5.24493
| 1.207643
|
"Look up an acronym"
word = rest.strip()
res = util.lookup_acronym(word)
if res is None:
return "Arg! I couldn't expand that..."
else:
return ' | '.join(res)
|
def acit(rest)
|
Look up an acronym
| 7.59467
| 5.860693
| 1.295866
|
"Pit two sworn enemies against each other (separate with 'vs.')"
if rest:
vtype = random.choice(phrases.fight_victories)
fdesc = random.choice(phrases.fight_descriptions)
# valid separators are vs., v., and vs
pattern = re.compile('(.*) (?:vs[.]?|v[.]) (.*)')
matcher = pattern.match(rest)
if not matcher:
karma.Karma.store.change(nick.lower(), -1)
args = (vtype, nick, fdesc)
return "/me %s %s in %s for bad protocol." % args
contenders = [c.strip() for c in matcher.groups()]
random.shuffle(contenders)
winner, loser = contenders
karma.Karma.store.change(winner, 1)
karma.Karma.store.change(loser, -1)
return "%s %s %s in %s." % (winner, vtype, loser, fdesc)
|
def fight(nick, rest)
|
Pit two sworn enemies against each other (separate with 'vs.')
| 5.414243
| 4.139887
| 1.307824
|
"Display the progress of something: start|end|percent"
if rest:
left, right, amount = [piece.strip() for piece in rest.split('|')]
ticks = min(int(round(float(amount) / 10)), 10)
bar = "=" * ticks
return "%s [%-10s] %s" % (left, bar, right)
|
def progress(rest)
|
Display the progress of something: start|end|percent
| 6.064472
| 3.927841
| 1.543971
|
recipient = ""
if rest:
recipient = rest.strip()
karma.Karma.store.change(recipient, -1)
return util.passagg(recipient, nick.lower())
|
def nastygram(nick, rest)
|
A random passive-agressive comment, optionally directed toward
some(one|thing).
| 14.609623
| 16.633699
| 0.878315
|
"Sincerely apologize"
if rest:
rest = rest.strip()
if rest:
return random.choice(phrases.direct_apologies) % dict(a=nick, b=rest)
else:
return random.choice(phrases.apologies) % dict(a=nick)
|
def meaculpa(nick, rest)
|
Sincerely apologize
| 4.938
| 3.884319
| 1.271265
|
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadata.version(pkg)
|
def version(rest)
|
Get the version of pmxbot or one of its plugins
| 7.841941
| 4.038473
| 1.941809
|
if ' in ' in rest:
dstr, tzname = rest.split(' in ', 1)
else:
dstr, tzname = rest, 'UTC'
tzobj = TZINFOS[tzname.strip()]
dt = dateutil.parser.parse(dstr, tzinfos=TZINFOS)
if dt.tzinfo is None:
dt = pytz.UTC.localize(dt)
res = dt.astimezone(tzobj)
return '{} {} -> {} {}'.format(
dt.strftime('%H:%M'), dt.tzname() or dt.strftime('%z'),
res.strftime('%H:%M'), tzname)
|
def timezone(rest)
|
Convert date between timezones.
Example:
> !tz 11:00am UTC in PDT
11:00 UTC -> 4:00 PDT
UTC is implicit
> !tz 11:00am in PDT
11:00 UTC -> 4:00 PDT
> !tz 11:00am PDT
11:00 PDT -> 18:00 UTC
| 2.78754
| 2.657511
| 1.048929
|
"Delete the various persistence objects"
for finalizer in cls._finalizers:
try:
finalizer()
except Exception:
log.exception("Error in finalizer %s", finalizer)
|
def finalize(cls)
|
Delete the various persistence objects
| 5.238894
| 3.531627
| 1.483422
|
rs = rest.strip()
if rs:
# give help for matching commands
for handler in Handler._registry:
if handler.name == rs.lower():
yield '!%s: %s' % (handler.name, handler.doc)
break
else:
yield "command not found"
return
# give help for all commands
def mk_entries():
handlers = (
handler
for handler in Handler._registry
if type(handler) is pmxbot.core.CommandHandler
)
handlers = sorted(handlers, key=operator.attrgetter('name'))
for handler in handlers:
res = "!" + handler.name
if handler.aliases:
alias_names = (alias.name for alias in handler.aliases)
res += " (%s)" % ', '.join(alias_names)
yield res
o = io.StringIO(" ".join(mk_entries()))
more = o.read(160)
while more:
yield more
time.sleep(0.3)
more = o.read(160)
|
def help(rest)
|
Help (this command)
| 3.358925
| 3.33201
| 1.008078
|
year, month = month.split('-')
return '{month_name}, {year}'.format(
month_name=calendar.month_name[int(month)],
year=year,
)
|
def pmon(month)
|
P the month
>>> print(pmon('2012-08'))
August, 2012
| 3.061606
| 3.183478
| 0.961717
|
year, month, day = map(int, dayfmt.split('-'))
return '{day} the {number}'.format(
day=calendar.day_name[calendar.weekday(year, month, day)],
number=inflect.engine().ordinal(day),
)
|
def pday(dayfmt)
|
P the day
>>> print(pday('2012-08-24'))
Friday the 24th
| 3.753029
| 3.46869
| 1.081973
|
if 'web_host' in config:
config['host'] = config.pop('web_host')
if 'web_port' in config:
config['port'] = config.pop('web_port')
|
def patch_compat(config)
|
Support older config values.
| 2.249855
| 2.087304
| 1.077876
|
path = importlib_resources.path('pmxbot.web.templates', filename)
return str(mgr.enter_context(path))
|
def resolve_file(mgr, filename)
|
Given a file manager (ExitStack), load the filename
and set the exit stack to clean up. See
https://importlib-resources.readthedocs.io/en/latest/migration.html#pkg-resources-resource-filename
for more details.
| 14.630157
| 11.558164
| 1.265786
|
month, year = month_string.split(',')
month_ord = cls.month_ordinal[month]
return year, month_ord
|
def date_key(cls, month_string)
|
Return a key suitable for sorting by month.
>>> k1 = ChannelPage.date_key('September, 2012')
>>> k2 = ChannelPage.date_key('August, 2013')
>>> k2 > k1
True
| 5.383239
| 8.452925
| 0.636849
|
time_s, sep, nick = fragment.rpartition('.')
time = datetime.datetime.strptime(time_s, '%H.%M.%S')
date = datetime.datetime.strptime(date_s, '%Y-%m-%d')
dt = datetime.datetime.combine(date, time.time())
loc_dt = self.timezone.localize(dt)
utc_dt = loc_dt.astimezone(pytz.utc)
url_tmpl = '/day/{channel}/{target_date}#{target_time}.{nick}'
url = url_tmpl.format(
target_date=utc_dt.date().isoformat(),
target_time=utc_dt.time().strftime('%H.%M.%S'),
**locals()
)
raise cherrypy.HTTPRedirect(url, 301)
|
def forward(self, channel, date_s, fragment)
|
Given an HREF in the legacy timezone, redirect to an href for UTC.
| 2.934546
| 2.80167
| 1.047427
|
"Parse a date from sqlite. Assumes the date is in US/Pacific time zone."
dt = record.pop('datetime')
fmts = [
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
]
for fmt in fmts:
try:
dt = datetime.datetime.strptime(dt, fmt)
break
except ValueError:
pass
else:
raise
tz = pytz.timezone('US/Pacific')
loc_dt = tz.localize(dt)
record['datetime'] = loc_dt
return record
|
def parse_date(record)
|
Parse a date from sqlite. Assumes the date is in US/Pacific time zone.
| 2.532123
| 1.922221
| 1.31729
|
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how many? Argument must be a positive integer."
raise StopIteration
count = int(rest)
try:
struck = Logger.store.strike(channel, nick, count)
tmpl = (
"Isn't undo great? Last %d statement%s "
"by %s were stricken from the record."
)
yield tmpl % (struck, 's' if struck > 1 else '', nick)
except Exception:
traceback.print_exc()
yield "Hmm.. I didn't find anything of yours to strike!"
|
def strike(channel, nick, rest)
|
Strike last <n> statements from the record
| 6.162432
| 5.149962
| 1.196598
|
"When did pmxbot last see <nick> speak?"
onick = rest.strip()
last = Logger.store.last_seen(onick)
if last:
tm, chan = last
tmpl = "I last saw {onick} speak at {tm} in channel #{chan}"
return tmpl.format(tm=tm, chan=chan, onick=onick)
else:
return "Sorry! I don't have any record of %s speaking" % onick
|
def where(channel, nick, rest)
|
When did pmxbot last see <nick> speak?
| 7.617095
| 4.674903
| 1.629359
|
"Where can one find the logs?"
default_url = 'http://' + socket.getfqdn()
base = pmxbot.config.get('logs URL', default_url)
logged_channel = channel in pmxbot.config.log_channels
path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
return urllib.parse.urljoin(base, path)
|
def logs(channel)
|
Where can one find the logs?
| 6.386255
| 5.210584
| 1.225631
|
words = [s.lower() for s in rest.split()]
if 'please' not in words:
return
include = 'stop' not in rest
existing = set(pmxbot.config.log_channels)
# add the channel if include, otherwise remove the channel
op = existing.union if include else existing.difference
pmxbot.config.log_channels = list(op([channel]))
|
def log(channel, rest)
|
Enable or disable logging for a channel;
use 'please' to start logging and 'stop please' to stop.
| 6.496044
| 5.362818
| 1.211312
|
"Keep a tab on the most recent message for each channel"
spec = dict(channel=doc['channel'])
doc['ref'] = logged_id
doc.pop('_id')
self._recent.replace_one(spec, doc, upsert=True)
|
def _add_recent(self, doc, logged_id)
|
Keep a tab on the most recent message for each channel
| 6.561939
| 3.96323
| 1.655705
|
coll = cls._get_collection(uri)
with ExceptionTrap(storage.pymongo.errors.OperationFailure) as trap:
coll.create_index([('message', 'text')], background=True)
return not trap
|
def _has_fulltext(cls, uri)
|
Enable full text search on the messages if possible and return True.
If the full text search cannot be enabled, then return False.
| 6.824576
| 5.571683
| 1.224868
|
user_id = self.slacker.users.get_user_id(username)
im = user_id and self.slacker.im.open(user_id).body['channel']['id']
return im and self.slack.server.channels.find(im)
|
def _find_user_channel(self, username)
|
Use slacker to resolve the username to an opened IM channel
| 3.810034
| 3.014658
| 1.263836
|
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)
|
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.
| 5.935711
| 5.467466
| 1.085642
|
total = sum(d.values())
target = random.random() * total
# elect the first item which pushes the count over target
count = 0
for word, proportion in d.items():
count += proportion
if count > target:
return word
|
def wchoice(d)
|
Given a dictionary of word: proportion, return a word randomly selected
from the keys weighted by proportion.
>>> wchoice({'a': 0, 'b': 1})
'b'
>>> choices = [wchoice({'a': 1, 'b': 2}) for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / choices.count('b')
>>> .4 < ratio < .6
True
| 5.142322
| 5.260158
| 0.977598
|
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)
|
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']
| 6.913889
| 7.343578
| 0.941488
|
'''
Get a definition for a word (uses Wordnik)
'''
_patch_wordnik()
# Jason's key - do not abuse
key = 'edc4b9b94b341eeae350e087c2e05d2f5a2a9e0478cefc6dc'
client = wordnik.swagger.ApiClient(key, 'http://api.wordnik.com/v4')
words = wordnik.WordApi.WordApi(client)
definitions = words.getDefinitions(word, limit=1)
if not definitions:
return
definition = definitions[0]
return str(definition.text)
|
def lookup(word)
|
Get a definition for a word (uses Wordnik)
| 7.295664
| 6.555001
| 1.112992
|
'''
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)
|
Return a Urban Dictionary definition for a word or None if no result was
found.
| 2.265284
| 1.700852
| 1.331852
|
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)
|
Generate a passive-aggressive statement to recipient from sender.
| 4.499917
| 4.506314
| 0.99858
|
"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)
|
Change the running config, something like a=b or a+=b or a-=b
| 3.008851
| 2.471642
| 1.217349
|
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)
|
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.
| 3.624385
| 3.508281
| 1.033094
|
rest = rest.strip()
if rest.startswith('add: ') or rest.startswith('add '):
quote_to_add = rest.split(' ', 1)[1]
Quotes.store.add(quote_to_add)
qt = False
return 'Quote added!'
if rest.startswith('del: ') or rest.startswith('del '):
cmd, sep, lookup = rest.partition(' ')
Quotes.store.delete(lookup)
return 'Deleted the sole quote that matched'
qt, i, n = Quotes.store.lookup(rest)
if not qt:
return
return '(%s/%s): %s' % (i, n, qt)
|
def quote(rest)
|
If passed with nothing then get a random quote. If passed with some
string then search for that. If prepended with "add:" then add it to the
db, eg "!quote add: drivers: I only work here because of pmxbot!".
Delete an individual quote by prepending "del:" and passing a search
matching exactly one query.
| 4.026294
| 3.860333
| 1.042991
|
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)
|
If exactly one quote matches, delete it. Otherwise,
raise a ValueError.
| 4.313572
| 4.086525
| 1.05556
|
indices = []
if index is None:
return indices
for atom in index.split(","):
atom = atom.strip()
if not atom:
continue
if (
(atom.startswith("'") and atom.endswith("'")) or
(atom.startswith('"') and atom.endswith('"'))
):
atom = atom[1:-1].lower()
for i, item in enumerate(items):
if atom in item.lower():
indices.append(i)
elif atom.startswith('/') and atom.endswith('/'):
atom = atom[1:-1]
for i, item in enumerate(items):
if re.search(atom, item):
indices.append(i)
elif ":" in atom:
start, end = [x.strip() for x in atom.split(":", 1)]
start = int(start) if start else 1
if start < 0:
start += len(items) + 1
end = int(end) if end else len(items)
if end < 0:
end += len(items) + 1
start -= 1 # Shift to Python 0-based indices
end -= 1 # Shift to Python 0-based indices
for i in range(start, end + 1):
indices.append(i)
elif atom == "first":
indices.append(0)
elif atom == "last":
indices.append(len(items) - 1)
else:
index = int(atom)
if index < 0:
index += len(items) + 1
index -= 1 # Shift to Python 0-based indices
indices.append(index)
return indices
|
def parse_index(index, items)
|
Return a list of 0-based index numbers from a (1-based) `index` str.
* A single item index, like `[3]`. Negative indices count backward from
the bottom; that is, the bottom-most item in a 3-item stack can be
identified by `[3]` or `[-1]`.
* A slice, shorthand for the entire inclusive range between two numbers,
like `[3:5]`. Either number may be negative, or omitted to mean 1 or -1,
respectively. If both are omitted as `[:]` then all items match.
* Any "text" surrounded by single or double-quotes, which matches any
item containing the text (case-insensitive).
* Any /text/ surrounded by forward-slashes, a regular expression
to match item content.
* The values "first" or "last" (without quotes).
* Any combination of the above, separated by commas; for example,
given a stack of items "1: red | 2: orange | 3: yellow | 4: green |
5: blue | 6: indigo | 7: violet", the index `[6, :2, "i"]` identifies
"6: indigo | 1: red | 2: orange | 7: violet". Note that "indigo"
matches both `[6]` and `["i"]`, but is only included once. However,
if the stack had another "8: indigo" entry, it would have been included.
| 1.767016
| 1.666196
| 1.060509
|
'Manage short lists in pmxbot. See !stack help for more info'
atoms = [atom.strip() for atom in rest.split(' ', 1) if atom.strip()]
if len(atoms) == 0:
subcommand = "show"
rest = ""
elif len(atoms) == 1:
subcommand = atoms[0]
rest = ""
else:
subcommand, rest = atoms
start = rest.find("[")
finish = rest.rfind("]")
sp = rest.find(" ")
if (
start != -1 and finish != -1 and start < finish and
(sp == -1 or start < sp)
):
topic, index = [atom.strip() for atom in rest[:finish].split("[", 1)]
if not topic:
topic = nick
new_item = rest[finish + 1:].strip()
else:
topic = nick
index = None
new_item = rest.strip()
if subcommand == "topics" or subcommand == "list":
items = Stack.store.get_topics()
items.sort()
else:
items = Stack.store.get_items(topic)
try:
indices = parse_index(index, items)
except ValueError:
return helpdoc["index"]
if debug:
print("SUBCOMMAND", subcommand.ljust(8), "TOPIC", topic.ljust(8),
"INDICES", str(indices).ljust(12), "ITEM", new_item)
if subcommand == "add":
if not new_item:
return ('!stack add <topic[index]> item: '
'You must provide an item to add.')
if not indices:
items.insert(0, new_item)
else:
for i in reversed(sorted(set(indices))):
if i >= len(items):
items.append(new_item)
else:
items.insert(i + 1, new_item)
Stack.store.save_items(topic, items)
elif subcommand == "pop":
if not indices:
indices = [0]
popped_items = [items.pop(i) for i in reversed(sorted(set(indices)))
if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output([("-", item) for item in reversed(popped_items)],
"(none popped)", pop=True)
elif subcommand == "show":
if new_item:
return helpdoc["show"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "shuffle":
if not indices:
random.shuffle(items)
else:
items = [items[i] for i in indices if len(items) > i >= 0]
Stack.store.save_items(topic, items)
return output(enumerate(items, 1))
elif subcommand == "topics" or subcommand == "list":
if new_item:
return helpdoc["topics"]
if not indices:
indices = range(len(items))
return output(
[(i + 1, items[i]) for i in indices if len(items) > i >= 0]
)
elif subcommand == "help":
return helpdoc.get(new_item, helpdoc["help"])
else:
return helpdoc["stack"]
|
def stack(nick, rest)
|
Manage short lists in pmxbot. See !stack help for more info
| 2.594954
| 2.45379
| 1.057529
|
if not pmxbot.config.get('use_ssl', False):
return lambda x: x
return importlib.import_module('ssl').wrap_socket
|
def _get_wrapper()
|
Get a socket wrapper based on SSL config.
| 9.045732
| 7.238229
| 1.249716
|
r
is_action, msg = self.action_pattern.match(msg).groups()
func = self._conn.action if is_action else self._conn.privmsg
try:
func(channel, msg)
return msg
except irc.client.MessageTooLong:
# some msgs will fail because they're too long
log.warning("Long message could not be transmitted: %s", msg)
except irc.client.InvalidCharacters:
tmpl = (
"Message contains carriage returns, "
"which aren't allowed in IRC messages: %r"
)
log.warning(tmpl, msg)
|
def transmit(self, channel, msg)
|
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').groups()
>>> bool(is_action)
True
>>> msg
'is feeling fine today'
| 4.965949
| 4.421504
| 1.123136
|
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)
|
Returns the code of the status or None if it does not exist
:return:
Status code of the response
| 2.652905
| 2.2872
| 1.159892
|
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)
|
Returns the message of the status or an empty string if it does not exist
:return:
Status message of the response
| 2.620225
| 2.317719
| 1.130519
|
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)
|
Returns the credit consumed by the request made
:return:
String with the number of credits consumed
| 3.700429
| 3.314255
| 1.116519
|
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)
|
Returns the remaining credits for the license key used after the request was made
:return:
String with remaining credits
| 3.431606
| 3.16369
| 1.084684
|
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)
|
Returns the results from the API without the status of the request
:return:
Dictionary with the results
| 5.281257
| 5.032423
| 1.049446
|
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)
|
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)
| 5.34553
| 4.606332
| 1.160474
|
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)
|
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).
| 2.953585
| 2.604635
| 1.133973
|
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)
|
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.
| 3.385695
| 3.33532
| 1.015103
|
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)
|
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.
| 5.600115
| 4.813409
| 1.163441
|
return sorted(self._get_crime_categories(date=date).values(),
key=lambda c: c.name)
|
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``).
| 5.393177
| 6.720433
| 0.802504
|
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)
|
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``).
| 3.775814
| 4.268553
| 0.884565
|
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)
|
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.
| 3.635143
| 2.994045
| 1.214124
|
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)
|
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).
| 3.434306
| 2.868786
| 1.197129
|
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)
|
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).
| 4.179801
| 3.356643
| 1.245232
|
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)
|
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.
| 3.123368
| 2.86273
| 1.091045
|
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)
|
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.
| 3.093782
| 2.58519
| 1.196733
|
scoreTagToString = ""
if scoreTag == "P+":
scoreTagToString = 'strong positive'
elif scoreTag == "P":
scoreTagToString = 'positive'
elif scoreTag == "NEU":
scoreTagToString = 'neutral'
elif scoreTag == "N":
scoreTagToString = 'negative'
elif scoreTag == "N+":
scoreTagToString = 'strong negative'
elif scoreTag == "NONE":
scoreTagToString = 'no sentiment'
return scoreTagToString
|
def scoreTagToString(self, scoreTag)
|
:param scoreTag:
:return:
| 2.148432
| 2.126667
| 1.010235
|
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)
|
This function is the target for RetroWrapper's internal
process and does all the work of communicating with the
environment.
| 6.483555
| 5.991402
| 1.082143
|
self._tx.put((RetroWrapper.symbol, attr, {}))
return self._rx.get()
|
def _ask_if_attr_is_callable(self, attr)
|
Returns whether or not the attribute is a callable.
| 37.373875
| 27.7127
| 1.348619
|
if "_tx" in self.__dict__ and "_proc" in self.__dict__:
self._tx.put(("close", (), {}))
self._proc.join()
|
def close(self)
|
Shutdown the environment.
| 6.006756
| 5.944719
| 1.010436
|
if not paramName:
raise ValueError('paramName cannot be empty')
self._params[paramName] = paramValue
|
def addParam(self, paramName, paramValue)
|
Add a parameter to the request
:param paramName:
Name of the parameter
:param paramValue:
Value of the parameter
| 4.858347
| 5.121237
| 0.948667
|
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)
|
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
| 4.021892
| 3.694613
| 1.088583
|
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="")
|
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
| 3.048484
| 3.018044
| 1.010086
|
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)
|
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
| 2.961593
| 2.886622
| 1.025972
|
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_)
|
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
| 4.632105
| 4.819508
| 0.961116
|
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)
|
Connection event listener
:param state: The new connection state
| 2.652813
| 2.781336
| 0.953791
|
self.__stop = False
self._queue.start()
self._zk.start()
|
def start(self)
|
Starts the connection
| 15.025349
| 16.083757
| 0.934194
|
self.__stop = True
self._queue.stop()
self._zk.stop()
|
def stop(self)
|
Stops the connection
| 12.408487
| 13.056355
| 0.950379
|
if path.startswith(self.__prefix):
return path
return "{}{}".format(self.__prefix, path)
|
def __path(self, path)
|
Adds the prefix to the given path
:param path: Z-Path
:return: Prefixed Z-Path
| 5.0018
| 4.736403
| 1.056033
|
return self._zk.create(
self.__path(path), data, ephemeral=ephemeral, sequence=sequence
)
|
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
| 4.010758
| 5.947437
| 0.674367
|
return self._zk.get(self.__path(path), watch=watch)
|
def get(self, path, watch=None)
|
Gets the content of a ZooKeeper node
:param path: Z-Path
:param watch: Watch method
| 7.395589
| 12.746575
| 0.580202
|
return self._zk.get_children(self.__path(path), watch=watch)
|
def get_children(self, path, watch=None)
|
Gets the list of children of a node
:param path: Z-Path
:param watch: Watch method
| 5.65314
| 11.317145
| 0.49952
|
return self._zk.set(self.__path(path), data)
|
def set(self, path, data)
|
Sets the content of a ZooKeeper node
:param path: Z-Path
:param data: New content
| 9.02185
| 17.174585
| 0.525302
|
# 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)
|
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
| 4.097022
| 4.559929
| 0.898484
|
# 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)
|
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
| 4.227484
| 4.40132
| 0.960504
|
# 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)
|
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
| 3.679107
| 3.520588
| 1.045027
|
# It's not a standard type, so it needs __jsonclass__
module_name = inspect.getmodule(obj).__name__
json_class = obj.__class__.__name__
if module_name not in ("", "__main__"):
json_class = "{0}.{1}".format(module_name, json_class)
return [json_class, []]
|
def _compute_jsonclass(obj)
|
Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field
| 4.326638
| 4.740028
| 0.912787
|
module_ = inspect.getmodule(obj)
if module_ in (None, builtins):
return True
return module_.__name__ in ("", "__main__")
|
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
| 4.845265
| 6.50495
| 0.744858
|
if not java_class:
return False
return (
JAVA_MAPS_PATTERN.match(java_class) is not None
or JAVA_LISTS_PATTERN.match(java_class) is not None
or JAVA_SETS_PATTERN.match(java_class) is not None
)
|
def _is_converted_class(java_class)
|
Checks if the given Java class is one we *might* have set up
| 2.763938
| 2.658427
| 1.039689
|
# 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)
|
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)
| 2.9679
| 2.9264
| 1.014181
|
if isinstance(request, (tuple, set, frozenset)):
# Special case : JSON arrays (Python lists)
return type(request)(from_jabsorb(element) for element in request)
elif isinstance(request, list):
# Check if we were a list or a tuple
if seems_raw:
return list(from_jabsorb(element) for element in request)
return tuple(from_jabsorb(element) for element in request)
elif isinstance(request, dict):
# Dictionary
java_class = request.get(JAVA_CLASS)
json_class = request.get(JSON_CLASS)
seems_raw = not java_class and not json_class
if java_class:
# Java Map ?
if JAVA_MAPS_PATTERN.match(java_class) is not None:
return HashableDict(
(from_jabsorb(key), from_jabsorb(value))
for key, value in request["map"].items()
)
# Java List ?
elif JAVA_LISTS_PATTERN.match(java_class) is not None:
return HashableList(
from_jabsorb(element) for element in request["list"]
)
# Java Set ?
elif JAVA_SETS_PATTERN.match(java_class) is not None:
return HashableSet(
from_jabsorb(element) for element in request["set"]
)
# Any other case
result = AttributeMap(
(from_jabsorb(key), from_jabsorb(value, seems_raw))
for key, value in request.items()
)
# Keep JSON class information as is
if json_class:
result[JSON_CLASS] = json_class
return result
elif not _is_builtin(request):
# Bean
for attr in dir(request):
# Only convert public fields
if not attr[0] == "_":
# Field conversion
setattr(request, attr, from_jabsorb(getattr(request, attr)))
return request
else:
# Any other case
return request
|
def from_jabsorb(request, seems_raw=False)
|
Transforms a jabsorb request into a more Python data model (converts maps
and lists)
:param request: Data coming from Jabsorb
:param seems_raw: Set it to True if the given data seems to already have
been parsed (no Java class hint). If True, the lists will
be kept as lists instead of being converted to tuples.
:return: A Python representation of the given data
| 2.586916
| 2.55552
| 1.012286
|
# type: () -> Requirement
return Requirement(
self.specification,
self.aggregate,
self.optional,
self.__original_filter,
self.immediate_rebind,
)
|
def copy(self)
|
Returns a copy of this instance
:return: A copy of this instance
| 15.345658
| 22.292412
| 0.68838
|
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)
|
Changes the current filter for the given one
:param props_filter: The new requirement filter on service properties
:raise TypeError: Unknown filter type
| 3.932158
| 3.885404
| 1.012033
|
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)
|
Deep copies the given object
:param data: Data to copy
:return: A copy of the data, if supported, else the data itself
| 2.773887
| 2.822551
| 0.982759
|
# 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)
|
Returns a deep copy of the current FactoryContext instance
:param inheritance: If True, current handlers configurations are stored
as inherited ones
| 6.397736
| 5.654735
| 1.131395
|
# 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)
|
Merges the inherited configuration with the current ones
:param excluded_handlers: Excluded handlers
| 3.0475
| 3.031688
| 1.005215
|
# 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)
|
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
| 5.010926
| 5.736519
| 0.873513
|
# 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)
|
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
| 4.885244
| 7.09309
| 0.688733
|
# type: () -> dict
# Copy properties
result = self.__hidden_properties.copy()
# Destroy the field
self.__hidden_properties.clear()
del self.__hidden_properties
return result
|
def grab_hidden_properties(self)
|
A one-shot access to hidden properties (the field is then destroyed)
:return: A copy of the hidden properties dictionary on the first call
:raise AttributeError: On any call after the first one
| 6.957349
| 6.475951
| 1.074336
|
# 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):
return properties.get(name)
def set_value(_, name, new_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)
|
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
| 4.617682
| 4.730289
| 0.976194
|
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)
|
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
| 3.118726
| 2.824875
| 1.104023
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.