コード例 #1
0
ファイル: browser.py プロジェクト: jean/zope.app.apidoc
 def getMenuLink(self, node):
     """Return the HTML link of the node that is displayed in the menu."""
     obj = node.context
     if isinstance(obj, Directive):
         ns = getParent(obj)
         apidoc_url = findAPIDocumentationRootURL(self.context, self.request)
         return '%s/ZCML/%s/%s/index.html' % (
             apidoc_url, getName(ns), getName(obj))
     return None
コード例 #2
0
 def getMenuLink(self, node):
     """Return the HTML link of the node that is displayed in the menu."""
     obj = node.context
     apidoc_url = findAPIDocumentationRootURL(self.context, self.request)
     if isinstance(obj, Utility):
         iface = getParent(obj)
         return '%s/Utility/%s/%s/index.html' % (apidoc_url, getName(iface), getName(obj))
     if isinstance(obj, UtilityInterface):
         return '%s/Interface/%s/index.html' % (apidoc_url, getName(obj))
コード例 #3
0
ファイル: demographics.py プロジェクト: asley/schooltool
 def update(self):
     if 'DONE' in self.request:
         url = absoluteURL(self.context, self.request)
         self.request.response.redirect(url)
     elif 'form-submitted' in self.request:
         for demo in self.context.values():
             name = 'delete.%s' % demo.__name__
             if name in self.request:
                 del self.context[demo.__name__]
                 return
         old_pos, new_pos = 0, 0, False
         for demo in self.context.values():
             old_pos += 1
             name = getName(demo)
             if 'pos.'+name not in self.request:
                 continue
             new_pos = int(self.request['pos.'+name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos-1, new_pos-1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos,moving)
         self.context.updateOrder(keys)
コード例 #4
0
 def edit(self,
          email=None,
          lastName=None,
          firstName=None,
          userId=None,
          password=None,
          groups=[]):
     """ """
     obj = self.context
     if email: obj.email = email
     if firstName: obj.firstName = firstName
     if lastName: obj.lastName = lastName
     if userId: obj.userId = userId
     if password: obj.password = password
     if groups is not None:
         name = getName(obj)
         gs = self.context.getYeepa().getGroupSource()
         oldGroups = self.context.getGroupNames()
         for g in oldGroups:
             if g not in groups:
                 gs.getGroup(g).removeMember(name)
         for g in groups:
             if g not in oldGroups:
                 gs.getGroup(g).addMember(name)
     return 'OK'
コード例 #5
0
 def getMembers(self):
     """ """
     userSource = self.context.getYeepa().getUserSource()
     name = getName(self.context)
     users = [u for u in userSource.getUsers(name)]
     return sorted((userAsDict(user) for user in users),
                   key=lambda x: x['nickName'])
コード例 #6
0
ファイル: table.py プロジェクト: Zojax/zojax.content.browser
    def pasteObjectLinks(self):
        """Paste oject links in the user clipboard to the container """
        target = self.context
        clipboard = getPrincipalClipboard(self.request)
        items = clipboard.getContents()
        moved = False
        not_pasteable_ids = []
        for item in items:
            duplicated_id = False
            try:
                obj = traverse(target, item['target'])
            except TraversalError:
                pass
            else:
                if item['action'] == 'copy':
                    linker = IObjectLinker(removeAllProxies(obj))
                    try:
                        linker.linkTo(target)
                    except DuplicateIDError:
                        duplicated_id = True
                else:
                    raise

            if duplicated_id:
                not_pasteable_ids.append(getName(obj))

        if moved:
            clipboard.clearContents()

        if not_pasteable_ids:
            abort()
            IStatusMessage(self.request).add(
                _("The given name(s) %s is / are already being used" % (
                    str(not_pasteable_ids))), 'error')
コード例 #7
0
 def setBody(self, body):
     """ """
     name = getName(self.context)
     if name and identPattern in body:
         body = body.replace(identPattern, name)
     self.context.body = body
     return 'OK'
コード例 #8
0
 def getMembers(self):
     """ """
     userSource = self.context.getYeepa().getUserSource()
     name = getName(self.context)
     users = [u for u in userSource.getUsers(name)]
     return sorted((userAsDict(user) for user in users),
                   key=lambda x: x['nickName'])
コード例 #9
0
    def getContextHelpTopic(self):
        """Retrieve a help topic based on the context of the
        help namespace.

        If the context is a view, try to find
        a matching help topic for the view and its context.
        If no help topic is found, try to get a help topic for
        the context only.

        If the context is not a view, try to retrieve a help topic
        based on the context.

        If nothing is found, return the onlinehelp root topic
        """
        if self.topic is not None:
            return self.topic

        onlinehelp = self.context
        help_context = onlinehelp.context
        self.topic = None
        if IBrowserView.providedBy(help_context):
            # called from a view
            self.topic = getTopicFor(getParent(help_context),
                                     getName(help_context))
            if self.topic is None:
                # nothing found for view try context only
                self.topic = getTopicFor(getParent(help_context))
        else:
            # called without view
            self.topic = getTopicFor(help_context)

        if self.topic is None:
            self.topic = onlinehelp

        return self.topic
コード例 #10
0
 def setBody(self, body):
     """ """
     name = getName(self.context)
     if name and identPattern in body:
         body = body.replace(identPattern, name)
     self.context.body = body
     return 'OK'
コード例 #11
0
ファイル: browser.py プロジェクト: jean/z3c.contents
    def handleCut(self, action):
        if not len(self.selectedItems):
            self.status = self.cutNoItemsMessage
            return

        items = []
        append = items.append
        for obj in self.selectedItems:
            mover = IObjectMover(obj)
            __name__ = api.getName(obj)
            if not mover.moveable():
                m = {"name": __name__}
                if name:
                    m["name"] = __name__
                    self.status = _(
                        "Object '${name}' (${name}) cannot be moved",
                        mapping=m)
                else:
                    self.status = _("Object '${name}' cannot be moved",
                                   mapping=m)
                transaction.doom()
                return
            append(api.joinPath(api.getPath(self.context), __name__))

        self.status = self.cutItemsSelected
        # store the requested operation in the principal annotations:
        self.clipboard.clearContents()
        self.clipboard.addItems('cut', items)
コード例 #12
0
 def update(self):
     if 'DONE' in self.request:
         url = absoluteURL(self.context, self.request)
         self.request.response.redirect(url)
     elif 'form-submitted' in self.request:
         for demo in self.context.values():
             name = 'delete.%s' % demo.__name__
             if name in self.request:
                 del self.context[demo.__name__]
                 return
         old_pos, new_pos = 0, 0, False
         for demo in self.context.values():
             old_pos += 1
             name = getName(demo)
             if 'pos.' + name not in self.request:
                 continue
             new_pos = int(self.request['pos.' + name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos - 1, new_pos - 1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos, moving)
         self.context.updateOrder(keys)
コード例 #13
0
ファイル: evaluation.py プロジェクト: mleist/ict-ok.org
 def getEvaluationsOfEvaluator(self, evaluator):
     """See interfaces.IEvaluations"""
     result = [(name, ev) for name, ev in self.items()
               if ev.evaluator == evaluator]
     result = Evaluations(result)
     location.locate(result, getParent(self), getName(self))
     return result
コード例 #14
0
def asDictionary(session):
    return {'ident': str(getName(session)),
            'title': session.title,
            'type': 'assessment',
            'sessionFormat': session.sessionFormat,
            'state': session.state,
            'duration': [session.duration, session.durationUnit]}
コード例 #15
0
def update_object(obj, data, includeOnly=None):
    logUpdate = data.get('_log_update', True)
    ident = (data.get('_identifier')
             or getattr(obj, 'identifier', getName(baseObject(obj))))
    changedValues = {}
    for attr, nv in data.items():
        if attr.startswith('_'):
            continue
        if includeOnly is not None and attr not in includeOnly:
            continue
        if isinstance(nv, Error):
            logger.warn('update_object error: %s: %s %s' % (ident, attr, nv))
            return 'error'
        if nv is _invalid:
            continue
        ov = getattr(obj, attr)
        if nv != ov:
            changedValues[attr] = (ov, nv)
            setattr(obj, attr, nv)
    if changedValues:
        if logUpdate:
            logger.info('update_object %s: %s' % (ident, changedValues))
        # TODO: notify(ObjectModifiedEvent())
        return 'updated'
    return None
コード例 #16
0
 def subItems(self):
     """Collect all tree items for the given context."""
     items = []
     keys = []
     append = items.append
     if IReadContainer.providedBy(self.context):
         try:
             keys = list(self.context.keys())
         except(Unauthorized, Forbidden):
             return items
     else:
         return items
     counter = 1
     for name in keys:
         # Only include items we can traverse to
         subItem = api.traverse(self.context, name, None)
         if subItem is not None:
             append((api.getName(subItem), subItem,
                 self._hasSubItems(subItem)))
         counter += 1
         if counter == self.maxItems:
             # add context which should support a item listing view with 
             # batch
             lenght = len(keys) - self.maxItems
             default = '[%s more items...]' % lenght
             name = zope.i18n.translate(
                 _('[${lenght} more items...]', mapping={'lenght':lenght}),
                 context=self.request, default=default)
             append((name, self.context, False))
             break
     return items
コード例 #17
0
def userAsDict(user):
    #return dict(ident=getName(user), nickName=user.nickName,
    return dict(ident=getName(user), nickName=user.nickName,
                title=user.title, email=user.email,
                userId=user.userId,
                firstName=user.firstName, lastName=user.lastName,
                groups=sorted(user.getGroupNames()),
               )
コード例 #18
0
 def getMenuTitle(self, node):
     """Return the title of the node that is displayed in the menu."""
     obj = node.context
     if isinstance(obj, UtilityInterface):
         return getName(obj).split('.')[-1]
     if obj.name == NONAME:
         return 'no name'
     return obj.name
コード例 #19
0
ファイル: evaluation.py プロジェクト: mleist/ict-ok.org
 def getEvaluationsForRequirement(self, req, recurse=True):
     """See interfaces.IEvaluations"""
     requirements = getRequirementList(req, recurse)
     result = [(name, ev) for name, ev in self.items()
               if ev.requirement in requirements]
     result = Evaluations(result)
     location.locate(result, getParent(self), getName(self))
     return result
コード例 #20
0
ファイル: browser.py プロジェクト: aclark4life/worldcookery
 def __call__(self):
     filename = getName(self.context) + '.pdf'
     response = self.request.response
     response.setHeader('Content-Disposition',
                        'attachment; filename=%s' % filename)
     response.setHeader('Content-Type', 'application/pdf')
     return getMultiAdapter((self.context, self.request),
                            IPDFPresentation)
コード例 #21
0
 def getItems(self, topic=None):
     """ Return a sequence of dictionaries for all items.
     """
     return sorted([{'ident': getName(item),
                     'title': self.getItemTitle(item),
                     'dimensions': item.getImageSize(),
                     'size': item.getSize()}
                         for item in self.context.values()],
                   lambda a, b: cmp(a['title'], b['title']))
コード例 #22
0
ファイル: browser.py プロジェクト: jean/zope.app.apidoc
 def getMenuTitle(self, node):
     """Return the title of the node that is displayed in the menu."""
     obj = node.context
     if isinstance(obj, Namespace):
         name = obj.getShortName()
         if name == 'ALL':
             return 'All Namespaces'
         return name
     return getName(obj)
コード例 #23
0
 def getScripts(self):
     """ Return a list of dictionaries with the scripts in this
         script container.
     """
     scripts = self.context.getItems()
     return [dict(name=getName(s),
                  title=s.title or u'',
                  parameters=s.parameters or u'')
             for s in scripts]
コード例 #24
0
def asDictionary(session):
    return {
        'ident': str(getName(session)),
        'title': session.title,
        'type': 'assessment',
        'sessionFormat': session.sessionFormat,
        'state': session.state,
        'duration': [session.duration, session.durationUnit]
    }
コード例 #25
0
ファイル: media.py プロジェクト: macagua/eduIntelligent-cynin
 def getItems(self, topic=None):
     """ Return a sequence of dictionaries for all items.
     """
     return sorted([{
         'ident': getName(item),
         'title': self.getItemTitle(item),
         'dimensions': item.getImageSize(),
         'size': item.getSize()
     } for item in self.context.values()],
                   lambda a, b: cmp(a['title'], b['title']))
コード例 #26
0
 def getScripts(self):
     """ Return a list of dictionaries with the scripts in this
         script container.
     """
     scripts = self.context.getItems()
     return [
         dict(name=getName(s),
              title=s.title or u'',
              parameters=s.parameters or u'') for s in scripts
     ]
コード例 #27
0
def userAsDict(user):
    #return dict(ident=getName(user), nickName=user.nickName,
    return dict(
        ident=getName(user),
        nickName=user.nickName,
        title=user.title,
        email=user.email,
        userId=user.userId,
        firstName=user.firstName,
        lastName=user.lastName,
        groups=sorted(user.getGroupNames()),
    )
コード例 #28
0
    def getId(self):
        """Return the id of the field as it is defined for the interface
        utility.

        Example::

          >>> from tests import getInterfaceDetails
          >>> details = getInterfaceDetails()
          >>> details.getId()
          'IFoo'
        """
        return getName(self.context)
コード例 #29
0
 def findByIds(self, ids):
     """Do a find for the `ids` listed in `ids`, which is a string."""
     finder = IFind(self.context)
     ids = ids.split()
     # if we don't have any ids listed, don't search at all
     if not ids:
         return []
     request = self.request
     result = []
     for object in finder.find([SimpleIdFindFilter(ids)]):
         url = absoluteURL(object, request)
         result.append({'id': getName(object), 'url': url})
     return result
コード例 #30
0
 def findByIds(self, ids):
     """Do a find for the `ids` listed in `ids`, which is a string."""
     finder = IFind(self.context)
     ids = ids.split()
     # if we don't have any ids listed, don't search at all
     if not ids:
         return []
     request = self.request
     result = []
     for object in finder.find([SimpleIdFindFilter(ids)]):
         url = absoluteURL(object, request)
         result.append({ 'id': getName(object), 'url': url})
     return result
コード例 #31
0
    def __call__(self):
        ids = getUtility(IIntIds)

        data = []
        for name, link in IAttachmentsExtension(self.context).items():
            if ILink.providedBy(link) and link:
                title = link.title or getName(link)
                data.append((title,  link.url))

        data.sort()
        js_encoded = encoder.encode(data)

        return """tinyMCELinkList = new Array(%s);""" % js_encoded[1:-1]
コード例 #32
0
    def __call__(self):
        ids = getUtility(IIntIds)

        data = []
        for name, image in IAttachmentsExtension(self.context).items():
            if IImage.providedBy(image) and image:
                id = ids.queryId(removeAllProxies(image))
                title = image.title or getName(image)
                data.append((title,  '@@content.attachment/%s' % id))

        data.sort()
        js_encoded = encoder.encode(data)

        return """tinyMCEImageList = new Array(%s);""" % js_encoded[1:-1]
コード例 #33
0
    def __call__(self):
        ids = getUtility(IIntIds)

        data = []
        for name, file in IAttachmentsExtension(self.context).items():
            if IFile.providedBy(file) and file:
                id = ids.queryId(removeAllProxies(file))
                title = file.title or getName(file)
                data.append((title,  '++attachment++%s' % id))

        data.sort()
        js_encoded = encoder.encode(data)

        return """tinyMCEMediaList = new Array(%s);""" % js_encoded[1:-1]
コード例 #34
0
 def activities(self):
     pos = 0
     for activity in list(self.context.values()):
         pos += 1
         url = absoluteURL(activity, self.request)
         if interfaces.ILinkedColumnActivity.providedBy(activity):
             url += '/editLinkedColumn.html'
         yield {
             'name': getName(activity),
             'title': activity.title,
             'url': url,
             'pos': pos,
             'deployed': self.context.deployed
         }
コード例 #35
0
ファイル: browser.py プロジェクト: jean/z3c.contents
    def handlePaste(self, action):
        items = self.clipboard.getContents()
        moved = False
        not_pasteable_ids = []
        for item in items:
            duplicated_id = False
            try:
                obj = api.traverse(self.context, item['target'])
            except TraversalError:
                pass
            else:
                if item['action'] == 'cut':
                    mover = IObjectMover(obj)
                    try:
                        mover.moveTo(self.context)
                        moved = True
                    except DuplicateIDError:
                        duplicated_id = True
                elif item['action'] == 'copy':
                    copier = IObjectCopier(obj)
                    try:
                        copier.copyTo(self.context)
                    except DuplicateIDError:
                        duplicated_id = True
                else:
                    raise

            if duplicated_id:
                not_pasteable_ids.append(api.getName(obj))

        if moved:
            # Clear the clipboard if we do a move, but not if we only do a copy
            self.clipboard.clearContents()

        if not_pasteable_ids != []:
            # Show the ids of objects that can't be pasted because
            # their ids are already taken.
            # TODO Can't we add a 'copy_of' or something as a prefix
            # instead of raising an exception ?
            transaction.doom()
            raise UserError(
                _("The given name(s) %s is / are already being used" % (
                    str(not_pasteable_ids))))
        else:
            # we need to update the table rows again, otherwise we don't
            # see the new item in the table
            self.updateAfterActionExecution()
            self.status = self.pasteSucsessMessage
コード例 #36
0
 def getItems(self, topic=None, typeName='content'):
     """ Return a sequence of dictonaries for all selected items.
     """
     topics = topic and [topic] or None
     result = []
     for node in self.context.getNodes(topics, typeName):
         entry = dict(ident=getName(node),
                      title=node.title,
                      body=node.body,
                      topics=sorted(node.topics),
                      references=sorted(node.references))
         if typeName == 'reference':
             entry['pages'] = node.pages
             entry['url'] = node.url
         result.append(entry)
     return sorted(result,  lambda a, b: cmp(a['title'], b['title']))
コード例 #37
0
 def getItems(self, topic=None, typeName='content'):
     """ Return a sequence of dictonaries for all selected items.
     """
     topics = topic and [topic] or None
     result = []
     for node in self.context.getNodes(topics, typeName):
         entry = dict(ident=getName(node),
                      title=node.title,
                      body=node.body,
                      topics=sorted(node.topics),
                      references=sorted(node.references))
         if typeName == 'reference':
             entry['pages'] = node.pages
             entry['url'] = node.url
         result.append(entry)
     return sorted(result, lambda a, b: cmp(a['title'], b['title']))
コード例 #38
0
ファイル: contents.py プロジェクト: CGTIC/Plone_SP
    def pasteObjects(self):
        """Paste ojects in the user clipboard to the container
        """
        target = self.context
        clipboard = getPrincipalClipboard(self.request)
        items = clipboard.getContents()
        moved = False
        not_pasteable_ids = []
        for item in items:
            duplicated_id = False
            try:
                obj = traverse(target, item['target'])
            except TraversalError:
                pass
            else:
                if item['action'] == 'cut':
                    mover = IObjectMover(obj)
                    try:
                        mover.moveTo(target)
                        moved = True
                    except DuplicateIDError:
                        duplicated_id = True
                elif item['action'] == 'copy':
                    copier = IObjectCopier(obj)
                    try:
                        copier.copyTo(target)
                    except DuplicateIDError:
                        duplicated_id = True
                else:
                    raise

            if duplicated_id:
                not_pasteable_ids.append(getName(obj))

        if moved:
            # Clear the clipboard if we do a move, but not if we only do a copy
            clipboard.clearContents()

        if not_pasteable_ids != []:
            # Show the ids of objects that can't be pasted because
            # their ids are already taken.
            # TODO Can't we add a 'copy_of' or something as a prefix
            # instead of raising an exception ?
            raise UserError(
                _("The given name(s) %s is / are already being used" %(
                str(not_pasteable_ids))))
コード例 #39
0
    def pasteObjects(self):
        """Paste ojects in the user clipboard to the container
        """
        target = self.context
        clipboard = getPrincipalClipboard(self.request)
        items = clipboard.getContents()
        moved = False
        not_pasteable_ids = []
        for item in items:
            duplicated_id = False
            try:
                obj = traverse(target, item['target'])
            except TraversalError:
                pass
            else:
                if item['action'] == 'cut':
                    mover = IObjectMover(obj)
                    try:
                        mover.moveTo(target)
                        moved = True
                    except DuplicateIDError:
                        duplicated_id = True
                elif item['action'] == 'copy':
                    copier = IObjectCopier(obj)
                    try:
                        copier.copyTo(target)
                    except DuplicateIDError:
                        duplicated_id = True
                else:
                    raise

            if duplicated_id:
                not_pasteable_ids.append(getName(obj))

        if moved:
            # Clear the clipboard if we do a move, but not if we only do a copy
            clipboard.clearContents()

        if not_pasteable_ids != []:
            # Show the ids of objects that can't be pasted because
            # their ids are already taken.
            # TODO Can't we add a 'copy_of' or something as a prefix
            # instead of raising an exception ?
            raise UserError(
                _("The given name(s) %s is / are already being used" %
                  (str(not_pasteable_ids))))
コード例 #40
0
 def createUser(self, nickName, email=None, userId=None, password=None,
                lastName=None, firstName=None, groups=[]):
     """ """
     obj = self.context.createUser(nickName)
     obj.email = email or u''
     obj.userId = userId or u''
     obj.password = password or u''
     obj.firstName = firstName or u''
     obj.lastName = lastName or u''
     name = getName(obj)
     if groups:
         gs = self.context.getYeepa().getGroupSource()
         for g in groups:
             group = gs.getGroup(g)
             if group is not None:
                 group.addMember(name)
     return name
コード例 #41
0
class Index(mars.view.PageletView):
    grok.context(IRootFolder)
    grok.require(permissions.MANAGESITE)
    title = _("Tree Fern Web Site Demo")

    columns = (
        table.CheckboxColumn(_('Sel')),
        column.GetterColumn(_('Id'), lambda item, f: api.getName(item),
                            table.link('index', _('View'))),
        column.GetterColumn(_('Title'), lambda item, f: item.title,
                            table.link('edit', _('Edit'))),
        column.GetterColumn(_('Created On'), table.getCreatedDate),
        column.GetterColumn(_('Modified On'), table.getModifiedDate),
    )

    status = None

    def table(self):
        formatter = AlternatingRowFormatter(self.context,
                                            self.request,
                                            self.items,
                                            columns=self.columns)
        formatter.widths = [25, 50, 300, 100, 100]
        formatter.cssClasses['table'] = 'list'
        return formatter()

    def update(self):
        self.items = [
            obj for obj in self.context.values()
            if interfaces.IWebSite.providedBy(obj)
        ]
        if 'ADD' in self.request:
            self.request.response.redirect('add')
        if 'DELETE' in self.request:
            if self.request.get('confirm_delete') != 'yes':
                self.status = _('You did not confirm the deletion correctly.')
                return
            if 'selected' in self.request:
                for id in self.request['selected']:
                    self.items.remove(self.context[id])
                    del self.context[id]
                self.status = _('Sites were successfully deleted.')
            else:
                self.status = _('No sites were selected.')
コード例 #42
0
 def edit(self, email=None, lastName=None, firstName=None,
          userId=None, password=None, groups=[]):
     """ """
     obj = self.context
     if email: obj.email = email
     if firstName: obj.firstName = firstName
     if lastName: obj.lastName = lastName
     if userId: obj.userId = userId
     if password: obj.password = password
     if groups is not None:
         name = getName(obj)
         gs = self.context.getYeepa().getGroupSource()
         oldGroups = self.context.getGroupNames()
         for g in oldGroups:
             if g not in groups:
                 gs.getGroup(g).removeMember(name)
         for g in groups:
             if g not in oldGroups:
                 gs.getGroup(g).addMember(name)
     return 'OK'
コード例 #43
0
 def update(self):
     if 'DELETE' in self.request:
         for name in self.request.get('delete', []):
             del self.context[name]
     elif 'form-submitted' in self.request:
         old_pos, new_pos = 0, 0, False
         for activity in self.context.values():
             old_pos += 1
             name = getName(activity)
             if 'pos.' + name not in self.request:
                 continue
             new_pos = int(self.request['pos.' + name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos - 1, new_pos - 1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos, moving)
         self.context.updateOrder(keys)
コード例 #44
0
ファイル: demographics.py プロジェクト: asley/schooltool
 def update(self):
     if 'DELETE' in self.request:
         for name in self.request.get('delete', []):
             del self.context[name]
     elif 'form-submitted' in self.request:
         old_pos, new_pos = 0, 0, False
         for activity in self.context.values():
             old_pos += 1
             name = getName(activity)
             if 'pos.'+name not in self.request:
                 continue
             new_pos = int(self.request['pos.'+name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos-1, new_pos-1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos,moving)
         self.context.updateOrder(keys)
コード例 #45
0
    def update(self):
        self.person = IPerson(self.request.principal, None)
        if self.person is None:
            # XXX ignas: i had to do this to make the tests pass,
            # someone who knows what this code should do if the user
            # is unauthenticated should add the relevant code
            raise Unauthorized("You don't have the permission to do this.")

        if 'DELETE' in self.request:
            for name in self.request.get('delete', []):
                del self.context[name]
        elif 'form-submitted' in self.request:
            old_pos = 0
            for activity in self.context.values():
                old_pos += 1
                name = getName(activity)
                if 'pos.' + name not in self.request:
                    continue
                new_pos = int(self.request['pos.' + name])
                if new_pos != old_pos:
                    self.context.changePosition(name, new_pos - 1)
コード例 #46
0
ファイル: utilities.py プロジェクト: jean/zope.app.apidoc
    def __call__(self):
        """Create breadcrumbs for a module or an object in a module or package.

        We cannot reuse the system's bread crumbs, since they go all the
        way up to the root, but we just want to go to the root module.
        """
        obj = self.context
        crumbs = []
        while not IDocumentationModule.providedBy(obj):
            crumbs.append(
                {'name': getName(obj),
                 'url': absoluteURL(obj, self.request)}
                )
            obj = getParent(obj)

        crumbs.append(
            {'name': _('[top]'),
             'url': absoluteURL(obj, self.request)}
            )
        crumbs.reverse()
        return crumbs
コード例 #47
0
 def createUser(self,
                nickName,
                email=None,
                userId=None,
                password=None,
                lastName=None,
                firstName=None,
                groups=[]):
     """ """
     obj = self.context.createUser(nickName)
     obj.email = email or u''
     obj.userId = userId or u''
     obj.password = password or u''
     obj.firstName = firstName or u''
     obj.lastName = lastName or u''
     name = getName(obj)
     if groups:
         gs = self.context.getYeepa().getGroupSource()
         for g in groups:
             group = gs.getGroup(g)
             if group is not None:
                 group.addMember(name)
     return name
コード例 #48
0
 def name(self):
     return getName(self.context)
コード例 #49
0
ファイル: talesapi.py プロジェクト: grodniewicz/oship
 def title_or_name(self):
     try:
         return getattr(self, 'title', '') or getName(self.context)
     except Unauthorized:
         return getName(self.context)
コード例 #50
0
ファイル: talesapi.py プロジェクト: grodniewicz/oship
 def name(self):
     return getName(self.context)
コード例 #51
0
 def title_or_name(self):
     try:
         return getattr(self, 'title', '') or getName(self.context)
     except Unauthorized:
         return getName(self.context)
コード例 #52
0
 def createItem(self, title=u'', format=''):
     """ """
     obj = self.context.createItem()
     obj.contentType = format
     obj.title = title
     return getName(obj)
コード例 #53
0
 def createAssessment(self, title=u'', topics=[]):
     """ """
     obj = self.context.createItem(title=title, topics=topics)
     return getName(obj)
コード例 #54
0
def getName(item):
    # probably not IPhysicallyLocatable but still could have a __name__
    try:
        return api.getName(item)
    except TypeError as e:
        return item.__name__
コード例 #55
0
 def testGetName(self):
     from zope.traversing.api import getName
     self.assertEqual(getName(self.item), 'item')
コード例 #56
0
 def testGetNameOfRoot(self):
     from zope.traversing.api import getName
     self.assertEqual(
         getName(self.root),
         u'',
     )
コード例 #57
0
ファイル: evaluation.py プロジェクト: mleist/ict-ok.org
 def __call__(self, *args, **kwargs):
     """See interfaces.IEvaluationsQuery"""
     result = Evaluations(self._query(*args, **kwargs))
     location.locate(result, getParent(self.context), getName(self.context))
     return result
コード例 #58
0
ファイル: media.py プロジェクト: macagua/eduIntelligent-cynin
 def createItem(self, title=u'', format=''):
     """ """
     obj = self.context.createItem()
     obj.contentType = format
     obj.title = title
     return getName(obj)
コード例 #59
0
ファイル: members.py プロジェクト: bendavis78/zope
 def anchor(value, item, formatter):
     site = hooks.getSite()
     url = '%s/members/%s/%s' % (absoluteURL(
         site, formatter.request), api.getName(item), view)
     return u'<a href="%s" title="%s">%s</a>' % (url, title, value)
コード例 #60
0
 def getGroups(self):
     """ """
     return sorted(
         dict(ident=getName(group), title=group.title)
         for group in self.context.getGroups())