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: 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 #2
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 #3
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 #4
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 #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: spatial_transforms.py    From PyTorchConv3D 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: functional.py    From opencv_transforms with MIT License 5 votes vote down vote up
def resize(img, size, interpolation=cv2.INTER_LINEAR):
    r"""Resize the input numpy ndarray to the given size.
    Args:
        img (numpy ndarray): Image to be resized.
        size (sequence or int): Desired output size. If size is a sequence like
            (h, w), the output size will be matched to this. If size is an int,
            the smaller edge of the image will be matched to this number maintaing
            the aspect ratio. i.e, if height > width, then image will be rescaled to
            :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`
        interpolation (int, optional): Desired interpolation. Default is
            ``cv2.INTER_CUBIC``
    Returns:
        PIL Image: Resized image.
    """
    if not _is_numpy_image(img):
        raise TypeError('img should be numpy 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))
    w, h, =  size

    if isinstance(size, int):
        if (w <= h and w == size) or (h <= w and h == size):
            return img
        if w < h:
            ow = size
            oh = int(size * h / w)
            output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)
        else:
            oh = size
            ow = int(size * w / h)
            output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)
    else:
        output = cv2.resize(img, dsize=(size[1], size[0]), interpolation=interpolation)
    if img.shape[2]==1:
        return output[:, :, np.newaxis]
    else:
        return output 
Example #19
Source File: transforms.py    From opencv_transforms with MIT License 5 votes vote down vote up
def __init__(self, size, interpolation=cv2.INTER_LINEAR):
        # assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
        if isinstance(size, int):
            self.size = (size,size)
        elif isinstance(size, collections.Iterable) and len(size) == 2:
            if type(size) == list:
                size = tuple(size)
            self.size = size
        else:
            raise ValueError('Unknown inputs for size: {}'.format(size))
        self.interpolation = interpolation 
Example #20
Source File: api.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            for sub in flatten(el):
                yield sub
        else:
            yield el 
Example #21
Source File: graph.py    From link-prediction_with_deep-learning with MIT License 5 votes vote down vote up
def degree(self, nodes=None):
    if isinstance(nodes, Iterable):
      return {v:len(self[v]) for v in nodes}
    else:
      return len(self[nodes]) 
Example #22
Source File: graph.py    From link-prediction_with_deep-learning with MIT License 5 votes vote down vote up
def degree(self, nodes=None):
    if isinstance(nodes, Iterable):
      return {v:len(self[v]) for v in nodes}
    else:
      return len(self[nodes]) 
Example #23
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 #24
Source File: dataoperation.py    From honeybee with GNU General Public License v3.0 5 votes vote down vote up
def flatten(input_list):
    """Return a flattened genertor from an input list.

    Usage:

        input_list = [['a'], ['b', 'c', 'd'], [['e']], ['f']]
        list(flatten(input_list))
        >> ['a', 'b', 'c', 'd', 'e', 'f']
    """
    for el in input_list:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el 
Example #25
Source File: image_utils.py    From Fast_Seg with Apache License 2.0 5 votes vote down vote up
def get_2dshape(shape, *, zero=True):
    if not isinstance(shape, collections.Iterable):
        shape = int(shape)
        shape = (shape, shape)
    else:
        h, w = map(int, shape)
        shape = (h, w)
    if zero:
        minv = 0
    else:
        minv = 1

    assert min(shape) >= minv, 'invalid shape: {}'.format(shape)
    return shape 
Example #26
Source File: augmentation.py    From DPC with MIT License 5 votes vote down vote up
def __init__(self, size, interpolation=Image.NEAREST):
        assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
        self.size = size
        self.interpolation = interpolation 
Example #27
Source File: config.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _inner_type_schema(inner_type):
  ret = []
  def _flatten(typ):
    if isinstance(typ, collections.Iterable):
      for subtyp in typ:
        _flatten(subtyp)
    else:
      ret.append(_SIMPLE_TYPE_LOOKUP[typ])
  _flatten(inner_type)
  return sorted(set(ret)) 
Example #28
Source File: runner.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _re_encode(obj):
  """Ensure consistent encoding for common python data structures."""
  if isinstance(obj, (unicode, str)):
    if isinstance(obj, str):
      obj = obj.decode('utf-8', 'replace')
    return obj.encode('utf-8', 'replace')
  elif isinstance(obj, collections.Mapping):
    return {_re_encode(k): _re_encode(v) for k, v in obj.iteritems()}
  elif isinstance(obj, collections.Iterable):
    return [_re_encode(i) for i in obj]
  else:
    return obj 
Example #29
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 #30
Source File: utils.py    From pybotgram with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_sudo(msg):
    return isinstance(settings.SUDO_USERS, collections.Iterable) and msg.src.id in settings.SUDO_USERS