Python types.ListType() Examples

The following are code examples for showing how to use types.ListType(). 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: pyblish-win   Author: pyblish   File: validate.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example 2
Project: core   Author: lifemapper   File: jsonFormatter.py    GNU General Public License v3.0 6 votes vote down vote up
def _getMapMetadata(baseUrl, mapName, layers):
    """Get a dictionary of mapping information

    Note:
        * This is very alpha.  We need to discuss exactly how we will implement
            maps going forward
    """
    mapDict = {
        'endpoint' : baseUrl,
        'mapName' : mapName
    }
    if isinstance(layers, ListType):
        lyrs = []
        for lyr in layers:
            lyrs.append({
                'metadataUrl' : lyr.metadataUrl,
                'layerName' : lyr.name
            })
        mapDict['layers'] = lyrs
    else:
        mapDict['layerName'] = layers
    return mapDict

# ............................................................................. 
Example 3
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 6 votes vote down vote up
def _setEPSG(self, epsg=None):
        if epsg == None:
            self._epsg = None
        else:
            if isinstance(epsg, (StringType, UnicodeType)): 
                try:
                    epsg = int(epsg)
                    self._epsg = epsg
                except:
                    raise LMError('Invalid epsg code {}'.format(epsg))
            elif isinstance(epsg, IntType):
                self._epsg = epsg
            elif isinstance(epsg, ListType) or isinstance(epsg, TupleType):
                epsgcodes = set(epsg).discard(None)
                if len(epsgcodes) == 1:
                    self._epsg = epsgcodes[0]
                else:
                    raise LMError('LMSpatialObject may only contain a single EPSG code'
                                      .format(epsgcodes))
            else:
                raise LMError('Invalid EPSG code {} type {}'.format(epsg, type(epsg))) 
Example 4
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 5
Project: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _json_object_to_object(self, json_object, entity_class, context={}):
        if type(json_object) == types.DictionaryType:
            if hasattr(entity_class, '_is_paginated') and entity_class._is_paginated:
                try:
                    if hasattr(self, '_process_page'):
                        return self._process_page(json_object, entity_class, context)
                    else:
                        raise AttributeError('Class %s does not have _process_page() method' % entity_class.__name__)
                except ValueError:
                    return map_to_object(json_object, entity_class)
            else:
                return map_to_object(json_object, entity_class)
        elif type(json_object) == types.ListType:
            objects = []
            for obj in json_object:
                objects.append(map_to_object(obj, entity_class))

            # if auto_page is set, return a page with the items
            if 'typeId' in json_object and json_object['typeId'] == 'com.tintri.api.rest.v310.dto.Page' and self.__auto_page:
                return TintriPage(paginated=entity_class._is_paginated, items=objects, context=context)
            else:
                return objects
        else:
            return json_object # Return any other type as is, such as None, string, number, boolean 
Example 6
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _eval_params(self, model, params):
        args = []
        for i, param in enumerate(params):
            if isinstance(param, types.ListType):
                value = self._eval_params(model, param)
            elif is_ref(param):
                value = self.process_ref(param)
            elif is_eval(param):
                value = self.process_eval(param)
            elif isinstance(param, types.DictionaryType): # supports XML syntax
                param_model = self.get_model(param.get('model', model))
                if 'search' in param:
                    q = eval(param['search'], self.eval_context)
                    ids = param_model.search(self.cr, self.uid, q)
                    value = self._get_first_result(ids)
                elif 'eval' in param:
                    local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                    local_context.update(self.id_map)
                    value = eval(param['eval'], self.eval_context, local_context)
                else:
                    raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
            else:
                value = param # scalar value
            args.append(value)
        return args 
Example 7
Project: openhatch   Author: campbe13   File: feedparser.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __getitem__(self, key):
        if key == 'category':
            return UserDict.__getitem__(self, 'tags')[0]['term']
        if key == 'enclosures':
            norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel'])
            return [norel(link) for link in UserDict.__getitem__(self, 'links') if link['rel']=='enclosure']
        if key == 'license':
            for link in UserDict.__getitem__(self, 'links'):
                if link['rel']=='license' and link.has_key('href'):
                    return link['href']
        if key == 'categories':
            return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
        realkey = self.keymap.get(key, key)
        if type(realkey) == types.ListType:
            for k in realkey:
                if UserDict.__contains__(self, k):
                    return UserDict.__getitem__(self, k)
        if UserDict.__contains__(self, key):
            return UserDict.__getitem__(self, key)
        return UserDict.__getitem__(self, realkey) 
Example 8
Project: pyomni   Author: taxpon   File: davlib.py    MIT License 6 votes vote down vote up
def post(self, url, data={ }, body=None, extra_hdrs={ }):
        headers = extra_hdrs.copy()

        assert body or data, "body or data must be supplied"
        assert not (body and data), "cannot supply both body and data"
        if data:
            body = ''
            for key, value in data.items():
                if isinstance(value, types.ListType):
                    for item in value:
                        body = body + '&' + key + '=' + urllib.quote(str(item))
                else:
                    body = body + '&' + key + '=' + urllib.quote(str(value))
            body = body[1:]
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        return self._request('POST', url, body, headers) 
Example 9
Project: pyomni   Author: taxpon   File: WebdavRequests.py    MIT License 6 votes vote down vote up
def __init__(self, nameList, defaultNameSpace = None):
        '''
        
        @param nameList:
        @param defaultNameSpace:
        '''
        
        assert isinstance(nameList, types.ListType) or isinstance(nameList, types.TupleType), \
            "1. argument has wrong type %s" % type(nameList)
        self.shortcuts = {}
        self.defaultNameSpace = defaultNameSpace
        for name in nameList:
            if  not isinstance(name, types.TupleType):
                name = (defaultNameSpace, name)            
            assert isinstance(name, types.TupleType) and len(name) == 2, \
                         "Name is not a namespace, name tuple: %s" % type(name)
            validatePropertyName(name[1])
            if  name[0] and not self.shortcuts.has_key(name[0]):
                self.shortcuts[name[0]] = 'ns%d' % len(self.shortcuts) 
Example 10
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def deepFindProperties(self, *names):
        """
        Retrieve given properties for this collection and all contained (nested) resources.
        
        Note:
        =====
          This operation can take a long time if used with recursive=true and is therefore
          disabled on some WebDAV servers.
        
        @param names: a list of property names
        @return: a map from resource URI to a map from property name to value.
        """
        assert isinstance(names, types.ListType.__class__) or isinstance(names, types.TupleType), \
                "Argument name has type %s" % str(type(names))
        body = createFindBody(names, self.defaultNamespace)
        response = self.connection.propfind(self.path, body, depth=Constants.HTTP_HEADER_DEPTH_INFINITY)
        return response.msr 
Example 11
Project: spider   Author: LaveyD   File: select_result.py    GNU General Public License v3.0 6 votes vote down vote up
def deduplication(arg):
    """
        deduplication the arg.

        @param:
            arg:the variable to deduplication

        if arg is list,then deduplication it and then the new list.
        if arg is tuple,then deduplication it and then the new tuple.
    """
    if type(arg) is types.ListType:
        return list(set(arg))
    elif type(arg) is types.TupleType:
        return tuple(set(arg))

    return arg 
Example 12
Project: octopuscloud   Author: christianbaun   File: connection.py    Apache License 2.0 6 votes vote down vote up
def add_jobflow_steps(self, jobflow_id, steps):
        """
        Adds steps to a jobflow

        :type jobflow_id: str
        :param jobflow_id: The job flow id
        :type steps: list(boto.emr.Step)
        :param steps: A list of steps to add to the job
        """
        if type(steps) != types.ListType:
            steps = [steps]
        params = {}
        params['JobFlowId'] = jobflow_id

        # Step args
        step_args = [self._build_step_args(step) for step in steps]
        params.update(self._build_step_list(step_args))

        return self.get_object('AddJobFlowSteps', params, RunJobFlowResponse) 
Example 13
Project: sd-agent-core-plugins   Author: serverdensity   File: test_cassandra.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testCustomJMXMetric(self):
        count = 0
        while self.reporter.metrics is None:
            time.sleep(1)
            count += 1
            if count > 25:
                raise Exception("No metrics were received in 25 seconds")

        metrics = self.reporter.metrics

        self.assertTrue(isinstance(metrics, ListType))
        self.assertTrue(len(metrics) > 0)
        log.info([t for t in metrics if "cassandra." in t['metric'] and "instance:cassandra_instance" in t['tags']])
        log.info(metrics)
        log.info(len([t for t in metrics if "cassandra." in t['metric'] and "instance:cassandra_instance" in t['tags']]))
        log.info(len([t for t in metrics if "instance:cassandra_instance" in t['tags']]))
        log.info(len([t for t in metrics if "cassandra." in t['metric']]))
        log.info(len(metrics))
        self.assertTrue(len([t for t in metrics if "cassandra." in t['metric'] and "instance:cassandra_instance" in t['tags']]) > 40, metrics) 
Example 14
Project: ironpython2   Author: IronLanguages   File: validate.py    Apache License 2.0 6 votes vote down vote up
def check_headers(headers):
    assert_(type(headers) is ListType,
        "Headers (%r) must be of type list: %r"
        % (headers, type(headers)))
    header_names = {}
    for item in headers:
        assert_(type(item) is TupleType,
            "Individual headers (%r) must be of type tuple: %r"
            % (item, type(item)))
        assert_(len(item) == 2)
        name, value = item
        assert_(name.lower() != 'status',
            "The Status header cannot be used; it conflicts with CGI "
            "script, and HTTP status is not given through headers "
            "(value: %r)." % value)
        header_names[name.lower()] = None
        assert_('\n' not in name and ':' not in name,
            "Header names may not contain ':' or '\\n': %r" % name)
        assert_(header_re.search(name), "Bad header name: %r" % name)
        assert_(not name.endswith('-') and not name.endswith('_'),
            "Names may not end in '-' or '_': %r" % name)
        if bad_header_value_re.search(value):
            assert_(0, "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example 15
Project: kay-template   Author: yosukesuzuki   File: rest.py    MIT License 6 votes vote down vote up
def xml_node_to_json(xml_node):
    if((len(xml_node.childNodes) == 1) and
       (xml_node.childNodes[0].nodeType == xml_node.TEXT_NODE)):
        return xml_node.childNodes[0].data
    else:
        json_node = {}
        
        for child_xml_node in xml_node.childNodes:
            new_child_json_node = xml_node_to_json(child_xml_node)
            cur_child_json_node = json_node.get(child_xml_node.nodeName, None)
            if(cur_child_json_node is None):
                cur_child_json_node = new_child_json_node
            else:
                # if we have more than one of the same type, turn the children into a list
                if(not isinstance(cur_child_json_node, types.ListType)):
                    cur_child_json_node = [cur_child_json_node]
                cur_child_json_node.append(new_child_json_node)
            json_node[child_xml_node.nodeName] = cur_child_json_node
            
        xml_node_attrs = xml_node.attributes
        for attr_name in xml_node_attrs.keys():
            json_node["@" + attr_name] = xml_node_attrs[attr_name].nodeValue

        return json_node 
Example 16
Project: kay-template   Author: yosukesuzuki   File: rest.py    MIT License 6 votes vote down vote up
def models_to_xml(self, request, model_name, model_handler, models,
                      list_props=None):
        """Returns a string of xml of the given models (may be list or
        single instance)."""
        impl = minidom.getDOMImplementation()
        doc = None
        try:
            if isinstance(models, (types.ListType, types.TupleType)):
                doc = impl.createDocument(None, LIST_EL_NAME, None)
                list_el = doc.documentElement
                if ((list_props is not None) and \
                      (list_props.has_key(QUERY_OFFSET_PARAM))):
                    list_el.attributes[QUERY_OFFSET_PARAM] = \
                        list_props[QUERY_OFFSET_PARAM]
                for model in models:
                    model_el = append_child(list_el, model_name)
                    model_handler.write_xml_value(model_el, model)
            else:
                doc = impl.createDocument(None, model_name, None)
                model_handler.write_xml_value(doc.documentElement, models)

            return self.doc_to_output(request, doc)
        finally:
            if doc:
                doc.unlink() 
Example 17
Project: kay-template   Author: yosukesuzuki   File: rest.py    MIT License 6 votes vote down vote up
def keys_to_xml(self, request, model_handler, models):
        """Returns a string of xml of the keys of the given models
        (may be list or single instance)."""
        impl = minidom.getDOMImplementation()
        doc = None
        try:
            if isinstance(models, (types.ListType, types.TupleType)):
                doc = impl.createDocument(None, LIST_EL_NAME, None)
                list_el = doc.documentElement
                    
                for model in models:
                    append_child(
                        list_el, KEY_PROPERTY_NAME,
                        model_handler.key_handler.get_value_as_string(model))
            else:
                doc = impl.createDocument(None, KEY_PROPERTY_NAME, None)
                doc.documentElement.appendChild(
                    doc.createTextNode(
                        model_handler.key_handler.get_value_as_string(models)))
            return self.doc_to_output(request, doc)
        finally:
            if doc:
                doc.unlink() 
Example 18
Project: neurovault-annotation   Author: vsoch   File: h_util.py    MIT License 6 votes vote down vote up
def make_quote_html(self,raw):
        """Render an annotation's quote."""
        quote = ''
        target = raw.target
        try:
          if target is None:
              return quote 
          if isinstance(target,types.ListType) and len(target) == 0:
              return quote
          dict = {}
          if isinstance(target,types.ListType) and len(target) > 0:  # empirically observed it can be a list or not
              dict = target[0]
          else:
              dict = target
          if dict.has_key('selector') == False:
              return quote 
          selector = dict['selector']
          for sel in selector:
              if sel.has_key('exact'):
                  quote = sel['exact']
        except:
          s = traceback.format_exc()
          print s
        return quote 
Example 19
Project: pyblish-win   Author: pyblish   File: headers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self,headers):
        if type(headers) is not ListType:
            raise TypeError("Headers must be a list of name/value tuples")
        self._headers = headers 
Example 20
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _check_choice(self):
        if self.type == "choice":
            if self.choices is None:
                raise OptionError(
                    "must supply a list of choices for type 'choice'", self)
            elif type(self.choices) not in (types.TupleType, types.ListType):
                raise OptionError(
                    "choices must be a list of strings ('%s' supplied)"
                    % str(type(self.choices)).split("'")[1], self)
        elif self.choices is not None:
            raise OptionError(
                "must not supply choices for type %r" % self.type, self) 
Example 21
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _proxify(self, obj):
        if isinstance(obj, RemoteProxy):
            return RPCProxy(self, obj.oid)
        if isinstance(obj, types.ListType):
            return map(self._proxify, obj)
        # XXX Check for other types -- not currently needed
        return obj 
Example 22
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, currargs=None, prevargs=None, lineno=None,  
                     doTrace=False, logger=None):
        """
        @todo: Exception will change in Python 3.0: update this.  
                 args will no longer exist, message can be any object
        @summary Constructor for the LMError class
        @param currargs: Current arguments (sequence or single string)
        @param prevargs: (optional) sequence of previous arguments for exception
                                being wrapped by LMError
        """
        super(LMError, self).__init__()
        self.lineno = lineno
        
        allargs = []
        if doTrace:
            sysinfo = sys.exc_info()
            tb = sysinfo[2]
            if tb is not None:
                tbargs = traceback.format_tb(tb)
            else:
                tbargs = [str(sysinfo)]
            
            for r in tbargs:
                allargs.append(r)
                
        if isinstance(currargs, TupleType) or isinstance(currargs, ListType):
            allargs.extend(currargs)
        elif currargs is not None:
            allargs.append(currargs)
            
        if isinstance(prevargs, TupleType) or isinstance(prevargs, ListType):
            allargs.extend(prevargs)
        elif prevargs is not None:
            allargs.append(prevargs)
        self.args = tuple(allargs)
        
# ............................................................................ 
Example 23
Project: core   Author: lifemapper   File: troubleshoot.py    GNU General Public License v3.0 5 votes vote down vote up
def _notifyPeople(self, subject, message, recipients=None):
        if recipients is None:
            recipients = self.developers
        elif not (isinstance(recipients, ListType) 
                     or isinstance(recipients, TupleType)):
            recipients = [recipients]
        notifier = EmailNotifier()
        try:
            notifier.sendMessage(recipients, subject, message)
        except Exception, e:
            self.log.error('Failed to notify %s about %s' 
                                % (str(recipients), subject))

# ............................................... 
Example 24
Project: core   Author: lifemapper   File: jsonFormatter.py    GNU General Public License v3.0 5 votes vote down vote up
def jsonObjectFormatter(obj):
    """Looks at object and converts to JSON based on its type
    """
    if isinstance(obj, ListType):
        response = []
        for o in obj:
            response.append(_formatObject(o))
    else:
        response = _formatObject(obj)
    
    return json.dumps(response, indent=3)

# ............................................................................. 
Example 25
Project: core   Author: lifemapper   File: layer2.py    GNU General Public License v3.0 5 votes vote down vote up
def writeLayer(self, srcData=None, srcFile=None, outFile=None, overwrite=False):
        """
        @summary: Writes vector data to file and sets dlocation.
        @param srcData: A stream, or string of valid vector data
        @param srcFile: A filename for valid vector data.  Currently only 
                             supports CSV and ESRI shapefiles.
        @param overwrite: True/False directing whether to overwrite existing 
                     file or not
        @postcondition: The raster file is written to the filesystem.
        @raise LMError: on 1) failure to write file 
                                 2) attempt to overwrite existing file with overwrite=False
                                 3) _dlocation is None  
        """
        if srcFile is not None:
            self.readData(dlocation=srcFile)
        if outFile is None:
            outFile = self.getDLocation()
        if self.features is not None:
            self.writeShapefile(dlocation=outFile, overwrite=overwrite)
        # No file, no features, srcData is iterable, write as CSV
        elif srcData is not None:
            if isinstance(srcData, ListType) or isinstance(srcData, TupleType):
                if not outFile.endswith(LMFormat.CSV.ext):
                    raise LMError('Iterable input vector data can only be written to CSV')
                else:
                    self.writeCSV(dlocation=outFile, overwrite=overwrite)
            else:
                raise LMError('Writing vector is currently supported only for file or iterable input data')
        self.setDLocation(dlocation=outFile)

# ............................................... 
Example 26
Project: core   Author: lifemapper   File: checkProgress.py    GNU General Public License v3.0 5 votes vote down vote up
def notifyPeople(logger, subject, message, recipients=TROUBLESHOOTERS):
    if not (isinstance(recipients, ListType) 
              or isinstance(recipients, TupleType)):
        recipients = [recipients]
    notifier = EmailNotifier()
    try:
        notifier.sendMessage(recipients, subject, message)
    except Exception, e:
        logger.error('Failed to notify {} about {}'.format(str(recipients), subject))

# ............................................... 
Example 27
Project: neos-classic-electrum-server   Author: neoscoin   File: stratum_http.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_request(request):
    if not isinstance(request, types.DictType):
        return Fault(-32600, 'Request must be {}, not %s.' % type(request))
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        return Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
    request.setdefault('params', [])
    method = request.get('method', None)
    params = request.get('params')
    param_types = (types.ListType, types.DictType, types.TupleType)
    if not method or type(method) not in types.StringTypes or type(params) not in param_types:
        return Fault(-32600, 'Invalid request parameters or method.', rpcid=rpcid)
    return True 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def bytes2int(bytes):
    """Converts a list of bytes or a string to an integer
    """

    if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
        raise TypeError("You must pass a string or a list")

    # Convert byte stream to integer
    integer = 0
    for byte in bytes:
        integer *= 256
        if type(byte) is types.StringType: byte = ord(byte)
        integer += byte

    return integer 
Example 29
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def bytes2int(bytes):
    r"""Converts a list of bytes or a string to an integer
    """

    if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
        raise TypeError("You must pass a string or a list")

    # Convert byte stream to integer
    integer = 0
    for byte in bytes:
        integer *= 256
        if type(byte) is types.StringType: byte = ord(byte)
        integer += byte

    return integer 
Example 30
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def str642int(string):
    """Converts a base64 encoded string into an integer.
    The chars of this string in in the range '0'-'9','A'-'Z','a'-'z','-','_'
    """

    if not (type(string) is types.ListType or type(string) is types.StringType):
        raise TypeError("You must pass a string or a list")

    integer = 0
    for byte in string:
        integer *= 64
        if type(byte) is types.StringType: byte = ord(byte)
        integer += from64(byte)

    return integer 
Example 31
Project: tintri-python-sdk   Author: Tintri   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def map_to_object(m, cls):
    def __getobjecttype(cls, varname):
        from .__init__ import TintriObject
        if '_property_map' in dir(cls):
            if varname in cls._property_map.keys():
                return cls._property_map[varname]
        return TintriObject

    if type(m) == types.DictionaryType:
        o = cls()
        
        ignoresetattr = None
        if hasattr(o, '_ignoresetattr'):
            ignoresetattr = o._ignoresetattr
            o._ignoresetattr = True

        for k in m.keys():
            cls2 = __getobjecttype(cls, k)
            setattr(o, k, map_to_object(m[k], cls2))

        if ignoresetattr:
            o._ignoresetattr = ignoresetattr
            
        return o
    elif type(m) == types.ListType:
        objects = []
        for obj in m:
            objects.append(map_to_object(obj, cls))
        return objects
    else:
        return m 
Example 32
Project: tintri-python-sdk   Author: Tintri   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dump_object(obj, level=0, name='', logger=None):
    if logger is None:
        logger = logging.getLogger(DEFAULT_LOGGER_NAME)
        logger.setLevel(logging.DEBUG)
        # don't add a StreamHandler to the logger object if it already has one
        if not any(isinstance(handler, logging.StreamHandler) for handler in logger.handlers):
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
            # Set the Formatter to the default format.
            ch.setFormatter(logging.Formatter())
            logger.addHandler(ch)

    #print " " * level + "[%s]:" % (type(obj).__name__)
    if level == 0:
        logger.info('[DUMP]',)
#         print " " * level + '>' * 14 + ' Object Dump ' + '>' * 14

    if obj == None:
        logger.info(" " * level + "%s[None]: None", name)
    elif type(obj) in [types.ListType, types.TupleType]:
        if len(obj) == 0:
            logger.info(" " * level + "%s[%s]: []", name, type(obj).__name__)
        else:
            logger.info(" " * level + "%s[%s]: [", name, type(obj).__name__)
            for e in obj:
                dump_object(e, level=level + 4, logger=logger)
            logger.info(" " * level + "]")
    elif hasattr(obj, '__dict__'):
        if len(obj.__dict__.keys()) == 0:
            logger.info(" " * level + "%s[%s]: {}", name, obj.__class__.__name__)
        else:
            logger.info(" " * level + "%s[%s]: {", name, obj.__class__.__name__)
            for key, value in obj.__dict__.items():
                if not key.startswith('_'):
                    dump_object(value, level=level + 4, name=key, logger=logger)
            logger.info(" " * level + "}")
    else:
        logger.info(" " * level + "%s[%s]: %s", name, type(obj).__name__, `obj`)

    #    if level == 0:
    #    print " " * level + '<' * 41 
Example 33
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 34
Project: openhatch   Author: campbe13   File: feedparser.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __setitem__(self, key, value):
        for k in self.keymap.keys():
            if key == k:
                key = self.keymap[k]
                if type(key) == types.ListType:
                    key = key[0]
        return UserDict.__setitem__(self, key, value) 
Example 35
Project: openhatch   Author: campbe13   File: feedparser.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _writer(self, stream, node, prefix):
        if not node: return
        if hasattr(node, 'keys'):
            keys = node.keys()
            keys.sort()
            for k in keys:
                if k in ('description', 'link'): continue
                if node.has_key(k + '_detail'): continue
                if node.has_key(k + '_parsed'): continue
                self._writer(stream, node[k], prefix + k + '.')
        elif type(node) == types.ListType:
            index = 0
            for n in node:
                self._writer(stream, n, prefix[:-1] + '[' + str(index) + '].')
                index += 1
        else:
            try:
                s = str(node).encode('utf-8')
                s = s.replace('\\', '\\\\')
                s = s.replace('\r', '')
                s = s.replace('\n', r'\n')
                stream.write(prefix[:-1])
                stream.write('=')
                stream.write(s)
                stream.write('\n')
            except:
                pass 
Example 36
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: _pydev_inspect.py    MIT License 5 votes vote down vote up
def strseq(object, convert, join=joinseq):
    """Recursively walk a sequence, stringifying each element."""
    if type(object) in [types.ListType, types.TupleType]:
        return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
    else:
        return convert(object) 
Example 37
Project: pystran   Author: stijnvanhoey   File: latextablegenerator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_data(self, data, label="", sigfigs=2, labeltype='cutin'):
      '''Add a matrix of data.  [data] should be a list with length equal to
      the number of columns of the table.  Each item of [data] should be a 
      list or numpy array.  A list of strings will be inserved as is.  If
      a column is a 1-D array of float type, the number of significant
      figures will be set to [sigfigs].  If a column is 2D with shape
      (N,2), it is treated as a value with uncertainty and the uncertainty
      will be rounded to [sigfigs] and value will be rounded accordingly, 
      and both will be printed with parenthetical errors.  If a label is
      given, it will be printed in the table with \cutinhead if labeltype
      is 'cutin' or \sidehead if labeltype is 'side'.'''

      if type(data) is not types.ListType:
         raise ValueError, "data should be a list"
      if len(data) != self.numcols:
         raise ValueError, \
               "Error, length of data mush match number of table columns"

      for datum in data:
         if type(datum) not in [types.ListType, numpy.ndarray]:
            raise ValueError, "data must be list of lists and numpy arrays"
         if len(numpy.shape(datum)) not in [1,2]:
            raise ValueError, "data items must be 1D or 2D"

      nrows = numpy.shape(data[0])[0]
      for datum in data[1:]:
         if numpy.shape(datum)[0] != nrows:
            raise ValueError, "each data item must have same first dimension"
      self.nrows.append(nrows)
      if len(numpy.shape(sigfigs)) == 0:
         self.sigfigs.append([sigfigs for i in range(self.numcols)])
      else:
         if len(numpy.shape(sigfigs)) != 1:
            raise ValueError, \
               "sigfigs must be scalar or have same length as number of columns"
         self.sigfigs.append(sigfigs)
      self.data_labels.append(label)
      self.data_label_types.append(labeltype)
      self.data.append(data) 
Example 38
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def findProperties(self, *names):
        """
        Retrieve given properties for this collection and all directly contained resources.
        
        @param names: a list of property names
        @return: a map from resource URI to a map from property name to value.
        """
        assert isinstance(names, types.ListType) or isinstance(names, types.TupleType), \
                "Argument name has type %s" % str(type(names))
        body = createFindBody(names, self.defaultNamespace)
        response = self.connection.propfind(self.path, body, depth=1)
        return response.msr 
Example 39
Project: spider   Author: LaveyD   File: select_result.py    GNU General Public License v3.0 5 votes vote down vote up
def strip_null(arg,null=None):
    """
        strip list,set,tuple,dict null item.

        @param:
            arg:the variable to strip null
            null:the null definition,if it is None,then use NULL as the null

        if arg is list,then strip the null item,return the new list
        if arg is tuple,then strip the null item,return the new tuple
        if arg is set,then strip the null item,return the new set
        if arg is dict,then strip the dict item which value is null.return the new dict
    """
    if null is None:
        null = NULL

    if type(arg) is types.ListType:
        return [i for i in arg if i not in null]
    elif type(arg) is types.TupleType:
        return tuple([i for i in arg if i not in null])
    elif type(arg) is type(set()):
        return arg.difference(set(null))
    elif type(arg) is types.DictType:
        return {key:value for key,value in arg.items() if value not in null}

    return arg 
Example 40
Project: python-lcms2   Author: sk1project   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def cmsDoTransform(hTransform, inbuff, outbuff, val=None):
	"""
	Transform color values from inputBuffer to outputBuffer using provided 
	lcms transform handle.
	
	hTransform - a valid lcms transformation handle
	inbuff - 5-member list object.
	outbuff - 5-member list object with any values for recording 
					transformation results. Can be [0,0,0,0,0].
	val - stub parameter for python-lcms compatibility			              
	"""
	if type(inbuff) is types.ListType and type(outbuff) is types.ListType and \
	len(inbuff) == 5 and len(outbuff) == 5 :
		vals = inbuff[:4] + [outbuff[4], ]
		if inbuff[4] == COLOR_WORD:
			ret = _lcms2.transformPixel16b(hTransform, *vals)
		elif inbuff[4] == COLOR_DBL:
			ret = _lcms2.transformPixelDbl(hTransform, *vals)
		else:
			ret = _lcms2.transformPixel(hTransform, *vals)
		outbuff[0] = ret[0]
		outbuff[1] = ret[1]
		outbuff[2] = ret[2]
		outbuff[3] = ret[3]
		return

	else:
		msg = 'inputBuffer and outputBuffer must be Python 5-member list objects'
		raise CmsError, msg 
Example 41
Project: octopuscloud   Author: christianbaun   File: xmlmanager.py    Apache License 2.0 5 votes vote down vote up
def _build_query(self, cls, filters, limit, order_by):
        import types
        if len(filters) > 4:
            raise Exception('Too many filters, max is 4')
        parts = []
        properties = cls.properties(hidden=False)
        for filter, value in filters:
            name, op = filter.strip().split()
            found = False
            for property in properties:
                if property.name == name:
                    found = True
                    if types.TypeType(value) == types.ListType:
                        filter_parts = []
                        for val in value:
                            val = self.encode_value(property, val)
                            filter_parts.append("'%s' %s '%s'" % (name, op, val))
                        parts.append("[%s]" % " OR ".join(filter_parts))
                    else:
                        value = self.encode_value(property, value)
                        parts.append("['%s' %s '%s']" % (name, op, value))
            if not found:
                raise Exception('%s is not a valid field' % name)
        if order_by:
            if order_by.startswith("-"):
                key = order_by[1:]
                type = "desc"
            else:
                key = order_by
                type = "asc"
            parts.append("['%s' starts-with ''] sort '%s' %s" % (key, key, type))
        return ' intersection '.join(parts) 
Example 42
Project: octopuscloud   Author: christianbaun   File: connection.py    Apache License 2.0 5 votes vote down vote up
def _build_bootstrap_action_list(self, bootstrap_actions):
        if type(bootstrap_actions) != types.ListType:
            bootstrap_actions = [bootstrap_actions]

        params = {}
        for i, bootstrap_action in enumerate(bootstrap_actions):
            for key, value in bootstrap_action.iteritems():
                params['BootstrapActions.memeber.%s.%s' % (i + 1, key)] = value
        return params 
Example 43
Project: octopuscloud   Author: christianbaun   File: connection.py    Apache License 2.0 5 votes vote down vote up
def _build_step_list(self, steps):
        if type(steps) != types.ListType:
            steps = [steps]

        params = {}
        for i, step in enumerate(steps):
            for key, value in step.iteritems():
                params['Steps.memeber.%s.%s' % (i+1, key)] = value
        return params 
Example 44
Project: sd-agent-core-plugins   Author: serverdensity   File: test_tomcat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tomcat_metrics(self):
        count = 0
        while self.reporter.metrics is None:
            time.sleep(1)
            count += 1
            if count > 25:
                raise Exception("No metrics were received in 25 seconds")

        metrics = self.reporter.metrics

        self.assertTrue(isinstance(metrics, ListType))
        self.assertTrue(len(metrics) > 0)
        self.assertEquals(len([t for t in metrics if t['metric'] == "tomcat.threads.busy" and "instance:tomcat_instance" in t['tags']]), 2, metrics)
        self.assertEquals(len([t for t in metrics if t['metric'] == "tomcat.bytes_sent" and "instance:tomcat_instance" in t['tags']]), 0, metrics)
        self.assertTrue(len([t for t in metrics if "jvm." in t['metric'] and "instance:tomcat_instance" in t['tags']]) > 4, metrics) 
Example 45
Project: sd-agent-core-plugins   Author: serverdensity   File: test_couchbase.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_metrics(self):
        raise SkipTest("Skipped for now as it's hard to configure couchbase on travis")
        self.check.check(self.config['instances'][0])

        metrics = self.check.get_metrics()

        self.assertTrue(isinstance(metrics, ListType))
        self.assertTrue(len(metrics) > 3)
        self.assertTrue(len([k for k in metrics if "instance:http://localhost:8091" in k[3]['tags']]) > 3)

        self.assertTrue(len([k for k in metrics if -1 != k[0].find('by_node')]) > 1, 'Unable to fund any per node metrics')
        self.assertTrue(len([k for k in metrics if -1 != k[0].find('by_bucket')]) > 1, 'Unable to fund any per node metrics') 
Example 46
Project: sd-agent-core-plugins   Author: serverdensity   File: test_couchbase.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_query_monitoring_metrics(self):
        raise SkipTest("Skipped for now as it's hard to configure couchbase on travis")
        # Add query monitoring endpoint and reload check
        self.config['instances'][0]['query_monitoring_url'] = 'http://localhost:8093'
        self.check = load_check('couchbase', self.config, self.agentConfig)
        self.check.check(self.config['instances'][0])

        metrics = self.check.get_metrics()

        self.assertTrue(isinstance(metrics, ListType))
        self.assertTrue(len(metrics) > 3)

        self.assertTrue(len([k for k in metrics if 'query' in k[0]]) > 1, 'Unable to fund any query metrics') 
Example 47
Project: sd-agent-core-plugins   Author: serverdensity   File: test_kafka.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testCustomJMXMetric(self):
        count = 0
        while self.reporter.metrics is None:
            time.sleep(1)
            count += 1
            if count > 25:
                raise Exception("No metrics were received in 25 seconds")

        metrics = self.reporter.metrics
        # expected_tags = ['env:test', 'instance:kafka-172.17.0.1-9999', 'kafka:broker']

        self.assertTrue(isinstance(metrics, ListType))
        self.assertTrue(len(metrics) > 0)
        log.info(metrics)
        log.info(len(metrics))
        self.assertTrue(
            len([t for t in metrics if "jvm." in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) >= 13, metrics)
        self.assertTrue(
            len([t for t in metrics if "kafka.request." in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) == 12, metrics)
        self.assertTrue(
            len([t for t in metrics if "kafka.replication." in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) == 6, metrics)

        # CLIENT metrics.
        # kafka.producer.request_latency_avg
        self.assertTrue(
            len([t for t in metrics if "kafka.producer." in t['metric'] and "instance:kafka-172.17.0.1-7777" in t['tags']]) == 1, metrics)
        # kafka.consumer.fetch_rate, kafka.consumer.max_lag
        self.assertTrue(
            len([t for t in metrics if "kafka.consumer." in t['metric'] and "instance:kafka-172.17.0.1-7777" in t['tags']]) == 2, metrics)


        # self.assertTrue(
        #     len([t for t in metrics if "kafka.follower." in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) > 40, metrics)
        # self.assertTrue(
        #     len([t for t in metrics if "kafka.net." in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) > 40, metrics)
        # self.assertTrue(
        #     len([t for t in metrics if "kafka.messages_in" in t['metric'] and "instance:kafka-172.17.0.1-9999" in t['tags']]) > 40, metrics) 
Example 48
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):
        scxx_converter.init_info(self)
        self.type_name = 'list'
        self.check_func = 'PyList_Check'
        self.c_type = 'py::list'
        self.return_type = 'py::list'
        self.to_c_return = 'py::list(py_obj)'
        self.matching_types = [types.ListType]
        # ref counting handled by py::list
        self.use_ref_count = 0 
Example 49
Project: TAF   Author: couchbaselabs   File: BeautifulSoup.py    Apache License 2.0 5 votes vote down vote up
def isList(l):
    """Convenience method that works with all 2.x versions of Python
    to determine whether or not something is listlike."""
    return hasattr(l, '__iter__') \
           or (type(l) in (types.ListType, types.TupleType)) 
Example 50
Project: TESTGIT   Author: B-ROY   File: feedparser.py    Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key):
        if key == 'category':
            return UserDict.__getitem__(self, 'tags')[0]['term']
        if key == 'categories':
            return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
        realkey = self.keymap.get(key, key)
        if type(realkey) == types.ListType:
            for k in realkey:
                if UserDict.has_key(self, k):
                    return UserDict.__getitem__(self, k)
        if UserDict.has_key(self, key):
            return UserDict.__getitem__(self, key)
        return UserDict.__getitem__(self, realkey)