nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: seanmonstar/warp
Pull request #534 (2020-04-14 09:22:57)

making cookie filter generic over T: FromStr + Send + 'static
PR for the issue: https://github.com/seanmonstar/warp/issues/530


Patch:
diff --git a/src/filters/cookie.rs b/src/filters/cookie.rs
index 6509145..5e421af 100644
--- a/src/filters/cookie.rs
+++ b/src/filters/cookie.rs
@@ -7,16 +7,20 @@ use super::header;
 use crate::filter::{Filter, One};
 use crate::reject::Rejection;
 use std::convert::Infallible;
+use std::str::FromStr;
 
 /// Creates a `Filter` that requires a cookie by name.
 ///
 /// If found, extracts the value of the cookie, otherwise rejects.
-pub fn cookie(name: &'static str) -> impl Filter<Extract = One<String>, Error = Rejection> + Copy {
+pub fn cookie<T>(name: &'static str) -> impl Filter<Extract = One<T>, Error = Rejection> + Copy
+where
+    T: FromStr + Send + 'static,
+{
     header::header2().and_then(move |cookie: Cookie| {
         let cookie = cookie
             .get(name)
-            .map(String::from)
-            .ok_or_else(|| crate::reject::missing_cookie(name));
+            .ok_or_else(|| crate::reject::missing_cookie(name))
+            .and_then(|s| T::from_str(s).map_err(|_| crate::reject::missing_cookie(name)));
         future::ready(cookie)
     })
 }
@@ -25,9 +29,18 @@ pub fn cookie(name: &'static str) -> impl Filter<Extract = One<String>, Error =
 ///
 /// If found, extracts the value of the cookie, otherwise continues
 /// the request, extracting `None`.
-pub fn optional(
+pub fn optional<T>(
     name: &'static str,
-) -> impl Filter<Extract = One<Option<String>>, Error = Infallible> + Copy {
-    header::optional2()
-        .map(move |opt: Option<Cookie>| opt.and_then(|cookie| cookie.get(name).map(String::from)))
+) -> impl Filter<Extract = One<Option<T>>, Error = Infallible> + Copy
+where
+    T: FromStr + Send + 'static,
+{
+    header::optional2().map(move |opt: Option<Cookie>| {
+        let cookie = opt.and_then(|cookie| cookie.get(name).map(|x| T::from_str(x)));
+        match cookie {
+            Some(Ok(t)) => Some(t),
+            Some(Err(_)) => None,
+            None => None,
+        }
+    })
 }


Test patch:
diff --git a/tests/cookie.rs b/tests/cookie.rs
index fadf3e3..4cf286a 100644
--- a/tests/cookie.rs
+++ b/tests/cookie.rs
@@ -2,7 +2,7 @@
 
 #[tokio::test]
 async fn cookie() {
-    let foo = warp::cookie("foo");
+    let foo = warp::cookie::<String>("foo");
 
     let req = warp::test::request().header("cookie", "foo=bar");
     assert_eq!(req.filter(&foo).await.unwrap(), "bar");
@@ -19,7 +19,7 @@ async fn cookie() {
 
 #[tokio::test]
 async fn optional() {
-    let foo = warp::cookie::optional("foo");
+    let foo = warp::cookie::optional::<String>("foo");
 
     let req = warp::test::request().header("cookie", "foo=bar");
     assert_eq!(req.filter(&foo).await.unwrap().unwrap(), "bar");
@@ -38,7 +38,7 @@ async fn optional() {
 async fn missing() {
     let _ = pretty_env_logger::try_init();
 
-    let cookie = warp::cookie("foo");
+    let cookie = warp::cookie::<String>("foo");
 
     let res = warp::test::request()
         .header("cookie", "not=here")
Repository: seanmonstar/warp
Pull request #696 (2020-08-23 06:47:33)

allow warp::path!() call with no arguments
This is a feature request + implementation for it. Let me know if you think this is a bad idea.

---

It is equivalent to `warp::path::end()`. This is useful to have some symmetry
when defining multiple routes with `path!`:

```
warp::path!().map(|| 0)
.or(warp::path!("add" / u32 / u32).map(|a, b| a + b))
.or(warp::path!("mul" / u32 / u32).map(|a, b| a * b))
```

utkarshkukreti: Rebased!
masklinn: FWIW I had this exact same need / request recently. I replaced the not-working `path!()` call by an `end()` but it feels unclear and icky. 

Patch:
diff --git a/src/filters/path.rs b/src/filters/path.rs
index 435ebf6..e4de98b 100644
--- a/src/filters/path.rs
+++ b/src/filters/path.rs
@@ -535,6 +535,9 @@ macro_rules! path {
 #[macro_export]
 // not public API
 macro_rules! __internal_path {
+    (@start) => (
+        $crate::path::end()
+    );
     (@start ..) => ({
         compile_error!("'..' cannot be the only segment")
     });


Test patch:
diff --git a/tests/path.rs b/tests/path.rs
index 3d5662c..54ebe00 100644
--- a/tests/path.rs
+++ b/tests/path.rs
@@ -246,6 +246,16 @@ async fn path_macro() {
     let req = warp::test::request().path("/foo/bar/baz");
     let p = path!("foo" / "bar" / ..).and(warp::path!("baz"));
     assert!(req.matches(&p).await);
+
+    // Empty
+
+    let req = warp::test::request().path("/");
+    let p = path!();
+    assert!(req.matches(&p).await);
+
+    let req = warp::test::request().path("/foo");
+    let p = path!();
+    assert!(!req.matches(&p).await);
 }
 
 #[tokio::test]
Repository: bids-standard/pybids
Pull request #1119 (2025-02-27 13:18:26)

fix: Allow numpy arrays to treat PaddedInt like int
If an exception is raised by `val == self.sval or ...` (that is, `val.__eq__(self.sval).__bool__()`), we defer to the `val` type to determine the correct behavior. This is currently only expected to be triggered by array-like types, but any type that goes this far out of its way to change its boolean behavior is one we don't want to get too fancy with.

In the spirit of not getting fancy, we drop any consideration of the padded string in this context. 



Patch:
diff --git a/src/bids/layout/utils.py b/src/bids/layout/utils.py
index acc6c2ff..326c0739 100644
--- a/src/bids/layout/utils.py
+++ b/src/bids/layout/utils.py
@@ -65,7 +65,13 @@ class PaddedInt(int):
         self.sval = str(val)
 
     def __eq__(self, val):
-        return val == self.sval or super().__eq__(val)
+        try:
+            return val == self.sval or super().__eq__(val)
+        except ValueError:
+            # `or` triggers `__bool__`. If this fails, it is almost
+            # certainly an array type. Do not attempt string comparisons
+            # and allow val to determine the return type
+            return val == self
 
     def __str__(self):
         return self.sval


Test patch:
diff --git a/src/bids/layout/tests/test_utils.py b/src/bids/layout/tests/test_utils.py
index 26f1511b..103fee1e 100644
--- a/src/bids/layout/tests/test_utils.py
+++ b/src/bids/layout/tests/test_utils.py
@@ -2,12 +2,14 @@
 
 import os
 
+import numpy as np
 import pytest
+import pandas as pd
 import bids
 from bids.exceptions import ConfigError
 
 from ..models import Entity, Config
-from ..utils import BIDSMetadata, parse_file_entities, add_config_paths
+from ..utils import BIDSMetadata, PaddedInt, parse_file_entities, add_config_paths
 
 
 def test_bidsmetadata_class():
@@ -73,3 +75,31 @@ def test_add_config_paths():
     add_config_paths(dummy=bids_json)
     config = Config.load('dummy')
     assert 'subject' in config.entities
+
+
+def test_PaddedInt_array_comparisons():
+    # Array comparisons should work, not raise exceptions
+    arr = np.array([5, 5, 5])
+    assert np.all(arr == PaddedInt(5))
+    assert np.all(arr == PaddedInt("05"))
+    assert np.all(PaddedInt(5) == arr)
+    assert np.all(PaddedInt("05") == arr)
+
+    # If the value gets put into an array, it should be considered an int
+    # We lose the padding, but it's unlikely we would try to recover it
+    # from an array.
+    assert np.array([PaddedInt(5)]).dtype == np.int64
+
+    # Verify that we do get some False results
+    assert np.array_equal(np.array([4, 5, 6]) == PaddedInt(5), [False, True, False])
+
+
+def test_PaddedInt_dataframe_behavior():
+    # Verify that pandas dataframes are not more special than numpy arrays,
+    # as far as PaddedInt is concerned
+    df = pd.DataFrame({'a': [5, 5, 5]})
+    pidf = pd.DataFrame({'a': [PaddedInt(5)] * 3})
+    assert np.all(df['a'] == PaddedInt(5))
+    assert np.all(df == pidf)
+
+    assert pidf['a'].dtype is np.dtype('int64')
Repository: bids-standard/pybids
Pull request #1120 (2025-03-04 21:49:54)

fix: Copy entities dict before modifying run variable type
This resolves a very particular bug, which may or may not be the last, related to losing the zero-padding when processing a dataset with fitlins.

It turns out that once you call `BIDSStatsModelsGraph.load_collections()`, you lose the `PaddedInt` type in the BIDSFile's entity dictionary. This is because we mutate the dictionary in-place. This PR copies the dict and improves the comments.

Starting with a test I can confirm failed before the fix was applied.


Patch:
diff --git a/src/bids/variables/io.py b/src/bids/variables/io.py
index d0dedeb4..31d78958 100644
--- a/src/bids/variables/io.py
+++ b/src/bids/variables/io.py
@@ -188,10 +188,13 @@ def _load_time_variables(layout, dataset=None, columns=None, scan_length=None,
     # Main loop over images
     for img_obj in images:
 
-        entities = img_obj.entities
         img_f = img_obj.path
 
-        # Run is not mandatory, but we need a default for proper indexing
+        # Run is not mandatory, but we need it to behave like an int and not
+        # a PaddedInt later when we call `dataset.get_nodes('run', select_on)`
+        # Without this, we would see "run ==02" in the query, which breaks
+        # pandas.
+        entities = img_obj.entities.copy()
         if 'run' in entities:
             entities['run'] = int(entities['run'])
 


Test patch:
diff --git a/src/bids/modeling/tests/test_statsmodels.py b/src/bids/modeling/tests/test_statsmodels.py
index 54110d58..af6a0252 100644
--- a/src/bids/modeling/tests/test_statsmodels.py
+++ b/src/bids/modeling/tests/test_statsmodels.py
@@ -12,6 +12,7 @@ import json
 from bids.modeling import BIDSStatsModelsGraph
 from bids.modeling.statsmodels import ContrastInfo, expand_wildcards
 from bids.layout import BIDSLayout
+from bids.layout.utils import PaddedInt
 from bids.tests import get_test_data_path
 from bids.variables import BIDSVariableCollection
 
@@ -43,6 +44,13 @@ def graph_nodummy():
     graph.load_collections(scan_length=480, subject=["01", "02"])
     return graph
 
+def test_load_collections_types(graph):
+    # Very narrow regression test that ensures that load_collections does not
+    # modify the types of entities in-place
+    layout = graph.layout
+    bold = layout.get(suffix="bold", extension="nii.gz")[0]
+    assert isinstance(bold.entities["run"], PaddedInt)
+
 @pytest.mark.skipif(not has_graphviz, reason="Test requires graphviz")
 def test_write_graph(graph, tmp_path):
     from graphviz import Digraph
@@ -306,4 +314,4 @@ def test_missing_value_fill():
     graph.run_graph(missing_values='ignore')
 
     outputs = graph.nodes['run'].outputs_
-    assert np.isnan(outputs[0].model_spec.X).any().any()
\ No newline at end of file
+    assert np.isnan(outputs[0].model_spec.X).any().any()