internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: HypothesisWorks/hypothesis

Issue:
`example()` method yields too simple values in strategies
Hi!

Thanks for the library, it looks promising to newcomer :)

I was just learning your API and found that results of `example()` call are really too simple. Noticed the issue when playing with `recursive` strategy. Given the code from [docs](https://hypothesis.readthedocs.io/en/latest/data.html#recursive-data) and lot of samples I haven't really seen something more complex than `{'':[None]}`, most of values are simply `{}, None or []`, there are very few floats as well.

I understand its simplified to be more informative but currently its simplified to the extent that wasn't much helpful. At the end I used `given()` decorator and results were as expected.


Discussion:

Resolving patch:
diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/strategies.py b/hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
--- a/hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
+++ b/hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
@@ -16,7 +16,7 @@
 import sys
 import warnings
 from collections import defaultdict
-from random import choice as random_choice
+from random import shuffle
 from typing import (
     Any,
     Callable,
@@ -315,6 +315,11 @@ def example(self) -> Ex:
                     "#drawing-interactively-in-tests for more details."
                 )
 
+        try:
+            return self.__examples.pop()
+        except (AttributeError, IndexError):
+            self.__examples: List[Ex] = []
+
         from hypothesis.core import given
 
         # Note: this function has a weird name because it might appear in
@@ -322,18 +327,18 @@ def example(self) -> Ex:
         @given(self)
         @settings(
             database=None,
-            max_examples=10,
+            max_examples=100,
             deadline=None,
             verbosity=Verbosity.quiet,
             phases=(Phase.generate,),
             suppress_health_check=HealthCheck.all(),
         )
         def example_generating_inner_function(ex):
-            examples.append(ex)
+            self.__examples.append(ex)
 
-        examples: List[Ex] = []
         example_generating_inner_function()
-        return random_choice(examples)
+        shuffle(self.__examples)
+        return self.__examples.pop()
 
     def map(self, pack: Callable[[Ex], T]) -> "SearchStrategy[T]":
         """Returns a new strategy that generates values by generating a value


Test patch:
Repository: HypothesisWorks/hypothesis

Issue:
PyCon 2022 Sprints - Quick Start guide: Unclear
The portion of the quick start guide which guides users to fix the code by adding the below code to the beginning of the function is unclear. I am not sure which function to add the code snippet to. 

It might be easier to understand if the entire code function is display with some distinguishing marker showing the added code. 

![image](https://user-images.githubusercontent.com/72617548/166294431-e0abeb29-419d-41e2-beef-213e67b4273b.png)



Discussion:

Resolving patch:
diff --git a/hypothesis-python/setup.py b/hypothesis-python/setup.py
--- a/hypothesis-python/setup.py
+++ b/hypothesis-python/setup.py
@@ -16,7 +16,8 @@
 
 if sys.version_info[:2] < (3, 7):
     raise Exception(
-        "This version of Python is too old to install new versions of Hypothesis.  "
+        "You are trying to install Hypothesis using Python "
+        f"{sys.version.split()[0]}, but it requires Python 3.7 or later."
         "Update `pip` and `setuptools`, try again, and you will automatically "
         "get the latest compatible version of Hypothesis instead.  "
         "See also https://python3statement.org/practicalities/"


Test patch:
diff --git a/hypothesis-python/tests/conftest.py b/hypothesis-python/tests/conftest.py
--- a/hypothesis-python/tests/conftest.py
+++ b/hypothesis-python/tests/conftest.py
@@ -37,11 +37,6 @@
 if sys.version_info >= (3, 11):
     collect_ignore_glob.append("cover/test_asyncio.py")  # @asyncio.coroutine removed
 
-    assert sys.version_info.releaselevel == "alpha"
-    # TODO: our traceback elision doesn't work with Python 3.11's nice new format yet
-    collect_ignore_glob.append("cover/test_traceback_elision.py")
-    collect_ignore_glob.append("pytest/test_capture.py")
-
 
 def pytest_configure(config):
     config.addinivalue_line("markers", "slow: pandas expects this marker to exist.")
diff --git a/hypothesis-python/tests/cover/test_lookup_py37.py b/hypothesis-python/tests/cover/test_lookup_py37.py
--- a/hypothesis-python/tests/cover/test_lookup_py37.py
+++ b/hypothesis-python/tests/cover/test_lookup_py37.py
@@ -163,10 +163,6 @@ def test_resolving_standard_callable_ellipsis(x: collections.abc.Callable[..., E
     assert isinstance(x(1, 2, 3, a=4, b=5, c=6), Elem)
 
 
-@pytest.mark.skipif(
-    sys.version_info[:3] == (3, 11, 0),
-    reason="https://github.com/python/cpython/issues/91621",
-)
 @given(...)
 def test_resolving_standard_callable_no_args(x: collections.abc.Callable[[], Elem]):
     assert isinstance(x, collections.abc.Callable)
Repository: HypothesisWorks/hypothesis

Issue:
Update pinned dependencies
Automatically update pinned dependencies


Discussion:

Resolving patch:
diff --git a/hypothesis-python/src/hypothesis/extra/_array_helpers.py b/hypothesis-python/src/hypothesis/extra/_array_helpers.py
--- a/hypothesis-python/src/hypothesis/extra/_array_helpers.py
+++ b/hypothesis-python/src/hypothesis/extra/_array_helpers.py
@@ -387,8 +387,8 @@ def mutually_broadcastable_shapes(
         ...     print(strat.example())
         BroadcastableShapes(input_shapes=((4, 1, 3), (4, 2, 3), ()), result_shape=(4, 2, 3))
         BroadcastableShapes(input_shapes=((3,), (1, 3), (2, 3)), result_shape=(2, 3))
-        BroadcastableShapes(input_shapes=((), (), ()), result_shape=(2, 3))
-        BroadcastableShapes(input_shapes=((3,), (), (3,)), result_shape=(2, 3))
+        BroadcastableShapes(input_shapes=((), (), ()), result_shape=())
+        BroadcastableShapes(input_shapes=((3,), (), (3,)), result_shape=(3,))
         BroadcastableShapes(input_shapes=((1, 2, 3), (3,), ()), result_shape=(1, 2, 3))
 
     """


Test patch:
Repository: HypothesisWorks/hypothesis

Issue:
Hypofuzz entrypoint causes test_lazy_import to fail
If hypofuzz is installed, test_lazy_import fails due to `pytest` being in `sys.modules`.


Discussion:
These kind of issues are obviously not caught in CI, since the set of potential entrypoints is unknowable. I don't know it there's anything to fix here, maybe a comment somewhere in the test about the potential for false positives?
Hmm, maybe we should have an environment variable or something which disables plugins?  Useful for testing ourselves, and also for end-user debugging I guess 🤔 

Resolving patch:
diff --git a/hypothesis-python/src/hypothesis/entry_points.py b/hypothesis-python/src/hypothesis/entry_points.py
--- a/hypothesis-python/src/hypothesis/entry_points.py
+++ b/hypothesis-python/src/hypothesis/entry_points.py
@@ -16,6 +16,7 @@
 """
 
 import importlib.metadata
+import os
 
 
 def get_entry_points():
@@ -29,7 +30,8 @@ def get_entry_points():
 
 
 def run():
-    for entry in get_entry_points():  # pragma: no cover
-        hook = entry.load()
-        if callable(hook):
-            hook()
+    if not os.environ.get("HYPOTHESIS_NO_PLUGINS"):
+        for entry in get_entry_points():  # pragma: no cover
+            hook = entry.load()
+            if callable(hook):
+                hook()


Test patch:
diff --git a/hypothesis-python/tests/cover/test_lazy_import.py b/hypothesis-python/tests/cover/test_lazy_import.py
--- a/hypothesis-python/tests/cover/test_lazy_import.py
+++ b/hypothesis-python/tests/cover/test_lazy_import.py
@@ -8,6 +8,7 @@
 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
 # obtain one at https://mozilla.org/MPL/2.0/.
 
+import os
 import subprocess
 import sys
 
@@ -44,4 +45,7 @@ def test_hypothesis_does_not_import_test_runners(tmp_path):
     # See https://github.com/HypothesisWorks/hypothesis/pull/2204
     fname = tmp_path / "test.py"
     fname.write_text(SHOULD_NOT_IMPORT_TEST_RUNNERS, encoding="utf-8")
-    subprocess.check_call([sys.executable, str(fname)])
+    subprocess.check_call(
+        [sys.executable, str(fname)],
+        env={**os.environ, **{"HYPOTHESIS_NO_PLUGINS": "1"}},
+    )
Repository: HypothesisWorks/hypothesis

Issue:
`NotImplementedError: This should never happen` getting raised in MyGrad CI
MyGrad's nightly CI run is failing with the aforementioned error within `hypothesis.internal.conjecture.shrinker.Shrinker`: https://github.com/rsokl/MyGrad/actions/runs/6217407874/job/16872437842

[Here](https://github.com/rsokl/MyGrad/blob/133072b526966e235d70bbfcf9eb86d43d0fcfa1/tests/wrappers/test_uber.py#L220-L241) is one of the tests that is triggering it. 


Discussion:
Darn, seems this really isn't as impossible as I thought back in April... odd that we didn't hit it in six months of dogfooding, though [it did come up in an extension PR yesterday](https://github.com/HypothesisWorks/hypothesis/pull/3624/commits/0b3f7ef114f074fd2ed226050ddeaebcd5a2b216#diff-7a67fe51323e874a6ed0c3e8fff48695f3603c0820e6323c4c37ff870ac96818) 🤯 

Resolving patch:
diff --git a/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py b/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py
--- a/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py
+++ b/hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py
@@ -547,7 +547,7 @@ def explain(self):
 
                 # Turns out this was a variable-length part, so grab the infix...
                 if result.status == Status.OVERRUN:
-                    continue  # pragma: no cover
+                    continue  # pragma: no cover  # flakily covered
                 if not (
                     len(buf_attempt_fixed) == len(result.buffer)
                     and result.buffer.endswith(buffer[end:])
@@ -568,11 +568,13 @@ def explain(self):
                     chunks[(start, end)].append(result.buffer[start:res_end])
                     result = self.engine.cached_test_function(buf_attempt_fixed)
 
-                    if (
-                        result.status == Status.OVERRUN
-                        or len(buf_attempt_fixed) != len(result.buffer)
-                        or not result.buffer.endswith(buffer[end:])
-                    ):
+                    if result.status == Status.OVERRUN:
+                        continue  # pragma: no cover  # flakily covered
+
+                    if not (
+                        len(buf_attempt_fixed) == len(result.buffer)
+                        and result.buffer.endswith(buffer[end:])
+                    ):  # pragma: no cover
                         raise NotImplementedError("This should never happen")
                 else:
                     chunks[(start, end)].append(result.buffer[start:end])


Test patch:
Repository: HypothesisWorks/hypothesis

Issue:
Hypothesis's fake Random disagrees with true Random when sampling empty sequences
The following code doesn't work correctly when using Hypothesis's fake random number generator:

```python
from hypothesis import given, strategies as st

@given(rnd=st.randoms(use_true_random=False))
def test_sample_from_empty(rnd):
    assert rnd.sample([], 0) == []
```

It fails with:

```
E           hypothesis.errors.InvalidArgument: Cannot sample from a length-zero sequence.
E           Falsifying example: test_sample_from_empty(
E               rnd=HypothesisRandom(generated data),
E           )
```

But the following test passes:

```
from random import Random

def test_sample_from_empty():
    rnd = Random()
    assert rnd.sample([], 0) == []
```

The issue is that although you can't sample a non-zero number of elements from an empty sequence, it's perfectly valid to sample 0 elements from an empty sequence, and the normal Random class supports this fine but our emulation of it does not.


Discussion:

Resolving patch:
diff --git a/hypothesis-python/src/hypothesis/strategies/_internal/random.py b/hypothesis-python/src/hypothesis/strategies/_internal/random.py
--- a/hypothesis-python/src/hypothesis/strategies/_internal/random.py
+++ b/hypothesis-python/src/hypothesis/strategies/_internal/random.py
@@ -296,14 +296,17 @@ def _hypothesis_do_random(self, method, kwargs):
                     f"Sample size {k} not in expected range 0 <= k <= {len(seq)}"
                 )
 
-            result = self.__data.draw(
-                lists(
-                    sampled_from(range(len(seq))),
-                    min_size=k,
-                    max_size=k,
-                    unique=True,
+            if k == 0:
+                result = []
+            else:
+                result = self.__data.draw(
+                    lists(
+                        sampled_from(range(len(seq))),
+                        min_size=k,
+                        max_size=k,
+                        unique=True,
+                    )
                 )
-            )
 
         elif method == "getrandbits":
             result = self.__data.draw_bits(kwargs["n"])


Test patch:
diff --git a/hypothesis-python/tests/cover/test_randoms.py b/hypothesis-python/tests/cover/test_randoms.py
--- a/hypothesis-python/tests/cover/test_randoms.py
+++ b/hypothesis-python/tests/cover/test_randoms.py
@@ -381,3 +381,8 @@ def test_can_sample_from_large_subset(rnd):
     ys = rnd.sample(xs, n)
     assert set(ys).issubset(set(xs))
     assert len(ys) == len(set(ys)) == n
+
+
+@given(st.randoms(use_true_random=False))
+def test_can_draw_empty_from_empty_sequence(rnd):
+    assert rnd.sample([], 0) == []
Repository: mlcommons/GaNDLF

Issue:
U-Net style archs need a minimum patch size
**Is your feature request related to a problem? Please describe.**
Currently, if the patch size of U-Net variants is `16`, the final output is `[...,1]`, which does not make sense.

**Describe the solution you'd like**
Add a minimum patch size requirement, based on the number of layers in the network.

**Describe alternatives you've considered**
N.A.

**Additional context**
Reported by Vinayak.



Discussion:

Resolving patch:
diff --git a/GANDLF/utils.py b/GANDLF/utils.py
--- a/GANDLF/utils.py
+++ b/GANDLF/utils.py
@@ -143,6 +143,12 @@ def checkPatchDivisibility(patch_size, number = 16):
         patch_size_to_check = patch_size_to_check[1:]
     if np.count_nonzero(np.remainder(patch_size_to_check, number)) > 0:
         return False
+    
+    # adding check to address https://github.com/CBICA/GaNDLF/issues/53
+    # there is quite possibly a better way to do this
+    unique = np.unique(patch_size_to_check)
+    if (unique.shape[0] == 1) and (unique[0] <= number):
+        return False
     return True
 
 


Test patch:
Repository: mlcommons/GaNDLF

Issue:
`densenet` requires patches to be divisible by 16, which is not really correct
**Describe the bug**
When `parameters["model"]["architecture"] == densenet121` (or any other variant), patch divisibility is kicking in.

**To Reproduce**
Steps to reproduce the behavior:
1. Select a `densenet` variant for `["model"]["architecture"]`
2. Put `patch_size` as something not divisible by `16`
3. See error triggered in `parameterParsing.py`

**Expected behavior**
DenseNet should not require this check.

**Screenshots**
N.A.

**GaNDLF Version**
0.0.11-dev

**Desktop (please complete the following information):**
N.A.

**Additional context**
Originally reported by @orhunguley 



Discussion:

Resolving patch:
diff --git a/GANDLF/parameterParsing.py b/GANDLF/parameterParsing.py
--- a/GANDLF/parameterParsing.py
+++ b/GANDLF/parameterParsing.py
@@ -239,6 +239,9 @@ def get_model(
             )
 
         amp = False  # this is not yet implemented for densenet
+        # these checks are not needed
+        divisibilityCheck_patch = False
+        divisibilityCheck_baseFilter = False
 
     elif "vgg" in modelname:  # common parsing for vgg
         if modelname == "vgg11":
@@ -253,13 +256,14 @@ def get_model(
             sys.exit("Requested VGG type '" + modelname + "' has not been implemented")
 
         amp = False  # this is not yet implemented for vgg
+        # these checks are not needed
+        divisibilityCheck_patch = False
+        divisibilityCheck_baseFilter = False
 
         if "batch_norm" in kwargs:
             batch_norm = kwargs.get("batch_norm")
         else:
             batch_norm = True
-        divisibilityCheck_patch = False
-        divisibilityCheck_baseFilter = False
         layers = make_layers(
             vgg_config, num_dimensions, num_channels, batch_norm=batch_norm
         )
@@ -292,6 +296,8 @@ def get_model(
             ]
         )
         model.classifier = nn.Sequential(*features)  # Replace the model classifier
+        amp = False  # this is not yet implemented for vgg
+        # these checks are not needed
         divisibilityCheck_patch = False
         divisibilityCheck_baseFilter = False
 


Test patch:
Repository: mlcommons/GaNDLF

Issue:
Extend loss weight calculation for classification
**Is your feature request related to a problem? Please describe.**
Currently, classification problems don't use weight calculations for specific classes. 

**Describe the solution you'd like**
Similar to segmentation, the weights should be dynamic.

**Describe alternatives you've considered**
N.A.

**Additional context**
N.A.



Discussion:

Resolving patch:
diff --git a/GANDLF/losses.py b/GANDLF/losses.py
--- a/GANDLF/losses.py
+++ b/GANDLF/losses.py
@@ -25,8 +25,8 @@ def cel(out, target, params):
         # more examples you have in the training data, the smaller the weight you have in the loss
         class_weights = 1.0 / class_weights
 
-        class_weights = class_weights.float().to(params["device"])
-
+        class_weights = class_weights.float().to(target.device)
+        
     cel = CrossEntropyLoss(weight=class_weights)
     return cel(out, target)
 


Test patch:
Repository: mlcommons/GaNDLF

Issue:
Error In Classification due to a bug in get_loss_and_metrics()
**Describe the bug**
New version of "get_loss_and_metrics" function is not covering classification tasks. 
line 494 --> "if len(predicted) > 1:" statement is designed for sdnet-style archs but for classification tasks, the len(pred) is equal to the batch size, which is the case most of the time for classification.

**To Reproduce**
Steps to reproduce the behavior:
1. run GaNDLF for classification tasks
2. You can use the config file I attached.

**Expected behavior**
The following error occures.
![image](https://user-images.githubusercontent.com/24361544/127570316-19a1da95-1a36-4912-8cee-5cebdbaa62bc.png)
That is due to line 496 --> loss_seg = loss_function(predicted[0], ground_truth.squeeze(-1), params) uses only the prediction, but the ground truth has the shape of batch_size.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**GaNDLF Version**
Version information is found on Help > About
0.11

**Desktop (please complete the following information):**
 - Linux WSL Ubuntu 20.04
[config_classification.txt](https://github.com/CBICA/GaNDLF/files/6903853/config_classification.txt)




Discussion:

Resolving patch:
diff --git a/GANDLF/losses.py b/GANDLF/losses.py
--- a/GANDLF/losses.py
+++ b/GANDLF/losses.py
@@ -26,7 +26,7 @@ def cel(out, target, params):
         class_weights = 1.0 / class_weights
 
         class_weights = class_weights.float().to(target.device)
-        
+
     cel = CrossEntropyLoss(weight=class_weights)
     return cel(out, target)
 
diff --git a/GANDLF/parameterParsing.py b/GANDLF/parameterParsing.py
--- a/GANDLF/parameterParsing.py
+++ b/GANDLF/parameterParsing.py
@@ -491,7 +491,8 @@ def get_loss_and_metrics(image, ground_truth, predicted, params):
         The computed metric from the label and the output
     """
     loss_function = fetch_loss_function(params["loss_function"], params)
-    if len(predicted) > 1:
+    sdnet_check = (len(predicted) > 1) and (params["model"]["architecture"] == "sdnet")
+    if sdnet_check:
         # this is specific for sdnet-style archs
         loss_seg = loss_function(predicted[0], ground_truth.squeeze(-1), params)
         loss_function = fetch_loss_function("l1", None)
@@ -507,7 +508,7 @@ def get_loss_and_metrics(image, ground_truth, predicted, params):
     # Metrics should be a list
     for metric in params["metrics"]:
         metric_function = fetch_metric(metric)  # Write a fetch_metric
-        if len(predicted) > 1:
+        if sdnet_check:
             metric_output[metric] = (
                 metric_function(predicted[0], ground_truth.squeeze(-1), params)
                 .cpu()


Test patch:
Repository: mlcommons/GaNDLF

Issue:
Add option to change all data to a single orientation
**Is your feature request related to a problem? Please describe.**
Since GaNDLF includes preprocessing, it would make sense to ensure that the orientation of all datasets is consistent.

**Describe the solution you'd like**
It would be useful to ensure TorchIO's [`to_canonical`](https://torchio.readthedocs.io/transforms/preprocessing.html?highlight=canonical#torchio.transforms.ToCanonical) is added as an option in `ImagesFromDataFrame`.

**Describe alternatives you've considered**
Use SimpleITK's `DICOMOrientImageFilter`, but this cannot be done until TorchIO [requires SimpleITK<2](https://github.com/fepegar/torchio/commit/3509cf88e67004d1cbff080297dae016986b9d22).

**Additional context**
N.A.



Discussion:

Resolving patch:
diff --git a/GANDLF/data/ImagesFromDataFrame.py b/GANDLF/data/ImagesFromDataFrame.py
--- a/GANDLF/data/ImagesFromDataFrame.py
+++ b/GANDLF/data/ImagesFromDataFrame.py
@@ -22,6 +22,7 @@
     RandomFlip,
     RandomGamma,
     Pad,
+    ToCanonical,
 )
 from torchio import Image, Subject
 import SimpleITK as sitk
@@ -375,6 +376,9 @@ def ImagesFromDataFrame(dataframe, parameters, train):
 
     # first, we want to do thresholding, followed by clipping, if it is present - required for inference as well
     if not (preprocessing is None):
+        if "to_canonical" in preprocessing:
+            augmentation_list.append(ToCanonical())
+
         if train:  # we want the crop to only happen during training
             if "crop_external_zero_planes" in preprocessing:
                 augmentation_list.append(
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -43,7 +43,7 @@
     "coverage",
     "psutil",
     "medcam",
-    "torchmetrics"
+    "torchmetrics",
 ]
 
 setup(
@@ -69,6 +69,7 @@
         "Programming Language :: Python :: 3.6",
         "Programming Language :: Python :: 3.7",
         "Programming Language :: Python :: 3.8",
+        "Topic :: Scientific/Engineering :: Medical Science Apps",
     ],
     description=(
         "PyTorch-based framework that handles segmentation/regression/classification using various DL architectures for medical imaging."
@@ -78,7 +79,7 @@
     long_description=readme,
     long_description_content_type="text/markdown",
     include_package_data=True,
-    keywords="semantic, segmentation, regression, classification, brain, breast, liver, lung, augmentation, medical-imaging",
+    keywords="semantic, segmentation, regression, classification, data-augmentation, medical-imaging",
     zip_safe=False,
 )
 


Test patch:
diff --git a/testing/test_full.py b/testing/test_full.py
--- a/testing/test_full.py
+++ b/testing/test_full.py
@@ -663,6 +663,7 @@ def test_cli_function_preprocess():
     parameters["patch_sampler"] = "label"
     parameters["weighted_loss"] = True
     parameters["save_output"] = True
+    parameters["data_preprocessing"]["to_canonical"] = None
 
     # store this separately for preprocess testing
     with open(file_config_temp, "w") as outfile: