def main():
    keys = generate_array('key')
    values = generate_array('values')

    result = {key: value for key, value in zip_l(keys, values) if key}

    print(f'Keys:\n {keys}')
    print(f'Values:\n {values}')

    print(f'Result dictionary:\n {result}')
예제 #2
0
    def xml(self):

        c_ids = [
            cid or new_id()
            for _, cid in zip_l(self.connector_types, self.connector_ids or [])
        ]
        owners = self.owners or ([None] * len(c_ids))

        return xml_dict.xml_node(tag='packagedElement',
                                 attributes={
                                     XMI.type: self.type,
                                     XMI.id: self.id,
                                     'visibility': 'public'
                                 },
                                 children=list(
                                     flatmap(create_connector(self.id),
                                             zip(self.connector_types, c_ids),
                                             owners)))
예제 #3
0
def _save(im, fp, filename):
    """save an image to disk (called by the save method)"""
    encoderinfo = im.encoderinfo

    def rows(im):
        """Rows generator from image"""
        for i in range(im.size[1]):
            row = []
            for j in range(im.size[0]):
                px = im.getpixel((j, i))
                if hasattr(px, '__iter__'):
                    # Multi-channel image
                    row.extend(px)
                else:
                    # Single channel image
                    row.append(px)
            yield row

    # Default values
    meta = dict(im.info)
    if im.mode == 'P':
        meta['palette'], bits = get_palette(im)
    else:
        parsed_mode = png.parse_mode(im.mode, 8)
        (meta['greyscale'], meta['alpha'], bits) = parsed_mode
        if bits == 1:
            fullrows = rows

            def rows(im):
                """Wrapper rows to strictly bool value"""
                for row in fullrows(im):
                    yield [bool(it) for it in row]

    transparency = im.encoderinfo.get('transparency',
                                      im.info.get('transparency', None))
    if (transparency or transparency == 0):
        if im.mode == "P":
            # "Patch" palette with transparency
            if isinstance(transparency, bytes):
                transparency = bytearray(transparency)
            else:
                # integer is number of transparent colour
                transparency = max(0, min(255, transparency))
                transparency = bytearray((255, ) * transparency)
                transparency.append(0)

            # limit to actual palette size
            alpha_bytes = 2**bits
            palette = zip_l(meta['palette'],
                            transparency[:alpha_bytes],
                            fillvalue=255)
            meta['palette'] = list(map(lambda it: it[0] + (it[1], ), palette))
            transparency = None
        elif im.mode == "L":
            transparency = max(0, min(65535, transparency))
        elif im.mode == "RGB":
            # as max value per channel in RGB mode is 255
            # higher trasparency is a bug
            if max(transparency) > 255:
                im = im.convert('RGBA')
                meta['alpha'] = True
                transparency = None
            pass  # triade will pass to writer
        else:
            if "transparency" in encoderinfo:
                # don't bother with transparency if it's an RGBA
                # and it's in the info dict. It's probably just stale.
                raise IOError("cannot use transparency for this mode")

    if 'aspect' in im.info:
        meta['resolution'] = (meta.pop('aspect'), 0)
    if 'dpi' in im.info:
        meta['resolution'] = (meta.pop('dpi'), 'i')
    meta.pop('transparency', None)

    writer = png.Writer(size=im.size,
                        bitdepth=bits,
                        transparent=transparency,
                        compression=encoderinfo.get("compress_level", -1),
                        **meta)

    writer.write(fp, rows(im))

    #  TODO: pnginfo (?)

    try:
        fp.flush()
    except:
        pass
예제 #4
0
def _save(im, fp, filename):
    """save an image to disk (called by the save method)"""
    encoderinfo = im.encoderinfo

    def rows(im):
        """Rows generator from image"""
        for i in range(im.size[1]):
            row = []
            for j in range(im.size[0]):
                px = im.getpixel((j, i))
                if hasattr(px, '__iter__'):
                    # Multi-channel image
                    row.extend(px)
                else:
                    # Single channel image
                    row.append(px)
            yield row
    # Default values
    meta = dict(im.info)
    if im.mode == 'P':
        meta['palette'], bits = get_palette(im)
    else:
        parsed_mode = png.parse_mode(im.mode, 8)
        (meta['greyscale'], meta['alpha'], bits) = parsed_mode
        if bits == 1:
            fullrows = rows

            def rows(im):
                """Wrapper rows to strictly bool value"""
                for row in fullrows(im):
                    yield [bool(it) for it in row]

    transparency = im.encoderinfo.get('transparency',
                        im.info.get('transparency',
                            None))
    if (transparency or transparency == 0):
        if im.mode == "P":
            # "Patch" palette with transparency
            if isinstance(transparency, bytes):
                transparency = bytearray(transparency)
            else:  # not sure about this
                transparency = max(0, min(255, transparency))
                transparency = bytearray((255,) * transparency)

            # limit to actual palette size
            alpha_bytes = 2 ** bits
            palette = zip_l(meta['palette'],
                            transparency[:alpha_bytes],
                            fillvalue=255)
            meta['palette'] = list(map(lambda it: it[0] + (it[1],), palette))
            transparency = None
        elif im.mode == "L":
            transparency = max(0, min(65535, transparency))
        elif im.mode == "RGB":
            # as max value per channel in RGB mode is 255
            # higher trasparency is a bug
            if max(transparency) > 255:
                im = im.convert('RGBA')
                meta['alpha'] = True
                transparency = None
            pass  # triade will pass to writer
        else:
            if "transparency" in encoderinfo:
                # don't bother with transparency if it's an RGBA
                # and it's in the info dict. It's probably just stale.
                raise IOError("cannot use transparency for this mode")

    if 'aspect' in im.info:
        meta['resolution'] = (meta.pop('aspect'), 0)
    if 'dpi' in im.info:
        meta['resolution'] = (meta.pop('dpi'), 'i')
    meta.pop('transparency', None)

    writer = png.Writer(size=im.size,
                        bitdepth=bits,
                        transparent=transparency,
                        compression=encoderinfo.get("compress_level", -1),
                        **meta)

    writer.write(fp, rows(im))

    #  TODO: pnginfo (?)

    try:
        fp.flush()
    except:
        pass
예제 #5
0
def _save(im, fp, filename):
    # save an image to disk (called by the save method)
    encoderinfo = im.encoderinfo
    def rows(im):
        for i in range(im.size[1]):
            row = []
            for j in range(im.size[0]):
                px = im.getpixel((j, i))
                if hasattr(px, '__iter__'):
                    #Multi-channel image
                    row.extend(px)
                else:
                    #Single channel image
                    row.append(px)
            yield row
    # Default values
    meta = dict(im.info)
    bits = 8
    if im.mode == 'L':
        meta['greyscale'] = True
    if im.mode == 'I':
        meta['greyscale'] = True
        bits = 16
    elif im.mode == 'LA':
        meta['greyscale'] = True
        meta['alpha'] = True
    elif im.mode == 'RGBA':
        meta['alpha'] = True
    elif im.mode == 'L;4':
        meta['greyscale'] = True
        bits = 4
    elif im.mode == 'L;2':
        meta['greyscale'] = True
        bits = 2
    elif im.mode == 'L;1':
        meta['greyscale'] = True
        bits = 1
    elif im.mode == '1':
        meta['greyscale'] = True
        bits = 1
        fullrows = rows

        def rows(im):
            for row in fullrows(im):
                yield [bool(it) for it in row]

    if im.mode == "P":
        palette_bytes = im.palette.getdata()[1]
        # attempt to minimize storage requirements for palette images
        if "bits" in encoderinfo:
            # number of bits specified by user
            colors = 1 << encoderinfo["bits"]
        else:
            # check palette contents
            if im.palette:
                # For now palette only RGB
                colors = max(min(len(palette_bytes) // 3, 256), 2)
            else:
                colors = 256

        if colors <= 2:
            bits = 1
        elif colors <= 4:
            bits = 2
        elif colors <= 16:
            bits = 4
        else:
            bits = 8

        # For now palette only RGB
        palette_byte_number = (2 ** bits) * 3
        # Match to declared palette size
        palette_bytes = bytearray(palette_bytes[:palette_byte_number])
        if len(palette_bytes) < palette_byte_number:
            palette_bytes.extend((0,) * \
                                 (palette_byte_number - len(palette_bytes)))
        meta['palette'] = group(palette_bytes, 3)

    transparency = encoderinfo.get('transparency',
                        im.info.get('transparency',
                            None))
    if (transparency or transparency == 0):
        if im.mode == "P":
            # "Patch" palette with transparency
            if isinstance(transparency, bytes):
                transparency = bytearray(transparency)
            else:  # not sure about this
                transparency = max(0, min(255, transparency))
                transparency = bytearray((255,) * transparency)

            # limit to actual palette size
            alpha_bytes = 2 ** bits
            palette = zip_l(meta['palette'],
                            transparency[:alpha_bytes],
                            fillvalue=255)
            meta['palette'] = list(map(lambda it: it[0] + (it[1],), palette))
            transparency = None
        elif im.mode == "L":
            transparency = max(0, min(65535, transparency))
        elif im.mode == "RGB":
            # as max value per channel in RGB mode is 255
            # higher trasparency is a bug
            if max(transparency) > 255:
                im = im.convert('RGBA')
                meta['alpha'] = True
                transparency = None
            pass  # triade will pass to writer
        else:
            if "transparency" in encoderinfo:
                # don't bother with transparency if it's an RGBA
                # and it's in the info dict. It's probably just stale.
                raise IOError("cannot use transparency for this mode")

    if 'aspect' in im.info:
        meta['phy'] = (meta.pop('aspect'), 0)
    if 'dpi' in im.info:
        meta['phy'] = (meta.pop('dpi'), 'i')
    meta.pop('transparency', None)

    writer = png.Writer(size=im.size,
                        bitdepth=bits,
                        transparent=transparency,
                        compression=encoderinfo.get("compress_level", -1),
                        **meta)

    writer.write(fp, rows(im))

    #  TODO: pnginfo (?)

    try:
        fp.flush()
    except:
        pass