internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: holoviz/panel

Issue:
Race Condition with threaded Periodic Callback can result in additional executions
#### ALL software version info

panel==1.2.1

#### Description of expected behavior and the observed behavior

Looks like due to a race condition, by scheduling a "heavy" periodic callback, it can be executed more than the maximum count when letting panel handle the multithreading. This is because, I believe, the counter is incremented after the callback is finished executing, and with multiple threads many instances can be scheduled while waiting for the count to be met.

In the below example, when you toggle on the periodic with a 0 delay it runs as expected, but increasing the delay beyond the period will result in additional executions of the callback. The larger the delay the worse the effect.

#### Complete, minimal, self-contained example code that reproduces the issue

```python
# app.py
import time
import panel as pn
pn.extension(nthreads=0)  # or > 1

def heavy():
    print(cb.counter)
    time.sleep(delay.value)  # simulate lots of work

delay = pn.widgets.IntInput(name='Delay', value=0, start=0, end=5, step=1)

cb = pn.state.add_periodic_callback(heavy, 200, count=5, start=False)
toggle = pn.widgets.Toggle(name='Run', value=False)
toggle.link(cb, bidirectional=True, value='running')

pn.Column(delay, toggle).servable()
```

Run with:
```shell
panel serve app.py
```

#### Stack traceback and/or browser JavaScript console output

N/A

#### Screenshots or screencasts of the bug in action

N/A


Discussion:
Feel free to assign to me, I will dive into this tonight.

Resolving patch:
diff --git a/panel/io/callbacks.py b/panel/io/callbacks.py
--- a/panel/io/callbacks.py
+++ b/panel/io/callbacks.py
@@ -82,7 +82,11 @@ def _exec_callback(self, post=False):
         from .state import set_curdoc
         try:
             with set_curdoc(self._doc):
-                cb = self.callback()
+                if self.running:
+                    self.counter += 1
+                    if self.counter > self.count:
+                        self.stop()
+                cb = self.callback() if self.running else None
         except Exception:
             cb = None
         if post:
@@ -98,7 +102,6 @@ def _post_callback(self):
         if not self._background:
             with edit_readonly(state):
                 state._busy_counter -= 1
-        self.counter += 1
         if self.timeout is not None:
             dt = (time.time() - self._start_time) * 1000
             if dt > self.timeout:


Test patch:
Repository: holoviz/panel

Issue:
Basic Auth does not use Panel favicon or color
I'm on the current Panel `main` branch. I wanted to try out basic auth.

```
panel serve script.py --basic-auth my_password --cookie-secret my_super_safe_cookie_secret
```

But it does not use the Panel favicon or blue color for the Button. This makes it look like a half finished solution.

Personally I don't understand why you want to expose a link to what for the users of your app is complicated documentation of auth. That is just confusing and information overload.

![image](https://github.com/holoviz/panel/assets/42288570/1a757cc4-959a-44b2-ba55-257f5293b131)



Discussion:

Resolving patch:
diff --git a/panel/auth.py b/panel/auth.py
--- a/panel/auth.py
+++ b/panel/auth.py
@@ -869,7 +869,7 @@ def post(self):
             next_url = self.get_cookie("next_url", "/")
             self.redirect(next_url)
         else:
-            error_msg = "?error=" + tornado.escape.url_escape("Login incorrect")
+            error_msg = "?error=" + tornado.escape.url_escape("Invalid username or password!")
             self.redirect(self.request.uri + error_msg)
 
     def set_current_user(self, user):


Test patch:
Repository: holoviz/panel

Issue:
--autoreload does not work in Panel 1.2.2
Run this code with `panel serve --autoreload tmp.py` and change the end to 2 the 

``` python
# tmp.py
import panel as pn

pn.widgets.IntSlider(end=1).servable()
```

A git bisect indicates https://github.com/holoviz/panel/pull/5344 is the culprit. 


Discussion:

Resolving patch:
diff --git a/panel/io/callbacks.py b/panel/io/callbacks.py
--- a/panel/io/callbacks.py
+++ b/panel/io/callbacks.py
@@ -84,7 +84,7 @@ def _exec_callback(self, post=False):
             with set_curdoc(self._doc):
                 if self.running:
                     self.counter += 1
-                    if self.counter > self.count:
+                    if self.count is not None and self.counter > self.count:
                         self.stop()
                 cb = self.callback() if self.running else None
         except Exception:


Test patch:
diff --git a/panel/tests/ui/command/test_serve.py b/panel/tests/ui/command/test_serve.py
new file mode 100644
--- /dev/null
+++ b/panel/tests/ui/command/test_serve.py
@@ -0,0 +1,36 @@
+import os
+import time
+
+import pytest
+
+from panel.tests.util import (
+    run_panel_serve, unix_only, wait_for_port, write_file,
+)
+
+try:
+    from playwright.sync_api import expect
+    pytestmark = pytest.mark.ui
+except ImportError:
+    pytestmark = pytest.mark.skip('playwright not available')
+
+
+@unix_only
+def test_autoreload_app(py_file, port, page):
+    app = "import panel as pn; pn.Row('Example 1').servable()"
+    app2 = "import panel as pn; pn.Row('Example 2').servable()"
+    write_file(app, py_file.file)
+
+    app_name = os.path.basename(py_file.name)[:-3]
+
+    with run_panel_serve(["--port", str(port), '--autoreload', py_file.name]) as p:
+        port = wait_for_port(p.stdout)
+        time.sleep(0.2)
+
+        page.goto(f"http://localhost:{port}/{app_name}")
+        expect(page.locator(".markdown")).to_have_text("Example 1")
+
+        # Timeout to ensure websocket is initialized
+        time.sleep(1.0)
+
+        write_file(app2, py_file.file)
+        expect(page.locator(".markdown")).to_have_text('Example 2')
Repository: holoviz/panel

Issue:
Improve error on invalid serve URL
The following simple app:

```python
import panel as pn
pn.extension()
pn.serve({"/spam/alot/": "Spam!"})
```

fails like this:
```
Launching server at http://localhost:49227
2023-10-07 14:01:16,537 404 GET /spam/static/js/bokeh.min.js?v=42698ba71b55a4634cf5e5295f093fe1788c0e0490180931b0805da09afea8a1250e1dc5138d8a90816cd53eb0749cc3eb145e7d9599734fcfb037e9ec223efd (::1) 0.42ms
2023-10-07 14:01:16,540 404 GET /spam/static/js/bokeh-gl.min.js?v=bb6b0349fc67ef87c67e017bb1124d47d870b3e58a6eece0f2a2ebd0485412e64def06faf8764c9157add17d41de5fe4dd33e9126b17c11cdf7bd6691d68f379 (::1) 0.31ms
2023-10-07 14:01:16,540 404 GET /spam/static/extensions/panel/panel.min.js?v=fb7e691caef7a59ca25d1fd9580b7a7d13146fd012a16bf047f631f7bf8a1326 (::1) 0.35ms
2023-10-07 14:01:16,541 404 GET /spam/static/js/bokeh-widgets.min.js?v=ddb73df6eae93f1df236ed7e56f58298ebb768a4ed15b068d68a2c492100a71fbf50245d6e4516a69de4f3665bf8cef661d4b1dcf756eea3804c58169fb0fb15 (::1) 0.43ms
2023-10-07 14:01:16,541 404 GET /spam/static/js/bokeh-tables.min.js?v=2627454bb0563a61287a353dcdbd4870dcd6f4cda89abca94325f271f910e04044091d74651ab12316c9b6260cd4d7c3765be89ac62e4e35166ea4ca9c564c6c (::1) 0.26ms
2023-10-07 14:01:16,548 WebSocket connection opened
2023-10-07 14:01:16,548 ServerConnection created
2023-10-07 14:01:16,569 404 GET /spam/static/extensions/panel/images/favicon.ico (::1) 0.19ms
```

As pointed out by @philippjfr  in the thread https://github.com/holoviz/panel/issues/5576#issuecomment-1751694610  the problem is the trailing slash `/`, after removing it the app works as intended.

I think if it's (a) really the case that Bokeh can never serve such URLs and (b) there is a robust way and clear place to put the URL validation logic, then it would be nice if you could give a better error massage here, e.g. something like a "ValueError: invalid URL - trailing slash / not supported".


Discussion:

Resolving patch:
diff --git a/panel/io/server.py b/panel/io/server.py
--- a/panel/io/server.py
+++ b/panel/io/server.py
@@ -1080,6 +1080,8 @@ def get_server(
     if isinstance(panel, dict):
         apps = {}
         for slug, app in panel.items():
+            if slug.endswith('/') and not slug == '/':
+                raise ValueError(f"Invalid URL: trailing slash '/' used for {slug!r} not supported.")
             if isinstance(title, dict):
                 try:
                     title_ = title[slug]


Test patch:
Repository: holoviz/panel

Issue:
`pn.widgets.EditableFloatSlider` format not always working
When creating an `EditableFloatSlider` and slowly dragging the slider, it does not always follow the defined formatting. 

This is a silent issue and does not produce any errors neither in python nor in javascript.

```python
import panel as pn
pn.extension()

pn.widgets.EditableFloatSlider(
            name='Threhshold', 
            start=0,
            end=5,
            step=0.01,
            value=3.5,
            format='1[.]0'
            )
```

![chrome-capture-2023-6-19](https://github.com/holoviz/panel/assets/31830274/03e1bb1b-3172-4fed-8f7b-37f3c68fe1ad)



Discussion:
I'd like to chime in here and say that the formatter doesn't work on the `EditableFloatSlider` but it does work on the `EditableRangeSlider` using the same steps:

```python
import numpy as np
import panel as pn
from bokeh.models.formatters import NumeralTickFormatter

pn.extension()

pn.serve(
    pn.Row(
        pn.widgets.EditableFloatSlider(
            start=0,
            end=np.pi,
            step=0.111111,
            value=0.3,
            format=NumeralTickFormatter(format='0.00'),
        ),
        pn.widgets.EditableRangeSlider(
            start=0,
            end=np.pi,
            step=0.111111,
            value=(0.3, 0.4),
            format=NumeralTickFormatter(format='0.00'),
        )
    )
)
```

And here's the screenshot:

![image](https://github.com/holoviz/panel/assets/14017872/c524f11e-4346-4f7a-9acd-4789ec501559)


Resolving patch:
diff --git a/panel/widgets/slider.py b/panel/widgets/slider.py
--- a/panel/widgets/slider.py
+++ b/panel/widgets/slider.py
@@ -813,7 +813,8 @@ def __init__(self, **params):
 
         self._value_edit = self._input_widget(
             margin=0, align='end', css_classes=['slider-edit'],
-            stylesheets=[f'{CDN_DIST}css/editable_slider.css']
+            stylesheets=[f'{CDN_DIST}css/editable_slider.css'],
+            format=self.format,
         )
         self._value_edit.param.watch(self._sync_value, 'value')
         self._value_edit.param.watch(self._sync_value, 'value_throttled')


Test patch:
Repository: holoviz/panel

Issue:
`state.access_token` ignores new tokens acquired from refresh
#### ALL software version info
(this library, plus any other relevant software, e.g. bokeh, python, notebook, OS, browser, etc)

Version 1.2.3

#### Description of expected behavior and the observed behavior

Expected behavior: 

When a user connects with an expired oauth access token, a new access token is should be acquired using the refresh token and
made available via `state.access_token`.

Observed behavior:

When a user connects with an expired oauth access token, a new access token is acquired using the refresh token. However,
when attempting to access this access token via `state.access_token`, `None` is returned, as the code is only looking at
the original expired access token, not the new one that was refreshed.

#### 

- [x] I may be interested in making a pull request to address this



Discussion:

Resolving patch:
diff --git a/panel/io/state.py b/panel/io/state.py
--- a/panel/io/state.py
+++ b/panel/io/state.py
@@ -904,7 +904,7 @@ def access_token(self) -> str | None:
         """
         Returns the OAuth access_token if enabled.
         """
-        if self.user in self._oauth_user_overrides and 'refresh_token' in self._oauth_user_overrides:
+        if self.user in self._oauth_user_overrides and 'access_token' in self._oauth_user_overrides[self.user]:
             return self._oauth_user_overrides[self.user]['access_token']
         access_token = self._decode_cookie('access_token')
         if not access_token:


Test patch:
Repository: holoviz/panel

Issue:
Document pn.extension
I'm on Panel 0.13.0.

If I search the Panel web site I cannot find a reference page or other material documenting `pn.extension`. 

Besides `import panel as pn` this is the most used Panel command, so I believe it should be documented. There are so many things you can do with this command.


Discussion:
I agree. But I would hold on for now on this one. One of the goals for the next release is a documentation overhaul, we'll have to decide the extent of this overhaul and how to reorganize the documentation (between ref guides,  howtos, etc.).
Hi all,

I am wondering if there is any update to having full documentation of pn.extension? The closest I can find is on this [page](https://panel.holoviz.org/api/panel.config.html#panel.config.panel_extension) and it refers here. Hoping to get more insight into usage of it. Thanks!

Resolving patch:
diff --git a/panel/config.py b/panel/config.py
--- a/panel/config.py
+++ b/panel/config.py
@@ -219,7 +219,7 @@ class _config(_base_config):
     throttled = param.Boolean(default=False, doc="""
         If sliders and inputs should be throttled until release of mouse.""")
 
-    _admin = param.Boolean(default=False, doc="Whether the admin panel was enabled.")
+    _admin = param.Boolean(default=False, doc="Whether the admin panel is enabled.")
 
     _admin_endpoint = param.String(default=None, doc="Name to use for the admin endpoint.")
 
@@ -263,8 +263,8 @@ class _config(_base_config):
     _npm_cdn = param.Selector(default='https://cdn.jsdelivr.net/npm',
         objects=['https://unpkg.com', 'https://cdn.jsdelivr.net/npm'],  doc="""
         The CDN to load NPM packages from if resources are served from
-        CDN. Allows switching between https://unpkg.com and
-        https://cdn.jsdelivr.net/npm for most resources.""")
+        CDN. Allows switching between [https://unpkg.com](https://unpkg.com) and
+        [https://cdn.jsdelivr.net/npm](https://cdn.jsdelivr.net/npm) for most resources.""")
 
     _nthreads = param.Integer(default=None, doc="""
         When set to a non-None value a thread pool will be started.
@@ -474,6 +474,10 @@ def _template_hook(self, value):
     def _doc_build(self):
         return os.environ.get('PANEL_DOC_BUILD')
 
+    @property
+    def admin(self):
+        return self._admin
+
     @property
     def admin_endpoint(self):
         return os.environ.get('PANEL_ADMIN_ENDPOINT', self._admin_endpoint)
@@ -635,7 +639,14 @@ class panel_extension(_pyviz_extension):
     - Update the global configuration `pn.config`
     (keyword arguments).
 
-    Reference: https://github.com/holoviz/panel/issues/3404
+    Parameters
+    ----------
+    *args : list[str]
+        Positional arguments listing the extension to load. For example "plotly",
+        "tabulator".
+    **params : dict[str,Any]
+        Keyword arguments to be set on the `pn.config` element. See
+        https://panel.holoviz.org/api/config.html
 
     :Example:
 


Test patch:
Repository: holoviz/panel

Issue:
find_requirements includes datetime and random
I'm on the current `main` branch of Panel.

When I use `find_requirements` like below I get "packages" included like `datetime` and `random` from the `stdlib`.

```python
from panel.io.convert import find_requirements
code = """
import panel as pn
import pandas as pd

import random
from datetime import datetime, timedelta
"""

requirements = find_requirements(code)
print(requirements)
```

```bash
$ python app.py
['datetime', 'pandas', 'panel', 'random']
```


Discussion:

Resolving patch:
diff --git a/panel/io/mime_render.py b/panel/io/mime_render.py
--- a/panel/io/mime_render.py
+++ b/panel/io/mime_render.py
@@ -34,6 +34,8 @@
 #---------------------------------------------------------------------
 
 def _stdlibs():
+    if sys.version_info[:2] >= (3, 10):
+        return sys.stdlib_module_names
     env_dir = str(pathlib.Path(sys.executable).parent.parent)
     modules = list(sys.builtin_module_names)
     for m in pkgutil.iter_modules():


Test patch:
diff --git a/panel/tests/io/test_mime_render.py b/panel/tests/io/test_mime_render.py
--- a/panel/tests/io/test_mime_render.py
+++ b/panel/tests/io/test_mime_render.py
@@ -33,6 +33,8 @@ def test_find_imports_stdlibs():
     import os
     import base64
     import pathlib
+    import random
+    from datetime import datetime, timedelta
     """
     assert find_requirements(code) == []
Repository: holoviz/panel

Issue:
Plotting styling guides are gone
As discussed on Discourse the styling gallery notebooks for Plotly, Altair, Seaborn and Matplotlib have gone missing with Panel 1.0 release.

Please re-add. Thx.


Discussion:

Resolving patch:
diff --git a/panel/models/echarts.py b/panel/models/echarts.py
--- a/panel/models/echarts.py
+++ b/panel/models/echarts.py
@@ -62,4 +62,4 @@ def __js_skip__(cls):
 
     renderer = Enum("canvas", "svg")
 
-    theme = Enum("default", "light", "dark")
+    theme = String("default")


Test patch:
Repository: holoviz/panel

Issue:
Make FileInput Button adhere to the design
``` python
import panel as pn

pn.extension(design="bootstrap")

file_input_stylesheet = """
input[type="file"].bk-input {
  padding-left: 10px;
}
input[type="file"]::file-selector-button {
  background: var(--surface-color);
  color: var(--surface-text-color);
}
"""

pn.widgets.FileInput().servable()
pn.widgets.Button(name="Button").servable()
pn.widgets.FileInput(stylesheets=[file_input_stylesheet]).servable()
```

![image](https://github.com/holoviz/panel/assets/19758978/67cd5853-d24e-4aa9-a3c3-773c4bf11ef5)



Discussion:

Resolving patch:
diff --git a/panel/widgets/input.py b/panel/widgets/input.py
--- a/panel/widgets/input.py
+++ b/panel/widgets/input.py
@@ -10,8 +10,8 @@
 from base64 import b64decode
 from datetime import date, datetime
 from typing import (
-    TYPE_CHECKING, Any, ClassVar, Dict, Iterable, Mapping, Optional, Tuple,
-    Type,
+    TYPE_CHECKING, Any, ClassVar, Dict, Iterable, List, Mapping, Optional,
+    Tuple, Type,
 )
 
 import numpy as np
@@ -27,6 +27,7 @@
 )
 
 from ..config import config
+from ..io.resources import CDN_DIST
 from ..layout import Column, Panel
 from ..models import (
     DatetimePicker as _bkDatetimePicker, TextAreaInput as _bkTextAreaInput,
@@ -195,6 +196,8 @@ class FileInput(Widget):
 
     _widget_type: ClassVar[Type[Model]] = _BkFileInput
 
+    _stylesheets: ClassVar[List[str]] = [f'{CDN_DIST}css/button.css']
+
     def _process_param_change(self, msg):
         msg = super()._process_param_change(msg)
         if 'value' in msg:


Test patch:
Repository: holoviz/panel

Issue:
Perspective toggle_config not working
I've been used to using Perspectives `toggle_config` parameter. After upgrade to 1.4.0 it no longer works on instantiation.

This can also be seen in the reference guide

![image](https://github.com/holoviz/panel/assets/42288570/895a806d-9848-49f5-b567-dca5ac9d7cd7)

After some inspection of the code base I can see a new `settings` parameter was introduced up to 1.4.0 and this is shadowing the `toggle_config` parameter.

Both parameters are mentioned (in different ways) in the reference documentation. But they do the same thing.

![image](https://github.com/holoviz/panel/assets/42288570/600263f9-4744-45a9-8d9b-bea943923a1c)

Only the `settings` parameter should be available. The `toggle_config` parameter needs to be removed.


Discussion:

Resolving patch:
diff --git a/panel/models/perspective.py b/panel/models/perspective.py
--- a/panel/models/perspective.py
+++ b/panel/models/perspective.py
@@ -76,8 +76,6 @@ class Perspective(HTMLBox):
 
     source = Instance(ColumnDataSource)
 
-    toggle_config = Bool(True)
-
     theme = Enum(*PERSPECTIVE_THEMES, default="pro")
 
     title = Either(String(), Null())
diff --git a/panel/pane/perspective.py b/panel/pane/perspective.py
--- a/panel/pane/perspective.py
+++ b/panel/pane/perspective.py
@@ -314,9 +314,6 @@ class Perspective(ModelPane, ReactiveData):
     settings = param.Boolean(default=True, doc="""
       Whether to show the settings menu.""")
 
-    toggle_config = param.Boolean(default=True, doc="""
-      Whether to show the config menu.""")
-
     theme = param.ObjectSelector(default='pro', objects=THEMES, doc="""
       The style of the PerspectiveViewer. For example pro-dark""")
 
@@ -382,10 +379,6 @@ def _get_properties(self, doc, source=None):
         if 'theme' in props and 'material' in props['theme']:
             props['theme'] = props['theme'].replace('material', 'pro')
         del props['object']
-        if props.get('toggle_config'):
-            props['height'] = self.height or 300
-        else:
-            props['height'] = self.height or 150
         if source is None:
             source = ColumnDataSource(data=self._data)
         else:


Test patch:
Repository: statsmodels/statsmodels

Issue:
Pandas: Not checking whether endog and exog indices conform
``` python
import statsmodels.api as sm
from pandas import DataFrame

d = sm.datasets.macrodata.load_pandas().data
#growth rates
gs_l_realinv = 400 * np.log(d['realinv']).diff().dropna()
gs_l_realgdp = 400 * np.log(d['realgdp']).diff().dropna()
lint = d['realint'][:-1] # incorrect indexing as example

endog = gs_l_realinv

# re-index because they won't conform to lint
realgdp = gs_l_realgdp.reindex(lint.index, method='bfill')
data = dict(const=np.ones_like(lint), lrealgdp=realgdp, lint=lint)
exogg = DataFrame(data)

# which index do we get??
res = OLS(endog, exogg).fit()
```



Discussion:

Resolving patch:
diff --git a/statsmodels/base/data.py b/statsmodels/base/data.py
--- a/statsmodels/base/data.py
+++ b/statsmodels/base/data.py
@@ -140,6 +140,16 @@ class PandasData(ModelData):
     Data handling class which knows how to reattach pandas metadata to model
     results
     """
+    def _check_integrity(self):
+        try:
+            endog, exog = self._orig_endog, self._orig_exog
+            # exog can be None and we could be upcasting one or the other
+            if exog is not None and (hasattr(endog, 'index') and
+                    hasattr(exog, 'index')):
+                assert self._orig_endog.index.equals(self._orig_exog.index)
+        except AssertionError:
+            raise ValueError("The indices for endog and exog are not aligned")
+        super(PandasData, self)._check_integrity()
 
     def _get_row_labels(self, arr):
         try:


Test patch:
diff --git a/statsmodels/base/tests/test_data.py b/statsmodels/base/tests/test_data.py
--- a/statsmodels/base/tests/test_data.py
+++ b/statsmodels/base/tests/test_data.py
@@ -385,6 +385,28 @@ def test_endogexog(self):
         np.testing.assert_equal(self.data.endog, self.endog.values.squeeze())
         np.testing.assert_equal(self.data.exog, self.exog.values[:,None])
 
+def test_alignment():
+    """
+    Fix Issue #206
+    """
+    from statsmodels.regression.linear_model import OLS
+    from statsmodels.datasets.macrodata import load_pandas
+
+    d = load_pandas().data
+    #growth rates
+    gs_l_realinv = 400 * np.log(d['realinv']).diff().dropna()
+    gs_l_realgdp = 400 * np.log(d['realgdp']).diff().dropna()
+    lint = d['realint'][:-1] # incorrect indexing for test purposes
+
+    endog = gs_l_realinv
+
+    # re-index because they won't conform to lint
+    realgdp = gs_l_realgdp.reindex(lint.index, method='bfill')
+    data = dict(const=np.ones_like(lint), lrealgdp=realgdp, lint=lint)
+    exog = pandas.DataFrame(data)
+
+    # which index do we get??
+    np.testing.assert_raises(ValueError, OLS, *(endog, exog))
 
 class TestMultipleEqsArrays(TestArrays):
     @classmethod