我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用types.FloatType()。
def getValueStrings( val, blnUgly=True ): #Used by joinWithComma function to join list items for SQL queries. #Expects to receive 'valid' types, as this was designed specifically for joining object attributes and nonvalid attributes were pulled. #If the default blnUgly is set to false, then the nonvalid types are ignored and the output will be pretty, but the SQL Insert statement will #probably be wrong. tplStrings = (types.StringType, types.StringTypes ) tplNums = ( types.FloatType, types.IntType, types.LongType, types.BooleanType ) if isinstance( val, tplNums ): return '#num#'+ str( val ) + '#num#' elif isinstance( val, tplStrings ): strDblQuote = '"' return strDblQuote + val + strDblQuote else: if blnUgly == True: return "Error: nonconvertable value passed - value type: %s" % type(val ) else: return None
def assertEquals( exp, got ): """assertEquals(exp, got) Two objects test as "equal" if: * they are the same object as tested by the 'is' operator. * either object is a float or complex number and the absolute value of the difference between the two is less than 1e-8. * applying the equals operator ('==') returns True. """ from types import FloatType, ComplexType if exp is got: r = True elif ( type( exp ) in ( FloatType, ComplexType ) or type( got ) in ( FloatType, ComplexType ) ): r = abs( exp - got ) < 1e-8 else: r = ( exp == got ) if not r: print >>sys.stderr, "Error: expected <%s> but got <%s>" % ( repr( exp ), repr( got ) ) traceback.print_stack()
def assertEquals( exp, got, msg = None ): """assertEquals( exp, got[, message] ) Two objects test as "equal" if: * they are the same object as tested by the 'is' operator. * either object is a float or complex number and the absolute value of the difference between the two is less than 1e-8. * applying the equals operator ('==') returns True. """ if exp is got: r = True elif ( type( exp ) in ( FloatType, ComplexType ) or type( got ) in ( FloatType, ComplexType ) ): r = abs( exp - got ) < 1e-8 else: r = ( exp == got ) if not r: print >>sys.stderr, "Error: expected <%s> but got <%s>%s" % ( repr( exp ), repr( got ), colon( msg ) ) traceback.print_stack()
def __imul__(self, other): """Producto punto con otro""" if isinstance(other, Vector3): self.x *= other.get_x() self.y *= other.get_y() self.z *= other.get_z() return self else: if isinstance(other, types.ListType) or isinstance(other, types.TupleType): self.x *= other[0] self.y *= other[1] self.z *= other[2] return self elif isinstance(other, types.IntType) or isinstance(other, types.FloatType): self.x *= other self.y *= other self.z *= other return self else: self.throwError(2, "__imul__") return self
def __idiv__(self, other): """Division con otro vector por valor""" if isinstance(other, Vector3): self.x /= other.get_x() self.y /= other.get_y() self.z /= other.get_z() return self else: if isinstance(other, types.ListType) or isinstance(other, types.TupleType): self.x /= other[0] self.y /= other[1] self.z /= other[2] return self elif isinstance(other, types.IntType) or isinstance(other, types.FloatType): self.x /= other self.y /= other self.z /= other return self else: self.throwError(2, "__idiv__") return self
def isOlderThan(self, arg): if not self.timestamp: return True if isinstance(arg, types.IntType) or isinstance(arg, types.LongType) or isinstance(arg, types.FloatType): return self.timestamp < arg if isinstance(arg, TimeStampFile): if arg.timestamp is None: return False else: return arg.timestamp > self.timestamp elif isinstance(arg, types.ListType): files = arg else: files = [arg] for f in files: if os.path.getmtime(f) > self.timestamp: return True return False
def isNewerThan(self, arg): if not self.timestamp: return False if isinstance(arg, types.IntType) or isinstance(arg, types.LongType) or isinstance(arg, types.FloatType): return self.timestamp > arg if isinstance(arg, TimeStampFile): if arg.timestamp is None: return False else: return arg.timestamp < self.timestamp elif isinstance(arg, types.ListType): files = arg else: files = [arg] for f in files: if os.path.getmtime(f) < self.timestamp: return True return False
def _parsePaneOptions(self, name, args): # Parse <args> for options. for arg, value in args.items(): if type(value) == types.FloatType: relvalue = value value = self._absSize(relvalue) else: relvalue = None if arg == 'size': self._size[name], self._relsize[name] = value, relvalue elif arg == 'min': self._min[name], self._relmin[name] = value, relvalue elif arg == 'max': self._max[name], self._relmax[name] = value, relvalue else: raise ValueError, 'keyword must be "size", "min", or "max"'
def __init__(self, user, passwd, host=constants.CDefMySQLDBHost, port=constants.CDefMySQLDBPort, db=constants.CDefMySQLDBName, identify=None, resetDB=False, resetIdentify=True, frequency=constants.CDefMySQLStatsGenFreq, commit_freq=constants.CDefMySQLStatsCommitFreq): """ The creator of the DBSQLite Class """ super(DBMySQLAdapter, self).__init__(frequency, identify) self.mysqldbmod = None self.connection = None self.resetDB = resetDB self.resetIdentify = resetIdentify self.db = db self.host = host self.port = port self.user = user self.passwd = passwd self.typeDict = {types.FloatType: "DOUBLE(14,6)"} self.cursorPool = None self.commitFreq = commit_freq
def __pow__(self, other): """Raise each element of sparse vector to a power. If power is another sparse vector, compute elementwise power. In this latter case, by convention, 0^0 = 0. """ if not isSparseVector(self): raise TypeError("Argument must be a SparseVector") if isSparseVector(other): rv = SparseVector(max(self.n, other.n), {}) for k in self.values.keys(): rv[k] = self[k]**other[k] return rv if not isinstance(other, types.IntType) and \ not isinstance(other, types.LongType) and \ not isinstance(other, types.FloatType): raise TypeError("Power must be numeric or a sparse vector") rv = SparseVector(self.n, {}) for k in self.values.keys(): rv[k] = math.pow(self[k], other) return rv
def _escape_json(json): """Escapes all string fields of JSON data. Operates recursively.""" t = type(json) if t == types.StringType or t == types.UnicodeType: return cgi.escape(json) elif t == types.IntType: return json elif t == types.FloatType: return json elif t == types.DictType: result = {} for f in json.keys(): result[f] = _escape_json(json[f]) return result elif t == types.ListType: result = [] for f in json: result.append(_escape_json(f)) return result else: raise RuntimeError, "Unsupported type: %s" % str(t)
def convert(cf): rc = [] for i in cf.keys(): if cf[i]['type'] == types.StringType: rc.append([i, cf[i]['val'], None]) elif cf[i]['type'] == types.FloatType: rc.append([i, `cf[i]['val']`, None]) elif cf[i]['type'] == types.IntType: rc.append([i, `cf[i]['val']`, None]) elif cf[i]['type'] == 'toggle': rc.append([i, write_yes(cf[i]['val']), 'toggle']) elif cf[i]['type'] == types.ListType: rc.append([i, `cf[i]['val']`, None]) else: error("don't know how to handle " + `cf[i]['type']`) return rc
def find_sqltype(val): """ Find sqlite data type which matches the type of `val`. Parameters ---------- val : any python type Returns ------- sqltype : str String with sql type which can be used to set up a sqlile table """ mapping = {\ types.NoneType: 'NULL', types.IntType: 'INTEGER', types.LongType: 'INTEGER', types.FloatType: 'REAL', # 'FLOAT' also works types.StringTypes: 'TEXT', # StringType + UnicodeType types.BufferType: 'BLOB'} for typ in mapping.keys(): if isinstance(val, typ): return mapping[typ] raise StandardError("type '%s' unknown, cannot find mapping " "to sqlite3 type" %str(type(val)))
def is_scalar_element(self, x): """Is x a scalar By default a scalar is an element in the complex number field. A class that wants to perform linear algebra on things other than numbers may override this function. """ return isinstance(x, types.IntType) or \ isinstance(x, types.FloatType) or \ isinstance(x, types.ComplexType)
def makeObjInsertStrings( obj, tplObjects = None, blnUseParens=True, blnGetAllAttrib=True ): # Returns a 3 val tuple, the first two of which are strings which can be dropped into a MySQL Insert statement for (1) column names and (2) values if not tplObjects: return None, None, None if isinstance( obj, tplObjects ): #find out what got passed - valid objects must be included in tuple tplObjects strDblQuote = '"' lstCols = list() lstVals = list() lstExcludedAttrib = list() dctObj = vars( obj ) lstObjVarNames = dctObj.keys() if blnGetAllAttrib: tplValidTypes = ( types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.StringTypes, types.NoneType ) for varName in lstObjVarNames: val = dctObj[ varName ] if isinstance( val, tplValidTypes ): lstCols.append( varName ) if val or val == 0: lstVals.append( dctObj[ varName ] ) else: lstVals.append('') else: lstExcludedAttrib.append( varName ) if blnUseParens: strCols = joinListItems( lstCols ) strVals = joinListItems( lstVals ) else: strCols = joinListItems( lstCols, blnUseParens=False ) strCols = joinListItems( lstVals, blnUseParens=False ) strCols = strCols.replace('"', '') return strCols, strVals, lstExcludedAttrib else: print 'No object passed.' return None, None, None
def to_sec(v): """ Convert millisecond, microsecond or nanosecond to second. ms_to_ts, us_to_ts, ns_to_ts are then deprecated. """ v = float(str(v)) if (type(v) != types.FloatType or v < 0): raise ValueError('invalid time to convert to second: {v}'.format(v=v)) l = len(str(int(v))) if l == 10: return int(v) elif l == 13: return int(v / 1000) elif l == 16: return int(v / (1000**2)) elif l == 19: return int(v / (1000**3)) else: raise ValueError( 'invalid time length, not 10, 13, 16 or 19: {v}'.format(v=v))
def ponderate(self, a=1): """Pondera el vector por un numero""" if isinstance(a, types.FloatType) or isinstance(a, types.IntType): self.x *= a self.y *= a self.z *= a else: self.throwError(2, "ponderate") return self
def __mul__(self, other): """Producto punto o producto por valor""" if isinstance(other, Vector3): return Vector3(self.x * other.get_x(), self.y * other.get_y(), self.z * other.get_z()) else: if isinstance(other, types.ListType) or isinstance(other, types.TupleType): return Vector3(self.x * other[0], self.y * other[1], self.z * other[2]) elif isinstance(other, types.IntType) or isinstance(other, types.FloatType): return Vector3(self.x * other, self.y * other, self.z * other) else: self.throwError(2, "__mul__") return self
def __div__(self, other): """Dividir por un ector o por un valor""" if isinstance(other, Vector3): return Vector3(self.x / other.get_x(), self.y / other.get_y(), self.z / other.get_z()) else: if isinstance(other, types.IntType) or isinstance(other, types.FloatType): return Vector3(self.x / other, self.y / other, self.z / other) else: self.throwError(2, "__div__") return self
def show_font_details(font): print('{0:-^80}:'.format(' Font Details: ')) for name in dir(font): if name.startswith('_'): continue value = getattr(font, name) if name == 'sfnt_names': for locale, _name, _value in value: print('{0:>32}: {1} = {2}'.format(locale, _name, _value)) if type(value) in (types.IntType, types.FloatType,) + types.StringTypes: print('{0:>32}: {1}'.format(name, value))
def AddRow( self, *cells ) : height = None if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ): height = int( cells[ 0 ] ) cells = cells[ 1 : ] # make sure all of the spans add up to the number of columns # otherwise the table will get corrupted if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) : raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' ) self.Rows.append( ( height, cells ) )
def mysql_escape(f): @wraps(f) def decorated_function(*args, **kwargs): newargs = [] #??????????? for arg in args: #???????? if type(arg) is types.StringType or type(arg) is types.UnicodeType: newargs.append(MySQLdb.escape_string(arg)) #?? elif isinstance(arg, dict): newargs.append(MySQLdb.escape_dict(arg, { types.StringType: _str_escape, types.UnicodeType: _str_escape, types.IntType: _no_escape, types.FloatType: _no_escape })) #??????? else: newargs.append(arg) newargs = tuple(newargs) func = f(*newargs, **kwargs) return func return decorated_function
def __init__(self, dbname=constants.CDefSQLiteDBName, identify=None, resetDB=False, resetIdentify=True, frequency=constants.CDefSQLiteStatsGenFreq, commit_freq=constants.CDefSQLiteStatsCommitFreq): """ The creator of the DBSQLite Class """ super(DBSQLite, self).__init__(frequency, identify) self.sqlite3mod = None self.connection = None self.resetDB = resetDB self.resetIdentify = resetIdentify self.dbName = dbname self.typeDict = {types.FloatType: "real"} self.cursorPool = None self.commitFreq = commit_freq
def __rpow__(self, other): """Use each element of sparse vector as power of base.""" if not isSparseVector(self): raise TypeError("Argument must be a SparseVector") if not isinstance(other, types.IntType) and \ not isinstance(other, types.LongType) and \ not isinstance(other, types.FloatType): raise TypeError("Power must be numeric") rv = SparseVector(self.n, {}) for k in self.values.keys(): rv[k] = math.pow(other, self[k]) return rv
def object_properties_count(self, o): """ returns the number of user browsable properties of an object. """ o_type = type(o) if isinstance(o, (types.DictType, types.ListType, types.TupleType, set,)): return len(o) elif isinstance(o, (types.NoneType, types.BooleanType, types.FloatType, types.UnicodeType, types.FloatType, types.IntType, types.StringType, types.LongType, types.ModuleType, types.MethodType, types.FunctionType,)): return 0 else: # Following lines are used to debug variables members browsing # and counting # if False and str(o_type) == "<class 'socket._socketobject'>": # print "@378" # print dir(o) # print "hasattr(o, '__dict__')=%s" % hasattr(o,'__dict__') # count = 0 # if hasattr(o, '__dict__'): # for m_name, m_value in o.__dict__.iteritems(): # if m_name.startswith('__'): # print " %s=>False" % (m_name,) # continue # if type(m_value) in (types.ModuleType, types.MethodType, types.FunctionType,): # print " %s=>False" % (m_name,) # continue # print " %s=>True" % (m_name,) # count +=1 # print " %s => %s = %s" % (o, count, dir(o),) # else: if hasattr(o, '__dict__'): count = len([m_name for m_name, m_value in o.__dict__.iteritems() if not m_name.startswith('__') and not type(m_value) in (types.ModuleType, types.MethodType, types.FunctionType,) ]) else: count = 0 return count
def testConversion(self): """test timetostring and stringtotime""" Time.setcurtime() assert type(Time.curtime) is types.FloatType or types.LongType assert type(Time.curtimestr) is types.StringType assert (Time.cmp(int(Time.curtime), Time.curtimestr) == 0 or Time.cmp(int(Time.curtime) + 1, Time.curtimestr) == 0) time.sleep(1.05) assert Time.cmp(time.time(), Time.curtime) == 1 assert Time.cmp(Time.timetostring(time.time()), Time.curtimestr) == 1
def set_hp(self, hp): if type(hp) in [ types.IntType, types.FloatType]: self._DistributedCapturePoint__hp = hp else: self._DistributedCapturePoint__hp = 0
def set_maxHp(self, maxHp): if type(maxHp) in [ types.IntType, types.FloatType]: self._DistributedCapturePoint__maxHp = maxHp else: self._DistributedCapturePoint__maxHp = 1
def set_hp(self, hp): if type(hp) in [ types.IntType, types.FloatType]: self._DistributedBattleAvatar__hp = hp else: self._DistributedBattleAvatar__hp = 0
def set_maxHp(self, maxHp): if type(maxHp) in [ types.IntType, types.FloatType]: self._DistributedBattleAvatar__maxHp = maxHp else: self._DistributedBattleAvatar__maxHp = 1
def set_hp(self, hp): if type(hp) in [ types.IntType, types.FloatType]: self._DistributedInteractiveProp__hp = hp else: self._DistributedInteractiveProp__hp = 1
def frepr(var, ffmt="%.16e"): """Similar to Python's repr(), but return floats formated with `ffmt` if `var` is a float. If `var` is a string, e.g. 'lala', it returns 'lala' not "'lala'" as Python's repr() does. Parameters ---------- var : almost anything (str, None, int, float) ffmt : format specifier for float values Examples -------- >>> frepr(1) '1' >>> frepr(1.0) '1.000000000000000e+00' >>> frepr(None) 'None' >>> # Python's repr() does: 'abc' -> "'abc'" >>> frepr('abc') 'abc' """ if isinstance(var, types.FloatType): return ffmt %var elif isinstance(var, types.StringType): return var else: return repr(var)
def get_float_key_map(cls, key_map): float_key_map = {} for (key,value) in key_map.items(): if type(value) == types.FloatType: float_key_map[key] = value return float_key_map
def dump(self, pickler): pickler.dump(self.tag) pickler.dump(self._what) pickler.dump(self._extra) pickler.dump(self._comment) if self.prop: # Skip system variables pickler.dump([x for x in self.prop.items() if type(x[1]) in (IntType, LongType, FloatType, BooleanType, StringType, UnicodeType)]) else: pickler.dump(None) pickler.dump(self.enable) # ---------------------------------------------------------------------- # Load card from unpickler # ----------------------------------------------------------------------
def _convert_to(l, dest_unit="m"): if type(l) in (types.IntType, types.LongType, types.FloatType): return l * _m[_default_unit] * scale['u'] / _m[dest_unit] elif not isinstance(l, length): l = length(l) # convert to length instance if necessary return (l.t + l.u*scale['u'] + l.v*scale['v'] + l.w*scale['w'] + l.x*scale['x']) / _m[dest_unit]
def humannum(data, unit=None, include=None, exclude=None): if isinstance(data, types.DictType): data = data.copy() keys = set(data.keys()) if include is not None: keys = keys & set(include) if exclude is not None: keys = keys - set(exclude) for k in keys: data[k] = humannum(data[k]) return data elif isinstance(data, types.BooleanType): # We have to deal with bool because for historical reason bool is # subclass of int. # When bool is introduced into python 2.2 it is represented with int, # similar to C. return data elif isinstance(data, types.ListType): return [humannum(x) for x in data] elif isinstance(data, types.StringTypes): return data elif isinstance(data, integer_types): return humannum_int(data, unit=unit) elif isinstance(data, types.FloatType): if data > 999: return humannum_int(int(data), unit=unit) elif abs(data) < 0.0000000001: return '0' else: return '%.2f' % (data) else: return data
def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns=0, maxDepth=None): '''An insanely CPU-intensive process for finding stuff. ''' if paths is None: paths = [] if seen is None: seen = {} if eq(start, goal): paths.append(path) if seen.has_key(id(start)): if seen[id(start)] is start: return if maxDepth is not None: if maxDepth == 0: return maxDepth -= 1 seen[id(start)] = start if isinstance(start, types.DictionaryType): r = [] for k, v in start.items(): objgrep(k, goal, eq, path+'{'+repr(v)+'}', paths, seen, showUnknowns, maxDepth) objgrep(v, goal, eq, path+'['+repr(k)+']', paths, seen, showUnknowns, maxDepth) elif isinstance(start, types.ListType) or isinstance(start, types.TupleType): for idx in xrange(len(start)): objgrep(start[idx], goal, eq, path+'['+str(idx)+']', paths, seen, showUnknowns, maxDepth) elif isinstance(start, types.MethodType): objgrep(start.im_self, goal, eq, path+'.im_self', paths, seen, showUnknowns, maxDepth) objgrep(start.im_func, goal, eq, path+'.im_func', paths, seen, showUnknowns, maxDepth) objgrep(start.im_class, goal, eq, path+'.im_class', paths, seen, showUnknowns, maxDepth) elif hasattr(start, '__dict__'): for k, v in start.__dict__.items(): objgrep(v, goal, eq, path+'.'+k, paths, seen, showUnknowns, maxDepth) if isinstance(start, types.InstanceType): objgrep(start.__class__, goal, eq, path+'.__class__', paths, seen, showUnknowns, maxDepth) elif isinstance(start, weakref.ReferenceType): objgrep(start(), goal, eq, path+'()', paths, seen, showUnknowns, maxDepth) elif (isinstance(start, types.StringTypes+ (types.IntType, types.FunctionType, types.BuiltinMethodType, RegexType, types.FloatType, types.NoneType, types.FileType)) or type(start).__name__ in ('wrapper_descriptor', 'method_descriptor', 'member_descriptor', 'getset_descriptor')): pass elif showUnknowns: print 'unknown type', type(start), start return paths