rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
username = Option('urlgrab_username', 'Account name for URL posting') password = Option('urlgrab_password', 'Password for URL Posting') service = Option('urlgrab_service', 'URL Posting Service (delicious/faves)', 'delicious') | username = Option('username', 'Account name for URL posting') password = Option('password', 'Password for URL Posting') service = Option('service', 'URL Posting Service (delicious/faves)', 'delicious') | def __init__(self, url, channel, identity_id): self.url = url self.channel = channel self.identity_id = identity_id self.time = datetime.utcnow() |
@match(r'^(?:net(?:work)?\s+scan|nmap)\s+((?:[0-9]{1,2}\.){3}[0-9]{1,2})/([0-9]{1,2})$') | @match(r'^(?:net(?:work)?\s+scan|nmap)\s+((?:[0-9]{1,3}\.){3}[0-9]{1,3})/([0-9]{1,2})$') | def host_scan(self, event, host): if host.startswith('127.0.0.') or host.lower().startswith('localhost'): event.addresponse(u"I'm not allowed to inspect my host's internal interface.") return |
if airport[4] and airport[5]: | if airport[3] and airport[4]: | def airport_search(self, event, query): ids = self._airport_search(query) if len(ids) == 0: event.addresponse(u"Sorry, I don't know that airport") elif len(ids) == 1: id = ids[0] airport = self.airports[id] code = 'unknown code' if airport[4] and airport[5]: code = 'codes %s and %s' % (airport[3], airport[4]) elif airport[4]: code = 'code %s' % airport[3] elif airport[5]: code = 'code %s' % airport[4] event.addresponse(u'%s in %s, %s has %s' % (airport[0], airport[1], airport[2], code)) else: results = [] for id in ids: airport = self.airports[id] code = '' if airport[3] or airport[4]: code = ' (%s)' % u'/'.join(filter(lambda c: c, airport[3:5])) results.append('%s%s' % (airport[0], code)) event.addresponse(u'Found the following airports: %s', human_join(results)[:480]) |
code = 'code %s' % airport[3] elif airport[5]: | def airport_search(self, event, query): ids = self._airport_search(query) if len(ids) == 0: event.addresponse(u"Sorry, I don't know that airport") elif len(ids) == 1: id = ids[0] airport = self.airports[id] code = 'unknown code' if airport[4] and airport[5]: code = 'codes %s and %s' % (airport[3], airport[4]) elif airport[4]: code = 'code %s' % airport[3] elif airport[5]: code = 'code %s' % airport[4] event.addresponse(u'%s in %s, %s has %s' % (airport[0], airport[1], airport[2], code)) else: results = [] for id in ids: airport = self.airports[id] code = '' if airport[3] or airport[4]: code = ' (%s)' % u'/'.join(filter(lambda c: c, airport[3:5])) results.append('%s%s' % (airport[0], code)) event.addresponse(u'Found the following airports: %s', human_join(results)[:480]) | |
def test_complex_dict_response(self): | def test_complex_dict_with_kwargs_response(self): "Keyword arguments to addresponse override response dict values." | def test_complex_dict_response(self): ev = self._ev() self.assertEqual([], ev.responses) ev.addresponse({'reply': 'r1', 'target': 't1', 'source': 's1', 'address': 'a1', 'conflate': 'c1'}) ev.addresponse({'reply': 'r1', 'target': 't1', 'source': 's1', 'address': 'a1', 'conflate': 'c1'}, reply='r2', target='t2', source='s2', address='a2', conflate='c2') self.assertEqual([{'reply': 'r1', 'target': 't1', 'source': 's1', 'address': 'a1', 'conflate': 'c1'}, {'reply': 'r2', 'target': 't2', 'source': 's2', 'address': 'a2', 'conflate': 'c2'}], ev.responses) |
if not urlparse(url).scheme: up = True else: up = status < 400 | if url == urlparse(url).path and '/' not in url: up = True else: up = status < 400 | def _isitup(self, url): valid_url = self._makeurl(url) if Resolver is not None: r = Resolver() host = urlparse(valid_url).netloc.split(':')[0] try: response = r.query(host) except NoAnswer: return False, u'No DNS A/CNAME-records for that domain' except NXDOMAIN: return False, u'No such domain' |
@match(r'^weather\s+(?:(?:for|at|in)\s+)?(.+)$') | @match(r'^weather (?:(?:for|at|in) )?(.+)$') | def remote_forecast(self, place): soup = self._get_page(place) forecasts = [] table = [table for table in soup.findAll('table') if table.findAll('td', align='left')][0] |
@match(r'^forecast\s+(?:for\s+)?(.+)$') | @match(r'^(?:weather )forecast (?:for )?(.+)$') | def weather(self, event, place): try: values = self.remote_weather(place) event.addresponse(u'In %(place)s at %(time)s: %(temp)s; Humidity: %(humidity)s; Wind: %(wind)s; Conditions: %(conditions)s; Sunrise/set: %(sunrise)s/%(sunset)s; Moonrise/set: %(moonrise)s/%(moonset)s', values) except Weather.TooManyPlacesException, e: event.addresponse(u'Too many places match %(place)s: %(exception)s', { 'place': place, 'exception': human_join(e.args[0], separator=u';'), }) except Weather.WeatherException, e: event.addresponse(unicode(e)) |
else: | elif e.code == 500: | def update(self, event, service_name, id): service = self.services[service_name.lower()] try: event.addresponse(u'%(screen_name)s: "%(text)s"', self.remote_update(service, int(id))) except HTTPError, e: if e.code in (401, 403): event.addresponse(u'That %s is private', service['name']) elif e.code == 404: event.addresponse(u'No such %s', service['name']) else: event.addresponse(u'I can only see the Fail Whale') |
up, _, _ = self._isitup(url) | up, _ = self._isitup(url) | def _whensitup(self, event, url, delay, total_delay = 0): up, _, _ = self._isitup(url) if up: event.addresponse(u'%s is now up', self._makeurl(url)) return total_delay += delay if total_delay >= self.whensitup_maxperiod * 60 * 60: event.addresponse(u"Sorry, it appears %s is never coming up. I'm not going to check any more.", self._makeurl(url)) delay *= self.whensitup_factor delay = max(delay, self.whensitup_maxdelay) ibid.dispatcher.call_later(delay, self._whensitup, event, url, delay) |
if self._isitup(url): | up, _ = self._isitup(self._makeurl(url)) if up: | def whensitup(self, event, url): if self._isitup(url): event.addresponse(u'%s is up right now', self._makeurl(url)) return ibid.dispatcher.call_later(self.whensitup_delay, self._whensitup, event, url, self.whensitup_delay) event.addresponse(u"I'll let you know when %s is up", url) |
lines = [u'%(type)s event triggered' % exc_event.type] | lines = [u'%s event triggered' % exc_event.type] | def exception(self, event, kind): exc_event = last_exc_event if exc_event is None: event.addresponse(choice((u'Are you *looking* for trouble?', u"I'll make an exception for you."))) else: if kind.lower() == 'exception': try: lines = [u'%(type)s event "%(message)s" triggered ' % {'type': exc_event.type, 'message': exc_event.message['raw']}] except (KeyError, TypeError): lines = [u'%(type)s event triggered' % exc_event.type] |
exc_lock.acquire() try: last_exc_info = event.exc_info finally: exc_lock.release() | last_exc_info = event.exc_info | def process(self, event): global last_exc_info |
re.compile(r'^(%s)(?:[:;.?>!,-]|\s)+' % names, re.I | re.DOTALL), | re.compile(r'^(?P<nick>%s)(?:[:;.?>!,-]|\s)+(?P<body>.*)' % names, re.I | re.DOTALL), | def setup(self): names = '|'.join(re.escape(x) for x in self.names) verbs = '|'.join(re.escape(x) for x in self.verbs) self.patterns = [ re.compile(r'^(%s)(?:[:;.?>!,-]|\s)+' % names, re.I | re.DOTALL), # "hello there, bot"-style addressing. But we want to be sure that # there wasn't normal addressing too: re.compile(r'^(?:\S+:.*|.*,\s*(%s))\s*$' % names, re.I | re.DOTALL) ] self.verb_pattern = re.compile(r'^(?:%s)\s+(?:%s)\s+' % (names, verbs), re.I | re.DOTALL) |
re.compile(r'^(?:\S+:.*|.*,\s*(%s))\s*$' % names, re.I | re.DOTALL) | re.compile(r'^(?:\S+:.*|(?P<body>.*),\s*(?P<nick>%s))\s*$' % names, re.I | re.DOTALL) | def setup(self): names = '|'.join(re.escape(x) for x in self.names) verbs = '|'.join(re.escape(x) for x in self.verbs) self.patterns = [ re.compile(r'^(%s)(?:[:;.?>!,-]|\s)+' % names, re.I | re.DOTALL), # "hello there, bot"-style addressing. But we want to be sure that # there wasn't normal addressing too: re.compile(r'^(?:\S+:.*|.*,\s*(%s))\s*$' % names, re.I | re.DOTALL) ] self.verb_pattern = re.compile(r'^(?:%s)\s+(?:%s)\s+' % (names, verbs), re.I | re.DOTALL) |
if matches and matches.group(1): new_message = pattern.sub('', event.message['stripped']) event.addressed = matches.group(1) | if matches and matches.group('nick'): new_message = matches.group('body') event.addressed = matches.group('nick') | def handle_addressed(self, event): if 'addressed' not in event: event.addressed = False |
event.message['deaddressed'] = pattern.sub('', event.message['raw']) | event.message['deaddressed'] = \ pattern.search(event.message['raw']).group('body') | def handle_addressed(self, event): if 'addressed' not in event: event.addressed = False |
event.addresponse(u'%(who)%(from_who) asked me to remind you %(what), %(ago) ago.', { | event.addresponse(u'%(who)s%(from_who)s asked me to remind you %(what)s, %(ago)s ago.', { | def announce(self, event, who, what, from_who, from_when): """This handler gets called after the timeout and will notice the user.""" |
event.addresponse(u'%(who)%(from_who) asked me to ping you, %(ago) ago.', { | event.addresponse(u'%(who)s%(from_who)s asked me to ping you, %(ago)s ago.', { | def announce(self, event, who, what, from_who, from_when): """This handler gets called after the timeout and will notice the user.""" |
event.addresponse(u"I can't travel in time back to %(ago) ago (yet) so I'll tell you now %(what)", { | event.addresponse(u"I can't travel in time back to %(ago)s ago (yet) so I'll tell you now %(what)s", { | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"I can't travel in time back to %(ago) ago (yet)", { | event.addresponse(u"I can't travel in time back to %(ago)s ago (yet)", { | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"okay, I will remind %(who) in %(time)", { | event.addresponse(u"okay, I will remind %(who)s in %(time)s", { | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"okay, I will ping %(who) in %(time)", { | event.addresponse(u"okay, I will ping %(who)s in %(time)s", { | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
player_re = re.compile(r'^1018 Idata "\s+bnet\s+%s\s+"(\S+?)"?\s+\d+\s+' % gametype) | player_re = re.compile(r'^1018 INFO "\s+bnet\s+%s\s+"(\S+?)"?\s+\d+\s+' % gametype) | def bnet_players(self, gametype): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.bnet_host, self.bnet_port)) s.settimeout(5) s.send('\03%s\n%s\n/con\n/quit\n' % (self.bnet_user, self.bnet_pass)) |
autoload = False | def __unicode__(self): return unicode(self.msg) | |
params = urlencode({'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', | params = urlencode({'STUDENTID': user.encode('utf-8'), 'ADD': 'ADD STUDENT', | def _add_user(self, monitor_url, user): matches = re.search(r'a=(.+)&', monitor_url) auth = matches.group(1) params = urlencode({'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', 'a': auth.encode('utf-8'), 'monitor': '1'}) etree = get_html_parse_tree(monitor_url, treetype=u'etree', data=params) for font in etree.getiterator(u'font'): if u'No STATUS file for' in font.text: raise UsacoException(u'Sorry, user %s not found' % user) |
if u'No STATUS file for' in font.text: | if font.text and u'No STATUS file for' in font.text: | def _add_user(self, monitor_url, user): matches = re.search(r'a=(.+)&', monitor_url) auth = matches.group(1) params = urlencode({'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', 'a': auth.encode('utf-8'), 'monitor': '1'}) etree = get_html_parse_tree(monitor_url, treetype=u'etree', data=params) for font in etree.getiterator(u'font'): if u'No STATUS file for' in font.text: raise UsacoException(u'Sorry, user %s not found' % user) |
.join(Identity) \ | .join('identities') \ | def summon(self, event, who, source): if not source: source = self.default_source |
uri += u'?charset=utf8' else: params = parse_qs(uri.split(u'?', 1)[1]) if u'charset' not in params: uri += u'&charset=utf8' | uri += u'?' params = parse_qs(uri.split(u'?', 1)[1]) if u'charset' not in params: uri += u'&charset=utf8' if u'sql_mode' not in params: uri += u'&sql_mode=ANSI_QUOTES' if u'use_unicode' not in params: uri += u'&use_unicode=0' | def load(self, name): uri = ibid.config.databases[name] echo = ibid.config.debugging.get(u'sqlalchemy_echo', False) |
convert_unicode=True, assert_unicode=True, echo=echo) | convert_unicode=True, assert_unicode=True, echo=echo, pool_recycle=3600) | def load(self, name): uri = ibid.config.databases[name] echo = ibid.config.debugging.get(u'sqlalchemy_echo', False) |
dbapi_con.set_sql_mode("ANSI") | def connect(self, dbapi_con, con_record): dbapi_con.set_sql_mode("ANSI") mysql_engine = ibid.config.get('mysql_engine', 'InnoDB') c = dbapi_con.cursor() c.execute("SET storage_engine=%s;" % mysql_engine) c.execute("SET time_zone='+0:00';") c.close() | |
c.execute("SET storage_engine=%s;" % mysql_engine) c.execute("SET time_zone='+0:00';") | c.execute("SET SESSION storage_engine=%s;" % mysql_engine) c.execute("SET SESSION time_zone='+0:00';") | def connect(self, dbapi_con, con_record): dbapi_con.set_sql_mode("ANSI") mysql_engine = ibid.config.get('mysql_engine', 'InnoDB') c = dbapi_con.cursor() c.execute("SET storage_engine=%s;" % mysql_engine) c.execute("SET time_zone='+0:00';") c.close() |
engine.dialect.use_ansiquotes = True | def connect(self, dbapi_con, con_record): dbapi_con.set_sql_mode("ANSI") mysql_engine = ibid.config.get('mysql_engine', 'InnoDB') c = dbapi_con.cursor() c.execute("SET storage_engine=%s;" % mysql_engine) c.execute("SET time_zone='+0:00';") c.close() | |
variant, _ = variant.contents[0].split(None, 1) | variant, rest = variant.contents[0].split(None, 1) | def variant (self): if self.variants is None: return [] |
@match(r'^(?:(?:mac|oui|ether|ether(?:net)?(?:\s*code)?)\s+)?((?:(?:[0-9a-f]{2}[:-]?){3}){1,2})$') def lookup_mac(self, event, mac): | @match(r'^((?:mac|oui|ether(?:net)?(?:\s*code)?)\s+)?((?:(?:[0-9a-f]{2}(?(1)[:-]?|:))){2,5}[0-9a-f]{2})$') def lookup_mac(self, event, _, mac): | def handle_man(self, event, section, page): command = [self.man, page] if section: command.insert(1, section) |
arrive_ap = '%s %s' % (td.find('div').text.strip(), td.find('div').find('span').text.strip()) | span = [s for s in td.find('div').getiterator('span')][1] arrive_ap = '%s %s' % (td.find('div').text.strip(), span.text.strip()) else: arrive_ap = '%s %s' % (td.find('div').text.strip(), td.find('div').find('span').text.strip()) | def flight_search(self, event, dpt, to): airport_dpt = airport_search(dpt) airport_to = airport_search(to) if len(airport_dpt) == 0: event.addresponse(u"Sorry, I don't know the airport you want to leave from") return if len(airport_to) == 0: event.addresponse(u"Sorry, I don't know the airport you want to fly to") return if len(airport_dpt) > 1: event.addresponse(u'The following airports match the departure: %s', human_join(repr_airport(id) for id in airport_dpt)[:480]) return if len(airport_to) > 1: event.addresponse(u'The following airports match the destination: %s', human_join(repr_airport(id) for id in airport_to)[:480]) return |
if kind == 'owned' and yours: | if kind == 'owned' and yours != 'your': | def give(self, event, receiver, determiner, object): if determiner is None: determiner = '' |
now = datetime.now() | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" | |
delta = time - datetime.now() | delta = time - now | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
(u'bot', u': '), (u'ant', u', '), (u'test_ibid', u' '), | (u'bot', u'%s: '), (u'bot', u' %s: '), (u'ant', u'%s, '), (u'test_ibid', u'%s '), | def test_non_messages(self): for event_type in [u'timer', u'rpc']: event = self.create_event(u'bot: foo', event_type) self.processor.process(event) self.assertFalse(hasattr(event, u'addressed')) self.assertEqual(event.message['deaddressed'], u'bot: foo') |
event = self.create_event(u'%s%sfoo' % prefix) | event = self.create_event((prefix[1] % prefix[0]) + u'foo') | def test_happy_prefix_names(self): for prefix in self.happy_prefixes: event = self.create_event(u'%s%sfoo' % prefix) self.processor.process(event) self.assert_addressed(event, prefix[0], u'foo') |
for processor in ibid.processors: try: processor.process(event) except Exception, e: self.log.exception( u'Exception occured in %s processor of %s plugin.\n' u'Event: %s', processor.__class__.__name__, processor.name, event) event.complain = isinstance(e, (IOError, socket.error, JSONException)) and u'network' or u'exception' event.processed = True if 'session' in event: event.session.rollback() event.session.close() del event['session'] if 'session' in event and (event.session.dirty or event.session.deleted): try: event.session.commit() except IntegrityError: self.log.exception(u"Exception occured committing session from the %s processor of %s plugin", processor.__class__.__name__, processor.name) event.complain = u'exception' event.session.rollback() event.session.close() del event['session'] if 'session' in event: event.session.close() del event['session'] | process(event, self.log) | def _process(self, event): for processor in ibid.processors: try: processor.process(event) except Exception, e: self.log.exception( u'Exception occured in %s processor of %s plugin.\n' u'Event: %s', processor.__class__.__name__, processor.name, event) event.complain = isinstance(e, (IOError, socket.error, JSONException)) and u'network' or u'exception' event.processed = True if 'session' in event: event.session.rollback() event.session.close() del event['session'] |
matchpat = r'(\S+?)\s*(%s)\s*(?:[[{(]+\s*(.+?)\s*[\]})]+)?' | matchpat = r'(\S+?)\s*(%s)' | def setup(self): # When not addressed, match karma changes in any text if self.addressed: matchpat = r'^(.+?)\s*(%s)\s*(?:[[{(]+\s*(.+?)\s*[\]})]+)?$' else: matchpat = r'(\S+?)\s*(%s)\s*(?:[[{(]+\s*(.+?)\s*[\]})]+)?' |
def set(self, event, subject, adjust, reason): | def set(self, event, subject, adjust, reason = None): | def set(self, event, subject, adjust, reason): if self.public and not event.public: event.addresponse(u'Karma must be done in public') return |
event.addresponse(u'%(subject)s now has %(value)s %(points) of karma', { | event.addresponse(u'%(subject)s now has %(value)s %(points)s of karma', { | def set(self, event, subject, adjust, reason): if self.public and not event.public: event.addresponse(u'Karma must be done in public') return |
if word in 'aedhilmnorsx': return 'an' elif len(word) == 1: return 'a' | if len(word) == 1: if wordi in 'aedhilmnorsx': return 'an' else: return 'a' | def indefinite_article(noun_phrase): # algorithm adapted from CPAN package Lingua-EN-Inflect-1.891 by Damian Conway m = re.search('\w+', noun_phrase) if m: word = m.group(0) else: return 'an' wordi = word.lower() for anword in ("euler", "heir", "honest", "hono"): if wordi.startswith(anword): return 'an' if wordi.startswith('hour') and not wordi.startswith('houri'): return 'an' if word in 'aedhilmnorsx': return 'an' elif len(word) == 1: return 'a' if re.match(r'(?!FJO|[HLMNS]Y.|RY[EO]|SQU|' r'(F[LR]?|[HL]|MN?|N|RH?|S[CHKLMNPTVW]?|X(YL)?)[AEIOU])' r'[FHLMNRSX][A-Z]', word): return 'an' for regex in (r'^e[uw]', r'^onc?e\b', r'^uni([^nmd]|mo)','^u[bcfhjkqrst][aeiou]'): if re.match(regex, wordi): return 'a' # original regex was /^U[NK][AIEO]?/ but that matches UK, UN, etc. if re.match('^U[NK][AIEO]', word): return 'a' elif word == word.upper(): if wordi[0] in 'aedhilmnorsx': return 'an' else: return 'a' if wordi[0] in 'aeiou': return 'an' if re.match(r'^y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt)', wordi): return 'an' else: return 'a' |
self.protocols[parts[0]].append(parts[1]) | self.protocols[parts[0].lower()].append(parts[1]) | def _load_services(self): if self.protocols: return |
self.protocols[proto].append(parts[1]) | self.protocols[proto.lower()].append(parts[1]) | def _load_services(self): if self.protocols: return |
params = urlencode({u'NAME': user.encode('utf-8'), u'PASSWORD': password.encode('utf-8')}) | params = urlencode({'NAME': user.encode('utf-8'), 'PASSWORD': password.encode('utf-8')}) | def _login(self, user, password): params = urlencode({u'NAME': user.encode('utf-8'), u'PASSWORD': password.encode('utf-8')}) etree = get_html_parse_tree(u'http://ace.delos.com/usacogate', data=params, treetype=u'etree') for font in etree.getiterator(u'font'): if font.text and 'Please try again' in font.text: return None return etree |
if font.text and 'Please try again' in font.text: | if font.text and u'Please try again' in font.text: | def _login(self, user, password): params = urlencode({u'NAME': user.encode('utf-8'), u'PASSWORD': password.encode('utf-8')}) etree = get_html_parse_tree(u'http://ace.delos.com/usacogate', data=params, treetype=u'etree') for font in etree.getiterator(u'font'): if font.text and 'Please try again' in font.text: return None return etree |
params = urlencode({u'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', u'a': auth.encode('utf-8'), u'monitor': u'1'}) | params = urlencode({'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', 'a': auth.encode('utf-8'), 'monitor': '1'}) | def _add_user(self, monitor_url, user): matches = re.search(r'a=(.+)&', monitor_url) auth = matches.group(1) params = urlencode({u'STUDENTID': user.econde('utf-8'), 'ADD': 'ADD STUDENT', u'a': auth.encode('utf-8'), u'monitor': u'1'}) etree = get_html_parse_tree(monitor_url, treetype=u'etree', data=params) for font in etree.getiterator(u'font'): if u'No STATUS file for' in font.text: raise UsacoException(u'Sorry, user %s not found' % user) |
params = urlencode({u'id': usaco_user.encode('utf-8'), u'search': u'SEARCH'}) | params = urlencode({'id': usaco_user.encode('utf-8'), 'search': 'SEARCH'}) | def get_division(self, event, user): try: usaco_user = self._get_usaco_user(event, user) except UsacoException, e: event.addresponse(e) return |
"Return sigular or plural depending on count" if count == 1: | "Return singular or plural depending on count" if abs(count) == 1: | def plural(count, singular, plural): "Return sigular or plural depending on count" if count == 1: return singular return plural |
"Calling later should call stuff later." | "Calling later calls stuff later." | def test_call_later_no_args(self): "Calling later should call stuff later." ev = self._ev() ev.channel = None ev.public = None dfr = defer.Deferred() tm = datetime.now() def _cl(_ev): _ev.did_stuff = True dfr.callback(_ev) def _cb(_ev, _self, _oev): _self.assertTrue(tm + timedelta(seconds=0.01) < datetime.now()) _self.assertTrue(_ev.did_stuff) _self.assertFalse(hasattr(_oev, 'did_stuff')) dfr.addCallback(_cb, self, ev) self.dispatcher.call_later(0.01, _cl, ev) return dfr |
"Calling later should call stuff later." | "Calling later with args calls stuff later." | def test_call_later_args(self): "Calling later should call stuff later." ev = self._ev() ev.channel = None ev.public = None dfr = defer.Deferred() tm = datetime.now() def _cl(_ev, val): _ev.did_stuff = val dfr.callback(_ev) def _cb(_ev, _self, _oev): _self.assertTrue(tm + timedelta(seconds=0.01) < datetime.now()) _self.assertEqual('thingy', _ev.did_stuff) _self.assertFalse(hasattr(_oev, 'did_stuff')) dfr.addCallback(_cb, self, ev) self.dispatcher.call_later(0.01, _cl, ev, 'thingy') return dfr |
"Calling later should call stuff later." | "Calling later with kwargs calls stuff later." | def test_call_later_kwargs(self): "Calling later should call stuff later." ev = self._ev() ev.channel = None ev.public = None dfr = defer.Deferred() tm = datetime.now() def _cl(_ev, val='default'): _ev.did_stuff = val dfr.callback(_ev) def _cb(_ev, _self, _oev): _self.assertTrue(tm + timedelta(seconds=0.01) < datetime.now()) _self.assertEqual('thingy', _ev.did_stuff) _self.assertFalse(hasattr(_oev, 'did_stuff')) dfr.addCallback(_cb, self, ev) self.dispatcher.call_later(0.01, _cl, ev, val='thingy') return dfr |
if urlparse(url).netloc != 'file': | if urlparse(url).scheme == 'file': | def draw(self, event, url, colour, width, height): if not urlparse(url).netloc: url = 'http://' + url if urlparse(url).netloc != 'file': event.addresponse(u'Are you trying to haxor me?') return if not urlparse(url).path: url += '/' |
event.addresponse(', '.join(['%s: %s (%s)' % (karmas.index(karma), karma.subject, karma.value) for karma in karmas])) | event.addresponse(u', '.join( u'%s: %s (%s)' % (karmas.index(karma), karma.subject, karma.value) for karma in karmas)) | def ladder(self, event, reverse): karmas = event.session.query(Karma) if reverse: karmas = karmas.order_by(Karma.value.asc()) else: karmas = karmas.order_by(Karma.value.desc()) karmas = karmas.limit(30).all() |
and fnmatch.fnmatch(event.channel, channel_glob)): | and fnmatch.fnmatch(channel, channel_glob)): | def get_logfile(self, event): self.lock.acquire() try: when = event.time if not self.date_utc: when = when.replace(tzinfo=tzutc()).astimezone(tzlocal()) |
usage = u'remind (me|someone else) in <delta> about something' | usage = u'remind <person> in <time> about <something>' | def coffee_accept(self, event): if (event.source, event.channel) not in self.pots: event.addresponse(u"There isn't a pot on") |
event.addresponse(u'%s: %s asked me to remind you %s, %s ago.' % (who, from_who, what, ago(datetime.now()-from_when))) else: event.addresponse(u'%s: %s asked me to ping you, %s ago.' % (who, from_who, ago(datetime.now()-from_when))) | event.addresponse(u'%s: %s asked me to remind you %s, %s ago.', (who, from_who, what, ago(datetime.now()-from_when))) else: event.addresponse(u'%s: %s asked me to ping you, %s ago.', (who, from_who, ago(datetime.now()-from_when))) | def announce(self, event, who, what, from_who, from_when): """handler that gets called after the timeout""" |
elif at == "at" or at == "on": | elif at in ("at", "on"): | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"I can't travel in time back to %s ago (yet) so I'll tell you now %s" % (ago(-delta), what)) | event.addresponse(u"I can't travel in time back to %s ago (yet) so I'll tell you now %s", (ago(-delta), what)) | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"I can't travel in time back to %s ago (yet)" % ago(-delta)) | event.addresponse(u"I can't travel in time back to %s ago (yet)", ago(-delta)) | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
event.addresponse(u"will remind %s %s in %s" % (who, what, ago(delta)), action=True) else: event.addresponse(u"will ping %s in %s" % (who, ago(delta)), action=True) | event.addresponse(u"okay, I will remind %s in %s", (who, ago(delta))) else: event.addresponse(u"okay, I will ping %s in %s", (who, ago(delta))) | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
re.compile(r'^(%s)([:;.?>!,-]+)*\s*' % '|'.join(self.names), | re.compile(r'^(%s)([:;.?>!,-]+)?\s*' % '|'.join(self.names), | def setup(self): self.patterns = [ re.compile(r'^(%s)([:;.?>!,-]+)*\s*' % '|'.join(self.names), re.I | re.DOTALL), # "hello there, bot"-style addressing. But we want to be sure that # there wasn't normal addressing too: re.compile(r'^(?:\S+:.*|.*,\s*(%s))\s*$' % '|'.join(self.names), re.I | re.DOTALL) ] |
@match(r'^\s*(?:please\s+)?(tell|pm|privmsg|msg|ask|remind)' | @match(r'^\s*(?:please\s+)?(tell|pm|privmsg|msg|ask)' | def __init__(self, from_id, to_id, memo, private=False): self.from_id = from_id self.to_id = to_id self.memo = memo self.private = private self.delivered = False self.time = datetime.utcnow() |
def dinner (self, who, event, veg): | def dinner (self, event, who, veg): | def dinner (self, who, event, veg): url = 'http://www.whatthefuckshouldimakefordinner.com/' if veg: url += 'veg.php' |
(u'day2', u'%02i', now.day), | def _interpolate(message, event): "Expand factoid variables" utcnow = datetime.utcnow() now = utcnow.replace(tzinfo=tzutc()).astimezone(tzlocal()) substitutions = [(u'who', event.sender['nick']), (u'channel', event.channel), (u'source', event.source), (u'year', unicode(now.year)), (u'month2', u'%02i' % now.month), (u'month1', unicode(now.month)), (u'month', unicode(now.strftime('%B'))), (u'mon', unicode(now.strftime('%b'))), (u'day', unicode(now.day)), (u'day2', u'%02i', now.day), (u'hour', unicode(now.hour)), (u'minute', unicode(now.minute)), (u'second', unicode(now.second)), (u'date', format_date(utcnow, 'date')), (u'time', format_date(utcnow, 'time')), (u'dow', unicode(now.strftime('%A'))), (u'weekday', unicode(now.strftime('%A'))), (u'unixtime', unicode(utcnow.strftime('%s'))), ] for var, expansion in substitutions: message = message.replace(u'$' + var, expansion) return message | |
print e.hdrs | def _post_url(self, event, url=None): "Posts a URL to delicious.com" | |
OTHER_STUFF = ('am', 'pm', 'st', 'nd', 'rd', 'th', 'morning', 'afternoon', 'evening') | OTHER_STUFF = ('am', 'pm', 'st', 'nd', 'rd', 'th', 'morning', 'afternoon', 'evening', 'anytime') | def int_duration(self): hours, minutes = 0, 0 match = re.search(r'(\d+)hr', self.duration) if match: hours = int(match.group(1)) match = re.search(r'(\d+)min', self.duration) if match: minutes = int(match.group(1)) return int(hours)*60 + int(minutes) |
'description': u'Generic timed reminders', | 'description': u'Programs reminders in the future for you or other people.', | def coffee_accept(self, event): if (event.source, event.channel) not in self.pots: event.addresponse(u"There isn't a pot on") |
matchpat = r'(\S+?)\s*(%s)' | matchpat = r'(\S+)\s*(%s)' | def setup(self): # When not addressed, match karma changes in any text if self.addressed: matchpat = r'^(.+?)\s*(%s)\s*(?:[[{(]+\s*(.+?)\s*[\]})]+)?$' else: matchpat = r'(\S+?)\s*(%s)' |
feature = 'factoids' | feature = 'factoid' | def get_factoid(session, name, number, pattern, is_regex, all=False, literal=False): """session: SQLAlchemy session name: Factoid name (can contain arguments unless literal query) number: Return factoid[number] (or factoid[number:] for literal queries) pattern: Return factoids matching this pattern (cannot be used in conjuction with number) is_regex: Pattern is a real regex all: Return a random factoid from the set if False literal: Match factoid name literally (implies all) """ # First pass for exact matches, if necessary again for wildcard matches if literal: passes = (False,) else: passes = (False, True) for wild in passes: factoid = None query = session.query(Factoid)\ .add_entity(FactoidName).join(Factoid.names)\ .add_entity(FactoidValue).join(Factoid.values) if wild: # Reversed LIKE because factoid name contains SQL wildcards if # factoid supports arguments query = query.filter(':fact LIKE name ESCAPE :escape') \ .params(fact=name, escape='\\') else: query = query.filter(FactoidName.name == escape_name(name)) # For normal matches, restrict to the subset applicable if not literal: query = query.filter(FactoidName.wild == wild) if pattern: if is_regex: query = query.filter(FactoidValue.value.op('REGEXP')(pattern)) else: pattern = '%%%s%%' % escape_like_re.sub(r'\\\1', pattern) # http://www.sqlalchemy.org/trac/ticket/1400: # We can't use .like() in MySQL query = query.filter('value LIKE :pattern ESCAPE :escape') \ .params(pattern=pattern, escape='\\') if number: try: if literal: return query.order_by(FactoidValue.id)[int(number) - 1:] else: factoid = query.order_by(FactoidValue.id)[int(number) - 1] except IndexError: continue if all or literal: if factoid is not None: return [factoid] else: factoid = query.all() else: factoid = factoid or query.order_by(func.random()).first() if factoid: return factoid |
feature = 'factoids' | feature = 'factoid' | def literal(self, event, name, number, pattern, is_regex): factoids = get_factoid(event.session, name, number, pattern, is_regex, literal=True) number = number and int(number) or 1 if factoids: event.addresponse(u', '.join(u'%i: %s' % (index + number, value.value) for index, (factoid, name, value) in enumerate(factoids))) |
feature = 'factoids' | feature = 'factoid' | def alias(self, event, target, source): |
feature = 'factoids' | feature = 'factoid' | def _interpolate(message, event): "Expand factoid variables" utcnow = datetime.utcnow() now = utcnow.replace(tzinfo=tzutc()).astimezone(tzlocal()) message = message.replace(u'$who', event.sender['nick']) message = message.replace(u'$channel', event.channel) message = message.replace(u'$year', unicode(now.year)) message = message.replace(u'$month', unicode(now.month)) message = message.replace(u'$day', unicode(now.day)) message = message.replace(u'$hour', unicode(now.hour)) message = message.replace(u'$minute', unicode(now.minute)) message = message.replace(u'$second', unicode(now.second)) message = message.replace(u'$date', format_date(utcnow, 'date')) message = message.replace(u'$time', format_date(utcnow, 'time')) message = message.replace(u'$dow', unicode(now.strftime('%A'))) message = message.replace(u'$unixtime', unicode(utcnow.strftime('%s'))) return message |
feature = 'factoids' | feature = 'factoid' | def remote_get(self, name, number=None, pattern=None, is_regex=None, event={}): factoid = get_factoid(event.session, name, number, pattern, is_regex) |
feature = 'factoids' | feature = 'factoid' | def last_set(self, event): if self.last_set_factoid is None: event.addresponse(u'Sorry, nobody has taught me anything recently') else: event.addresponse(u'It was: %s', self.last_set_factoid) |
try: users = self.bnet_players('W3XP') except socket.error: event.addresponse(u"Sorry, I couldn't contact the server. Maybe it's down") return | users = self.bnet_players('W3XP') | def dota_players(self, event): try: users = self.bnet_players('W3XP') except socket.error: event.addresponse(u"Sorry, I couldn't contact the server. Maybe it's down") return if users: event.addresponse(u'The battlefield contains %s', human_join(users)) else: event.addresponse(u'Nobody. Everyone must have a lives...') |
try: server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | def cs_players(self, event): try: server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
players.sort(key=lambda x: x['fragtotal'], reverse=True) event.addresponse(u'There are %(clients)i/%(clientmax)s players playing %(map)s: %(players)s', { 'clients': clientcount, 'clientmax': clientmax, 'map': map, 'players': human_join(u'%s (%i)' % (p['nickname'], p['fragtotal']) for p in players), }) except socket.error: event.addresponse(u"Sorry, I couldn't contact the server. Maybe it's down") | players.sort(key=lambda x: x['fragtotal'], reverse=True) event.addresponse(u'There are %(clients)i/%(clientmax)s players playing %(map)s: %(players)s', { 'clients': clientcount, 'clientmax': clientmax, 'map': map, 'players': human_join(u'%s (%i)' % (p['nickname'], p['fragtotal']) for p in players), }) | def cs_players(self, event): try: server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
from_who = "you" | from_who = "You" | def announce(self, event, who, what, from_who, from_when): """This handler gets called after the timeout and will notice the user.""" |
if total_seconds < 0: if what: event.addresponse(u"I can't travel in time back to %(ago)s ago (yet) so I'll tell you now %(what)s", { | if total_seconds < -24*60*60: event.addresponse(u"I can't travel in time back to %(ago)s ago (yet) so I'll tell you tomorrow instead", { | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
'what': what | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" | |
else: event.addresponse(u"I can't travel in time back to %(ago)s ago (yet)", { 'ago': ago(-delta) }) | return elif total_seconds < 0: delta += timedelta(days=1) total_seconds = (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6 | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
if what: event.addresponse(u"okay, I will remind %(who)s in %(time)s", { | event.addresponse(u"Okay, I will %(action)s %(who)s%(time)s", { 'action': 'remind' if what else 'ping', | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
'time': ago(delta) | 'time': " in " + ago(delta) if delta else "", | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" |
else: event.addresponse(u"okay, I will ping %(who)s in %(time)s", { 'who': who, 'time': ago(delta) }) | def remind(self, event, who, at, when, how, what): """This is the main handler that gets called on the above @match. This parses the date and sets up the "announce" function to be fired when the time is up.""" | |
@match(r'^(?:remind|ping)\s+(?:(me|\w+)\s+)?(at|on|in)\s+(.*?)(?:(about|of|to) (.*))?$') | @match(r'(?:please )?(?:remind|ping) (?:(me|\w+) )?(at|on|in) (.*?)(?:(about|of|to) (.*))?') | def announce(self, event, who, what, from_who, from_when): """handler that gets called after the timeout""" |
"""main handler | """This is the main handler that gets called on the above @match. | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
this parses the date and sets up the "announce" function to be | This parses the date and sets up the "announce" function to be | def remind(self, event, who, at, when, how, what): """main handler this parses the date and sets up the "announce" function to be fired when the time is up.""" |
if presence.x and presence.x.defaultUri == 'http://jabber.org/protocol/muc realjid = JID(presence.x.item["jid"]) | for mucuser in presence.elements(name='x', uri='http://jabber.org/protocol/muc if mucuser.item.hasAttribute('jid'): realjid = JID(mucuser.item["jid"]) | def _onPresenceAvailable(self, presence): entity = JID(presence["from"]) |
if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): | if ( align != None and crossLink(left_child, node, align) )\ or ( align == None and classify(left_child, node, nPUBetween, model) ): | def reorderVV(node, align, model, bDebug): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.append(extra) # append node.right_children.append(left_child) if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.append(extra) bReorder = True elif left_child.pos in ['NT', 'M', 'CD', 'OD']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) # insert node.right_children.insert(0, left_child) if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) bReorder = True elif left_child.pos in ['PU']: nPUBetween += 1 if not bReorder: left_children.insert(0, left_child) if align: recordOrder(bReorder, left_child, node, nPUBetween, model) node.left_children = left_children |
if align: | if align != None: | def reorderVV(node, align, model, bDebug): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos in ['P']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.append(extra) # append node.right_children.append(left_child) if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.append(extra) bReorder = True elif left_child.pos in ['NT', 'M', 'CD', 'OD']: if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) # insert node.right_children.insert(0, left_child) if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) bReorder = True elif left_child.pos in ['PU']: nPUBetween += 1 if not bReorder: left_children.insert(0, left_child) if align: recordOrder(bReorder, left_child, node, nPUBetween, model) node.left_children = left_children |
if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): | if ( align != None and crossLink(left_child, node, align) )\ or ( align == None and classify(left_child, node, nPUBetween, model) ): | def reorderNN(node, align, model, bDebug): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos == 'DEC' or left_child.pos == 'DEG': if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): reorderDE(left_child, align, model) if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) node.right_children.insert(0, left_child) if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) bReorder = True elif left_child.pos == 'PU': nPUBetween += 1 if not bReorder: left_children.insert(0, left_child) if align: recordOrder(bReorder, left_child, node, nPUBetween, model) node.left_children = left_children |
if align: | if align != None: | def reorderNN(node, align, model, bDebug): left_children = [] nPUBetween = 0 while node.left_children: left_child = node.left_children.pop(-1) # for each left bReorder = False if left_child.pos == 'DEC' or left_child.pos == 'DEG': if ( align and crossLink(left_child, node, align) )\ or ( not align and classify(left_child, node, nPUBetween, model) ): reorderDE(left_child, align, model) if bDebug: extra = dep.CDepNode(); extra.token=')'; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) node.right_children.insert(0, left_child) if bDebug: extra = dep.CDepNode(); extra.token='('+left_child.pos; extra.pos=""; extra.word_index=-1 node.right_children.insert(0, extra) bReorder = True elif left_child.pos == 'PU': nPUBetween += 1 if not bReorder: left_children.insert(0, left_child) if align: recordOrder(bReorder, left_child, node, nPUBetween, model) node.left_children = left_children |
if align: | if alignFile: | def deg(node): assert node.pos == 'DEG' for left_child in node.left_children: if left_child.pos == 'JJ': return False return True |
source, target = map(int, line[2:-1].split()) | target, source = map(int, line[2:-1].split()) | def readAlign(path): retval = {} n=0 file = gzip.open(path) for line in file: if line.startswith('SENT:'): |
number = int(line[6:-1]) assert number == n | def readAlign(path): retval = {} n=0 file = gzip.open(path) for line in file: if line.startswith('SENT:'): number = int(line[6:-1]) assert number == n # make sure of sentence index if n>0: yield retval retval = {} n += 1 else: assert line.startswith('S ') source, target = map(int, line[2:-1].split()) if not source in retval: retval[source] = [] retval[source].append(target) yield retval file.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.