Python collections.Iterable() Examples

The following are 30 code examples of collections.Iterable(). 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 also want to check out all available functions/classes of the module collections , or try the search function .
Example #1
Source File: configparserwrapper.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
def validate_sections(self, list_sections):
        """
            Validate a list of section names for availability.

            @param list_sections: list of section names
            @type list_sections: list of str

            @return: None if all valid, otherwise list of invalid sections
            @rtype: None | list[str]
        """
        assert isinstance(list_sections, Iterable), "Invalid, not a list: '{}'".format(list_sections)
        invalid_sections = []
        for section in list_sections:
            if not self._config.has_section(section):
                invalid_sections.append(section)
        if len(invalid_sections) > 0:
            return invalid_sections
        return None 
Example #2
Source File: main.py    From twitterscraper with MIT License 6 votes vote down vote up
def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        elif isinstance(obj, collections.Iterable):
            return list(obj)
        elif isinstance(obj, dt.datetime):
            return obj.isoformat()
        elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
            return dict(obj)
        elif hasattr(obj, '__dict__'):
            return {member: getattr(obj, member)
                    for member in dir(obj)
                    if not member.startswith('_') and
                    not hasattr(getattr(obj, member), '__call__')}

        return json.JSONEncoder.default(self, obj) 
Example #3
Source File: utils.py    From ICDAR-2019-SROIE with MIT License 6 votes vote down vote up
def encode(self, text):
        """Support batch or single str.

        Args:
            text (str or list of str): texts to convert.

        Returns:
            torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
            torch.IntTensor [n]: length of each text.
        """
        if isinstance(text, str):
            text = [
                self.dict[char.lower() if self._ignore_case else char]
                for char in text
            ]
            length = [len(text)]
        elif isinstance(text, collections.Iterable):
            length = [len(s) for s in text]
            text = ''.join(text)
            text, _ = self.encode(text)
        return (torch.IntTensor(text), torch.IntTensor(length)) 
Example #4
Source File: nyu_transform.py    From Visualizing-CNNs-for-monocular-depth-estimation with MIT License 6 votes vote down vote up
def changeScale(self, img, size, interpolation=Image.BILINEAR):

        if not _is_pil_image(img):
            raise TypeError(
                'img should be PIL Image. Got {}'.format(type(img)))
        if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):
            raise TypeError('Got inappropriate size arg: {}'.format(size))

        if isinstance(size, int):
            w, h = img.size
            if (w <= h and w == size) or (h <= w and h == size):
                return img
            if w < h:
                ow = size
                oh = int(size * h / w)
                return img.resize((ow, oh), interpolation)
            else:
                oh = size
                ow = int(size * w / h)
                return img.resize((ow, oh), interpolation)
        else:
            return img.resize(size[::-1], interpolation) 
Example #5
Source File: ext.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def split_by(source, target, separator=None):
    """Split the source to multiple values by the separator"""
    try:
        if not source:
            return []
        elif isinstance(source, six.string_types) and separator:
            values = source.split(separator)
            return [{target: value.strip()} for value in values]
        elif isinstance(source, six.string_types):
            return [{target: source}]
        elif isinstance(source, Iterable):
            return [{target: value} for value in source]
        else:
            return [{target: source}]
    except Exception as ex:
        _logger.warning("split_by method encountered exception "
                        "source=%s message=%s cause=%s", source, ex,
                        traceback.format_exc())
        return [] 
Example #6
Source File: compound.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, model_spec, **kwargs):

        if isinstance(model_spec, (ModelMeta, string_type)):
            self.model_classes = (model_spec,)
            allow_subclasses = True
        elif isinstance(model_spec, Iterable):
            self.model_classes = tuple(model_spec)
            allow_subclasses = False
        else:
            raise Exception("The first argument to PolyModelType.__init__() "
                            "must be a model or an iterable.")

        self.claim_function = kwargs.pop("claim_function", None)
        self.allow_subclasses = kwargs.pop("allow_subclasses", allow_subclasses)

        CompoundType.__init__(self, **kwargs) 
Example #7
Source File: ext.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def split_by(source, target, separator=None):
    """Split the source to multiple values by the separator"""
    try:
        if not source:
            return []
        elif isinstance(source, six.string_types) and separator:
            values = source.split(separator)
            return [{target: value.strip()} for value in values]
        elif isinstance(source, six.string_types):
            return [{target: source}]
        elif isinstance(source, Iterable):
            return [{target: value} for value in source]
        else:
            return [{target: source}]
    except Exception as ex:
        _logger.warning("split_by method encountered exception "
                        "source=%s message=%s cause=%s", source, ex,
                        traceback.format_exc())
        return [] 
Example #8
Source File: dataoperation.py    From honeybee with GNU General Public License v3.0 6 votes vote down vote up
def flatten_tuple_list(input_list):
    """Return a flattened generator from an input list of (x, y, z) tuples.

    Usage:
        input_list = [[(0, 0, 0)], [(10, 0, 0), (10, 10, 0)]]
        print(list(flattenPointList(input_list)))

        >> [(0, 0, 0), (10, 0, 0), (10, 10, 0)]
    """
    for el in input_list:
        if isinstance(el, collections.Iterable) \
            and not isinstance(el, basestring) \
                and (isinstance(el[0], collections.Iterable) or hasattr(el[0], 'X')):
            for sub in flatten_tuple_list(el):
                yield sub
        else:
            yield el 
Example #9
Source File: datatype.py    From honeybee with GNU General Public License v3.0 6 votes vote down vote up
def to_rad_string(self):
        """Return formatted value for Radiance based on the type of descriptor."""
        if self._value is None:
            return ""

        try:
            if not isinstance(self._value, basestring) \
                    and isinstance(self._value, Iterable):
                # tuple
                return "-%s %s" % (self._name, " ".join(map(str, self._value)))
            else:
                if self._is_joined:
                    # joined strings such as -of
                    return "-%s%s" % (self._name, str(self._value))
                else:
                    # numbers
                    return "-%s %s" % (self._name, str(self._value))

        except TypeError:
            raise ValueError("Failed to set the value to {}".format(self._value)) 
Example #10
Source File: _utils.py    From python-zhmcclient with Apache License 2.0 6 votes vote down vote up
def repr_list(_list, indent):
    """Return a debug representation of a list or tuple."""
    # pprint represents lists and tuples in one row if possible. We want one
    # per row, so we iterate ourselves.
    if _list is None:
        return 'None'
    if isinstance(_list, MutableSequence):
        bm = '['
        em = ']'
    elif isinstance(_list, Iterable):
        bm = '('
        em = ')'
    else:
        raise TypeError("Object must be an iterable, but is a %s" %
                        type(_list))
    ret = bm + '\n'
    for value in _list:
        ret += _indent('%r,\n' % value, 2)
    ret += em
    ret = repr_text(ret, indent=indent)
    return ret.lstrip(' ') 
Example #11
Source File: _bashcomplete.py    From recruit with Apache License 2.0 6 votes vote down vote up
def is_incomplete_argument(current_params, cmd_param):
    """
    :param current_params: the current params and values for this argument as already entered
    :param cmd_param: the current command parameter
    :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In
    other words whether or not the this cmd_param argument can still accept values
    """
    if not isinstance(cmd_param, Argument):
        return False
    current_param_values = current_params[cmd_param.name]
    if current_param_values is None:
        return True
    if cmd_param.nargs == -1:
        return True
    if isinstance(current_param_values, abc.Iterable) \
            and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:
        return True
    return False 
Example #12
Source File: users_id_token.py    From endpoints-python with Apache License 2.0 6 votes vote down vote up
def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
  """
  We frequently require passed objects to support iteration or
  containment expressions, but not be strings. (Of course, strings
  support iteration and containment, but not usefully.)  If the passed
  object is a string, we'll wrap it in a tuple and return it. If it's
  already an iterable, we'll return it as-is. Otherwise, we'll raise a
  TypeError.
  """
  required_type = (_Iterable,) if iterable_only else (_Container, _Iterable)
  required_type_name = ' or '.join(t.__name__ for t in required_type)

  if not isinstance(obj, required_type):
    raise ValueError('{} must be of type {}'.format(name, required_type_name))
  # at this point it is definitely the right type, but might be a string
  if isinstance(obj, basestring):
    if log_warning:
      _logger.warning('{} passed as a string; should be list-like'.format(name))
    return (obj,)
  return obj 
Example #13
Source File: catalog.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, mapping=None):
        """Initialize a Catalog Builder.

        Args:
            mapping: An optional mapping (such as a dictionary) of items, or an
                iterable series of 2-tuples containing keys and values.

        Raises:
            TypeError: If mapping is not None and is neither of mapping nor iterable type.
            ValueError: If mapping is an iterable of tuples, and the tuples are not pairs.
        """
        if mapping is None:
            self._catalog = []
        elif isinstance(mapping, Mapping):
            self._catalog = list(mapping.items())
        elif isinstance(mapping, Iterable):
            self._catalog = []
            for pair in mapping:
                if len(pair) != 2:
                    raise ValueError("{!r} is not a pair. Catalogs can only be constructed "
                                     "from iterable series of 2-tuples.")
                self._catalog.append(pair)
        else:
            raise TypeError("Mapping must be either a mapping (e.g. dict), or an iterable "
                            "series of 2-tuples. {!r} does not qualify.") 
Example #14
Source File: video_transforms.py    From DDPAE-video-prediction with MIT License 5 votes vote down vote up
def __init__(self, size, interpolation='bilinear'):
    assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
    self.size = size
    self.interpolation = interpolation 
Example #15
Source File: configparserwrapper.py    From CAMISIM with Apache License 2.0 5 votes vote down vote up
def log_invalid_sections(self, list_sections):
        """
            print out a list of invalid section names to log.

            @param list_sections: list of section names
            @type list_sections: list[str]

            @return: None
            @rtype: None
        """
        assert isinstance(list_sections, Iterable), "Invalid, not a list: '{}'".format(list_sections)
        for section in list_sections:
            self._logger.warning("Invalid section '{}'".format(section)) 
Example #16
Source File: utils.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def __init__(self, size, interpolation=Image.BILINEAR):
        assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
        self.size = size
        self.interpolation = interpolation 
Example #17
Source File: placement_sampler.py    From robosuite with MIT License 5 votes vote down vote up
def sample_quat(self):
        if self.z_rotation is None:
            rot_angle = np.random.uniform(high=2 * np.pi, low=0)
        elif isinstance(self.z_rotation, collections.Iterable):
            rot_angle = np.random.uniform(
                high=max(self.z_rotation), low=min(self.z_rotation)
            )
        else:
            rot_angle = self.z_rotation

        return [np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)] 
Example #18
Source File: transforms.py    From ACAN with MIT License 5 votes vote down vote up
def __init__(self, size, interpolation='nearest'):
        assert isinstance(size, int) or isinstance(size, float) or \
               (isinstance(size, collections.Iterable) and len(size) == 2)
        self.size = size
        self.interpolation = interpolation 
Example #19
Source File: data.py    From DeepLung with GNU General Public License v3.0 5 votes vote down vote up
def collate(batch):
    if torch.is_tensor(batch[0]):
        return [b.unsqueeze(0) for b in batch]
    elif isinstance(batch[0], np.ndarray):
        return batch
    elif isinstance(batch[0], int):
        return torch.LongTensor(batch)
    elif isinstance(batch[0], collections.Iterable):
        transposed = zip(*batch)
        return [collate(samples) for samples in transposed] 
Example #20
Source File: transforms.py    From DeepLung with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, size, interpolation=Image.BILINEAR):
        # assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 3)
        self.size = size
        self.interpolation = interpolation 
Example #21
Source File: transforms.py    From DeepLung with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, size, interpolation=Image.BILINEAR):
        assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 3)
        self.size = size
        self.interpolation = interpolation 
Example #22
Source File: bn.py    From pytorch-segmentation-toolbox with MIT License 5 votes vote down vote up
def _pair(x):
    if isinstance(x, Iterable):
        return x
    return tuple(repeat(x, 2)) 
Example #23
Source File: graph_canvas.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def flatten(l):
    try:
        bs = basestring
    except NameError:
        # Py3k
        bs = str
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, bs):
            for sub in flatten(el):
                yield sub
        else:
            yield el 
Example #24
Source File: newstr.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def startswith(self, prefix, *args):
        if isinstance(prefix, Iterable):
            for thing in prefix:
                if isnewbytes(thing):
                    raise TypeError(self.no_convert_msg.format(type(thing)))
        return super(newstr, self).startswith(prefix, *args) 
Example #25
Source File: newstr.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def endswith(self, prefix, *args):
        # Note we need the decorator above as well as the isnewbytes()
        # check because prefix can be either a bytes object or e.g. a
        # tuple of possible prefixes. (If it's a bytes object, each item
        # in it is an int.)
        if isinstance(prefix, Iterable):
            for thing in prefix:
                if isnewbytes(thing):
                    raise TypeError(self.no_convert_msg.format(type(thing)))
        return super(newstr, self).endswith(prefix, *args) 
Example #26
Source File: newint.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def from_bytes(cls, mybytes, byteorder='big', signed=False):
        """
        Return the integer represented by the given array of bytes.

        The mybytes argument must either support the buffer protocol or be an
        iterable object producing bytes.  Bytes and bytearray are examples of
        built-in objects that support the buffer protocol.

        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.

        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        if byteorder not in ('little', 'big'):
            raise ValueError("byteorder must be either 'little' or 'big'")
        if isinstance(mybytes, unicode):
            raise TypeError("cannot convert unicode objects to bytes")
        # mybytes can also be passed as a sequence of integers on Py3.
        # Test for this:
        elif isinstance(mybytes, collections.Iterable):
            mybytes = newbytes(mybytes)
        b = mybytes if byteorder == 'big' else mybytes[::-1]
        if len(b) == 0:
            b = b'\x00'
        # The encode() method has been disabled by newbytes, but Py2's
        # str has it:
        num = int(native(b).encode('hex'), 16)
        if signed and (b[0] & 0x80):
            num = num - (2 ** (len(b)*8))
        return cls(num)


# def _twos_comp(val, bits):
#     """compute the 2's compliment of int value val"""
#     if( (val&(1<<(bits-1))) != 0 ):
#         val = val - (1<<bits)
#     return val 
Example #27
Source File: auth.py    From uplink with MIT License 5 votes vote down vote up
def get_auth(auth_object=None):
    if auth_object is None:
        return utils.no_op
    elif isinstance(auth_object, collections.Iterable):
        return BasicAuth(*auth_object)
    elif callable(auth_object):
        return auth_object
    else:
        raise ValueError("Invalid authentication strategy: %s" % auth_object) 
Example #28
Source File: recurrent.py    From chainerrl with MIT License 5 votes vote down vote up
def unchain_backward(state):
    """Call Variable.unchain_backward recursively."""
    if isinstance(state, collections.Iterable):
        for s in state:
            unchain_backward(s)
    elif isinstance(state, chainer.Variable):
        state.unchain_backward() 
Example #29
Source File: types.py    From recordlinkage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _iterable_not_string(x):
    return (isinstance(x, collections.Iterable) and
            not isinstance(x, str)) 
Example #30
Source File: core.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def flatten(l):
    """
    Flattens an irregualr list.
    From https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists
    """
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el