rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
format = image.format and image.format or 'PNG' | format = image.format and image.format or default_format | def scale(self, data, w, h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's size = int(w), int(h) |
value = getattr(self, name) if not value: | value = getattr(self, name, '') msgid = getattr(self, name+'_msgid', None) or value if not value and not msgid: | def _translate_attribute(self, instance, name): value = getattr(self, name) if not value: return '' domain = (getattr(self, 'i18n_domain', None) or getattr(instance, 'i18n_domain', None)) if domain is None: return value msgid = getattr(self, name+'_msgid', None) or value return i18n.translate(domain, msgid, mapping=ins... |
msgid = getattr(self, name+'_msgid', None) or value | def _translate_attribute(self, instance, name): value = getattr(self, name) if not value: return '' domain = (getattr(self, 'i18n_domain', None) or getattr(instance, 'i18n_domain', None)) if domain is None: return value msgid = getattr(self, name+'_msgid', None) or value return i18n.translate(domain, msgid, mapping=ins... | |
dtool.overrideDiscussionFor(self, allowDiscussion) | try: dtool.overrideDiscussionFor(self, allowDiscussion) except 'Unauthorized': log_exc() | def allowDiscussion(self, allowDiscussion=None, **kw): if allowDiscussion is not None: try: allowDiscussion = int(allowDiscussion) except (TypeError, ValueError): allowDiscussion = allowDiscussion.lower().strip() d = {'on' : 1, 'off': 0, 'none':None, '':None} allowDiscussion = d.get(allowDiscussion, None) dtool = getTo... |
def Identifer(self): """ dublin core getId method""" return self.getId() | def Identifer(self): """ dublin core getId method""" return self.getId() | |
security.declareProtected(CMFCorePermissions.View, 'listContributors') def listContributors(self): """Dublin Core element - Contributors""" return self.Contributors() security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'addCreator') def addCreator(self, creator=None): """ Add creator to Dublin Core creat... | def Identifier(self): """Dublin Core element - Object ID""" # XXX: fixme using 'portal_metadata' (we need to prepend the # right prefix to self.getPhysicalPath(). return self.absolute_url() | |
self.set(field.getName(), instance, field.default) | base = aq_base (instance) if not base._md.has_key(field.getName()): self.set(field.getName(), instance, field.default) | def initializeField(self, instance, field): self.set(field.getName(), instance, field.default) |
self.unset(field.getName(), instance) | pass | def cleanupField(self, instance, field, **kwargs): self.unset(field.getName(), instance) |
if hasattr(aq_base(instance), '_md'): del instance._md | pass | def cleanupInstance(self, instance, item=None, container=None): if hasattr(aq_base(instance), '_md'): del instance._md |
value = {} | types = [] | def addableTypes(self, instance, field): """Returns a dictionary which maps portal_type to its human readable form.""" tool = instance.portal_types value = {} |
value[typeid] = info.Title() return value | value = {} value['id'] = typeid value['name'] = info.Title() destinations = self.destination and [self.destination] or \ lookupDestinationsFor(info, tool) value['destinations'] = destinations types.append(value) return types | def addableTypes(self, instance, field): """Returns a dictionary which maps portal_type to its human readable form.""" tool = instance.portal_types value = {} |
purl = getToolByName(instance, 'portal_url') if not self.destination: | if self.destination: purl = getToolByName(instance, 'portal_url') | def getDestination(self, instance): purl = getToolByName(instance, 'portal_url') if not self.destination: return purl.getRelativeUrl(aq_parent(instance)) else: value = getattr(aq_base(instance), self.destination, self.destination) if callable(value): value = value() |
return purl.getPortalPath() + value | return value | def getDestination(self, instance): purl = getToolByName(instance, 'portal_url') if not self.destination: return purl.getRelativeUrl(aq_parent(instance)) else: value = getattr(aq_base(instance), self.destination, self.destination) if callable(value): value = value() |
return getSchemata(self.klass) | return getSchemata(self.klass('test')) | def schemata(self): from Products.Archetypes.Schema import getSchemata return getSchemata(self.klass) |
return self.klass.getSchema().signature() | return self.klass('test').Schema().signature() | def signature(self): return self.klass.getSchema().signature() |
cache = context._v_sql_cache={}, Bucket() cache, tcache = cache max_cache = context.max_cache_ now = time() t = now - context.cache_time_ if len(cache) > max_cache / 2: keys = tcache.keys() keys.reverse() while keys and (len(keys) > max_cache or keys[-1] < t): key = keys[-1] q = tcache[key] del tcache[key] if int(cache... | self.original_encoding = None self.raw = data self.size = len(data) self.setFilename(filename) def transform(self, instance, mt): """Takes a mimetype so object.foo.transform('text/plain') should return a plain text version of the raw content return None if no data or if data is untranformable to desired output mime... | def _cached_result(self, DB__, query): context = self.context # Try to fetch from cache if hasattr(context,'_v_sql_cache'): cache = context._v_sql_cache else: cache = context._v_sql_cache={}, Bucket() cache, tcache = cache max_cache = context.max_cache_ now = time() t = now - context.cache_time_ if len(cache) > max_cac... |
dbc = getattr(context, self.connection_id) | return instance.getCharset() | def _get_dbc(self): """Get the database connection""" context = self.context |
raise AttributeError, ( "The database connection <em>%s</em> cannot be found." % ( self.connection_id)) try: DB__ = dbc() except ConflictError: raise except: raise 'Database Error', ( '%s is not connected to a database' % self.id) return dbc, DB__ def __call__(self, src__=0, test__=0, **kw): """Call the database met... | return 'UTF8' def getContentType(self): """return the mimetype string for this BU""" return self.mimetype def setContentType(self, instance, value): """ """ mtr = getToolByName(instance, 'mimetypes_registry') if not IMimetypesRegistry.isImplementedBy(mtr): raise RuntimeError('%s(%s) is not a valid mimetype registry' ... | def _get_dbc(self): """Get the database connection""" context = self.context |
try: result = DB__.query(query, context.max_rows_) except ConflictError: raise except: log_exc(msg='Database query failed', reraise=1) if hasattr(context, '_v_sql_brain'): brain = context._v_sql_brain else: brain=context._v_sql_brain = getBrain(context.class_file_, context.class_name_) if type(result) is type(''): f ... | self.filename = filename security.declareProtected(CMFCorePermissions.View, "index_html") def index_html(self, REQUEST, RESPONSE): """download method""" filename = self.filename if self.filename: RESPONSE.setHeader('Content-Disposition', 'attachment; filename=%s' % self.getFilename()) RESPONSE.setHeader('Content-Typ... | def __call__(self, src__=0, test__=0, **kw): """Call the database method |
"Please apply a package name for klas %s" % repr(klass), | "Please apply a package name for class %s" % repr(klass), | def registerType(klass, package=None): if not package: warnings.warn("registerType without a package name is deprecated. " "Please apply a package name for klas %s" % repr(klass), DeprecationWarning, stacklevel=2) package = _guessPackage(klass.__module__) # Registering a class results in classgen doing its thing # Set... |
self.url = inst.absolute_url(1) | self.url = inst.absolute_url() | def __init__(self, inst): self.id = obj2id(inst) self.url = inst.absolute_url(1) self.uid = inst.UID() self.title = inst.title_or_id() self.text = '%s: %s' % (inst.getId(), inst.Title()) |
def local_refernece_graph(inst): | def local_reference_graph(inst): | def local_refernece_graph(inst): nodes = {} graphs = { 'forward' : {}, 'backward' : {}, } rc = inst.reference_catalog references = rc.getReferences(inst) back_references = rc.getBackReferences(inst) node = Node(inst) nodes[inst.UID()] = node for ref in references: tob = ref.getTargetObject() target = Node(tob) if ... |
g = local_refernece_graph(inst) | g = local_reference_graph(inst) | def getDot(inst): g = local_refernece_graph(inst) data = build_graph(g, inst) return data |
stdout, stdin = popen2('%s -Gpack -Tcmapx' %( GRAPHVIZ_BINARY,)) | stdout, stdin = popen2('%s -Gpack -Tcmapx ' % GRAPHVIZ_BINARY) | def get_cmapx(inst): data = getDot(inst) |
if not mimetype or mimetype == 'None': | if mimetype == 'None': | def set(self, instance, value, **kwargs): """ Assign input value to object. If mimetype is not specified, pass to processing method without one and add mimetype returned to kwargs. Assign kwargs to instance. """ value = self._process_input(value, default=self.default, **kwargs) encoding = kwargs.get('encoding') if type... |
return aq_parent(instance).absolute_url() | purl = getToolByName(instance, 'portal_url') return purl.getRelativeUrl(aq_parent(instance)) | def getDestination(self, instance): if not self.destination: return aq_parent(instance).absolute_url() else: portal_url = instance.portal_url() value = getattr(aq_base(instance), self.destination, self.destination) if callable(value): value = value() |
portal_url = instance.portal_url() | def getDestination(self, instance): if not self.destination: return aq_parent(instance).absolute_url() else: portal_url = instance.portal_url() value = getattr(aq_base(instance), self.destination, self.destination) if callable(value): value = value() | |
return portal_url + value | return value | def getDestination(self, instance): if not self.destination: return aq_parent(instance).absolute_url() else: portal_url = instance.portal_url() value = getattr(aq_base(instance), self.destination, self.destination) if callable(value): value = value() |
if type_datum is UnicodeType: | type_datum = type(datum) if type_datum == UnicodeType: | def SearchableText(self): """All fields marked as 'searchable' are concatenated together here for indexing purpose""" data = [] charset = self.getCharset() for field in self.Schema().fields(): if not field.searchable: continue method = field.getAccessor(self) try: datum = method(mimetype="text/plain") except TypeError... |
log("WARNING: no validator %s for %s" % (name, | log("WARNING: no validator %s for %s" % (vname, | def _validationLayer(self): """ Resolve that each validator is in the service. If validator is not, log a warning. |
if hasattr(REQUEST, 'RESPONSE'): REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, '')) | return | def __bobo_traverse__(self, REQUEST, name, RESPONSE=None): """ transparent access to session subobjects """ # is it a registered sub object data = self.getSubObject(name, REQUEST, RESPONSE) if data is not None: return data # or a standard attribute (maybe acquired...) # DM 2004-08-10: this breaks FTP/WebDAV's PUT: # I... |
def reinstallArchetypes(portal,out): ''' lets quickinstaller reinstall the archetypes ''' refcat=getToolByName(portal,REFERENCE_CATALOG,None) if not refcat: print >>out, 'reinstalling Archetypes...' getToolByName(portal,'portal_quickinstaller').reinstallProducts(['Archetypes']) print >>out, 'reinstalled Archetypes.' | class StdoutStringIO(StringIO): """StringIO that also writes to stdout """ def write(self, s): print >> sys.stdout, str(s), StringIO.write(self, s) def reinstallArchetypes(portal, out): """let's quickinstaller (re)install Archetypes and it's dependencies """ qi = getToolByName(portal, 'portal_quickinstaller') product... | def reinstallArchetypes(portal,out): ''' lets quickinstaller reinstall the archetypes ''' # heuristic: if there is no reference_catalog, lets reinstall refcat=getToolByName(portal,REFERENCE_CATALOG,None) if not refcat: print >>out, 'reinstalling Archetypes...' getToolByName(portal,'portal_quickinstaller').reinstallProd... |
print >>out, "Old references are stored in %s, so migrating them to new style reference annotations." % (TOOL_NAME) | print >>out, "Old references are stored in %s, so migrating them to new style reference annotations.\n" % (TOOL_NAME) | def migrateReferences(portal, out): # FIRST # a 1.2 -> 1.3 (new annotation style) migration path at = getToolByName(portal, TOOL_NAME) rc = getToolByName(portal, REFERENCE_CATALOG) uc = getToolByName(portal, UID_CATALOG) count=0 # Old 1.2 style references are stored inside archetype_tool on the 'ref' # attribute ref... |
print >>out, "%s old references migrated." % count | print >>out, "\n%s old references migrated." % count | def migrateReferences(portal, out): # FIRST # a 1.2 -> 1.3 (new annotation style) migration path at = getToolByName(portal, TOOL_NAME) rc = getToolByName(portal, REFERENCE_CATALOG) uc = getToolByName(portal, UID_CATALOG) count=0 # Old 1.2 style references are stored inside archetype_tool on the 'ref' # attribute ref... |
print >>out, 'migrating reference from Archetypes 1.3. beta2' | print >>out, 'migrating reference from Archetypes 1.3. beta2\n' | def migrateReferences(portal, out): # FIRST # a 1.2 -> 1.3 (new annotation style) migration path at = getToolByName(portal, TOOL_NAME) rc = getToolByName(portal, REFERENCE_CATALOG) uc = getToolByName(portal, UID_CATALOG) count=0 # Old 1.2 style references are stored inside archetype_tool on the 'ref' # attribute ref... |
print >>out, '\nDone\n' | def migrateReferences(portal, out): # FIRST # a 1.2 -> 1.3 (new annotation style) migration path at = getToolByName(portal, TOOL_NAME) rc = getToolByName(portal, REFERENCE_CATALOG) uc = getToolByName(portal, UID_CATALOG) count=0 # Old 1.2 style references are stored inside archetype_tool on the 'ref' # attribute ref... | |
print >>out, '\nDone\n' | def migrateUIDs(portal, out): count=0 uc = getToolByName(portal, UID_CATALOG) # temporary add a new index if olduididx not in uc.indexes(): uc.addIndex(olduididx, 'FieldIndex', extra=None) if not olduididx in uc.schema(): uc.addColumn(olduididx) # clear UID Catalog uc.manage_catalogClear() # rebuild UIDS on objects ... | |
print >>out, count, "old UID attributes removed." | print >>out, "\n%s old UID attributes removed." % count print >>out, 'Done\n' | def removeOldUIDs(portal, out): # remove temporary needed index uc = getToolByName(portal, UID_CATALOG) if olduididx in uc.indexes(): uc.delIndex(olduididx) if olduididx in uc.schema(): uc.delColumn(olduididx) count=0 allbrains = uc() for brain in allbrains: #Get a uid for each thingie obj = brain.getObject() objUID = ... |
def getRaw(self, instance, **kwargs): | def getRaw(self, instance, aslist=0, **kwargs): | def getRaw(self, instance, **kwargs): """Return the list of UIDs referenced under this fields relationship """ rc = getToolByName(instance, REFERENCE_CATALOG) brains = rc(sourceUID=instance.UID(), relationship=self.relationship) return [b.targetUID for b in brains] |
return [b.targetUID for b in brains] | res = [b.targetUID for b in brains] if not self.multiValued and not aslist: if res: res = res[0] else: res = None return res | def getRaw(self, instance, **kwargs): """Return the list of UIDs referenced under this fields relationship """ rc = getToolByName(instance, REFERENCE_CATALOG) brains = rc(sourceUID=instance.UID(), relationship=self.relationship) return [b.targetUID for b in brains] |
if fieldset is not None: | if not IMultiPageSchema.providedBy(self): fields = schema.fields() elif fieldset is not None: | def _processForm(self, data=1, metadata=None, REQUEST=None, values=None): request = REQUEST or self.REQUEST if values: form = values else: form = request.form fieldset = form.get('fieldset', None) schema = self.Schema() schemata = self.Schemata() fields = [] |
imgdata = self.scale(data, w, h) pimage = PIL.Image.open(imgdata) | imgdata, format = self.scale(data, w, h) | def createScales(self, instance): """creates the scales and save them """ if not has_pil or not self.sizes: return img = self.getRaw(instance) if not img: return data = str(img.data) for n, size in self.sizes.items(): w, h = size id = self.getName() + "_" + n imgdata = self.scale(data, w, h) pimage = PIL.Image.open(img... |
'image/%s' % lower(pimage.format) | 'image/%s' % format | def createScales(self, instance): """creates the scales and save them """ if not has_pil or not self.sizes: return img = self.getRaw(instance) if not img: return data = str(img.data) for n, size in self.sizes.items(): w, h = size id = self.getName() + "_" + n imgdata = self.scale(data, w, h) pimage = PIL.Image.open(img... |
keys = {'height':int(h), 'width':int(w)} | size = int(w), int(h) | def scale(self,data,w,h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's keys = {'height':int(h), 'width':int(w)} |
image.thumbnail((keys['width'],keys['height']), pilfilter) | image.thumbnail(size, pilfilter) format = image.format and image.format or 'PNG' | def scale(self,data,w,h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's keys = {'height':int(h), 'width':int(w)} |
if original_mode == 'P' and image.format == 'GIF': | if original_mode == 'P' and format == 'GIF': | def scale(self,data,w,h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's keys = {'height':int(h), 'width':int(w)} |
image.save(thumbnail_file, image.format, quality=88) | image.save(thumbnail_file, format, quality=88) | def scale(self,data,w,h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's keys = {'height':int(h), 'width':int(w)} |
return thumbnail_file.read() | return thumbnail_file, format.lower() | def scale(self,data,w,h): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's keys = {'height':int(h), 'width':int(w)} |
self.assertEquals(got, expected) | try: self.assertEqual(got, expected) except self.failureException: if ZOPE28: raise | def testSame(self): gen_dummy() # The BaseUnit expects 'instance' to be # acquisition wrapped, or else it does return # the untransformed text -- this was introduced # for compatibility with APE. parent = Dummy(oid='parent') dummy = Dummy(oid='dummy', init_transforms=1).__of__(parent) input = open(self.input) bu = Base... |
if type(validators) not in [type(()), type([])]: | if type(validators) not in (TupleType, ListType): | def _validationLayer(self): """ Resolve that each validator is in the service. If validator is not, log a warning. |
if isinstance(value, type('')) or \ isinstance(value, type(u'')): | if type(value) in STRING_TYPES: | def validate_vocabulary(self, instance, value, errors): """Make sure value is inside the allowed values for a given vocabulary""" error = None if value: # coerce value into a list called values values = value if isinstance(value, type('')) or \ isinstance(value, type(u'')): values = [value] elif not (isinstance(value, ... |
elif not (isinstance(value, type((1,))) or \ isinstance(value, type([]))): | elif type(value) not in (TupleType, ListType): | def validate_vocabulary(self, instance, value, errors): """Make sure value is inside the allowed values for a given vocabulary""" error = None if value: # coerce value into a list called values values = value if isinstance(value, type('')) or \ isinstance(value, type(u'')): values = [value] elif not (isinstance(value, ... |
if type(v) in [type(()), type([])]: | if type(v) in (TupleType, ListType): | def validate_vocabulary(self, instance, value, errors): """Make sure value is inside the allowed values for a given vocabulary""" error = None if value: # coerce value into a list called values values = value if isinstance(value, type('')) or \ isinstance(value, type(u'')): values = [value] elif not (isinstance(value, ... |
print type(data) | def createScales(self, instance): """creates the scales and save them """ if not has_pil or not self.sizes: return img = self.getRaw(instance) if not img: return data = str(img.data) print type(data) for n, size in self.sizes.items(): w, h = size id = self.getName() + "_" + n imgdata = self.scale(data, w, h) image = se... | |
def lookupTemplates(self, instance=None): | def lookupTemplates(self, instance_or_portaltype=None): | def lookupTemplates(self, instance=None): """Lookup templates by giving an instance or a portal_type. |
if type(instance) is not StringType: fti = instance.getTypeInfo() instance = getattr(self.getTypeInfo(), 'portal_type', None) | if not type(instance_or_portaltype) in StringTypes: portal_type = getattr(instance_or_portaltype.getTypeInfo(), 'portal_type', None) else: portal_type = instance_or_portaltype | def lookupTemplates(self, instance=None): """Lookup templates by giving an instance or a portal_type. |
templates = self._templates[instance] | templates = self._templates[portal_type] | def lookupTemplates(self, instance=None): """Lookup templates by giving an instance or a portal_type. |
if not instance or not hasattr(instance, 'aq_parent'): | if not hasattr(instance, 'aq_parent'): | def transform(self, instance, mt, **kwargs): """Takes a mimetype so object.foo.transform('text/plain') should return a plain text version of the raw content |
print "Fired EditBeginsEvent" | def notifyEditBegins(self): """ """ print "Fired EditBeginsEvent" notify(EditBeginsEvent(aq_inner(self.context))) | |
def isLocked(self): | def hasLock(self): user_id = getSecurityManager().getUser().getId() for lock in self.context.wl_lockValues(): if not lock.isValid(): continue creator = lock.getCreator() if creator and creator[1] == user_id: return True return False def isLockedForMe(self): | def isLocked(self): """ """ if not hasattr(self.context, 'wl_isLocked'): return False elif self.context.wl_isLocked(): user_id = getSecurityManager().getUser().getId() for lock in self.context.wl_lockValues(): if not lock.isValid(): continue # Skip invalid/expired locks creator = lock.getCreator() if creator and creato... |
user_id = getSecurityManager().getUser().getId() for lock in self.context.wl_lockValues(): if not lock.isValid(): continue creator = lock.getCreator() if creator and creator[1] == user_id: return False return True | return not self.hasLock() | def isLocked(self): """ """ if not hasattr(self.context, 'wl_isLocked'): return False elif self.context.wl_isLocked(): user_id = getSecurityManager().getUser().getId() for lock in self.context.wl_lockValues(): if not lock.isValid(): continue # Skip invalid/expired locks creator = lock.getCreator() if creator and creato... |
return {'userid': userid, 'creator':creatorFullname, 'lockCreationTime': lockCreationTime, 'authorPage': authorPage} | return {'userid': userid, 'creator':creatorFullname, 'lockCreationTime': lockCreationTime, 'authorPage': authorPage, 'timeDifference':self.getNiceTimeDifference(lockCreationTime) } | def getLockInformations(self): """ """ for lock in self.context.wl_lockValues(): if not lock.isValid(): continue # Skip invalid/expired locks userid = lock.getCreator()[1] lockCreationTime = lock.getModifiedTime() mt = getToolByName(self.context, 'portal_membership', None) pu = getToolByName(self.context, 'portal_url',... |
parts = alternative.split('|') | parts = schema[0].split('|') | def install_indexes(self, out, types): catalog = getToolByName(self, 'portal_catalog') for cls in types: if 'indexes' not in cls.installMode: continue for field in cls.schema.fields(): if field.index: if type(field.index) is StringType: index = (field.index,) else: index = field.index for alternative in index: insta... |
form_tool.setValidators("base_edit", ["validate_base"]) | form_tool.setValidators("base_metadata", ["validate_base"]) | def install_validation(self, out, types): form_tool = getToolByName(self, 'portal_form') type_tool = getToolByName(self, 'portal_types') # No validation on references form_tool.setValidators('reference_edit', []) # Default validation for types form_tool.setValidators("base_edit", ["validate_base"]) form_tool.setValid... |
SkinnedFolder.manage_delObjects(self, ids, REQUEST=REQUEST) | return SkinnedFolder.manage_delObjects(self, ids, REQUEST=REQUEST) | def manage_delObjects(self, ids=[], REQUEST=None): """ We need to enforce security. """ mt=getToolByName(self, 'portal_membership') if type(ids) is str: ids = [ids] for id in ids: item = self._getOb(id) if not mt.checkPermission(CMFCorePermissions.DeleteObjects, item): raise Unauthorized, ( "Do not have permissions to ... |
if ZOPE28 and not ZOPE29: outname += '.zope28' | def testSame(self): gen_dummy() # The BaseUnit expects 'instance' to be # acquisition wrapped, or else it does return # the untransformed text -- this was introduced # for compatibility with APE. parent = Dummy(oid='parent') dummy = Dummy(oid='dummy', init_transforms=1).__of__(parent) input = open(self.input) bu = Base... | |
if self.default_method: method = getattr(instance, self.default_method, None) | if field.default_method: method = getattr(instance, field.default_method, None) | def setDefaults(self, instance): """Only call during object initialization. Sets fields to schema defaults """ ## XXX think about layout/vs dyn defaults for field in self.values(): if field.name.lower() != 'id': # always set defaults #if not hasattr(aq_base(instance), field.name) and \ # getattr(instance, field.name,... |
setattr(file, 'content_type', value) self.set(instance, file) | try: setattr(file, 'content_type', value) except AttributeError: pass else: self.set(instance, file) | def setContentType(self, instance, value): """Set mimetype in the base unit. """ file = self.get(instance) setattr(file, 'content_type', value) self.set(instance, file) |
return file.content_type | return getattr(file, 'content_type', self.default_content_type) | def getContentType(self, instance, fromBaseUnit=True): file = self.get(instance) return file.content_type |
mimetype = kwargs.get('mimetype', 'image/png') if HAS_PIL: if self.original_size or self.max_size: if not value: return self.default w=h=0 if self.max_size: if value.width > self.max_size[0] or \ value.height > self.max_size[1]: factor = min(float(self.max_size[0])/float(value.width), float(self.max_size[1])/float(valu... | if not HAS_PIL: return str(value.data) mimetype = kwargs.get('mimetype', self.default_content_type) if self.original_size or self.max_size: if not value: return self.default w=h=0 if self.max_size: if value.width > self.max_size[0] or \ value.height > self.max_size[1]: factor = min(float(self.max_size[0])/float(value... | def rescaleOriginal(self, value, **kwargs): """rescales the original image and sets the data |
image = self.default | image = self.getDefault(instance) | def createOriginal(self, instance, value, **kwargs): """create the original image (save it) """ if value: image = self._wrapValue(instance, value, **kwargs) else: image = self.default |
pilfilter = PIL.Image.NEAREST if PIL.Image.VERSION >= "1.1.3": pilfilter = PIL.Image.ANTIALIAS | def scale(self, data, w, h, default_format = 'PNG'): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's size = int(w), int(h) | |
image.thumbnail(size, pilfilter) | image.thumbnail(size, self.pil_resize_algo) | def scale(self, data, w, h, default_format = 'PNG'): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's size = int(w), int(h) |
image.save(thumbnail_file, format, quality=88) | image.save(thumbnail_file, format, quality=self.pil_quality) | def scale(self, data, w, h, default_format = 'PNG'): """ scale image (with material from ImageTag_Hotfix)""" #make sure we have valid int's size = int(w), int(h) |
_types_callback = [] | def process_types(types, pkg_name): content_types = () constructors = () ftis = () for rti in types: typeName = rti['name'] klass = rti['klass'] module = rti['module'] if hasattr(module, "factory_type_information"): fti = module.factory_type_information else: fti = deepcopy(base_factory_type_information) m... | |
for tc in _types_callback: tc(klass, package) | def registerType(klass, package=None): if not package: package = _guessPackage(klass.__module__) ## registering a class results in classgen doing its thing ## Set up accessor/mutators and sane meta/portal_type generateClass(klass) data = { 'klass' : klass, 'name' : klass.meta_type, 'portal_type': klass.portal_type, ... | |
for k, t in _types.items(): self._types[k] = {'signature':t['signature'], 'update':1} cb = lambda klass, package:self.registerType(klass, package) _types_callback.append(cb) self.last_types_update = DateTime() | def __init__(self): self._schemas = PersistentMapping() self._templates = PersistentMapping() self._registeredTemplates = PersistentMapping() # meta_type -> [names of CatalogTools] self.catalog_map = PersistentMapping() self._types = {} for k, t in _types.items(): self._types[k] = {'signature':t['signature'], 'update':... | |
keys = self._types.keys() | currentTypes = _types ourTypes = self._types; modified = 0 keys = self._listAllTypes() | def getChangedSchema(self): """Returns a list of tuples indicating which schema have changed. Tuples have the form (schema, changed)""" list = [] keys = self._types.keys() keys.sort() for t in keys: list.append((t, self._types[t]['update'])) return list |
list.append((t, self._types[t]['update'])) | if t not in ourTypes: ourTypes[t] = currentTypes[t]['signature']; modified = 1 list.append((t, 0)) elif t not in currentTypes: del ourTypes[t]; modified = 1 else: list.append((t, ourTypes[t] != currentTypes[t]['signature'])) if modified: self._p_changed = 1 | def getChangedSchema(self): """Returns a list of tuples indicating which schema have changed. Tuples have the form (schema, changed)""" list = [] keys = self._types.keys() keys.sort() for t in keys: list.append((t, self._types[t]['update'])) return list |
for t in self._types.keys(): if self._types[t]['update']: update_types.append(t) | update_types = [ti[0] for ti in self.getChangedSchema() if ti[1]] | def manage_updateSchema(self, REQUEST=None): """Make sure all objects' schema are up to date""" |
for t in self._types.keys(): | for t in self._listAllTypes(): | def manage_updateSchema(self, REQUEST=None): """Make sure all objects' schema are up to date""" |
self._types[t]['update'] = 0 | self._types[t] = _types[t]['signature'] | def manage_updateSchema(self, REQUEST=None): """Make sure all objects' schema are up to date""" |
def __setstate__(self, v): """Add a callback to track product registrations""" ArchetypeTool.inheritedAttribute('__setstate__')(self, v) global _types global _types_callback if hasattr(self, '_types'): if not hasattr(self, 'last_types_update') or \ self.last_types_update.lessThan(last_load): for k, t in _types.items():... | def __setstate__(self, v): """Add a callback to track product registrations""" ArchetypeTool.inheritedAttribute('__setstate__')(self, v) global _types global _types_callback if hasattr(self, '_types'): if not hasattr(self, 'last_types_update') or \ self.last_types_update.lessThan(last_load): for k, t in _types.items():... | |
CMFBTreeFolder.__init__(self, id) | CMFBTreeFolder.__init__(self, oid) | def __init__(self, oid, **kwargs): CMFBTreeFolder.__init__(self, id) BaseFolder.__init__(self, oid, **kwargs) |
name = "container"" | name = "container" | def getProviders(self, instance, providers=None): providers = self._defaultSchema(instance, providers) provider = instance.aq_parent schema = self._getSchema(provider) if schema: providers.insert(0, SchemaResult(provider.getSchemaPriority(), schema, self._checksum(schema), provider)) # and recurse collector = provider.... |
from zLOG import LOG LOG("Condition", 100, self.condition) | def testCondition(self, folder, portal, object): """Test the widget condition.""" try: if self.condition: ec = createExprContext(folder, portal, object) from zLOG import LOG LOG("Condition", 100, self.condition) return Expression(self.condition)(ec) else: return 1 except AttributeError: return 1 | |
'image/" + lower(pimage.format)) | 'image/%s' % lower(pimage.format) ) | def createScales(self, instance): """creates the scales and save them """ if not has_pil or not self.sizes: return img = self.getRaw(instance) if not img: return data = str(img.data) for n, size in self.sizes.items(): w, h = size id = self.getName() + "_" + n imgdata = self.scale(data, w, h) pimage = PIL.Image.open(img... |
size=0 size+=len(str(self.get(instance))) | original = self.get(instance) size = original and original.get_size() or 0 | def get_size(self, instance): """Get size of the stored data used for get_size in BaseObject """ sizes = self.getAvailableSizes(instance) size=0 size+=len(str(self.get(instance))) |
size+=len(str(data)) | size+=data and data.get_size() or 0 | def get_size(self, instance): """Get size of the stored data used for get_size in BaseObject """ sizes = self.getAvailableSizes(instance) size=0 size+=len(str(self.get(instance))) |
template = str(template) | if not isinstance(template, (str, unicode)): template = str(template) | def edit(self, connection_id, arguments, template): """Change database method properties |
def validate(self, value): | def validate(self, value, **kwargs): | def validate(self, value): """ Validate passed-in value using all field validators. Return None if all validations pass; otherwise, return failed result returned by validator """ for v in self.validators: res = validation.validate(v, value) if res != 1: return res return None |
res = validation.validate(v, value) | res = validation.validate(v, value, **kwargs) | def validate(self, value): """ Validate passed-in value using all field validators. Return None if all validations pass; otherwise, return failed result returned by validator """ for v in self.validators: res = validation.validate(v, value) if res != 1: return res return None |
res = field.validate(value) | res = field.validate(value, instance=instance, field=field, REQUEST=REQUEST) | def validate(self, instance, REQUEST=None, errors=None, data=None, metadata=None): """Validate the state of the entire object""" if REQUEST: fieldset = REQUEST.form.get('fieldset', None) else: fieldset = None fields = [] |
if isinstance(wrapped, DefaultDublinCoreImpl): DefaultDublinCoreImpl.__init__(wrapped) | wrapped.initializeArchetype() | def getWidgets(self, instance=None, package=None, type=None, context=None, mode='edit', fields=None, schemata=None, nosort=None): """Empty widgets for standalone rendering""" |
self.error_log = self.getPortal().error_log | self.error_log = self.portal.error_log | def afterSetUp(self): # basic data # Put dummy sdm and dummy SESSION object into REQUEST request = self.app.REQUEST self.app._setObject('session_data_manager', DummySessionDataManager()) sdm = self.app.session_data_manager request.set('SESSION', sdm.getSessionData()) |
if RESPONSE is not None: RESPONSE.notFoundError("%s\n%s" % (name, '')) | REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, '')) | def __bobo_traverse__(self, REQUEST, name, RESPONSE=None): """ transparent access to session subobjects """ # is it a registered sub object data = self.getSubObject(name, REQUEST, RESPONSE) if data is not None: return data # or a standard attribute (maybe acquired...) target = getattr(self, name, None) if target is not... |
base = aq_base(instance) del base._md | if hasattr(aq_base(instance), '_md'): del base._md | def cleanupInstance(self, instance, item=None, container=None): base = aq_base(instance) del base._md |
accessor = field.getDefault | accessor = lambda: field.getDefault(instance) | def getWidgets(self, instance=None, package=None, type=None, context=None, mode='edit', fields=None, schemata=None, nosort=None): """Empty widgets for standalone rendering""" |
accessor = self.Schema()[key].getAccessor(self) | accessor = self.Schema()[key].getEditAccessor(self) if not accessor: accessor = self.Schema()[key].getAccessor(self) | def __getitem__(self, key): """play nice with externaleditor again""" if key not in self.Schema().keys() and key[:1] != "_": #XXX 2.2 return getattr(self, key, None) or getattr(aq_parent(aq_inner(self)), key, None) accessor = self.Schema()[key].getAccessor(self) return accessor() |
print "bind %s to %s" % (k,v) | def manage_templates(self, REQUEST=None): """Sets all the template/type mappings. """ prefix = 'template_names_' #import pdb; pdb.set_trace() for key in REQUEST.form.keys(): if key.startswith(prefix): k = key[len(prefix):] v = REQUEST.form.get(key) print "bind %s to %s" % (k,v) self.bindTemplate(k, v) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.