rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
if not re.search(r"{{-.*-}}", l):
if not re.search(r"{{-.*-.*}}", l):
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
2e7db129055f80b1ee24b678ddba316192b6734b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/2e7db129055f80b1ee24b678ddba316192b6734b/wiktio2xml.py
if not re.search(r"{{-.*-}}", l):
if not re.search(r"{{-.*-.*}}", l):
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
2e7db129055f80b1ee24b678ddba316192b6734b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/2e7db129055f80b1ee24b678ddba316192b6734b/wiktio2xml.py
if not re.search(r"{{-.*-}}", l):
if not re.search(r"{{-.*-.*}}", l):
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
2e7db129055f80b1ee24b678ddba316192b6734b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/2e7db129055f80b1ee24b678ddba316192b6734b/wiktio2xml.py
file = file[1] print "voices/fr/words/" + file.replace("}}", "")
file = file[1].replace("}}", "") print "<a href=http://fr.wiktionary.org/wiki/Fichier:" \ + file + ">" + file + "</a>"
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
2e7db129055f80b1ee24b678ddba316192b6734b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/2e7db129055f80b1ee24b678ddba316192b6734b/wiktio2xml.py
print self.equivs
def __init__(self, gcomprisBoard): # Save the gcomprisBoard, it defines everything we need # to know from the core self.gcomprisBoard = gcomprisBoard
688c17fe23a581d12f8605c8f929efd7a834f840 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/688c17fe23a581d12f8605c8f929efd7a834f840/hangman.py
l = concat + l
def parseText(self): inWord = wiktio.Word() inDefinition = None inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = "" filterIndent = "" gender = ""
693ebee3c07d10de8294c115918813df0ffbb607 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/693ebee3c07d10de8294c115918813df0ffbb607/wiktio2xml.py
print "Tuxpaint not killed", self.pid
print "Tuxpaint not killed", pid
def end(self): gcompris.sound.reopen() global pid # force kill - data loss if pid != None: print "Tuxpaint not killed", self.pid #import os #os.kill(self.pid, signal.SIGKILL) if self.rootitem != None: self.rootitem.remove() self.rootitem = None
45b5cf3d4ebc20ecaaf4a3179202244ecc07876d /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/45b5cf3d4ebc20ecaaf4a3179202244ecc07876d/tuxpaint.py
if (gcompris.get_properties().fullscreen and not gcompris.get_properties().noxf86vm): gtk.gdk.pointer_grab(data.window.window, True, 0, data.window.window) if (gtk.gtk_version <= (2,6,10)): data.window.unfullscreen() data.window.fullscreen()
def child_callback(fd, cond, data): # restore pointergrab if running fullscreen if (gcompris.get_properties().fullscreen and not gcompris.get_properties().noxf86vm): gtk.gdk.pointer_grab(data.window.window, True, 0, data.window.window) #bug in gtk2.6/window if (gtk.gtk_version <= (2,6,10)): data.window.unfullscreen() data.window.fullscreen() global pid pid = None global fles fles.end() gcompris.end_board()
45b5cf3d4ebc20ecaaf4a3179202244ecc07876d /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11306/45b5cf3d4ebc20ecaaf4a3179202244ecc07876d/tuxpaint.py
req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i"
req_string = "show line1:%s line2:%s duration:%s " req_string += "brightness:%s font:%s centered:%i"
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
6768994c2cf8f8867a578b903d001b9de8119c1c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11405/6768994c2cf8f8867a578b903d001b9de8119c1c/player.py
(line1, line2, duration, brightness, font, int(centered)))
(line1, line2, str(duration), str(brightness), font, int(centered))) def display(self, line1="", line2="", duration=3): line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "display line1:%s line2:%s duration:%s " self.request(req_string % (line1, line2, str(duration))
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
6768994c2cf8f8867a578b903d001b9de8119c1c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11405/6768994c2cf8f8867a578b903d001b9de8119c1c/player.py
req_string = "display line1:%s line2:%s duration:%s "
req_string = "display %s %s %s"
def display(self, line1="", line2="", duration=3): line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "display line1:%s line2:%s duration:%s " self.request(req_string % (line1, line2, str(duration)))
6c406b2f62657570837019f93add3a70f96ef28f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/11405/6c406b2f62657570837019f93add3a70f96ef28f/player.py
p = subprocess.Popen(cmd, env=local_env, stdout=subprocess.PIPE)
def run_test_prog(bits, pagesize, cmd, **env): if paranoid_pool_check: beforepool = snapshot_pool_state() print "Pool state: %s" % str(beforepool) local_env = os.environ.copy() local_env.update(env) local_env["PATH"] = "./obj%d:../obj%d:%s" \ % (bits, bits, local_env.get("PATH", "")) local_env["LD_LIBRARY_PATH"] = "../obj%d:obj%d:%s" \ % (bits, bits, local_env.get("LD_LIBRARY_PATH", "")) local_env["HUGETLB_DEFAULT_PAGE_SIZE"] = repr(pagesize) p = subprocess.Popen(cmd, env=local_env, stdout=subprocess.PIPE) try: rc = p.wait() except KeyboardInterrupt: # Abort and mark this a strange test result return (None, "") out = p.stdout.read().strip() if paranoid_pool_check: afterpool = snapshot_pool_state() if afterpool != beforepool: print >>sys.stderr, "Hugepage pool state not preserved!" print >>sys.stderr, "BEFORE: %s" % str(beforepool) print >>sys.stderr, "AFTER: %s" % str(afterpool) sys.exit(98) return (rc, out)
e183f433594a8f3bf59ffa6c90c56445281736f1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/3715/e183f433594a8f3bf59ffa6c90c56445281736f1/run_tests.py
if len(wordsizes) == 0: wordsizes = set([32, 64])
if len(wordsizes) == 0: wordsizes = get_wordsizes()
def main(): global wordsizes, pagesizes, dangerous, paranoid_pool_check, system_default_hpage_size testsets = set() env_override = {"QUIET_TEST": "1", "HUGETLBFS_MOUNTS": "", "HUGETLB_ELFMAP": None, "HUGETLB_MORECORE": None} env_defaults = {"HUGETLB_VERBOSE": "0"} dangerous = 0 paranoid_pool_check = False try: opts, args = getopt.getopt(sys.argv[1:], "vVfdt:b:p:c") except getopt.GetoptError, err: print str(err) sys.exit(1) for opt, arg in opts: if opt == "-v": env_override["QUIET_TEST"] = None env_defaults["HUGETLB_VERBOSE"] = "2" elif opt == "-V": env_defaults["HUGETLB_VERBOSE"] = "99" elif opt == "-f": dangerous = 1 elif opt == "-t": for t in arg.split(): testsets.add(t) elif opt == "-b": for b in arg.split(): wordsizes.add(int(b)) elif opt == "-p": for p in arg.split(): pagesizes.add(int(p)) elif opt == '-c': paranoid_pool_check = True else: assert False, "unhandled option" if len(testsets) == 0: testsets = set(["func", "stress"]) if len(wordsizes) == 0: wordsizes = set([32, 64]) if len(pagesizes) == 0: pagesizes = get_pagesizes() if len(pagesizes) == 0: print "Unable to find available page sizes, are you sure hugetlbfs" print "is mounted and there are available huge pages?" return 1 setup_env(env_override, env_defaults) init_results() (rc, system_default_hpage_size) = hpage_size() if rc != 0: print "Unable to find system default hugepage size." print "Is hugepage supported included in this kernel?" return 1 check_hugetlbfs_path() if "func" in testsets: functional_tests() if "stress" in testsets: stress_tests() results_summary()
30c9d6c77246225e28fe3282cab92b554b5f8bb2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/3715/30c9d6c77246225e28fe3282cab92b554b5f8bb2/run_tests.py
profiles = ['profile-recensio.policy:default'] + additional_profiles
profiles = ['profile-recensio.policy:default'] + additional_profiles +\ ['profile-recensio.policy:default']
def reloadProfiles(br): profiles = ['profile-recensio.policy:default'] + additional_profiles for profile in profiles: print "Trying to load profile %s" % profile br.open(host + '/portal_setup/manage_importSteps') br.getControl(name='context_id', index=0).value = [profile] br.getForm('profileform').submit() br.getControl('Import all steps').click() print "Profile %s loaded" % profile
103cea0a3672af9e1f91aaa4bb27a1d1abf81fe2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/103cea0a3672af9e1f91aaa4bb27a1d1abf81fe2/__init__.py
criterion.setLocation('/')
criterion.setRelativePath('/') criterion.setRecurse(True)
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setLocation('/') except BadRequest: pass
a1e61e0be15636594b4ae06cb9d328bd515aa0cb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/a1e61e0be15636594b4ae06cb9d328bd515aa0cb/setuphandlers.py
portal_types = []
portal_types = ['Rezension']
def configureContentRatings(context): portal = context.getSite() utility = getUtility(IRatingCategoryAssignment) portal_types = [] categories_to_set = [utility._avalable_categories.by_token[''].value] for type in portal_types: utility.assign_categories(type, categories_to_set)
45d3975fb6b9201a8552018fc75d02dc6ba9c3d8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/45d3975fb6b9201a8552018fc75d02dc6ba9c3d8/setuphandlers.py
criterion = new_discussions.addCriterion(field='last_comment_date',\ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-')
try: criterion = new_discussions.addCriterion(field='last_comment_date',\ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setLocation('/') except BadRequest: pass
45d3975fb6b9201a8552018fc75d02dc6ba9c3d8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/45d3975fb6b9201a8552018fc75d02dc6ba9c3d8/setuphandlers.py
if id not in ['images']: language = 'de' else:
if id in ['images']:
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id not in ['images']: language = 'de' else: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
445c640b1b0bca473c2354f6a1a8ca81dba5efa1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/445c640b1b0bca473c2354f6a1a8ca81dba5efa1/setuphandlers.py
doSetLanguage(ob, language)
doSetLanguage(ob, language)
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id not in ['images']: language = 'de' else: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
445c640b1b0bca473c2354f6a1a8ca81dba5efa1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/445c640b1b0bca473c2354f6a1a8ca81dba5efa1/setuphandlers.py
if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
445c640b1b0bca473c2354f6a1a8ca81dba5efa1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/445c640b1b0bca473c2354f6a1a8ca81dba5efa1/setuphandlers.py
log.warning('%s is already translated into %s!' % path,lang_trans)
log.warning('%s is already translated into %s!' % ("/".join(path + [item]),lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
445c640b1b0bca473c2354f6a1a8ca81dba5efa1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/445c640b1b0bca473c2354f6a1a8ca81dba5efa1/setuphandlers.py
if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
445c640b1b0bca473c2354f6a1a8ca81dba5efa1 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/445c640b1b0bca473c2354f6a1a8ca81dba5efa1/setuphandlers.py
fp = getattr(site, 'front-page', None) if not fp: log.error('Front page not found') return id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string')
for fp_id in ['front-page', 'front-page-en', 'front-page-fr']: fp = getattr(site, fp_id, None) if not fp: log.error('%s not found' % fp_id) continue id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string')
def setupHomepage(context): site = context.getSite() fp = getattr(site, 'front-page', None) if not fp: log.error('Front page not found') return id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
f2abd3d751b93638d0417fbb150a989d7d79cd82 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f2abd3d751b93638d0417fbb150a989d7d79cd82/setuphandlers.py
autoren = getattr(portal, 'autoren', None) if not autoren: log.warning('Folder "autoren" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_en = getattr(portal, 'autoren-en', None) if not autoren_en: log.warning('Folder "autoren-en" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_en, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_fr = getattr(portal, 'autoren-fr', None) if not autoren_fr: log.warning('Folder "autoren-fr" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_fr, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') themen = getattr(portal, 'themen-epochen-regionen', None) if not themen: log.warning('Folder "themen-epochen-regionen" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(themen, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='browse-topics', type='string')
for autoren_id in ['autoren', 'autoren-en', 'autoren-fr']: autoren = getattr(portal, autoren_id, None) if not autoren: log.warning('Folder "%s" not found on portal. Please run recensio.contenttypes.initial_content' % autoren_id) else: fp = getattr(autoren, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') for themen_id in ['themen-epochen-regionen', 'themen-epochen-regionen-en', 'themen-epochen-regionen-fr']: themen = getattr(portal, themen_id, None) if not themen: log.warning('Folder "%s" not found on portal. Please run recensio.contenttypes.initial_content' % themen_id) else: fp = getattr(themen, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='browse-topics', type='string')
def setViewsOnFolders(context): portal = context.getSite() autoren = getattr(portal, 'autoren', None) if not autoren: log.warning('Folder "autoren" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_en = getattr(portal, 'autoren-en', None) if not autoren_en: log.warning('Folder "autoren-en" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_en, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_fr = getattr(portal, 'autoren-fr', None) if not autoren_fr: log.warning('Folder "autoren-fr" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_fr, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') themen = getattr(portal, 'themen-epochen-regionen', None) if not themen: log.warning('Folder "themen-epochen-regionen" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(themen, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='browse-topics', type='string') rezensionen = getattr(portal, 'rezensionen', None) zeitschriften = getattr(rezensionen, 'zeitschriften', None) if not zeitschriften: log.warning('Folder "zeitschriften" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = zeitschriften id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='publications-view', type='string')
f2abd3d751b93638d0417fbb150a989d7d79cd82 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f2abd3d751b93638d0417fbb150a989d7d79cd82/setuphandlers.py
obj = getattr(portal, id + lang, None)
obj = getattr(portal, (id + lang), None)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
f2abd3d751b93638d0417fbb150a989d7d79cd82 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f2abd3d751b93638d0417fbb150a989d7d79cd82/setuphandlers.py
log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang)
log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id + lang))
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
f2abd3d751b93638d0417fbb150a989d7d79cd82 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f2abd3d751b93638d0417fbb150a989d7d79cd82/setuphandlers.py
self.assertTrue(compare(expected, real), ("Error in Line %i:\nExp:\n%s\nGot:\n%s" % (lineno, '\n'.join(expected_mail.split('<<<\n')[max(0, lineno-2):lineno+3]), '\n'.join(view.mailhost.sentMail.split('<<<\n')[max(0, lineno-2):lineno+3]))).encode('ascii', 'ignore'))
self.assertTrue(compare(expected, real), ("Error in Line %i:\nExp:\n%s\nGot:\n%s" % (lineno, '<<<\n'.join(expected_mail.split('\n')[max(0, lineno-2):lineno+3]), '<<<\n'.join(view.mailhost.sentMail.split('\n')[max(0, lineno-2):lineno+3]))).encode('ascii', 'ignore'))
def send(self, messageText, mto, mfrom, subject, charset): self.sentMail = messageText
b8c08f0b2deedab1576d093d923a2d0216549e8d /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/b8c08f0b2deedab1576d093d923a2d0216549e8d/testEmailNewPublication.py
mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or '[email protected]' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings) msg = "" for result in self.context.queryCatalog(): msg += self.tmpl % {'Title' : result.Title, 'Description' : result.Description, 'created' : result.created.strftime('%d.%m.%Y'), 'last_comment_date' : result.last_comment_date and result.last_comment_date.strftime('%d.%m.%Y')} if not self.errors:
try: mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) raise ValidationError() user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) raise ValidationError() mail_to = user.getProperty('email') if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) raise ValidationError() self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings) if not settings.settings.mail_format: self.errors.append(_('Mailsettings not configured')) raise ValidationError() msg = settings.prefix for topic in self.context.objectValues(): if not IATTopic.providedBy(topic): continue if IDiscussionCollections.providedBy(topic): tmpl = settings.comment_result_template else: tmpl = settings.standard_result_template for result in topic.queryCatalog(): for key in result.__record_schema__.keys(): if hasattr(getattr(result, key), 'strftime'): setattr(result, key, getattr(result, key).strftime(settings.mail_format)) msg += tmpl % result if self.errors: raise ValidationError
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or '[email protected]' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
bc18d5e3ed92357461700e0371f326cc3d0ef52f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bc18d5e3ed92357461700e0371f326cc3d0ef52f/email.py
return super(MailCollection, self).__call__()
except ValidationError: pass finally: messages = IStatusMessage(self.request) if self.errors: for error in self.errors: messages.addStatusMessage(error, type='error') else: messages.addStatusMessage(u"Mail sending will be prepared. Mail will be sent to %s" % mail_to, type="info") return self.request.response.redirect(self.context.absolute_url())
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or '[email protected]' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
bc18d5e3ed92357461700e0371f326cc3d0ef52f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bc18d5e3ed92357461700e0371f326cc3d0ef52f/email.py
self.mag.invokeFactory(type_name="Volume", id=review['volume'])
self.mag.invokeFactory(type_name="Volume", id=review['volume'], title=review['volume'])
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
6c7f2ad411550ebf57280a49e309cc501f575568 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/6c7f2ad411550ebf57280a49e309cc501f575568/sehepunkte.py
volume.invokeFactory(type_name='Issue', id=review['issue'])
volume.invokeFactory(type_name='Issue', id=review['issue'], title=review['issue'])
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
6c7f2ad411550ebf57280a49e309cc501f575568 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/6c7f2ad411550ebf57280a49e309cc501f575568/sehepunkte.py
request.form['pdf'] = FakeFile('../../src/recensio.imports/samples/demo1.pdf') request.form['xls'] = file('../../src/recensio.imports/samples/initial.xls')
request.form['pdf'] = FakeFile( '../../src/recensio.imports/samples/demo1.pdf') request.form['xls'] = FakeFile( '../../src/recensio.imports/samples/initial.xls')
def testFormat(self): portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ['Manager']) setRoles(portal, TEST_USER_NAME, ['Manager']) request = self.layer['request'] reviews = portal["sample-reviews"] reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
92d931724dcad929fac06e2d57bc37751f665de8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/92d931724dcad929fac06e2d57bc37751f665de8/testExcelImport.py
applyProfile(portal, 'recensio.contenttypes:example_content')
def setUpPloneSite(self, portal): wftool = getToolByName(portal, 'portal_workflow') wftool.setDefaultChain('plone_workflow') applyProfile(portal, 'Products.CMFPlone:plone-content') applyProfile(portal, 'recensio.policy:test') applyProfile(portal, 'recensio.contenttypes:example_content')
3191c038ee37108e9bb8748dd0902d7874b08161 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/3191c038ee37108e9bb8748dd0902d7874b08161/layer.py
@guard def addWorkflowScriptsForRegularContent(context): script = """ rwh = context.restrictedTraverse('@@recensio_workflow_helper') rwh.handleTransition(info) """ addWorkflowScripts( context, wf_name = 'simple_publication_workflow', script_name = 'handle_change', script_contents = script, after_transitions_to_hook_in = ['submit', 'publish'] )
def addWorkflowScriptsForComments(context): script = """
fba4d2cfae5c38e41453bf6c14a48c4d1c50fe0f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/fba4d2cfae5c38e41453bf6c14a48c4d1c50fe0f/setuphandlers.py
def customizeWorkflowAndPermissions(context): portal = context.getSite() pwf = portal.portal_workflow spw = pwf.getWorkflowById('simple_publication_workflow') spw.description = ' - Simple workflow that is useful for basic web sites. - Things start out as private, and can either be submitted for review, or published directly. - The creator of a content item can edit the item even after it is published. - Modified for recensio.net: Added deleted state' guard = Guard() guard.roles = ('Manager', 'Editor', 'Owner', ) if 'delete' in spw.transitions: spw.transitions.deleteTransitions(['delete']) if 'restore' in spw.transitions: spw.transitions.deleteTransitions(['restore']) if 'deleted' in spw.states: spw.states.deleteStates(['deleted']) spw.transitions.addTransition('delete') spw.transitions['delete'].guard = guard spw.transitions['delete'].title = 'Delete' spw.transitions['delete'].description = 'Mark the content as deleted and make it invisible for all except managers' spw.transitions['delete'].new_state_id = 'deleted' spw.transitions['delete'].after_script_name = 'handle_change' spw.transitions['delete'].actbox_name = 'Delete' spw.transitions['delete'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=delete' spw.transitions.addTransition('restore') spw.transitions['restore'].guard = guard spw.transitions['restore'].title = 'Restore' spw.transitions['restore'].description = 'Restore the content from the deleted state and make it visible again' spw.transitions['restore'].new_state_id = 'private' spw.transitions['restore'].after_script_name = 'handle_change' spw.transitions['restore'].actbox_name = 'Restore' spw.transitions['restore'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=restore' spw.states.addState('deleted') spw.states['deleted'].title = 'Deleted' spw.states['deleted'].description = 'Marked as deleted and invisible to all but managers' spw.states['deleted'].transitions = ('restore',) for perm in spw.permissions: spw.states['deleted'].setPermission(perm, acquired=0, roles=['Manager', 'Editor', 'Owner']) for state in ['pending', 'private', 'published']: trans = spw.states[state].transitions if not 'delete' in trans: trans = list(trans) trans.append('delete') spw.states[state].transitions = tuple(trans) @guard
def customizeWorkflowAndPermissions(context): portal = context.getSite() pwf = portal.portal_workflow spw = pwf.getWorkflowById('simple_publication_workflow') spw.description = ' - Simple workflow that is useful for basic web sites. - Things start out as private, and can either be submitted for review, or published directly. - The creator of a content item can edit the item even after it is published. - Modified for recensio.net: Added deleted state' guard = Guard() guard.roles = ('Manager', 'Editor', 'Owner', ) # delete existing states and transitions to avoid clashes if 'delete' in spw.transitions: spw.transitions.deleteTransitions(['delete']) if 'restore' in spw.transitions: spw.transitions.deleteTransitions(['restore']) if 'deleted' in spw.states: spw.states.deleteStates(['deleted']) # add Transitions spw.transitions.addTransition('delete') spw.transitions['delete'].guard = guard spw.transitions['delete'].title = 'Delete' spw.transitions['delete'].description = 'Mark the content as deleted and make it invisible for all except managers' spw.transitions['delete'].new_state_id = 'deleted' spw.transitions['delete'].after_script_name = 'handle_change' spw.transitions['delete'].actbox_name = 'Delete' spw.transitions['delete'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=delete' spw.transitions.addTransition('restore') spw.transitions['restore'].guard = guard spw.transitions['restore'].title = 'Restore' spw.transitions['restore'].description = 'Restore the content from the deleted state and make it visible again' spw.transitions['restore'].new_state_id = 'private' spw.transitions['restore'].after_script_name = 'handle_change' spw.transitions['restore'].actbox_name = 'Restore' spw.transitions['restore'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=restore' # add state and register transitions with states spw.states.addState('deleted') spw.states['deleted'].title = 'Deleted' spw.states['deleted'].description = 'Marked as deleted and invisible to all but managers' spw.states['deleted'].transitions = ('restore',) # access only for Manager for perm in spw.permissions: spw.states['deleted'].setPermission(perm, acquired=0, roles=['Manager', 'Editor', 'Owner']) for state in ['pending', 'private', 'published']: trans = spw.states[state].transitions if not 'delete' in trans: trans = list(trans) trans.append('delete') spw.states[state].transitions = tuple(trans)
fba4d2cfae5c38e41453bf6c14a48c4d1c50fe0f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/fba4d2cfae5c38e41453bf6c14a48c4d1c50fe0f/setuphandlers.py
log.debug('Homepage view was set on the front page') mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
log.debug('Homepage view was set on the front page') mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text[fp_id], omit_border=True)
def setupHomepage(context): site = context.getSite() for fp_id in ['front-page', 'front-page-en', 'front-page-fr']: fp = getattr(site, fp_id, None) if not fp: log.error('%s not found' % fp_id) continue id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
21c4bb49b6943853a239c421ea79aff9ee4b7887 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/21c4bb49b6943853a239c421ea79aff9ee4b7887/setuphandlers.py
self.originalUrlGetter = sehepunkte_parser._getHTMLData sehepunkte_parser._getHTMLData = lambda a:a
def setUp(self): self.fake_logger = FakeLogger() importSehepunkte.logger = self.fake_logger self.originalUrlGetter = sehepunkte_parser._getHTMLData sehepunkte_parser._getHTMLData = lambda a:a
49db0250fa267a14a19c55d2b77b3c41a0a49e52 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/49db0250fa267a14a19c55d2b77b3c41a0a49e52/testSehepunkte.py
sehepunkte_parser._getHTMLData = self.originalUrlGetter
pass
def tearDown(self): sehepunkte_parser._getHTMLData = self.originalUrlGetter
49db0250fa267a14a19c55d2b77b3c41a0a49e52 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/49db0250fa267a14a19c55d2b77b3c41a0a49e52/testSehepunkte.py
for dataset in data: dataset.pop('html')
def testImportGood(self): should_be = [] data = [x for x in sehepunkte_parser.parse(file(testdata_filename).read())] for dataset in data: dataset.pop('html') self.assertEquals(testdata_parsed, list(data))
49db0250fa267a14a19c55d2b77b3c41a0a49e52 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/49db0250fa267a14a19c55d2b77b3c41a0a49e52/testSehepunkte.py
def testBadURL(self): sehepunkte_parser._getHTMLData = self.originalUrlGetter data = file(testdata_filename).read() data = data.replace('http://www.sehepunkte.de/export/rezension_17542.html', 'http://doesnotexist.syslab.de') self.assertRaises(IOError, list, sehepunkte_parser.parse(data))
def testImportBad(self): data1 = file(testdata_filename).read() data2 = data1.replace('<review id="17542">', '<somethingelse>') data2 = data2.replace('</review>', '</somethingelse>', 1) data1 = sehepunkte_parser.parse(data1) data2 = sehepunkte_parser.parse(data2) self.assertEquals(len(list(data1)), len(list(data2)) + 1)
49db0250fa267a14a19c55d2b77b3c41a0a49e52 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/49db0250fa267a14a19c55d2b77b3c41a0a49e52/testSehepunkte.py
settings = registry.forInterface(IRecensioSettings)
try: settings = registry.forInterface(IRecensioSettings) except KeyError: settings = dict()
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
f46453582494b135951a948be11b1eb2e71d9fd6 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f46453582494b135951a948be11b1eb2e71d9fd6/workflow.py
mail_to = settings.review_submitted_email or mail_from
mail_to = getattr(settings, 'review_submitted_email', None) or mail_from
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
f46453582494b135951a948be11b1eb2e71d9fd6 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f46453582494b135951a948be11b1eb2e71d9fd6/workflow.py
Die folgende Mail wurde generiert zur Benachrichtigung von Fürchtegott Hubermüller. Bitte prüfen Sie sie und leiten sie ggf. weiter an
Die folgende Mail wurde generiert zur Benachrichtigung von Tadeusz Kot\u0142owski. Bitte prüfen Sie sie und leiten sie ggf. weiter an
def testFormat(self): expected_mail = u'''Liebe Redaktion,
80d5b49f62e4f1683cb7342df0ec9c02f12799b5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/80d5b49f62e4f1683cb7342df0ec9c02f12799b5/testEmailNewPublication.py
Dear Mr Fürchtegott Hubermüller,
Dear Mr Tadeusz Kot\u0142owski,
def testFormat(self): expected_mail = u'''Liebe Redaktion,
80d5b49f62e4f1683cb7342df0ec9c02f12799b5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/80d5b49f62e4f1683cb7342df0ec9c02f12799b5/testEmailNewPublication.py
self.assertEquals(2, obj.pageStart) self.assertEquals(5, obj.pageEnd)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
self.assertEquals('653645', obj.issn)
self.assertEquals('653645', obj.isbn)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
self.assertEquals(2, obj.pageStart) self.assertEquals(4, obj.pageEnd)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
self.assertEquals('265742', obj.issn)
self.assertEquals('265742', obj.isbn)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
self.assertEquals('4', obj.issn) self.assertEquals('2000', obj.yearOfPublication)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
self.assertEquals(({u'lastname': u'Autor Nachname', u'firstname': u'Autor Vorname'},), obj.authors) self.assertEquals(3, obj.pageStart) self.assertEquals(4, obj.pageEnd)
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
210449271edd39a39aa8b4fde2b3d84539c4b5a5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/210449271edd39a39aa8b4fde2b3d84539c4b5a5/testExcelImport.py
messages.addStatusMessage(self.ts.translate(_('mail_sending_prepared'), context=self.context) % mail_to, type="info")
messages.addStatusMessage(self.ts.translate(_('mail_sending_prepared', default="uMailversand wird vorbereitet. Mail wird versandt an %s"), context=self.context) % mail_to, type="info")
def __call__(self): self.errors = [] messages = IStatusMessage(self.request) try: mail_from, mail_to = self.getMailAddresses() registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings) if not settings.mail_format: self.errors.append(_('Mailsettings not configured')) raise ValidationError()
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
subject = self.ts.translate(_('mail_new_comment_subject'), context=self.context) mail_to = self.findRecipient() msg_template = self.ts.translate(_('mail_new_comment_body'), context=self.context)
mail_to, pref_lang = self.findRecipient() subject = self.ts.translate(_('mail_new_comment_subject'), target_language=pref_lang) msg_template = self.ts.translate(_('mail_new_comment_body'), target_language=pref_lang)
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address)
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
messages.addStatusMessage(self.ts.translate(_('mail_no_recipients'), context=self.context), type="warning")
messages.addStatusMessage(self.ts.translate(_('mail_no_recipients'), target_language=pref_lang), type="warning")
def sendMail(self, msg, mail_from, mail_to, subject): if mail_to: self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8') else: messages = IStatusMessage(self.request) messages.addStatusMessage(self.ts.translate(_('mail_no_recipients'), context=self.context), type="warning")
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
return owner.getProperty('email')
return owner.getProperty('email'), owner.getProperty('preferred_language', 'de')
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email')
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
args['mail_to'] = args['mail_from'] msg_template = self.ts.translate(_('mail_new_publication_intro'), context=self.context) + self.ts.translate(_('mail_new_publication_body'), context=self.context)
pref_lang = 'de' if author.has_key('email') and author['email']: args['mail_to'] = author['email'] pref_lang = get_preferred_language(author['email'], pref_lang) msg_template = self.ts.translate(_('mail_new_publication_body'), target_language=pref_lang) else: args['mail_to'] = args['mail_from'] pref_lang = get_preferred_language(args['mail_from'], pref_lang) msg_template = self.ts.translate(_('mail_new_publication_intro'), target_language=pref_lang) + self.ts.translate(_('mail_new_publication_body'), target_language=pref_lang)
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
subject = self.ts.translate(_('mail_new_publication_subject'), context=self.context) % args['title']
subject = self.ts.translate(_('mail_new_publication_subject', default=u"Es wurde eine Rezension von %s veröffentlicht"), target_language=pref_lang) % args['title']
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
mail_to = self.findRecipient(result)
mail_to, pref_lang = self.findRecipient(result)
def sendMail(self, result): msg = self.formatMessage(result) mail_to = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context)
subject = self.ts.translate(_('mail_uncommented_subject'), target_language=pref_lang)
def sendMail(self, result): msg = self.formatMessage(result) mail_to = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
msg_template = self.ts.translate(_('mail_uncommented_body'), context=self.context)
msg_template = self.ts.translate(_('mail_uncommented_body'), target_language=pref_lang)
def formatMessage(self, result): title = result.Title owner_name = result.Creator url = result.getURL() date = result.created.strftime('%d.%m.%Y') msg_template = self.ts.translate(_('mail_uncommented_body'), context=self.context)
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
return owner.getProperty('email') or self.findSender()
return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'de')
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender()
bf24e656edadbf8ae1822a6d6171ec4569a6ebed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/bf24e656edadbf8ae1822a6d6171ec4569a6ebed/email.py
log.info('I am sending the following msg:\n%s' % msg)
log.info(u'I am sending the following msg:\n%s' % msg)
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
1c43e04d66670d365375430fb912585f18838a11 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/1c43e04d66670d365375430fb912585f18838a11/workflow.py
subject=subject, immediate=True)
subject=subject, charset='utf-8', immediate=True)
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
1c43e04d66670d365375430fb912585f18838a11 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/1c43e04d66670d365375430fb912585f18838a11/workflow.py
mailhost.send(msg, mail_from, mail_to, title, immediate=True)
mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, immediate=True)
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
072d4eb61914418de0b8e661a691e4b38a5dd250 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/072d4eb61914418de0b8e661a691e4b38a5dd250/workflow.py
return owner.getProperty('email'), owner.getProperty('preferred_language', 'de')
return owner.getProperty('email'), owner.getProperty('preferred_language', 'en')
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email'), owner.getProperty('preferred_language', 'de')
f71293d440addf09542afa70fa6080b95178dd12 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f71293d440addf09542afa70fa6080b95178dd12/email.py
def get_preferred_language(email, default='de'):
def get_preferred_language(email, default='en'):
def get_preferred_language(email, default='de'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
f71293d440addf09542afa70fa6080b95178dd12 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f71293d440addf09542afa70fa6080b95178dd12/email.py
pref_lang = 'de'
pref_lang = 'en'
def get_preferred_language(email, default='de'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
f71293d440addf09542afa70fa6080b95178dd12 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f71293d440addf09542afa70fa6080b95178dd12/email.py
return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'de')
return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'en')
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'de')
f71293d440addf09542afa70fa6080b95178dd12 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/f71293d440addf09542afa70fa6080b95178dd12/email.py
for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None)
for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id) continue doPublish(obj, pwt)
9c226745d8ad510f3faabbc9ec0c575f47bc3f2d /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/9c226745d8ad510f3faabbc9ec0c575f47bc3f2d/setuphandlers.py
log.warning('Object %s not found. Please run import step "Recensio initial content"' % id)
log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id) continue doPublish(obj, pwt)
9c226745d8ad510f3faabbc9ec0c575f47bc3f2d /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/9c226745d8ad510f3faabbc9ec0c575f47bc3f2d/setuphandlers.py
addIndex('ort', 'FieldIndex', extra={'indexed_attrs': ['yearOfPublication']})
addIndex('ort', 'FieldIndex', extra={'indexed_attrs': ['placeOfPublication']})
def addIndex(name, type, **kw): if not name in cat.indexes(): log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw) elif not filter(lambda x: x.getId() == name, cat.getIndexObjects())[0].meta_type == type: cat.delIndex(name) log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw)
b9b7202a1c1e1f4492319deaad6b8ccb4fd0c384 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10562/b9b7202a1c1e1f4492319deaad6b8ccb4fd0c384/setuphandlers.py
htmlpage = urllib.urlopen(url,data=postdata)
htmlpage = urllib.urlopen(self.url,data=postdata)
def __get_html(self):
acc18cfe5d2a0cedf22de297999e78022841731b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10886/acc18cfe5d2a0cedf22de297999e78022841731b/htmlparser.py
field = str(message.get_payload())
field = self.__get_body(message)
def get_messages(self):
a3b48f3ff1e058545c86b5f6370bb7be548abfcd /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/10886/a3b48f3ff1e058545c86b5f6370bb7be548abfcd/analyzer.py
descriptor = lifecycleevent.Attributes(IPortalObject, 'title') event = ActionSucceededEvent(self.folder, descriptor, None, None)
event = ActionSucceededEvent(self.folder, None, None, None)
def test_update_of_review_portlet(self): self.loginAsPortalOwner() portal = self.portal portal.portal_workflow.doActionFor(self.portal['front-page'], 'retract') portal.portal_workflow.doActionFor(self.portal['front-page'], 'submit') self.create_portlet(u'review', ReviewAssignment()) descriptor = lifecycleevent.Attributes(IPortalObject, 'title') event = ActionSucceededEvent(self.folder, descriptor, None, None) event.old_state, event.new_state = 'private', 'pending' workflowTriggersReviewPortletReload(self.portal, self.view, event) result = self.view.render() command = result[0] self.failUnless(command.has_key('selector')) self.failUnless(command['selector'].startswith('portletwrapper')) self.failUnless(command.has_key('name')) self.assertEqual(command['name'], 'replaceInnerHTML') self.failUnless(command.has_key('params')) params = result[0]['params'] self.failUnless(params.has_key('html')) html = params['html'] self.failUnless('portletWorkflowReview' in html) self.failUnless(command.has_key('selectorType')) self.assertEqual(command['selectorType'], 'htmlid')
805ef05de75a0cec7330cebd9ec40203d35470f7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/12181/805ef05de75a0cec7330cebd9ec40203d35470f7/test_part_reloading.py
def __call__(self, view): attr = self.attr decorator = self.decorator isclass = inspect.isclass(view) ronly = self.requestonly(view) if isclass and ronly: view = preserve_view_attrs(view, self.map_requestonly_class(view)) elif isclass: view = preserve_view_attrs(view, self.map_class(view)) elif ronly: view = preserve_view_attrs(view, self.map_requestonly_func(view)) elif attr: view = preserve_view_attrs(view, self.map_attr(view)) elif self.renderer is not None: view = preserve_view_attrs(view, self.map_rendered(view)) if decorator is not None: view = preserve_view_attrs(view, decorator(view)) return view def map_requestonly_class(self, view): attr = self.attr def _class_requestonly_view(context, request): inst = view(request) if attr is None: response = inst() else: response = getattr(inst, attr)() if self.renderer is not None and not is_response(response): response = self.renderer.render_view(request, response, view, context) return response return _class_requestonly_view def map_class(self, view): attr = self.attr def _class_view(context, request): inst = view(context, request) if attr is None: response = inst() else: response = getattr(inst, attr)() if self.renderer is not None and not is_response(response): response = self.renderer.render_view(request, response, view, context) return response return _class_view def map_requestonly_func(self, view): attr = self.attr def _requestonly_view(context, request): if attr is None: response = view(request) else: response = getattr(view, attr)(request) if self.renderer is not None and not is_response(response): response = self.renderer.render_view(request, response, view, context) return response return _requestonly_view def map_attr(self, view): attr = self.attr def _attr_view(context, request): response = getattr(view, attr)(context, request) if self.renderer is not None and not is_response(response): response = self.renderer.render_view(request, response, view, context) return response return _attr_view def map_rendered(self, view): def _rendered_view(context, request): response = view(context, request) if self.renderer is not None and not is_response(response): response = self.renderer.render_view(request, response, view, context) return response return _rendered_view
def requestonly(self, view): attr = self.attr if attr is None: attr = '__call__' if inspect.isfunction(view): fn = view elif inspect.isclass(view): try: fn = view.__init__ except AttributeError: return False else: try: fn = getattr(view, attr) except AttributeError: return False
ae6513b9e93d876902936c257aef6a506f850aa3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/ae6513b9e93d876902936c257aef6a506f850aa3/config.py
request.route_url(mymodel)
request.model_url(mymodel)
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
cd5e1437ebe1683d5fc71858fa4057a4febcebeb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/cd5e1437ebe1683d5fc71858fa4057a4febcebeb/request.py
route_url(model, request)
model_url(model, request)
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
cd5e1437ebe1683d5fc71858fa4057a4febcebeb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/cd5e1437ebe1683d5fc71858fa4057a4febcebeb/request.py
newt = NS.sub('xmlns="http://pyramid.pylonshq.com"', newt)
newt = NS.sub('xmlns="http://pylonshq.com/pyramid"', newt)
def fix_zcml(path): for root, dirs, files in os.walk(path): for file in files: if file.endswith('.zcml'): absfile = os.path.join(root, file) text = open(absfile, 'rb').read() newt =INCLUDES.sub('include package="pyramid.includes"', text) newt = NS.sub('xmlns="http://pyramid.pylonshq.com"', newt) if text != newt: newf = open(absfile, 'wb') newf.write(newt) newf.flush() newf.close() for dir in dirs: if dir.startswith('.'): dirs.remove(dir)
e11fd45a5dbde00d4699522bf1b629850dc4ae55 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/e11fd45a5dbde00d4699522bf1b629850dc4ae55/fix_bfg_imports.py
'relative name %r irresolveable without package' % value)
'relative name %r irresolveable without package' % (value,))
def _pkg_resources_style(self, value): """ package.module:attr style """ import pkg_resources if value.startswith('.') or value.startswith(':'): if not self.package: raise ConfigurationError( 'relative name %r irresolveable without package' % value) if value in ['.', ':']: value = self.package.__name__ else: value = self.package.__name__ + value return pkg_resources.EntryPoint.parse( 'x=%s' % value).load(False)
2a591a5f56222d7ee407a22acbe2d9cd0102373f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/2a591a5f56222d7ee407a22acbe2d9cd0102373f/configuration.py
'relative name %r irresolveable without package' % value)
'relative name %r irresolveable without package' % (value,))
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % value) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % value ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
2a591a5f56222d7ee407a22acbe2d9cd0102373f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/2a591a5f56222d7ee407a22acbe2d9cd0102373f/configuration.py
'package' % value
'package' % (value,)
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % value) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % value ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
2a591a5f56222d7ee407a22acbe2d9cd0102373f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/2a591a5f56222d7ee407a22acbe2d9cd0102373f/configuration.py
The ``name`` argument is a string representing :term:`view name` of the view which is registered. It may alternately be a *url prefix*. The ``path`` argument is the path on disk where the static files reside. This can be an absolute path, a package-relative path, or a :term:`asset specification`.
The ``name`` argument is a string representing an application-relative local URL prefix. It may alternately be a full URL. The ``path`` argument is the path on disk where the static files reside. This can be an absolute path, a package-relative path, or a :term:`asset specification`.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
``Expires`` and ``Cache-Control`` headers for static assets served. Note that this argument has no effect when the ``name`` is a *url prefix*. By default, this argument is ``None``, meaning that no particular Expires or Cache-Control headers are set in the response.
``Expires`` and ``Cache-Control`` headers for static assets served. Note that this argument has no effect when the ``name`` is a *url prefix*. By default, this argument is ``None``, meaning that no particular Expires or Cache-Control headers are set in the response.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
The ``add_static_view`` function is typically used in conjunction with the :func:`pyramid.url.static_url` function. ``add_static_view`` adds a view which renders a static asset when some URL is visited; :func:`pyramid.url.static_url` generates a URL to that asset. The ``name`` argument to ``add_static_view`` is usually a :term:`view name`. When this is the case, the :func:`pyramid.url.static_url` API will generate a URL which points to a Pyramid view, which will serve up a set of assets that live in the package itself. For example:
The ``add_static_view`` function is typically used in conjunction with the :func:`pyramid.url.static_url` function. ``add_static_view`` adds a view which renders a static asset when some URL is visited; :func:`pyramid.url.static_url` generates a URL to that asset. The ``name`` argument to ``add_static_view`` is usually a :term:`view name`. When this is the case, the :func:`pyramid.url.static_url` API will generate a URL which points to a Pyramid view, which will serve up a set of assets that live in the package itself. For example:
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
Code that registers such a view can generate URLs to the view via :func:`pyramid.url.static_url`:
Code that registers such a view can generate URLs to the view via :func:`pyramid.url.static_url`:
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
When ``add_static_view`` is called with a ``name`` argument that represents a simple view name, as it is above, subsequent calls to :func:`pyramid.url.static_url` with paths that start with the ``path`` argument passed to ``add_static_view`` will generate a URL something like ``http://<Pyramid app URL>/images/logo.png``, which will cause the ``logo.png`` file in the ``images`` subdirectory of the ``mypackage`` package to be served. ``add_static_view`` can alternately be used with a ``name`` argument which is a *URL*, causing static assets to be served from an external webserver. This happens when the ``name`` argument is a URL (detected as any string with a slash in it). In this mode, the ``name`` is used as the URL prefix when generating a URL using :func:`pyramid.url.static_url`. For example, if ``add_static_view`` is called like so:
When ``add_static_view`` is called with a ``name`` argument that represents a URL prefix, as it is above, subsequent calls to :func:`pyramid.url.static_url` with paths that start with the ``path`` argument passed to ``add_static_view`` will generate a URL something like ``http://<Pyramid app URL>/images/logo.png``, which will cause the ``logo.png`` file in the ``images`` subdirectory of the ``mypackage`` package to be served. ``add_static_view`` can alternately be used with a ``name`` argument which is a *URL*, causing static assets to be served from an external webserver. This happens when the ``name`` argument is a fully qualified URL (e.g. starts with ``http://`` or similar). In this mode, the ``name`` is used as the prefix of the full URL when generating a URL using :func:`pyramid.url.static_url`. For example, if ``add_static_view`` is called like so:
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
Subsequently, the URLs generated by :func:`pyramid.url.static_url` for that static view will be prefixed with ``http://example.com/images``:
Subsequently, the URLs generated by :func:`pyramid.url.static_url` for that static view will be prefixed with ``http://example.com/images``:
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
When ``add_static_view`` is called with a ``name`` argument that is the URL prefix ``http://example.com/images``, subsequent calls to :func:`pyramid.url.static_url` with paths that start with the ``path`` argument passed to ``add_static_view`` will generate a URL something like ``http://example.com/logo.png``. The external webserver listening on ``example.com`` must be itself configured to
When ``add_static_view`` is called with a ``name`` argument that is the URL ``http://example.com/images``, subsequent calls to :func:`pyramid.url.static_url` with paths that start with the ``path`` argument passed to ``add_static_view`` will generate a URL something like ``http://example.com/logo.png``. The external webserver listening on ``example.com`` must be itself configured to
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
781f9e02e0433a77e78f07f28e5b7d2064e73af4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/781f9e02e0433a77e78f07f28e5b7d2064e73af4/config.py
fixer_names = get_fixers_from_package('repoze.bfg.fixers')
fixer_names = get_fixers_from_package('pyramid.fixers')
def main(argv=None): if argv is None: argv = sys.argv path = argv[1] fixer_names = get_fixers_from_package('repoze.bfg.fixers') tool = RefactoringTool(fixer_names) tool.refactor([path], write=True)
6f19024d79f091f1310ed547d7a1eb93b457e07e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/6f19024d79f091f1310ed547d7a1eb93b457e07e/fix_bfg_imports.py
if splitted[-1] in ('__init__.py', '__init__.pyc', '__init__.pyo'):
if splitted[-1] in init_names:
def package_name(pkg_or_module): """ If this function is passed a module, return the dotted Python package name of the package in which the module lives. If this function is passed a package, return the dotted Python package name of the package itself.""" if pkg_or_module is None: return '__main__' pkg_filename = pkg_or_module.__file__ pkg_name = pkg_or_module.__name__ splitted = os.path.split(pkg_filename) if splitted[-1] in ('__init__.py', '__init__.pyc', '__init__.pyo'): # it's a package return pkg_name return pkg_name.rsplit('.', 1)[0]
3c2ed7f1aac4b88fba1c6ee4721ab11c0b3251ed /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/3c2ed7f1aac4b88fba1c6ee4721ab11c0b3251ed/path.py
renderer=None, view_renderer=None,
renderer=None, view_renderer=None,
def add_route(self, name, path, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, _info=u''): """ Add a :term:`route configuration` to the current configuration state, as well as possibly a :term:`view configuration` to be used to specify a :term:`view callable` that will be invoked when this route matches. The arguments to this method are divided into *predicate*, *non-predicate*, and *view-related* types. :term:`Route predicate` arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational.
78a659d76e5bbb7544212174f010c1f50f8bcbe6 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/78a659d76e5bbb7544212174f010c1f50f8bcbe6/configuration.py
:class:`pyramid.view.view_config``: ``context``, ``permission``,
:class:`pyramid.view.view_config`: ``context``, ``permission``,
def my_view(context, request): return 'OK'
06c20074f0e3e624ba69ed6b6e4d0b17649ce9e6 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/06c20074f0e3e624ba69ed6b6e4d0b17649ce9e6/view.py
'``pyramid.threadlocals.get_current_registry().settings`` instead or use '
'``pyramid.threadlocal.get_current_registry().settings`` instead or use '
def get_settings(): """ Return a 'settings' object for the current application. A 'settings' object is a dictionary-like object that contains key/value pairs based on the dictionary passed as the ``settings`` argument to the :class:`pyramid.configuration.Configurator` constructor or the :func:`pyramid.router.make_app` API. .. note:: For backwards compatibility, dictionary keys can also be looked up as attributes of the settings object. .. note:: the :class:`pyramid.configuration.Configurator.get_settings` method performs the same duty. .. warning:: This method is deprecated as of Pyramid 1.0. Use ``pyramid.threadlocals.get_current_registry().settings`` instead or use ' the ``settings`` attribute of the registry available from the request (``request.registry.settings``). """ reg = get_current_registry() return reg.settings
bc414e504a11e91da9e6aa3fdd7e3aea724104f9 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/bc414e504a11e91da9e6aa3fdd7e3aea724104f9/settings.py
.. note:: Using the :meth:``renderer_globals_factory``
.. note:: Using the :meth:`renderer_globals_factory`
def set_renderer_globals_factory(self, factory): """ The object passed as ``factory`` will be used by the :mod:`repoze.bfg` rendering machinery as a renderers global factory (see :ref:`adding_renderer_globals`). The factory must return a dictionary of items that will be merged intto the *system* dictionary passed in to every renderer used by the application.
2b80b6c978d9d149f41cda541b6c23a68bd2bf0a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/2b80b6c978d9d149f41cda541b6c23a68bd2bf0a/configuration.py
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
815471bf42ab88c1524755735fbb84126bb65563 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/815471bf42ab88c1524755735fbb84126bb65563/threadlocal.py
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
815471bf42ab88c1524755735fbb84126bb65563 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/815471bf42ab88c1524755735fbb84126bb65563/threadlocal.py
for_ = GlobalObject(title=u'handler', required=True)
handler = GlobalObject(title=u'handler', required=True)
def route(_context, name, pattern=None, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, view_attr=None, renderer=None, view_renderer=None, view_context=None, traverse=None, use_global_views=False, path=None): """ Handle ``route`` ZCML directives """ # the strange ordering of the request kw args above is for b/w # compatibility purposes. # these are route predicates; if they do not match, the next route # in the routelist will be tried if view_context is None: view_context = view_for or for_ view_permission = view_permission or permission view_renderer = view_renderer or renderer if pattern is None: pattern = path if pattern is None: raise ConfigurationError('route directive must include a "pattern"') config = Configurator.with_context(_context) config.add_route( name, pattern, factory=factory, header=header, xhr=xhr, accept=accept, path_info=path_info, request_method=request_method, request_param=request_param, custom_predicates=custom_predicates, view=view, view_context=view_context, view_permission=view_permission, view_renderer=view_renderer, view_attr=view_attr, use_global_views=use_global_views, traverse=traverse, )
566bcdc90ae2be6f9b304e3eee3440bac1a0da05 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/566bcdc90ae2be6f9b304e3eee3440bac1a0da05/zcml.py
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
820bd95aa720a5769f3a86a755a0eb22d8725489 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/820bd95aa720a5769f3a86a755a0eb22d8725489/url.py
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
820bd95aa720a5769f3a86a755a0eb22d8725489 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/820bd95aa720a5769f3a86a755a0eb22d8725489/url.py
'traverse=('a','b')) => http://e.com/1/2/a/b
traverse=('a','b')) => http://e.com/1/2/a/b
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
820bd95aa720a5769f3a86a755a0eb22d8725489 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/820bd95aa720a5769f3a86a755a0eb22d8725489/url.py
'traverse=('/a/b')) => http://e.com/1/2/a/b
traverse='/a/b') => http://e.com/1/2/a/b
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
820bd95aa720a5769f3a86a755a0eb22d8725489 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/14321/820bd95aa720a5769f3a86a755a0eb22d8725489/url.py