Python types.FloatType() Examples

The following are 30 code examples of types.FloatType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: recipe-577473.py    From code with MIT License 6 votes vote down vote up
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() 
Example #2
Source File: recipe-577538.py    From code with MIT License 6 votes vote down vote up
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() 
Example #3
Source File: recipe-577538.py    From code with MIT License 6 votes vote down vote up
def assertNotEquals( exp, got, msg = None ):
    """assertNotEquals( 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 = False
    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 different values but both are equal to <%s>%s" % ( repr( exp ), colon( msg ) )
        traceback.print_stack() 
Example #4
Source File: NumberToString.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def realEncode(self, data):
        """Convert number to string.
        If no formatString was specified in class constructor data type is
        dynamically determined and converted using a default formatString of
        "%d", "%f", or "%d" for Int, Float, and Long respectively.
        """

        if self._formatString is None:
            retType = type(data)
            if retType is IntType:
                return "%d" % data
            elif retType is FloatType:
                return "%f" % data
            elif retType is LongType:
                return "%d" % data
            else:
                return data

        return self._formatString % data 
Example #5
Source File: occutils_geomplate.py    From pythonocc-utils with GNU Lesser General Public License v3.0 6 votes vote down vote up
def radius(self, z):
        '''
        sets the height of the point constraining the plate, returns
        the radius at this point
        '''
        if isinstance(z, types.FloatType):
            self.pnt.SetX(z)
        else:
            self.pnt.SetX(float(z[0]))
        self.build_surface()
        uv = uv_from_projected_point_on_face(self.plate, self.pnt)
        print(uv)
        radius = radius_at_uv(self.plate, uv.X(), uv.Y())
        print('z: %f radius: %f ' % (z, radius))
        self.curr_radius = radius
        return self.targetRadius-abs(radius) 
Example #6
Source File: c_spec.py    From Computable with MIT License 5 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        # Not sure this is really that safe...
        self.type_name = 'float'
        self.check_func = 'PyFloat_Check'
        self.c_type = 'double'
        self.return_type = 'double'
        self.to_c_return = "PyFloat_AsDouble(py_obj)"
        self.matching_types = [types.FloatType] 
Example #7
Source File: mysql_escape_warp.py    From iOS-private-api-checker with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #8
Source File: timeutil.py    From pykit with MIT License 5 votes vote down vote up
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)) 
Example #9
Source File: pyjsontestrunner.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def valueTreeToString(fout, value, path = '.'):
    ty = type(value) 
    if ty  is types.DictType:
        fout.write('%s={}\n' % path)
        suffix = path[-1] != '.' and '.' or ''
        names = value.keys()
        names.sort()
        for name in names:
            valueTreeToString(fout, value[name], path + suffix + name)
    elif ty is types.ListType:
        fout.write('%s=[]\n' % path)
        for index, childValue in zip(xrange(0,len(value)), value):
            valueTreeToString(fout, childValue, path + '[%d]' % index)
    elif ty is types.StringType:
        fout.write('%s="%s"\n' % (path,value))
    elif ty is types.IntType:
        fout.write('%s=%d\n' % (path,value))
    elif ty is types.FloatType:
        fout.write('%s=%.16g\n' % (path,value))
    elif value is True:
        fout.write('%s=true\n' % path)
    elif value is False:
        fout.write('%s=false\n' % path)
    elif value is None:
        fout.write('%s=null\n' % path)
    else:
        assert False and "Unexpected value type" 
Example #10
Source File: DistributedCapturePoint.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_hp(self, hp):
            if type(hp) in [types.IntType, types.FloatType]:
                self.__hp = hp
            else:
                self.__hp = 0 
Example #11
Source File: DistributedCapturePoint.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_maxHp(self, maxHp):
            if type(maxHp) in [types.IntType, types.FloatType]:
                self.__maxHp = maxHp
            else:
                self.__maxHp = 1 
Example #12
Source File: DistributedInteractiveProp.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_hp(self, hp):
            if type(hp) in [types.IntType, types.FloatType]:
                self.__hp = hp
            else:
                self.__hp = 1 
Example #13
Source File: DistributedInteractiveProp.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_maxHp(self, maxHp):
            if type(maxHp) in [types.IntType, types.FloatType]:
                self.__maxHp = maxHp
            else:
                self.__maxHp = 1 
Example #14
Source File: DistributedBattleAvatar.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_hp(self, hp):
            if type(hp) in [types.IntType, types.FloatType]:
                self.__hp = hp
            else:
                self.__hp = 0 
Example #15
Source File: EdwardsActiveDigitalController.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, name, host='ip-address', port=9955):

        Instrument.__init__(self, name, tags=['physical'])
        
        self.add_parameter('condenser_pressure',
            type=types.FloatType,
            flags=Instrument.FLAG_GET, units='mbar')
        self.add_parameter('still_pressure',
            type=types.FloatType,
            flags=Instrument.FLAG_GET, units='mbar')
            
        self.HOST, self.PORT = host, port 
Example #16
Source File: mpfit.py    From serval with MIT License 5 votes vote down vote up
def parinfo(self, parinfo=None, key='a', default=None, n=0):
		if self.debug:
			print 'Entering parinfo...'
		if (n == 0) and (parinfo is not None):
			n = len(parinfo)
		if n == 0:
			values = default
	
			return values
		values = []
		for i in range(n):
			if (parinfo is not None) and (parinfo[i].has_key(key)):
				values.append(parinfo[i][key])
			else:
				values.append(default)

		# Convert to numeric arrays if possible
		test = default
		if type(default) == types.ListType:
			test=default[0]
		if isinstance(test, types.IntType):
			values = numpy.asarray(values, int)
		elif isinstance(test, types.FloatType):
			values = numpy.asarray(values, float)
		return values
	
	# Call user function or procedure, with _EXTRA or not, with
	# derivatives or not. 
Example #17
Source File: unit.py    From OpenRAM with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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] 
Example #18
Source File: timeJ2000.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def __coerce__(self,other):
        if isinstance(other,types.FloatType) or isinstance(other,types.IntType) or isinstance(other,types.LongType):
            return (self.sec,other)
        if isinstance(other,types.StringType):
            return (from_J2000(self.sec,"YYYYMMDD_HHMMSS"),other)
        if isinstance(other,types.ListType) or isinstance(other,types.TupleType):
            return (from_J2000(self.sec,"LIST"),other) 
Example #19
Source File: shapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _repr(self,I=None):
    '''return a repr style string with named fixed args first, then keywords'''
    if type(self) is InstanceType:
        if self is EmptyClipPath:
            _addObjImport(self,I,'EmptyClipPath')
            return 'EmptyClipPath'
        if I: _addObjImport(self,I)
        if isinstance(self,Shape):
            from inspect import getargs
            args, varargs, varkw = getargs(self.__init__.im_func.func_code)
            P = self.getProperties()
            s = self.__class__.__name__+'('
            for n in args[1:]:
                v = P[n]
                del P[n]
                s = s + '%s,' % _repr(v,I)
            for n,v in P.items():
                v = P[n]
                s = s + '%s=%s,' % (n, _repr(v,I))
            return s[:-1]+')'
        else:
            return repr(self)
    elif type(self) is FloatType:
        return fp_str(self)
    elif type(self) in (ListType,TupleType):
        s = ''
        for v in self:
            s = s + '%s,' % _repr(v,I)
        if type(self) is ListType:
            return '[%s]' % s[:-1]
        else:
            return '(%s%s)' % (s[:-1],len(self)==1 and ',' or '')
    else:
        return repr(self) 
Example #20
Source File: para.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def shrinkWrap(self, line):
        # for non justified text, collapse adjacent text/shift's into single operations
        result = []
        index = 0
        maxindex = len(line)
        while index<maxindex:
            e = line[index]
            te = type(e)
            if te in (StringType, UnicodeType) and index<maxindex-1:
                # collect strings and floats
                thestrings = [e]
                thefloats = 0.0
                index = index+1
                nexte = line[index]
                tnexte = type(nexte)
                while index<maxindex and (tnexte in (FloatType, StringType, UnicodeType)):
                    # switch to expandable space if appropriate
                    if tnexte is FloatType:
                        if thefloats<0 and nexte>0:
                            thefloats = -thefloats
                        if nexte<0 and thefloats>0:
                            nexte = -nexte
                        thefloats = thefloats + nexte
                    elif tnexte in (StringType, UnicodeType):
                        thestrings.append(nexte)
                    index = index+1
                    if index<maxindex:
                        nexte = line[index]
                        tnexte = type(nexte)
                # wrap up the result
                s = ' '.join(thestrings)
                result.append(s)
                result.append(float(thefloats))
                # back up for unhandled element
                index = index-1
            else:
                result.append(e)
            index = index+1

        return result 
Example #21
Source File: psCharStrings.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def compile(self):
		if self.bytecode is not None:
			return
		assert self.program, "illegal CharString: decompiled to empty program"
		assert self.program[-1] in ("endchar", "return", "callsubr", "callgsubr",
				"seac"), "illegal CharString"
		bytecode = []
		opcodes = self.opcodes
		program = self.program
		encodeInt = self.getIntEncoder()
		encodeFixed = self.getFixedEncoder()
		i = 0
		end = len(program)
		while i < end:
			token = program[i]
			i = i + 1
			tp = type(token)
			if tp == types.StringType:
				try:
					bytecode.extend(map(chr, opcodes[token]))
				except KeyError:
					raise CharStringCompileError, "illegal operator: %s" % token
				if token in ('hintmask', 'cntrmask'):
					bytecode.append(program[i])  # hint mask
					i = i + 1
			elif tp == types.IntType:
				bytecode.append(encodeInt(token))
			elif tp == types.FloatType:
				bytecode.append(encodeFixed(token))
			else:
				assert 0, "unsupported type: %s" % tp
		try:
			bytecode = "".join(bytecode)
		except TypeError:
			print bytecode
			raise
		self.setBytecode(bytecode) 
Example #22
Source File: banana.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _encode(self, obj, write):
        if isinstance(obj, types.ListType) or isinstance(obj, types.TupleType):
            if len(obj) > SIZE_LIMIT:
                raise BananaError, \
                      "list/tuple is too long to send (%d)" % len(obj)
            int2b128(len(obj), write)
            write(LIST)
            for elem in obj:
                self._encode(elem, write)
        elif isinstance(obj, types.IntType):
            if obj >= 0:
                int2b128(obj, write)
                write(INT)
            else:
                int2b128(-obj, write)
                write(NEG)
        elif isinstance(obj, types.LongType):
            if obj >= 0l:
                int2b128(obj, write)
                write(LONGINT)
            else:
                int2b128(-obj, write)
                write(LONGNEG)
        elif isinstance(obj, types.FloatType):
            write(FLOAT)
            write(struct.pack("!d", obj))
        elif isinstance(obj, types.StringType):
            # TODO: an API for extending banana...
            if (self.currentDialect == "pb") and self.outgoingSymbols.has_key(obj):
                symbolID = self.outgoingSymbols[obj]
                int2b128(symbolID, write)
                write(VOCAB)
            else:
                if len(obj) > SIZE_LIMIT:
                    raise BananaError, \
                          "string is too long to send (%d)" % len(obj)
                int2b128(len(obj), write)
                write(STRING)
                write(obj)
        else:
            raise BananaError, "could not send object: %s" % repr(obj) 
Example #23
Source File: type_tests.py    From conary with Apache License 2.0 5 votes vote down vote up
def CheckExpectedTypesStandardTypes(self):
        self.cur.execute("create table test (a, b, c)")
        self.cur.execute("insert into test(a, b, c) values (5, 6.3, 'hello')")
        #self.cur.execute("-- types int, float, str")
        self.cur.execute("select * from test")
        res = self.cur.fetchone()
        self.failUnless(isinstance(res.a, types.IntType),
                        "The built-in int converter didn't work.")
        self.failUnless(isinstance(res.b, types.FloatType),
                        "The built-in float converter didn't work.")
        self.failUnless(isinstance(res.c, types.StringType),
                        "The built-in string converter didn't work.") 
Example #24
Source File: userfunction_tests.py    From conary with Apache License 2.0 5 votes vote down vote up
def CheckFloatFunction(self):
        self.cur.execute("create table test (a)")
        self.cur.execute("insert into test(a) values (?)", 5.0)
        self.cur.execute("select floatreturner(a) as a from test")
        res = self.cur.fetchone()
        self.failUnless(isinstance(res.a, types.FloatType),
                        "The result should have been a float.")
        self.failUnlessEqual(res.a, 5.0 * 2.0,
                        "The function returned the wrong result.") 
Example #25
Source File: Elements.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 ) ) 
Example #26
Source File: __init__.py    From fontmerger with MIT License 5 votes vote down vote up
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)) 
Example #27
Source File: base.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_number(n):
    """
    Determines if it is a number or not

    Returns: Type
    """
    return type(n) in (IntType, LongType, FloatType) 
Example #28
Source File: pychart_types.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def IntervalType(val):
    if type(val) in (types.IntType, types.LongType,
                     types.FloatType, types.FunctionType):
	return None
    return "Expecting a number or a function" 
Example #29
Source File: pychart_types.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def NumberType(val):
    if type(val) in (types.IntType, types.LongType, types.FloatType):
        return None
    else:
        return "Expecting a number" 
Example #30
Source File: pychart_types.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def UnitType(val):
    if type(val) in (types.IntType, types.LongType, types.FloatType):
        return
    else:
        return "Expecting a unit"