Python types.FloatType() Examples

The following are code examples for showing how to use types.FloatType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 6 votes vote down vote up
def f_measure(self, alpha=0.5):
        """
        @return: the overall F measure for all texts that have been
            scored by this C{ChunkScore}.
        @rtype: C{float}
        
        @param alpha: the relative weighting of precision and recall.
            Larger alpha biases the score towards the precision value,
            while smaller alpha biases the score towards the recall
            value.  C{alpha} should have a value in the range [0,1].
        @type alpha: C{float}
        """
        assert chktype(1, alpha, types.FloatType, types.IntType)
        p = self.precision()
        r = self.recall()
        if p == 0 or r == 0:    # what if alpha is 0 or 1?
            return 0
        return 1/(alpha/p + (1-alpha)/r) 
Example 2
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value 
Example 3
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value 
Example 4
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value 
Example 5
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value 
Example 6
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value 
Example 7
Project: jack   Author: jack-cli-cd-ripper   File: rc.py    GNU General Public License v2.0 6 votes vote down vote up
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 
Example 8
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def make_arrays(**attrs):
    """
    Makes an array of same type from all attributes in attrs dictionary
    A bit slow! Avoid using this function!
    """
    for attr in attrs.keys():
        obj = attrs[attr]
        if type(attrs[attr]) == ndarray:
            attrs[attr] = attrs[attr].reshape((1,) + obj.shape)
        elif type(obj) in (types.FloatType, types.LongType):
            attrs[attr] = array([obj], float)
        elif type(obj) == types.IntType:
            attrs[attr] = array([obj], int)
        elif type(obj) == types.BooleanType:
            attrs[attr] = array([obj], bool)
        else:
            # another strange type
            dt = 'O'
            for typename in dir(types):
                if type(obj) == types.__dict__[typename]:
                    dt = get_dtype(typename)
                    break
            attrs[attr] = array([obj], dtype=dt)
    return attrs 
Example 9
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 6 votes vote down vote up
def get_printformat(self, attr):
        """
        Returnes the standad fortran stringformat for attribute.
        """
        config = self.get_config(attr)
        tt = config['type'][0]
        if tt in ('IntType', 'LongType'):
            return '%' + str(config['digits_integer']) + 'd'

        elif tt in ('FloatType', 'ComplexType'):
            return '%' + str(config['digits_integer']) + '.'\
                + str(config['digits_fraction']) + 'f'

        else:
            # its a string
            return '%s'

        return printformat 
Example 10
Project: NLP.py   Author: PythonOptimizers   File: sparse_vector_class.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 11
Project: CC3501-2017-1   Author: CC3501   File: utils_math.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 12
Project: CC3501-2017-1   Author: CC3501   File: utils_math.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 13
Project: CC3501-2017-1   Author: CC3501   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 14
Project: CC3501-2017-1   Author: CC3501   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
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 
Example 15
Project: pyasm   Author: gabe-k   File: dispy.py    ISC License 6 votes vote down vote up
def write_object(f, o, indents, count):
	f.write('\t' * indents)
	if count > 1:
		f.write(int_to_str(count) + " * ")
	if type(o) == types.CodeType:
		f.write('code ')
		write_code(f, o, indents)
	elif type(o) == types.StringType:
		f.write('string ')
		write_string(f, o)
	elif type(o) == types.IntType:
		f.write('int ')
		write_int(f, o)
	elif type(o) == types.ListType:
		f.write('list ')
		write_list(f, o, indents)
	elif type(o) == types.TupleType:
		f.write('tuple ')
		write_list(f, o, indents)
	elif type(o) == types.NoneType:
		write_none(f, o)
	elif type(o) == types.FloatType:
		f.write('float ')
		write_float(f, o) 
Example 16
Project: SamPy   Author: sniemi   File: pyefficiency.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def type_tests(n, rep=5000):
    """Check isinstance vs type vs length tests."""

    e = EfficiencyTable('Checking type: isinstance, type, etc. (%d rep.)' % n)
    setup = """\
from numpy import ndarray, linspace, zeros
from types import FloatType
import operator
x = linspace(0, 1, %d)
""" % n
    code = ['isinstance(x, float)',
            'isinstance(x, ndarray)',
            'type(x) == type(zeros(2,float))',
            'type(x) == FloatType',
            'operator.isNumberType(x)',
            ]
    tests = [[timeit.Timer(c, setup=setup).timeit(rep), c] \
             for c in code]
    for t, c in tests:
        e.add(c, t)
    print e 
Example 17
Project: core   Author: lifemapper   File: initWorkflow.py    GNU General Public License v3.0 5 votes vote down vote up
def _getAlgorithm(self, config, algHeading):
        """
        @note: Returns configured algorithm
        """
        acode =  config.get(algHeading, BoomKeys.ALG_CODE)
        alg = Algorithm(acode)
        alg.fillWithDefaults()
        inputs = {}
        # override defaults with any option specified
        algoptions = config.getoptions(algHeading)
        for name in algoptions:
            pname, ptype = alg.findParamNameType(name)
            if pname is not None:
                if ptype == types.IntType:
                    val = config.getint(algHeading, pname)
                elif ptype == types.FloatType:
                    val = config.getfloat(algHeading, pname)
                else:
                    val = config.get(algHeading, pname)
                    # Some algorithms(mask) may have a parameter indicating a layer,
                    # if so, add name to parameters and object to inputs
                    if acode == 'hull_region_intersect' and pname == 'region':
                    # TODO: re-enable this later.  
                    #       Now, always use layer in SDM_MASK_META in scenario meta
                        pass
#                         if val.endswith(LMFormat.GTIFF.ext):
#                             val = val[:-len(LMFormat.GTIFF.ext)]
#                         inputs[pname] = val
                alg.setParameter(pname, val)
        if inputs:
            alg.setInputs(inputs)
        return alg
      
    # ............................................................................. 
Example 18
Project: core   Author: lifemapper   File: cwalken.py    GNU General Public License v3.0 5 votes vote down vote up
def _getAlgorithm(self, algHeading):
        """
        @note: Returns configured algorithm
        """
        acode =  self.cfg.get(algHeading, BoomKeys.ALG_CODE)
        alg = Algorithm(acode)
        alg.fillWithDefaults()
        inputs = {}
        # override defaults with any option specified
        algoptions = self.cfg.getoptions(algHeading)
        for name in algoptions:
            pname, ptype = alg.findParamNameType(name)
            if pname is not None:
                if ptype == IntType:
                    val = self.cfg.getint(algHeading, pname)
                elif ptype == FloatType:
                    val = self.cfg.getfloat(algHeading, pname)
                else:
                    val = self.cfg.get(algHeading, pname)
                    # Some algorithms(mask) may have a parameter indicating a layer,
                    # if so, add name to parameters and object to inputs
                    if acode == ECOREGION_MASK_METHOD and pname == 'region':
                        inputs[pname] = val
                alg.setParameter(pname, val)
        if inputs:
            alg.setInputs(inputs)
        return alg

    # ............................................................................. 
Example 19
Project: SLiPy   Author: glentner   File: mpfit.py    GNU General Public License v2.0 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 20
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, freqdist, gamma, bins=None):
        """
        Use the Lidstone estimate to create a probability distribution
        for the experiment used to generate C{freqdist}.

        @type freqdist: C{FreqDist}
        @param freqdist: The frequency distribution that the
            probability estimates should be based on.
        @type gamma: C{float}
        @param gamma: A real number used to paramaterize the
            estimate.  The Lidstone estimate is equivalant to adding
            M{gamma} to the count for each bin, and taking the
            maximum likelihood estimate of the resulting frequency
            distribution.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, gamma, types.FloatType, types.IntType)
        assert _chktype(3, bins, types.IntType, types.NoneType)
        if (bins == 0) or (bins is None and freqdist.N() == 0):
            name = self.__class__.__name__[:-8]
            raise ValueError('A %s probability distribution ' % name +
                             'must have at least one bin.')
        if (bins is not None) and (bins < freqdist.B()):
            name = self.__class__.__name__[:-8]
            raise ValueError('\nThe number of bins in a %s must be ' % name +
                             'greater than or equal to\nthe number of '+
                             'bins in the FreqDist used to create it.')
        
        self._freqdist = freqdist
        self._gamma = float(gamma)
        self._N = self._freqdist.N()

        if bins is None: bins = freqdist.B()
        self._bins = bins 
Example 21
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def set_prob(self, prob):
        """
        Set the probability associated with this object to C{prob}.
        @param prob: The new probability
        @type prob: C{float}
        """
        assert _chktype(1, prob, types.IntType, types.FloatType)
        self.__prob = prob
        self.__logprob = None 
Example 22
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def set_logprob(self, logprob):
        """
        Set the log probability associated with this object to
        C{logprob}.  I.e., set the probability associated with this
        object to C{exp(logprob)}.
        @param logprob: The new log probability
        @type logprob: C{float}
        """
        assert _chktype(1, prob, types.IntType, types.FloatType)
        self.__logprob = prob
        self.__prob = None 
Example 23
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value

##################################################
# COLOR PRINT
################################################## 
Example 24
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value

##################################################
# COLOR PRINT
################################################## 
Example 25
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool (Deokwoo Jung's conflicted copy 2014-07-01).py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value

##################################################
# COLOR PRINT
################################################## 
Example 26
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value

##################################################
# COLOR PRINT
################################################## 
Example 27
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value

##################################################
# COLOR PRINT
################################################## 
Example 28
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value

##################################################
# COLOR PRINT
################################################## 
Example 29
Project: DDEA-DEV   Author: TinyOS-Camp   File: toolset.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value


##################################################
# BINARY OBJECT
################################################## 
Example 30
Project: DDEA-DEV   Author: TinyOS-Camp   File: toolset.py    GNU General Public License v2.0 5 votes vote down vote up
def read(filename, index, delim="", ctype=""):
    openfile = open(filename, "r")
    lines = openfile.readlines()
    openfile.close()

    _ctype = type(ctype)
    value = []

    for line in lines:
        tmp = line.rstrip().rsplit(delim)
        for i in index:
            val = tmp[i]
            if _ctype == types.IntType:
                convertedval = int(val)
            elif _ctype == types.FloatType:
                convertedval = float(val)
            elif _ctype == types.StringType:
                convertedval = val
            elif _ctype == types.BooleanType:
                convertedval = bool(val)
            else:
                convertedval = val
            value.append(convertedval)

    return value


##################################################
# BINARY OBJECT
################################################## 
Example 31
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 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 32
Project: xuemc   Author: skycucumber   File: Utility.py    GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, key):
        NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
        if isinstance(key, NumberTypes):
            return self.list[key]
        return self.data[key] 
Example 33
Project: Computable   Author: ktraunmueller   File: c_spec.py    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 34
Project: poker   Author: surgebiswas   File: c_spec.py    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 35
Project: iOS-private-api-checker   Author: NetEaseGame   File: mysql_escape_warp.py    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 36
Project: openode   Author: JvGinkel   File: util.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def convert_py_to_js_data(val, id_):
    """
    Converts Python data type to JS data type.

    Practically what this means is, convert ``False`` to ``false``, ``True`` to ``true`` and so on.
    It also takes care of the conversion of :py:class:`.JSVar`, :py:class:`.JSFunction`
    and :py:class:`.JSFunctionInContext`. It takes care of recursively converting lists and dictionaries
    too.

    :param val: The Python data to convert.
    :type val: Any

    :param id_: The DOM id of the element in which context :py:class:`.JSFunctionInContext` functions
        should run. (This is not needed if ``val`` contains no :py:class:`.JSFunctionInContext`)
    :type id_: :py:obj:`str`

    :rtype: :py:obj:`unicode`
    """
    if type(val) == types.BooleanType:
        return u'true' if val else u'false'
    elif type(val) in [types.IntType, types.LongType, types.FloatType]:
        return force_unicode(val)
    elif isinstance(val, JSFunctionInContext):
        return u"django_select2.runInContextHelper(%s, '%s')" % (val, id_)
    elif isinstance(val, JSVar):
        return val  # No quotes here
    elif isinstance(val, dict):
        return convert_dict_to_js_map(val, id_)
    elif isinstance(val, list):
        return convert_to_js_arr(val, id_)
    else:
        return convert_to_js_str(val) 
Example 37
Project: pykit   Author: bsc-s2   File: timeutil.py    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 38
Project: qgis-wps4server   Author: 3liz   File: InAndOutputs.py    GNU General Public License v3.0 5 votes vote down vote up
def _control(self, value):
        """Control input value for dangerous characters or types, like "#"

        :param value: value to be controled
        """

        # ugly characters, only if string
        if value and type(value) != types.BooleanType:
            for char in self.restrictedCharacters:
                if value.find(char) > -1:
                    raise Exceptions.InvalidParameterValue(value)

        # type
        try:
            if self.dataType == types.FloatType:
                value = float(value)
            elif self.dataType == types.StringType:
                if not value:
                    value = ''
                elif type(value) == types.StringType:
                    value = value.decode('utf8')
                else:
                    value = unicode(value)
            elif self.dataType == types.IntType:
                value = int(value)
            elif self.dataType == types.BooleanType:
                value = bool(value)
            # TODO other types missing
        except (ValueError), e:
            raise Exceptions.InvalidParameterValue(value)

        # value list 
Example 39
Project: qgis-wps4server   Author: 3liz   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def getDataTypeReference(self, inoutput):
        """Returns data type reference according to W3C

        :param inoutput: :class:`pywps.Process.InAndOutputs.Input`
            or :class:`pywps.Process.InAndOutputs.Output`

        :rtype: string
        :returns: url to w3.org
        """

        dataType = {"type": None, "reference": None}
        if inoutput.dataType == types.StringType:
            dataType["type"] = "string"
            dataType["reference"] = "http://www.w3.org/TR/xmlschema-2/#string"
        elif inoutput.dataType == types.FloatType:
            dataType["type"] = "float"
            dataType["reference"] = "http://www.w3.org/TR/xmlschema-2/#float"
        elif inoutput.dataType == types.IntType:
            dataType["type"] = "integer"
            dataType["reference"] = "http://www.w3.org/TR/xmlschema-2/#integer"
        elif inoutput.dataType == types.BooleanType:
            dataType["type"] = "boolean"
            dataType["reference"] = "http://www.w3.org/TR/xmlschema-2/#boolean"
        else:
            # TODO To be continued...
            dataType["type"] = "string"
            dataType["reference"] = "http://www.w3.org/TR/xmlschema-2/#string"
            pass

        return dataType 
Example 40
Project: tashi   Author: stroucki   File: util.py    Apache License 2.0 5 votes vote down vote up
def fixObject(obj):
	if (type(obj) in [types.StringType, types.BooleanType, types.IntType, types.FloatType, types.NoneType, types.UnicodeType]):
		return obj
	try:
		if (getattr(obj, "__dict__", None)):
			for k in obj.__dict__:
				if (not k.startswith("_")):
					setattr(obj, "_%s" % (k), fixObject(getattr(obj, k)))
		else:
			obj = map(lambda x: fixObject(x), obj)
	except:
		log("%s\n" % (traceback.format_exc(sys.exc_info())))
		log("%s\n" % (type(obj)))
	return obj 
Example 41
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: pyjsontestrunner.py    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 42
Project: eve-metrics   Author: ccpgames   File: Elements.py    MIT 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 43
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **args):
        """Variable
        """
        self.init_config('cars')
        self.config('x', 0.456685, group=[
                    'state'], perm='w', digits_fraction=2)

        self.config('color', [0.2, 0.8, 0.2], metatype='color',
                    struct='array', group=['parameter'], perm='w')
        self.config('load', 'user', struct='dict', perm='r')
        self.config('n', 0,  struct='array', info='number', perm='w',
                    group=['state', 'parameters'],
                    min=0, max=5)
        self.config('b', False, struct='array', perm='w',
                    info='bool...', group=['state', 'costs'])
        self.config('a', 0.0, struct='array', info='acceleration',
                    group=['state', 'costs'], digits_fraction=2)
        self.config('v', 0.0, struct='array', info='velocity',
                    group=['state'], unit='m/s', digits_fraction=2)
        self.config('d', 0.0, unit='m', struct='array',
                    info='this is \nthe distance', digits_fraction=2)
        self.config('j', 0.0, struct='array', perm='r', digits_fraction=2)
        self.add_items(v=[8.7, 5.5, 34.1, 2], a=[-8, -5, -34, -2])

        self.config('mods', TestMod, struct='dict')
        self.config('m', [0.0, 0.0, 0.0], struct='array')
        self.config('g', zeros((3, 4)), struct='array')
        self.config('coords', array([0.0, 0.0, 0.0], float),
                    # type=['FloatType'],
                    struct='array',
                    name='coordinates',
                    info='Array with xyz coordinates of each node')
        newids = self.suggest_ids(3)
        self.create_ids(newids, v=[5, 6, 7])
        # print 'config=\n',self.get_config() 
Example 44
Project: SUMO_dy_public   Author: DayuanTan   File: classman.py    GNU General Public License v3.0 5 votes vote down vote up
def format_value(self, _id, show_unit=False, show_parentesis=False):
        if show_unit:
            unit = ' ' + self.format_unit(show_parentesis)
        else:
            unit = ''
        # return repr(self[_id])+unit

        #self.min = minval
        #self.max = maxval
        #self.digits_integer = digits_integer
        #self.digits_fraction = digits_fraction
        val = self[_id]
        tt = type(val)

        if tt in (types.LongType, types.IntType):
            return str(val) + unit

        elif tt in (types.FloatType, types.ComplexType):
            if hasattr(attrconf, 'digits_fraction'):
                digits_fraction = self.digits_fraction
            else:
                digits_fraction = 3
            return "%." + str(digits_fraction) + "f" % (val) + unit

        else:
            return str(val) + unit

        # return str(self[_id])+unit 
Example 45
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 5 votes vote down vote up
def set_widgetvalue(self, value):
        """
        Sets value for valuewidget.
        Depends on attribute type and hence widgettype.
        To be overwritten.
        """
        if 1:  # self._attrconf.is_writable():
            # set value to label
            # numpy returns dtype... even for scalars
            # make sure to convert value in a native python scalar
            if type(value) not in (types.IntType, types.LongType, types.FloatType):
                value = value.tolist()
            self.valuewidget.SetValue(str(value)) 
Example 46
Project: spc   Author: whbrewer   File: Elements.py    MIT 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 47
Project: NLP.py   Author: PythonOptimizers   File: sparse_vector_class.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 48
Project: Pirates-Online-Rewritten   Author: PiratesOnlineRewritten   File: DistributedCapturePoint.py    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 49
Project: Pirates-Online-Rewritten   Author: PiratesOnlineRewritten   File: DistributedCapturePoint.py    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 50
Project: Pirates-Online-Rewritten   Author: PiratesOnlineRewritten   File: DistributedInteractiveProp.py    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