def __init__(self): """Index by email of all the requests""" self._id="ConfManagers" self._idx = indexes.IndexesHolder().getById("pendingConfManagers") # All the pending managers self._tasksIdx=indexes.IndexesHolder().getById("pendingConfManagersTasks") # Tasks which send reminder emails periodically asking # for the creation of one indico account self._reminder=PendingConfManagerReminder
def __init__(self): """Index by email of all the request to add Authors or Speakers""" self._id = "Submitters" self._idx = indexes.IndexesHolder().getById( "pendingSubmitters") # All the ContributionParticipants self._tasksIdx = indexes.IndexesHolder().getById( "pendingSubmittersTasks" ) # Tasks which send reminder emails periodically asking for the creation of one indico account self._reminder = PendingSubmitterReminder
def __init__(self): """Index by email of all the request to add Chairpersons or Speakers""" self._id = "ConfSubmitters" self._idx = indexes.IndexesHolder().getById( "pendingConfSubmitters" ) # All the Conference Chairpersons/Speakers self._tasksIdx = indexes.IndexesHolder().getById( "pendingConfSubmittersTasks" ) # Tasks which send reminder emails periodically asking for the creation of one indico account self._reminder = PendingConfSubmitterReminder
def _getAnswer(self): import MaKaC.common.indexes as indexes nameIdx = indexes.IndexesHolder().getIndex('categoryName') try: query = ' AND '.join( map( lambda y: "*%s*" % y, filter(lambda x: len(x) > 0, self._searchString.split(' ')))) foundEntries = nameIdx.search(query) except parsetree.ParseError: foundEntries = [] number = len(foundEntries) # get only the first 10 results foundEntries = foundEntries[:7] entryNames = [] for (categId, value) in foundEntries: categ = CategoryManager().getById(categId) entryNames.append({ 'title': categ.getTitle(), 'path': self._getPath(categ), 'url': str(urlHandlers.UHCategoryDisplay.getURL(categ)) }) return {"list": entryNames, "number": number}
def _getAnswer(self): import MaKaC.common.indexes as indexes nameIdx = indexes.IndexesHolder().getIndex('conferenceTitle') query = ' '.join(map(lambda y: "*%s*" % y, self._searchString.split())) foundEntries = nameIdx.search(query) number = len(foundEntries) # get only the first 10 results foundEntries = foundEntries[:7] entryTitles = [] for (confId, value) in foundEntries: conference = CategoryManager().getById(confId) entryTitles.append({ 'title': conference.getTitle(), 'url': str(urlHandlers.UHConferenceDisplay.getURL(conference)) }) return {"list": entryTitles, "number": number}
def _initialiseDays(self): """ """ self._days = OOBTree() res = sets.Set() self._categIdx = {} self._icons = {} im = indexes.IndexesHolder() calIdx = im.getIndex("calendar") catIdx = im.getIndex("category") c1 = calIdx.getObjectsIn(self.getStartDate(), self.getEndDate()) icons = [] for categ in self.getCategoryList(): confIds = sets.Set(catIdx.getItems(categ.getId())) confIds.intersection_update(c1) for confId in confIds: if not self._categIdx.has_key(confId): self._categIdx[confId] = [] self._categIdx[confId].append(categ) res.union_update(confIds) icons = self.setIcons(categ) for icon in icons: l = list(sets.Set(catIdx.getItems(icon)) & c1) if len(l) > 0: self._icons[icon] = l ch = conference.ConferenceHolder() for confId in res: self._mapConferenceToDays(ch.getById(confId), self._categIdx[confId])
def main(): DBMgr.getInstance().startRequest() im = indexes.IndexesHolder() im.removeById('calendar') DBMgr.getInstance().commit() ch = CategoryManager() list = ch.getList() totnum = len(list) curnum = 0 curper = 0 for cat in list: committed = False DBMgr.getInstance().sync() calindex = im.getIndex('calendar') while not committed: try: del cat._calIdx except: pass for conf in cat.getConferenceList(): calindex.indexConf(conf) try: DBMgr.getInstance().commit() committed = True except: DBMgr.getInstance().abort() print "retry %s" % cat.getId() curnum += 1 per = int(float(curnum) / float(totnum) * 100) if per != curper: curper = per if per in [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]: print "done %s%%" % per DBMgr.getInstance().endRequest()
def main(): """ This script deletes existing category indexes and recreates them. """ dbi = DBMgr.getInstance() dbi.startRequest() im = indexes.IndexesHolder() im.removeById('categoryDate') catIdx = im.getIndex('categoryDate') cm = CategoryManager() num_categs = len(cm._getIdx()) cur_num = cur_percent = 0 for cat in cm._getIdx().itervalues(): for conf in cat.conferences.itervalues(): catIdx.indexConf(conf) dbi.commit() cur_num += 1 percent = int(float(cur_num) / num_categs * 100) if percent != cur_percent: cur_percent = percent print "{0}%".format(percent) dbi.endRequest()
def main(): """This script deletes existing category indexes and recreates them.""" db.DBMgr.getInstance().startRequest() im = indexes.IndexesHolder() im.removeById('categoryDate') catIdx = im.getIndex('categoryDate') ch = CategoryManager() totnum = len(ch.getList()) curnum = 0 curper = 0 for cat in ch.getList(): while 1: try: for conf in cat.getConferenceList(): catIdx.indexConf(conf) transaction.commit() break except: db.DBMgr.getInstance().sync() curnum += 1 per = int(float(curnum)/float(totnum)*100) if per != curper: curper = per print "%s%%" % per db.DBMgr.getInstance().endRequest()
def index(req, **params): """This script displays the list of meetings taking place in a given category at a given date""" global ids try: fid = params['fid'] date = params['date'] except: return usage() #create list of ids ids = re.split(' ',fid) #create date object db.DBMgr.getInstance().startRequest() tz = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone() [year, month, day] = re.split('-',date) startdate = timezone(tz).localize(datetime.datetime(int(year),int(month),int(day))) enddate = startdate.replace(hour=23,minute=59) #create result set res = sets.Set() #instanciate indexes im = indexes.IndexesHolder() calIdx = im.getIndex('categoryDate') for cid in ids: confIds = calIdx.getObjectsInDays(cid, startdate, enddate) res.update(confIds) res = list(res) res.sort(sortByStartDate) return displayList(res,tz)
def _initialiseDays(self): """ """ self._days = OOBTree() res = set() self._categIdx = {} self._icons = {} catDayIdx = indexes.IndexesHolder().getIndex("categoryDate") for categ in self.getCategoryList(): confs = catDayIdx.getObjectsInDays(categ.getId(), self.getStartDate(), self.getEndDate()) for conf in confs: confId = conf.getId() if not self._categIdx.has_key(confId): self._categIdx[confId] = [] self._categIdx[confId].append(categ) res.update(confs) for conf in res: #getting icon from the nearest owner category owner = conf.getOwner() while owner != None and owner.getId() != "0": if owner.getIcon(): if self._icons.has_key(owner.getId()): self._icons[owner.getId()].append(conf.getId()) else: self._icons[owner.getId()] = [conf.getId()] break owner = owner.getOwner() #mapping conf to days self._mapConferenceToDays(conf, self._categIdx[conf.getId()])
def setUp(self): a = Avatar() a.setId("creator") self._conf = Conference(a) self._conf.setId('a') category = Category() category.setId('1') self._conf.addOwner(category) catDateIdx = indexes.IndexesHolder().getIndex('categoryDate') catDateIdx.indexConf(self._conf) self._conf.setTimezone('UTC')
def getConfList(startdate, enddate, ids): #create result set res = sets.Set() #instanciate indexes im = indexes.IndexesHolder() catIdx = im.getIndex('category') calIdx = im.getIndex('calendar') c1 = calIdx.getObjectsIn(startdate, enddate) for id in ids: confIds = sets.Set(catIdx.getItems(id)) confIds.intersection_update(c1) res.union_update(confIds) res = list(res) res.sort(sortByStartDate) return res
def getBody(self): res = sets.Set() im = indexes.IndexesHolder() catIdx = im.getIndex('category') calIdx = im.getIndex('calendar') if self._date == None: c1 = calIdx.getObjectsEndingAfter(nowutc().astimezone( timezone(self._tz))) else: date = self._date c1 = calIdx.getObjectsInDay(date) confIds = sets.Set(catIdx.getItems(self._categ.getId())) confIds.intersection_update(c1) res.union_update(confIds) res = list(res) res.sort(sortByStartDate) rss = xmlGen.XMLGen() rss.openTag('rss version="2.0"') rss.openTag("channel") rss.writeTag( "title", "Indico RSS Feed for category %s" % self._categ.getTitle()) rss.writeTag("link", Config.getInstance().getBaseURL()) rss.writeTag( "description", "Forthcoming meetings in category %s" % self._categ.getTitle()) rss.writeTag("language", "en") rss.writeTag( "pubDate", nowutc().astimezone(timezone( self._tz)).strftime("%a, %d %b %Y %H:%M:%S %Z")) rss.writeTag("category", "") rss.writeTag("generator", "CDS Indico %s" % Config.getInstance().getVersion()) rss.writeTag( "webMaster", info.HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail()) rss.writeTag("ttl", "1440") for confId in res: ch = ConferenceHolder() conf = ch.getById(confId) rss = ConferenceToRSS(conf, tz=self._tz).getCore(rss) rss.closeTag("channel") rss.closeTag("rss") return rss.getXml()
def _generateList(self, date=None): if not date: date = timezoneUtils.nowutc() categDateIdx = indexes.IndexesHolder().getById('categoryDate') objDict = {} for obj in self._objects: if isinstance(obj.getObject(), conference.Conference): self.processEvent(date, obj.getObject(), obj, objDict) elif isinstance(obj.getObject(), conference.Category): events = categDateIdx.getObjectsIn(obj.getObject().getId(), date, date+obj.getAdvertisingDelta()) ## HACK: Remove when this version goes into production (See above) for eventId in events: try: conf = conference.ConferenceHolder().getById(eventId) self.processEvent(date, conf, obj, objDict) except: pass resultList = [] keys = objDict.keys() keys.sort(reverse=True) for weight in keys: sortedEvents = objDict[weight] sortedEvents.sort(key=operator.attrgetter('startDate')) for elem in sortedEvents: resultList.append(elem) if len(resultList) == self._maxEvents: break # sort again, so that the final result is an ordered list # that is suitable for display resultList.sort(key=operator.attrgetter('startDate')) Logger.get('upcoming_events').info("Regenerated upcoming event cache") return resultList
def main(): db.DBMgr.getInstance().startRequest() im = indexes.IndexesHolder() emailindex = im.getIndex('email') nameindex = im.getIndex('name') surnameindex = im.getIndex('surname') organisationindex = im.getIndex('organisation') calendarindex = im.getIndex('calendar') categindex = im.getIndex('category') print """ calendar: %s category: %s email: %s name: %s surname: %s organisation: %s""" % ( len(repr(calendarindex.dump())), len(repr(categindex.dump())), len(repr(emailindex.dump())), len(repr(nameindex.dump())), len(repr(surnameindex.dump())), len(repr(organisationindex.dump()))) db.DBMgr.getInstance().endRequest(False)
def main(): """This script deletes existing user indexes (email,name,surname,organisation) and recreates them.""" db.DBMgr.getInstance().startRequest() try: del db.DBMgr.getInstance().getDBConnection().root()['indexes']['email'] except: pass try: del db.DBMgr.getInstance().getDBConnection().root()['indexes']['name'] except: pass try: del db.DBMgr.getInstance().getDBConnection().root( )['indexes']['surName'] except: pass try: del db.DBMgr.getInstance().getDBConnection().root( )['indexes']['organisation'] except: pass try: del db.DBMgr.getInstance().getDBConnection().root( )['indexes']['status'] except: pass ah = user.AvatarHolder() ih = indexes.IndexesHolder() emailindex = ih.getById('email') nameindex = ih.getById('name') surNameindex = ih.getById('surName') orgindex = ih.getById('organisation') statindex = ih.getById('status') users = ah.getList() for us in users: emailindex.indexUser(us) nameindex.indexUser(us) surNameindex.indexUser(us) orgindex.indexUser(us) statindex.indexUser(us) db.DBMgr.getInstance().endRequest()
def updateCalendarIndex(): DBMgr.getInstance().startRequest() im = indexes.IndexesHolder() im.removeById('calendar') DBMgr.getInstance().commit() ch = CategoryManager() list = ch.getList() totnum = len(list) curnum = 0 curper = 0 for cat in list: committed = False DBMgr.getInstance().sync() calindex = im.getIndex('calendar') while not committed: try: del cat._calIdx except: pass for conf in cat.getConferenceList(): try: calindex.indexConf(conf) except Exception, e: log("%s" % e) log("calindex: exception indexing [%s] sd:%s, ed:%s" % (conf.getId(), conf.getStartDate(), conf.getEndDate())) try: DBMgr.getInstance().commit() committed = True except: DBMgr.getInstance().abort() log("retry %s" % cat.getId()) curnum += 1 per = int(float(curnum) / float(totnum) * 100) if per != curper: curper = per if per in [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]: log("done %s%%" % per)
def _getAnswer(self): im = indexes.IndexesHolder() ch = conference.ConferenceHolder() calIdx = im.getIndex("calendar") evtIds = calIdx.getObjectsIn(self._sDate, self._eDate) evtsByCateg = {} for evtId in evtIds: try: evt = ch.getById(evtId) categs = evt.getOwnerList() categname = categs[0].getName() if not evtsByCateg.has_key(categname): evtsByCateg[categname] = [] evtsByCateg[categname].append( (evt.getTitle().strip(), evt.getAdjustedStartDate().strftime('%d/%m/%Y %H:%M '), evt.getAdjustedEndDate().strftime('%d/%m/%Y %H:%M '), evt.getTimezone())) except Exception: continue return evtsByCateg
def main(): """This script deletes existing category indexes and recreates them.""" dbi = db.DBMgr.getInstance() dbi.startRequest() im = indexes.IndexesHolder() im.removeById('categoryName') catIdx = im.getIndex('categoryName') ch = CategoryManager() totnum = len(ch.getList()) curnum = 0 curper = 0 for cat in ch.getList(): while 1: print cat.getId(), cat.getTitle() catIdx.index(cat.getId(), cat.getTitle().decode('utf-8')) dbi.commit() break curnum += 1 per = int(float(curnum) / float(totnum) * 100) if per != curper: curper = per print "%s%%" % per dbi.endRequest()
def _getAnswer(self): import MaKaC.common.indexes as indexes nameIdx = indexes.IndexesHolder().getIndex('categoryName') query = ' '.join(map(lambda y: "*%s*" % y, self._searchString.split())) foundEntries = nameIdx.search(query, limit=7) number = len(foundEntries) entryNames = [] for (categId, value) in foundEntries: categ = CategoryManager().getById(categId) entryNames.append({ 'title': categ.getTitle(), 'path': self._getPath(categ), 'url': str(urlHandlers.UHCategoryDisplay.getURL(categ)) }) return {"list": entryNames, "number": number}
def __init__(self): """Index by email of all the requests""" self._id = "Managers" self._idx = indexes.IndexesHolder().getById( "pendingManagers") # All the pending managers
def __init__(self): """Index by email of all the request to add Authors or Speakers""" self._id = "Submitters" self._idx = indexes.IndexesHolder().getById( "pendingSubmitters") # All the ContributionParticipants
def __init__(self): """Index by email of all the requests""" self._id = "Coordinators" self._idx = indexes.IndexesHolder().getById( "pendingCoordinators") # All the pending coordinators
def _getAnswer(self): if self._user: idxs = indexes.IndexesHolder() funcGet = "get%s%s" % (self._dataType[0].upper(), self._dataType[1:]) funcSet = "set%s%s" % (self._dataType[0].upper(), self._dataType[1:]) if self._dataType == "title": if self._value in TitlesRegistry().getList(): self._user.setTitle(self._value) else: raise NoReportError(_("Invalid title value")) elif self._dataType == "surName": self._user.setFieldSynced('surName', False) surName = idxs.getById("surName") surName.unindexUser(self._avatar) self._user.setSurName(self._value) surName.indexUser(self._avatar) elif self._dataType == "name": self._user.setFieldSynced('firstName', False) name = idxs.getById("name") name.unindexUser(self._avatar) self._user.setName(self._value) name.indexUser(self._avatar) elif self._dataType == "organisation": self._user.setFieldSynced('affiliation', False) org = idxs.getById("organisation") org.unindexUser(self._avatar) self._user.setOrganisation(self._value) org.indexUser(self._avatar) elif self._dataType == "email": # Check if there is any user with this email address if self._value != self._avatar.getEmail(): other = user.AvatarHolder().match({"email": self._value}, forceWithoutExtAuth=True) if other and other[0] != self._avatar: raise NoReportError( _("The email address %s is already used by another user." ) % self._value) email = idxs.getById("email") email.unindexUser(self._avatar) self._user.setEmail(self._value) email.indexUser(self._avatar) elif self._dataType == "secondaryEmails": emailList = self._buildEmailList() secondaryEmails = [] # check if every secondary email is valid for email in emailList: if email != "": av = user.AvatarHolder().match( {"email": email}, forceWithoutExtAuth=True) if av and av[0] != self._avatar: raise NoReportError( _("The email address %s is already used by another user." ) % email) else: secondaryEmails.append(email) self._user.setSecondaryEmails(secondaryEmails) return ", ".join(self._user.getSecondaryEmails()) elif self._dataType == "telephone": self._user.setFieldSynced('phone', False) self._user.setTelephone(self._value) elif self._dataType == "fax": self._user.setFieldSynced('fax', False) self._user.setFax(self._value) else: getattr(self._user, funcSet)(self._value) return getattr(self._user, funcGet)() else: raise ServiceError("ERR-U5", _("User id not specified"))
def _getAnswer(self): if self._user: idxs = indexes.IndexesHolder() funcGet = "get%s%s" % (self._dataType[0].upper(), self._dataType[1:]) funcSet = "set%s%s" % (self._dataType[0].upper(), self._dataType[1:]) if self._dataType == "title": if self._value in TitlesRegistry().getList(): self._user.setTitle(self._value) else: raise NoReportError(_("Invalid title value")) elif self._dataType == "surName": self._user.setFieldSynced('surName', False) self._user.setSurName(self._value, reindex=True) elif self._dataType == "name": self._user.setFieldSynced('firstName', False) self._user.setName(self._value, reindex=True) elif self._dataType == "organisation": self._user.setFieldSynced('affiliation', False) self._user.setOrganisation(self._value, reindex=True) elif self._dataType == "email": # Check if there is any user with this email address if self._value != self._avatar.getEmail(): other = user.AvatarHolder().match( {"email": self._value}, searchInAuthenticators=False) if other and other[0] != self._avatar: raise NoReportError( _("The email address %s is already used by another user." ) % self._value) self._user.setEmail(self._value, reindex=True) elif self._dataType == "secondaryEmails": emailList = self._buildEmailList() secondaryEmails = [] newSecondaryEmailAdded = False # check if every secondary email is valid for sEmail in emailList: sEmail = sEmail.lower().strip() if sEmail != "": av = user.AvatarHolder().match( {"email": sEmail}, searchInAuthenticators=False) if av and av[0] != self._avatar: raise NoReportError( _("The email address %s is already used by another user." ) % sEmail) elif self._user.getEmail( ) == sEmail: # do not accept primary email address as secondary continue elif self._user.hasSecondaryEmail(sEmail): secondaryEmails.append(sEmail) else: newSecondaryEmailAdded = True self._user.addPendingSecondaryEmail(sEmail) self._sendSecondaryEmailNotifiication(sEmail) self._user.setSecondaryEmails(secondaryEmails, reindex=True) if newSecondaryEmailAdded: warn = Warning( _("New secondary email address"), _("You will receive an email in order to confirm\ your new email address. Once confirmed, it will be shown in your profile." )) return ResultWithWarning( ", ".join(self._user.getSecondaryEmails()), warn).fossilize() else: return ", ".join(self._user.getSecondaryEmails()) elif self._dataType == "telephone": self._user.setFieldSynced('phone', False) self._user.setTelephone(self._value) elif self._dataType == "fax": self._user.setFieldSynced('fax', False) self._user.setFax(self._value) elif self._dataType == "address": self._user.setFieldSynced('address', False) self._user.setAddress(self._value) else: getattr(self._user, funcSet)(self._value) return getattr(self._user, funcGet)() else: raise ServiceError("ERR-U5", _("User id not specified"))
def index(req, **params): """This script displays the list of meetings which are planned in the coming week""" global ids try: stdate = params['stdate'] nbweeks = params['nbweeks'] except: return usage() [year, month, day] = stdate.split("-") days = int(nbweeks) * 7 ch = ConferenceHolder() previous = "" if str(year) == "2008": previous = """<a href="http://indico.cern.ch/tools/SSLPdisplay.py?stdate=2007-07-02&nbweeks=7">Previous Year Lecture Programme</a>""" elif str(year) == "2009": previous = """<a href="http://indico.cern.ch/tools/SSLPdisplay.py?stdate=2008-06-30&nbweeks=9">Previous Year Lecture Programme</a>""" elif str(year) == "2010": previous = """<a href="http://indico.cern.ch/tools/SSLPdisplay.py?stdate=2009-06-29&nbweeks=8">Previous Year Lecture Programme</a>""" elif str(year) == "2011": previous = """<a href="http://indico.cern.ch/scripts/SSLPdisplay.py?stdate=2010-07-05&nbweeks=7">Previous Year Lecture Programme</a>""" html = """ <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="Author" content="Matthias Egger"> <meta name="GENERATOR" content="Mozilla/4.75 [en] (Win95; U) [Netscape]"> <meta name="resp1" content="Matthias Egger"> <meta name="resp2" content="Tanja Peeters"> <meta name="DateCreated" content="971205"> <meta name="DateExpires" content="981201"> <meta name="DateModified" content="971205"> <meta name="Keywords" content="summer student lecture programme"> <meta name="Description" content="The Summer Student lecture programme."> <title>Summer Student Lecture Programme</title> </head> <body text="#000099" bgcolor="#FFFFCC" link="#000000" vlink="#C6600" alink="#FF9900"> <div align=right></div> <map name="cern_options_banner_2"><area shape="rect" coords="1,16,70,35" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/Welcome.html"><area shape="rect" coords="72,17,146,35" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/youngpeople.html"><area shape="rect" coords="146,15,181,37" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/staff.html"><area shape="rect" coords="182,15,224,38" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/fellows.html"><area shape="rect" coords="225,15,286,38" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/associates.html"><area shape="rect" coords="286,16,337,37" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/students.html"><area shape="rect" coords="338,16,389,36" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/aboutus.html"><area shape="rect" coords="391,17,449,35" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/contactus.html"><area shape="rect" coords="450,16,503,35" href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/other.html"><area shape="rect" coords="506,2,552,46" href="http://www.cern.ch"><area shape="default" nohref></map> %s <br> <br> <center> <p><a NAME="Prog"></a><b><font face="Verdana"><font color="#000080"><font size=+2>Summer Student Lecture Programme %s </font></font></font></b></center> </font></font></font> <p><b><font face="Verdana"><font color="#000080"><font size=-1>Keys:</font></font></font></b> <br><font face="Verdana"><font size=-1><font color="green">(v): videos</font></font></font> <br><font face="Verdana"><font size=-1><font color="red">(t): transparencies</font></font></font> <br><font face="Verdana"><font size=-1><font color="brown">(l): web lecture</font></font></font> <br><font face="Verdana"><font size=-1><font color="blue">(b): biography</font></font></font> <br><font face="Verdana"><font size=-1><font color="grey">(q): questionnaire</font></font></font> <br> """ % (previous, year) #create list of ids ids = [345, 346, 347, 348] db.DBMgr.getInstance().startRequest() tz = info.HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone() #create date object startdate = timezone(tz).localize( datetime.datetime(int(year), int(month), int(day))) stdatedays = startdate.toordinal() enddate = startdate + datetime.timedelta(days=int(days)) #create result set res = sets.Set() #instanciate indexes im = indexes.IndexesHolder() catIdx = im.getIndex('category') calIdx = im.getIndex('calendar') c1 = calIdx.getObjectsIn(startdate, enddate) for id in ids: confIds = sets.Set(catIdx.getItems(id)) confIds.intersection_update(c1) res.update(confIds) res = list(res) res.sort(sortByStartDate) seminars = {} stimes = [] etimes = [] for id in res: obj = ch.getById(id) agenda = {} agenda['object'] = obj agenda['id'] = obj.getId() agenda['stime1'] = obj.getAdjustedStartDate(tz).time().isoformat()[0:5] agenda['atitle'] = obj.getTitle() agenda['desc'] = "" if obj.getComments() != "": agenda['desc'] = "<br>%s" % obj.getComments() if obj.getChairList() != []: agenda['chairman'] = obj.getChairList()[0].getFullName() else: agenda['chairman'] = "" agenda['stdate'] = obj.getAdjustedStartDate(tz).date() agenda['fduration'] = (obj.getAdjustedEndDate(tz) - obj.getAdjustedStartDate(tz)).seconds agenda['etime1'] = obj.getAdjustedEndDate(tz).time().isoformat()[0:5] stime = obj.getAdjustedStartDate(tz).time().isoformat()[0:5] etime = obj.getAdjustedEndDate(tz).time().isoformat()[0:5] stdate = obj.getAdjustedStartDate(tz).date() if not seminars.has_key(stdate): seminars[stdate] = {} if not seminars[stdate].has_key(stime): seminars[stdate][stime] = [] seminars[stdate][stime].append(agenda) if not stime in stimes: stimes.append(stime) etimes.append(etime) for week in range(0, int(nbweeks)): html += """<table BORDER CELLPADDING=4 WIDTH="100%" > <tr> <td VALIGN=TOP WIDTH="6%" HEIGHT="27" BGCOLOR="#FFFFFF"> <center><b><font face="Arial">Time</font></b></center> </td>""" beginweek = stdatedays + (week * 7) endweek = stdatedays + (week + 1) * 7 - 2 # display day names days = beginweek while days < endweek: thisday = datetime.datetime.fromordinal(days).strftime("%A %d %b") html += """ <td VALIGN=TOP WIDTH="19%%" HEIGHT="27" BGCOLOR="#FFFFFF"> <center><b><font face="Arial">%s</font></b></center> </td>""" % thisday days += 1 html += "</TR>" #display hour per hour agenda rowtext = "" for i in range(len(stimes)): val = stimes[i] rowtext = "" nbtalks = 0 rowtext += """ <TR><td VALIGN=TOP WIDTH="6%%" BGCOLOR="#FFFFFF"> <center><b><font face="Arial">%s</font></b> <br><b><font face="Arial">-</font></b> <br><b><font face="Arial">%s</font></b></center> </td>""" % (stimes[i], etimes[i]) days = beginweek while days < endweek: thisday = datetime.date.fromordinal(days) texttime = "" if seminars.has_key(thisday) and seminars[thisday].has_key( val): for agenda in seminars[thisday][val]: ida = agenda['id'] if agenda['stime1'] != stimes[i] or agenda[ 'etime1'] != etimes[i]: texttime = "<BR><i>(" + agenda[ 'stime1'] + " - " + agenda['etime1'] + ")</i>" #FILES textfiles = "" miscitems = 0 for m in agenda['object'].getAllMaterialList(): entry = m.getTitle().lower() if entry[0:4] != "part": if entry == "video" or entry == "video in cds": entry = "<font color=green>v</font>" elif entry in ["transparencies", "slides"]: entry = "<font color=red>t</font>" elif entry in ["biography"]: entry = "<font color=blue>b</font>" elif entry == "questionnaire": entry = "<font color=grey>q</font>" elif entry == "syncomat": entry = "<font color=brown>l</font>" elif entry == "lecture": entry = "<font color=brown>l</font>" elif entry == "lecture_from_2000": entry = "<font color=brown>l/2000</font>" elif entry == "video_from_2000": entry = "<font color=green>v/2000</font>" else: entry = "m" url = UHMaterialDisplay.getURL(m) textfiles += "(<A HREF=%s>%s</A>)" % (url, entry) rowtext += """<td VALIGN=TOP WIDTH="19%%"><font face="Arial"><font size=-1><a href="%s">%s</a>%s%s</font></font><p><i><font face="Arial"><font size=-1><i>%s</I>%s</font></font></i></td>\n""" % ( UHConferenceDisplay.getURL(agenda['object']), agenda['atitle'], agenda['desc'], textfiles, agenda['chairman'], texttime) nbtalks += 1 else: rowtext += """<td VALIGN=TOP WIDTH="19%"> </td>""" days += 1 rowtext += "</TR>" if nbtalks != 0: html += rowtext html += "</TABLE>" html += "<br> " html += """ <br> <!-- <p><a href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/6sumprog.html#SUMMER STUDENTS">CERN Recruitment Service</a> --> <center> <hr WIDTH="100%"> <!-- <br><font face="Verdana,Helvetica,Helvetica"><font size=-2><font color="#A00000"><a href="http://cern.web.cern.ch/CERN/Divisions/PE/HRS/Recruitment/search_HRS.html">Search</a></font><font color="#0000A0"> the pages of the Recruitment Service</font></font></font> <br><font face="Verdana,Helvetica"><font color="#000099"><font size=-2> Comments about this Web site to: <a href="mailto:[email protected]">[email protected]</a></font></font></font> <br><font face="Verdana,Helvetica"><font color="#000099"><font size=-2>Enquiries about Recruitment Programmes to: <a href="mailto:[email protected]">[email protected]</a></font></font></font> --> <br><font face="Verdana,Helvetica"><font color="#000099"><font size=-2>Copyright CERN - the European Laboratory for Particle Physics (Geneva, Switzerland)</font></font></font></center> <p><br> </body> </html>""" return html
def updateOAIIndexes(): DBMgr.getInstance().startRequest() ch = ConferenceHolder() ih = indexes.IndexesHolder() catIdx = ih.getById("category") confIdx = ih.getById("OAIConferenceModificationDate") contIdx = ih.getById("OAIContributionModificationDate") confIdxPr = ih.getById("OAIPrivateConferenceModificationDate") contIdxPr = ih.getById("OAIPrivateContributionModificationDate") confIdx.initIndex() contIdx.initIndex() confIdxPr.initIndex() contIdxPr.initIndex() DBMgr.getInstance().commit() log("Count conferences...") ids = catIdx.getItems('0') totalConf = len(ids) log("%d conferences found"%totalConf) ic = 1 DBMgr.getInstance().sync() DBMgr.getInstance().endRequest() i = 0 pubConf = 0 privConf = 0 while ids: if len(ids) >= 10: lids = ids[:10] del ids[:10] else: lids = ids ids = None startic = ic startPubConf = pubConf startPrivConf = privConf for j in range(10): try: DBMgr.getInstance().startRequest() for id in lids: conf = ch.getById(id) confIdx = ih.getById("OAIConferenceModificationDate") contIdx = ih.getById("OAIContributionModificationDate") confIdxPr = ih.getById("OAIPrivateConferenceModificationDate") contIdxPr = ih.getById("OAIPrivateContributionModificationDate") log("Index conference %s: %d on %d"%(id, ic, totalConf)) ic += 1 if conf.hasAnyProtection(): confIdxPr.indexConference(conf) privConf += 1 else: confIdx.indexConference(conf) pubConf += 1 for cont in conf.getContributionList(): if cont.hasAnyProtection(): contIdxPr.indexContribution(cont) else: contIdx.indexContribution(cont) for sc in cont.getSubContributionList(): if cont.isProtected(): contIdxPr.indexContribution(sc) else: contIdx.indexContribution(sc) DBMgr.getInstance().endRequest() log("wait 0.5s...") sleep(0.5) break except Exception, e: log("error %s, retry %d time(s)"%(e,int(10-j))) sleep(int(j)) ic = startic pubConf = startPubConf privConf = startPrivConf DBMgr.getInstance().abort()
def _process(self): if self._statusValue != "OK": return self._createResponse(self._statusValue, self._message) ih = indexes.IndexesHolder() calIdx = ih.getIndex("calendar") catIdx = ih.getIndex("category") ch = conference.ConferenceHolder() # A *preliminary* set of conference id's is created here # This set is constructed using indexes, without getting the Conference # objects from the DB. listOfSets = [] if self._startDateAt != None: listOfSets.append(calIdx.getObjectsStartingInDay( self._startDateAt)) if self._startDateFrom != None: listOfSets.append( calIdx.getObjectsStartingIn(self._startDateFrom, self._startDateTo)) if self._endDateAt != None: listOfSets.append(calIdx.getObjectsEndingInDay(self._endDateAt)) if self._endDateFrom != None: listOfSets.append( calIdx.getObjectsEndingIn(self._endDateFrom, self._endDateTo)) if self._date != None: listOfSets.append(calIdx.getObjectsIn(self._date, self._date)) if self._category != None: resultSet = Set() if type(self._category) is list: for i in self._category: resultSet.union_update(catIdx.getItems(i)) else: resultSet.union_update(catIdx.getItems(self._category)) listOfSets.append(resultSet) if self._id != None: resultSet = Set() if type(self._id) is list: listOfSets.append(Set(self._id)) else: listOfSets.append(Set([self._id])) prelimResult = listOfSets[0] for i in range(1, len(listOfSets)): prelimResult.intersection_update(listOfSets[i]) result = Set() XG = xmlGen.XMLGen() XG.openTag("response") XG.openTag("status") XG.writeTag("value", "OK") XG.writeTag("message", "Returning search results") XG.closeTag("status") XG.openTag("event-list") for i in prelimResult: try: try: c = ch.getById(i) except: continue if self._author != None and not self._checkAuthor( c, self._author): continue if self._room != None and not self._checkRoom(c, self._room): continue if self._startDateFrom != None: if c.getStartDate() < self._startDateFrom or \ c.getStartDate() > self._startDateTo: continue if self._startDateAt != None: if c.getStartDate() != self._startDateAt: continue if self._endDateFrom != None: if c.getEndDate() < self._endDateFrom or \ c.getEndDate() > self._endDateTo: continue if self._endDateAt != None: if c.getEndDate() != self._endDateAt: continue result.add(i) if self._format != "full": self._printConference(c, XG) else: XG.openTag("event") og = outputGenerator(self.getAW(), XG) og._confToXML(c, {}) XG.closeTag("event") except KeyError: continue XG.closeTag("event-list") XG.closeTag("response") self._req.content_type = "text/xml" return XG.getXml()
def _process(self): if self._cancel: self._redirect(urlHandlers.UHUserDetails.getURL(self._avatar)) return save = False self._params["msg"] = "" if self._save: save = True #check submited data if not self._params.get("name", ""): self._params["msg"] += "You must enter a name.<br>" save = False if not self._params.get("surName", ""): self._params["msg"] += "You must enter a surname.<br>" save = False if not self._params.get("organisation", ""): self._params[ "msg"] += "You must enter the name of your organisation.<br>" save = False if not self._params.get("email", ""): self._params["msg"] += "You must enter an email address.<br>" save = False if self._params.get("email", "") != self._avatar.getEmail(): av = user.AvatarHolder().match( {"email": self._params.get("email", "")}, forceWithoutExtAuth=True) if av: if av[0] != self._avatar: self._params["msg"] += "This email is already used" save = False if save: #Data are OK, save them idxs = indexes.IndexesHolder() org = idxs.getById('organisation') email = idxs.getById('email') name = idxs.getById('name') surName = idxs.getById('surName') org.unindexUser(self._avatar) email.unindexUser(self._avatar) name.unindexUser(self._avatar) surName.unindexUser(self._avatar) self._params["secEmails"] = self._normaliseListParam( self._params.get("secEmails", [])) _UserUtils.setUserData(self._avatar, self._params) self._getSession().setLang(self._avatar.getLang()) org.indexUser(self._avatar) email.indexUser(self._avatar) name.indexUser(self._avatar) surName.indexUser(self._avatar) #----Grant rights if anything ph = pendingQueues.PendingQueuesHolder() ph.grantRights(self._avatar) #----- websession = self._aw.getSession() tzUtil = timezoneUtils.SessionTZ(self._aw.getUser()) tz = tzUtil.getSessionTZ() websession.setVar("ActiveTimezone", tz) self._redirect(urlHandlers.UHUserDetails.getURL(self._avatar)) elif self._addEmail: self._params["secEmails"] = self._normaliseListParam( self._params.get("secEmails", [])) email = self._params.get("secEmailAdd", "") av = user.AvatarHolder().match({"email": email}, exact=1, forceWithoutExtAuth=True) add = True if av: if av[0] != self._avatar: self._params["msg"] += "This email is already used" add = False if email and add and not email in self._params["secEmails"]: self._params["secEmails"].append(email) p = adminPages.WPUserModification(self, self._avatar, self._params) return p.display() elif self._removeEmail: emails = self._normaliseListParam( self._params.get("secEmailRemove", [])) self._params["secEmails"] = self._normaliseListParam( self._params["secEmails"]) for email in emails: if email and email in self._params["secEmails"]: self._params["secEmails"].remove(email) p = adminPages.WPUserModification(self, self._avatar, self._params) websession = self._aw.getSession() tzUtil = timezoneUtils.SessionTZ(self._aw.getUser()) tz = tzUtil.getSessionTZ() websession.setVar("ActiveTimezone", tz) return p.display() else: p = adminPages.WPUserModification(self, self._avatar, self._params) websession = self._aw.getSession() tzUtil = timezoneUtils.SessionTZ(self._aw.getUser()) tz = tzUtil.getSessionTZ() websession.setVar("ActiveTimezone", tz) return p.display() """