rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
f.write("\n")
f.write("\n\n")
def onUpload(self, params): message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') # Append the message to a file, to make it easier to rebuild # the database later. message = message.replace('\r\n', '\n').replace('\r', '\n') if isSpam: f = open("_pop3proxyspam.mbox", "a") else: f = ope...
self.push("""<p>Trained on your message. Saving database...</p>""") self.push(" ") if not status.useDB and status.pickleName: fp = open(status.pickleName, 'wb') cPickle.dump(self.bayes, fp, 1) fp.close() self.push("<p>Done.</p><p><a href='/'>Home</a></p>")
self.push("<p>OK. Return <a href='/'>Home</a> or train another:</p>") self.push(self.pageSection % ('Train another', self.train))
def onUpload(self, params): message = params.get('file') or params.get('text') isSpam = (params['which'] == 'spam') # Append the message to a file, to make it easier to rebuild # the database later. message = message.replace('\r\n', '\n').replace('\r', '\n') if isSpam: f = open("_pop3proxyspam.mbox", "a") else: f = ope...
body = (self.pageSection % ("Statistics for '%s':" % word, info) +
body = (self.pageSection % ("Statistics for '%s'" % word, info) +
def onWordquery(self, params): word = params['word'] try: # Must be a better way to get __dict__ for a new-style class... wi = self.bayes.wordinfo[word] members = dict(map(lambda n: (n, getattr(wi, n)), wi.__slots__)) members['atime'] = time.asctime(time.localtime(members['atime'])) info = """Number of spam messages: <...
number = int(args)
try: number = int(args) except ValueError: number = -1
def onList(self, command, args): """POP3 LIST command, with optional message number argument.""" if args: number = int(args) if 0 < number <= len(self.maildrop): return "+OK %d\r\n" % len(self.maildrop[number-1]) else: return "-ERR no such message\r\n" else: returnLines = ["+OK"] for messageIndex in range(len(self.mail...
return self._getMessage(int(args), 12345)
try: number = int(args) except ValueError: number = -1 return self._getMessage(number, 12345)
def onRetr(self, command, args): """POP3 RETR command.""" return self._getMessage(int(args), 12345)
number, lines = map(int, args.split())
try: number, lines = map(int, args.split()) except ValueError: number, lines = -1, -1
def onTop(self, command, args): """POP3 RETR command.""" number, lines = map(int, args.split()) return self._getMessage(number, lines)
assert response.find(options.hammie_header_name) != -1
assert response.find(options.hammie_header_name) >= 0
def runProxy(): # Name the database in case it ever gets auto-flushed to disk. bayes = hammie.createbayes('_pop3proxy.db') BayesProxyListener('localhost', 8110, 8111, bayes) bayes.learn(tokenizer.tokenize(spam1), True) bayes.learn(tokenizer.tokenize(good1), False) proxyReady.set() asyncore.loop()
self.SetOptionValue(None) self.SetOptionValue("", self.option_folder_name)
self.SetOptionValue(None) hedit = win32gui.GetDlgItem(self.window.hwnd, id) text = win32gui.GetWindowText(hedit) self.SetOptionValue(text, self.option_folder_name)
def OnCommand(self, wparam, lparam): code = win32api.HIWORD(wparam) id = win32api.LOWORD(wparam) if id == self.control_id: if code==win32con.EN_CHANGE: if not self.in_setting_name: self.SetOptionValue(None) # reset the folder IDs. self.SetOptionValue("", self.option_folder_name) return opt_processors.FolderIDProcessor....
crashMe()
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): # Remove the trailing .\r\n before passi...
import smtpproxy
def prepare(state): # Do whatever we've been asked to do... state.createWorkers() # Launch any SMTP proxies. Note that if the user hasn't specified any # SMTP proxy information in their configuration, then nothing will # happen. import smtpproxy servers, proxyPorts = smtpproxy.LoadServerInfo() smtpproxy.CreateProxies...
fixedAttrtrans = None if hasattr(xmllib, 'attrtrans') and isinstance(xmllib.attrtrans, str): class UnicodeAttrtrans: def __getitem__(self, c): if unichr(c) in ' \r\n\t': return ord(u' ') return c fixedAttrtrans = UnicodeAttrtrans()
def unknown_endtag(self, tag): if self._pendingText: self._collapsePendingText() self._currentNode = self._currentNode.parent
if isinstance(source, unicode) and fixedAttrtrans: originalAttrtrans = xmllib.attrtrans xmllib.attrtrans = fixedAttrtrans
def _generateTree(source): """Given some XML source, generates a lightweight DOM tree rooted at a `_RootNode`.""" # Fix xmllib if necessary. if isinstance(source, unicode) and fixedAttrtrans: originalAttrtrans = xmllib.attrtrans xmllib.attrtrans = fixedAttrtrans # Lots of HTML files start with a DOCTYPE declaration l...
if isinstance(source, unicode) and fixedAttrtrans: xmllib.attrtrans = originalAttrtrans
def _generateTree(source): """Given some XML source, generates a lightweight DOM tree rooted at a `_RootNode`.""" # Fix xmllib if necessary. if isinstance(source, unicode) and fixedAttrtrans: originalAttrtrans = xmllib.attrtrans xmllib.attrtrans = fixedAttrtrans # Lots of HTML files start with a DOCTYPE declaration l...
if isinstance(source, (str, unicode)):
if isinstance(source, str):
def __init__(self, source, readonly=False): """Creates a `Meld` from XML source. `readonly` does what it says."""
raise TypeError, "Melds must be constructed from strings"
raise TypeError, "Melds must be constructed from ASCII strings"
def __init__(self, source, readonly=False): """Creates a `Meld` from XML source. `readonly` does what it says."""
if not isinstance(value, (str, unicode)):
if not isinstance(value, str):
def _quoteAttribute(self, value): """Minimally quotes an attribute value, using `&quot;`, `&amp;`, `&lt;` and `&gt;`.""" if not isinstance(value, (str, unicode)): value = str(value) value = value.replace('"', '&quot;') value = value.replace('<', '&lt;').replace('>', '&gt;') value = re.sub(r'&(?![a-zA-Z0-9]+;)', '&amp;'...
if not isinstance(value, (str, unicode)):
if not isinstance(value, str):
def _replaceNodeContent(self, node, value): """Replaces the content of the given node. If `value` is a string, it is parsed as XML. If it is a Meld, it it cloned. The existing children are deleted, the new nodes are set as the children of `node`."""
not isinstance(values, (str, unicode)):
not isinstance(values, str):
def __mod__(self, values): """`object % value`, `object % sequence`, or `object % dictionary` all mimic the `%` operator for strings:
def __unicode__(self): """Returns the XML that this `Meld` represents. Don't call this directly - instead convert a `Meld` to unicode using `unicode(object)`.""" return unicode(self._tree.toText())
def __unicode__(self): """Returns the XML that this `Meld` represents. Don't call this directly - instead convert a `Meld` to unicode using `unicode(object)`.""" return unicode(self._tree.toText())
TypeError: Melds must be constructed from strings
TypeError: Melds must be constructed from ASCII strings
def __unicode__(self): """Returns the XML that this `Meld` represents. Don't call this directly - instead convert a `Meld` to unicode using `unicode(object)`.""" return unicode(self._tree.toText())
'unicode': r"""
'no unicode': r"""
def __unicode__(self): """Returns the XML that this `Meld` represents. Don't call this directly - instead convert a `Meld` to unicode using `unicode(object)`.""" return unicode(self._tree.toText())
>>> a = Meld('<html><span id="two">Two</span></html>') >>> u.one = a.two >>> print repr(unicode(u)) u'<html><span id="one"><span id="two">Two</span></span></html>' >>> a.two = Meld(u'<x a="Unicode\nValue"/>') >>> print a <html><span id="two"><x a="Unicode Value"/></span></html>
Traceback (most recent call last): ... TypeError: Melds must be constructed from ASCII strings
def __unicode__(self): """Returns the XML that this `Meld` represents. Don't call this directly - instead convert a `Meld` to unicode using `unicode(object)`.""" return unicode(self._tree.toText())
("safe_headers", "Safe headers", ("abuse-reports-to", "date errors-to",
("safe_headers", "Safe headers", ("abuse-reports-to", "date", "errors-to",
def bool(val): return not not val
test_str = v0 + sep + v1
test_str = str(v0) + sep + str(v1)
def unconvert(self): '''Convert value from the appropriate type to a string.''' if type(self.value) in types.StringTypes: # nothing to do return self.value if self.is_boolean(): # A wee bit extra for Python 2.2 if self.value == True: return "True" else: return "False" if type(self.value) == types.TupleType: if len(self...
if test_tuple[0] == v0 and test_tuple[1] == v1 and \
print test_tuple, v0, v1 if test_tuple[0] == str(v0) and \ test_tuple[1] == str(v1) and \
def unconvert(self): '''Convert value from the appropriate type to a string.''' if type(self.value) in types.StringTypes: # nothing to do return self.value if self.is_boolean(): # A wee bit extra for Python 2.2 if self.value == True: return "True" else: return "False" if type(self.value) == types.TupleType: if len(self...
print "Deleted the dead popup control - re-creating"
print "The above toolbar message is common - " \ "recreating the toolbar..."
def SetupUI(self): manager = self.manager assert self.toolbar is None, "Should not yet have a toolbar"
if event_hook.use_timer:
if event_hook is None: manager.LogDebug(0, "Skipping processing of missed messages in folder '%s', " "as it is not available" % folder.name) elif event_hook.use_timer:
def ProcessMissedMessages(self): from time import clock config = self.manager.config.filter manager = self.manager field_name = manager.config.general.field_score_name for folder in manager.message_store.GetFolderGenerator( config.watch_folder_ids, config.watch_include_sub): event_hook = self._GetHookForFolder(folder) ...
ret = self.folder_hooks[folder.id]
ret = self.folder_hooks.get(folder.id) if ret is None: return None
def _GetHookForFolder(self, folder): ret = self.folder_hooks[folder.id] assert ret.target == folder return ret
folder = msgstore_folder.GetOutlookItem()
def _HookFolderEvents(self, folder_ids, include_sub, HandlerClass): new_hooks = {} for msgstore_folder in self.manager.message_store.GetFolderGenerator( folder_ids, include_sub): existing = self.folder_hooks.get(msgstore_folder.id) if existing is None or existing.__class__ != HandlerClass: folder = msgstore_folder.GetO...
PR_HASATTACH,
def _GetMessageText(self): # This is finally reliable. The only messages this now fails for # are for "forwarded" messages, where the forwards are actually # in an attachment. Later. # Note we *dont* look in plain text attachments, which we arguably # should. from spambayes import mboxutils
has_attach = data[2][1] headers = self._GetPotentiallyLargeStringProp(prop_ids[3], data[3])
headers = self._GetPotentiallyLargeStringProp(prop_ids[2], data[2])
def _GetMessageText(self): # This is finally reliable. The only messages this now fails for # are for "forwarded" messages, where the forwards are actually # in an attachment. Later. # Note we *dont* look in plain text attachments, which we arguably # should. from spambayes import mboxutils
return self._GetPropFromStream(prop)
return GetPropFromStream(self.mapi_object, prop)
def GetField(self, prop, raise_errors = False): self._EnsureObject() if type(prop) != type(0): props = ( (mapi.PS_PUBLIC_STRINGS, prop), ) prop = self.mapi_object.GetIDsFromNames(props, 0)[0] if PROP_TYPE(prop) == PT_ERROR: # No such property return None prop = PROP_TAG( PT_UNSPECIFIED, PROP_ID(prop)) try: hr, props = ...
h.text = text
h.text = cgi.escape(text)
def _appendMessages(self, table, keyedMessageInfo, label, sort_order, reverse=False): """Appends the rows of a table of messages to 'table'.""" stripe = 0
RFC822_HEADER_RE]:
RFC822_HEADER_RE, BODY_PEEK_RE]:
def _extract_fetch_data(response): '''Extract data from the response given to an IMAP FETCH command.''' # Response might be a tuple containing literal data # At the moment, we only handle one literal per response. This # may need to be improved if our code ever asks for something # more complicated (like RFC822.Header...
self.rfc822_command = "BODY.PEEK[]"
self.rfc822_command = "(BODY.PEEK[])" self.rfc822_key = "BODY[]"
def __init__(self): message.Message.__init__(self) self.folder = None self.previous_folder = None self.rfc822_command = "BODY.PEEK[]" self.got_substance = False self.invalid = False
new_msg = email.Parser.Parser().parsestr(data["RFC822"])
new_msg = email.Parser.Parser().parsestr(data[self.rfc822_key])
def get_substance(self): '''Retrieve the RFC822 message from the IMAP server and set as the substance of this message.''' if self.got_substance: return if not self.uid or not self.id: print "Cannot get substance of message without an id and an UID" return imap.SelectFolder(self.folder.name) try: response = imap.uid("FE...
self.mapi_object.SaveChanges(mapi.KEEP_OPEN_READWRITE | USE_DEFERRED_ERRORS)
self.mapi_object.SaveChanges(mapi.KEEP_OPEN_READWRITE)
def Save(self): assert self.dirty, "asking me to save a clean message!" # There are some known exceptions that can be raised by IMAP and hotmail # For now, we just let the caller handle all errors, and manually # reset the dirty flag. Only current caller is filter.py # There are also some issues with the "unread flag"...
(get_version_string("Outlook"), get_version_string())
(get_version_string("Outlook", version_key), get_version_string())
def OnConnection(self, application, connectMode, addin, custom): # Handle failures during initialization so that we are not # automatically disabled by Outlook. # Our error reporter is in the "manager" module, so we get that first locale.setlocale(locale.LC_NUMERIC, "C") # see locale comments above import manager try: ...
print "Starting register"
def RegisterAddin(klass): # prints to help debug binary install issues. print "Starting register" import _winreg key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins") subkey = _winreg.CreateKey(key, klass._reg_progid_) print "Setting values" _winreg.SetValueEx(subkey, "Comma...
print "Setting values"
def RegisterAddin(klass): # prints to help debug binary install issues. print "Starting register" import _winreg key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins") subkey = _winreg.CreateKey(key, klass._reg_progid_) print "Setting values" _winreg.SetValueEx(subkey, "Comma...
if disposition in options["Headers", "notate_to"]:
if isinstance(options["Headers", "notate_to"], types.StringTypes): notate_to = (options["Headers", "notate_to"],) else: notate_to = options["Headers", "notate_to"] if disposition in notate_to:
def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed."""
if disposition in options["Headers", "notate_subject"]:
if isinstance(options["Headers", "notate_subject"], types.StringTypes): notate_subject = (options["Headers", "notate_subject"],) else: notate_subject = options["Headers", "notate_subject"] if disposition in notate_subject:
def addSBHeaders(self, prob, clues): """Add hammie header, and remember message's classification. Also, add optional headers if needed."""
print usernames[i], self.imap_pwds[i]
def _login_to_imap_server(self, imap, i): if imap and imap.logged_in: return imap if imap is None or not imap.connected: try: server = options["imap", "server"][i] except KeyError: content = self._buildBox(_("Error"), None, _("Please check server/port details.")) self.write(content) self._writePostamble() return None i...
MYPR_MESSAGE_ID_A, PR_IMPORTANCE, PR_CLIENT_SUBMIT_TIME, \
MYPR_MESSAGE_ID_A, PR_IMPORTANCE, PR_CLIENT_SUBMIT_TIME,
def _GetFakeHeaders(self): # This is designed to fake up some SMTP headers for messages # on an exchange server that do not have such headers of their own. prop_ids = PR_SUBJECT_A, PR_SENDER_NAME_A, PR_DISPLAY_TO_A, \ PR_DISPLAY_CC_A, PR_MESSAGE_DELIVERY_TIME, \ MYPR_MESSAGE_ID_A, PR_IMPORTANCE, PR_CLIENT_SUBMIT_TIME, ...
("X-Mailer", 7, False, self._format_version),
def _GetFakeHeaders(self): # This is designed to fake up some SMTP headers for messages # on an exchange server that do not have such headers of their own. prop_ids = PR_SUBJECT_A, PR_SENDER_NAME_A, PR_DISPLAY_TO_A, \ PR_DISPLAY_CC_A, PR_MESSAGE_DELIVERY_TIME, \ MYPR_MESSAGE_ID_A, PR_IMPORTANCE, PR_CLIENT_SUBMIT_TIME, ...
def _format_version(self, raw): return "Exchange Client " + raw
def _format_version(self, unused): return "Microsoft Exchange Client"
def _format_version(self, raw): # Data is just a version string, so prepend something to it. return "Exchange Client " + raw
self.SetDlgItemText(IDC_EDIT_CERTAIN, "%d" % self.mgr.config.filter.spam_threshold)
self.SetDlgItemText(IDC_EDIT_CERTAIN, "%s" % self.mgr.config.filter.spam_threshold)
def OnInitDialog(self): self.SetDlgItemText(IDC_EDIT_CERTAIN, "%d" % self.mgr.config.filter.spam_threshold) self.HookCommand(self.OnEditChange, IDC_EDIT_CERTAIN) self.SetDlgItemText(IDC_EDIT_UNSURE, "%d" % self.mgr.config.filter.unsure_threshold) self.HookCommand(self.OnEditChange, IDC_EDIT_UNSURE)
self.SetDlgItemText(IDC_EDIT_UNSURE, "%d" % self.mgr.config.filter.unsure_threshold)
self.SetDlgItemText(IDC_EDIT_UNSURE, "%s" % self.mgr.config.filter.unsure_threshold)
def OnInitDialog(self): self.SetDlgItemText(IDC_EDIT_CERTAIN, "%d" % self.mgr.config.filter.spam_threshold) self.HookCommand(self.OnEditChange, IDC_EDIT_CERTAIN) self.SetDlgItemText(IDC_EDIT_UNSURE, "%d" % self.mgr.config.filter.unsure_threshold) self.HookCommand(self.OnEditChange, IDC_EDIT_UNSURE)
slider_pos = slider.GetPos() self.SetDlgItemText(idc_edit, "%d" % slider_pos)
slider_pos = float(slider.GetPos()) self.SetDlgItemText(idc_edit, "%s" % slider_pos)
def OnSlider(self, params): lParam = params[3] slider = self.GetDlgItem(IDC_SLIDER_CERTAIN) if slider.GetSafeHwnd() == lParam: idc_edit = IDC_EDIT_CERTAIN else: slider = self.GetDlgItem(IDC_SLIDER_UNSURE) assert slider.GetSafeHwnd() == lParam idc_edit = IDC_EDIT_UNSURE slider_pos = slider.GetPos() self.SetDlgItemText(i...
val = int(edit.GetWindowText())
val = float(edit.GetWindowText())
def _AdjustSliderToEdit(self, idc_slider, idc_edit): slider = self.GetDlgItem(idc_slider) edit = self.GetDlgItem(idc_edit) try: val = int(edit.GetWindowText()) except ValueError: return slider.SetPos(val)
original_score = 100 * msgstore_message.GetField(\
original_score = msgstore_message.GetField(\
def ShowClues(mgr, explorer): from cgi import escape app = explorer.Application msgstore_message = explorer.GetSelectedMessages(False) if msgstore_message is None: return mgr.classifier_data.message_db.load_msg(msgstore_message) item = msgstore_message.GetOutlookItem() score, clues = mgr.score(msgstore_message, evide...
if original_score >= mgr.config.filter.spam_threshold: original_class = "spam" elif original_score >= mgr.config.filter.unsure_threshold: original_class = "unsure" else: original_class = "good"
if original_score is not None: original_score *= 100.0 if original_score >= mgr.config.filter.spam_threshold: original_class = "spam" elif original_score >= mgr.config.filter.unsure_threshold: original_class = "unsure" else: original_class = "good"
def ShowClues(mgr, explorer): from cgi import escape app = explorer.Application msgstore_message = explorer.GetSelectedMessages(False) if msgstore_message is None: return mgr.classifier_data.message_db.load_msg(msgstore_message) item = msgstore_message.GetOutlookItem() score, clues = mgr.score(msgstore_message, evide...
if self._contains(msg['Subject'], key, ic):
subj = str(msg['Subject']) if self._contains(subj, key, ic):
def onReview(self, **params): """Present a list of message for (re)training.""" # Train/discard sumbitted messages. self._writePreamble("Review") id = '' numTrained = 0 numDeferred = 0 if params.get('go') != 'Refresh': for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == ...
self._doSave()
def onReview(self, **params): """Present a list of message for (re)training.""" # Train/discard sumbitted messages. self._writePreamble("Review") id = '' numTrained = 0 numDeferred = 0 if params.get('go') != 'Refresh': for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == ...
self.total += self._lambda(scr) * options.best_cutoff_fn_weight
self.total += (1 - self._lambda(scr)) * options.best_cutoff_fn_weight
def spam(self, scr): self.total += self._lambda(scr) * options.best_cutoff_fn_weight
self.total += (1 - self._lambda(scr)) * options.best_cutoff_fp_weight
self.total += self._lambda(scr) * options.best_cutoff_fp_weight
def ham(self, scr): self.total += (1 - self._lambda(scr)) * options.best_cutoff_fp_weight
response = self.select(folder, False)
response = self.select(folder, None)
def SelectFolder(self, folder): '''A method to point ensuing imap operations at a target folder''' if self.current_folder != folder: if self.current_folder != None: if self.do_expunge: # It is faster to do close() than a single # expunge when we log out (because expunge returns # a list of all the deleted messages, tha...
print """WARNING: Your imap server uses commas as the folder delimiter. This may cause unpredictable errors.""" folders.append(fol[m.end()+5:-1])
print "WARNING: Your imap server uses a comma as the " \ "folder delimiter. This may cause unpredictable " \ "errors." folders.append(fol[m.end()+4:].strip('"'))
def folder_list(self): '''Return a alphabetical list of all folders available on the server''' response = self.list() if response[0] != "OK": return [] all_folders = response[1] folders = [] for fol in all_folders: # Sigh. Some servers may give us back the folder name as a # literal, so we need to crunch this out. if ...
"%(cls_ham)d (%(perc_ham)d%%) good, " \ "%(cls_spam)d (%(perc_spam)d%%) spam " \
"%(cls_ham)d (%(perc_ham).0f%%) good, " \ "%(cls_spam)d (%(perc_spam).0f%%) spam " \
def GetStats(self): if self.total == 0: return ["SpamBayes has processed zero messages"] chunks = [] push = chunks.append perc_ham = 100.0 * self.cls_ham / self.total perc_spam = 100.0 * self.cls_spam / self.total perc_unsure = 100.0 * self.cls_unsure / self.total format_dict = dict(perc_spam=perc_spam, perc_ham=perc_h...
self.unknownCorpus = FileCorpus(factory,
self.unknownCorpus = ExpiryFileCorpus(age, factory,
def ensureDir(dirname): try: os.mkdir(dirname) except OSError, e: if e.errno != errno.EEXIST: raise
PR_DISPLAY_NAME_A), None, None, 0)
PR_DISPLAY_NAME_A), None, order, 0)
def _BuildFoldersMAPI(manager, folder_id): folder = manager.message_store.GetFolder(folder_id).OpenEntry() # Get the hierarchy table for it. table = folder.GetHierarchyTable(0) children = [] rows = mapi.HrQueryAllRows(table, (PR_ENTRYID, PR_STORE_ENTRYID, PR_DISPLAY_NAME_A), None, None, 0) for (eid_tag, eid),(storeeid_...
db_status = "Database has %d good and %d spam" % (nham, nspam)
db_status = "Database has %d good and %d spam." % (nham, nspam)
def Init(self): bayes = self.window.manager.classifier_data.bayes nspam = bayes.nspam nham = bayes.nham if nspam > 10 and nham > 10: db_status = "Database has %d good and %d spam" % (nham, nspam) elif nspam > 0 or nham > 0: db_status = "Database only has %d good and %d spam - you should consider performing additional t...
db_status = "Database only has %d good and %d spam - you should consider performing additional training" % (nham, nspam)
db_status = "Database only has %d good and %d spam - you should " \ "consider performing additional training." % (nham, nspam)
def Init(self): bayes = self.window.manager.classifier_data.bayes nspam = bayes.nspam nham = bayes.nham if nspam > 10 and nham > 10: db_status = "Database has %d good and %d spam" % (nham, nspam) elif nspam > 0 or nham > 0: db_status = "Database only has %d good and %d spam - you should consider performing additional t...
db_status = "Database has no training information"
db_status = "Database has no training information. SpamBayes " \ "will deliver all messages to your 'Unsure' folder, " \ "ready for you to classify."
def Init(self): bayes = self.window.manager.classifier_data.bayes nspam = bayes.nspam nham = bayes.nham if nspam > 10 and nham > 10: db_status = "Database has %d good and %d spam" % (nham, nspam) elif nspam > 0 or nham > 0: db_status = "Database only has %d good and %d spam - you should consider performing additional t...
tokens = tokenize(stream) was_spam = mgr.message_db.get(msg.searchkey) if was_spam is None: pass elif was_spam == is_spam: return False else: mgr.bayes.unlearn(tokens, was_spam, False) mgr.bayes.learn(tokens, is_spam, False)
if was_spam is not None: mgr.bayes.unlearn(tokenize(stream), was_spam, False) mgr.bayes.learn(tokenize(stream), is_spam, False)
def train_message(msg, is_spam, mgr, rescore=False): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. # If re-classified AND rescore = True, then a new score ...
global classifier
global classifier, parm_map
def __init__(self, cls, imap, pwd): global classifier # Only offer SSL if it is available try: from imaplib import IMAP_SSL except ImportError: parm_list = list(parm_map) parm_list.remove(("imap", "use_ssl")) parm_map = tuple(parm_list) UserInterface.UserInterface.__init__(self, cls, parm_map) classifier = cls self.ima...
win32con.WM_USER+20 : self.OnTaskbarNotify,
WM_TASKBAR_NOTIFY : self.OnTaskbarNotify,
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
wc = WNDCLASS() hinst = wc.hInstance = GetModuleHandle(None) wc.lpszClassName = "SpambayesTaskbar" wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW; wc.hCursor = LoadCursor( 0, win32con.IDC_ARROW ) wc.hbrBackground = win32con.COLOR_WINDOW wc.lpfnWndProc = message_map classAtom = RegisterClass(wc)
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = CreateWindow(classAtom, "SpamBayes", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) UpdateWindow(self.hwnd)
hinst = GetModuleHandle(None) dialogTemplate = [['SpamBayes', (14, 10, 246, 187), -1865809852 & ~win32con.WS_VISIBLE, None, (8, 'Tahoma')],] self.hwnd = CreateDialogIndirect(hinst, dialogTemplate, 0, message_map)
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
iconPathName = os.path.abspath(os.path.join( os.path.split(sys.executable)[0], "pyc.ico" ))
iconPathName = os.path.abspath( "resources\\sbicon.ico" )
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "SpamBayes")
nid = (self.hwnd, 0, flags, WM_TASKBAR_NOTIFY, hicon, "SpamBayes")
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
pop3proxy.prepare(state=pop3proxy.state) self.StartProxyThread()
def __init__(self): # The ordering here is important - it is the order that they will # appear in the menu. As dicts don't have an order, this means # that the order is controlled by the id. Any items were the # function is None will appear as separators. self.control_functions = {1024 : ("Start SpamBayes", self.Star...
pop3proxy.start(pop3proxy.state) self.started = True
self.StartProxyThread()
def StartStop(self): # XXX This needs to be finished off. # XXX This should determine if we are using the service, and if so # XXX start/stop that, and if not kick pop3proxy off in a separate # XXX thread, or stop the thread that was started. if self.started: pop3proxy.stop(pop3proxy.state) self.started = False else: p...
def train(bayes, msgs, is_spam): """Train bayes with all messages from a mailbox."""
def getmbox(msgs): """Return an iterable mbox object given a file/directory/folder name."""
def train(bayes, msgs, is_spam): """Train bayes with all messages from a mailbox.""" def _factory(fp): try: return email.message_from_file(fp) except email.Errors.MessageParseError: return '' if msgs.startswith("+"): import mhlib mh = mhlib.MH() mbox = mailbox.MHMailbox(os.path.join(mh.getpath(), msgs[1:])) elif os.pa...
mbox = mailbox.MHMailbox(os.path.join(mh.getpath(), msgs[1:]))
mbox = mailbox.MHMailbox(os.path.join(mh.getpath(), msgs[1:]), _factory)
def _factory(fp): try: return email.message_from_file(fp) except email.Errors.MessageParseError: return ''
return mbox def train(bayes, msgs, is_spam): """Train bayes with all messages from a mailbox.""" mbox = getmbox(msgs)
def _factory(fp): try: return email.message_from_file(fp) except email.Errors.MessageParseError: return ''
disp += "; " + "; ".join(map(lambda x: "%s: %.2f" % (`x[0]`, x[1]), clues))
disp += "; " + formatclues(clues)
def filter(bayes, input, output): """Filter (judge) a message""" msg = email.message_from_file(input) prob, clues = bayes.spamprob(tokenize(str(msg)), True) if prob < 0.9: disp = "No" else: disp = "Yes" disp += "; %.2f" % prob disp += "; " + "; ".join(map(lambda x: "%s: %.2f" % (`x[0]`, x[1]), clues)) msg.add_header("X...
opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:')
opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:u:')
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:') except getopt.error, msg: usage(1, msg) if not opts: usage(0, "No options given") pck = "hammie.db" good = spam = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) elif opt == '-g': good = arg elif opt == '-s': spam = a...
good = spam = None
good = spam = unknown = None
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hdfg:s:p:') except getopt.error, msg: usage(1, msg) if not opts: usage(0, "No options given") pck = "hammie.db" good = spam = None do_filter = usedb = False for opt, arg in opts: if opt == '-h': usage(0) elif opt == '-g': good = arg elif opt == '-s': spam = a...
score = float(messageInfo.score.rstrip('%'))
try: score = float(messageInfo.score.rstrip('%')) except ValueError: score = None
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
if score > options["html_ui", "spam_discard_level"]:
if score is not None \ and score > options["html_ui", "spam_discard_level"]:
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
if score < options["html_ui", "ham_discard_level"]:
if score is not None \ and score < options["html_ui", "ham_discard_level"]:
def _appendMessages(self, table, keyedMessageInfo, label, sort_order): """Appends the rows of a table of messages to 'table'.""" stripe = 0
if params.get('go') != 'refresh':
if params.get('go') != 'Refresh':
def onReview(self, **params): """Present a list of message for (re)training.""" # Train/discard sumbitted messages. self._writePreamble("Review") id = '' numTrained = 0 numDeferred = 0 if params.get('go') != 'refresh': for key, value in params.items(): if key.startswith('classify:'): id = key.split(':')[2] if value == ...
In such a case we use the module oe.mailbox to convert the DBX
In such a case we use the module oe_mailbox to convert the DBX
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
header = oe.mailbox.dbxFileHeader(dbxStream)
header = oe_mailbox.dbxFileHeader(dbxStream)
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
file_info_len = oe.mailbox.dbxFileHeader.FH_FILE_INFO_LENGTH fh_entries = oe.mailbox.dbxFileHeader.FH_ENTRIES fh_ptr = oe.mailbox.dbxFileHeader.FH_TREE_ROOT_NODE_PTR
file_info_len = oe_mailbox.dbxFileHeader.FH_FILE_INFO_LENGTH fh_entries = oe_mailbox.dbxFileHeader.FH_ENTRIES fh_ptr = oe_mailbox.dbxFileHeader.FH_TREE_ROOT_NODE_PTR
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
info = oe.mailbox.dbxFileInfo(dbxStream,
info = oe_mailbox.dbxFileInfo(dbxStream,
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
tree = oe.mailbox.dbxTree(dbxStream, address, entries)
tree = oe_mailbox.dbxTree(dbxStream, address, entries)
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
messageInfo = oe.mailbox.dbxMessageInfo(dbxStream,
messageInfo = oe_mailbox.dbxMessageInfo(dbxStream,
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
oe.mailbox.dbxMessageInfo.MI_MESSAGE_ADDRESS): address = oe.mailbox.dbxMessageInfo.MI_MESSAGE_ADDRESS
oe_mailbox.dbxMessageInfo.MI_MESSAGE_ADDRESS): address = oe_mailbox.dbxMessageInfo.MI_MESSAGE_ADDRESS
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
message = oe.mailbox.dbxMessage(dbxStream,
message = oe_mailbox.dbxMessage(dbxStream,
def _convertOutlookExpressToMbox(self, content): """Check if the uploaded mailbox file is an Outlook Express DBX one.
self.uiPort = options["html_ui", "port"] self.launchUI = options["html_ui", "launch_browser"] self.gzipCache = options["Storage", "cache_use_gzip"] self.cacheExpiryDays = options["Storage", "cache_expiry_days"] self.runTestServer = False self.isTest = False
def init(self): assert not self.prepared, "init after prepare, but before close" # Open the log file. if options["globals", "verbose"]: self.logFile = open('_pop3proxy.log', 'wb', 0) self.servers = [] self.proxyPorts = [] if options["pop3proxy", "remote_servers"]: for server in options["pop3proxy", "remote_servers"]: s...
self.bad_urls = pickle.load(b_file)
try: self.bad_urls = pickle.load(b_file) except IOError, ValueError: if options["globals", "verbose"]: print >>sys.stderr, "Bad URL pickle, using new." self.bad_urls = {"url:non_resolving": (), "url:non_html": (), "url:unknown_error": ()}
def setup(self): # Can't import this at the top because it's circular. # XXX Someone smarter than me, please figure out the right # XXX way to do this. from spambayes.FileCorpus import ExpiryFileCorpus, FileMessageFactory
self.http_error_urls = pickle.load(h_file)
try: self.http_error_urls = pickle.load(h_file) except IOError, ValueError: if options["globals", "verbose"]: print >>sys.stderr, "Bad HHTP error pickle, using new." self.http_error_urls = {}
def setup(self): # Can't import this at the top because it's circular. # XXX Someone smarter than me, please figure out the right # XXX way to do this. from spambayes.FileCorpus import ExpiryFileCorpus, FileMessageFactory
b_file = file(self.bad_url_cache_name, "w") pickle.dump(self.bad_urls, b_file) b_file.close() h_file = file(self.http_error_cache_name, "w") pickle.dump(self.http_error_urls, h_file) h_file.close()
for name, data in [(self.bad_url_cache_name, self.bad_urls), (self.http_error_cache_name, self.http_error_urls),]: cache = open(name + ".tmp", "w") pickle.dump(data, cache) cache.close() try: os.rename(name + ".tmp", name) except OSError: os.remove(name) os.rename(name + ".tmp", name)
def _save_caches(self): # XXX Note that these caches are never refreshed, which might not # XXX be a good thing long-term (if a previously invalid URL # XXX becomes valid, for example). b_file = file(self.bad_url_cache_name, "w") pickle.dump(self.bad_urls, b_file) b_file.close() h_file = file(self.http_error_cache_name...
if self.draft:
if self.recent:
def _flags_iter(self): if self.deleted: yield "\\DELETED" if self.answered: yield "\\ANSWERED" if self.flagged: yield "\\FLAGGED" if self.seen: yield "\\SEEN" if self.draft: yield "\\DRAFT" if self.draft: yield "\\RECENT"
def train_message(msg, is_spam, mgr, update_probs = True):
def train_message(msg, is_spam, mgr):
def train_message(msg, is_spam, mgr, update_probs = True): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. from tokenizer import tokenize stream = msg.GetEma...
if update_probs: mgr.bayes.update_probabilities()
def train_message(msg, is_spam, mgr, update_probs = True): # Train an individual message. # Returns True if newly added (message will be correctly # untrained if it was in the wrong category), False if already # in the correct category. Catch your own damn exceptions. from tokenizer import tokenize stream = msg.GetEma...
if train_message(message, isspam, mgr, False):
if train_message(message, isspam, mgr):
def train_folder( f, isspam, mgr, progress): num = num_added = 0 for message in f.GetMessageGenerator(): if progress.stop_requested(): break progress.tick() try: if train_message(message, isspam, mgr, False): num_added += 1 except: print "Error training message '%s'" % (message,) traceback.print_exc() num += 1 print "C...
ids = [self.optin.get()]
ids = [self.option.get()]
def OnCommand(self, wparam, lparam): mgr = self.window.manager id = win32api.LOWORD(wparam) if id == self.button_id: is_multi = self.option.multiple_values_allowed() if is_multi: ids = self.option.get() else: ids = [self.optin.get()] from dialogs import FolderSelector if self.option_include_sub: cb_state = self.option_...