Python types.BooleanType() Examples

The following are code examples for showing how to use types.BooleanType(). 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: core   Author: lifemapper   File: gbifquery.py    GNU General Public License v3.0 6 votes vote down vote up
def _assembleDownloadPredicate(self, queryParams):
      fullPredicate = GBIF.QUERY_PARAMS[GBIF.DOWNLOAD_COMMAND].copy()
      predicates = []
      for key, val in queryParams.iteritems():
         if isinstance(val, ListType) or isinstance(val, TupleType):
            for v in val:
               pred = {"type": "equals", "key": key, "value": v}
         elif key not in ['offset', 'limit']:
            if isinstance(val, BooleanType):
               val = str(val).lower()
            pred = {"type": "equals", "key": key, "value": val}
         predicates.append(pred)
      predicate = {"type": "and",
                   "predicates": predicates}
      fullPredicate["predicate"] = predicate
      jsonPred  = json.dumps(fullPredicate)
      return jsonPred

# ............................................... 
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: biolib   Author: dparks1134   File: custom_help_formatter.py    GNU General Public License v3.0 6 votes vote down vote up
def _get_help_string(self, action):
        """Place default value in help string."""
        h = action.help
        if '%(default)' not in action.help:
            if action.default != '' and action.default != [] and action.default is not None and type(action.default) != types.BooleanType:
                if action.default is not argparse.SUPPRESS:
                    defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]

                    if action.option_strings or action.nargs in defaulting_nargs:
                        if '\n' in h:
                            lines = h.splitlines()
                            lines[0] += ' (default: %(default)s)'
                            h = '\n'.join(lines)
                        else:
                            h += ' (default: %(default)s)'
            return h 
Example 8
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 6 votes vote down vote up
def _set_attrs(self,l,d):
    self.obsolete = d['OBSOLETE']!=None
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    # Default is STRUCTURAL, see RFC2552 or draft-ietf-ldapbis-syntaxes
    self.kind = 0
    if d['ABSTRACT']!=None:
      self.kind = 1
    elif d['AUXILIARY']!=None:
      self.kind = 2
    if self.kind==0 and not d['SUP'] and self.oid!='2.5.6.0':
      # STRUCTURAL object classes are sub-classes of 'top' by default
      self.sup = ('top',)
    else:
      self.sup = d['SUP']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.sup)==TupleType
    assert type(self.kind)==IntType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return 
Example 9
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 6 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.aux = d['AUX']
    self.must = d['MUST']
    self.may = d['MAY']
    self.nots = d['NOT']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.aux)==TupleType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    assert type(self.nots)==TupleType
    return 
Example 10
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 6 votes vote down vote up
def _set_attrs(self,l,d):
    self.obsolete = d['OBSOLETE']!=None
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    # Default is STRUCTURAL, see RFC2552 or draft-ietf-ldapbis-syntaxes
    self.kind = 0
    if d['ABSTRACT']!=None:
      self.kind = 1
    elif d['AUXILIARY']!=None:
      self.kind = 2
    if self.kind==0 and not d['SUP'] and self.oid!='2.5.6.0':
      # STRUCTURAL object classes are sub-classes of 'top' by default
      self.sup = ('top',)
    else:
      self.sup = d['SUP']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.sup)==TupleType
    assert type(self.kind)==IntType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return 
Example 11
Project: elasticsearch-monitoring   Author: BigDataBoutique   File: fetch_stats.py    Apache License 2.0 6 votes vote down vote up
def into_signalfx(sfx_key, cluster_health, node_stats):
    import signalfx
    sfx = signalfx.SignalFx()
    ingest = sfx.ingest(sfx_key)
    for node in node_stats:
        source_node = node['source_node']
        for s in node_stats_to_collect:
            flattened = flatten_json(node['node_stats'][s])
            for k,v in flattened.items():
                if isinstance(v, (int, float)) and not isinstance(v, types.BooleanType):
                    ingest.send(gauges=[{"metric": 'elasticsearch.node.' + s + '.' + k, "value": v,
                                         "dimensions": {
                                             'cluster_uuid': node.get('cluster_uuid'),
                                             'cluster_name': node.get('cluster_name'),
                                             'node_name': source_node.get('name'),
                                             'node_host': source_node.get('host'),
                                             'node_host': source_node.get('ip'),
                                             'node_uuid': source_node.get('uuid'),
                                             'cluster_name': source_node.get('uuid'),
                                             }
                                         }])
    ingest.stop() 
Example 12
Project: tashi   Author: stroucki   File: util.py    Apache License 2.0 6 votes vote down vote up
def boolean(value):
	"""Convert a variable to a boolean"""
	if (type(value) == types.BooleanType):
		return value
	if (type(value) == types.IntType):
		return (value != 0)

	# See if it can be expressed as a string
	try:
		value = str(value)
	except:
		raise ValueError

	lowercaseValue = value.lower()
	if lowercaseValue in ['yes', 'true', '1']:
		return True
	elif lowercaseValue in ['no', 'false', '0']:
		return False
	else:
		raise ValueError 
Example 13
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 14
Project: SUMO_dy_public   Author: DayuanTan   File: processes.py    GNU General Public License v3.0 6 votes vote down vote up
def get_optionstring(self, is_primed=True):
        # print 'get_optionstring'
        s = ''
        for attr in self._optionattrs:
            value = getattr(self, attr)
            cmlattr = self._transdir.get(attr, attr)
            # print '  option',attr,cmlattr,attr in
            # self._filepathattrs,type(value)
            if attr in self._filepathattrs:
                s += ' ' + cmlattr + \
                    ' %s' % filepathlist_to_filepathstring(
                        value.split(','), is_primed=is_primed)
            elif type(value) == types.BooleanType:
                if value:
                    s += ' ' + cmlattr
            elif type(value) in [types.StringTypes, types.UnicodeType]:
                s += ' ' + cmlattr + " '%s'" % value
            else:
                s += ' ' + cmlattr + ' %s' % value
        return s 
Example 15
Project: ZWUtils-Python2   Author: Adam5Wu   File: ConsoleKit.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def StrToBoolean(str,default=None):
#------------------------ Acceptable boolean strings -------------------------
	BOOLEAN_TRUE = ['TRUE','YES','Y','ON','1']
	BOOLEAN_FALSE = ['FALSE','NO','N','OFF','0']
	
	iStr = str.upper()
	if iStr in BOOLEAN_TRUE:
		return True
	elif iStr in BOOLEAN_FALSE:
		return False
	else:
#----------------------- Handle no matching condition ------------------------
		if type(default) is types.BooleanType:
			print >>sys.stdout, "? Ignored invalid Boolean string '%s'"%str
			return default
		elif type(default) is types.NoneType:
			raise Exception("Invalid Boolean string '%s'"%str)
		else:
			raise Exception("Invalid Boolean string '%s' and default parameter '%s'"%(str,default))

#=============================================================================
#--------------------- Print seconds in hh:mm:ss format ----------------------
#============================================================================= 
Example 16
Project: hws   Author: nash-x   File: constant.py    Apache License 2.0 6 votes vote down vote up
def str_to_bool(cver_str):
    """
    convert string to boolean
    :param cver_str: string should to convert
    :return: Boolean
    """
    if type(cver_str) is types.BooleanType:
        return cver_str
    elif type(cver_str) is types.StringType:
        bool_map = {'true': True, 'false': False}
        bool_str = cver_str.lower() if cver_str else ""
        if not bool_map.has_key(bool_str):
            raise ValueError('%s is not valid boolean.' % cver_str)
        else:
            return bool_map[bool_str]
    else:
        raise ValueError('%s is not valid boolean.' % cver_str) 
Example 17
Project: DDEA   Author: deokwooj   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 18
Project: DDEA   Author: deokwooj   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 19
Project: splunk-azure-website-logs   Author: azure-contrib   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _fill_data_minidom(xmldoc, element_name, data_member):
    xmlelements = _get_child_nodes(xmldoc, _get_serialization_name(element_name))

    if not xmlelements or not xmlelements[0].childNodes:
        return None

    value = xmlelements[0].firstChild.nodeValue

    if data_member is None:
        return value
    elif isinstance(data_member, datetime):
        return _to_datetime(value)
    elif type(data_member) is types.BooleanType:
        return value.lower() != 'false'
    else:
        return type(data_member)(value) 
Example 20
Project: py-text   Author: PinaeOS   File: conf_utils.py    Apache License 2.0 6 votes vote down vote up
def get(self, key, default): 
        if key is not None:
            value = self.conf.get(key)
            if value is None:
                return default
                
            if type(default) == types.IntType:
                return int(value)
            elif type(default) == types.FloatType:
                return float(value)
            elif type(default) == types.BooleanType:
                return bool(value)
    
            return str(value)
            
        return None 
Example 21
Project: TranskribusDU   Author: Transkribus   File: Parameter.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getStringCmdLine(self):
        long = False  
        result = ""
        option = ""
        if self.optionShort:
            option = self.optionShort
        elif self.optionLong:
            option = self.optionLong
            long = True
        if self.arg:
            if self.arg!="":
                if type(self.arg) != types.BooleanType:
                    if long:
                        result = result + option + "=" + str(self.arg) + " "
                    else: 
                        result = result + option + " " + str(self.arg) + " "
        return result
                
    ## Get a string value which contains all informations about the current parameter
    #@return a string value 
Example 22
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _coerce_bool(self, value, default=False):
        if isinstance(value, types.BooleanType):
            b = value
        if isinstance(value, types.StringTypes):
            b = value.strip().lower() not in ('0', 'false', 'off', 'no')
        elif isinstance(value, types.IntType):
            b = bool(value)
        else:
            b = default
        return b 
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: cloudify-agent   Author: cloudify-cosmo   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_bool_or_default(raw_value, default_value):
    if raw_value is None:
        return default_value

    if isinstance(raw_value, types.BooleanType):
        return raw_value
    elif isinstance(raw_value, basestring):
        return raw_value.lower() == 'true'
    else:
        raise ValueError('value has invalid type: {0}, expected boolean or '
                         'string'.format(type(raw_value))) 
Example 32
Project: TAF   Author: couchbaselabs   File: BeautifulSoup.py    Apache License 2.0 5 votes vote down vote up
def _matches(self, markup, matchAgainst):
        #print "Matching %s against %s" % (markup, matchAgainst)
        result = False
        if matchAgainst == True and type(matchAgainst) == types.BooleanType:
            result = markup != None
        elif callable(matchAgainst):
            result = matchAgainst(markup)
        else:
            #Custom match methods take the tag as an argument, but all
            #other ways of matching match the tag name as a string.
            if isinstance(markup, Tag):
                markup = markup.name
            if markup and not isString(markup):
                markup = unicode(markup)
            #Now we know that chunk is either a string, or None.
            if hasattr(matchAgainst, 'match'):
                # It's a regexp object.
                result = markup and matchAgainst.search(markup)
            elif isList(matchAgainst):
                result = markup in matchAgainst
            elif hasattr(matchAgainst, 'items'):
                result = markup.has_key(matchAgainst)
            elif matchAgainst and isString(markup):
                if isinstance(markup, unicode):
                    matchAgainst = unicode(matchAgainst)
                else:
                    matchAgainst = str(matchAgainst)

            if not result:
                result = matchAgainst == markup
        return result 
Example 33
Project: dtguess   Author: ownport   File: utils.py    MIT License 5 votes vote down vote up
def get_default_instances():

    return [
        types.StringType(), types.DecimalType(), types.IntegerType(),
        types.DateType('%Y-%m-%d %H:%M:%S'), types.BooleanType()
    ] 
Example 34
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.syntax = d['SYNTAX'][0]
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert self.syntax is None or type(self.syntax)==StringType
    return 
Example 35
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.applies = d['APPLIES']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.applies)==TupleType
    return 
Example 36
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.oc = d['OC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.oc)==StringType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return 
Example 37
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.syntax = d['SYNTAX'][0]
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert self.syntax is None or type(self.syntax)==StringType
    return 
Example 38
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.applies = d['APPLIES']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.applies)==TupleType
    return 
Example 39
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.form = d['FORM'][0]
    self.sup = d['SUP']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.form)==StringType
    assert type(self.sup)==TupleType
    return 
Example 40
Project: Splunk_TA_LDAP   Author: f33dy0urhe4d   File: models.py    Apache License 2.0 5 votes vote down vote up
def _set_attrs(self,l,d):
    self.names = d['NAME']
    self.desc = d['DESC'][0]
    self.obsolete = d['OBSOLETE']!=None
    self.oc = d['OC'][0]
    self.must = d['MUST']
    self.may = d['MAY']
    assert type(self.names)==TupleType
    assert self.desc is None or type(self.desc)==StringType
    assert type(self.obsolete)==BooleanType and (self.obsolete==0 or self.obsolete==1)
    assert type(self.oc)==StringType
    assert type(self.must)==TupleType
    assert type(self.may)==TupleType
    return 
Example 41
Project: fimap   Author: crunchsec   File: BeautifulSoup.py    GNU General Public License v2.0 5 votes vote down vote up
def _matches(self, markup, matchAgainst):
        #print "Matching %s against %s" % (markup, matchAgainst)
        result = False
        if matchAgainst == True and type(matchAgainst) == types.BooleanType:
            result = markup != None
        elif callable(matchAgainst):
            result = matchAgainst(markup)
        else:
            #Custom match methods take the tag as an argument, but all
            #other ways of matching match the tag name as a string.
            if isinstance(markup, Tag):
                markup = markup.name
            if markup and not isString(markup):
                markup = unicode(markup)
            #Now we know that chunk is either a string, or None.
            if hasattr(matchAgainst, 'match'):
                # It's a regexp object.
                result = markup and matchAgainst.search(markup)
            elif isList(matchAgainst):
                result = markup in matchAgainst
            elif hasattr(matchAgainst, 'items'):
                result = markup.has_key(matchAgainst)
            elif matchAgainst and isString(markup):
                if isinstance(markup, unicode):
                    matchAgainst = unicode(matchAgainst)
                else:
                    matchAgainst = str(matchAgainst)

            if not result:
                result = matchAgainst == markup
        return result 
Example 42
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 43
Project: dkodi   Author: dknlght   File: BeautifulSoup.py    GNU General Public License v2.0 5 votes vote down vote up
def _matches(self, markup, matchAgainst):
        #print "Matching %s against %s" % (markup, matchAgainst)
        result = False
        if matchAgainst == True and type(matchAgainst) == types.BooleanType:
            result = markup != None
        elif callable(matchAgainst):
            result = matchAgainst(markup)
        else:
            #Custom match methods take the tag as an argument, but all
            #other ways of matching match the tag name as a string.
            if isinstance(markup, Tag):
                markup = markup.name
            if markup and not isString(markup):
                markup = unicode(markup)
            #Now we know that chunk is either a string, or None.
            if hasattr(matchAgainst, 'match'):
                # It's a regexp object.
                result = markup and matchAgainst.search(markup)
            elif isList(matchAgainst):
                result = markup in matchAgainst
            elif hasattr(matchAgainst, 'items'):
                result = markup.has_key(matchAgainst)
            elif matchAgainst and isString(markup):
                if isinstance(markup, unicode):
                    matchAgainst = unicode(matchAgainst)
                else:
                    matchAgainst = str(matchAgainst)

            if not result:
                result = matchAgainst == markup
        return result 
Example 44
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 45
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 46
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 47
Project: faircoop-market   Author: sarantapichos   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _coerce_bool(self, value, default=False):
        if isinstance(value, types.BooleanType):
            b = value
        if isinstance(value, types.StringTypes):
            b = value.strip().lower() not in ('0', 'false', 'off', 'no')
        elif isinstance(value, types.IntType):
            b = bool(value)
        else:
            b = default
        return b 
Example 48
Project: emulated-sdn-application   Author: tranlyvu   File: base.py    Apache License 2.0 5 votes vote down vote up
def validate_advertise_peer_as(advertise_peer_as):
    if not isinstance(advertise_peer_as, BooleanType):
        raise ConfigTypeError(desc='Invalid type for advertise-peer-as, '
                              'expected bool got %s' %
                              type(advertise_peer_as))
    return advertise_peer_as


# =============================================================================
# Other utils.
# ============================================================================= 
Example 49
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 5 votes vote down vote up
def get_string_attr_value(self, attr, value):
        """
        Returns a string with correctly formatted value of attribute.
        """
        # print '\n\nget_string_attr_value',attr,value,type(value)
        # print self.get_printformat(attr)+self.get_unit(attr)
        #print (self.get_printformat(attr)+self.get_unit(attr))%(value)
        config = self.get_config(attr)
        tt = config['type'][0]
        unit = self.get_unit(attr, show_parentesis=True)
        if tt in ('BooleanType',):
            if value:
                s = 'True'
            else:
                s = 'False'
            return s + self.get_unit(attr, show_parentesis=True)

        elif type(value) in ARRAYTYPES:
            # value is an array=> print signe items
            s = '['
            for v in value:
                s += self.get_string_attr_value(attr, v) + ','
            s += ']'
            return s

        else:
            try:
                return (self.get_printformat(attr)
                        + ' ' + self.get_unit(attr, show_parentesis=True)) % value
            except:
                print '\n WARNING could not print', attr, '=', value
                return 'Error' 
Example 50
Project: server   Author: iw3hxn   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _coerce_bool(self, value, default=False):
        if isinstance(value, types.BooleanType):
            b = value
        if isinstance(value, types.StringTypes):
            b = value.strip().lower() not in ('0', 'false', 'off', 'no')
        elif isinstance(value, types.IntType):
            b = bool(value)
        else:
            b = default
        return b