Python types.TupleType() Examples

The following are code examples for showing how to use types.TupleType(). 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: 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 3
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 4
Project: neos-classic-electrum-server   Author: neoscoin   File: deserialize.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = {}
        reverseLookup = {}
        i = 0
        uniqueNames = []
        uniqueValues = []
        for x in enumList:
            if isinstance(x, types.TupleType):
                x, i = x
            if not isinstance(x, types.StringType):
                raise EnumException("enum name is not a string: %r" % x)
            if not isinstance(i, types.IntType):
                raise EnumException("enum value is not an integer: %r" % i)
            if x in uniqueNames:
                raise EnumException("enum name is not unique: %r" % x)
            if i in uniqueValues:
                raise EnumException("enum value is not unique for %r" % x)
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 5
Project: DRCOG_Urbansim   Author: apdjustino   File: autogen_helper_functions.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def parsetree_substitute(parsetree, dict):
    """function that takes a parsetree and returns a new tree, substituting subtrees in dict 
       with the corresponding replacement tree.  dict is a dictionary whose keys are the 
       tree fragments to replace and whose values are the replacement tree fragments"""
    if type(parsetree) is TupleType:
        newtree = ()
        for t in parsetree:
            if t in dict:
                newtree = newtree + ( dict[t] , )
            else:
                newtree = newtree + ( parsetree_substitute(t, dict) , )
        return newtree
    else:
        if parsetree in dict:
            return dict[parsetree]
        else:
            return parsetree 
Example 6
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 7
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 8
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 9
Project: aws-cfn-plex   Author: lordmuffin   File: pubkey.py    MIT License 6 votes vote down vote up
def decrypt(self, ciphertext):
        """Decrypt a piece of data. 

        :Parameter ciphertext: The piece of data to decrypt.
        :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt`

        :Return: A byte string if ciphertext was a byte string or a tuple
         of byte strings. A long otherwise.
        """
        wasString=0
        if not isinstance(ciphertext, types.TupleType):
            ciphertext=(ciphertext,)
        if isinstance(ciphertext[0], types.StringType):
            ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
        plaintext=self._decrypt(ciphertext)
        if wasString: return long_to_bytes(plaintext)
        else: return plaintext 
Example 10
Project: Uwallet-server   Author: UlordChain   File: deserialize.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = {}
        reverseLookup = {}
        i = 0
        uniqueNames = []
        uniqueValues = []
        for x in enumList:
            if isinstance(x, types.TupleType):
                x, i = x
            if not isinstance(x, types.StringType):
                raise EnumException("enum name is not a string: %r" % x)
            if not isinstance(i, types.IntType):
                raise EnumException("enum value is not an integer: %r" % i)
            if x in uniqueNames:
                raise EnumException("enum name is not unique: %r" % x)
            if i in uniqueValues:
                raise EnumException("enum value is not unique for %r" % x)
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 11
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 12
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 13
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 14
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 15
Project: electrum-martexcoin-server   Author: martexcoin   File: deserialize.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = {}
        reverseLookup = {}
        i = 0
        uniqueNames = []
        uniqueValues = []
        for x in enumList:
            if isinstance(x, types.TupleType):
                x, i = x
            if not isinstance(x, types.StringType):
                raise EnumException("enum name is not a string: %r" % x)
            if not isinstance(i, types.IntType):
                raise EnumException("enum value is not an integer: %r" % i)
            if x in uniqueNames:
                raise EnumException("enum name is not unique: %r" % x)
            if i in uniqueValues:
                raise EnumException("enum value is not unique for %r" % x)
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
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: kay-template   Author: yosukesuzuki   File: media_compiler.py    MIT License 6 votes vote down vote up
def equal_object_(a, b):
  if type(a) == types.DictType and type(b) == types.DictType:
    if len(a.keys()) != len(b.keys()):
      return False
    for k, v in a.iteritems():
      if k not in b:
        return False
      if not equal_object_(v, b[k]):
        return False
    return True
  elif type(a) in [types.ListType, types.TupleType] and \
        type(b) in [types.ListType, types.TupleType]:
    if len(a) != len(b):
      return False
    ia = iter(a)
    ib = iter(b)
    try:
      while True:
        if not equal_object_(ia.next(), ib.next()):
          return False
    except:
      pass
    return True
  else:
    return a == b 
Example 19
Project: dumpDex   Author: CvvT   File: idaapi.py    Apache License 2.0 6 votes vote down vote up
def pack(self, L):
        """
        Packs a list or tuple into a byref buffer
        """
        t = type(L)
        if not (t == types.ListType or t == types.TupleType):
            raise ValueError, "Either a list or a tuple must be passed"
        self.__size = len(L)
        if self.__size == 1:
            self.__typedobj = Appcall__.typedobj(self.__type + ";")
        else:
            self.__typedobj = Appcall__.typedobj("%s x[%d];" % (self.__type, self.__size))
        # Now store the object in a string buffer
        ok, buf = self.__typedobj.store(L)
        if ok:
            return Appcall__.byref(buf)
        else:
            return None 
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: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 22
Project: pyblish-win   Author: pyblish   File: symbols.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_args(self, scope, args):
        for name in args:
            if type(name) == types.TupleType:
                self._do_args(scope, name)
            else:
                scope.add_param(name) 
Example 23
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 24
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 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: core   Author: lifemapper   File: log.py    GNU General Public License v3.0 5 votes vote down vote up
def reportError(self, msg):
      if type(msg) is ListType or type(msg) is TupleType:
         msg = ' '.join(msg)
      sysinfo = sys.exc_info()
      argStr = '\n'.join(str(arg) for arg in sysinfo[1].args)
      tb = sysinfo[2]
      if tb is not None:
         tbStr = '\n'.join(traceback.format_tb(tb))
      else:
         tbStr = str(sysinfo)
      errStr = '\n'.join([tbStr, argStr])
      self.error(msg)
      self.error(errStr)

   # .............................................. 
Example 28
Project: radius-1xtest   Author: shanghai-edu   File: packet.py    Apache License 2.0 5 votes vote down vote up
def _PktEncodeAttribute(self, key, value):
        if type(key)==types.TupleType:
            value=struct.pack("!L", key[0]) + \
                self._PktEncodeAttribute(key[1], value)
            key=26

        return struct.pack("!BB", key, (len(value)+2))+value 
Example 29
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 30
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 31
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_first_result(self, results, default=False):
        if len(results):
            value = results[0]
            if isinstance(value, types.TupleType):
                value = value[0]
        else:
            value = default
        return value 
Example 32
Project: razzy-spinner   Author: rafasashi   File: chunk.py    GNU General Public License v3.0 5 votes vote down vote up
def _tag(self, tok):
        if type(tok) == types.TupleType:
            return tok[1]
        elif isinstance(tok, Tree):
            return tok.node
        else:
            raise ValueError, 'chunk structures must contain tokens and trees' 
Example 33
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 34
Project: pystran   Author: stijnvanhoey   File: latextablegenerator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_header_row(self, headers, cols=None):
      '''Add a header row to the table.  [headers] should be a list of the
      strings that will be in the header.  [cols], if specified, should be a 
      list of column indexes.  If [cols] is None, it is assummed the headers
      are in order and there are no multicolumns.  If cols is specified, you
      can indicate the the ith header spans several columns by setting the
      ith value of cols to a 2-tuple of first and last columns for the span.'''
      
      if cols is None:
         if len(headers) != self.numcols:
            raise ValueError, "Error, headers must be a list of length %d" %\
                  self.numcols
         self.headers.append(headers)
         self.header_ids.append(range(self.numcols))
      else:
         ids = []
         for item in cols:
            if type(item) is types.IntType:
               ids.append(item)
            elif type(item) is types.TupleType:
               ids += range(item[0],item[1]+1)

         ids.sort
         if ids != range(self.numcols):
            raise ValueError, "Error, missing columns in cols"
         self.headers.append(headers)
         self.header_ids.append(cols)
      return 
Example 35
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 36
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 37
Project: talkback   Author: Axilent   File: core.py    MIT License 5 votes vote down vote up
def conduct_interview(self,session):
        """ 
        Conducts the interview with the user.
        """
        if self.introduction:
            session.speak(self.introduction)
        
        for question in self.questions:
            if type(question) is TupleType:
                self.ask_multiple_choice_question(session,question)
            elif type(question) is StringType:
                self.ask_question(session,question)
            else:
                raise ValueError('Bad question:%s' % str(question)) 
Example 38
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 = 'tuple'
        self.check_func = 'PyTuple_Check'
        self.c_type = 'py::tuple'
        self.return_type = 'py::tuple'
        self.to_c_return = 'py::tuple(py_obj)'
        self.matching_types = [types.TupleType]
        # ref counting handled by py::tuple
        self.use_ref_count = 0 
Example 39
Project: centreon-discovery   Author: Centreon-Community   File: pubkey.py    GNU General Public License v2.0 5 votes vote down vote up
def decrypt(self, ciphertext):
        """decrypt(ciphertext:tuple|string|long): string
        Decrypt 'ciphertext' using this key.
        """
        wasString=0
        if not isinstance(ciphertext, types.TupleType):
            ciphertext=(ciphertext,)
        if isinstance(ciphertext[0], types.StringType):
            ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
        plaintext=self._decrypt(ciphertext)
        if wasString: return long_to_bytes(plaintext)
        else: return plaintext 
Example 40
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 41
Project: TAF   Author: couchbaselabs   File: BeautifulSoup.py    Apache License 2.0 5 votes vote down vote up
def _subMSChar(self, orig):
        """Changes a MS smart quote character to an XML or HTML
        entity."""
        sub = self.MS_CHARS.get(orig)
        if type(sub) == types.TupleType:
            if self.smartQuotesTo == 'xml':
                sub = '&#x%s;' % sub[1]
            else:
                sub = '&%s;' % sub[0]
        return sub 
Example 42
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def normalizeFilter (filterVar):
    if filterVar == None or filterVar == '*':
        filterVar = ("*",)
    elif not isinstance(filterVar, TupleType):
        filterVar = (filterVar,)
    return filterVar


######################################################################
# Namespace handling
###################################################################### 
Example 43
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toClarkQName (tupleOrLocalName):
    """converts a tuple (namespace, localName) into clark notation {namespace}localName
       qNames without namespace remain unchanged

    Input parameter:
        'tupleOrLocalName':  tuple '(namespace, localName)' to be converted
    Returns a string {namespace}localName
    """
    if isinstance(tupleOrLocalName, TupleType):
        if tupleOrLocalName[0] != EMPTY_NAMESPACE:
            return "{%s}%s" %(tupleOrLocalName[0], tupleOrLocalName[1])
        else:
            return tupleOrLocalName[1]
    else:
        return tupleOrLocalName 
Example 44
Project: SherpaHighLevel   Author: Shedino   File: xsvalXmlIf.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getXsdAttrNode (self, tupleOrAttrName):
        """Retrieve XML schema node responsible for the requested attribute.

        Input parameter:
            tupleOrAttrName:  tuple '(namespace, attributeName)' or 'attributeName' if no namespace is used
        Returns XML schema node responsible for the requested attribute.
        """
        try:
            return self.xsdAttrNodes[tupleOrAttrName]
        except:
            if isinstance(tupleOrAttrName, TupleType):
                if tupleOrAttrName[1] == '*' and len(self.xsdAttrNodes) == 1:
                    return self.xsdAttrNodes.values()[0]
            return None 
Example 45
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def normalizeFilter (filterVar):
    if filterVar == None or filterVar == '*':
        filterVar = ("*",)
    elif not isinstance(filterVar, TupleType):
        filterVar = (filterVar,)
    return filterVar


######################################################################
# Namespace handling
###################################################################### 
Example 46
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toClarkQName (tupleOrLocalName):
    """converts a tuple (namespace, localName) into clark notation {namespace}localName
       qNames without namespace remain unchanged

    Input parameter:
        'tupleOrLocalName':  tuple '(namespace, localName)' to be converted
    Returns a string {namespace}localName
    """
    if isinstance(tupleOrLocalName, TupleType):
        if tupleOrLocalName[0] != EMPTY_NAMESPACE:
            return "{%s}%s" %(tupleOrLocalName[0], tupleOrLocalName[1])
        else:
            return tupleOrLocalName[1]
    else:
        return tupleOrLocalName 
Example 47
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def _get_server(self, key):
        if type(key) == types.TupleType:
            return memcache.Client._get_server(key)

        for i in range(self._SERVER_RETRIES):
            iterator = self.hash_ring.iterate_nodes(key)
            for server_uri in iterator:
                server_obj = self.server_mapping[server_uri]
                if server_obj.connect():
                    return server_obj, key

        return None, None 
Example 48
Project: Uwallet-server   Author: UlordChain   File: stratum_http.py    GNU 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 49
Project: bitmask-dev   Author: leapcode   File: test_imap.py    GNU General Public License v3.0 5 votes vote down vote up
def sortNest(l):
    l = l[:]
    l.sort()
    for i in range(len(l)):
        if isinstance(l[i], types.ListType):
            l[i] = sortNest(l[i])
        elif isinstance(l[i], types.TupleType):
            l[i] = tuple(sortNest(list(l[i])))
    return l 
Example 50
Project: ironpython2   Author: IronLanguages   File: optparse.py    Apache License 2.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)