internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Kinto/kinto

Issue:
Memory permission backend implementation of remove_principal() is wrong
According to the `PermissionBase` docstring, `remove_principal` is supposed to `Remove a principal from every user`. In other words, `remove_principal(principal)` is equivalent to `remove_user_principal(user_id, principal) for user_id in all_possible_user_ids`. However, the current implementation stores all permissions of all kinds in one hash table, and removes the principal from permissions of non-user things as well.


Discussion:

Resolving patch:
diff --git a/kinto/core/permission/memory.py b/kinto/core/permission/memory.py
--- a/kinto/core/permission/memory.py
+++ b/kinto/core/permission/memory.py
@@ -48,7 +48,9 @@ def remove_user_principal(self, user_id, principal):
 
     @synchronized
     def remove_principal(self, principal):
-        for user_principals in self._store.values():
+        for key, user_principals in self._store.items():
+            if not key.startswith("user:"):
+                continue
             try:
                 user_principals.remove(principal)
             except KeyError:


Test patch:
diff --git a/kinto/core/permission/testing.py b/kinto/core/permission/testing.py
--- a/kinto/core/permission/testing.py
+++ b/kinto/core/permission/testing.py
@@ -141,6 +141,17 @@ def test_can_remove_principal_from_every_users(self):
         retrieved = self.permission.get_user_principals(user_id2)
         self.assertEqual(retrieved, {principal2})
 
+    def test_cannot_remove_principal_from_objects(self):
+        object_id = "/buckets/some-bucket"
+        user_id = "user"
+        principal = "readers-group"
+        self.permission.add_principal_to_ace(object_id, "read", principal)
+        self.permission.add_user_principal(user_id, principal)
+        self.permission.remove_principal(principal)
+
+        retrieved = self.permission.get_object_permissions(object_id)
+        self.assertEqual(retrieved, {"read": set([principal])})
+
     def test_authenticated_is_returned_for_everybody(self):
         user_id = "foo"
         principal = "bar"
Repository: Kinto/kinto

Issue:
DELETE /v1/accounts raises a 500
```
$ http DELETE https://natim.alwaysdata.net/v1/accounts --auth admin:admin
HTTP/1.1 500 Internal Server Error
Access-Control-Expose-Headers: Retry-After, Alert, Backoff, Content-Length
Content-Length: 177
Content-Type: application/json
Date: Mon, 28 Jan 2019 20:45:56 GMT
Via: 1.1 alproxy
X-Content-Type-Options: nosniff
```

```
  File "/home/natim/kinto/kinto/kinto/plugins/accounts/views.py", line 221, in on_account_changed
    username = request.matchdict["id"]
KeyError: 'id'
```
DELETE /v1/accounts raises a 500
```
$ http DELETE https://natim.alwaysdata.net/v1/accounts --auth admin:admin
HTTP/1.1 500 Internal Server Error
Access-Control-Expose-Headers: Retry-After, Alert, Backoff, Content-Length
Content-Length: 177
Content-Type: application/json
Date: Mon, 28 Jan 2019 20:45:56 GMT
Via: 1.1 alproxy
X-Content-Type-Options: nosniff
```

```
  File "/home/natim/kinto/kinto/kinto/plugins/accounts/views.py", line 221, in on_account_changed
    username = request.matchdict["id"]
KeyError: 'id'
```


Discussion:

Resolving patch:
diff --git a/kinto/plugins/accounts/views.py b/kinto/plugins/accounts/views.py
--- a/kinto/plugins/accounts/views.py
+++ b/kinto/plugins/accounts/views.py
@@ -132,9 +132,11 @@ def on_account_changed(event):
     request = event.request
     cache = request.registry.cache
     settings = request.registry.settings
-    # Extract username and password from current user
-    username = request.matchdict["id"]
     hmac_secret = settings["userid_hmac_secret"]
-    cache_key = utils.hmac_digest(hmac_secret, ACCOUNT_CACHE_KEY.format(username))
-    # Delete cache
-    cache.delete(cache_key)
+
+    for obj in event.impacted_objects:
+        # Extract username and password from current user
+        username = obj["old"]["id"]
+        cache_key = utils.hmac_digest(hmac_secret, ACCOUNT_CACHE_KEY.format(username))
+        # Delete cache
+        cache.delete(cache_key)


Test patch:
diff --git a/tests/plugins/test_accounts.py b/tests/plugins/test_accounts.py
--- a/tests/plugins/test_accounts.py
+++ b/tests/plugins/test_accounts.py
@@ -362,6 +362,11 @@ def test_admin_can_delete_other_accounts(self):
         self.app.delete_json("/accounts/bob", headers=self.admin_headers)
         self.app.get("/accounts/bob", headers=get_user_headers("bob", "987654"), status=401)
 
+    def test_admin_can_delete_all_accounts(self):
+        self.app.delete_json("/accounts", headers=self.admin_headers)
+
+        self.app.get("/accounts/bob", headers=get_user_headers("bob", "987654"), status=401)
+
     def test_admin_can_set_others_password(self):
         self.app.patch_json(
             "/accounts/bob", {"data": {"password": "bouh"}}, headers=self.admin_headers
Repository: Kinto/kinto

Issue:
Remove pinning and pip_pre config once jsonschema 3 is released properly
Refs https://github.com/Kinto/kinto/pull/1898#pullrequestreview-180204186


Discussion:

Resolving patch:
diff --git a/kinto/schema_validation.py b/kinto/schema_validation.py
--- a/kinto/schema_validation.py
+++ b/kinto/schema_validation.py
@@ -1,12 +1,12 @@
 import colander
-from jsonschema import ValidationError, SchemaError, RefResolutionError
+from jsonschema import (
+    Draft7Validator as DraftValidator,
+    ValidationError,
+    SchemaError,
+    RefResolutionError,
+)
 from jsonschema.validators import validator_for
 
-try:  # pragma: no cover
-    from jsonschema import Draft7Validator as DraftValidator
-except ImportError:
-    from jsonschema import Draft4Validator as DraftValidator
-
 from pyramid.settings import asbool
 
 from kinto.core import utils


Test patch:
Repository: Kinto/kinto

Issue:
memcached cache backend does not really test memcached
@autrilla reported that when he moved Kinto to GCP, the heartbeat reported success for all backends, including cache, even though there is no `memcached`. I think the problem is here:

https://github.com/Kinto/kinto/blob/61494caae2bb8fe342f32f6a5d89f40ed2b62dff/kinto/core/cache/__init__.py#L87-L91

The heartbeat for the cache backend just sends two messages which don't expect responses. For something like memcached which communicates over UDP, these messages can "succeed" by silently going nowhere.
memcached cache backend does not really test memcached
@autrilla reported that when he moved Kinto to GCP, the heartbeat reported success for all backends, including cache, even though there is no `memcached`. I think the problem is here:

https://github.com/Kinto/kinto/blob/61494caae2bb8fe342f32f6a5d89f40ed2b62dff/kinto/core/cache/__init__.py#L87-L91

The heartbeat for the cache backend just sends two messages which don't expect responses. For something like memcached which communicates over UDP, these messages can "succeed" by silently going nowhere.


Discussion:

Resolving patch:
diff --git a/kinto/core/cache/__init__.py b/kinto/core/cache/__init__.py
--- a/kinto/core/cache/__init__.py
+++ b/kinto/core/cache/__init__.py
@@ -86,9 +86,9 @@ def ping(request):
         try:
             if random.SystemRandom().random() < _HEARTBEAT_DELETE_RATE:
                 backend.delete(_HEARTBEAT_KEY)
-            else:
-                backend.set(_HEARTBEAT_KEY, "alive", _HEARTBEAT_TTL_SECONDS)
-            return True
+                return backend.get(_HEARTBEAT_KEY) is None
+            backend.set(_HEARTBEAT_KEY, "alive", _HEARTBEAT_TTL_SECONDS)
+            return backend.get(_HEARTBEAT_KEY) == "alive"
         except Exception:
             logger.exception("Heartbeat Failure")
             return False


Test patch:
Repository: Kinto/kinto

Issue:
Straighten out commit_veto situation
In https://github.com/Kinto/kinto-signer/issues/591, we discovered that failing requests do not necessarily abort the transaction. (Exceptions do, but non-exceptional responses with e.g. 503 status codes don't.) There seems to be some confusion about this throughout the codebase; for example see https://github.com/Kinto/kinto-signer/blob/master/kinto_signer/listeners.py#L23-L24. At some point it must have seemed like Pyramid's [commit_veto hook](https://docs.pylonsproject.org/projects/pyramid_tm/en/latest/#adding-a-commit-veto-hook) would solve this automatically for us, but actually rereading this I see that "By default, `pyramid_tm` does not configure a commit veto into the system; you must do it explicitly."

However, the docstring for our [notify_resource_events_before](https://github.com/Kinto/kinto/blob/master/kinto/core/events.py#L152) *claims* to be a commit veto hook, muddying the waters somewhat. This code was added in https://github.com/Kinto/kinto/pull/1263, when we discovered that running "before resource changed" events as a "before commit" hook was invalid and we had to figure out a better approach.

- It seems like at a very minimum, the docstring here is invalid. I believe this is not really a veto but rather just part of the events machinery. 
- Should there be a `commit_veto` hook? Personally I would find it surprising that 4xx/5xx responses always automatically abort the transaction, even if they were not driven by exceptions.



Discussion:

Resolving patch:
diff --git a/kinto/core/events.py b/kinto/core/events.py
--- a/kinto/core/events.py
+++ b/kinto/core/events.py
@@ -150,10 +150,12 @@ def __next__(self):
 
 
 def notify_resource_events_before(handler, registry):
-    """pyramid_tm "commit veto" hook to run ResourceChanged events.
+    """Tween that runs ResourceChanged events.
+
+    This tween runs under EXCVIEW, so exceptions raised by
+    ResourceChanged events are caught and dealt the same as any other
+    exceptions.
 
-    This hook being a "commit veto" let us tell pyramid_tm to abort
-    the transaction if the ResourceChanged listeners raise.
     """
 
     def tween(request):


Test patch:
Repository: Textualize/textual

Issue:
Lazy load Widgets
We have a `widgets` module that imports all the widgets. THis allows for easy imports like:

```python
from textual.widgets import DataTable, Button
```

The downside is that all widgets are imported even if you only need one, increasing startup time.

I think we should be able to do this lazily some how, possibly by implementing a module level `__getattr__`.


Discussion:

Resolving patch:
diff --git a/src/textual/widgets/__init__.py b/src/textual/widgets/__init__.py
--- a/src/textual/widgets/__init__.py
+++ b/src/textual/widgets/__init__.py
@@ -1,21 +1,41 @@
-from ._footer import Footer
-from ._header import Header
-from ._button import Button
-from ._placeholder import Placeholder
-from ._static import Static
-from ._tree_control import TreeControl, TreeClick, TreeNode, NodeID
-from ._directory_tree import DirectoryTree, FileClick
+from __future__ import annotations
+from importlib import import_module
+import typing
 
+from ..case import camel_to_snake
+
+if typing.TYPE_CHECKING:
+    from ..widget import Widget
+
+
+# ⚠️For any new built-in Widget we create, not only we have to add them to the following list, but also to the
+# `__init__.pyi` file in this same folder - otherwise text editors and type checkers won't be able to "see" them.
 __all__ = [
     "Button",
     "DirectoryTree",
-    "FileClick",
     "Footer",
     "Header",
     "Placeholder",
     "Static",
-    "TreeClick",
     "TreeControl",
-    "TreeNode",
-    "NodeID",
 ]
+
+
+_WIDGETS_LAZY_LOADING_CACHE: dict[str, type[Widget]] = {}
+
+# Let's decrease startup time by lazy loading our Widgets:
+def __getattr__(widget_class: str) -> type[Widget]:
+    try:
+        return _WIDGETS_LAZY_LOADING_CACHE[widget_class]
+    except KeyError:
+        pass
+
+    if widget_class not in __all__:
+        raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'")
+
+    widget_module_path = f"._{camel_to_snake(widget_class)}"
+    module = import_module(widget_module_path, package="textual.widgets")
+    class_ = getattr(module, widget_class)
+
+    _WIDGETS_LAZY_LOADING_CACHE[widget_class] = class_
+    return class_


Test patch:
Repository: Textualize/textual

Issue:
Grid cell margin issue
Adding margin: 1 to the cells within this grid causes unexpected output:

<img width="752" alt="image" src="https://user-images.githubusercontent.com/5740731/190180955-3b10bd1f-60ca-4fda-9473-bc7d9a325b9d.png">

## `grid_buttons.py`

```python
from textual.app import App, ComposeResult
from textual.widgets import Button


class GridButtons(App):
    def compose(self) -> ComposeResult:
        yield Button.success("A")
        yield Button.success("B")
        yield Button.success("C")
        yield Button.success("D")
        yield Button.success("E")
        yield Button.success("F")


app = GridButtons(css_path="grid_buttons.css")
if __name__ == '__main__':
    app.run()
```

## `grid_buttons.css`

```scss
Screen {
    layout: grid;
    grid-size: 3;
    grid-rows: 1fr;
    grid-columns: 1fr;
}

Button {
    margin: 1;
}
```


Discussion:

Resolving patch:
diff --git a/src/textual/layouts/grid.py b/src/textual/layouts/grid.py
--- a/src/textual/layouts/grid.py
+++ b/src/textual/layouts/grid.py
@@ -150,7 +150,7 @@ def repeat_scalars(scalars: Iterable[Scalar], count: int) -> list[Scalar]:
                 fraction_unit,
             )
             region = (
-                Region(x, y, int(width), int(height))
+                Region(x, y, int(width + margin.width), int(height + margin.height))
                 .shrink(margin)
                 .clip_size(cell_size)
             )


Test patch:
Repository: Textualize/textual

Issue:
A `Widget`-derived widget with `inherit_bindings=False`, but no `BINDINGS`, appears to still inherit bindings
This is *very* much related to #1343, but I think merits an issue of its own to consider first. The reasons *why* this happens seem clear enough, but I feel the setup may cause confusion. With Textual as it is of 0.6.0 (with the bindings for movement keys being on `Widget`), consider this widget:

```python
class Odradek( Widget, inherit_bindings=False ):
    pass
````

vs this:

```python
class Odradek( Widget, inherit_bindings=False ):
    BINDINGS = []
````

In the former case the bindings of `Widget` are still inherited. In the latter they're not.


Discussion:
Much the same issue as https://github.com/Textualize/textual/pull/1336
> Much the same issue as #1336

So, you are saying that https://github.com/Textualize/textual/blob/338d74cd4657087487e4c1208b80e6d042e95bb1/src/textual/dom.py#L232 should be `base.__dict__.get("BINDINGS", [])` instead of `base.BINDINGS`?
@davep I'll be happy to tackle this one.
Yup. Suspect that will do it.
> @davep I'll be happy to tackle this one.

If you do, likely best to *not* start building up tests for it as I've just popped one for this exactly situation into https://github.com/Textualize/textual/pull/1346 and there's going to be more to come, that aren't the same issue but potentially overlap.

Resolving patch:
diff --git a/src/textual/dom.py b/src/textual/dom.py
--- a/src/textual/dom.py
+++ b/src/textual/dom.py
@@ -229,7 +229,7 @@ def _merge_bindings(cls) -> Bindings:
             if issubclass(base, DOMNode):
                 if not base._inherit_bindings:
                     bindings.clear()
-                bindings.append(Bindings(base.BINDINGS))
+                bindings.append(Bindings(base.__dict__.get("BINDINGS", [])))
         keys = {}
         for bindings_ in bindings:
             keys.update(bindings_.keys)


Test patch:
diff --git a/tests/test_dom.py b/tests/test_dom.py
--- a/tests/test_dom.py
+++ b/tests/test_dom.py
@@ -45,6 +45,39 @@ def test_validate():
         node.toggle_class("1")
 
 
+def test_inherited_bindings():
+    """Test if binding merging is done correctly when (not) inheriting bindings."""
+    class A(DOMNode):
+        BINDINGS = [("a", "a", "a")]
+
+    class B(A):
+        BINDINGS = [("b", "b", "b")]
+
+    class C(B, inherit_bindings=False):
+        BINDINGS = [("c", "c", "c")]
+
+    class D(C, inherit_bindings=False):
+        pass
+
+    class E(D):
+        BINDINGS = [("e", "e", "e")]
+
+    a = A()
+    assert list(a._bindings.keys.keys()) == ["a"]
+
+    b = B()
+    assert list(b._bindings.keys.keys()) == ["a", "b"]
+
+    c = C()
+    assert list(c._bindings.keys.keys()) == ["c"]
+
+    d = D()
+    assert not list(d._bindings.keys.keys())
+
+    e = E()
+    assert list(e._bindings.keys.keys()) == ["e"]
+
+
 def test_get_default_css():
     class A(DOMNode):
         pass
Repository: Textualize/textual

Issue:
Support clearing columns via `DataTable.clear()`
Looks like this feature must have gotten lost in the shuffle, since the docstring mentions it but the function doesn't support it: https://github.com/Textualize/textual/blob/3aaa4d3ec1cfd1be86c781a34da09e6bc99e8eff/src/textual/widgets/_data_table.py#L315-L328

Happy to do a PR for this. Is it as simple as running `self.columns.clear()` if the `columns` argument is `True`?


Discussion:

Resolving patch:
diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py
--- a/src/textual/widgets/_data_table.py
+++ b/src/textual/widgets/_data_table.py
@@ -312,7 +312,7 @@ def _get_cell_region(self, row_index: int, column_index: int) -> Region:
         cell_region = Region(x, y, width, height)
         return cell_region
 
-    def clear(self) -> None:
+    def clear(self, columns: bool = False) -> None:
         """Clear the table.
 
         Args:
@@ -323,6 +323,8 @@ def clear(self) -> None:
         self._y_offsets.clear()
         self.data.clear()
         self.rows.clear()
+        if columns:
+            self.columns.clear()
         self._line_no = 0
         self._require_update_dimensions = True
         self.refresh()


Test patch:
diff --git a/tests/test_table.py b/tests/test_table.py
--- a/tests/test_table.py
+++ b/tests/test_table.py
@@ -1,5 +1,7 @@
 import asyncio
 
+from rich.text import Text
+
 from textual.app import App, ComposeResult
 from textual.widgets import DataTable
 
@@ -18,13 +20,32 @@ async def test_table_clear() -> None:
         table.add_columns("foo", "bar")
         assert table.row_count == 0
         table.add_row("Hello", "World!")
+        assert [col.label for col in table.columns] == [Text("foo"), Text("bar")]
         assert table.data == {0: ["Hello", "World!"]}
         assert table.row_count == 1
         table.clear()
+        assert [col.label for col in table.columns] == [Text("foo"), Text("bar")]
         assert table.data == {}
         assert table.row_count == 0
 
 
+async def test_table_clear_with_columns() -> None:
+    """Check DataTable.clear(columns=True)"""
+
+    app = TableApp()
+    async with app.run_test() as pilot:
+        table = app.query_one(DataTable)
+        table.add_columns("foo", "bar")
+        assert table.row_count == 0
+        table.add_row("Hello", "World!")
+        assert [col.label for col in table.columns] == [Text("foo"), Text("bar")]
+        assert table.data == {0: ["Hello", "World!"]}
+        assert table.row_count == 1
+        table.clear(columns=True)
+        assert [col.label for col in table.columns] == []
+        assert table.data == {}
+        assert table.row_count == 0
+
 async def test_table_add_row() -> None:
 
     app = TableApp()
Repository: Textualize/textual

Issue:
Some scrollbar color styles have no effect
The rules `scrollbar_background_active` and `scrollbar_color_hover` do not affect the way a scrollbar looks like.

Run the app below and notice that you can't make the scrollbar background red when you drag it, nor can you turn the thumb pink when you hover it.

```py
from textual.app import App
from textual.widgets import Label

TEXT = """I must not fear.
Fear is the mind-killer.
Fear is the little-death that brings total obliteration.
I will face my fear.
I will permit it to pass over me and through me.
And when it has gone past, I will turn the inner eye to see its path.
Where the fear has gone there will be nothing. Only I will remain.
"""

_CSS = """
Screen {
    scrollbar-background-active: red;
    scrollbar-background-hover: purple;
    scrollbar-color-active: yellow;
    scrollbar-color-hover: pink;
}
"""

class ScrollbarActiveApp(App):
    CSS = _CSS
    def compose(self):
        yield Label(TEXT * 10)
```


Discussion:
Thank you for your issue. Give us a little time to review it.

PS. You might want to check the [FAQ](https://github.com/textualize/textual/blob/main/FAQ.md) if you haven't done so already.

This is an automated reply, generated by [FAQtory](https://github.com/willmcgugan/faqtory)

Resolving patch:
diff --git a/src/textual/scrollbar.py b/src/textual/scrollbar.py
--- a/src/textual/scrollbar.py
+++ b/src/textual/scrollbar.py
@@ -225,14 +225,15 @@ def __rich_repr__(self) -> rich.repr.Result:
 
     def render(self) -> RenderableType:
         styles = self.parent.styles
-        background = (
-            styles.scrollbar_background_hover
-            if self.mouse_over
-            else styles.scrollbar_background
-        )
-        color = (
-            styles.scrollbar_color_active if self.grabbed else styles.scrollbar_color
-        )
+        if self.grabbed:
+            background = styles.scrollbar_background_active
+            color = styles.scrollbar_color_active
+        elif self.mouse_over:
+            background = styles.scrollbar_background_hover
+            color = styles.scrollbar_color_hover
+        else:
+            background = styles.scrollbar_background
+            color = styles.scrollbar_color
         color = background + color
         scrollbar_style = Style.from_color(color.rich_color, background.rich_color)
         return ScrollBarRender(
diff --git a/src/textual/widget.py b/src/textual/widget.py
--- a/src/textual/widget.py
+++ b/src/textual/widget.py
@@ -190,8 +190,10 @@ class Widget(DOMNode):
     Widget{
         scrollbar-background: $panel-darken-1;
         scrollbar-background-hover: $panel-darken-2;
+        scrollbar-background-active: $panel-darken-3;
         scrollbar-color: $primary-lighten-1;
         scrollbar-color-active: $warning-darken-1;
+        scrollbar-color-hover: $primary-lighten-1;
         scrollbar-corner-color: $panel-darken-1;
         scrollbar-size-vertical: 2;
         scrollbar-size-horizontal: 1;


Test patch:
Repository: Textualize/textual

Issue:
Change Clock color
Following on from #1411, perhaps the clock colour needs a wee revisit too?

![Screenshot 2022-12-31 at 10 04 46](https://user-images.githubusercontent.com/28237/210132768-00166ecf-0bf3-4486-bc7f-09cc52d46b21.png)



Discussion:
Thank you for your issue. Give us a little time to review it.

PS. You might want to check the [FAQ](https://github.com/textualize/textual/blob/main/FAQ.md) if you haven't done so already.

This is an automated reply, generated by [FAQtory](https://github.com/willmcgugan/faqtory)

Resolving patch:
diff --git a/src/textual/widgets/_header.py b/src/textual/widgets/_header.py
--- a/src/textual/widgets/_header.py
+++ b/src/textual/widgets/_header.py
@@ -45,7 +45,7 @@ class HeaderClock(HeaderClockSpace):
 
     DEFAULT_CSS = """
     HeaderClock {
-        background: $secondary-background-lighten-1;
+        background: $foreground-darken-1 5%;
         color: $text;
         text-opacity: 85%;
         content-align: center middle;
@@ -97,7 +97,7 @@ class Header(Widget):
     }
     Header.-tall {
         height: 3;
-    }    
+    }
     """
 
     tall = Reactive(False)


Test patch: