def __init__(self, code, name, description, base_unit):
		"""Creates a new product"""
		self.code = code
		self.name = name
		self.description = description
		self.bill_of_materials = PersistentDict()
		self.bill_of_activities = PersistentDict()
Example #2
0
class PersistentDictConfigStorage(DictConfigStorage):

    def __init__(self, *a, **kw):
        self._dict = PersistentDict() 
        ConfigStorage.__init__(self, *a, **kw)

    def getDict(self):
        site = getSite()
        if site is not None:
            ann = IAnnotations(site)
            if ASSETS_SETTING_KEY not in ann:
                ann[ASSETS_SETTING_KEY] = self._dict
            return ann[ASSETS_SETTING_KEY]
        return self._dict

    def __getitem__(self, key):
        key = key.lower()
        value = self._get_deprecated(key)
        if not value is None:
            return value
        self._dict = self.getDict()
        return self._dict.__getitem__(key)

    def __setitem__(self, key, value):
        key = key.lower()
        if not self._set_deprecated(key, value):
            self._dict = self.getDict()
            self._dict.__setitem__(key, value)
            self._dict._p_changed = True
Example #3
0
def save_form_in_session(context, request):
    sdm = getToolByName(context, "session_data_manager")
    session = sdm.getSessionData(create=True)
    path = "/".join(context.getPhysicalPath())
    pdict = PersistentDict()
    pdict.update(request.form)
    session.set(path, pdict)
Example #4
0
 def test_rendering_no_nested_links(self):
     obj = PersistentDict({1: PersistentFrob()})
     obj._p_oid = p64(0x18)
     self.assertEqual(
         PersistentDictValue(obj).render(),
         '<a class="objlink" href="@@zodbbrowser?oid=0x18">'
         '{1: &lt;PersistentFrob&gt;}</a>')
Example #5
0
 def __init__(self, name, parent=None):
     PersistentDict.__init__(self)
     PersistentLocationAware.__init__(self, name, parent)
     self.__name__ = name
     if parent is not None:
         parent[name] = self
     self.__parent__ = parent
Example #6
0
 def add(self, data, index=-1):
     """Add data to the storage. Data must the a dict-like structure"""
     row = PersistentDict()
     row.update(data)
     if index>-1:
         self._ann.insert(index, row)
     else:
         self._ann.append(row)
 def __init__(self, id, title):
     """ """
     self.id = id
     self.title = title
     self.config = PersistentDict(self.default_config)
     self.timestamps = PersistentDict()
     # Confirmations list
     self.pending_anonymous_subscriptions = PersistentList()
    def __init__(self, name, title, default_language):
        self.data = PersistentDict()
        self.order = PersistentDict()
        self.count = PersistentDict()
        self.version = PersistentDict()

        self.name = name
        self.title = title
        self.default_language = default_language
    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)
Example #10
0
 def __init__(self, name, description=None, parent=None):
     PersistentDict.__init__(self)
     PersistentLocationAware.__init__(self)
     self.__name__ = name
     self.__parent__ = parent
     if description is None:
         self.description = name
     else:
         self.description = description
     self.preview_picture = None
     self.preview_size = (-1,-1)
Example #11
0
class Amendment(Commentable,
                CorrelableEntity,
                SearchableEntity,
                DuplicableEntity,
                PresentableEntity):
    """Amendment class"""

    icon = 'icon novaideo-icon icon-amendment'
    name = renamer()
    result_template = 'novaideo:views/templates/amendment_result.pt'
    author = SharedUniqueProperty('author')
    proposal = SharedUniqueProperty('proposal', 'amendments')

    def __init__(self, **kwargs):
        super(Amendment, self).__init__(**kwargs)
        self.explanations = PersistentDict()
        self.set_data(kwargs)

   # @region.cache_on_arguments() 
    def get_used_ideas(self):
        """Return used ideas"""

        result = []
        if not hasattr(self, 'explanations'):
            return result

        for explanation in self.explanations.values():
            if explanation['intention'] is not None:
                try:
                    result.extend(
                          Intention.get_explanation_ideas(
                             explanation['intention'])
                          )
                except Exception:
                    pass

        return list(set(result))

    @property
    def related_ideas(self):
        """Return added ideas"""

        result = []
        for explanation in self.explanations.values():
            if explanation['intention'] is not None:
                try:
                    result.extend(
                        Intention.get_explanation_data(
                            explanation['intention'])['related_ideas']
                        )
                except Exception:
                    pass

        return list(set(result))
Example #12
0
    def _fixup(self):
        # due to compatibility reasons this method fixes data structure
        # for old Taxonomy instances.
        # XXX: remove this in version 2.0 to prevent write on read
        if self.order is None:
            safeWrite(self, getRequest())
            self.order = PersistentDict()
            self.count = PersistentDict()

        if self.version is None:
            safeWrite(self, getRequest())
            self.version = PersistentDict()
Example #13
0
    def add_facet(self, name, **kwargs):
        """ Add facet

            >>> _ = visualization.add_facet('country', a=1, b=2)
            >>> facet = visualization.facet('country')
            >>> sorted(facet.items())
            [('a', 1), ('b', 2), ('label', 'country'), ('name', ...]

        """
        config = self._facets()
        kwargs.update({'name': name})
        kwargs.setdefault('type', u'daviz.list.facet')
        facet = PersistentDict(kwargs)
        config.append(facet)
        return facet.get('name', '')
Example #14
0
    def add_view(self, name, **kwargs):
        """ Add view

            >>> _ = visualization.add_view(name='daviz.map',
            ...                     lat='latitude', long='longitude')
            >>> view = visualization.view('daviz.map')
            >>> sorted(view.items())
            [('lat', 'latitude'), ('long', 'longitude'), ('name', 'daviz.map')]

        """
        config = self._views()
        kwargs.update({'name': name})
        view = PersistentDict(kwargs)
        config.append(view)
        return view.get('name', '')
Example #15
0
    def add_source(self, name, **kwargs):
        """ Add source

            >>> _ = visualization.add_source('http://bit.ly/rdf', type='rdf')
            >>> source = visualization.source('http://bit.ly/rdf')
            >>> sorted(source.items())
            [('name', 'http://bit.ly/rdf'), ('type', 'rdf')]

        """
        config = self._sources()
        kwargs.update({'name': name})
        kwargs.setdefault('type', u'json')
        source = PersistentDict(kwargs)
        config.append(source)
        return source.get('name', '')
class Tool(UniqueObject, SimpleItem):
    """
    Contentrules subscription tool
    """
    id = SUBSCRIPTION_TOOL
    meta_type = 'Contentrules Subscription Tool'
    plone_tool = 1

    def __init__(self):
        self.subscriptions = PersistentDict()

    def registerUser(self, rule_id, email):
        """
        Insert the given email address in the given rule_id
        """
        if not rule_id in self.subscriptions:
            self.subscriptions[rule_id] = [email]
        else:
            if email in self.subscriptions[rule_id]:
                factory = getUtility(IVocabularyFactory,
                                     "contentrules.subscription.vocabularies.SubscriptionRulesVocabulary")
                vocabulary = factory(self)
                rule_term = vocabulary.getTerm(rule_id)
                msg = _('already_subscribed_error',
                        default='The given email is already present for "${title}"',
                        mapping=dict(title=rule_term.title))
                return False, msg
            else:
                self.subscriptions[rule_id].append(email)
        return True, ""

    def getSubscriptions(self):
        """
        Return the list of subscriptions
        """
        return self.subscriptions

    def getActionUIDS(self):
        """
        return a list of email addresses for the given rule_id
        """
        return self.subscriptions.keys()

    def getRegisteredList(self, rule_id):
        """
        return a list of email addresses for the given rule_id
        """
        return self.subscriptions.get(rule_id, [])
Example #17
0
    def test_fix_image_field_modification_time(self):
        from persistent.dict import PersistentDict
        title = u'Fix image field modification time'
        step = self._get_upgrade_step(title)
        self.assertIsNotNone(step)

        # simulate state on previous version
        cover = self._create_cover(id='test-cover', layout='Empty layout')
        cover.cover_layout = (
            '[{"type": "row", "children": [{"column-size": 16, "type": '
            '"group", "children": [{"tile-type": '
            '"collective.cover.basic", "type": "tile", "id": '
            '"ca6ba6675ef145e4a569c5e410af7511"}], "roles": ["Manager"]}]}]')

        tile = cover.get_tile('ca6ba6675ef145e4a569c5e410af7511')
        obj = self.portal['my-image']
        tile.populate_with_object(obj)

        dmgr = ITileDataManager(tile)
        old_data = dmgr.get()
        old_data['image_mtime'] = repr(old_data['image_mtime'])
        dmgr.annotations[dmgr.key] = PersistentDict(old_data)

        data = dmgr.get()
        self.assertIsInstance(data['image_mtime'], str)

        # run the upgrade step to validate the update
        self._do_upgrade_step(step)

        data = dmgr.get()
        self.assertIsInstance(data['image_mtime'], float)
Example #18
0
 def __init__(self, title):
     self.title = title
     self.__name__ = normalise_title(title)
     self._properties = PersistentDict({})
     self._extra_behaviour = PersistentList([])
     
     self._update_properties()
Example #19
0
 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
     ))
Example #20
0
def concordar_ressalva(context, paragrafo_id, userid=None):
    """ Concorda com um parágrafo de um item.
    Se nenhum usuário for passado, o corrente será usado.
    Se o usuário tinha concordado com o parágrafo previamente, remove tal voto.
    Se o usuário tinha discordado do item previamente, remove o voto e adiciona
    um novo de concordância.
    """
    action = None
    userid = userid or _get_user_id()
    annotations = IAnnotations(context)

    if userid in annotations[discordancias][paragrafo_id]:
        annotations[discordancias][paragrafo_id].pop(userid)

    if userid in annotations[concordancias][
            paragrafo_id] and 'ressalva' in annotations[concordancias][
                paragrafo_id][userid]:
        annotations[concordancias][paragrafo_id].pop(userid)
        action = "desfazer"
        event.notify(UnlikeEvent(context))
    else:
        annotations[concordancias][paragrafo_id][userid] = PersistentDict()
        annotations[concordancias][paragrafo_id][userid]["has_voted"] = True
        annotations[concordancias][paragrafo_id][userid]["ressalva"] = ''
        action = "concordar_ressalva"
        event.notify(LikeEvent(context))

    context.reindexObject(idxs=['concordancias'])
    return action
Example #21
0
 def test_second_step_required_columns_nok(self):
     """Test validation of required columns"""
     request = self.layer["request"]
     request.form = {
         "form.buttons.import": u"Importer",
         "form.widgets.column_0": u"--NOVALUE--",
         "form.widgets.column_1": u"--NOVALUE--",
         "form.widgets.column_2": u"--NOVALUE--",
         "form.widgets.decimal_import": u"False",
         "form.widgets.allow_empty": u"False",
     }
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = False
     annotation["separator"] = u";"
     annotation["source"] = NamedBlobFile(
         data=self._csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     form = importform.ImportFormSecondStep(self.container, request)
     form.updateFieldsFromSchemata()
     form.updateWidgets()
     data, errors = form.extractData()
     self.assertEqual(1, len(errors))
     self.assertEqual(
         "The following required columns are missing: identifier",
         translate(errors[0].error.message),
     )
 def _storage(self):
     return IAnnotations(
         self.context
     ).setdefault(
         PAI_STORAGE_KEY,
         PersistentDict()
     )
Example #23
0
 def getDefault(self, name):
     try:
         return self._defaults.get(name)
     except AttributeError:  # Backward compatibility
         self._defaults = PersistentDict()
         self.setDefault(name, 'Plone Default')
         return self.getDefault(name)
Example #24
0
    def getAllUserRolesInfo(self):
        state = self._getStorage4UserRolesInfo()
        auth_tool = self.context.getAuthenticationTool()

        # add user.roles info
        for user in auth_tool.getUsers():
            userid = user.name
            roles = user.roles
            if userid not in state:
                state[userid] = PersistentList()

            unsaved_roles = []
            for r in roles:
                has_role = False
                for su in state[userid]:
                    if r in su['roles']:
                        has_role = True
                        break
                if not has_role:
                    unsaved_roles.append(r)
            if unsaved_roles != []:
                unsaved_roles = PersistentList(unsaved_roles)
                state[userid].append(PersistentDict({'roles': unsaved_roles}))

        return state
class Base(object):
    use_interface = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(self.context)

        self._metadata = annotations.get('collective.documentviewer', None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            self._metadata['last_updated'] = DateTime('1901/01/01').ISO8601()
            self.storage_version = STORAGE_VERSION
            annotations['collective.documentviewer'] = self._metadata

    def __setattr__(self, name, value):
        if name[0] == '_' or name in ['context', 'use_interface']:
            self.__dict__[name] = value
        else:
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in self.use_interface.names():
            default = self.use_interface[name].default
        elif name in _defaults:
            default = _defaults.get(name, None)

        return self._metadata.get(name, default)
Example #26
0
class AnnotationAdapter(object):
    """Abstract Base Class for an annotation storage.

    If the annotation wasn't set, it won't be created until the first attempt
    to set a property on this adapter.
    So, the context doesn't get polluted with annotations by accident.

    """
    ANNOTATION_KEY = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(context)
        self._data = annotations.get(self.ANNOTATION_KEY, None)

    def __setattr__(self, name, value):
        if name in ('context', '_data', 'ANNOTATION_KEY'):
            self.__dict__[name] = value
        else:
            if self._data is None:
                self._data = PersistentDict()
                annotations = IAnnotations(self.context)
                annotations[self.ANNOTATION_KEY] = self._data
            self._data[name] = value

    def __getattr__(self, name):
        return self._data and self._data.get(name, None) or None
Example #27
0
class Base(object):
    use_interface = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(self.context)

        self._metadata = annotations.get('wc.pageturner', None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            self._metadata['last_updated'] = DateTime('1901/01/01').ISO8601()
            annotations['wc.pageturner'] = self._metadata

    def __setattr__(self, name, value):
        if name[0] == '_' or name in ['context', 'use_interface']:
            self.__dict__[name] = value
        else:
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in self.use_interface.names():
            default = self.use_interface[name].default

        return self._metadata.get(name, default)
Example #28
0
 def __init__(self,
              parent,
              form,
              REQUEST,
              real_doc=None,
              validation_mode=False):
     self._parent = parent
     self.REQUEST = REQUEST
     if real_doc:
         self.items = PersistentDict(real_doc.items)
         self.setItem('Form', form.getFormName())
         self.real_id = real_doc.id
         form.validateInputs(REQUEST, self)
         form.readInputs(self, REQUEST, validation_mode=validation_mode)
     else:
         self.items = {}
         self.setItem('Form', form.getFormName())
         self.real_id = "TEMPDOC"
         mapped_field_ids, rowdata = getDatagridRowdata(self, REQUEST)
         if mapped_field_ids and rowdata:
             for f in mapped_field_ids:
                 self.setItem(f.strip(), rowdata[mapped_field_ids.index(f)])
         else:
             form.validateInputs(REQUEST, self)
             form.readInputs(self, REQUEST, validation_mode=validation_mode)
Example #29
0
    def _annotation_storage(self, create_if_missing=False):
        annotations = IAnnotations(self.context)
        # Avoid writes on read
        if REMINDER_ANNOTATIONS_KEY not in annotations and create_if_missing:
            annotations[REMINDER_ANNOTATIONS_KEY] = PersistentDict()

        return annotations.get(REMINDER_ANNOTATIONS_KEY, {})
Example #30
0
 def getSocialAppConfig(self):
     if not hasattr(self, '_socialAppConfig'):
         self._socialAppConfig = PersistentDict({
             'active': False,
             'facebook': {}
         })
     return self._socialAppConfig
class DavizSettings(SimpleItem):
    """ Daviz Settings
    """
    meta_type = "EEA Daviz Settings"
    security = ClassSecurityInfo()
    implements(IDavizSettings)
    id = 'portal_daviz'

    manage_options = (
        {'label': 'Edit', 'action': 'zmi_edit_html'},
    ) + SimpleItem.manage_options

    def __init__(self, p_id, title="all daviz settings"):
        super(DavizSettings, self).__init__()
        self._setId(p_id)
        self.title = title
        self.settings = PersistentDict()

        site = getSite()
        sm = site.getSiteManager()
        ds = sm.queryUtility(IDavizSettings)
        if ds:
            sm.unregisterUtility(ds, IDavizSettings)
        sm.registerUtility(self, IDavizSettings)

    def disabled(self, view, content_type):
        """ Is view disabled for given content_type
        """
        if not isinstance(view, (str, unicode)):
            view = getattr(view, '__name__', '')
        if not isinstance(content_type, (str, unicode)):
            content_type = getattr(content_type, 'portal_type',
                           getattr(content_type, 'meta_type', None))
        portal_types = self.settings.get(u'forbidden.%s' % view, None) or []
        return content_type in portal_types
Example #32
0
class AnnotationAdapter(object):
    """Abstract Base Class for an annotation storage.

    If the annotation wasn't set, it won't be created until the first attempt
    to set a property on this adapter.
    So, the context doesn't get polluted with annotations by accident.

    """
    ANNOTATION_KEY = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(context)
        self._data = annotations.get(self.ANNOTATION_KEY, None)

    def __setattr__(self, name, value):
        if name in ('context', '_data', 'ANNOTATION_KEY'):
            self.__dict__[name] = value
        else:
            if self._data is None:
                self._data = PersistentDict()
                annotations = IAnnotations(self.context)
                annotations[self.ANNOTATION_KEY] = self._data
            self._data[name] = value

    def __getattr__(self, name):
        return self._data and self._data.get(name, None) or None
Example #33
0
 def __init__(self, context):
     annotations = IAnnotations(context)
     mapping = annotations.get(KEY)
     if mapping is None:
         blank = {'email': u'', 'dashboard_objs': AdmUtilUserDashboardSet()}
         mapping = annotations[KEY] = PersistentDict(blank)
     self.mapping = mapping
Example #34
0
    def getAllLDAPGroupRolesInfo(self):
        state = self._getStorage4LDAPGroupRolesInfo()
        auth_tool = self.context.getAuthenticationTool()

        if not hasattr(self.context, 'acl_satellite'):
            return state

        mapped_roles = self.context.acl_satellite.getAllLocalRoles()
        for group in mapped_roles:
            roles = mapped_roles[group]
            if group not in state:
                state[group] = PersistentList()

            unsaved_roles = []
            for r in roles:
                has_role = False
                for sg in state[group]:
                    if r in sg['roles']:
                        has_role = True
                        break
                if not has_role:
                    unsaved_roles.append(r)
            if unsaved_roles != []:
                unsaved_roles = PersistentList(unsaved_roles)
                state[group].append(PersistentDict({'roles': unsaved_roles}))

        return state
Example #35
0
 def test_second_step_import_single_column(self):
     """Test importing csv data"""
     form = importform.ImportFormSecondStep(self.container,
                                            self.layer["request"])
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = False
     annotation["separator"] = u";"
     csv = StringIO()
     lines = [
         ["", "key1", "Key 1"],
         ["", "key2", "Key 2"],
     ]
     for line in lines:
         csv.write(";".join(line) + "\n")
     csv.seek(0)
     annotation["source"] = NamedBlobFile(
         data=csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     data = {
         "column_0": None,
         "column_1": "identifier",
         "column_2": None,
         "decimal_import": False,
         "allow_empty": False,
     }
     form._import(data)
     self.assertEqual(2, len(self.container))
     self.assertEqual(["key1", "key2"],
                      sorted(
                          [e.identifier for e in self.container.values()]))
     self.assertEqual(["key1", "key2"],
                      sorted([e.title for e in self.container.values()]))
Example #36
0
 def test_second_step_basic_delimiter(self):
     """Test edge case related to csv delimiter"""
     form = importform.ImportFormSecondStep(self.container,
                                            self.layer["request"])
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = False
     annotation["separator"] = u","
     csv = StringIO()
     lines = [
         ["", "key1", "Key 1"],
         ["key1", "key1.1", '"Key 1,1"'],
         ["key1.1", "key1.1.1", '"Key 1.1.1"'],
     ]
     for line in lines:
         csv.write(",".join(line) + "\n")
     csv.seek(0)
     annotation["source"] = NamedBlobFile(
         data=csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     exception = None
     try:
         form.update()
     except Exception as e:
         exception = e
     self.assertIsNone(exception)
    def __init__(self, id=None):

        if id is not None:
            self.id = str(id)

        self._chains = PersistentDict()
        self._chainDefaultConfig  = DEFAULT_RULES
Example #38
0
 def test_second_step_import_encoding_form(self):
     """Test importing csv data with special chars in header and content"""
     form = importform.ImportFormSecondStep(self.container,
                                            self.layer["request"])
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = True
     annotation["separator"] = u";"
     csv = StringIO()
     lines = [
         [u"猫".encode("utf8"), u"èè".encode("utf8"), u"ùù".encode("utf8")],
         ["", u"kéy1".encode("utf8"), u"Kèy 1".encode("utf8")],
         [
             u"kéy1".encode("utf8"), u"kéy1.1".encode("utf8"),
             u"猫".encode("utf8")
         ],
     ]
     for line in lines:
         csv.write(";".join(line) + "\n")
     csv.seek(0)
     annotation["source"] = NamedBlobFile(
         data=csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     form.update()
     exception = None
     try:
         render = form.render()
     except UnicodeDecodeError as e:
         exception = e
     self.assertIsNone(exception)
     self.assertTrue(u"Column {0}".format(u"猫") in render)
Example #39
0
    def __init__(self, nadimak, jeLiRacunalo, igra):
        self.nadimak = nadimak
        self.karte = PersistentList()
        self.igra = igra
        self.jeLiRacunalo = jeLiRacunalo
        self.zastavice = PersistentDict()

        self.zastavice.update({
            'uzmiKarte': 0,
            'provjeriZvanja': 0,
            'hocuLiZvati': 0,
            'baciKartu': 0
        })

        self.igra.onSudjeluj(self)
        transaction.commit()
Example #40
0
 def test_second_step_optional_columns_data_ok(self):
     """Test validation of optional columns data"""
     request = self.layer["request"]
     request.form = {
         "form.buttons.import": u"Importer",
         "form.widgets.column_0": u"parent_identifier",
         "form.widgets.column_1": u"identifier",
         "form.widgets.column_2": u"title",
         "form.widgets.column_3": u"informations",
         "form.widgets.decimal_import": u"False",
         "form.widgets.allow_empty": u"False",
     }
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = False
     annotation["separator"] = u";"
     csv = StringIO()
     lines = [
         ["", "key1", "Key 1", "infos"],
         ["key1", "key1.1", "Key 1.1", ""],
         ["key1.1", "key1.1.1", "Key 1.1.1", ""],
     ]
     for line in lines:
         csv.write(";".join(line) + "\n")
     csv.seek(0)
     annotation["source"] = NamedBlobFile(
         data=csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     form = importform.ImportFormSecondStep(self.container, request)
     form.updateFieldsFromSchemata()
     form.updateWidgets()
     data, errors = form.extractData()
     self.assertEqual(0, len(errors))
Example #41
0
def get_storage(context, default=None):
    annotations = IAnnotations(context)
    if annotation_key not in annotations:
        if default is not None:
            return default
        annotations[annotation_key] = PersistentDict()
    return annotations[annotation_key]
Example #42
0
 def set_source_data(self, source_data):
     if not hasattr(self, 'source_data'):
         self.source_data = PersistentDict({})
     
     app_name = source_data.get('app_name')
     self.source_data.setdefault(app_name, {})
     self.source_data[app_name] = source_data
Example #43
0
def make_persistent(value):
    if type(value) == list:
        return PersistentList([make_persistent(i) for i in value])
    elif type(value) == dict:
        return PersistentDict([(i[0], make_persistent(i[1]))
                               for i in value.items()])
    return value
Example #44
0
class FeedSettings(object):
    implements(IFeedSettings)
    adapts(ISyndicatable)

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(context)

        self._metadata = annotations.get(FEED_SETTINGS_KEY, None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            annotations[FEED_SETTINGS_KEY] = self._metadata

        registry = getUtility(IRegistry)
        self.site_settings = registry.forInterface(ISiteSyndicationSettings)

    def __setattr__(self, name, value):
        if name in ('context', '_metadata', 'site_settings'):
            self.__dict__[name] = value
        else:
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in ISiteSyndicationSettings.names():
            default = getattr(self.site_settings, name)
        elif name == 'enabled' and self.site_settings.default_enabled:
            default = True
        elif name in IFeedSettings.names():
            default = IFeedSettings[name].default

        return self._metadata.get(name, default)
    def __init__(self, context, interfaces=[IGallerySettings]):
        """
        The interfaces argument allows you to customize which
        interface these settings implemenet.
        """
        self.context = context

        self._interfaces = interfaces
        if type(self._interfaces) not in (list, tuple):
            self._interfaces = [self._interfaces]
        self._interfaces = list(self._interfaces)
        if IGallerySettings not in self._interfaces:
            self._interfaces.append(IGallerySettings)
        if None in self._interfaces:
            self._interfaces.remove(None)

        annotations = IAnnotations(context)

        self._metadata = annotations.get('collective.plonetruegallery', None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            annotations['collective.plonetruegallery'] = self._metadata

        from collective.plonetruegallery.utils import convertMeasurementToInt
        self._inline_conversions = {
            'nivoslider_width': convertMeasurementToInt,
            'nivoslider_height': convertMeasurementToInt
        }
class DavizSettings(SimpleItem):
    """ Daviz Settings
    """
    meta_type = "EEA Daviz Settings"
    security = ClassSecurityInfo()
    implements(IDavizSettings)
    id = 'portal_daviz'

    manage_options = (
        {'label': 'Edit', 'action': 'zmi_edit_html'},
    ) + SimpleItem.manage_options

    def __init__(self, p_id, title="all daviz settings"):
        super(DavizSettings, self).__init__()
        self._setId(p_id)
        self.title = title
        self.settings = PersistentDict()

        site = getSite()
        sm = site.getSiteManager()
        ds = sm.queryUtility(IDavizSettings)
        if ds:
            sm.unregisterUtility(ds, IDavizSettings)
        sm.registerUtility(self, IDavizSettings)

    def disabled(self, view, content_type):
        """ Is view disabled for given content_type
        """
        if not isinstance(view, (str, unicode)):
            view = getattr(view, '__name__', '')
        if not isinstance(content_type, (str, unicode)):
            content_type = getattr(content_type, 'portal_type',
                           getattr(content_type, 'meta_type', None))
        portal_types = self.settings.get(u'forbidden.%s' % view, None) or []
        return content_type in portal_types
Example #47
0
 def _set_field_type(self, value):
     portal = getSite()
     anno = IAnnotations(portal)
     name = 'sllintra.content.field_type'
     if anno.get(name) is None:
         anno[name] = PersistentDict()
     anno[name].update({self.field.getName(): value})
Example #48
0
class PortletAssignmentSettings(Contained):

    def __init__(self):
        self.data = PersistentDict()

    def __setitem__(self, name, value):
        self.data[name] = value

    def __delitem__(self, name):
        del self.data[name]

    def __getitem__(self, name):
        return self.data.__getitem__(name)

    def get(self, name, default=None):
        return self.data.get(name, default)
def save_users_statistics_reports(site, time_periods, reports):
    """ Input:
        - the list of time periods (as used in generate_users_statistics())
        - the list of reports (as returned by generate_users_statistics())

        Save reports as annotations on site in format:
        '2015/01/01-2015/01/31': {
            'active': 300,
            'new': 100,
            'total': 2000,
            'last_update': DateTime
        }

        Return True on saved or False for invalid input
    """
    stats_annot = IAnnotations(site).setdefault(USERS_STATISTICS_KEY,
                                                PersistentDict({}))

    if len(time_periods) == len(reports):
        for i in range(0, len(time_periods)):
            report = reports[i]
            report['last_update'] = DateTime()
            stats_annot[period_title(time_periods[i])] = report

            print "Saved report: {0}".format(period_title(time_periods[i]))
    else:
        return False

    transaction.commit()
    return True
Example #50
0
 def __init__(self, id):
     """ Initialization
     """
     CMFBTreeFolder.__init__(self, id)
     self.id = id
     self.items = PersistentDict()
     self.plomino_modification_time = DateTime().toZone(TIMEZONE)
Example #51
0
 def _setupConfigAnnotation(self):
     """ Make sure that we can store the field config.
     """
     annotations = IAnnotations(self)
     settings = annotations.get("PLOMINOFIELDCONFIG", None)
     if not settings:
         annotations["PLOMINOFIELDCONFIG"] = PersistentDict()
Example #52
0
class Base(object):
    use_interface = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(self.context)

        self._metadata = annotations.get('vindula.streaming', None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            self._metadata['last_updated'] = DateTime('1901/01/01').ISO8601()
            self.storage_version = STORAGE_VERSION
            annotations['vindula.streaming'] = self._metadata

    def __setattr__(self, name, value):
        if name[0] == '_' or name in ['context', 'use_interface']:
            self.__dict__[name] = value
        else:
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in self.use_interface.names():
            default = self.use_interface[name].default
        elif name in _defaults:
            default = _defaults.get(name, None)

        return self._metadata.get(name, default)
class RosterSettings(object):
    use_interface = None

    def __init__(self, context, interface):
        self.use_interface = interface
        self.context = context
        annotations = IAnnotations(self.context)

        self._metadata = annotations.get('collective.eventmanager', None)
        if self._metadata is None:
            self._metadata = PersistentDict()
            annotations['collective.eventmanager'] = self._metadata

    def __setattr__(self, name, value):
        if name[0] == '_' or name in ['context', 'use_interface']:
            self.__dict__[name] = value
        else:
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in self.use_interface.names():
            default = self.use_interface[name].default

        return self._metadata.get(name, default)
Example #54
0
class Base(object):
    use_interface = None

    def __init__(self, context):
        self.context = context
        annotations = IAnnotations(self.context)

        self._metadata = annotations.get('wildcard.media', None)

    def __setattr__(self, name, value):
        if name[0] == '_' or name in ['context', 'use_interface']:
            self.__dict__[name] = value
        else:
            if self._metadata is None:
                self._metadata = PersistentDict()
                annotations = IAnnotations(self.context)
                annotations['wildcard.media'] = self._metadata
            self._metadata[name] = value

    def __getattr__(self, name):
        default = None
        if name in self.use_interface.names():
            default = self.use_interface[name].default

        if self._metadata is None:
            return default
        return self._metadata.get(name, default)
Example #55
0
 def test_second_step_basic_encoding(self):
     """Ensure that form can be displayed even with special characters"""
     form = importform.ImportFormSecondStep(self.container,
                                            self.layer["request"])
     annotations = IAnnotations(self.container)
     annotation = annotations[importform.ANNOTATION_KEY] = PersistentDict()
     annotation["has_header"] = False
     annotation["separator"] = u";"
     csv = StringIO()
     lines = [
         ["null", "key1", "key1.1", "Key 1.1", "informations"],
         [
             "null",
             "",
             u"key1 éà$€".encode("utf8"),
             u"Key 1 éà$€".encode("utf8"),
             u"informations éà$€".encode("utf8"),
         ],
     ]
     for line in lines:
         csv.write(";".join(line) + "\n")
     csv.seek(0)
     annotation["source"] = NamedBlobFile(
         data=csv.read(),
         contentType=u"text/csv",
         filename=u"test.csv",
     )
     exception = None
     try:
         form.update()
     except UnicodeDecodeError as e:
         exception = e
     self.assertIsNone(exception)
Example #56
0
    def set(self, data):
        # when setting data, we need to purge scales/image data...
        # XXX hack?
        try:
            scale_key = self.key.replace('.data.', '.scale.')
            del self.annotations[scale_key]
        except KeyError:
            pass

        for k, v in data.items():
            if INamedImage.providedBy(v):
                mtime_key = '{0}_mtime'.format(k)
                if (self.key not in self.annotations
                        or k not in self.annotations[self.key]
                        or (self.key in self.annotations
                            and data[k] != self.annotations[self.key][k])):
                    # set modification time of the image
                    notify(Purge(self.tile))
                    data[mtime_key] = '%f' % time.time()
                else:
                    data[mtime_key] = self.annotations[self.key].get(
                        mtime_key, '')

        self.annotations[self.key] = PersistentDict(data)
        notify(ObjectModifiedEvent(self.context))
Example #57
0
 def set(self, field_name, value):
     shared_data = self.shared_data
     data = shared_data.setdefault(self.related_key, PersistentDict())
     if value is None:
         data[field_name] = None
     else:
         data[field_name] = float(value)
Example #58
0
 def test_persist_simple(self):
     root = self.conn.root()
     root['aba'] = PersistentDict()
     root['aba']['maba'] = 3
     self.reopen()
     root = self.conn.root()
     self.assertEqual(root['aba']['maba'], 3)
Example #59
0
    def __init__(self, principalId, store=None):
        self.principalId = principalId
        self.data = PersistentDict() # We don't really expect that many

        # _v_store is used to remember a mapping object that we should
        # be saved in if we ever change
        self._v_store = store