Beispiel #1
0
class Adder(grok.Application, grok.Model):
    """An adding machine with tape
    
    >>> adder = Adder()
    >>> adder.total
    0.0
    >>> adder.addTerm(0)
    0.0
    >>> '%.2f' % adder.addTerm(1.2)
    '1.20'
    >>> '%.2f' % adder.addTerm(-1)
    '0.20'
    
    Besides adding, Adder also contains a history of the added terms
    
    >>> ['%.2f' % term for term in adder.terms]
    ['0.00', '1.20', '-1.00']
    
    """
    def __init__(self):
        super(Adder, self).__init__()
        self.message = None
        self.clear()

    def clear(self):
        self.terms = PersistentList()
        self.total = 0.0

    def addTerm(self, term):
        self.terms.append(term)
        self.total += term
        return self.total
class MockMailHost(MailBase):
    """A MailHost that collects messages instead of sending them.
    """

    def __init__(self, id):
        self.reset()

    def reset(self):
        self.messages = PersistentList()

    def _send(self, mfrom, mto, messageText, immediate=False):
        """ Send the message """
        self.messages.append(messageText)

    def send(self, messageText, mto=None, mfrom=None, subject=None,
             encode=None, immediate=False, charset=None, msg_type=None):
        messageText, mto, mfrom = _mungeHeaders(messageText,
                                                mto, mfrom, subject,
                                                charset=charset,
                                                msg_type=msg_type)
        self.messages.append(messageText)

    # Outside of the tests we patch the MailHost to provide a
    # secureSend method for backwards compatibility, so we should do
    # that for our MockMailHost as well.
    secureSend = secureSend
def replace_values(obj, orig, new):
    """ replace all occurences of column name
    """
    if isinstance(obj, PersistentList) or isinstance(obj, list):
        if isinstance(obj, PersistentList):
            new_obj = PersistentList()
        else:
            new_obj = []
        for item in obj:
            new_item = replace_values(item, orig, new)
            new_obj.append(new_item)
        return new_obj

    if isinstance(obj, PersistentDict) or isinstance(obj, dict):
        if isinstance(obj, PersistentDict):
            new_obj = PersistentDict()
        else:
            new_obj = {}
        for key in obj.keys():
            new_value = replace_values(obj[key], orig, new)
            new_key = replace_values(key, orig, new)
            new_obj[new_key] = new_value
        return new_obj

    if isinstance(obj, basestring):
        new_obj = obj.replace(orig, new)
        return new_obj

    return obj
Beispiel #4
0
def get_msfd_reporting_history_from_file(file):
    res = PersistentList()
    sheets = get_data(file)
    env_data = sheets['ENV']

    indx_date_due = env_data[0].index('DateDue')
    indx_date_received = env_data[0].index('DateReceived')

    for row in env_data:
        row = [isinstance(x, basestring) and x.strip() or x for x in row]
        while len(row) < 14:
            row.append('')

        date_due = row[indx_date_due]
        date_received = row[indx_date_received]

        if isinstance(date_due, datetime):
            row[indx_date_due] = date_due.date()

        if isinstance(date_received, datetime):
            row[indx_date_received] = date_received.date()

        res.append(ReportingHistoryENVRow(*row[:14]))

    return res
Beispiel #5
0
class SubProcess(Activity):

    def __init__(self, definition):
        super(SubProcess, self).__init__(definition)
        self.sub_processes = PersistentList()

    def _start_subprocess(self, action):
        def_container = find_service('process_definition_container')
        pd = def_container.get_definition(getattr(self.definition.sub_process_definition,
                                                  'id', self.definition.sub_process_definition))
        proc = pd()
        proc.__name__ = proc.id
        runtime = find_service('runtime')
        runtime.addtoproperty('processes', proc)
        proc.defineGraph(pd)
        self.definition._init_subprocess(self.process, proc)
        proc.attachedTo = action
        proc.execute()
        self.sub_processes.append(proc)
        return proc

    def stop(self):
        runtime = find_service('runtime')
        for process in self.sub_processes:
            process._finished = True
            for node in process.nodes:
                node.stop()
                node.setproperty('workitems', [])

            runtime.delfromproperty('processes', process)
class MailingListManager(SimpleItem):
    implements(IMailingListManager)

    def __init__(self):
        self.mailinglists = PersistentList()
        self.id_seed = 0

    def add(self, name, email, protocol):
        self.id_seed += 1
        self.mailinglists.append({'id': self.id_seed,
                                  'name': name,
                                  'email': email,
                                  'protocol': protocol})

    def remove(self, list_id):
        self.mailinglists = filter(lambda l: str(l['id']) != list_id,
                                   self.mailinglists)

    def get_mailinglist_by_id(self, list_id):
        for mlist in self.mailinglists:
            if str(mlist['id']) == str(list_id):
                return mlist
        return None

    @property
    def protocols(self):
        return [{'id': 'mailman',
                 'name': 'Mailman'},
                {'id': 'google_groups',
                 'name': 'Google Groups'},
                {'id': 'sympa',
                 'name': 'Sympa'}]
Beispiel #7
0
class GenericContainer(grok.Container):
    def __init__(self, name, id=None):
        super(GenericContainer, self).__init__()
        self.name = name
        self.id = id
        self.item_count = 0
        self.item_order = PersistentList()

    def items(self):
        t = []
        for key in self.item_order: t.append(self[unicode(key)])
        return t

    def inverse_items(self):
        t = self.items()
        t.reverse()
        return t

    def delete(self,id):
        self.item_order.pop(self.item_order.index(int(id)))

    def add_item(self,item):
        self[unicode(self.item_count)] = item
        self.item_order.append(self.item_count)
        self.item_count += 1

    def max(self):
        if self.items() is not None:
            return self.items()[-1]
    
    def min(self):
        if self.items is not None:
            return self.items()[0]
Beispiel #8
0
 def __call__(self):
     term = getTermForDate(self.event.date)
     if term is None:
         return
     old_date = self.event.date
     new_date = self.event.replacement_date
     schoolyear = ISchoolYear(term)
     timetables = ITimetableContainer(schoolyear)
     for timetable in timetables.values():
         if IScheduleExceptions.providedBy(timetable):
             modified = False
             scheduled = DateRange(timetable.first, timetable.last)
             meeting_exceptions = PersistentList()
             if old_date in scheduled:
                 meetings = list(timetable.iterMeetings(old_date))
                 for meeting in meetings:
                     meeting_exceptions.append(
                         MeetingException(
                             meeting.dtstart.replace(year=new_date.year,
                                                     month=new_date.month,
                                                     day=new_date.day),
                             meeting.duration,
                             period=meeting.period,
                             meeting_id=meeting.meeting_id))
                 timetable.exceptions[old_date] = PersistentList()
                 modified = True
             if new_date in scheduled:
                 timetable.exceptions[new_date] = meeting_exceptions
                 modified = True
             if modified:
                 zope.lifecycleevent.modified(timetable)
Beispiel #9
0
class Wizard(Behavior):
    steps = {}
    transitions = ()

    def __init__(self, **kwargs):
        super(Wizard, self).__init__(**kwargs)
        self.transitionsinstances = PersistentList()
        self.stepinstances = PersistentList()
        for key, step in self.steps.items():
            stepinstance = step(step_id=key, wizard=self)
            self.stepinstances.append((stepinstance.step_id, stepinstance))

        _stepinstances = dict(self.stepinstances)
        for transition in self.transitions:
            sourceinstance = _stepinstances[transition[0]]
            targetinstance = _stepinstances[transition[1]]
            transitionid = transition[0]+'->'+transition[1]
            condition = None
            try:
                condition = transition[3]
            except Exception:
                condition = default_condition

            default = False
            try:
                default = transition[2]
            except Exception:
                pass

            transitioninstance = Transition(sourceinstance, targetinstance, 
                                            transitionid, condition, default)
            self.transitionsinstances.append((transitionid, transitioninstance))
Beispiel #10
0
class OrderedPersistentDict(DictMixin, Persistent):
    def __init__(self, data=None):
        self._data = PersistentMapping()
        self._keylist = PersistentList()
        if not data is None:
            self.update(data)

    def __setitem__(self, key, val):
        self._data[key] = val
        if key in self._keylist:
            self._keylist.remove(key)

        self._keylist.append(key)

    def __getitem__(self, key):
        return self._data[key]

    def __delitem__(self, key):
        self._keylist.remove(key)
        del self._data[key]

    def keys(self):
        return self._keylist[:]

    def reverse(self):
        items = list(self.items())
        items.reverse()
        return items
Beispiel #11
0
class GalleryAlbum(GalleryContainer):
    def __init__(self, name, description=None, long_description=None,
                 location=None,
                 date_from=datetime.datetime.now(), date_to=None,
                 parent=None):
        GalleryContainer.__init__(self, name, description, parent=parent)
        self.long_description = long_description
        self.location = location
        self.date_from = date_from
        self.date_to = date_to
        self.__pictures = PersistentList()

    @property
    def pictures(self):
        return self.__pictures

    def add(self, item):
        self[item.__name__] = item

    def insert(self, index, item):
        GalleryContainer.add(self, item)
        self.__pictures.insert(index, item)

    def __setitem__(self, name, item):
        GalleryContainer.__setitem__(self, name, item)
        self.__pictures.append(item)

    def __delitem__(self, name):
        self.__pictures.remove(self[name])
        GalleryContainer.__delitem__(self, name)
Beispiel #12
0
class GalleryAlbum(GalleryContainer):
    def __init__(self,
                 name,
                 description=None,
                 long_description=None,
                 location=None,
                 date_from=datetime.datetime.now(),
                 date_to=None,
                 parent=None):
        GalleryContainer.__init__(self, name, description, parent=parent)
        self.long_description = long_description
        self.location = location
        self.date_from = date_from
        self.date_to = date_to
        self.__pictures = PersistentList()

    @property
    def pictures(self):
        return self.__pictures

    def add(self, item):
        self[item.__name__] = item

    def insert(self, index, item):
        GalleryContainer.add(self, item)
        self.__pictures.insert(index, item)

    def __setitem__(self, name, item):
        GalleryContainer.__setitem__(self, name, item)
        self.__pictures.append(item)

    def __delitem__(self, name):
        self.__pictures.remove(self[name])
        GalleryContainer.__delitem__(self, name)
Beispiel #13
0
def journal_entry_factory(context, action, title,
                          visible=True, comment='', actor=None,
                          documents=None):
    if actor is None:
        actor = api.user.get_current().getId()

    comment = comment == '' and get_change_note(getRequest(), '') or comment
    title = propper_string(title)
    action = propper_string(action)
    comment = propper_string(comment)

    action_entry = PersistentDict({'type': action,
                                   'title': title,
                                   'visible': visible})
    if documents:
        action_documents = PersistentList()
        for doc in documents:
            action_documents.append(PersistentDict(
                {'id': Oguid.for_object(doc).id, 'title': doc.title}))
        action_entry['documents'] = action_documents

    entry = {
        'obj': context,
        'action': action_entry,
        'actor': actor,
        'comment': comment}

    notify(JournalEntryEvent(**entry))
Beispiel #14
0
class Sponsored(HasState):
    """Mixin class for sponsored objects.
    
    Refactored out of Voteable.
    """
    def __init__(self, min_sponsors=1):
        HasState.__init__(self)
        self.min_sponsors = min_sponsors
        self.__sponsors = PersistentList()

    def add_sponsor(self, sponsor):
        if sponsor not in self.__sponsors:
            self.__sponsors.append(sponsor)
        
    def get_sponsors(self):
        return self.__sponsors
    
    def enough_sponsors(self):
        return len(self.__sponsors) >= self.min_sponsors

    def set_pending(self):
        """Transition from new to pending state. Awaiting more sponsors."""
        if self.get_state() != 'new':
            raise InvalidState, "cannot transition to pending from '%s' state." % self.get_state()
        
        self.set_state('pending')

    def force_accept(self):
        """Force into accepted state, regardless of vote or status."""
        self.set_state('accepted')
    
    def is_sponsor(self, user):
        return user in self.__sponsors
Beispiel #15
0
class MockMailHost(MailBase):
    """A MailHost that collects messages instead of sending them.
    """
    def __init__(self, id):
        self.reset()

    def reset(self):
        self.messages = PersistentList()

    def _send(self, mfrom, mto, messageText, immediate=False):
        """ Send the message """
        self.messages.append(messageText)

    def send(self,
             messageText,
             mto=None,
             mfrom=None,
             subject=None,
             encode=None,
             immediate=False,
             charset=None,
             msg_type=None):
        messageText, mto, mfrom = _mungeHeaders(messageText,
                                                mto,
                                                mfrom,
                                                subject,
                                                charset=charset,
                                                msg_type=msg_type)
        self.messages.append(messageText)

    # Outside of the tests we patch the MailHost to provide a
    # secureSend method for backwards compatibility, so we should do
    # that for our MockMailHost as well.
    secureSend = secureSend
Beispiel #16
0
    def notifications(self, value):

        # check that value is list
        if not isinstance(value, list):
            raise Exception("Notifcations should be list of dictionaries, "
                            "that can be dumped using json module.")

        # check that all list items are dictionaries
        for item in value:
            if not isinstance(item, dict):
                raise Exception("Notifcations should be list of dictionaries, "
                                "that can be dumped using json module.")

        # check that we can dump value using json module
        try:
            json.dumps(value)
        except:
            raise Exception("Notifcations should be list of dictionaries, "
                            "that can be dumped using json module.")

        # if assignee is storing notifications then we store to annotations
        current = api.user.get_current().getId()
        assignee = getattr(self.context, 'assignee', None)
        if assignee and current in assignee:
            annotations = self._setup_annotations()
            rules = PersistentList()
            for item in value:
                rules.append(PersistentDict(item))
            annotations[TASK_NOTIFICATIONS_KEY][current] = rules

        # otherwise we store
        else:
            setattr(self.context, 'notifications', value)

        self.context.reindexObject()
class MockMailHost(MailBase):
    """A MailHost that collects messages instead of sending them.
    """

    def __init__(self, id):
        self.reset()

    def reset(self):
        self.messages = PersistentList()

    def _send(self, mfrom, mto, messageText, immediate=False):
        """ Send the message """
        self.messages.append(messageText)

    def send(self,
             messageText,
             mto=None,
             mfrom=None,
             subject=None,
             encode=None,
             immediate=False,
             charset=None,
             msg_type=None):
        """send *messageText* modified by the other parameters.

        *messageText* can either be an ``email.message.Message``
        or a string.
        Note that Products.MailHost 4.10 had changes here.
        """
        msg, mto, mfrom = _mungeHeaders(messageText, mto, mfrom,
                                        subject, charset, msg_type,
                                        encode)
        self.messages.append(msg)
Beispiel #18
0
class WebhookDeliveryAttemptInternalInfo(DCTimesMixin, Contained):

    exception_history = ()

    def __init__(self):
        now = self.createdTime = self.lastModified = time.time()
        pid = os.getpid()
        hostname = socket.gethostname()
        transaction_note = transaction.get().description
        self.originated = DeliveryOriginationInfo(
            pid,
            hostname,
            now,
            transaction_note,
        )

    def storeExceptionInfo(self, exc_info):
        self.storeExceptionText(print_exception_to_text(exc_info))

    def storeExceptionText(self, text):
        """
        Store an exception text, usually as created by
        :func:`nti.webhooks._util.print_exception_to_text`
        """
        if self.exception_history == ():
            if IPersistent.providedBy(self.__parent__):
                self.__parent__._p_changed = True  # pylint:disable=protected-access
                self.exception_history = PersistentList()
            else:
                self.exception_history = []
        assert isinstance(text, text_type)
        self.exception_history.append(text)
Beispiel #19
0
class Response(Persistent):

    implements(IResponse)

    def __init__(self, text):
        self.__parent__ = self.__name__ = None
        self.text = text
        self.changes = PersistentList()
        sm = getSecurityManager()
        user = sm.getUser()
        self.creator = user.getId() or '(anonymous)'
        self.date = DateTime()
        self.type = 'additional'
        self.mimetype = ''
        self.rendered_text = None
        self.relatedItems = ()
        self.added_object = None
        self.successor_oguid = None
        self.transition = None

    def add_change(self, id, name, before, after):
        """Add a new issue change.
        """
        delta = dict(
            id=id,
            name=name,
            before=before,
            after=after)
        self.changes.append(delta)

    def creator_link(self):
        info = getUtility(IContactInformation)
        return info.render_link(self.creator)
Beispiel #20
0
class CustomizationMarker(PersistentInterfaceClass, ZMIObject):

    meta_type = "Silva Customization Marker"

    silvaconf.icon("markers.png")
    silvaconf.factory("manage_addCustomizationMarkerForm")
    silvaconf.factory("manage_addCustomizationMarker")

    def __init__(self, name, doc=None):
        self.id = name
        PersistentInterfaceClass.__init__(self, name=name, bases=(ICustomizableMarker,), __doc__=doc)
        ZMIObject.__init__(self)
        self.marked = PersistentList()

    def updateIdentifier(self):
        self.__identifier__ = self.markerId()

    def addMarkedObject(self, obj):
        oid = getUtility(IIntIds).register(obj)
        self.marked.append(oid)

    def removeMarkedObject(self, obj):
        oid = getUtility(IIntIds).getId(obj)
        self.marked.remove(oid)

    def markedObjects(self):
        resolver = getUtility(IIntIds).getObject
        return [resolver(oid) for oid in self.marked]

    def markerId(self):
        return u"marker:%s" % ".".join(self.getPhysicalPath()[1:])
Beispiel #21
0
class PruneJob(Job):
    short_name = 'prune'
    verbose_name = _('Prune archives')
    executor = PruneJobExecutor

    class State(Job.State):
        discovering = s('discovering', _('Discovering archives to prune'))
        prune = s('prune', _('Pruning archives'))

    def __init__(self, config: PruneConfig):
        super().__init__()
        self.config = config
        self.repositories = PersistentList()

    def find_archives(self):
        self.update_state(self.State.job_created, self.State.discovering)
        self.archives = self.config.apply_policy()
        for repository, _ in self.config.yield_archives_by_repository(
                self.archives):
            self.repositories.append(repository)
            repository.jobs[self.id] = self

    def execute(self):
        self.update_state(self.State.discovering, self.State.prune)
        self.config.prune(self.archives)
        self.update_state(self.State.prune, self.State.done)
        log.info('Job %s completed successfully', self.id)
Beispiel #22
0
    def _process(self):
        if self._target.isClosed():
            return json.dumps({'status': 'error'}, textarea=True)
        else:
            if self._tempFilePath is not None:
                if self._conf.getPosterTemplateManager().hasTemplate(self.__templateId):
                # Save
                    backgroundId = self._conf.getPosterTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath,self._bgPosition)
                else:
                # New
                    key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId)
                    value = session.get(key)
                    if value is None:
                    # First background
                        tempFilePathList = PersistentList()
                        tempFilePathList.append((self._tempFilePath,self._bgPosition))
                        session[key] = tempFilePathList
                        backgroundId = 0
                    else:
                    # We have more
                        value.append((self._tempFilePath, self._bgPosition))
                        backgroundId = len(value) - 1
                        session.modified = True

                return json.dumps({
                    'status': 'OK',
                    'id': backgroundId,
                    'url': str(urlHandlers.UHConfModifPosterGetBackground.getURL(self._conf, self.__templateId, backgroundId)),
                    'pos': self._bgPosition
                }, textarea=True)
Beispiel #23
0
def replace_values(obj, orig, new):
    """ replace all occurences of column name
    """
    if isinstance(obj, (PersistentList, list)):
        if isinstance(obj, PersistentList):
            new_obj = PersistentList()
        else:
            new_obj = []
        for item in obj:
            new_item = replace_values(item, orig, new)
            new_obj.append(new_item)
        return new_obj

    if isinstance(obj, (PersistentDict, dict)):
        if isinstance(obj, PersistentDict):
            new_obj = PersistentDict()
        else:
            new_obj = {}
        for key in obj.keys():
            new_value = replace_values(obj[key], orig, new)
            new_key = replace_values(key, orig, new)
            new_obj[new_key] = new_value
        return new_obj

    if isinstance(obj, basestring):
        new_obj = obj.replace(orig, new)
        return new_obj

    return obj
Beispiel #24
0
class SubProcess(Activity):
    def __init__(self, definition):
        super(SubProcess, self).__init__(definition)
        self.sub_processes = PersistentList()

    def _start_subprocess(self, action):
        def_container = find_service('process_definition_container')
        pd = def_container.get_definition(
            getattr(self.definition.sub_process_definition, 'id',
                    self.definition.sub_process_definition))
        proc = pd()
        proc.__name__ = proc.id
        runtime = find_service('runtime')
        runtime.addtoproperty('processes', proc)
        proc.defineGraph(pd)
        self.definition._init_subprocess(self.process, proc)
        proc.attachedTo = action
        proc.execute()
        self.sub_processes.append(proc)
        return proc

    def stop(self):
        runtime = find_service('runtime')
        for process in self.sub_processes:
            process._finished = True
            for node in process.nodes:
                node.stop()
                node.setproperty('workitems', [])

            runtime.delfromproperty('processes', process)
class MockMailHost(MailBase):
    """A MailHost that collects messages instead of sending them.
    """
    def __init__(self, id):
        self.reset()

    def reset(self):
        self.messages = PersistentList()

    def _send(self, mfrom, mto, messageText, immediate=False):
        """ Send the message """
        self.messages.append(messageText)

    def send(self,
             messageText,
             mto=None,
             mfrom=None,
             subject=None,
             encode=None,
             immediate=False,
             charset=None,
             msg_type=None):
        messageText, mto, mfrom = _mungeHeaders(messageText,
                                                mto,
                                                mfrom,
                                                subject,
                                                charset=charset,
                                                msg_type=msg_type)
        self.messages.append(messageText)
Beispiel #26
0
class Response(Persistent):
    """A persistent lightweight object which represents a single response.
    Addable to the response container of plone objects, for example to
    workspace todo's.
    """

    implements(IResponse)

    def __init__(self, response_type='default'):
        self.response_id = None
        self.response_type = response_type

        self.created = datetime.now()
        self.creator = api.user.get_current().id

        self.text = ''
        self.changes = PersistentList()

    def add_change(self, field_id, before, after, field_title=''):
        self.changes.append(PersistentDict(
            field_id=field_id,
            field_title=field_title,  # Deprecated, only for the old gever-ui
            before=before,
            after=after
        ))
Beispiel #27
0
class ListSearchScheduler(SearchScheduler):
    def __init__(self, sched_list=None, **kwargs):
        super(ListSearchScheduler, self).__init__(**kwargs)
        if sched_list is None:
            sched_list = []
        self._list = PersistentList(sched_list)
        self._unhandled_list = PersistentList([])
        self.should_run = True
        self.add_poll_delay = 1  # second

    def __eq__(self, o):
        return self._list == o._list

    timefunc = volprop('timefunc', lambda: time)
    delayfunc = volprop('delayfunc', lambda: sleep)
    sched = volprop('sched')
    thread = volprop('thread')
    is_running = volprop('is_running', lambda: False)

    def add_schedule(self, query, sched, handler):
        search_sched = SearchSchedule(query, sched)
        self._list.append((search_sched, handler))
        self._unhandled_list.append((search_sched, handler))
        # self.send_event(ScheduleAddedEvent(search_sched, handler))

    def run(self):
        self.sched = scheduler(self.timefunc, self.delayfunc)

        for s, handler in self._list:
            query_event(datetime.now(), self.sched, s, handler)

        def handle_adds():
            while len(self._unhandled_list) > 0:
                s, handler = self._unhandled_list.pop(0)
                query_event(s.start, self.sched, s, handler)

            self.sched.enter(self.add_poll_delay, 0, handle_adds, ())

        handle_adds()

        def runner():
            while self.should_run:
                self.is_running = True
                try:
                    self.sched.run()
                except Exception:
                    L.error("Got an exception while running scheduler: ",
                            exc_info=True)
            self.is_running = False

        self.thread = Thread(target=runner)
        self.thread.start()

    def stop(self):
        if self.sched:
            while not self.sched.empty():
                for evt in self.sched.queue:
                    self.sched.cancel(evt)
        if self.thread:
            self.thread.join()
Beispiel #28
0
class Response(Persistent):

    implements(IResponse)

    def __init__(self, text):
        self.__parent__ = self.__name__ = None
        self.text = text
        self.changes = PersistentList()
        sm = getSecurityManager()
        user = sm.getUser()
        self.creator = user.getId() or '(anonymous)'
        self.date = DateTime()
        self.type = 'additional'
        self.mimetype = ''
        self.rendered_text = None
        self.attachment = None

    def add_change(self, id, name, before, after):
        """Add a new issue change.
        """
        delta = dict(
            id=id,
            name=name,
            before=before,
            after=after)
        self.changes.append(delta)
Beispiel #29
0
    def _process(self):
        if self._target.isClosed():
            return json.dumps({'status': 'error'}, textarea=True)
        else:
            if self._tempFilePath is not None:
                if self._conf.getBadgeTemplateManager().hasTemplate(self.__templateId):
                    backgroundId = self._conf.getBadgeTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath)
                else:
                    key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId)
                    value = session.get(key)
                    if value is None:
                        tempFilePathList = PersistentList()
                        tempFilePathList.append(self._tempFilePath)
                        session[key] = tempFilePathList
                        backgroundId = 0
                    else:
                        value.append(self._tempFilePath)
                        backgroundId = len(value) - 1
                        session.modified = True

                return json.dumps({
                    'status': 'OK',
                    'id': backgroundId,
                    'url': str(urlHandlers.UHConfModifBadgeGetBackground.getURL(self._conf, self.__templateId, backgroundId))
                }, textarea=True)
Beispiel #30
0
class SponsoredQueue(QonPersistent):
    """A queue to keep Sponsored items that are in pending state.
    
    Code refactored out of Voteable.
    """
    def __init__(self):
        self.queue = PersistentList()

    def add_to_queue(self, item):
        self.queue.append(item)

    def remove_from_queue(self, item):
        if item in self.queue:
            self.queue.remove(item)

    def add_sponsor(self, item, sponsor):
        """Add sponsor to item."""
        item.add_sponsor(sponsor)
        if item.enough_sponsors():
            self.force_accept(item)

    def get_items_by_state(self, state):
        items = [item for item in self.queue if item.get_state() == state]
        return items

    def new_items(self):
        return self.get_items_by_state('new')
        
    def pending_items(self):
        return self.get_items_by_state('pending')
    
    def force_accept(self, item):
        item.force_accept()
        self.remove_from_queue(item)
Beispiel #31
0
 def notify_personal_news_added(self, item):
     """Notice that a personal news item (BlogItem) was created."""
     plist = self.__recent_personal_news
     if not plist:
         plist = PersistentList()
     plist.append(item)
     plist = plist[-self._personal_news_count:]
     self.__recent_personal_news = plist
Beispiel #32
0
class Parcel(Persistent):

    @property
    def uploading(self):
        return 'upload_time' not in self.metadata

    def __init__(self, warehouse, name):
        self._warehouse = warehouse
        self.name = name
        self.metadata = PersistentMapping()
        self.history = PersistentList()

    def save_metadata(self, new_metadata):
        self._warehouse.logger.info("Metadata update for %r: %r (user %s)",
                                    self.name, new_metadata, _current_user())
        for key, value in new_metadata.iteritems():
            self.metadata[_ensure_unicode(key)] = _ensure_unicode(value)

    def get_path(self):
        return self._warehouse.parcels_path / self.name

    def get_files(self):
        for f in self.get_path().listdir():
            if not f.name.startswith('.') and not f.isdir():
                yield f

    def finalize(self):
        self._warehouse.logger.info("Finalizing %r (user %s)",
                                    self.name, _current_user())
        self.checksum = checksum(self.get_path())
        self.save_metadata({'upload_time': datetime.utcnow().isoformat()})

    def link_in_tree(self):
        symlink_path = self._warehouse.tree_path
        for name in METADATA:
            symlink_path = symlink_path / self.metadata[name]
        symlink_path.makedirs_p()
        target_path = self.get_path()
        for c in xrange(1, 101):
            symlink_path_c = symlink_path / str(c)
            if not symlink_path_c.islink():
                target_path.symlink(symlink_path_c)
                return symlink_path_c
            else:
                if symlink_path_c.readlink() == target_path:
                    return
        else:
            raise RuntimeError("Unable to create symlink, tried 100 numbers")

    def add_history_item(self, title, time, actor, description_html):
        item = ParcelHistoryItem(self, title, time, actor, description_html)
        item.id_ = len(self.history) + 1
        self.history.append(item)
        return item

    @property
    def last_modified(self):
        return self.history[-1].time
Beispiel #33
0
    def serialize_users(self):
        """Returns a persistent list of dicts for all users.
        """
        value = PersistentList()
        for item in self.users:
            value.append(
                PersistentDict({'id': item.id, 'title': item.get_title()}))

        return value
Beispiel #34
0
    def serialize_users(self):
        """Returns a persistent list of dicts for all users.
        """
        value = PersistentList()
        for item in self.users:
            value.append(
                PersistentDict({'id': item.id, 'title': item.get_title()}))

        return value
Beispiel #35
0
class OrderedContainer(Container):
    """A Grok container that remembers the order of its items.

    This straightforward extension of the basic `grok.Container`
    remembers the order in which items have been inserted, so that
    `keys()`, `values()`, `items()`, and iteration across the container
    can all return the items in the order they were inserted.  The only
    way of changing the order is to call the `updateOrder()` method.

    """
    implements(interfaces.IOrderedContainer)

    def __init__(self):
        super(OrderedContainer, self).__init__()
        self._order = PersistentList()

    def keys(self):
        # Return a copy of the list to prevent accidental modifications.
        return self._order[:]

    def __iter__(self):
        return iter(self.keys())

    def values(self):
        return (self[key] for key in self._order)

    def items(self):
        return ((key, self[key]) for key in self._order)

    def __setitem__(self, key, object):
        foo = self.has_key(key)
        # Then do whatever containers normally do.
        super(OrderedContainer, self).__setitem__(key, object)
        if not foo:
            self._order.append(key)

    def __delitem__(self, key):
        # First do whatever containers normally do.
        super(OrderedContainer, self).__delitem__(key)
        self._order.remove(key)

    def updateOrder(self, order):
        """Impose a new order on the items in this container.

        Items in this container are, by default, returned in the order
        in which they were inserted.  To change the order, provide an
        argument to this method that is a sequence containing every key
        already in the container, but in a new order.

        """
        if set(order) != set(self._order):
            raise ValueError("Incompatible key set.")

        self._order = PersistentList()
        self._order.extend(order)
        notifyContainerModified(self)
Beispiel #36
0
class ViewletsForType(Persistent):
    def __init__(self):
        self.viewlets  = PersistentList()
        self.default = ''
        self.use_default_viewlets = True
        self.use_default_default = True

    def append(self, item):
        if not item in self.viewlets:
            self.viewlets.append(item)
            self.use_default_viewlets = False

    def remove(self, item, force=False):
        if item == self.default:
            if force:
                self.setDefault(None)
            else:
                msg = "Viewlet %s cannot be unregistered :" + \
                      " it is set as default."
                msg = msg % item
                raise CompositePackError, msg
        if item in self.viewlets:
            self.viewlets.remove(item)
        if not self.viewlets:
            self.use_default_viewlets = True

    def getList(self):
        return self.viewlets

    def clearList(self):
        while self.viewlets:
            self.viewlets.pop()
        self.use_default_viewlets = True

    def setDefault(self, item):
        if self.use_default_viewlets or item in self.viewlets or item is None:
            self.default = item
            self.use_default_default = False
        else:
            msg = "Viewlet %s cannot be set as default :" + \
                  " it is not registered."
            msg = msg % item
            raise CompositePackError, msg

    def clearDefault(self):
        self.default = ''
        self.use_default_default = True

    def getDefault(self):
        return self.default

    def queryDefault(self, default=None):
        if self.default:
            return self.default
        else:
            return default
Beispiel #37
0
    def serialize_contacts(self):
        """Returns a persistent list of dicts for all contacts.
        """
        value = PersistentList()
        for item in self.contacts:
            value.append(
                PersistentDict({'id': item.get_contact_id(),
                                'title': item.get_title()}))

        return value
Beispiel #38
0
    def serialize_contacts(self):
        """Returns a persistent list of dicts for all contacts.
        """
        value = PersistentList()
        for item in self.contacts:
            value.append(
                PersistentDict({'id': item.get_contact_id(),
                                'title': item.get_title()}))

        return value
    def __call__(self):
        req = self.request
        settings = Settings(self.context)
        annotations = settings.annotations
        if annotations is None:
            annotations = PersistentDict()
            settings.annotations = annotations

        sections = settings.sections
        if sections is None:
            sections = PersistentList()
            settings.sections = sections

        action = req.form['action']
        if action == 'addannotation':
            page = int(req.form['page'])
            if page not in annotations:
                annotations[page] = PersistentList()

            pageann = annotations[page]
            data = {
                "id": random.randint(1, 9999999),
                "coord": req.form['coord'],
                "title": req.form.get('title', ''),
                "content": req.form.get('content', '')}
            pageann.append(data)
            return json.dumps(data)
        elif action == 'removeannotation':
            page = int(req.form['page'])
            if page in annotations:
                ann_id = int(req.form['id'])
                found = False
                annotations = annotations[page]
                for ann in annotations:
                    if ann['id'] == ann_id:
                        found = ann
                        break

                if found:
                    annotations.remove(found)

        elif action == 'addsection':
            data = {
                'page': req.form['page'],
                'title': req.form['title']
            }
            sections.append(data)
            return json.dumps(data)
        elif action == 'removesection':
            data = {
                'page': req.form['page'],
                'title': req.form['title']
            }
            if data in sections:
                sections.remove(data)
    def __call__(self):
        req = self.request
        settings = Settings(self.context)
        annotations = settings.annotations
        if annotations is None:
            annotations = PersistentDict()
            settings.annotations = annotations

        sections = settings.sections
        if sections is None:
            sections = PersistentList()
            settings.sections = sections

        action = req.form['action']
        if action == 'addannotation':
            page = int(req.form['page'])
            if page not in annotations:
                annotations[page] = PersistentList()

            pageann = annotations[page]
            data = {
                "id": random.randint(1, 9999999),
                "coord": req.form['coord'],
                "title": req.form.get('title', ''),
                "content": req.form.get('content', '')}
            pageann.append(data)
            return json.dumps(data)
        elif action == 'removeannotation':
            page = int(req.form['page'])
            if page in annotations:
                ann_id = int(req.form['id'])
                found = False
                annotations = annotations[page]
                for ann in annotations:
                    if ann['id'] == ann_id:
                        found = ann
                        break

                if found:
                    annotations.remove(found)

        elif action == 'addsection':
            data = {
                'page': req.form['page'],
                'title': req.form['title']
            }
            sections.append(data)
            return json.dumps(data)
        elif action == 'removesection':
            data = {
                'page': req.form['page'],
                'title': req.form['title']
            }
            if data in sections:
                sections.remove(data)
Beispiel #41
0
class Guestbook(grok.Model):
    meta_type = "guestbook"

    def __init__(self, id):
        super(Guestbook, self).__init__(id)
        self.comments = PersistentList()

    def add_comment(self, name, comment):
        self.comments.append(dict(name=name.decode('utf-8'),
                                  comment=comment.decode('utf-8'),
                                  created_at=datetime.now()))
Beispiel #42
0
    def _add_user_map(self, token):
        if not token.access or token.user is None:
            return

        # only tracking access tokens with user defined.
        user_tokens = self._user_token_map.get(token.user, None)
        if user_tokens is None:
            user_tokens = PersistentList()
            self._user_token_map[token.user] = user_tokens

        user_tokens.append(token.key)
class NyPortalLanguageManager(Persistent):

    implements(ILanguageAvailability)

    def __init__(self, default_langs=[('en', 'English')]):
        if not isinstance(default_langs, list):
            raise ValueError("Default languages must be a list of touples"
                             " (code, name)")
        self.portal_languages = PersistentList(default_langs)

    def getAvailableLanguages(self):
        """Return a sequence of language tags for available languages
        """
        return tuple([ x[0] for x in self.portal_languages ])

    def addAvailableLanguage(self, lang_code, lang_name=None):
        """Adds available language in portal"""
        lang_code = normalize_code(lang_code)
        if not lang_name:
            n = NyLanguages()
            lang_name = n.get_language_name(lang_code)
        if lang_code not in self.getAvailableLanguages():
            self.portal_languages.append((lang_code, lang_name))

    def delAvailableLanguage(self, lang):
        lang = normalize_code(lang)
        pos = list(self.getAvailableLanguages()).index(lang)
        if pos > -1:
            if len(self.getAvailableLanguages()) == 1:
                raise ValueError("Can not delete the only available language")
            else:
                self.portal_languages.pop(pos)

    # MORE:
    def set_default_language(self, lang):
        lang = normalize_code(lang)
        if lang not in self.getAvailableLanguages():
            raise ValueError("Language %s is not provided by portal" % lang)
        available = list(self.getAvailableLanguages())
        if len(available)==1:
            return
        pos = available.index(lang)
        new_default = self.portal_languages.pop(pos)
        self.portal_languages.insert(0, new_default)

    def get_default_language(self):
        return self.portal_languages[0][0]

    def get_language_name(self, code):
        pos = list(self.getAvailableLanguages()).index(code)
        if pos > -1:
            return self.portal_languages[pos][1]
        else:
            return "???"
Beispiel #44
0
 def __iadd__(self, other):
     if isinstance(other, PSetList):
         return PSetList(self.sets + other.sets)
     elif isinstance(other, (PersistentList, list, tuple)):
         return PSetList(self.sets + other)
     elif isinstance(other, PSet):
         new_sets = PersistentList(self.sets)
         new_sets.append(other)
         return PSetList(new_sets)
     else:
         raise TypeError
Beispiel #45
0
class NyPortalLanguageManager(Persistent):

    implements(ILanguageAvailability)

    def __init__(self, default_langs=[('en', 'English')]):
        if not isinstance(default_langs, list):
            raise ValueError("Default languages must be a list of touples"
                             " (code, name)")
        self.portal_languages = PersistentList(default_langs)

    def getAvailableLanguages(self):
        """Return a sequence of language tags for available languages
        """
        return tuple([x[0] for x in self.portal_languages])

    def addAvailableLanguage(self, lang_code, lang_name=None):
        """Adds available language in portal"""
        lang_code = normalize_code(lang_code)
        if not lang_name:
            n = NyLanguages()
            lang_name = n.get_language_name(lang_code)
        if lang_code not in self.getAvailableLanguages():
            self.portal_languages.append((lang_code, lang_name))

    def delAvailableLanguage(self, lang):
        lang = normalize_code(lang)
        pos = list(self.getAvailableLanguages()).index(lang)
        if pos > -1:
            if len(self.getAvailableLanguages()) == 1:
                raise ValueError("Can not delete the only available language")
            else:
                self.portal_languages.pop(pos)

    # MORE:
    def set_default_language(self, lang):
        lang = normalize_code(lang)
        if lang not in self.getAvailableLanguages():
            raise ValueError("Language %s is not provided by portal" % lang)
        available = list(self.getAvailableLanguages())
        if len(available) == 1:
            return
        pos = available.index(lang)
        new_default = self.portal_languages.pop(pos)
        self.portal_languages.insert(0, new_default)

    def get_default_language(self):
        return self.portal_languages[0][0]

    def get_language_name(self, code):
        pos = list(self.getAvailableLanguages()).index(code)
        if pos > -1:
            return self.portal_languages[pos][1]
        else:
            return "???"
def recording_event_subscriber(*args):
    site = getSite()
    if not hasattr(site, EVENT_RECORD_ATTRIBUTE_NAME):
        events = PersistentList()
        setattr(site, EVENT_RECORD_ATTRIBUTE_NAME, events)
    else:
        events = getattr(site, EVENT_RECORD_ATTRIBUTE_NAME)

    if len(args) == 1:
        events.append(args[0])
    else:
        events.append(args)
 def setUp(self):
     BoKeepBasicTestSetup.setUp(self)
     p_list_1 = PersistentList()
     p_list_2 = PersistentList()
     timelog = Timesheet(1, 2, 3)
     p_list_1.append(timelog)
     p_list_2.append(timelog)
     self.books.get_dbhandle().set_sub_database(
         'haha', (p_list_1, p_list_2) )
     self.books.close()
     self.books_new = create_filestorage_backed_bookset_from_file(
         self.filestorage_file, False)
 def setCheckMailCallback(self, validator, position=None):
     """Add the validator to the callback chain at the correct position.
     If no position is passed, just append it to the end of the chain.
     """
     chain = getattr(self, '_check_mail_callback_chain', None)
     if chain is None:
         chain = PersistentList()
         self._check_mail_callback_chain = chain
     if position is None:
         chain.append(validator)
     else:
         chain.insert(position, validator)
def recording_event_subscriber(*args):
    site = getSite()
    if not hasattr(site, EVENT_RECORD_ATTRIBUTE_NAME):
        events = PersistentList()
        setattr(site, EVENT_RECORD_ATTRIBUTE_NAME, events)
    else:
        events = getattr(site, EVENT_RECORD_ATTRIBUTE_NAME)

    if len(args) == 1:
        events.append(args[0])
    else:
        events.append(args)
Beispiel #50
0
class LimitedCardinality(MultiInstanceAction):
    def __init__(self, workitem, **kwargs):
        super(LimitedCardinality, self).__init__(workitem, **kwargs)
        self.instances = PersistentList()
        self.numberOfInstances = self.loopCardinality.__func__(self.process)
        for instance_num in range(self.numberOfInstances):
            #@TODO solution plus simple
            ActionInstance._init_attributes_(ActionInstance, self)
            instance = ActionInstance(instance_num, self, workitem)
            self.workitem.add_action(instance)
            self.instances.append(instance_num)

        self.isexecuted = True
Beispiel #51
0
    def serialize_documents(self):
        """Returns a persistent list of dicts with the following data for for
        all documents:

        id: oguid
        title: document title
        """
        value = PersistentList()
        for doc in self.documents:
            value.append(PersistentDict(
                {'id': Oguid.for_object(doc).id, 'title': doc.title}))

        return value
class InviteTicket(Folder, WorkflowAware):
    """ Invite ticket. Send these to give access to new users.
        See :mod:`voteit.core.models.interfaces.IInviteTicket`.
        All methods are documented in the interface of this class.
    """
    implements(IInviteTicket)
    content_type = 'InviteTicket'
    allowed_contexts = () #Not addable through regular forms
    add_permission = None
    #No schemas
    
    def __init__(self, email, roles, message = u"", sent_by = None):
        self.email = email.lower()
        for role in roles:
            if role not in SELECTABLE_ROLES:
                raise ValueError("InviteTicket got '%s' as a role, and that isn't selectable." % role)
        self.roles = roles
        assert isinstance(message, basestring)
        self.message = message
        self.created = utcnow()
        self.closed = None
        self.claimed_by = None
        self.sent_by = sent_by
        self.token = ''.join([choice(string.letters + string.digits) for x in range(30)])
        self.sent_dates = PersistentList()
        self.uid = unicode(uuid4())
        super(InviteTicket, self).__init__()

    def send(self, request, message = u""):
        if self.closed: #Just as a precaution
            return
        meeting = find_interface(self, IMeeting)
        html = render_view_action(self, request, 'email', 'invite_ticket', message = message)
        subject = _(u"Invitation to ${meeting_title}", mapping = {'meeting_title': meeting.title})
        if send_email(subject = subject, recipients = self.email, html = html, request = request, send_immediately = True):
            self.sent_dates.append(utcnow())

    def claim(self, request):
        #Is the ticket open?
        if self.get_workflow_state() != 'open':
            raise Forbidden("Access already granted with this ticket")
        #Find required resources and do some basic validation
        meeting = find_interface(self, IMeeting)
        assert meeting
        userid = authenticated_userid(request)
        if userid is None:
            raise Forbidden("You can't claim a ticket unless you're authenticated.")
        meeting.add_groups(userid, self.roles)
        self.claimed_by = userid
        self.set_workflow_state(request, 'closed')
        self.closed = utcnow()
Beispiel #53
0
class Player(Persistent):
    """
    A Player plays matches. He is local to a Game, so a single physical Person could be two distinct 'Player' objects.
    This is because the Player has a skill rating associated with it, which only makes sense for
    his skill in a single game.
    """
    def __init__(self, name):
        self.name = name
        # Trueskill Rating for this player
        self._rating = trueskill.Rating()
        # List of matches this player participated in
        self.matches = PersistentList()
        # History of skill
        self.history = PersistentList()

    def add_match(self, match):
        self.matches.append(match)
        self.history.append({
            'match': match,
            'skill': self.skill(),
            'confidence': self.confidence(),
            'exposure': self.exposure()
        })

    def set_rating(self, rating):
        self._rating = rating
        self._p_changed = True

    def get_rating(self):
        return self._rating

    def reset_rating(self):
        self.set_rating(trueskill.Rating())

    def skill(self):
        return self._rating.mu

    def confidence(self):
        return self._rating.sigma

    def exposure(self):
        return trueskill.expose(self._rating)

    def wins(self):
        return [m for m in self.matches if m.won(self)]

    def losses(self):
        return [m for m in self.matches if not m.won(self) and not m.draw()]

    def __repr__(self):
        return self.name
Beispiel #54
0
 def _create_slot(self):
     annotations = IAnnotations(self.portal)
     tiles = PersistentList()
     for _ in range(2):
         tile_id = utils.get_random_string(30)
         annotations[TILE_ANNOTATIONS_KEY_PREFIX + '.' + tile_id] = PersistentDict({
             'foo': 'bar'
         })
         tiles.append({
             'id': tile_id
         })
     annotations[TILE_ANNOTATIONS_KEY_PREFIX + '.' + self.slot_id] = PersistentDict({
         'tiles': tiles
     })
Beispiel #55
0
class Runda(Persistent):
    def __init__(self):
        self.tim1Zvanja = 0
        self.tim2Zvanja = 0
        self.bacanja = PersistentList()
        self.adut = None
        self.timKojiJeZvao = None

    def dodajBacanje(self, bacanje):
        self.bacanja.append(bacanje)

    def postaviAdut(self, boja, tim):
        self.adut = boja
        self.timKojiJeZvao = tim
Beispiel #56
0
    def create_command_list(script_id, commands):
        """
        :param script_id:
        :param commands: list of string
        :return: list of Commands created from given list
        :rtype: PersistentList
        """
        result = PersistentList()
        for source_code in commands:
            command = CommandManagementApplication.create(
                script_id=script_id, source_code=source_code)
            result.append(command)

        return result