rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.Catalog.catalog_object(indexable, pp)
self.Catalog.catalog_object(object, pp)
def reindex_mailObjects(self): """ Reindex the mailObjects that we contain. """ for object in self.archive.objectValues('Folder'): if hasattr(object, 'mailFrom'): pp = '/'.join(indexable.getPhysicalPath()) self.Catalog.uncatalog_object(pp) self.Catalog.catalog_object(indexable, pp) return indexables
mailString.encode(getConfiguration().default_zpublisher_encoding)
mailString.encode(getConfiguration().default_zpublisher_encoding or 'UTF-8')
def manage_addMail(self, mailString): """ Store mail & attachments in a folder and return it. """ import re archive = self.restrictedTraverse(self.getValueFor('storage'), default=None) # no archive available? then return immediately if archive is None: return None (header, body) = self.splitMail(mailString) # get the content type header, and re-encode the email to the default encoding ct = header.get('content-type',None) encoding = 'ascii' if ct: encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"].*?;', ct) encoding = encoding_match and encoding_match.groups()[0] for try_encoding in (encoding, 'utf-8', 'iso-8859-1', 'iso-8859-15'): try: mailString = mailString.decode(try_encoding) mailString.encode(getConfiguration().default_zpublisher_encoding) (header, body) = self.splitMail(mailString) break except (UnicodeDecodeError, LookupError): pass # if 'keepdate' is set, get date from mail, if self.getValueFor('keepdate'): timetuple = rfc822.parsedate_tz(header.get('date')) time = DateTime(rfc822.mktime_tz(timetuple)) # ... take our own date, clients are always lying! else: time = DateTime() # let's create the mailObject mailFolder = archive subject = self.mime_decode_header(header.get('subject', 'No Subject')) # correct the subject subject = self.tidy_subject(subject) if subject.lower().find('re:', 0, 3) == 0 and len(subject) > 3: subject = subject[3:].strip() elif len(subject) == 0: subject = 'No Subject' compressedsubject = re.sub('\s+', '', subject) sender = self.mime_decode_header(header.get('from','No From')) title = "%s / %s" % (subject, sender) # we use our IdFactory to get the next ID, rather than trying something # ad-hoc id = str(self.get_nextId()) self.addMailBoxerMail(mailFolder, id, title) mailObject = getattr(mailFolder, id) # unpack attachments (TextBody, ContentType, HtmlBody, Attachments) = self.unpackMail( mailString) # ContentType is only set for the TextBody if ContentType: mailBody = TextBody else: mailBody = self.HtmlToText(HtmlBody) # and now add some properties to our new mailobject self.setMailBoxerMailProperty(mailObject, 'mailFrom', sender, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailSubject', subject, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailDate', time, 'date') self.setMailBoxerMailProperty(mailObject, 'mailBody', mailBody, 'utext') self.setMailBoxerMailProperty(mailObject, 'compressedSubject', compressedsubject, 'string') types = {'date': ('date', convert_date), 'from': ('lines', convert_addrs), 'to': ('lines', convert_addrs), 'received': ('lines', null_convert),} for key in header.keys(): if key in types: self.setMailBoxerMailProperty(mailObject, key, types[key][1](self.mime_decode_header(header.get(key,''))), types[key][0]) else: self.setMailBoxerMailProperty(mailObject, key, self.mime_decode_header(header.get(key,'')), 'text') sender_id = self.get_mailUserId(mailObject.getProperty('from', [])) self.setMailBoxerMailProperty(mailObject, 'mailUserId', sender_id, 'string') self.catalogMailBoxerMail(mailObject)
return indexables
return 1
def reindex_mailObjects(self): """ Reindex the mailObjects that we contain. """ for object in self.archive.objectValues('Folder'): if hasattr(object, 'mailFrom'): pp = '/'.join(object.getPhysicalPath()) self.Catalog.uncatalog_object(pp) self.Catalog.catalog_object(object, pp) return indexables
group = getattr(listmanager, group_id)
group = getattr(list_manager, group_id)
def send_email(self, REQUEST, RESPONSE, group_id, email_address, email_id, message, subject=''): """ Send an email to the group. We send the email via the mail server so it will handle things like message ID's for us. """ list_manager = self.get_xwfMailingListManager() sec = getSecurityManager() user = sec.getUser() if email_address not in user.get_emailAddresses(): raise 'Forbidden', 'Only the authenticated owner of an email address may use it to post' group = getattr(listmanager, group_id) group_email = group.getProperty('mailto') group_name = group.getProperty('title') message_id = None if email_id: orig_email = self.get_email(email_id) subject = 'Re: %s' % orig_email.getProperty('subject') message_id = orig_email.getProperty('message-id', '') name = '%s %s' % (user.preferredName, user.lastName) headers = """From: %s <%s>
except:
except Exception, x: LOG('XWFMailingList', PROBLEM, 'A problem was experienced while getting values: %s' % x)
def getValueFor(self, key): # getting the maillist and moderatedlist is a special case, working in with the # XWFT group framework pass_group_id = False if key in ('digestmaillist', 'maillist', 'moderator', 'moderatedlist','mailinlist'): maillist = [] if key in ('digestmaillist', 'maillist'): address_getter = 'get_deliveryEmailAddressesByKey' member_getter = 'get_memberUserObjects' #address_getter = 'get_preferredEmailAddresses' pass_group_id = True maillist_script = getattr(self, 'maillist_members', None) elif key in ('moderator',): address_getter = 'get_emailAddresses' member_getter = 'get_moderatorUserObjects' maillist_script = None maillist = self.aq_inner.getProperty('moderator', []) if not maillist: maillist = self.aq_parent.getProperty('moderator',[]) elif key in ('moderatedlist',): address_getter = 'get_emailAddresses' member_getter = 'get_moderatedUserObjects' maillist_script = None maillist = self.aq_inner.getProperty('moderatedlist', []) if not maillist: maillist = self.aq_parent.getProperty('moderatedlist',[]) else: address_getter = 'get_emailAddresses' member_getter = 'get_memberUserObjects' maillist_script = getattr(self, 'mailinlist_members', None) # look for a maillist script if maillist_script: return maillist_script() try: users = getattr(self, member_getter)() for user in users: # we're looking to send out regular email, but this user is set to digest if key == 'maillist' and user.get_deliverySettingsByKey(self.getId()) == 3: continue elif key == 'digestmaillist' and user.get_deliverySettingsByKey(self.getId()) != 3: continue
last_name = nparts[1:]
last_name = ' '.join(nparts[1:])
def requestMail(self, REQUEST): # Handles un-/subscribe-requests.
memberlist = self.lowerList(self.getValueFor('maillist'))
memberlist = self.lowerList(self.getValueFor('digestmaillist'))
def manage_digestBoxer(self, REQUEST): """ Send out a digest of topics to users who have requested it.
fr = curr_thread_results[0]
def thread_sorter(a, b): if s_on in ('mailDate', 'mailSubject'): a = getattr(a[1][0], s_on); b = getattr(b[1][0], s_on) elif s_on in ('mailCount', ): a = a[0]; b = b[0] else: return 0 if not a > b: return s_order == 'asc' and -1 or 1 elif not a < b: return s_order == 'asc' and 1 or -1 else: return 0
security.declareProtected('Manage properties','getMemberUserObjects')
security.declareProtected('Manage properties','get_mailUserId')
def manage_delMember(self, email): """ Remove member from group. """ user = self.acl_users.get_userByEmail(email) if user: user.del_groupWithNotification('%s_member' % self.getId()) return 1
mailObject.manage_addProperty('mailSubject', Subject, 'string')
def manage_addMail(self, Mail): """ store mail & attachments in a folder and return it """
if Subject.lower().find('re:', 0, 3) == 0 and len(subject) > 3:
if Subject.lower().find('re:', 0, 3) == 0 and len(Subject) > 3:
def manage_addMail(self, Mail): """ store mail & attachments in a folder and return it """
f = file('/home/richard/foo.txt', 'a+') f.write(str(urlparts))
def getAuthorizedURL(url, auth): # annoyingly, xmlrpclib only recognises user@pass style # authentication, so having gone to the trouble of parsing # it out, we now need to add it back in again if not auth: return url import urlparse urlparts = list(urlparse.urlparse(url)) urlparts[1] = auth+'@'+urlparts[1] f = file('/home/richard/foo.txt', 'a+') f.write(str(urlparts)) return urlparse.urlunparse(urlparts)
encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"].*?;', ct)
encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"]?;', ct)
def manage_addMail(self, mailString): """ Store mail & attachments in a folder and return it. """ import re archive = self.restrictedTraverse(self.getValueFor('storage'), default=None) # no archive available? then return immediately if archive is None: return None (header, body) = self.splitMail(mailString) # get the content type header, and re-encode the email to the default encoding ct = header.get('content-type',None) encoding = 'ascii' if ct: encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"].*?;', ct) encoding = encoding_match and encoding_match.groups()[0] or 'ascii' convert_encoding_to_default(mailString, encoding) (header, body) = self.splitMail(mailString) # if 'keepdate' is set, get date from mail, if self.getValueFor('keepdate'): timetuple = rfc822.parsedate_tz(header.get('date')) time = DateTime(rfc822.mktime_tz(timetuple)) # ... take our own date, clients are always lying! else: time = DateTime() # let's create the mailObject mailFolder = archive subject = self.mime_decode_header(header.get('subject', 'No Subject')) subject = convert_encoding_to_default(subject, encoding) # correct the subject subject = self.tidy_subject(subject) if subject.lower().find('re:', 0, 3) == 0 and len(subject) > 3: subject = subject[3:].strip() elif len(subject) == 0: subject = 'No Subject' compressedsubject = re.sub('\s+', '', subject) sender = self.mime_decode_header(header.get('from','No From')) sender = convert_encoding_to_default(sender, encoding) title = "%s / %s" % (subject, sender) # we use our IdFactory to get the next ID, rather than trying something # ad-hoc id = str(self.get_nextId()) self.addMailBoxerMail(mailFolder, id, title) mailObject = getattr(mailFolder, id) # unpack attachments (TextBody, ContentType, HtmlBody, Attachments) = self.unpackMail( mailString) # ContentType is only set for the TextBody if ContentType: mailBody = TextBody else: mailBody = self.HtmlToText(HtmlBody) # and now add some properties to our new mailobject self.setMailBoxerMailProperty(mailObject, 'mailFrom', sender, 'string') self.setMailBoxerMailProperty(mailObject, 'mailSubject', subject, 'string') self.setMailBoxerMailProperty(mailObject, 'mailDate', time, 'date') self.setMailBoxerMailProperty(mailObject, 'mailBody', mailBody, 'text') self.setMailBoxerMailProperty(mailObject, 'compressedSubject', compressedsubject, 'string') types = {'date': ('date', convert_date), 'from': ('lines', convert_addrs), 'to': ('lines', convert_addrs), 'received': ('lines', null_convert),} for key in header.keys(): if key in types: self.setMailBoxerMailProperty(mailObject, key, types[key][1](self.mime_decode_header(header.get(key,''))), types[key][0]) else: self.setMailBoxerMailProperty(mailObject, key, self.mime_decode_header(header.get(key,'')), 'text') sender_id = self.get_mailUserId(mailObject.getProperty('from', [])) self.setMailBoxerMailProperty(mailObject, 'mailUserId', sender_id, 'string') self.catalogMailBoxerMail(mailObject)
if custom_mailcheck(mailinglist=self, sender=email, message=message):
if custom_mailcheck(mailinglist=self, sender=email, header=header, body=body):
def checkMail(self, REQUEST): # [email protected]: this is mostly the same as the MailBoxer parent, # only with notification. # Check for ip, loops and spam. # Check for correct IP mtahosts = self.getValueFor('mtahosts') if mtahosts: if 'HTTP_X_FORWARDED_FOR' in self.REQUEST.environ.keys(): REMOTE_IP = self.REQUEST.environ['HTTP_X_FORWARDED_FOR'] else: REMOTE_IP = self.REQUEST.environ['REMOTE_ADDR']
pass
maillist = None
def getValueFor(self, key): # getting the maillist is a special case, working in with the # XWFT group framework pass_group_id = False if key in ('digestmaillist', 'maillist', 'mailinlist'): if key in ('digestmaillist', 'maillist'): address_getter = 'get_deliveryEmailAddressesByKey' #address_getter = 'get_preferredEmailAddresses' pass_group_id = True maillist_script = getattr(self, 'maillist_members', None) else: address_getter = 'get_emailAddresses' maillist_script = getattr(self, 'mailinlist_members', None) # look for a maillist script if maillist_script: return maillist_script() maillist = [] try: users = self.get_memberUserObjects() for user in users: # we're looking to send out regular email, but this user is set to digest if key == 'maillist' and user.get_deliverySettingsByKey(self.getId()) == 3: continue elif key == 'digestmaillist' and user.get_deliverySettingsByKey(self.getId()) != 3: continue
if not maillist: maillist = self.getProperty('maillist')
if maillist == None: maillist = self.getProperty('maillist', [])
def getValueFor(self, key): # getting the maillist is a special case, working in with the # XWFT group framework pass_group_id = False if key in ('digestmaillist', 'maillist', 'mailinlist'): if key in ('digestmaillist', 'maillist'): address_getter = 'get_deliveryEmailAddressesByKey' #address_getter = 'get_preferredEmailAddresses' pass_group_id = True maillist_script = getattr(self, 'maillist_members', None) else: address_getter = 'get_emailAddresses' maillist_script = getattr(self, 'mailinlist_members', None) # look for a maillist script if maillist_script: return maillist_script() maillist = [] try: users = self.get_memberUserObjects() for user in users: # we're looking to send out regular email, but this user is set to digest if key == 'maillist' and user.get_deliverySettingsByKey(self.getId()) == 3: continue elif key == 'digestmaillist' and user.get_deliverySettingsByKey(self.getId()) != 3: continue
def process_form(self): pass
def process_form(self): pass
'''Did the user write the email message?
"""Did the user write the email message?
def user_authored(self): '''Did the user write the email message? ARGUMENTS None. RETURNS A boolean that is "True" if the current user authored the email message, "False" otherwise. SIDE EFFECTS None.''' assert self.post assert self.request user = self.request.AUTHENTICATED_USER retval = user.getId() == self.post['mailUserId'] assert retval in (True, False) return retval
None.'''
None."""
def user_authored(self): '''Did the user write the email message? ARGUMENTS None. RETURNS A boolean that is "True" if the current user authored the email message, "False" otherwise. SIDE EFFECTS None.''' assert self.post assert self.request user = self.request.AUTHENTICATED_USER retval = user.getId() == self.post['mailUserId'] assert retval in (True, False) return retval
'''Does the author of the post exist?
"""Does the author of the post exist?
def author_exists(self): '''Does the author of the post exist? RETURNS True if the author of the post exists on the system, False otherwise. SIDE EFFECTS None.''' assert self.post retval = False authorId = self.post['mailUserId'] retval = self.context.Scripts.get.user_exists(authorId) assert retval in (True, False) return retval
None.'''
None."""
def author_exists(self): '''Does the author of the post exist? RETURNS True if the author of the post exists on the system, False otherwise. SIDE EFFECTS None.''' assert self.post retval = False authorId = self.post['mailUserId'] retval = self.context.Scripts.get.user_exists(authorId) assert retval in (True, False) return retval
def thread_results(self, REQUEST, bstart, bsize, s_on, s_order):
def thread_results(self, REQUEST, b_start, b_size, s_on, s_order):
def thread_results(self, REQUEST, bstart, bsize, s_on, s_order):
if moderatedlist:
if moderated and moderatedlist:
def send_email(self, REQUEST, RESPONSE, group_id, email_address, email_id, message, subject=''): """ Send an email to the group. """ list_manager = self.get_xwfMailingListManager() sec = getSecurityManager() user = sec.getUser() if email_address not in user.get_emailAddresses(): raise 'Forbidden', 'Only the authenticated owner of an email address may use it to post' group = getattr(list_manager, group_id)
if getattr(self, '__initialised', 1): return 1
if getattr(item, '_initialised', False): return False
def manage_afterAdd(self, item, container): """ For configuring the object post-instantiation. """ if getattr(self, '__initialised', 1): return 1 item._setObject('Catalog', XWFCatalog()) wordsplitter = Record() wordsplitter.group = 'Word Splitter' wordsplitter.name = 'HTML aware splitter' casenormalizer = Record() casenormalizer.group = 'Case Normalizer' casenormalizer.name = 'Case Normalizer' stopwords = Record() stopwords.group = 'Stop Words' stopwords.name = 'Remove listed and single char words' item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords)) zctextindex_extras = Record() zctextindex_extras.index_type = 'Okapi BM25 Rank' zctextindex_extras.lexicon_id = 'Lexicon' for key, index in self.get_metadataIndexMap().items(): if index == 'ZCTextIndex': zctextindex_extras.doc_attr = key item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': # we need to shortcut this one item.Catalog._catalog.addIndex(key, MultiplePathIndex(key)) else: item.Catalog.addIndex(key, index) # add the metadata we need item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate') item.manage_addProduct['MailHost'].manage_addMailHost('MailHost', smtp_host='127.0.0.1') return True
item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords))
def manage_afterAdd(self, item, container): """ For configuring the object post-instantiation. """ if getattr(self, '__initialised', 1): return 1 item._setObject('Catalog', XWFCatalog()) wordsplitter = Record() wordsplitter.group = 'Word Splitter' wordsplitter.name = 'HTML aware splitter' casenormalizer = Record() casenormalizer.group = 'Case Normalizer' casenormalizer.name = 'Case Normalizer' stopwords = Record() stopwords.group = 'Stop Words' stopwords.name = 'Remove listed and single char words' item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords)) zctextindex_extras = Record() zctextindex_extras.index_type = 'Okapi BM25 Rank' zctextindex_extras.lexicon_id = 'Lexicon' for key, index in self.get_metadataIndexMap().items(): if index == 'ZCTextIndex': zctextindex_extras.doc_attr = key item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': # we need to shortcut this one item.Catalog._catalog.addIndex(key, MultiplePathIndex(key)) else: item.Catalog.addIndex(key, index) # add the metadata we need item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate') item.manage_addProduct['MailHost'].manage_addMailHost('MailHost', smtp_host='127.0.0.1') return True
item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': item.Catalog._catalog.addIndex(key, MultiplePathIndex(key))
try: item.Catalog.addIndex(key, index, zctextindex_extras) except CatalogError: pass
def manage_afterAdd(self, item, container): """ For configuring the object post-instantiation. """ if getattr(self, '__initialised', 1): return 1 item._setObject('Catalog', XWFCatalog()) wordsplitter = Record() wordsplitter.group = 'Word Splitter' wordsplitter.name = 'HTML aware splitter' casenormalizer = Record() casenormalizer.group = 'Case Normalizer' casenormalizer.name = 'Case Normalizer' stopwords = Record() stopwords.group = 'Stop Words' stopwords.name = 'Remove listed and single char words' item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords)) zctextindex_extras = Record() zctextindex_extras.index_type = 'Okapi BM25 Rank' zctextindex_extras.lexicon_id = 'Lexicon' for key, index in self.get_metadataIndexMap().items(): if index == 'ZCTextIndex': zctextindex_extras.doc_attr = key item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': # we need to shortcut this one item.Catalog._catalog.addIndex(key, MultiplePathIndex(key)) else: item.Catalog.addIndex(key, index) # add the metadata we need item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate') item.manage_addProduct['MailHost'].manage_addMailHost('MailHost', smtp_host='127.0.0.1') return True
item.Catalog.addIndex(key, index)
try: item.Catalog.addIndex(key, index) except CatalogError: pass
def manage_afterAdd(self, item, container): """ For configuring the object post-instantiation. """ if getattr(self, '__initialised', 1): return 1 item._setObject('Catalog', XWFCatalog()) wordsplitter = Record() wordsplitter.group = 'Word Splitter' wordsplitter.name = 'HTML aware splitter' casenormalizer = Record() casenormalizer.group = 'Case Normalizer' casenormalizer.name = 'Case Normalizer' stopwords = Record() stopwords.group = 'Stop Words' stopwords.name = 'Remove listed and single char words' item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords)) zctextindex_extras = Record() zctextindex_extras.index_type = 'Okapi BM25 Rank' zctextindex_extras.lexicon_id = 'Lexicon' for key, index in self.get_metadataIndexMap().items(): if index == 'ZCTextIndex': zctextindex_extras.doc_attr = key item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': # we need to shortcut this one item.Catalog._catalog.addIndex(key, MultiplePathIndex(key)) else: item.Catalog.addIndex(key, index) # add the metadata we need item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate') item.manage_addProduct['MailHost'].manage_addMailHost('MailHost', smtp_host='127.0.0.1') return True
item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate')
for md in ('id','mailSubject','mailFrom','mailDate'): try: item.Catalog.addColumn(md) except CatalogError: pass
def manage_afterAdd(self, item, container): """ For configuring the object post-instantiation. """ if getattr(self, '__initialised', 1): return 1 item._setObject('Catalog', XWFCatalog()) wordsplitter = Record() wordsplitter.group = 'Word Splitter' wordsplitter.name = 'HTML aware splitter' casenormalizer = Record() casenormalizer.group = 'Case Normalizer' casenormalizer.name = 'Case Normalizer' stopwords = Record() stopwords.group = 'Stop Words' stopwords.name = 'Remove listed and single char words' item.Catalog.manage_addProduct['ZCTextIndex'].manage_addLexicon( 'Lexicon', 'Default Lexicon', (wordsplitter, casenormalizer, stopwords)) zctextindex_extras = Record() zctextindex_extras.index_type = 'Okapi BM25 Rank' zctextindex_extras.lexicon_id = 'Lexicon' for key, index in self.get_metadataIndexMap().items(): if index == 'ZCTextIndex': zctextindex_extras.doc_attr = key item.Catalog.addIndex(key, index, zctextindex_extras) elif index == 'MultiplePathIndex': # we need to shortcut this one item.Catalog._catalog.addIndex(key, MultiplePathIndex(key)) else: item.Catalog.addIndex(key, index) # add the metadata we need item.Catalog.addColumn('id') item.Catalog.addColumn('mailSubject') item.Catalog.addColumn('mailFrom') item.Catalog.addColumn('mailDate') item.manage_addProduct['MailHost'].manage_addMailHost('MailHost', smtp_host='127.0.0.1') return True
self.__initialised = 1
self._initialised = True
def upgrade(self): """ Upgrade to the latest version. """ currversion = getattr(self, '_version', 0) if currversion == self.version: return 'already running latest version (%s)' % currversion
memberlist = self.lowerList(self.getValueFor('maillist'))
memberlist = self.lowerList(self.getValueFor('mailinlist'))
def requestMail(self, REQUEST): # Handles un-/subscribe-requests.
custom_mailcheck = getattr(context, 'custom_mailcheck', None)
custom_mailcheck = getattr(self, 'custom_mailcheck', None)
def checkMail(self, REQUEST): # [email protected]: this is mostly the same as the MailBoxer parent, # only with notification. # Check for ip, loops and spam. # Check for correct IP mtahosts = self.getValueFor('mtahosts') if mtahosts: if 'HTTP_X_FORWARDED_FOR' in self.REQUEST.environ.keys(): REMOTE_IP = self.REQUEST.environ['HTTP_X_FORWARDED_FOR'] else: REMOTE_IP = self.REQUEST.environ['REMOTE_ADDR']
def get_userFromEmail(
def get_userFromEmail(
return sender_id
return ''
def get_mailUserId(self, from_addrs=[]): member_users = self.get_memberUserObjects() for addr in from_addrs: for member_user in member_users: addrs = member_user.getProperty('emailAddresses', []) for member_addr in addrs: if member_addr.lower() == addr.lower(): return member_user.getId() return sender_id
for group in member_groups: group = self.acl_users.getGroupById('%s_member' % self.listId())
for gid in member_groups: group = self.acl_users.getGroupById(gid)
def getValueFor(self, key): # getting the maillist is a special case, working in with the # XWFT group framework if key == 'maillist': # look for a maillist script maillist_script = getattr(self, 'maillist_members', None) if maillist_script: return maillist_script() maillist = [] try: member_groups = self.getProperty('member_groups', ['%s_member' % self.listId()]) uids = [] for group in member_groups: group = self.acl_users.getGroupById('%s_member' % self.listId()) uids += group.getUsers() for uid in uids: user = self.acl_users.getUser(uid) for email in user.get_preferredEmailAddresses(): email = email.strip() if email and email not in maillist: maillist.append(email) except: pass # last ditch effort if not maillist: maillist = self.getProperty('maillist') return maillist # Again, look for the property locally, then assume it is in the parent if self.aq_inner.hasProperty(key): return self.aq_inner.getProperty(key) else: return self.aq_parent.getProperty(key)
encoding = encoding_match and encoding_match.groups()[0]
encoding = encoding_match and encoding_match.groups()[0] or 'ascii'
def manage_addMail(self, mailString): """ Store mail & attachments in a folder and return it. """ import re archive = self.restrictedTraverse(self.getValueFor('storage'), default=None) # no archive available? then return immediately if archive is None: return None (header, body) = self.splitMail(mailString) # get the content type header, and re-encode the email to the default encoding ct = header.get('content-type',None) encoding = 'ascii' if ct: encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"].*?;', ct) encoding = encoding_match and encoding_match.groups()[0] for try_encoding in (encoding, 'utf-8', 'iso-8859-1', 'iso-8859-15'): try: mailString = mailString.decode(try_encoding) mailString.encode(getConfiguration().default_zpublisher_encoding or 'UTF-8') (header, body) = self.splitMail(mailString) break except (UnicodeDecodeError, LookupError): pass # if 'keepdate' is set, get date from mail, if self.getValueFor('keepdate'): timetuple = rfc822.parsedate_tz(header.get('date')) time = DateTime(rfc822.mktime_tz(timetuple)) # ... take our own date, clients are always lying! else: time = DateTime() # let's create the mailObject mailFolder = archive subject = self.mime_decode_header(header.get('subject', 'No Subject')) # correct the subject subject = self.tidy_subject(subject) if subject.lower().find('re:', 0, 3) == 0 and len(subject) > 3: subject = subject[3:].strip() elif len(subject) == 0: subject = 'No Subject' compressedsubject = re.sub('\s+', '', subject) sender = self.mime_decode_header(header.get('from','No From')) title = "%s / %s" % (subject, sender) # we use our IdFactory to get the next ID, rather than trying something # ad-hoc id = str(self.get_nextId()) self.addMailBoxerMail(mailFolder, id, title) mailObject = getattr(mailFolder, id) # unpack attachments (TextBody, ContentType, HtmlBody, Attachments) = self.unpackMail( mailString) # ContentType is only set for the TextBody if ContentType: mailBody = TextBody else: mailBody = self.HtmlToText(HtmlBody) # and now add some properties to our new mailobject self.setMailBoxerMailProperty(mailObject, 'mailFrom', sender, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailSubject', subject, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailDate', time, 'date') self.setMailBoxerMailProperty(mailObject, 'mailBody', mailBody, 'utext') self.setMailBoxerMailProperty(mailObject, 'compressedSubject', compressedsubject, 'string') types = {'date': ('date', convert_date), 'from': ('lines', convert_addrs), 'to': ('lines', convert_addrs), 'received': ('lines', null_convert),} for key in header.keys(): if key in types: self.setMailBoxerMailProperty(mailObject, key, types[key][1](self.mime_decode_header(header.get(key,''))), types[key][0]) else: self.setMailBoxerMailProperty(mailObject, key, self.mime_decode_header(header.get(key,'')), 'text') sender_id = self.get_mailUserId(mailObject.getProperty('from', [])) self.setMailBoxerMailProperty(mailObject, 'mailUserId', sender_id, 'string') self.catalogMailBoxerMail(mailObject)
mailString.encode(getConfiguration().default_zpublisher_encoding or 'UTF-8')
mailString.encode(getConfiguration().default_zpublisher_encoding or 'utf-8')
def manage_addMail(self, mailString): """ Store mail & attachments in a folder and return it. """ import re archive = self.restrictedTraverse(self.getValueFor('storage'), default=None) # no archive available? then return immediately if archive is None: return None (header, body) = self.splitMail(mailString) # get the content type header, and re-encode the email to the default encoding ct = header.get('content-type',None) encoding = 'ascii' if ct: encoding_match = re.search('charset=[\'\"]?(.*?)[\'\"].*?;', ct) encoding = encoding_match and encoding_match.groups()[0] for try_encoding in (encoding, 'utf-8', 'iso-8859-1', 'iso-8859-15'): try: mailString = mailString.decode(try_encoding) mailString.encode(getConfiguration().default_zpublisher_encoding or 'UTF-8') (header, body) = self.splitMail(mailString) break except (UnicodeDecodeError, LookupError): pass # if 'keepdate' is set, get date from mail, if self.getValueFor('keepdate'): timetuple = rfc822.parsedate_tz(header.get('date')) time = DateTime(rfc822.mktime_tz(timetuple)) # ... take our own date, clients are always lying! else: time = DateTime() # let's create the mailObject mailFolder = archive subject = self.mime_decode_header(header.get('subject', 'No Subject')) # correct the subject subject = self.tidy_subject(subject) if subject.lower().find('re:', 0, 3) == 0 and len(subject) > 3: subject = subject[3:].strip() elif len(subject) == 0: subject = 'No Subject' compressedsubject = re.sub('\s+', '', subject) sender = self.mime_decode_header(header.get('from','No From')) title = "%s / %s" % (subject, sender) # we use our IdFactory to get the next ID, rather than trying something # ad-hoc id = str(self.get_nextId()) self.addMailBoxerMail(mailFolder, id, title) mailObject = getattr(mailFolder, id) # unpack attachments (TextBody, ContentType, HtmlBody, Attachments) = self.unpackMail( mailString) # ContentType is only set for the TextBody if ContentType: mailBody = TextBody else: mailBody = self.HtmlToText(HtmlBody) # and now add some properties to our new mailobject self.setMailBoxerMailProperty(mailObject, 'mailFrom', sender, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailSubject', subject, 'ustring') self.setMailBoxerMailProperty(mailObject, 'mailDate', time, 'date') self.setMailBoxerMailProperty(mailObject, 'mailBody', mailBody, 'utext') self.setMailBoxerMailProperty(mailObject, 'compressedSubject', compressedsubject, 'string') types = {'date': ('date', convert_date), 'from': ('lines', convert_addrs), 'to': ('lines', convert_addrs), 'received': ('lines', null_convert),} for key in header.keys(): if key in types: self.setMailBoxerMailProperty(mailObject, key, types[key][1](self.mime_decode_header(header.get(key,''))), types[key][0]) else: self.setMailBoxerMailProperty(mailObject, key, self.mime_decode_header(header.get(key,'')), 'text') sender_id = self.get_mailUserId(mailObject.getProperty('from', [])) self.setMailBoxerMailProperty(mailObject, 'mailUserId', sender_id, 'string') self.catalogMailBoxerMail(mailObject)
import random self.id = id self.title = title
MailBoxer.__init__(self, id, title)
def __init__(self, id, title, mailto): """ Setup a MailBoxer with reasonable defaults. """ import random self.id = id self.title = title self.mailto = mailto self.hashkey = str(random.random())
self.hashkey = str(random.random()) def get_property(self, id): """ """ return getattr(aq_base(self), id) def del_property(self, id): """ """ return delattr(aq_base(self), id)
def valid_property_id(self, id): if not id or id[:1]=='_' or (id[:3]=='aq_') \ or (' ' in id) or escape(id) != id: return False return True
def __init__(self, id, title, mailto): """ Setup a MailBoxer with reasonable defaults. """ import random self.id = id self.title = title self.mailto = mailto self.hashkey = str(random.random())
else: delattr(aq_base(self), item['id'])
else: try: self._delProperty(item['id']) except: pass
def init_properties(self): """ Tidy up the property sheet, since we don't want to control most of the properties that have already been defined in the parent MailingListManager. """ delete_properties = filter(lambda x: x not in self.mailinglist_properties, self.propertyIds()) props = [] for item in self._properties: if item['id'] not in delete_properties: props.append(item) else: delattr(aq_base(self), item['id']) self._properties = tuple(props) self._p_changed = 1 return True
def get_maillist(self): """ """ return self.getValueFor('maillist') def get_mailinlist(self): """ """ return self.getValueFor('mailinlist')
def get_maillist(self): """ """ return self.getValueFor('maillist')
user = security.getUser()
sec = getSecurityManager() user = sec.getUser()
def send_email(self, REQUEST, RESPONSE, group_id, email_address, email_id, message, subject=''): """ Send an email to the group. We send the email via the mail server so it will handle things like message ID's for us. """ list_manager = self.get_xwfMailingListManager() user = security.getUser() if email_address not in user.get_emailAddresses(): raise 'Forbidden', 'Only the authenticated owner of an email address may use it to post' group = getattr(listmanager, group_id) group_email = group.getProperty('mailto') group_name = group.getProperty('title') message_id = None if email_id: orig_email = self.get_email(email_id) subject = 'Re: %s' % orig_email.getProperty('subject') message_id = orig_email.getProperty('message-id', '') name = '%s %s' % (user.preferredName, user.lastName) headers = """From: %s <%s>
class Service(component.Service):
class Service(component.Service, protocol.Factory):
def connectionLost(self, reason): if self.state == socks5.STATE_CONNECT_PENDING: self.service.removePendingConnection(self.addr, self) else: if self.peersock != None: self.peersock.peersock = None self.peersock.transport.loseConnection() self.peersock = None self.service.removeActiveConnection(self.addr, self)
self.associateWithRouter(config["secret"], config["rhost"], config["rport"])
self.associateWithRouter(config["secret"], config["rhost"], int(config["rport"], 10))
def __init__(self, serviceParent, config): component.Service.__init__(self, config["jid"], serviceParent)
i["name"] = "JEP-65 Proxy"
i["name"] = "SOCKS5 Bytestreams Service"
def onDisco(self, iq): iq.swapAttribs("to", "from") iq["type"] = "result" iq.query.children = [] i = iq.query.addElement("identity") i["category"] = "proxy" i["type"] = "bytestreams" i["name"] = "JEP-65 Proxy" iq.query.addElement("feature")["var"] = "http://jabber.org/protocol/bytestreams" self.xmlstream.send(iq)
iq.query.addElement("error")["code"] = "405"
e = iq.addElement("error") e["code"] = "405" e["type"] = "cancel" c = e.addElement("condition") c["xmlns"] = "urn:ietf:params:xml:ns:xmpp-stanzas" c.addElement("not-allowed")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate))
iq.query.addElement("error")["code"] = "404"
e = iq.addElement("error") e["code"] = "404" e["type"] = "cancel" c = e.addElement("condition") c["xmlns"] = "urn:ietf:params:xml:ns:xmpp-stanzas" c.addElement("item-not-found")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate))
s["jid"] = self.jabberId
s["jid"] = self.jid
def onGetHostInfo(self, iq): iq.swapAttributeValues("to", "from") iq["type"] = "result" iq.query.children = [] s = iq.query.addElement("streamhost") s["jid"] = self.jabberId s["host"] = self.proxyIP s["port"] = str(self.proxyPort) self.send(iq)
if self.service.addConnection(addr):
if self.service.addConnection(addr, self):
def connectRequested(self, addr, port): # Check for special connect to the namespace -- this signifies that the client # is just checking to ensure it can connect to the streamhost if addr == "http://jabber.org/protocol/bytestreams": self.connectCompleted(addr, 0) self.transport.loseConnection() return # Save addr, for cleanup self.addr = addr # Check to see if the requested address is already # activated -- send an error if so if self.service.isActive(addr): self.sendErrorReply(socks5.REPLY_CONN_NOT_ALLOWED) return
self.peersock.transport.loseConnection()
self.peersock.transport.unregisterProducer()
def connectionLost(self, reason): if self.state == socks5.STATE_CONNECT_PENDING: self.service.removePendingConnection(self.addr, self) else: if self.peersock != None: self.peersock.peersock = None self.peersock.transport.loseConnection() self.peersock = None self.service.removeActiveConnection(self.addr, self)
self.service.removeActiveConnection(self.addr, self)
self.service.removeActiveConnection(self.addr)
def connectionLost(self, reason): if self.state == socks5.STATE_CONNECT_PENDING: self.service.removePendingConnection(self.addr, self) else: if self.peersock != None: self.peersock.peersock = None self.peersock.transport.loseConnection() self.peersock = None self.service.removeActiveConnection(self.addr, self)
iq.swapAttribs("to", "from")
iq.swapAttributeValues("to", "from")
def onGetHostInfo(self, iq): iq.swapAttribs("to", "from") iq["type"] = "result" iq.query.children = [] s = iq.query.addElement("streamhost") s["jid"] = self.jabberId s["host"] = self.proxyIP s["port"] = self.proxyPort self.xmlstream.send(iq)
s["port"] = self.proxyPort
s["port"] = str(self.proxyPort)
def onGetHostInfo(self, iq): iq.swapAttribs("to", "from") iq["type"] = "result" iq.query.children = [] s = iq.query.addElement("streamhost") s["jid"] = self.jabberId s["host"] = self.proxyIP s["port"] = self.proxyPort self.xmlstream.send(iq)
iq.swapAttribs("to", "from")
print iq.toXml() iq.swapAttributeValues("to", "from")
def onDisco(self, iq): iq.swapAttribs("to", "from") iq["type"] = "result" iq.query.children = [] i = iq.query.addElement("identity") i["category"] = "proxy" i["type"] = "bytestreams" i["name"] = "SOCKS5 Bytestreams Service" iq.query.addElement("feature")["var"] = "http://jabber.org/protocol/bytestreams" self.xmlstream.send(iq)
iq.swapAttribs("to", "from")
iq.swapAttributeValues("to", "from")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate))
olist[0].transport.startReading() olist[1].transport.startReading()
olist[0].transport.registerProducer(olist[1], 0) olist[1].transport.registerProducer(olist[0], 0)
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate))
c = e.addElement("condition")
c = e.addElement("not-allowed")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate)) log.msg("Activation requested for: ", sid)
c.addElement("not-allowed")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate)) log.msg("Activation requested for: ", sid)
c = e.addElement("condition")
c = e.addElement("item-not-found")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate)) log.msg("Activation requested for: ", sid)
c.addElement("item-not-found")
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate)) log.msg("Activation requested for: ", sid)
sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate))
fromJID = jid.internJID(iq["from"]) activateJID = jid.internJID(iq.query.activate) sid = hashSID(iq.query["sid"], fromJID, activateJID)
def onActivateStream(self, iq): sid = hashSID(iq.query["sid"], iq["from"], str(iq.query.activate)) log.msg("Activation requested for: ", sid)
sigpow += test_vec_out[k].r * test_vec_out[k].i +
sigpow += test_vec_out[k].r * test_vec_out[k].r +
def compare_func(): s="""
err = test_vec_out[k].r - testbuf[k].r; noisepow += err * err; err = test_vec_out[k].i - testbuf[k].i; noisepow += err * err;
C_SUB(err,test_vec_out[k],testbuf[k].r); noisepow += err.r * err.r + err.i + err.i;
def compare_func(): s="""
*h = self->box.h - self->element->il - self->element->ib
*h = self->box.h - self->element->it - self->element->ib def land_widget_inner_extents(LandWidget *self, float *l, *t, *r, *b): *l = self->box.x + self->element->il *t = self->box.y + self->element->it *r = self->box.x + self->box.w - self->element->ir *b = self->box.y + self->box.h - self->element->ib
def land_widget_inner(LandWidget *self, float *x, *y, *w, *h): *x = self->box.x + self->element->il *y = self->box.y + self->element->it *w = self->box.w - self->element->il - self->element->ir *h = self->box.h - self->element->il - self->element->ib
land_free(self->data)
if self->data: land_free(self->data)
def land_array_destroy(LandArray *self): land_free(self->data) land_free(self)
atexit(land_log_del)
if not once: atexit(land_log_del) once++
def land_log_new(char const *base, int unique): FILE *f int i = 0 if logname: land_free(logname) logname = land_malloc(strlen(base) + 10) atexit(land_log_del) if unique: do: sprintf(logname, "%s%04d.log", base, i) f = fopen(logname, "r") if f: fclose(f) i++ while (f) else: sprintf(logname, "%s.log", base) f = fopen(logname, "w") if f: fprintf(f, "******* new log *******\n") fclose(f)
land_widget_base_size(super)
def land_widget_container_size(LandWidget *super): LandWidgetContainer *self = LAND_WIDGET_CONTAINER(super) if !self->children: return LandListItem *item = self->children->first while item: LandWidget *child = item->data land_call_method(child, size, (child)) item = item->next land_widget_base_size(super)
if pixel_y > -h:
def land_grid_draw_isometric(LandGrid *self, LandView *view): float w = self->cell_w / 2 float h = self->cell_h / 2 int cell_x, cell_y float pixel_x, pixel_y float view_x = view->scroll_x float view_y = view->scroll_y if !find_offset(self, view_x, view_y, &cell_x, &cell_y, &pixel_x, &pixel_y): return # One row up might also be in. if pixel_y > -h: # if cell_x > 0 && pixel_x > 0: # { # cell_x-- # pixel_x -= w # pixel_y -= h # } # elif cell_y > 0: cell_y-- pixel_x += w pixel_y -= h pixel_x += view->x pixel_y += view->y while pixel_y < view->y + view->h: float line_pixel_x = pixel_x float line_pixel_y = pixel_y int line_cell_x = cell_x int line_cell_y = cell_y while pixel_x - w < view->x + view->w: self->vt->draw_cell(self, view, cell_x, cell_y, pixel_x, pixel_y) if cell_x < (int)self->x_cells - 1: pixel_x += w pixel_y += h cell_x++ else: break if cell_y > 0: pixel_x += w pixel_y -= h cell_y-- else: break cell_x = line_cell_x cell_y = line_cell_y pixel_x = line_pixel_x pixel_y = line_pixel_y if pixel_x > view->x && cell_y < (int)self->y_cells - 1: pixel_x -= w pixel_y += h cell_y++ else: if cell_x >= self->x_cells - 1: break pixel_x += w pixel_y += h cell_x++
cell_y-- pixel_x += w pixel_y -= h
def land_grid_draw_isometric(LandGrid *self, LandView *view): float w = self->cell_w / 2 float h = self->cell_h / 2 int cell_x, cell_y float pixel_x, pixel_y float view_x = view->scroll_x float view_y = view->scroll_y if !find_offset(self, view_x, view_y, &cell_x, &cell_y, &pixel_x, &pixel_y): return # One row up might also be in. if pixel_y > -h: # if cell_x > 0 && pixel_x > 0: # { # cell_x-- # pixel_x -= w # pixel_y -= h # } # elif cell_y > 0: cell_y-- pixel_x += w pixel_y -= h pixel_x += view->x pixel_y += view->y while pixel_y < view->y + view->h: float line_pixel_x = pixel_x float line_pixel_y = pixel_y int line_cell_x = cell_x int line_cell_y = cell_y while pixel_x - w < view->x + view->w: self->vt->draw_cell(self, view, cell_x, cell_y, pixel_x, pixel_y) if cell_x < (int)self->x_cells - 1: pixel_x += w pixel_y += h cell_x++ else: break if cell_y > 0: pixel_x += w pixel_y -= h cell_y-- else: break cell_x = line_cell_x cell_y = line_cell_y pixel_x = line_pixel_x pixel_y = line_pixel_y if pixel_x > view->x && cell_y < (int)self->y_cells - 1: pixel_x -= w pixel_y += h cell_y++ else: if cell_x >= self->x_cells - 1: break pixel_x += w pixel_y += h cell_x++
land_widget_layout_inhibit(self)
def land_widget_base_size(LandWidget *self): land_widget_layout_inhibit(self) land_widget_layout(self) land_widget_layout_enable(self)
land_widget_layout_enable(self)
def land_widget_base_size(LandWidget *self): land_widget_layout_inhibit(self) land_widget_layout(self) land_widget_layout_enable(self)
static import global winsock
static import global winsock2, ws2tcpip static macro SHUT_RDWR SD_BOTH static import global sys/time, sys/socket, sys/ioctl, errno, arpa/inet static import netdb, signal
#ifdef WINDOWS
static import global sys/time, sys/socket, sys/ioctl, errno, arpa/inet, netdb,\ signal
#ifdef WINDOWS
static int once = 1
#ifdef WINDOWS
char a = 1;
def land_net_listen(LandNet *self, char const *address): int r struct sockaddr_in sock_address char *host int port if self->state != LAND_NET_INVALID: return self->local_address = strdup (address) split_address(address, &host, &port) # Resolve hostname. struct hostent *hostinfo if not (hostinfo = gethostbyname (host)): free (host) perror("gethostbyname") return free (host) int a = 1 setsockopt(self->sock, IPPROTO_TCP, SO_REUSEADDR, &a, sizeof(a)) # Address to listen on. sock_address.sin_family = AF_INET # Fill in IP (returned in network byte order by gethostbyname). sock_address.sin_addr = *(struct in_addr *) hostinfo->h_addr # Fill in port (and convert to network byte order). sock_address.sin_port = htons (port) r = bind(self->sock, (struct sockaddr *) &sock_address, sizeof sock_address) if r < 0: perror ("bind") return r = listen (self->sock, SOMAXCONN) if r < 0: perror ("listen") return self->state = LAND_NET_LISTENING D(land_log_message ("Listening on host %s port %d (%s).\n", host, port, land_net_get_address (self, 0)))
if WSAGetLastError () != WSAEINTR &&
if WSAGetLastError () != WSAEINTR and\
static def land_net_poll_recv(LandNet *self): int r if self->size == 0 or self->full == self->size: return r = recv (self->sock, self->buffer + self->full, self->size - self->full, 0) if r < 0: #if defined WINDOWS if WSAGetLastError () != WSAEINTR && WSAGetLastError () != WSAEWOULDBLOCK: #else if errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN: #endif perror ("recv") return return if r == 0: # Remote shut down. self->state = LAND_NET_INVALID self->full += r #ifdef DEBUG_BYTES land_log_message("Received %d bytes: ", r) int i for i = 0; i < r; i++: int c = (unsigned char)self->buffer[self->full - r + i] land_log_message_nostamp ("%d[%c],", c, c >= 32 && c <= 128 ? c : '.') land_log_message_nostamp("\n") #endif
if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues
if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues
def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues)
def __init__(self, codecMap): self.__codecMap = codecMap
def __init__(self, __codecMap): self.__codecMap = __codecMap
def __init__(self, codecMap): self.__codecMap = codecMap
def __cmp__(self, other): return cmp(self.__hashedValues, other)
# def __cmp__(self, other):
if len(client) > 1:
if hasattr(client, 'getDefaultComponentByPosition'):
def _encodeValue(self, encodeFun, client, defMode, maxChunkSize): if hasattr(client, 'setDefaultComponents'): client.setDefaultComponents() client.verifySizeSpec() # Guess client type basing on number of component types. # This is certainly a hack but how do I distinguish one from # another if they have the same tags&constraints? substrate = ''; idx = len(client) if len(client) > 1: # Set comps = [] while idx > 0: idx = idx - 1 if client[idx] is None: # Optional component continue if client.getDefaultComponentByPosition(idx) == client[idx]: continue comps.append(client[idx]) comps.sort(self._cmpSetComponents) for c in comps: substrate = substrate + encodeFun(c, defMode, maxChunkSize) else: # SetOf compSubs = [] while idx > 0: idx = idx - 1 compSubs.append( encodeFun(client[idx], defMode, maxChunkSize) ) compSubs.sort() # perhaps padding's not needed substrate = string.join(compSubs, '') return substrate, 1
r.append("<p>TEST_DATA is %s</p>" % (defaults.TEST_DATA,))
def default_page(): """Show the visitor the options to start a survey """ r=[cgiUtils.section('First: an outline of your survey')] r.append(cgiUtils.form_begin(action=THIS_SCRIPT,enctype='multipart/form-data',charset=defaults.HTML_CODEC)) #r.append("<form action='%s' enctype='multipart/form-data' method='POST' accept-charset='%s'>\n" % (THIS_SCRIPT,defaults.HTML_CODEC)) background="""<p>
id = self.optimizer_menu.FindItem("Features")
id = self.optimizer_menu.FindItem("Features...")
def enable_controls(self, enable=True): id = self.optimizer_menu.FindItem("Start") self.optimizer_menu.Enable(id, enable) id = self.optimizer_menu.FindItem("Features") self.optimizer_menu.Enable(id, enable) id = self.optimizer_menu.FindItem("Open") self.optimizer_menu.Enable(id, enable) self.status.enable_controls(enable) self.update_status()
if self.settings_filename != None:
if self.settings_filename is not None:
def save_cb(self, evt): if self.classifier == None: gui_util.message("There is no loaded classifier to save.") else: if self.settings_filename != None: wxBeginBusyCursor() self.classifier.save_settings(self.settings_filename) wxEndBusyCursor() else: self.save_as_cb(evt)
wxBeginBusyCursor() self.classifier.save_settings(self.settings_filename) wxEndBusyCursor()
if self.settings_filename is not None: wxBeginBusyCursor() self.classifier.save_settings(self.settings_filename) wxEndBusyCursor()
def save_as_cb(self, evt): if self.classifier == None: gui_util.message("There is no loaded classifier to save.") else: self.settings_filename = gui_util.save_file_dialog(self) wxBeginBusyCursor() self.classifier.save_settings(self.settings_filename) wxEndBusyCursor()
if self.default is None:
if default is None:
def __init__(self, name=None, default=None, length=-1): Class.__init__(self, name, self.klass) if type(length) != int: raise TypeError("'length' must be an int") self.length = length if self.default is None: self.default = [] self.has_default = False else: self.default = default self.has_default = True
subimage = SubImage(self.image, y, x, h, w) image = apply(wxEmptyImage, (w, h))
subimage = SubImage(self.image, y, x, h + 1, w + 1) image = apply(wxEmptyImage, (w + 1, h + 1))
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = self.GetViewStart() size = self.GetSizeTuple() ox = x - (origin[0] / self.scaling) oy = y - (origin[1] / self.scaling) if check: if ((x + w < (origin[0] / self.scaling) and y + h < (origin[1] / self.scaling)) or (x > (origin[0] + size[0]) / self.scaling and y > (origin[1] + size[1]) / self.scaling) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y if (x + w > self.image.ncols): w = self.image.ncols - x subimage = SubImage(self.image, y, x, h, w) image = apply(wxEmptyImage, (w, h)) image.SetData(apply(self.to_string_function, (subimage, ))) bmp = image.ConvertToBitmap() self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
break return selection, active_id, inactive_id
return selection, active_id, inactive_id return [], self.multi_iw.id, self.class_iw.id
def get_all_selected(self): for display in (self.multi_iw.id, self.class_iw.id): if display.IsSelection(): selection = display.GetSelectedItems(display.GetGridCursorRow(), display.GetGridCursorCol()) active_id = display inactive_id = self.get_other_multi(display) break return selection, active_id, inactive_id
filename = gui_util.open_file_dialog(self.text, self.extension)
parent = self.text.GetParent() filename = gui_util.open_file_dialog(parent, self.extension)
def OnBrowse(self, event): filename = gui_util.open_file_dialog(self.text, self.extension) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
self.text.GetParent().Raise() def get(self):
parent.Raise() if wxIsBusy(): wxEndBusyCursor() def get(self):
def OnBrowse(self, event): filename = gui_util.open_file_dialog(self.text, self.extension) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
filename = gui_util.save_file_dialog(self.text, self.extension)
parent = self.text.GetParent() filename = gui_util.save_file_dialog(parent, self.extension)
def OnBrowse(self, event): filename = gui_util.save_file_dialog(self.text, self.extension) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
self.text.GetParent().Raise()
parent.Raise() if wxIsBusy(): wxEndBusyCursor()
def OnBrowse(self, event): filename = gui_util.save_file_dialog(self.text, self.extension) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
parent = self.text.GetParent()
def OnBrowse(self, event): filename = gui_util.directory_dialog(self.text) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
self.text.GetParent().Raise() def get(self):
parent.Raise() if wxIsBusy(): wxEndBusyCursor() def get(self):
def OnBrowse(self, event): filename = gui_util.directory_dialog(self.text) if filename: self.text.SetValue(filename) self.text.GetParent().Raise()
self.status.enable_controls(True)
self.status.enable_controls(enable)
def enable_controls(self, enable=True): id = self.file_menu.FindItem("Start") self.file_menu.Enable(id, enable) id = self.file_menu.FindItem("Features") self.file_menu.Enable(id, enable) id = self.file_menu.FindItem("Open") self.file_menu.Enable(id, enable) self.status.enable_controls(True) self.update_status()
id = image
id = image.id_name
def do_auto_move(self, state): # if auto-moving is turned off, just return if state == []: return
image = dlg.show(self, image_menu.shell.locals, name="Choose image")
image = dlg.show(self, image_menu.shell.locals)
def _OnChooseImage(self, event): dlg = Args([Class("Image for context display", ImageBase)]) image = dlg.show(self, image_menu.shell.locals, name="Choose image") if image != None: self.id.set_image(image)
self.id.set_image(image)
self.id.set_image(image[0])
def _OnChooseImage(self, event): dlg = Args([Class("Image for context display", ImageBase)]) image = dlg.show(self, image_menu.shell.locals, name="Choose image") if image != None: self.id.set_image(image)
self._SaveEditorCollection(event)
self._SaveEditorCollection(self.editor_collection_filename)
def _OnSaveEditorCollectionAs(self, event): if gui_util.are_you_sure_dialog("There are %d glyphs in the editor.\nAre you sure you want to save?" % len(glyphs)): filename = gui_util.save_file_dialog(self._frame, gamera_xml.extensions) if filename: self.editor_collection_filename = filename self._SaveEditorCollection(event)
def __getattr__(self, attr): init_gamera() if hasattr(self, attr): return getattr(self, attr) else: raise AttributeError("'Image' object has no attribute '%s'." % attr)
def __getstate__(self): """Extremely basic pickling support for use in testing. Note that there is no unpickling support.""" dict = {} for key in self._members_for_menu: dict[key] = getattr(self, key) dict['encoded_data'] = util.encode_binary( self.to_string()) return dict
_gamera_initialised = True
def _init_gamera(): global _gamera_initialised if _gamera_initialised: return import plugin, gamera_xml, sys # Create the default functions for the menupl for method in ( plugin.PluginFactory( "load_image", "File", plugin.ImageType(ALL, "image"), plugin.ImageType(ALL), plugin.Args([plugin.FileOpen("filename")])), plugin.PluginFactory( "display", "Displaying", None, plugin.ImageType(ALL), None), plugin.PluginFactory( "display_ccs", "Displaying", None, plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "display_false_color", "Displaying", None, plugin.ImageType([GREYSCALE, FLOAT]), None), plugin.PluginFactory( "classify_manual", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "classify_heuristic", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "classify_automatic", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "unclassify", "Classification", None, plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "to_xml", "XML", plugin.String('xml'), plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "to_xml_filename", "XML", None, plugin.ImageType([ONEBIT]), plugin.Args([ plugin.FileSave("filename", extension=gamera_xml.extensions)])) ): method.register() paths.import_directory(paths.plugins, globals(), locals(), 1) sys.path.append(".") _gamera_initialised = True
raise RuntimeError("%s in not a TIFF or PNG file." % filename)
raise RuntimeError("%s is not a TIFF or PNG file." % filename)
def load_image(filename, compression = DENSE): """**load_image** (FileOpen *filename*, Choice *storage_format* = ``DENSE``)