Python types.TupleType() Examples

The following are 30 code examples for showing how to use types.TupleType(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module types , or try the search function .

Example 1
Project: mishkal   Author: linuxscout   File: lint.py    License: GNU 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)
        assert not bad_header_value_re.search(value), (
            "Bad header value: %r (bad char: %r)"
            % (value, bad_header_value_re.search(value).group(0))) 
Example 2
Project: earthengine   Author: mortcanty   File: pubkey.py    License: 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 3
Project: meddle   Author: glmcdona   File: validate.py    License: MIT License 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 4
Project: ironpython2   Author: IronLanguages   File: validate.py    License: 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 5
Project: Robofont-scripts   Author: loicsander   File: location.py    License: MIT License 6 votes vote down vote up
def isAmbivalent(self, dim=None):
        """
        Return True if any of the factors are in fact tuples.
        If a dimension name is given only that dimension is tested.
        ::
            >>> l = Location(pop=1)
            >>> l.isAmbivalent()
            False
            >>> l = Location(pop=1, snap=(100, -100))
            >>> l.isAmbivalent()
            True
        """
        if dim is not None:
            try:
                return type(self[dim]) == TupleType
            except KeyError:
                # dimension is not present, it should be 0, so not ambivalent
                return False
        for dim, val in self.items():
            if type(val) == TupleType:
                return True
        return False 
Example 6
Project: Robofont-scripts   Author: loicsander   File: location.py    License: MIT License 6 votes vote down vote up
def split(self):
        """
        Split an ambivalent location into 2. One for the x, the other for the y.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.split()
            (<Location pop:-5 >, <Location pop:5 >)
        """
        x = self.__class__()
        y = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                x[dim] = val[0]
                y[dim] = val[1]
            else:
                x[dim] = val
                y[dim] = val
        return x, y 
Example 7
Project: Robofont-scripts   Author: loicsander   File: location.py    License: MIT License 6 votes vote down vote up
def spliceX(self):
        """
        Return a copy with the x values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceX()
            <Location pop:-5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                new[dim] = val[0]
            else:
                new[dim] = val
        return new 
Example 8
Project: Robofont-scripts   Author: loicsander   File: location.py    License: MIT License 6 votes vote down vote up
def spliceY(self):
        """
        Return a copy with the y values preferred for ambivalent locations.
        ::

            >>> l = Location(pop=(-5,5))
            >>> l.spliceY()
            <Location pop:5 >
        """
        new = self.__class__()
        for dim, val in self.items():
            if type(val) == TupleType:
                new[dim] = val[1]
            else:
                new[dim] = val
        return new 
Example 9
Project: BinderFilter   Author: dxwu   File: validate.py    License: MIT License 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 10
Project: oss-ftp   Author: aliyun   File: validate.py    License: MIT License 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 11
Project: Safejumper-for-Desktop   Author: proxysh   File: pubkey.py    License: GNU General Public License v2.0 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 12
Project: encompass   Author: mazaclub   File: transaction.py    License: 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 type(x) == types.TupleType:
                x, i = x
            if type(x) != types.StringType:
                raise EnumException, "enum name is not a string: " + x
            if type(i) != types.IntType:
                raise EnumException, "enum value is not an integer: " + i
            if x in uniqueNames:
                raise EnumException, "enum name is not unique: " + x
            if i in uniqueValues:
                raise EnumException, "enum value is not unique for " + x
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 13
Project: pmatic   Author: LarsMichelsen   File: validate.py    License: GNU General Public License v2.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 14
Project: code   Author: ActiveState   File: recipe-473818.py    License: MIT License 6 votes vote down vote up
def new_looper(a, arg=None):
    """Helper function for nest()
    determines what sort of looper to make given a's type"""
    if isinstance(a,types.TupleType):
        if len(a) == 2:
            return RangeLooper(a[0],a[1])
        elif len(a) == 3:
            return RangeLooper(a[0],a[1],a[2])
    elif isinstance(a, types.BooleanType):
        return BooleanLooper(a)
    elif isinstance(a,types.IntType) or isinstance(a, types.LongType):
        return RangeLooper(a)
    elif isinstance(a, types.StringType) or isinstance(a, types.ListType):
        return ListLooper(a)
    elif isinstance(a, Looper):
        return a
    elif isinstance(a, types.LambdaType):
        return CalcField(a, arg) 
Example 15
Project: code   Author: ActiveState   File: recipe-223610.py    License: MIT License 6 votes vote down vote up
def __init__(self,rowset,description):
    # save the description as is
    self.description = fRow(description)
    self.description.__Field2Index__ = self.__fieldToIndex
    
    # Create the list and dict of fields
    self.fields = []
    self.__fieldDict = {}
    for f in range(len(description)):
      if type(description[f]) == types.TupleType or type(description[f]) == types.ListType:
        self.__fieldDict[description[f][0].lower()] = f
        self.fields.append( description[f][0].lower())
      else:
        self.__fieldDict[description[f].lower()] = f
        self.fields.append( description[f].lower())
    # Add all the rows
    for r in rowset:
      self.append(r) 
Example 16
Project: addon   Author: alfa-addon   File: handler.py    License: GNU General Public License v3.0 6 votes vote down vote up
def send_resp_header(self, cont_type, size, range=False):
    
        if range:
            self.send_response(206, 'Partial Content')
        else:
            self.send_response(200, 'OK')

        self.send_header('Content-Type', cont_type)
        self.send_header('Accept-Ranges', 'bytes')

        if range:
            if isinstance(range, (types.TupleType, types.ListType)) and len(range)==3:
                self.send_header('Content-Range', 'bytes %d-%d/%d' % range)
                self.send_header('Content-Length', range[1]-range[0]+1)
            else:
                raise ValueError('Invalid range value')
        else:
            self.send_header('Content-Length', size)
            
        self.send_header('Connection', 'close')
        self.end_headers() 
Example 17
Project: addon   Author: alfa-addon   File: handler.py    License: GNU General Public License v3.0 6 votes vote down vote up
def send_resp_header(self, cont_type, cont_length, range=False):  # @ReservedAssignment
        if range:
            self.send_response(206, 'Partial Content')
        else:
            self.send_response(200, 'OK')

        self.send_header('Content-Type', cont_type)
        self.send_header('transferMode.dlna.org', 'Streaming')
        self.send_header('contentFeatures.dlna.org',
                         'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000')
        self.send_header('Accept-Ranges', 'bytes')

        if range:
            if isinstance(range, (types.TupleType, types.ListType)) and len(range) == 3:
                self.send_header('Content-Range', 'bytes %d-%d/%d' % range)
                self.send_header('Content-Length', range[1] - range[0] + 1)
            else:
                raise ValueError('Invalid range value')
        else:
            self.send_header('Content-Length', cont_length)
        self.finish_header() 
Example 18
Project: razzy-spinner   Author: rafasashi   File: chunk.py    License: 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 19
Project: bayeslite   Author: probcomp   File: Transitions.py    License: Apache License 2.0 5 votes vote down vote up
def add(self, event, new_state,
    TupleType = TupleType):
    """
    Add transition to |new_state| on |event|.
    """
    if type(event) == TupleType:
      code0, code1 = event
      i = self.split(code0)
      j = self.split(code1)
      map = self.map
      while i < j:
        map[i + 1][new_state] = 1
        i = i + 2
    else:
      self.get_special(event)[new_state] = 1 
Example 20
Project: bayeslite   Author: probcomp   File: Transitions.py    License: Apache License 2.0 5 votes vote down vote up
def add_set(self, event, new_set,
    TupleType = TupleType):
    """
    Add transitions to the states in |new_set| on |event|.
    """
    if type(event) == TupleType:
      code0, code1 = event
      i = self.split(code0)
      j = self.split(code1)
      map = self.map
      while i < j:
        map[i + 1].update(new_set)
        i = i + 2
    else:
      self.get_special(event).update(new_set) 
Example 21
Project: bayeslite   Author: probcomp   File: Machines.py    License: Apache License 2.0 5 votes vote down vote up
def add_transitions(self, state, event, new_state):
    if type(event) == TupleType:
      code0, code1 = event
      if code0 == -maxint:
        state['else'] = new_state
      elif code1 <> maxint:
        while code0 < code1:
          state[chr(code0)] = new_state
          code0 = code0 + 1
    else:
      state[event] = new_state 
Example 22
Project: bayeslite   Author: probcomp   File: Lexicons.py    License: Apache License 2.0 5 votes vote down vote up
def parse_token_definition(self, token_spec):
    if type(token_spec) <> types.TupleType:
      raise Errors.InvalidToken("Token definition is not a tuple")
    if len(token_spec) <> 2:
      raise Errors.InvalidToken("Wrong number of items in token definition")
    pattern, action = token_spec
    if not isinstance(pattern, Regexps.RE):
      raise Errors.InvalidToken("Pattern is not an RE instance")
    return (pattern, action) 
Example 23
Project: meddle   Author: glmcdona   File: optparse.py    License: MIT License 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 24
Project: meddle   Author: glmcdona   File: optparse.py    License: MIT License 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 25
Project: bitmask-dev   Author: leapcode   File: test_imap.py    License: 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 26
Project: ironpython2   Author: IronLanguages   File: optparse.py    License: 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) 
Example 27
Project: ironpython2   Author: IronLanguages   File: optparse.py    License: Apache License 2.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 28
Project: ironpython2   Author: IronLanguages   File: symbols.py    License: Apache License 2.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 29
Project: faces   Author: skarlekar   File: _bsoup.py    License: GNU General Public License v2.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 30
Project: faces   Author: skarlekar   File: _bsoup.py    License: GNU General Public License v2.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