def _build_query(self, cls, filters, limit, order_by): import types if len(filters) > 4: raise Exception('Too many filters, max is 4') parts = [] properties = cls.properties(hidden=False) for filter, value in filters: name, op = filter.strip().split() found = False for property in properties: if property.name == name: found = True if types.TypeType(value) == types.ListType: filter_parts = [] for val in value: val = self.encode_value(property, val) filter_parts.append("'%s' %s '%s'" % (name, op, val)) parts.append("[%s]" % " OR ".join(filter_parts)) else: value = self.encode_value(property, value) parts.append("['%s' %s '%s']" % (name, op, value)) if not found: raise Exception('%s is not a valid field' % name) if order_by: if order_by.startswith("-"): key = order_by[1:] type = "desc" else: key = order_by type = "asc" parts.append("['%s' starts-with ''] sort '%s' %s" % (key, key, type)) return ' intersection '.join(parts)
def create_interface_mock(interface_class): '''given a Zope Interface class return a Mock sub class that implements the given Zope interface class. Mock objects created from this InterfaceMock will have Attributes and Methods required in the Interface will not have Attributes or Methods that are not specified ''' # the init method, automatically spec the interface methods def init(self, *args, **kwargs): Mock.__init__(self, spec=interface_class.names(), *args, **kwargs) # subclass named '<interface class name>Mock' name = interface_class.__name__ + "Mock" # create the class object and provide the init method klass = types.TypeType(name, (Mock, ), {"__init__": init}) # the new class should implement the interface classImplements(klass, interface_class) return klass
def convertPoints(): overwriteOutputDefault = arcpy.overwriteOutput arcpy.overwriteOutput = True # Input point FC # Output FC # Feature Field # Sort Field # Close Line or Leave Open inPts = arcpy.GetParameterAsText(0) outFeatures = arcpy.GetParameterAsText(1) IDField = arcpy.GetParameterAsText(2) sortField = arcpy.GetParameterAsText(3) closeLine = arcpy.GetParameterAsText(4) if IDField in ["", "#"]: IDField = None if sortField in ["", "#"]: cursorSort = IDField else: if IDField: cursorSort = IDField + ";" + sortField else: cursorSort = sortField if types.TypeType(closeLine) != types.BooleanType: if closeLine.lower() == "false": close = False else: close = True convertPointsToLine(inPts, outFeatures, IDField, cursorSort, close) arcpy.overwriteOutput = overwriteOutputDefault
def doClassMethodAdd(target, method, hook): if isinstance(target, (types.TypeType, types.ClassType)): setattr(target, method, classmethod(hook)) else: setattr(target, method, hook.__get__(types.TypeType(target), types.TypeType)) return hook
def doClassMethodHook(target, method, hook, invoke=HookInvoke.DEFAULT, enabled=True): origin = getattr(target, method).__func__ override = HookFunction(hook, origin, invoke, enabled) if isinstance(target, (types.TypeType, types.ClassType)): setattr(target, method, classmethod(override)) else: setattr(target, method, override.__get__(types.TypeType(target), types.TypeType)) return hook
def _build_filter_part(self, cls, filters, order_by=None): """ Build the filter part """ import types query_parts = [] order_by_filtered = False if order_by: if order_by[0] == "-": order_by_method = "desc"; order_by = order_by[1:] else: order_by_method = "asc"; for filter in filters: (name, op) = filter[0].strip().split(" ") value = filter[1] property = cls.find_property(name) if name == order_by: order_by_filtered = True if types.TypeType(value) == types.ListType: filter_parts = [] for val in value: val = self.encode_value(property, val) filter_parts.append("`%s` %s '%s'" % (name, op, val.replace("'", "''"))) query_parts.append("(%s)" % (" or ".join(filter_parts))) else: val = self.encode_value(property, value) query_parts.append("`%s` %s '%s'" % (name, op, val.replace("'", "''"))) type_query = "(`__type__` = '%s'" % cls.__name__ for subclass in cls.__sub_classes__: type_query += " or `__type__` = '%s'" % subclass.__name__ type_query +=")" query_parts.append(type_query) order_by_query = "" if order_by: if not order_by_filtered: query_parts.append("`%s` like '%%'" % order_by) order_by_query = " order by `%s` %s" % (order_by, order_by_method) if len(query_parts) > 0: return "where %s %s" % (" and ".join(query_parts), order_by_query) else: return ""
def query(self, cls, filters, limit=None, order_by=None): import types if len(filters) > 4: raise SDBPersistenceError('Too many filters, max is 4') s = "['__type__'='%s'" % cls.__name__ for subclass in cls.__sub_classes__: s += " OR '__type__'='%s'" % subclass.__name__ s += "]" parts = [s] properties = cls.properties(hidden=False) for filter, value in filters: name, op = filter.strip().split() found = False for property in properties: if property.name == name: found = True if types.TypeType(value) == types.ListType: filter_parts = [] for val in value: val = self.encode_value(property, val) filter_parts.append("'%s' %s '%s'" % (name, op, val)) parts.append("[%s]" % " OR ".join(filter_parts)) else: value = self.encode_value(property, value) parts.append("['%s' %s '%s']" % (name, op, value)) if not found: raise SDBPersistenceError('%s is not a valid field' % name) if order_by: if order_by.startswith("-"): key = order_by[1:] type = "desc" else: key = order_by type = "asc" parts.append("['%s' starts-with ''] sort '%s' %s" % (key, key, type)) query = ' intersection '.join(parts) rs = self.domain.query(query, max_items=limit) return self._object_lister(cls, rs)
def create_interface_mock(interface_class): """ Dynamically create a Mock sub class that implements the given Zope interface class. Adapted from http://programmaticallyspeaking.com/ mocking-zope-interfaces.html Examples -------- >>> from zope import interface >>> class IFoo(interface.Interface): >>> def bar(): >>> pass >>> IFooMock = create_interface_mock(IFoo) >>> foo_mock = IFooMock() >>> assert IFoo in interface.providedBy(foo_mock) >>> foo_mock.bar.return_value = "BANG!" >>> assert foo_mock.bar() == "BANG!" >>> # this would raise an error, unlike a normal mock >>> # foo_mock.baz() """ # the init method, automatically specifying the interface methods def init(self, *args, **kwargs): Mock.__init__(self, spec=interface_class.names(), *args, **kwargs) # we derive the sub class name from the interface name name = interface_class.__name__ + "Mock" # create the class object and provide the init method klass = types.TypeType(name, (Mock, ), {"__init__": init}) # the new class should implement the interface classImplements(klass, interface_class) return klass
def _createInterfaceMock(interfaces): """Dynamically create a Mock sub class that implements the given zope.interfaces""" spec = reduce(lambda fullSpec, intf: fullSpec + intf.names(), interfaces, []) # the init method, automatically specifying the interface methods def init(self, *args, **kwargs): Mock.__init__(self, spec=spec, *args, **kwargs) # we derive the sub class name from the interface names interfaceNames = reduce( lambda fullName, intf: "%s%s" % (fullName, intf.__name__), interfaces, "") name = interfaceNames + "Mock" # create the class object and provide the init method mockClass = types.TypeType(name, (Mock, ), {"__init__": init}) # the new class should implement the interfaces for i in interfaces: classImplements(mockClass, i) return mockClass
def _build_filter_part(self, cls, filters, order_by=None, select=None): """ Build the filter part """ import types query_parts = [] order_by_filtered = False if order_by: if order_by[0] == "-": order_by_method = "DESC" order_by = order_by[1:] else: order_by_method = "ASC" if select: if order_by and order_by in select: order_by_filtered = True query_parts.append("(%s)" % select) if isinstance(filters, six.string_types): query = "WHERE %s AND `__type__` = '%s'" % (filters, cls.__name__) if order_by in ["__id__", "itemName()"]: query += " ORDER BY itemName() %s" % order_by_method elif order_by is not None: query += " ORDER BY `%s` %s" % (order_by, order_by_method) return query for filter in filters: filter_parts = [] filter_props = filter[0] if not isinstance(filter_props, list): filter_props = [filter_props] for filter_prop in filter_props: (name, op) = filter_prop.strip().split(" ", 1) value = filter[1] property = cls.find_property(name) if name == order_by: order_by_filtered = True if types.TypeType(value) == list: filter_parts_sub = [] for val in value: val = self.encode_value(property, val) if isinstance(val, list): for v in val: filter_parts_sub.append(self._build_filter(property, name, op, v)) else: filter_parts_sub.append(self._build_filter(property, name, op, val)) filter_parts.append("(%s)" % (" OR ".join(filter_parts_sub))) else: val = self.encode_value(property, value) if isinstance(val, list): for v in val: filter_parts.append(self._build_filter(property, name, op, v)) else: filter_parts.append(self._build_filter(property, name, op, val)) query_parts.append("(%s)" % (" or ".join(filter_parts))) type_query = "(`__type__` = '%s'" % cls.__name__ for subclass in self._get_all_decendents(cls).keys(): type_query += " or `__type__` = '%s'" % subclass type_query += ")" query_parts.append(type_query) order_by_query = "" if order_by: if not order_by_filtered: query_parts.append("`%s` LIKE '%%'" % order_by) if order_by in ["__id__", "itemName()"]: order_by_query = " ORDER BY itemName() %s" % order_by_method else: order_by_query = " ORDER BY `%s` %s" % (order_by, order_by_method) if len(query_parts) > 0: return "WHERE %s %s" % (" AND ".join(query_parts), order_by_query) else: return ""
def getValue(self, name): ''' Returns the values of the variables given in name; name is either a String or a list of Strings. ''' if types.TypeType(name) == types.ListType: n = len(name) nameList = True names = name else: n = 1 nameList = False names = [name] iReal = [] iInteger = [] iBoolean = [] iString = [] refReal = [] refInteger = [] refBoolean = [] refString = [] for i, x in enumerate(names): dataType = self.description.scalarVariables[x].type.type if dataType == 'Real': refReal.append( self.description.scalarVariables[x].valueReference) iReal.append(i) elif dataType == 'Integer': refInteger.append( self.description.scalarVariables[x].valueReference) iInteger.append(i) elif dataType == 'Boolean': refBoolean.append( self.description.scalarVariables[x].valueReference) iBoolean.append(i) elif dataType == 'String': refString.append( self.description.scalarVariables[x].valueReference) iString.append(i) retValue = range(n) k = len(refReal) if k > 0: ref = FMUInterface.createfmiReferenceVector(k) for i in xrange(k): ref[i] = refReal[i] values = self.interface.fmiGetReal(ref) for i in xrange(k): retValue[iReal[i]] = values[i] k = len(refInteger) if k > 0: ref = FMUInterface.createfmiReferenceVector(k) for i in xrange(k): ref[i] = refInteger[i] values = self.interface.fmiGetInteger(ref) for i in xrange(k): retValue[iInteger[i]] = values[i] k = len(refBoolean) if k > 0: ref = FMUInterface.createfmiReferenceVector(k) for i in xrange(k): ref[i] = refBoolean[i] values = self.interface.fmiGetBoolean(ref) for i in xrange(k): retValue[iBoolean[i]] = values[i] k = len(refString) if k > 0: ref = FMUInterface.createfmiReferenceVector(k) for i in xrange(k): ref[i] = refString[i] values = self.interface.fmiGetString(ref) for i in xrange(k): retValue[iString[i]] = values[i] if nameList: return retValue else: return retValue[0]
def func(self): print "blah, blah, blah" """ d = {} exec(code, d) import types print types.ClassType.__class__ old_class = types.ClassType('OldClass', (), d) o = old_class() o.func() new_class = types.TypeType('NewClass', (), d) o = new_class() o.func() print '********************************' print types.ClassType print type(types.ClassType) print types.TypeType print type(types.TypeType) print type(types.TypeType).__class__ print types.MethodType
def _build_filter_part(self, cls, filters, order_by=None): """ Build the filter part """ import types query_parts = [] order_by_filtered = False if order_by: if order_by[0] == "-": order_by_method = "desc" order_by = order_by[1:] else: order_by_method = "asc" for filter in filters: filter_parts = [] filter_props = filter[0] if type(filter_props) != list: filter_props = [filter_props] for filter_prop in filter_props: (name, op) = filter_prop.strip().split(" ", 1) value = filter[1] property = cls.find_property(name) if name == order_by: order_by_filtered = True if types.TypeType(value) == types.ListType: filter_parts_sub = [] for val in value: val = self.encode_value(property, val) if isinstance(val, list): for v in val: filter_parts_sub.append( self._build_filter(property, name, op, v)) else: filter_parts_sub.append( self._build_filter(property, name, op, val)) filter_parts.append("(%s)" % (" or ".join(filter_parts_sub))) else: val = self.encode_value(property, value) if isinstance(val, list): for v in val: filter_parts.append( self._build_filter(property, name, op, v)) else: filter_parts.append( self._build_filter(property, name, op, val)) query_parts.append("(%s)" % (" or ".join(filter_parts))) type_query = "(`__type__` = '%s'" % cls.__name__ for subclass in self._get_all_decendents(cls).keys(): type_query += " or `__type__` = '%s'" % subclass type_query += ")" query_parts.append(type_query) order_by_query = "" if order_by: if not order_by_filtered: query_parts.append("`%s` like '%%'" % order_by) order_by_query = " order by `%s` %s" % (order_by, order_by_method) if len(query_parts) > 0: return "where %s %s" % (" and ".join(query_parts), order_by_query) else: return ""
def loads(bytes): s = wrap.loads(bytes) if s[0] == TYPE_NON_USERDEFINED: return vars(s[2])[s[1]] elif s[0] == TYPE_USERDEFINED: return types.TypeType(*s[1:])