Deep-Software-Analytics/SweSetupBench-lite huggingface dataset:
Repository: python-pillow/Pillow

Problem statement:
unintuitive save properties
> **progressive**
> If present, indicates that this image should be stored as a progressive JPEG file.

It is not completely obvious that `progressive = False` evaluates to it being set. I guess it's difficult to change this whilst keeping backwards compatibility. (I doubt someone passes `progressive = False` with the intention to enable it.)



Hints:

Patch:
diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py
--- a/PIL/JpegImagePlugin.py
+++ b/PIL/JpegImagePlugin.py
@@ -682,13 +682,16 @@ def validate_qtables(qtables):
                       o8(len(markers)) + marker)
             i += 1
 
+    # "progressive" is the official name, but older documentation
+    # says "progression"
+    # FIXME: issue a warning if the wrong form is used (post-1.1.7)
+    progressive = info.get("progressive", False) or\
+                  info.get("progression", False)
+
     # get keyword arguments
     im.encoderconfig = (
         quality,
-        # "progressive" is the official name, but older documentation
-        # says "progression"
-        # FIXME: issue a warning if the wrong form is used (post-1.1.7)
-        "progressive" in info or "progression" in info,
+        progressive,
         info.get("smooth", 0),
         "optimize" in info,
         info.get("streamtype", 0),
@@ -704,7 +707,7 @@ def validate_qtables(qtables):
     # channels*size, this is a value that's been used in a django patch.
     # https://github.com/matthewwithanm/django-imagekit/issues/50
     bufsize = 0
-    if "optimize" in info or "progressive" in info or "progression" in info:
+    if "optimize" in info or progressive:
         # keep sets quality to 0, but the actual value may be high.
         if quality >= 95 or quality == 0:
             bufsize = 2 * im.size[0] * im.size[1]


Test patch:
diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py
--- a/Tests/test_file_jpeg.py
+++ b/Tests/test_file_jpeg.py
@@ -227,12 +227,20 @@ def test_exif_gps_typeerror(self):
 
     def test_progressive_compat(self):
         im1 = self.roundtrip(hopper())
+        self.assertFalse(im1.info.get("progressive"))
+        self.assertFalse(im1.info.get("progression"))
+
+        im2 = self.roundtrip(hopper(), progressive=0)
+        im3 = self.roundtrip(hopper(), progression=0)  # compatibility
+        self.assertFalse(im2.info.get("progressive"))
+        self.assertFalse(im2.info.get("progression"))
+        self.assertFalse(im3.info.get("progressive"))
+        self.assertFalse(im3.info.get("progression"))
+
         im2 = self.roundtrip(hopper(), progressive=1)
         im3 = self.roundtrip(hopper(), progression=1)  # compatibility
         self.assert_image_equal(im1, im2)
         self.assert_image_equal(im1, im3)
-        self.assertFalse(im1.info.get("progressive"))
-        self.assertFalse(im1.info.get("progression"))
         self.assertTrue(im2.info.get("progressive"))
         self.assertTrue(im2.info.get("progression"))
         self.assertTrue(im3.info.get("progressive"))
Repository: python-pillow/Pillow

Problem statement:
Repeated looping over image stack shows last frame in place of first frame
When looping through the frames in an animation or TIFF stack with `ImageSequence.Iterator`, the frame pointer is not reset for the first frame. Consequently, if the loop is run through a second time the final frame is shown again instead of the first frame.
### Demo

Code

``` python
from PIL import Image, ImageSequence
import os
# Make a test image
os.system((
    "convert -depth 8 -size 1x1 xc:'rgb(100,100,100)' xc:'rgb(121,121,121)'"
    " xc:'rgb(142,142,142)' xc:'rgb(163,163,163)' image.tif"
))
# Open the image
im = Image.open('image.tif')
# Run through the image
print('First run')
for frame in ImageSequence.Iterator(im):
    print(list(frame.getdata()))
# Run through the image again
print('Second run')
for frame in ImageSequence.Iterator(im):
    print(list(frame.getdata()))
```

Output

```
First run
[100]
[121]
[142]
[163]
Second run
[163]
[121]
[142]
[163]
```



Hints:
Sounds fair enough to me. I've created a PR for review.


Patch:
diff --git a/PIL/ImageSequence.py b/PIL/ImageSequence.py
--- a/PIL/ImageSequence.py
+++ b/PIL/ImageSequence.py
@@ -35,8 +35,7 @@ def __init__(self, im):
 
     def __getitem__(self, ix):
         try:
-            if ix:
-                self.im.seek(ix)
+            self.im.seek(ix)
             return self.im
         except EOFError:
             raise IndexError  # end of sequence


Test patch:
diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py
--- a/Tests/test_imagesequence.py
+++ b/Tests/test_imagesequence.py
@@ -44,6 +44,17 @@ def test_libtiff(self):
         self._test_multipage_tiff()
         TiffImagePlugin.READ_LIBTIFF = False
 
+    def test_consecutive(self):
+        im = Image.open('Tests/images/multipage.tiff')
+        firstFrame = None
+        for frame in ImageSequence.Iterator(im):
+            if firstFrame == None:
+                firstFrame = frame.copy()
+            pass
+        for frame in ImageSequence.Iterator(im):
+            self.assert_image_equal(frame, firstFrame)
+            break
+
 if __name__ == '__main__':
     unittest.main()
Repository: python-pillow/Pillow

Problem statement:
TIFF tags removed when using libtiff
My specific utilization of Pillow requires that I generate a TIFF image with  G4 compression and provide at least the following tags; 256, 257, 259, 262, 273, 274, 278, 279, 282, and 283.

The following line in TiffImagePlugin.py specifies a list of tags to exclude from the file when using libtiff:
https://github.com/python-pillow/Pillow/blob/master/PIL/TiffImagePlugin.py#L1281

I cannot find any justification for this other than the comment on line 1280, "ICC Profile crashes."
Is it impossible to create a TIFF file using G4 compression with Pillow that contains the ROWSPERSTRIP (278) TIFF tag?



Hints:
I took the liberty of removing "ROWSPERSTRIP" from the blocklist collection on my local environment and it appears to behave as expected, error free. Any additional information would be greatly appreciated.

IIRC, libtiff was supposed to be adding those tags based on how the library was doing the encoding. 

ICCprofile was crashing, probably due to some questionable handling of the attributes.


Patch:
diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py
--- a/PIL/TiffImagePlugin.py
+++ b/PIL/TiffImagePlugin.py
@@ -1277,8 +1277,10 @@ def _save(im, fp, filename):
             except io.UnsupportedOperation:
                 pass
 
-        # ICC Profile crashes.
-        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS, ROWSPERSTRIP, ICCPROFILE]
+        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
+        # based on the data in the strip.
+        # ICCPROFILE crashes.
+        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS, ICCPROFILE]
         atts = {}
         # bits per sample is a single short in the tiff directory, not a list.
         atts[BITSPERSAMPLE] = bits[0]


Test patch:
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -165,6 +165,13 @@ def test_write_metadata(self):
                         self.assertEqual(
                             val, value, msg="%s didn't roundtrip" % tag)
 
+            # https://github.com/python-pillow/Pillow/issues/1561
+            requested_fields = ['StripByteCounts',
+                                'RowsPerStrip',
+                                'StripOffsets']
+            for field in requested_fields:
+                self.assertTrue(field in reloaded, "%s not in metadata" %field)
+
     def test_g3_compression(self):
         i = Image.open('Tests/images/hopper_g4_500.tif')
         out = self.tempfile("temp.tif")
Repository: python-pillow/Pillow

Problem statement:
Not able to open tiff-file with Pillow (regression)
We encountered a tiff-file that Pillow failed to open in version 3.0.0, in version 2.9.0 it works just fine.

https://drive.google.com/a/greyrook.com/file/d/0Bypf_GpBFGxZU3A1QmsxQlRXVXc/view

on `Image.open(path)`: `IOError: cannot identify image file`



Hints:
I've encountered the same problem on OS X and Ubuntu 14.04 LTS.

It looks like the wheels distributed on PyPI were compiled on a machine without libtiff – if I install from source (`pip install --no-binary=all --no-use-wheel Pillow==3`) it works as expected.

@acdha Which platform is missing tiff in the distributed files?

@wiredfool OS X and Linux 64-bit

We don't distribute binaries for Linux, so I'm not sure where that comes from.  The OS X wheels are built on Travis, and they pass the libtiff tests: https://travis-ci.org/python-pillow/pillow-wheels/jobs/88293220.

Hmmm, that's really quite odd – on both platforms, 2.9.0 installs without a
hitch with no special handling but 3.0.0 only works from source, not the
wheel. I'll look into it more on Monday.

Chris
On Fri, Nov 13, 2015 at 2:00 PM wiredfool notifications@github.com wrote:

> We don't distribute binaries for Linux, so I'm not sure where that comes
> from. The OS X wheels are built on Travis, and they pass the libtiff tests:
> https://travis-ci.org/python-pillow/pillow-wheels/jobs/88293220.
> 
> —
> Reply to this email directly or view it on GitHub
> https://github.com/python-pillow/Pillow/issues/1526#issuecomment-156525316
> .


Patch:
diff --git a/PIL/TiffTags.py b/PIL/TiffTags.py
--- a/PIL/TiffTags.py
+++ b/PIL/TiffTags.py
@@ -133,7 +133,7 @@ def cvt_enum(self, value):
 
     # FIXME add more tags here
     34665: ("ExifIFD", 3, 1),
-    34675: ('ICCProfile', 7, 1),
+    34675: ('ICCProfile', 7, 0),
 
     # MPInfo
     45056: ("MPFVersion", 7, 1),


Test patch:
diff --git a/Tests/images/hopper.iccprofile_binary.tif b/Tests/images/hopper.iccprofile_binary.tif
new file mode 100644
Binary files /dev/null and b/Tests/images/hopper.iccprofile_binary.tif differ
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -158,6 +158,14 @@ def test_iccprofile(self):
         self.assert_(type(im.info['icc_profile']) is not type(tuple))
         self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile'])
 
+    def test_iccprofile_binary(self):
+        # https://github.com/python-pillow/Pillow/issues/1526
+        # We should be able to load this, but probably won't be able to save it.
+
+        im = Image.open('Tests/images/hopper.iccprofile_binary.tif')
+        self.assertEqual(im.tag_v2.tagtype[34675], 1)
+        self.assert_(im.info['icc_profile'])
+
 
 
 if __name__ == '__main__':
Repository: python-pillow/Pillow

Problem statement:
Three "images" that cause PIL.Image.open() to hang
Hello,

Here's what I found with my early afl-fuzz fuzzing:

```
(virtualenv)[1/6][14:45:24][~/workspace/Pillow/pillow-virtualenv/o/hangs]$ for file in *; do hexdump -C $file; done
00000000  50 36                                             |P6|
00000002
00000000  50 35                                             |P5|
00000002
00000000  50 79 50                                          |PyP|
00000003
```



Hints:
Hi. Thanks for reporting, but unfortunately I don't quite follow. Would you be able to post some Python code that reproduces the problem?


Patch:
diff --git a/PIL/PpmImagePlugin.py b/PIL/PpmImagePlugin.py
--- a/PIL/PpmImagePlugin.py
+++ b/PIL/PpmImagePlugin.py
@@ -93,6 +93,8 @@ def _open(self):
                     s = self.fp.read(1)
                     if s not in b_whitespace:
                         break
+                    if s == b"":
+                        raise ValueError("File does not extend beyond magic number")
                 if s != b"#":
                     break
                 s = self.fp.readline()


Test patch:
diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py
--- a/Tests/test_file_ppm.py
+++ b/Tests/test_file_ppm.py
@@ -35,6 +35,14 @@ def test_16bit_pgm_write(self):
         reloaded = Image.open(f)
         self.assert_image_equal(im, reloaded)
 
+    def test_truncated_file(self):
+        path = self.tempfile('temp.pgm')
+        f = open(path, 'w')
+        f.write('P6')
+        f.close()
+
+        self.assertRaises(ValueError, lambda: Image.open(path))
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: python-pillow/Pillow

Problem statement:
load ico file with ImageFile will raise an exception
> Traceback (most recent call last):
>   File "t.py", line 12, in <module>
>     p.feed(data)
>   File "/.../lib/python2.7/site-packages/PIL/ImageFile.py", line 383, in feed
>     if flag or len(im.tile) != 1:
> TypeError: object of type 'NoneType' has no len()

```
from PIL import ImageFile
data = open('favicon.ico', 'rb').read()
p = ImageFile.Parser()
p.feed(data)
```

I found when excute `im = im.convert('RGBA')` in function frame() of IcoImagePlugin.py file, im.tile will lose and turn to NoneType. 



Hints:
Does it work if you just read the file directly?

```
from PIL import Image
im = Image.open('favicon.ico')
im = im.convert('RGBA')
```

The parser class isn't always quite as robust as just simply opening and reading the file. 

It works, but im.tile is still None. So in `feed` function when checking condition `len(im.tile) != 1`, the exception will also raise. I guess it is better to set im.tile's value an empty list instead of None.

Can you post the .ico file so I can take a look?

github editor can't support ico file, so i give a link the ico file i use.
http://www.python.org/favicon.ico

Works for me:

```
(vpy27)erics:~/Pillow/Images$ python
Python 2.7.5+ (default, Sep 19 2013, 13:49:51) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> im = Image.open('python.ico')
>>> im.load()
>>> im.size
(48, 48)
>>> im.convert('RGBA')
<PIL.Image.Image image mode=RGBA size=48x48 at 0x955550C>
>>> 
```

What Pillow are you running? 

[[edit]]  I see, you're still running the ImageFile.Parser class. Is there a reason that you're doing that instead of just opening directly?


Patch:
diff --git a/PIL/IcoImagePlugin.py b/PIL/IcoImagePlugin.py
--- a/PIL/IcoImagePlugin.py
+++ b/PIL/IcoImagePlugin.py
@@ -222,6 +222,10 @@ def load(self):
         self.mode = im.mode
         self.size = im.size
 
+
+    def load_seek(self):
+        # Flage the ImageFile.Parser so that it just does all the decode at the end.
+        pass
 #
 # --------------------------------------------------------------------
 


Test patch:
diff --git a/Tests/images/python.ico b/Tests/images/python.ico
new file mode 100644
Binary files /dev/null and b/Tests/images/python.ico differ
diff --git a/Tests/test_imagefile.py b/Tests/test_imagefile.py
--- a/Tests/test_imagefile.py
+++ b/Tests/test_imagefile.py
@@ -57,6 +57,13 @@ def roundtrip(format):
     # https://github.com/python-imaging/Pillow/issues/78
     #assert_exception(IOError, lambda: roundtrip("PDF"))
 
+def test_ico():
+    with open('Tests/images/python.ico', 'rb') as f:
+        data = f.read()
+    p = ImageFile.Parser()
+    p.feed(data)
+    assert_equal((48,48), p.image.size)
+
 def test_safeblock():
 
     im1 = lena()
Repository: pallets/click

Problem statement:
Allow customizing fail message for invalid choice in `click.types.Choice`
Move the fail art of `convert()` in the `Choice` class to a new method `get_invalid_choice_fail_message(self)` so in my subclass of `click.Choice` I can customize the way it shows the failing value for the choice

Some CLI option choices are multi-part meaning they are separated by some value, like a comma separated list for example. Maybe each section of this value represents a different part of a schema and it is nice to show a custom message about the specific part.

Contrived version:
Let says my choices are `["maine::goat", "maine::themepark"]` and I give it "maine::toast"`, it'd be nice to say the `maine` part was correct and the `toast` part was not.





Hints:

Patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -304,16 +304,21 @@ def convert(
         if normed_value in normed_choices:
             return normed_choices[normed_value]
 
+        self.fail(self.get_invalid_choice_message(value), param, ctx)
+
+    def get_invalid_choice_message(self, value: t.Any) -> str:
+        """Get the error message when the given choice is invalid.
+
+        :param value: The invalid value.
+
+        .. versionadded:: 8.2
+        """
         choices_str = ", ".join(map(repr, self.choices))
-        self.fail(
-            ngettext(
-                "{value!r} is not {choice}.",
-                "{value!r} is not one of {choices}.",
-                len(self.choices),
-            ).format(value=value, choice=choices_str, choices=choices_str),
-            param,
-            ctx,
-        )
+        return ngettext(
+            "{value!r} is not {choice}.",
+            "{value!r} is not one of {choices}.",
+            len(self.choices),
+        ).format(value=value, choice=choices_str, choices=choices_str)
 
     def __repr__(self) -> str:
         return f"Choice({list(self.choices)})"


Test patch:
diff --git a/tests/test_types.py b/tests/test_types.py
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -244,3 +244,9 @@ def test_invalid_path_with_esc_sequence():
             click.Path(dir_okay=False).convert(tempdir, None, None)
 
     assert "my\\ndir" in exc_info.value.message
+
+
+def test_choice_get_invalid_choice_message():
+    choice = click.Choice(["a", "b", "c"])
+    message = choice.get_invalid_choice_message("d")
+    assert message == "'d' is not one of 'a', 'b', 'c'."
Repository: pallets/click

Problem statement:
`ParamType` missing `name` errors on `to_info_dict`
When calling `to_info_dict` on a `ParamType` instance which doesn't have a `name` attribute, an exception is raised. While this is a bug in the downstream code, only `to_info_dict` is affected, so the bug often goes unnoticed.

```py3
class TestType(click.ParamType):
    pass

TestType().to_info_dict()
```

```
>       return {"param_type": param_type, "name": self.name}
E       AttributeError: 'TestType' object has no attribute 'name'

src/click/types.py:66: AttributeError
```

It would be nice to have some sort of reasonable fallback. I've put coded such possibility at https://github.com/pallets/click/compare/main...phy1729:fix-ParamType-no-name . I also fixed where the docs neglected to specify `name` in an example.

Environment:

- Python version: Python 3.9.9
- Click version: 8.0.3



Hints:

Patch:
diff --git a/src/click/types.py b/src/click/types.py
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -63,7 +63,14 @@ def to_info_dict(self) -> t.Dict[str, t.Any]:
         # The class name without the "ParamType" suffix.
         param_type = type(self).__name__.partition("ParamType")[0]
         param_type = param_type.partition("ParameterType")[0]
-        return {"param_type": param_type, "name": self.name}
+
+        # Custom subclasses might not remember to set a name.
+        if hasattr(self, "name"):
+            name = self.name
+        else:
+            name = param_type
+
+        return {"param_type": param_type, "name": name}
 
     def __call__(
         self,


Test patch:
diff --git a/tests/test_info_dict.py b/tests/test_info_dict.py
--- a/tests/test_info_dict.py
+++ b/tests/test_info_dict.py
@@ -266,3 +266,10 @@ def test_context():
         "ignore_unknown_options": False,
         "auto_envvar_prefix": None,
     }
+
+
+def test_paramtype_no_name():
+    class TestType(click.ParamType):
+        pass
+
+    assert TestType().to_info_dict()["name"] == "TestType"
Repository: pallets/click

Problem statement:
Option to reask on no input in `click.confirm`
It would be nice if similarly to `click.prompt`, `click.confirm` would allow to reask the user if no input is given.


Hints:

Patch:
diff --git a/src/click/termui.py b/src/click/termui.py
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -172,21 +172,29 @@ def confirm(
     If the user aborts the input by sending a interrupt signal this
     function will catch it and raise a :exc:`Abort` exception.
 
-    .. versionadded:: 4.0
-       Added the `err` parameter.
-
     :param text: the question to ask.
-    :param default: the default for the prompt.
+    :param default: The default value to use when no input is given. If
+        ``None``, repeat until input is given.
     :param abort: if this is set to `True` a negative answer aborts the
                   exception by raising :exc:`Abort`.
     :param prompt_suffix: a suffix that should be added to the prompt.
     :param show_default: shows or hides the default value in the prompt.
     :param err: if set to true the file defaults to ``stderr`` instead of
                 ``stdout``, the same as with echo.
+
+    .. versionchanged:: 8.0
+        Repeat until input is given if ``default`` is ``None``.
+
+    .. versionadded:: 4.0
+        Added the ``err`` parameter.
     """
     prompt = _build_prompt(
-        text, prompt_suffix, show_default, "Y/n" if default else "y/N"
+        text,
+        prompt_suffix,
+        show_default,
+        "y/n" if default is None else ("Y/n" if default else "y/N"),
     )
+
     while 1:
         try:
             # Write the prompt separately so that we get nice
@@ -199,7 +207,7 @@ def confirm(
             rv = True
         elif value in ("n", "no"):
             rv = False
-        elif value == "":
+        elif default is not None and value == "":
             rv = default
         else:
             echo("Error: invalid input", err=err)


Test patch:
diff --git a/tests/test_utils.py b/tests/test_utils.py
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -131,6 +131,14 @@ def test_no():
     assert result.output == "Foo [Y/n]: n\nno :(\n"
 
 
+def test_confirm_repeat(runner):
+    cli = click.Command(
+        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]
+    )
+    result = runner.invoke(cli, input="\ny\n")
+    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"
+
+
 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")
 def test_prompts_abort(monkeypatch, capsys):
     def f(_):