Changed some maps/filters to imaps/ifilters for efficiency reasons (I was bored, basically).

This commit is contained in:
Jeremy Fincher 2003-11-15 04:37:04 +00:00
parent 28d371aeca
commit eb6e112f70
19 changed files with 64 additions and 45 deletions

View File

@ -36,6 +36,7 @@ Babelfish-related commands.
import plugins import plugins
import random import random
from itertools import imap
import babelfish import babelfish
@ -54,7 +55,7 @@ def configure(onStart, afterConnect, advanced):
class Babelfish(callbacks.Privmsg): class Babelfish(callbacks.Privmsg):
threaded = True threaded = True
_abbrevs = utils.abbrev(map(str.lower, babelfish.available_languages)) _abbrevs = utils.abbrev(imap(str.lower, babelfish.available_languages))
_abbrevs['de'] = 'german' _abbrevs['de'] = 'german'
_abbrevs['jp'] = 'japanese' _abbrevs['jp'] = 'japanese'
_abbrevs['kr'] = 'korean' _abbrevs['kr'] = 'korean'

View File

@ -39,10 +39,9 @@ import re
import string import string
import urllib2 import urllib2
import xml.dom.minidom as minidom import xml.dom.minidom as minidom
from itertools import imap, ifilter
from htmlentitydefs import entitydefs as entities from htmlentitydefs import entitydefs as entities
import sqlite
import conf import conf
import utils import utils
import plugins import plugins
@ -227,7 +226,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
L.append(ircutils.bold('Status: ') + summary['status']) L.append(ircutils.bold('Status: ') + summary['status'])
if 'resolution' in summary: if 'resolution' in summary:
L.append(ircutils.bold('Resolution: ') + summary['resolution']) L.append(ircutils.bold('Resolution: ') + summary['resolution'])
return ', '.join(map(str, L)) return ', '.join(imap(str, L))
def _get_short_bug_summary(self, url, desc, number): def _get_short_bug_summary(self, url, desc, number):
bugxml = self._getbugxml(url, desc) bugxml = self._getbugxml(url, desc)

View File

@ -30,7 +30,10 @@
### ###
""" """
Silently listens to every message received on a channel and keeps statistics concerning joins, parts, and various other commands in addition to tracking statistics about smileys, actions, characters, and words. """ Silently listens to every message received on a channel and keeps statistics
concerning joins, parts, and various other commands in addition to tracking
statistics about smileys, actions, characters, and words.
"""
import plugins import plugins
@ -40,6 +43,7 @@ import sets
import time import time
import getopt import getopt
import string import string
from itertools import imap, ifilter
import sqlite import sqlite
@ -56,8 +60,8 @@ import callbacks
smileys = (':)', ';)', ':]', ':-)', ':-D', ':D', ':P', ':p', '(=', '=)') smileys = (':)', ';)', ':]', ':-)', ':-D', ':D', ':P', ':p', '(=', '=)')
frowns = (':|', ':-/', ':-\\', ':\\', ':/', ':(', ':-(', ':\'(') frowns = (':|', ':-/', ':-\\', ':\\', ':/', ':(', ':-(', ':\'(')
smileyre = re.compile('|'.join(map(re.escape, smileys))) smileyre = re.compile('|'.join(imap(re.escape, smileys)))
frownre = re.compile('|'.join(map(re.escape, frowns))) frownre = re.compile('|'.join(imap(re.escape, frowns)))
class ChannelDB(plugins.ChannelDBHandler, class ChannelDB(plugins.ChannelDBHandler,
plugins.Configurable, plugins.Configurable,

View File

@ -45,6 +45,7 @@ import random
import urllib import urllib
import inspect import inspect
import mimetypes import mimetypes
from itertools import imap
import conf import conf
import debug import debug
@ -326,7 +327,7 @@ class Fun(callbacks.Privmsg):
arg = privmsgs.getArgs(args) arg = privmsgs.getArgs(args)
m = re.match(self._dicere, arg) m = re.match(self._dicere, arg)
if m: if m:
(dice, sides) = map(int, m.groups()) (dice, sides) = imap(int, m.groups())
if dice > 6: if dice > 6:
irc.error(msg, 'You can\'t roll more than 6 dice.') irc.error(msg, 'You can\'t roll more than 6 dice.')
elif sides > 100: elif sides > 100:

View File

@ -38,11 +38,12 @@ import plugins
import re import re
import sets import sets
import time import time
import getopt
import string import string
import os.path import os.path
from itertools import imap
import sqlite import sqlite
import getopt
import conf import conf
import debug import debug
@ -231,7 +232,7 @@ class FunDB(callbacks.Privmsg):
'somewhere.') 'somewhere.')
return return
elif table not in self._tables: elif table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % \ irc.error(msg, '"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
cursor = self.db.cursor() cursor = self.db.cursor()
@ -263,7 +264,7 @@ class FunDB(callbacks.Privmsg):
irc.error(msg, 'The <id> argument must be an integer.') irc.error(msg, 'The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % \ irc.error(msg, '"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
cursor = self.db.cursor() cursor = self.db.cursor()
@ -293,7 +294,7 @@ class FunDB(callbacks.Privmsg):
irc.error(msg, 'The <id> argument must be an integer.') irc.error(msg, 'The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % \ irc.error(msg, '"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
try: try:
@ -326,14 +327,14 @@ class FunDB(callbacks.Privmsg):
table = privmsgs.getArgs(args) table = privmsgs.getArgs(args)
table = table.lower() table = table.lower()
if table not in self._tables: if table not in self._tables:
irc.error(msg, '%r is not valid. Valid values include %s.' % \ irc.error(msg, '%r is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
cursor = self.db.cursor() cursor = self.db.cursor()
sql = """SELECT count(*) FROM %ss""" % table sql = """SELECT count(*) FROM %ss""" % table
cursor.execute(sql) cursor.execute(sql)
total = int(cursor.fetchone()[0]) total = int(cursor.fetchone()[0])
irc.reply(msg, 'There %s currently %s in my database.' % \ irc.reply(msg, 'There %s currently %s in my database.' %
(utils.be(total), utils.nItems(total, table))) (utils.be(total), utils.nItems(total, table)))
def get(self, irc, msg, args): def get(self, irc, msg, args):
@ -349,7 +350,7 @@ class FunDB(callbacks.Privmsg):
irc.error(msg, 'The <id> argument must be an integer.') irc.error(msg, 'The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % \ irc.error(msg, '"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
cursor = self.db.cursor() cursor = self.db.cursor()
@ -374,7 +375,7 @@ class FunDB(callbacks.Privmsg):
irc.error(msg, 'The <id> argument must be an integer.') irc.error(msg, 'The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % \ irc.error(msg, '"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
cursor = self.db.cursor() cursor = self.db.cursor()
@ -406,7 +407,7 @@ class FunDB(callbacks.Privmsg):
raise callbacks.ArgumentError raise callbacks.ArgumentError
try: try:
(nick, reason) = map(' '.join, (nick, reason) = imap(' '.join,
utils.itersplit('for'.__eq__, nick.split(), 1)) utils.itersplit('for'.__eq__, nick.split(), 1))
except ValueError: except ValueError:
reason = '' reason = ''
@ -457,14 +458,14 @@ class FunDB(callbacks.Privmsg):
raise callbacks.ArgumentError raise callbacks.ArgumentError
try: try:
(nick, reason) = map(' '.join, (nick, reason) = imap(' '.join,
utils.itersplit('for'.__eq__, nick.split(), 1)) utils.itersplit('for'.__eq__, nick.split(), 1))
except ValueError: except ValueError:
reason = '' reason = ''
cursor = self.db.cursor() cursor = self.db.cursor()
if id: if id:
cursor.execute("""SELECT id, praise FROM praises WHERE id=%s""", id) cursor.execute("""SELECT id, praise FROM praises WHERE id=%s""",id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such praise.') irc.error(msg, 'There is no such praise.')
return return

View File

@ -41,6 +41,7 @@ import getopt
import socket import socket
import urllib2 import urllib2
import xml.dom.minidom import xml.dom.minidom
from itertools import imap, ifilter
import utils import utils
import debug import debug
@ -261,7 +262,7 @@ class Http(callbacks.Privmsg):
'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)'}) 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)'})
html = getPage(request) html = getPage(request)
# The following definitions are stripped and empties are removed. # The following definitions are stripped and empties are removed.
defs = filter(None, map(str.strip, self._acronymre.findall(html))) defs = filter(None, imap(str.strip, self._acronymre.findall(html)))
utils.sortBy(lambda s: not s.startswith('[not an acronym]'), defs) utils.sortBy(lambda s: not s.startswith('[not an acronym]'), defs)
for (i, s) in enumerate(defs): for (i, s) in enumerate(defs):
if s.startswith('[not an acronym]'): if s.startswith('[not an acronym]'):

View File

@ -34,6 +34,7 @@ Plugin for handling basic Karma stuff for a channel.
""" """
import os import os
from itertools import imap
import sqlite import sqlite
@ -95,7 +96,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp, plugins.ChannelDBHandler):
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, '%s has no karma.' % name) irc.reply(msg, '%s has no karma.' % name)
else: else:
(added, subtracted) = map(int, cursor.fetchone()) (added, subtracted) = imap(int, cursor.fetchone())
total = added - subtracted total = added - subtracted
s = 'Karma for %r has been increased %s %s ' \ s = 'Karma for %r has been increased %s %s ' \
'and decreased %s %s for a total karma of %s.' % \ 'and decreased %s %s for a total karma of %s.' % \
@ -103,7 +104,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp, plugins.ChannelDBHandler):
subtracted, utils.pluralize(subtracted, 'time'), total) subtracted, utils.pluralize(subtracted, 'time'), total)
irc.reply(msg, s) irc.reply(msg, s)
elif len(args) > 1: elif len(args) > 1:
normalizedArgs = map(str.lower, args) normalizedArgs = imap(str.lower, args)
criteria = ' OR '.join(['normalized=%s'] * len(args)) criteria = ' OR '.join(['normalized=%s'] * len(args))
sql = """SELECT name, added-subtracted sql = """SELECT name, added-subtracted
FROM karma WHERE %s FROM karma WHERE %s

View File

@ -45,6 +45,7 @@ import shlex
import string import string
import random import random
import sqlite import sqlite
from itertools import imap
from cStringIO import StringIO from cStringIO import StringIO
import conf import conf
@ -226,7 +227,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
# These are okay, unless there's an _is_ in there, in which case # These are okay, unless there's an _is_ in there, in which case
# we split on the leftmost one. # we split on the leftmost one.
if '_is_' in match.group(): if '_is_' in match.group():
key, fact = map(str.strip, match.group().split('_is_', 1)) key, fact = imap(str.strip, match.group().split('_is_', 1))
# Strip the key of punctuation and spaces # Strip the key of punctuation and spaces
key = key.rstrip('?! ') key = key.rstrip('?! ')
# Check and make sure it's not in the DB already # Check and make sure it's not in the DB already
@ -319,7 +320,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
# These are okay, unless there's an _is_ in there, in which case # These are okay, unless there's an _is_ in there, in which case
# we split on the leftmost one. # we split on the leftmost one.
if '_is_' in match.group(): if '_is_' in match.group():
key, new_fact = map(str.strip, match.group().split('_is_', 1)) key, new_fact = imap(str.strip, match.group().split('_is_', 1))
key = key.split(' ', 1)[1] # Take out everything to first space key = key.split(' ', 1)[1] # Take out everything to first space
cursor = self.db.cursor() cursor = self.db.cursor()
# Check and make sure it's in the DB # Check and make sure it's in the DB

View File

@ -36,6 +36,8 @@ Database.
import plugins import plugins
from itertools import imap
import IMDb import IMDb
import utils import utils
@ -55,7 +57,7 @@ class Movies(callbacks.Privmsg):
threaded = True threaded = True
def _formatMovie(self, movie): def _formatMovie(self, movie):
title = utils.unCommaThe(movie.title()) title = utils.unCommaThe(movie.title())
genres = utils.commaAndify(map(str.lower, movie.genres())) genres = utils.commaAndify(imap(str.lower, movie.genres()))
s = '"%s" (%s) belongs to the %s %s. ' \ s = '"%s" (%s) belongs to the %s %s. ' \
'It\'s been rated %s out of 10. ' \ 'It\'s been rated %s out of 10. ' \
'More information is available at <%s>' % \ 'More information is available at <%s>' % \

View File

@ -38,6 +38,7 @@ import plugins
import re import re
import sys import sys
import time import time
from itertools import imap, ifilter
import conf import conf
import debug import debug
@ -319,9 +320,12 @@ class Relay(callbacks.Privmsg, plugins.Configurable):
voices.append('+%s' % s) voices.append('+%s' % s)
else: else:
usersS.append(s) usersS.append(s)
map(list.sort, (ops, halfops, voices, usersS)) ops.sort()
usersS = ', '.join(filter(None, map(', '.join, voices.sort()
(ops,halfops,voices,usersS)))) usersS.sort()
halfops.sort()
usersS = ', '.join(ifilter(None, imap(', '.join,
(ops,halfops,voices,usersS))))
users.append('%s: %s' % (ircutils.bold(abbreviation), usersS)) users.append('%s: %s' % (ircutils.bold(abbreviation), usersS))
irc.reply(msg, '; '.join(users)) irc.reply(msg, '; '.join(users))

View File

@ -37,7 +37,7 @@ import re
import sets import sets
import urllib2 import urllib2
from itertools import ifilter from itertools import ifilter, imap
import conf import conf
import debug import debug
@ -151,7 +151,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
resp = [head % entry for entry in self._formatResp(text)] resp = [head % entry for entry in self._formatResp(text)]
if resp: if resp:
if len(resp) > 10: if len(resp) > 10:
resp = map(lambda s: utils.ellipsisify(s, 50), resp) resp = imap(lambda s: utils.ellipsisify(s, 50), resp)
return '%s' % utils.commaAndify(resp) return '%s' % utils.commaAndify(resp)
raise callbacks.Error, 'No Trackers were found. (%s)' %\ raise callbacks.Error, 'No Trackers were found. (%s)' %\
conf.replyPossibleBug conf.replyPossibleBug

View File

@ -40,7 +40,7 @@ import sys
import sets import sets
import time import time
import threading import threading
from itertools import islice, ifilter from itertools import islice, ifilter, imap
import conf import conf
import utils import utils
@ -142,8 +142,7 @@ class Status(callbacks.Privmsg):
time.strftime(conf.humanTimestampFormat, time.strftime(conf.humanTimestampFormat,
time.localtime(ended)), time.localtime(ended)),
utils.timeElapsed(ended-started)) utils.timeElapsed(ended-started))
L = map(format, L) irc.reply(msg, utils.commaAndify(imap(format, L)))
irc.reply(msg, utils.commaAndify(L))
def netstats(self, irc, msg, args): def netstats(self, irc, msg, args):
"""takes no arguments """takes no arguments

View File

@ -41,6 +41,7 @@ import pprint
import string import string
import smtplib import smtplib
import textwrap import textwrap
from itertools import imap
import conf import conf
import ircdb import ircdb
@ -233,7 +234,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
Returns the hostmasks currently being globally ignored. Returns the hostmasks currently being globally ignored.
""" """
if conf.ignores: if conf.ignores:
irc.reply(msg, utils.commaAndify(map(repr, conf.ignores))) irc.reply(msg, utils.commaAndify(imap(repr, conf.ignores)))
else: else:
irc.reply(msg, 'I\'m not currently globally ignoring anyone.') irc.reply(msg, 'I\'m not currently globally ignoring anyone.')

View File

@ -35,6 +35,7 @@ to have the <channel>.op capability. This plugin is loaded by default.
""" """
import time import time
from itertools import imap
import conf import conf
import debug import debug
@ -266,7 +267,7 @@ class Channel(callbacks.Privmsg):
irc.reply(msg, 'I\'m not currently ignoring any hostmasks ' irc.reply(msg, 'I\'m not currently ignoring any hostmasks '
'in %r' % channel) 'in %r' % channel)
return return
irc.reply(msg, utils.commaAndify(map(repr,c.ignores))) irc.reply(msg, utils.commaAndify(imap(repr,c.ignores)))
ignores = privmsgs.checkChannelCapability(ignores, 'op') ignores = privmsgs.checkChannelCapability(ignores, 'op')

View File

@ -60,7 +60,7 @@ def loadPluginModule(name):
files.extend(os.listdir(dir)) files.extend(os.listdir(dir))
loweredFiles = map(str.lower, files) loweredFiles = map(str.lower, files)
try: try:
index = map(str.lower, files).index(name.lower()+'.py') index = loweredFiles.index(name.lower()+'.py')
name = os.path.splitext(files[index])[0] name = os.path.splitext(files[index])[0]
except ValueError: # We'd rather raise the ImportError, so we'll let go... except ValueError: # We'd rather raise the ImportError, so we'll let go...
pass pass

View File

@ -584,7 +584,7 @@ class Privmsg(irclib.IrcCallback):
if self.isCommand(command): if self.isCommand(command):
#debug.printf('%s: %r' % (command, args)) #debug.printf('%s: %r' % (command, args))
method = getattr(self, command) method = getattr(self, command)
line = '%s %s' % (command, ' '.join(map(utils.dqrepr, args))) line = '%s %s' % (command, ' '.join(imap(utils.dqrepr, args)))
msg = ircmsgs.privmsg(fakeIrc.nick, line, fakeIrc.prefix) msg = ircmsgs.privmsg(fakeIrc.nick, line, fakeIrc.prefix)
try: try:
world.startup = True world.startup = True

View File

@ -41,11 +41,12 @@ import fix
import re import re
import copy import copy
import sets import sets
import time
import random
import string import string
import fnmatch import fnmatch
import operator import operator
import random from itertools import imap
import time
def isUserHostmask(s): def isUserHostmask(s):
"""Returns whether or not the string s is a valid User hostmask.""" """Returns whether or not the string s is a valid User hostmask."""
@ -318,10 +319,10 @@ def unDccIP(i):
assert isinstance(i, (int, long)), '%r is not an number.' % i assert isinstance(i, (int, long)), '%r is not an number.' % i
L = [] L = []
while len(L) < 4: while len(L) < 4:
L.insert(0, i % 256) L.append(i % 256)
i /= 256 i /= 256
return '.'.join(map(str, L)) L.reverse()
return '.'.join(imap(str, L))
class IrcString(str): class IrcString(str):
"""This class does case-insensitive comparison and hashing of nicks.""" """This class does case-insensitive comparison and hashing of nicks."""

View File

@ -39,6 +39,7 @@ import fix
import time import time
import socket import socket
from itertools import imap
import conf import conf
import debug import debug
@ -71,7 +72,7 @@ class SocketDriver(drivers.IrcDriver):
while msgs[-1] is not None: while msgs[-1] is not None:
msgs.append(self.irc.takeMsg()) msgs.append(self.irc.takeMsg())
del msgs[-1] del msgs[-1]
self.outbuffer += ''.join(map(str, msgs)) self.outbuffer += ''.join(imap(str, msgs))
if self.outbuffer: if self.outbuffer:
try: try:
sent = self.conn.send(self.outbuffer) sent = self.conn.send(self.outbuffer)

View File

@ -40,6 +40,7 @@ import fix
import types import types
import pprint import pprint
import string import string
from itertools import imap
class RingBuffer(object): class RingBuffer(object):
"""Class to represent a fixed-size ring buffer.""" """Class to represent a fixed-size ring buffer."""
@ -219,7 +220,7 @@ class queue(object):
return False return False
def __repr__(self): def __repr__(self):
return 'queue([%s])' % ', '.join(map(repr, self)) return 'queue([%s])' % ', '.join(imap(repr, self))
def __getitem__(self, oidx): def __getitem__(self, oidx):
if len(self) == 0: if len(self) == 0:
@ -295,7 +296,7 @@ class smallqueue(list):
return self[0] return self[0]
def __repr__(self): def __repr__(self):
return 'smallqueue([%s])' % ', '.join(map(repr, self)) return 'smallqueue([%s])' % ', '.join(imap(repr, self))
def reset(self): def reset(self):
self[:] = [] self[:] = []