python类FloatType()的实例源码

recipe-572197.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
recipe-577473.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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()
recipe-577482.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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()
utils_math.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
utils_math.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
mx.py 文件源码 项目:mx 作者: graalvm 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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
mx.py 文件源码 项目:mx 作者: graalvm 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
Pmw.py 文件源码 项目:ecel 作者: ARL-UTEP-OC 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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"'
DBAdapters.py 文件源码 项目:CAAPR 作者: Stargrazer82301 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
DBAdapters.py 文件源码 项目:CAAPR 作者: Stargrazer82301 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
sparse_vector_class.py 文件源码 项目:NLP.py 作者: PythonOptimizers 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
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
util.py 文件源码 项目:eclipse2017 作者: google 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
rc.py 文件源码 项目:jack 作者: jack-cli-cd-ripper 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
sql.py 文件源码 项目:pwtools 作者: elcorto 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
recipe-189971.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
recipe-572197.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
timeutil.py 文件源码 项目:pykit 作者: baishancloud 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
utils_math.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
utils_math.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
utils_math.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:fontmerger 作者: iij 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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))
Elements.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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 ) )
Elements.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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 ) )
Elements.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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 ) )
mysql_escape_warp.py 文件源码 项目:iOS-private-api-checker 作者: NetEaseGame 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
Elements.py 文件源码 项目:Problematica-public 作者: TechMaz 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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 ) )


问题


面经


文章

微信
公众号

扫码关注公众号