rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if self.DEBUG: print "_add_msg(%r, %r)" % (wordstream, is_spam) | def _add_msg(self, wordstream, is_spam): if self.DEBUG: print "_add_msg(%r, %r)" % (wordstream, is_spam) | |
if self.DEBUG: print "new count for %r = %d" % (word, is_spam and record.spamcount or record.hamcount) | def _add_msg(self, wordstream, is_spam): if self.DEBUG: print "_add_msg(%r, %r)" % (wordstream, is_spam) | |
if self.DEBUG: print "_remove_msg(%r, %r)" % (wordstream, is_spam) | def _remove_msg(self, wordstream, is_spam): if self.DEBUG: print "_remove_msg(%r, %r)" % (wordstream, is_spam) | |
print "TabProcessor init" | def Init(self): self.pages = {} self.currentPage = None self.currentPageIndex = -1 self.currentPageHwnd = None for index, page_id in enumerate(self.page_ids): template = self.window.manager.dialog_parser.dialogs[page_id] self.addPage(index, page_id, template[0][0]) self.switchToPage(0) print "TabProcessor init" | |
(DialogCommand, "IDC_BUT_FILTER_NOW", "IDD_FILTER_NOW"), (DialogCommand, "IDC_BUT_FILTER_DEFINE", "IDD_FILTER"), (DialogCommand, "IDC_BUT_TRAIN_NOW", "IDD_TRAINING"), (DialogCommand, "IDC_ADVANCED_BTN", "IDD_ADVANCED"), | def WizardTrainer(mgr, config, progress): import os, manager, train bayes_base = os.path.join(mgr.data_directory, "$sbwiz$default_bayes_database") mdb_base = os.path.join(mgr.data_directory, "$sbwiz$default_message_database") fnames = [] for ext in ".pck", ".db": fnames.append(bayes_base+ext) fnames.append(mdb_base+ext... | |
(CommandButtonProcessor, "IDC_ABOUT_BTN", ShowAbout, ()), | (CommandButtonProcessor, "IDC_BUT_ABOUT", ShowAbout, ()), | def WizardTrainer(mgr, config, progress): import os, manager, train bayes_base = os.path.join(mgr.data_directory, "$sbwiz$default_bayes_database") mdb_base = os.path.join(mgr.data_directory, "$sbwiz$default_message_database") fnames = [] for ext in ".pck", ".db": fnames.append(bayes_base+ext) fnames.append(mdb_base+ext... |
SPAM_THRESHOLD = options.spam_cutoff HAM_THRESHOLD = options.ham_cutoff | SPAM_THRESHOLD = options["Categorization", "spam_cutoff"] HAM_THRESHOLD = options["Categorization", "ham_cutoff"] | def bool(val): return not not val |
return Hammie(storage.open_storage((filename, mode), useDB) | return Hammie(storage.open_storage((filename, mode), useDB)) | def open(filename, useDB=True, mode='r'): """Open a file, returning a Hammie instance. If usedb is False, open as a pickle instead of a DBDict. mode is used as the flag to open DBDict objects. 'c' for read-write (create if needed), 'r' for read-only, 'w' for read-write. """ return Hammie(storage.open_storage((filen... |
print >> sys.stderr, ("Attempted to set [%s] %s with invalid" " value %s (%s)" % | print >> sys.stderr, ("Attempted to set [%s] %s with " "invalid value %s (%s)" % | def set(self, sect, opt, val=None): '''Set an option.''' if self.conversion_table.has_key((sect, opt.lower())): sect, opt = self.conversion_table[sect, opt.lower()] if self.is_valid(sect, opt, val): self._options[sect, opt.lower()].set(val) else: print >> sys.stderr, ("Attempted to set [%s] %s with invalid" " value %s ... |
import textwrap | def _report_option_error(self, sect, opt, val, stream, msg): import textwrap if sect in self.sections(): vopts = self.options(True) vopts = [v.split(']', 1)[1] for v in vopts if v.startswith('[%s]'%sect)] if opt not in vopts: print >> stream, "Invalid option:", opt print >> stream, "Valid options for", sect, "are:" vop... | |
vopts = textwrap.wrap(vopts) | vopts = wrap(vopts) | def _report_option_error(self, sect, opt, val, stream, msg): import textwrap if sect in self.sections(): vopts = self.options(True) vopts = [v.split(']', 1)[1] for v in vopts if v.startswith('[%s]'%sect)] if opt not in vopts: print >> stream, "Invalid option:", opt print >> stream, "Valid options for", sect, "are:" vop... |
vsects = textwrap.wrap(vsects) | vsects = wrap(vsects) | def _report_option_error(self, sect, opt, val, stream, msg): import textwrap if sect in self.sections(): vopts = self.options(True) vopts = [v.split(']', 1)[1] for v in vopts if v.startswith('[%s]'%sect)] if opt not in vopts: print >> stream, "Invalid option:", opt print >> stream, "Valid options for", sect, "are:" vop... |
import textwrap | def display(self, add_comments=False): '''Display options in a config file form.''' import textwrap output = StringIO.StringIO() keys = self._options.keys() keys.sort() currentSection = None for sect, opt in keys: if sect != currentSection: if currentSection is not None: output.write('\n') output.write('[') output.writ... | |
self.manager.classifier_data.message_db.store_msg(msg) | self.manager.classifier_data.message_db.store_msg(msgstore_message) | def OnClick(self, button, cancel): msgstore = self.manager.message_store msgstore_messages = self.explorer.GetSelectedMessages(True) if not msgstore_messages: return # If we are not yet enabled, tell the user. # (This is better than disabling the button as a) the user may not # understand why it is disabled, and b) as ... |
except: | except (BaseIMAP.error, socket.gaierror, socket.error): | def __init__(self, server, port, debug=0, do_expunge=False): try: BaseIMAP.__init__(self, server, port) except: # A more specific except would be good here, but I get # (in Python 2.2) a generic 'error' and a 'gaierror' # if I pass a valid domain that isn't an IMAP server # or invalid domain (respectively) print "Inval... |
sys.exit(-1) | sys.exit() | def __init__(self, server, port, debug=0, do_expunge=False): try: BaseIMAP.__init__(self, server, port) except: # A more specific except would be good here, but I get # (in Python 2.2) a generic 'error' and a 'gaierror' # if I pass a valid domain that isn't an IMAP server # or invalid domain (respectively) print "Inval... |
if str(e) == "permission denied": | if str(e) == "permission denied" or str(e) == "Login failed.": | def login(self, username, pwd): try: BaseIMAP.login(self, username, pwd) # superclass login except BaseIMAP.error, e: if str(e) == "permission denied": print "There was an error logging in to the IMAP server." print "The userid and/or password may be incorrect." sys.exit() else: raise self.logged_in = True |
opts, args = getopt.getopt(sys.argv[1:], 'hn:s:v', ['help']) | opts, args = getopt.getopt(sys.argv[1:], 'hgn:s:v', ['help']) | def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hn:s:v', ['help']) except getopt.error, msg: usage(1, msg) n = None verbose = False for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt == '-s': random.seed(int(arg)) elif opt == '-n': n = int(arg) elif opt == '-v': verbose = True if n is None... |
mbox = mboxutils.getmbox(inputpath) for msg in mbox: i = random.randrange(n) astext = str(msg) counter += 1 msgfile = open('%s/%d' % (outdirs[i], counter), 'wb') msgfile.write(astext) msgfile.close() if verbose: if counter % 100 == 0: sys.stdout.write('.') sys.stdout.flush() | if doglob: inpaths = glob.glob(inputpath) else: inpaths = [inputpath] for inpath in inpaths: mbox = mboxutils.getmbox(inpath) for msg in mbox: i = random.randrange(n) astext = str(msg) counter += 1 msgfile = open('%s/%d' % (outdirs[i], counter), 'wb') msgfile.write(astext) msgfile.close() if verbose: if counter % 100... | def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hn:s:v', ['help']) except getopt.error, msg: usage(1, msg) n = None verbose = False for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt == '-s': random.seed(int(arg)) elif opt == '-n': n = int(arg) elif opt == '-v': verbose = True if n is None... |
print >> sys.stderr, path | def make_HammieFilter(): # The sb_hammie script has some logic in the HammieFiler class that we need here too. # Ideally that should be moved into the spambayes package, but for now lets just # abuse sys.path, make assumptions about the directory layout, and import it direct # from the sb_filter script. from spambayes ... | |
messageName = "%10.10d" % time.time() | messageName = "%10.10d" % long(time.time()) | def onRetr(self, command, args, response): """Adds the judgement header based on the raw headers and body of the message.""" # Use '\n\r?\n' to detect the end of the headers in case of # broken emails that don't use the proper line separators. if re.search(r'\n\r?\n', response): # Break off the first line, which will b... |
summary = """POP3 proxy running on port <b>%(proxyPort)d</b>, proxying to <b>%(serverName)s:%(serverPort)d</b>.<br> | summary = """POP3 proxy running on <b>%(proxyPortsString)s</b>, proxying to <b>%(serversString)s</b>.<br> | def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap) |
<b>%(numHams)d</b> ham, <b>%(numUnsure)d</b> unsure. | <b>%(numHams)d</b> ham, <b>%(numUnsure)d</b> unsure.<br> Total emails trained: Spam: <b>%(nspam)d</b> Ham: <b>%(nham)d</b><br> <form action='save' method='POST'> <input type='submit' value='Save database'> </form> | def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap) |
reviewHeader = """<p>These are unclassified emails, which you can use to train the classifier. Check the Discard / Ham / Spam buttton for each email, then click 'Train' below. (To discard the whole page, leave everything with Discard checked and click 'Train'.)</p> | reviewHeader = """<p>These are untrained emails, which you can use to train the classifier. Check the Discard / Defer / Ham / Spam buttton for each email, then click 'Train' below. (Defer leaves the message here, to be trained on later.)</p> | def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap) |
<tr><td><b>Subject:</b></td><td><b>From:</b></td> <td><b>Discard / Ham / Spam</b></td></tr>""" | <tr><td><b>Messages classified as %s:</b></td> <td><b>From:</b></td> <td><b>Discard / Defer / Ham / Spam</b></td></tr>""" | def __init__(self, uiPort, socketMap=asyncore.socket_map): Listener.__init__(self, uiPort, UserInterface, (), socketMap=socketMap) |
image = "<img src='/helmet.gif' align='absmiddle'> " | image = "<img src='helmet.gif' align='absmiddle'> " | def pushPreamble(self, name, showImage=True): self.push(self.header % name) if name == 'Home': homeLink = name else: homeLink = "<a href='home'>Home</a> > %s" % name if showImage: image = "<img src='/helmet.gif' align='absmiddle'> " else: image = "" self.push(self.bodyStart % (image, homeLink)) |
body = (self.pageSection % ('Status', self.summary % state.__dict__)+ | stateDict = state.__dict__ stateDict.update(state.bayes.__dict__) body = (self.pageSection % ('Status', self.summary % stateDict)+ | def onHome(self, params): """Serve up the homepage.""" body = (self.pageSection % ('Status', self.summary % state.__dict__)+ self.pageSection % ('Train on proxied messages', self.review)+ self.pageSection % ('Train on a given message', self.train)+ self.pageSection % ('Classify a message', self.classify)+ self.pageSect... |
if not state.useDB and state.databaseFilename: self.push("<b>Saving...</b>") self.push(' ') state.bayes.store() | self.doSave() | def onShutdown(self, params): """Shutdown the server, saving the pickle if requested to do so.""" if params['how'].lower().find('save') >= 0: if not state.useDB and state.databaseFilename: self.push("<b>Saving...</b>") self.push(' ') # Acts as a flush for small buffers. state.bayes.store() self.push("<b>Shutdown</b>. ... |
return int(key[:10]) | return long(key[:10]) | def keyToTimestamp(self, key): """Given a message key (as seen in a Corpus), returns the timestamp for that message. This is the time that the message was received, not the Date header.""" return int(key[:10]) |
startKeyIndex = bisect.bisect(allKeys, "%d" % start) endKeyIndex = bisect.bisect(allKeys, "%d" % end) | startKeyIndex = bisect.bisect(allKeys, "%d" % long(start)) endKeyIndex = bisect.bisect(allKeys, "%d" % long(end)) | def buildReviewKeys(self, timestamp): """Builds an ordered list of untrained message keys, ready for output in the Review list. Returns a 5-tuple: the keys, the formatted date for the list (eg. "Friday, November 15, 2002"), the start of the prior page or zero if there isn't one, likewise the start of the given page, a... |
trainRadio = """<input type='radio' name='classify:%s' value='discard' checked> <input type='radio' name='classify:%s' value='ham'> <input type='radio' name='classify:%s' value='spam'>""" | def onReview(self, params): """Present a list of message for (re)training.""" | |
else: | elif value == 'discard': | def onReview(self, params): """Present a list of message for (re)training.""" |
state.unknownCorpus.removeMessage(state.unknownCorpus[id]) | try: state.unknownCorpus.removeMessage(state.unknownCorpus[id]) except KeyError: pass else: targetCorpus = None numDeferred += 1 | def onReview(self, params): """Present a list of message for (re)training.""" |
if id: | if numDeferred > 0: start = self.keyToTimestamp(id) elif id: | def onReview(self, params): """Present a list of message for (re)training.""" |
stripe = 0 for key in keys: cachedMessage = state.unknownCorpus[key] message = mboxutils.get_message(cachedMessage.getSubstance()) subject = self.trimAndQuote(message["Subject"] or "(none)", 50) from_ = self.trimAndQuote(message["From"] or "(none)", 40) key = cachedMessage.key() radioGroup = trainRadio % (key, key, ... | for header, type in ((options.header_spam_string, 'Spam'), (options.header_ham_string, 'Ham'), (options.header_unsure_string, 'Unsure')): if keyedMessages[header]: lines.append("<tr><td> </td><td></td><td></td></tr>") lines.append(self.reviewSubheader % type) self.appendMessages(lines, keyedMessages[header], heade... | def onReview(self, params): """Present a list of message for (re)training.""" |
title = "Unclassified messages received on %s" % date else: content = "<p>There are no unclassified messages to display.</p>" title = "No unclassified messages" | title = "Untrained messages received on %s" % date else: content = "<p>There are no untrained messages to display.</p>" title = "No untrained messages" | def onReview(self, params): """Present a list of message for (re)training.""" |
self.proxyPort = options.pop3proxy_port self.serverName = options.pop3proxy_server_name self.serverPort = options.pop3proxy_server_port | if options.pop3proxy_port != 110 or \ options.pop3proxy_server_name != '' or \ options.pop3proxy_server_port != 110: print "\n pop3proxy_port, pop3proxy_server_name and" print " pop3proxy_server_port are deprecated! Please use" print " pop3proxy_servers and pop3proxy_ports instead.\n" self.servers = [(options... | def __init__(self): """Initialises the State object that holds the state of the app. The default settings are read from Options.py and bayescustomize.ini and are then overridden by the command-line processing code in the __main__ code below.""" # Open the log file. self.logFile = open('_pop3proxy.log', 'wb', 0) |
def main(serverName, serverPort, proxyPort, uiPort, launchUI, databaseFilename, useDB): | def main(servers, proxyPorts, uiPort, launchUI): | def main(serverName, serverPort, proxyPort, uiPort, launchUI, databaseFilename, useDB): """Runs the proxy forever or until a 'KILL' command is received or someone hits Ctrl+Break.""" BayesProxyListener(serverName, serverPort, proxyPort) UserInterfaceListener(uiPort) if launchUI: webbrowser.open_new("http://localhost:%d... |
BayesProxyListener(serverName, serverPort, proxyPort) | for (server, serverPort), proxyPort in zip(servers, proxyPorts): BayesProxyListener(server, serverPort, proxyPort) | def main(serverName, serverPort, proxyPort, uiPort, launchUI, databaseFilename, useDB): """Runs the proxy forever or until a 'KILL' command is received or someone hits Ctrl+Break.""" BayesProxyListener(serverName, serverPort, proxyPort) UserInterfaceListener(uiPort) if launchUI: webbrowser.open_new("http://localhost:%d... |
state.proxyPort = int(arg) | state.proxyPorts = [int(arg)] | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. UserInterfaceListener(8881) BayesProxyListener('localhost', 8110, 8111) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
if len(args) >= 1: state.serverName = args[0] if len(args) >= 2: state.serverPort = int(args[1]) if not state.serverName: | if len(args) == 1: state.servers = [(args[0], 110)] elif len(args) == 2: state.servers = [(args[0], int(args[1]))] if not state.servers or not state.servers[0][0]: | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. UserInterfaceListener(8881) BayesProxyListener('localhost', 8110, 8111) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
"bayescustomize.ini as pop3proxy_server_name or on the\n" | "bayescustomize.ini as pop3proxy_servers or on the\n" | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. UserInterfaceListener(8881) BayesProxyListener('localhost', 8110, 8111) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
main(state.serverName, state.serverPort, state.proxyPort, state.uiPort, state.launchUI, state.databaseFilename, state.useDB) | state.buildServerStrings() main(state.servers, state.proxyPorts, state.uiPort, state.launchUI) | def runProxy(): # Name the database in case it ever gets auto-flushed to disk. UserInterfaceListener(8881) BayesProxyListener('localhost', 8110, 8111) state.bayes.learn(tokenizer.tokenize(spam1), True) state.bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop() |
print >> sys.stderr, "You do not have a dbm module available " \ | print >> sys.stderr, "\nYou do not have a dbm module available " \ | def open_storage(data_source_name, useDB=True, mode=None): """Return a storage object appropriate to the given parameters. By centralizing this code here, all the applications will behave the same given the same options. If useDB is false, a pickle will be used, otherwise if the data source name includes "::", whatev... |
import sys | def open_storage(data_source_name, useDB=True, mode=None): """Return a storage object appropriate to the given parameters. By centralizing this code here, all the applications will behave the same given the same options. If useDB is false, a pickle will be used, otherwise if the data source name includes "::", whatev... | |
win32gui.MessageBox(self.hwnd, str(why), self.dialog_def.caption, mb_flags) | win32gui.MessageBox(self.hwnd, str(why), "SpamBayes", mb_flags) | def ApplyHandlingOptionValueError(self, func, *args): try: func(*args) return True except ValueError, why: mb_flags = win32con.MB_ICONEXCLAMATION | win32con.MB_OK win32gui.MessageBox(self.hwnd, str(why), self.dialog_def.caption, mb_flags) return False |
code_only = os.path.join(LC_DIR, lcode.split("_")[0], 'DIALOGS') | code_only = os.path.join(DIALOGS_DIR, lcode.split("_")[0], 'DIALOGS') | def _rebuild_syspath_for_dialogs(self): """Add to sys.path the directories of the translated dialogs. |
def __init__(self, serverName, serverPort, lineCallback, ssl=False): Dibbler.BrighterAsyncChat.__init__(self) | def __init__(self, serverName, serverPort, lineCallback, ssl=False, map=None): Dibbler.BrighterAsyncChat.__init__(self, map=map) | def __init__(self, serverName, serverPort, lineCallback, ssl=False): Dibbler.BrighterAsyncChat.__init__(self) self.lineCallback = lineCallback self.request = '' self.set_terminator('\r\n') self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # create_socket creates a non-blocking socket. This is not great, # because... |
del self.ssl_socket, self.socket | del self.ssl_socket | def handle_close(self): self.lineCallback('') self.close() try: del self.ssl_socket, self.socket except AttributeError: pass |
def __init__(self, clientSocket, serverName, serverPort, ssl=False): | def __init__(self, clientSocket, serverName, serverPort, ssl=False, map=Dibbler._defaultContext._map): | def __init__(self, clientSocket, serverName, serverPort, ssl=False): Dibbler.BrighterAsyncChat.__init__(self, clientSocket) self.request = '' self.response = '' self.set_terminator('\r\n') self.command = '' # The POP3 command being processed... self.args = [] # ...and its arguments self.isClosing... |
self.onServerLine, ssl) | self.onServerLine, ssl, map) | def __init__(self, clientSocket, serverName, serverPort, ssl=False): Dibbler.BrighterAsyncChat.__init__(self, clientSocket) self.request = '' self.response = '' self.set_terminator('\r\n') self.command = '' # The POP3 command being processed... self.args = [] # ...and its arguments self.isClosing... |
def open_platform_mutex(): | def open_platform_mutex(mutex_name="SpamBayesServer"): | def open_platform_mutex(): if sys.platform.startswith("win"): try: import win32event, win32api, winerror, win32con import pywintypes, ntsecuritycon # ideally, the mutex name could include either the username, # or the munged path to the INI file - this would mean we # would allow multiple starts so long as they weren't... |
mutex_name = "SpamBayesServer" | def open_platform_mutex(): if sys.platform.startswith("win"): try: import win32event, win32api, winerror, win32con import pywintypes, ntsecuritycon # ideally, the mutex name could include either the username, # or the munged path to the INI file - this would mean we # would allow multiple starts so long as they weren't... | |
factory = GzipFileMessageFactory(self.mdb) | factory = GzipFileMessageFactory() | def createWorkers(self): """Using the options that were initialised in __init__ and then possibly overridden by the driver code, create the Bayes object, the Corpuses, the Trainers and so on.""" print "Loading database...", if self.isTest: self.useDB = "pickle" self.DBName = '_pop3proxy_test.pickle' # This is never s... |
factory = FileMessageFactory(self.mdb) | factory = FileMessageFactory() | def createWorkers(self): """Using the options that were initialised in __init__ and then possibly overridden by the driver code, create the Bayes object, the Corpuses, the Trainers and so on.""" print "Loading database...", if self.isTest: self.useDB = "pickle" self.DBName = '_pop3proxy_test.pickle' # This is never s... |
from textwrap import wrap | from textwrap import fill | def _wrap(self, text, width=70): """Wrap the text into lines no bigger than the specified width.""" try: from textwrap import wrap except ImportError: pass else: return '\n'.join(wrap(text, width)) # No textwrap module, so do the same stuff (more-or-less) ourselves. wordsep_re = re.compile(r'(\s+|' # a... |
return '\n'.join(wrap(text, width)) | return "\n".join([fill(paragraph, width) \ for paragraph in text.split('\n')]) | def _wrap(self, text, width=70): """Wrap the text into lines no bigger than the specified width.""" try: from textwrap import wrap except ImportError: pass else: return '\n'.join(wrap(text, width)) # No textwrap module, so do the same stuff (more-or-less) ourselves. wordsep_re = re.compile(r'(\s+|' # a... |
wordsep_re = re.compile(r'(\s+|' r'-*\w{2,}-(?=\w{2,})|' r'(?<=\S)-{2,}(?=\w))') if len(text) <= width: return [text] chunks = wordsep_re.split(text) chunks = filter(None, chunks) return '\n'.join(self._wrap_chunks(chunks, width)) | def fill(text, width): if len(text) <= width: return text wordsep_re = re.compile(r'(-*\w{2,}-(?=\w{2,})|' r'(?<=\S)-{2,}(?=\w))') chunks = wordsep_re.split(text) chunks = filter(None, chunks) return '\n'.join(self._wrap_chunks(chunks, width)) return "\n".join([fill(paragraph, width) \ for paragraph in text.split('\n')... | def _wrap(self, text, width=70): """Wrap the text into lines no bigger than the specified width.""" try: from textwrap import wrap except ImportError: pass else: return '\n'.join(wrap(text, width)) # No textwrap module, so do the same stuff (more-or-less) ourselves. wordsep_re = re.compile(r'(\s+|' # a... |
start = string.index(address, '<') + 1 end = string.index(address, '>') return address[start:end] | if '<' in address: start = string.index(address, '<') + 1 end = string.index(address, '>') return address[start:end] else: return address | def stripAddress(self, address): """ Strip the leading & trailing <> from an address. Handy for getting FROM: addresses. """ start = string.index(address, '<') + 1 end = string.index(address, '>') return address[start:end] |
elif e[0] == errno.ENOENT: | elif e[0] == errno.ENOENT or not os.path.exists(file): | def make_socket(server_options, file): refused_count = 0 no_server_count = 0 while 1: try: s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) s.connect(file) except socket.error,e: if e[0] == errno.EAGAIN: # baaah pass elif e[0] == errno.ENOENT: # no such file.... no such server. create one. no_server_count += 1 if n... |
hr, data = folder.GetProps((PR_DISPLAY_NAME_A,), 0) name = data[0][1] count = parent.GetContentsTable(0).GetRowCount(0) return MAPIMsgStoreFolder(self.msgstore, parent_id, name, count) | return self._FolderFromMAPIFolder(parent) | def GetParent(self): # return a folder object with the parent, or None folder = self.msgstore._OpenEntry(self.id) prop_ids = PR_PARENT_ENTRYID, hr, data = folder.GetProps(prop_ids,0) # Put parent ids together parent_eid = data[0][1] parent_id = self.id[0], parent_eid if hr != 0 or \ self.msgstore.session.CompareEntryID... |
fd, orf = tempfile.mkstemp() os.close(fd) | def extract_ocr_info(self, pnmfiles): fd, orf = tempfile.mkstemp() os.close(fd) | |
ocr = os.popen("%s -s %s -c %s -x %s -f %s 2>%s" % | ocr = os.popen("%s -s %s -c %s -f %s 2>%s" % | def extract_ocr_info(self, pnmfiles): fd, orf = tempfile.mkstemp() os.close(fd) |
orf, pnmfile, os.path.devnull)) | pnmfile, os.path.devnull)) | def extract_ocr_info(self, pnmfiles): fd, orf = tempfile.mkstemp() os.close(fd) |
for line in open(orf): if line.startswith("lines"): nlines = int(line.split()[1]) if nlines: ctokens.add("image-text-lines:%d" % int(log2(nlines))) | nlines = len(ctext.strip().split("\n")) if nlines: ctokens.add("image-text-lines:%d" % int(log2(nlines))) | def extract_ocr_info(self, pnmfiles): fd, orf = tempfile.mkstemp() os.close(fd) |
os.unlink(orf) | def extract_ocr_info(self, pnmfiles): fd, orf = tempfile.mkstemp() os.close(fd) | |
print "Could not find message (%s); perhaps it was " + \ "deleted from the POP3Proxy cache or the IMAP " + \ | print "Could not find message (%s); perhaps it was " \ "deleted from the POP3Proxy cache or the IMAP " \ | def train_cached_message(self, id, isSpam): if not self.train_message_in_pop3proxy_cache(id, isSpam) and \ not self.train_message_on_imap_server(id, isSpam): print "Could not find message (%s); perhaps it was " + \ "deleted from the POP3Proxy cache or the IMAP " + \ "server. This means that no training was done." % (i... |
print msg.get_payload() print msg.as_string() | def setPayload(self, payload): # This is a less-than-ideal method. The Python email package # has a clear distinction between parsing an email message and # creating an email message object. Here, we don't share that # distinction, because our message object is trying to do its # own parsing. A better system would b... | |
return val | return val.decode("mbcs", "ignore") | def GetProfileName(self): # Return the name of the MAPI profile currently in use. # XXX - note - early win32all versions are missing # GetStatusTable :( try: self.session.GetStatusTable except AttributeError: # We try and recover from this when win32all is updated, so no need to whinge. return None |
return re.sub(r'&(\w+);', r':PyMeldEntity:\1:', data) | return re.sub(r'&([A-Za-z0-9 | def _mungeEntities(self, data): return re.sub(r'&(\w+);', r':PyMeldEntity:\1:', data) |
return re.sub(r':PyMeldEntity:(\w+):', r'&\1;', data) | return re.sub(r':PyMeldEntity:([A-Za-z0-9 | def _unmungeEntities(self, data): return re.sub(r':PyMeldEntity:(\w+):', r'&\1;', data) |
return self._wrap_chunks(chunks, width) | return '\n'.join(self._wrap_chunks(chunks, width)) | def _wrap(self, text, width=70): """Wrap the text into lines no bigger than the specified width.""" try: from textwrap import wrap except ImportError: pass else: return '\n'.join(wrap(text, width)) # No textwrap module, so do the same stuff (more-or-less) ourselves. wordsep_re = re.compile(r'(\s+|' # a... |
oldShelvePickler = shelve.Pickler def binaryDefaultPickler(f, binary=1): return oldShelvePickler(f, binary) shelve.Pickler = binaryDefaultPickler | def bool(val): return not not val | |
self._setId(id) def _setId(self, id): | def setId(self, id): if self.id: raise ValueError, "MsgId has already been set, cannot be changed" # we should probably enforce type(id) is StringType. # the database will insist upon it, but at that point, it's harder # to diagnose if id is None: raise ValueError, "MsgId must not be None" self.id = id msginfoDB._get... | |
filter.filterer(mgr, progress) | filter.filterer(mgr, mgr.config, progress) | def trainer(mgr, config, progress): rebuild = config.training.rebuild rescore = config.training.rescore if not config.training.ham_folder_ids or not config.training.spam_folder_ids: progress.error("You must specify at least one spam, and one good folder") return if rebuild: # Make a new temporary bayes database to us... |
if item.Class == constants.olMail: msgstore_message = self.manager.message_store.GetMessage(item) | msgstore_message = self.manager.message_store.GetMessage(item) if msgstore_message and msgstore_message.IsFilterCandidate(): | def GetSelectedMessages(self, allow_multi = True, explorer = None): if explorer is None: explorer = self.Application.ActiveExplorer() sel = explorer.Selection if sel.Count > 1 and not allow_multi: self.manager.ReportError("Please select a single item", "Large selection") return None |
print "Bayes database is not dirty - not writing" | self.LogDebug(1, "Bayes database is not dirty - not writing") | def SaveBayesPostIncrementalTrain(self): # Save the database after a training operation - only actually # saves if we aren't using pickles. if self.db_manager.is_incremental(): if self.bayes_dirty: self.SaveBayes() else: print "Bayes database is not dirty - not writing" else: print "Using a slow database - not saving a... |
self.assert_(disp not in header) | self.assertEqual(header.find(disp), -1) | def test_delNotations(self): # Add each type of notation to each header and check that it # is removed. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "notate_%s" % (hea... |
self.assert_(disp in self.msg[headername]) | self.assertNotEqual(self.msg[headername].find(disp), -1) | def test_delNotations(self): # Add each type of notation to each header and check that it # is removed. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "notate_%s" % (hea... |
self.assert_(disp not in header) | self.assertEqual(header.find(disp), -1) | def test_delNotations_missing(self): # Check that nothing is removed if the disposition is not # there. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "notate_%s" % (hea... |
self.assert_(disp not in self.msg[headername]) | self.assertEqual(self.msg[headername].find(disp), -1) | def test_delNotations_missing(self): # Check that nothing is removed if the disposition is not # there. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "notate_%s" % (hea... |
def test_delNotations_only_once(self): | def test_delNotations_no_header(self): for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): del self.msg[headername] options["Headers", "notate_%s" % (headername,)] = \ (self.ham, self.unsure, self.spam) self.msg.delNotations() self.assertEqual(self.msg[headername], None) def test_delN... | def test_delNotations_only_once(self): # Check that only one disposition is removed, even if more than # one is present. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "... |
for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): header = self.msg[headername] self.assert_(disp not in header) options["Headers", "notate_%s" % (headername,)] = \ (self.ham, self.unsure, self.spam) prob = {self.ham:self.g_prob, self.spam:self.s_prob, self.unsure:self.u_prob}[disp] ... | for disp in (self.ham, self.spam, self.unsure): header = self.msg[headername] self.assertEqual(header.find(disp), -1) options["Headers", "notate_%s" % (headername,)] = \ (self.ham, self.unsure, self.spam) prob = {self.ham:self.g_prob, self.spam:self.s_prob, self.unsure:self.u_prob}[disp] self.msg.addSBHeaders(prob, se... | def test_delNotations_only_once(self): # Check that only one disposition is removed, even if more than # one is present. for headername in ["subject", "to"]: for disp in (self.ham, self.spam, self.unsure): # Add a notation to the header header = self.msg[headername] self.assert_(disp not in header) options["Headers", "... |
for cls in (MessageTest, SBHeaderMessageTest, MessageInfoPickleTest, MessageInfoDBTest, UtilitiesTest, ): | classes = (MessageTest, SBHeaderMessageTest, MessageInfoPickleTest, UtilitiesTest, ) from spambayes import dbmstorage try: dbmstorage.open_best() except dbmstorage.error: print "Skipping MessageInfoDBTest - no dbm module available" from spambayes import message def always_pickle(): return "__test.pik", "pickle" message... | def suite(): suite = unittest.TestSuite() for cls in (MessageTest, SBHeaderMessageTest, MessageInfoPickleTest, MessageInfoDBTest, UtilitiesTest, ): suite.addTest(unittest.makeSuite(cls)) return suite |
popup = self._AddControl( None, constants.msoControlPopup, None, None, Caption="SpamBayes", TooltipText = "SpamBayes anti-spam filters and functions", Enabled = True, Tag = "SpamBayesCommand.Popup") if popup is not None: | popup = None for attempt in range(2): popup = self._AddControl( None, constants.msoControlPopup, None, None, Caption="SpamBayes", TooltipText = "SpamBayes anti-spam filters and functions", Enabled = True, Tag = "SpamBayesCommand.Popup") if popup is None: break | def SetupUI(self): manager = self.manager assert self.toolbar is None, "Should not yet have a toolbar" |
self._AddControl(popup, | child = self._AddControl(popup, | def SetupUI(self): manager = self.manager assert self.toolbar is None, "Should not yet have a toolbar" |
print "Found SB toolbar - visible state is", toolbar.Visible | def _AddControl(self, parent, # who the control is added to control_type, # type of control to add. events_class, events_init_args, # class/Init() args **item_attrs): # extra control attributes. # Outlook Toolbars suck :) # We have tried a number of options: temp/perm in the standard toolbar, # Always creating our own ... | |
traceback.print_exc() | def _AddControl(self, parent, # who the control is added to control_type, # type of control to add. events_class, events_init_args, # class/Init() args **item_attrs): # extra control attributes. # Outlook Toolbars suck :) # We have tried a number of options: temp/perm in the standard toolbar, # Always creating our own ... | |
str = whichdb.whichdb("dumbdb") if str: | dbstr = whichdb.whichdb("dumbdb") if dbstr: | def main(): print "Pickle is available." db = dumbdbm.open("dumbdb", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dumbdb") if str: print "Dumbdbm is available." else: print "Dumbdbm is not available." db = dbhash.open("dbhash", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dbhash") if str == "dbhash": p... |
str = whichdb.whichdb("dbhash") if str == "dbhash": | dbstr = whichdb.whichdb("dbhash") if dbstr == "dbhash": | def main(): print "Pickle is available." db = dumbdbm.open("dumbdb", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dumbdb") if str: print "Dumbdbm is available." else: print "Dumbdbm is not available." db = dbhash.open("dbhash", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dbhash") if str == "dbhash": p... |
str = "" | dbstr = "" | def main(): print "Pickle is available." db = dumbdbm.open("dumbdb", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dumbdb") if str: print "Dumbdbm is available." else: print "Dumbdbm is not available." db = dbhash.open("dbhash", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dbhash") if str == "dbhash": p... |
str = whichdb.whichdb("bsddb3") if str == "dbhash": | dbstr = whichdb.whichdb("bsddb3") if dbstr == "dbhash": | def main(): print "Pickle is available." db = dumbdbm.open("dumbdb", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dumbdb") if str: print "Dumbdbm is available." else: print "Dumbdbm is not available." db = dbhash.open("dbhash", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dbhash") if str == "dbhash": p... |
try: db = dbhash.open(hammie, "c") except: print "Your storage %s is a: bsddb3" % (hammie,) return | if hasattr(bsddb, '__version__'): try: db = bsddb.hashopen(hammie, "r") except bsddb.error: pass else: db.close() print "Your storage", hammie, "is a: bsddb[3]" return | def main(): print "Pickle is available." db = dumbdbm.open("dumbdb", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dumbdb") if str: print "Dumbdbm is available." else: print "Dumbdbm is not available." db = dbhash.open("dbhash", "c") db["1"] = "1" db.close() str = whichdb.whichdb("dbhash") if str == "dbhash": p... |
if (notate_opt is not None) and (opt in notate_opt) and \ | if opt in notate_opt and msg[header] is not None and \ | def takeMessage(self, key, fromcorpus, fromCache=False): '''Move a Message from another corpus to this corpus''' msg = fromcorpus[key] msg.load() # ensure that the substance has been loaded |
self.push("250 OK\r\n") | self.push("354 Enter data ending with a . on a line by itself\r\n") | def onData(self, command, args): self.inData = True if self.train_as_ham == True or self.train_as_spam == True: self.push("250 OK\r\n") return None rv = command for arg in args: rv += ' ' + arg return rv |
rv = command for arg in args: rv += ' ' + arg return rv | return command + ' ' + ' '.join(args) | def onData(self, command, args): self.inData = True if self.train_as_ham == True or self.train_as_spam == True: self.push("250 OK\r\n") return None rv = command for arg in args: rv += ' ' + arg return rv |
self.current_control_tick = 0 | def _next_stage(self): if self.current_stage == 0: win32api.PostMessage(self.hprogress, commctrl.PBM_SETRANGE, 0, MAKELPARAM(0,self.total_control_ticks)) win32api.PostMessage(self.hprogress, commctrl.PBM_SETSTEP, 1, 0) win32api.PostMessage(self.hprogress, commctrl.PBM_SETPOS, 0, 0) self.current_control_tick = 0 | |
self.current_stage_tick = 0 | def set_max_ticks(self, m): self._next_stage() self.current_stage_tick = 0 self.current_stage_max = m | |
self.current_stage_tick += 1 | if self.current_stage_tick < self.current_stage_max: self.current_stage_tick += 1 | def tick(self): self.current_stage_tick += 1 # Calc how far through this stage. this_prop = float(self.current_stage_tick) / self.current_stage_max # How far through the total. stage_name, start, end = self._get_current_stage() # Calc the perc of the total control. stage_name, start, prop = self._get_current_stage() to... |
while self.current_control_tick < control_tick: self.current_control_tick += 1 win32api.PostMessage(self.hprogress, commctrl.PBM_STEPIT, 0, 0) | if verbose: print "Tick", self.current_stage_tick, "is", this_prop, "through the stage,", total_prop, "through the total - ctrl tick is", control_tick win32api.PostMessage(self.hprogress, commctrl.PBM_SETPOS, control_tick) | def tick(self): self.current_stage_tick += 1 # Calc how far through this stage. this_prop = float(self.current_stage_tick) / self.current_stage_max # How far through the total. stage_name, start, end = self._get_current_stage() # Calc the perc of the total control. stage_name, start, prop = self._get_current_stage() to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.