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

Issue:
Scheduler runs Queued tasks immediately instead of start_time setting
Please verify scheduler.py. Default of Next_run_time is now. 
Line 1125, 
all_available = db( ... &     (st.next_run_time <= now) &   ...)
, lacks of start_time constrain and will always make queued tasks were run immediately.



Discussion:
yep, the query has changed. I was refactoring the scheduler and left out this part, that will be taken care of with a slight modification on the queue_task function. a PR is on the way


Resolving patch:
diff --git a/gluon/scheduler.py b/gluon/scheduler.py
--- a/gluon/scheduler.py
+++ b/gluon/scheduler.py
@@ -1499,6 +1499,8 @@ def queue_task(self, function, pargs=[], pvars={}, **kwargs):
                 kwargs.update(start_time=start_time, next_run_time=next_run_time)
             except:
                 pass
+        if 'start_time' in kwargs and 'next_run_time' not in kwargs:
+            kwargs.update(next_run_time=kwargs['start_time'])
         rtn = self.db.scheduler_task.validate_and_insert(**kwargs)
         if not rtn.errors:
             rtn.uuid = tuuid


Test patch:
Repository: web2py/web2py

Issue:
Auth messages: unable_send_email vs. unable_to_send_email
Is there any reason to have both messages? They have the same value by default ("Unable to send email") (see [tools.py:1576](https://github.com/web2py/web2py/blob/59315c874de729c3d52904c0e5aa425157b1a726/gluon/tools.py#L1576)) but the code sometimes uses the former and sometimes the later.



Discussion:
it's probably a typo that needs fixing.


Resolving patch:
diff --git a/gluon/tools.py b/gluon/tools.py
--- a/gluon/tools.py
+++ b/gluon/tools.py
@@ -12,9 +12,11 @@
 
 import base64
 from functools import reduce
-from gluon._compat import pickle, thread, urllib2, Cookie, StringIO, configparser, MIMEBase, MIMEMultipart, \
-                          MIMEText, Encoders, Charset, long, urllib_quote, iteritems, to_bytes, to_native, add_charset, \
-                          charset_QP, basestring, unicodeT, to_unicode
+from gluon._compat import pickle, thread, urllib2, Cookie, StringIO
+from gluon._compat import configparser, MIMEBase, MIMEMultipart, MIMEText
+from gluon._compat import Encoders, Charset, long, urllib_quote, iteritems
+from gluon._compat import to_bytes, to_native, add_charset
+from gluon._compat import charset_QP, basestring, unicodeT, to_unicode
 import datetime
 import logging
 import sys
@@ -40,8 +42,9 @@
 from gluon.fileutils import read_file, check_credentials
 from gluon import *
 from gluon.contrib.autolinks import expand_one
-from gluon.contrib.markmin.markmin2html import \
-    replace_at_urls, replace_autolinks, replace_components
+from gluon.contrib.markmin.markmin2html import replace_at_urls
+from gluon.contrib.markmin.markmin2html import replace_autolinks
+from gluon.contrib.markmin.markmin2html import replace_components
 from pydal.objects import Row, Set, Query
 
 import gluon.serializers as serializers
@@ -1578,7 +1581,6 @@ class Auth(object):
         logged_out='Logged out',
         registration_successful='Registration successful',
         invalid_email='Invalid email',
-        unable_send_email='Unable to send email',
         invalid_login='Invalid login',
         invalid_user='Invalid user',
         invalid_password='Invalid password',
@@ -3633,7 +3635,7 @@ def reset_password_deprecated(self,
                                          message=self.messages.retrieve_password % dict(password=password)):
                 session.flash = self.messages.email_sent
             else:
-                session.flash = self.messages.unable_to_send_email
+                session.flash = self.messages.unable_send_email
             self.log_event(log, user)
             callback(onaccept, form)
             if not next:
@@ -3930,7 +3932,7 @@ def request_reset_password(self,
             if self.email_reset_password(user):
                 session.flash = self.messages.email_sent
             else:
-                session.flash = self.messages.unable_to_send_email
+                session.flash = self.messages.unable_send_email
             self.log_event(log, user)
             callback(onaccept, form)
             if not next:


Test patch:
Repository: web2py/web2py

Issue:
using web2py with Passenger
I'm using web2py on [Dreamhost ](https://www.dreamhost.com/)with the recommended [Phusion Passenger](https://www.phusionpassenger.com/) as the  deployment web server.  I configured the web2py [handlers/wsgihandler.py](https://github.com/web2py/web2py/blob/master/handlers/wsgihandler.py) as recommended by Dreamhost users (adding lines to launch python in a virtual environment), creating passenger_wsgi.py.  With just these edits, Passenger reported a timeout error from the application (web2py).  

The Passenger [debugging startup page](https://github.com/phusion/passenger/wiki/Debugging-application-startup-problems) notes that Passenger uses stdout for communication with the application and assumes that it is not "closed, overwritten, or redirected" by the application.  

Web2py overwrites stdout with stderr on line 31 in wsgihandler.py.  When I comment out this line, web2py (and Passenger) startup just fine and seem to work, although I haven't done much testing beyond startup.

So, my question is, is this line necessary?  If so, is there a fix to make this setup work properly?  If web2py requires both file descriptors pointing to the same place, maybe set stderr = stdout instead?



Discussion:
@mdipierro : any insights on why https://github.com/web2py/web2py/blob/master/handlers/wsgihandler.py#L35 is stricly needed ?

Yes. For Google App Engine.

ahem. why do we have a gaehandler.py then ?! :D

You are right. I guess it is not critically necessary. We could remove it.


Resolving patch:
diff --git a/handlers/wsgihandler.py b/handlers/wsgihandler.py
--- a/handlers/wsgihandler.py
+++ b/handlers/wsgihandler.py
@@ -7,22 +7,16 @@
 License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
 
 
-This is a WSGI handler for Apache
-Requires apache+mod_wsgi.
-
-In httpd.conf put something like:
-
-    LoadModule wsgi_module modules/mod_wsgi.so
-    WSGIScriptAlias / /path/to/wsgihandler.py
-
+This is a WSGI handler
 """
 
+import sys
+import os
+
 # change these parameters as required
 LOGGING = False
 SOFTCRON = False
 
-import sys
-import os
 
 path = os.path.dirname(os.path.abspath(__file__))
 os.chdir(path)
@@ -32,8 +26,6 @@
 
 sys.path = [path] + [p for p in sys.path if not p == path]
 
-sys.stdout = sys.stderr
-
 import gluon.main
 
 if LOGGING:


Test patch:
Repository: web2py/web2py

Issue:
autocomlete widget fix
``` diff
diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py
index 6adc4d1..097c737 100644
--- a/gluon/sqlhtml.py
+++ b/gluon/sqlhtml.py
@@ -736,7 +736,7 @@ class AutocompleteWidget(object):
         if self.is_reference:
             key2 = self.keyword + '_aux'
             key3 = self.keyword + '_auto'
-            attr['_class'] = 'string'
+            attr['_class'] = 'string form-control'
             name = attr['_name']
             if 'requires' in attr:
                 del attr['requires']
```



Discussion:
@RekGRpth : What is fixing by this patch exactly?

It is fix displaying autocomplete widget in forms

This isn't really a bug or issue, if you want to adapt the AutocompleteWidget to bootstrap you can subclass it or add the form-control class manually.

Considering Leonel explanation that this issue should be closed.

@leonelcamara , @BuhtigithuB : I don't really have time to test but is AutocompleteWidget correctly shown with "bootstrap formstyles" ? if anyone confirms it, I'll close this.


Resolving patch:
diff --git a/gluon/sqlhtml.py b/gluon/sqlhtml.py
--- a/gluon/sqlhtml.py
+++ b/gluon/sqlhtml.py
@@ -875,7 +875,7 @@ def formstyle_bootstrap(form, fields):
             controls.add_class('span4')
 
         if isinstance(label, LABEL):
-            label['_class'] = add_class(label.get('_class'),'control-label')
+            label['_class'] = add_class(label.get('_class'), 'control-label')
 
         if _submit:
             # submit button has unwrapped label and controls, different class
@@ -925,8 +925,11 @@ def formstyle_bootstrap3_stacked(form, fields):
             for e in controls.elements("input"):
                 e.add_class('form-control')
 
+        elif isinstance(controls, CAT) and isinstance(controls[0], INPUT):
+            controls[0].add_class('form-control')
+
         if isinstance(label, LABEL):
-            label['_class'] = add_class(label.get('_class'),'control-label')
+            label['_class'] = add_class(label.get('_class'), 'control-label')
 
         parent.append(DIV(label, _controls, _class='form-group', _id=id))
     return parent
@@ -975,8 +978,10 @@ def _inner(form, fields):
             elif isinstance(controls, UL):
                 for e in controls.elements("input"):
                     e.add_class('form-control')
+            elif isinstance(controls, CAT) and isinstance(controls[0], INPUT):
+                    controls[0].add_class('form-control')
             if isinstance(label, LABEL):
-                label['_class'] = add_class(label.get('_class'),'control-label %s' % label_col_class)
+                label['_class'] = add_class(label.get('_class'), 'control-label %s' % label_col_class)
 
             parent.append(DIV(label, _controls, _class='form-group', _id=id))
         return parent


Test patch:
Repository: web2py/web2py

Issue:
Scheduler - request.is_scheduler = None instead of True
When you access request.is_scheduler from outside of the scheduler you get False as one would expect. However, while running scheduler tasks request.is_scheduler = None instead of True. The current None value seems strange/non-intuitive.

```
#this won't work
if request.is_scheduler:
   #do special scheduler stuff

#To really know if you're running under the scheduler you must use this which makes no sense
if request.is_scheduler == None:
   #do special scheduler stuff
```

This has been the case for a while and is still happening with the latest git trunk



Discussion:
I think this should fix it:

At https://github.com/web2py/web2py/blob/master/gluon/scheduler.py#L480, change:

```
            _env = env(a=a, c=c, import_models=True)
```

to: 

```
            _env = env(a=a, c=c, import_models=True, extra_request=dict(is_scheduler=True))
```

yep, it does. A PR is on the way. @bmeredyk : this is probably due because usually one needs that condition to avoid executing a piece of code in the web-environment. But I see the point of consistency


Resolving patch:
diff --git a/gluon/scheduler.py b/gluon/scheduler.py
--- a/gluon/scheduler.py
+++ b/gluon/scheduler.py
@@ -477,7 +477,8 @@ def write(self, data):
             # Get controller-specific subdirectory if task.app is of
             # form 'app/controller'
             (a, c, f) = parse_path_info(task.app)
-            _env = env(a=a, c=c, import_models=True)
+            _env = env(a=a, c=c, import_models=True,
+                       extra_request={'is_scheduler': True})
             logging.getLogger().setLevel(level)
             f = task.function
             functions = current._scheduler.tasks


Test patch:
Repository: web2py/web2py

Issue:
response._view_environment missing in scheduler and shell
https://github.com/web2py/web2py/commit/b4acfd0724845633f667a55e593a15576379554d results in a failure to create `response._view_environment` when running scheduler tasks or the shell. Now, `response._view_environment` is only created in `gluon.main.serve_controller`, which only gets called for HTTP requests. A fix, is to create `response._view_environment` in `gluon.shell.env`, after the models have been run (just as in `gluon.main.serve_controller`).

```
    if import_models:
        try:
            run_models_in(environment)
        except RestrictedError as e:
            sys.stderr.write(e.traceback + '\n')
            sys.exit(1)

    response._view_environment = copy.copy(environment)  # <-- ADD THIS LINE
```

Note, this should actually be an improvement over the previous situation. In the original code, `response._view_environment` was set in `gluon.compileapp.build_environment`, which was run _before_ `run_models_in` -- so, the `_view_environment` did not includes objects created in the models. This change rectifies that problem.



Discussion:

Resolving patch:
diff --git a/gluon/shell.py b/gluon/shell.py
--- a/gluon/shell.py
+++ b/gluon/shell.py
@@ -15,6 +15,7 @@
 import os
 import sys
 import code
+import copy
 import logging
 import types
 import re
@@ -167,6 +168,8 @@ def check_credentials(request, other_application='admin'):
             sys.stderr.write(e.traceback + '\n')
             sys.exit(1)
 
+    response._view_environment = copy.copy(environment)
+
     environment['__name__'] = '__main__'
     return environment
 


Test patch:
Repository: web2py/web2py

Issue:
IS_EMPTY_OR validator returns incorrect "empty" value
When setting default validators, the https://github.com/web2py/web2py/commit/bdbc053285b67fd3ee02f2ea862b30ca495f33e2 commit mistakenly sets the `null` attribute of the `IS_EMPTY_OR` validator to `''` for _all_ field types rather than just the string based field types.

[This line](https://github.com/web2py/web2py/blob/1877f497309e71918aa78e1a1288cbe3cb5392ec/gluon/dal.py#L81):

```
 requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None)
```

should instead be:

```
 requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None)
```

Notice, `field.type` rather than `field`.



Discussion:

Resolving patch:
diff --git a/gluon/dal.py b/gluon/dal.py
--- a/gluon/dal.py
+++ b/gluon/dal.py
@@ -75,10 +75,10 @@ def _default_validators(db, field):
     if field.unique:
         requires.insert(0, validators.IS_NOT_IN_DB(db, field))
     excluded_fields = ['string', 'upload', 'text', 'password', 'boolean']
-    if (field.notnull or field.unique) and not field_type in excluded_fields:
+    if (field.notnull or field.unique) and field_type not in excluded_fields:
         requires.insert(0, validators.IS_NOT_EMPTY())
     elif not field.notnull and not field.unique and requires:
-        requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None)
+        requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None)
     return requires
 
 from gluon.serializers import custom_json, xml


Test patch:
Repository: web2py/web2py

Issue:
remove __pycache__ from the list of apps
in case someone wonders how many core devs are actively using the admin
app...here's the evidence ^_^'



Discussion:
## [Current coverage](https://codecov.io/gh/web2py/web2py/pull/1489?src=pr) is 53.68% (diff: 100%)

> Merging [#1489](https://codecov.io/gh/web2py/web2py/pull/1489?src=pr) into [master](https://codecov.io/gh/web2py/web2py/branch/master?src=pr) will increase coverage by **0.24%**

``` diff
@@             master      #1489   diff @@
==========================================
  Files            42         42          
  Lines         17336      17441   +105   
  Methods           0          0          
  Messages          0          0          
  Branches       4072       4125    +53   
==========================================
+ Hits           9265       9363    +98   
+ Misses         6874       6869     -5   
- Partials       1197       1209    +12   
```

> Powered by [Codecov](https://codecov.io?src=pr). Last update [cf9b2d8...a1c1d13](https://codecov.io/gh/web2py/web2py/compare/cf9b2d8fa052e0017cc9533697de9bb535c99940...a1c1d1357f029cc82048b22f2a73fd7607b5e501?src=pr)


Resolving patch:
diff --git a/gluon/rocket.py b/gluon/rocket.py
--- a/gluon/rocket.py
+++ b/gluon/rocket.py
@@ -11,7 +11,8 @@
 import socket
 import logging
 import platform
-from gluon._compat import iteritems, to_bytes, StringIO, urllib_unquote
+from gluon._compat import iteritems, to_bytes, StringIO
+from gluon._compat import urllib_unquote, to_native
 
 # Define Constants
 VERSION = '1.2.6'
@@ -1661,7 +1662,7 @@ def build_environ(self, sock_file, conn):
             try:
                 peercert = conn.socket.getpeercert(binary_form=True)
                 environ['SSL_CLIENT_RAW_CERT'] = \
-                    peercert and ssl.DER_cert_to_PEM_cert(peercert)
+                    peercert and to_native(ssl.DER_cert_to_PEM_cert(peercert))
             except Exception:
                 print(sys.exc_info()[1])
         else:


Test patch:
Repository: web2py/web2py

Issue:
webclient : cookie may contains several '=' 
Which leads to a ValueError: too many values to unpack.

A PR to correct the problem will follow

webclient : cookie may contains several '=' 
Which leads to a ValueError: too many values to unpack.

A PR to correct the problem will follow



Discussion:

Resolving patch:
diff --git a/gluon/contrib/webclient.py b/gluon/contrib/webclient.py
--- a/gluon/contrib/webclient.py
+++ b/gluon/contrib/webclient.py
@@ -46,6 +46,17 @@ def __init__(self,
         self.default_headers = default_headers
         self.sessions = {}
         self.session_regex = session_regex and re.compile(session_regex)
+        self.headers = {}
+
+    def _parse_headers_in_cookies(self):
+        self.cookies = {}
+        if 'set-cookie' in self.headers:
+            for item in self.headers['set-cookie'].split(','):
+                cookie = item[:item.find(';')]
+                pos = cookie.find('=')
+                key = cookie[:pos]
+                value = cookie[pos+1:]
+                self.cookies[key.strip()] = value.strip()
 
     def get(self, url, cookies=None, headers=None, auth=None):
         return self.post(url, data=None, cookies=cookies,
@@ -149,12 +160,7 @@ def post(self, url, data=None, cookies=None,
             else:
                 raise error
 
-        # parse headers into cookies
-        self.cookies = {}
-        if 'set-cookie' in self.headers:
-            for item in self.headers['set-cookie'].split(','):
-                key, value = item[:item.find(';')].split('=')
-                self.cookies[key.strip()] = value.strip()
+        self._parse_headers_in_cookies()
 
         # check is a new session id has been issued, symptom of broken session
         if self.session_regex is not None:


Test patch:
diff --git a/gluon/tests/test_web.py b/gluon/tests/test_web.py
--- a/gluon/tests/test_web.py
+++ b/gluon/tests/test_web.py
@@ -49,6 +49,24 @@ def stopwebserver():
     webserverprocess.terminate()
 
 
+class Cookie(unittest.TestCase):
+    def testParseMultipleEquals(self):
+        """ Test for issue #1500.
+        Ensure that a cookie containing one or more '=' is correctly parsed
+        """
+        client = WebClient()
+        client.headers['set-cookie'] = "key = value with one =;"
+        client._parse_headers_in_cookies()
+        self.assertIn("key", client.cookies)
+        self.assertEqual(client.cookies['key'], "value with one =")
+
+        client.headers['set-cookie'] = "key = value with one = and another one =;"
+        client._parse_headers_in_cookies()
+        client._parse_headers_in_cookies()
+        self.assertIn("key", client.cookies)
+        self.assertEqual(client.cookies['key'], "value with one = and another one =")
+
+
 class LiveTest(unittest.TestCase):
 
     @classmethod
Repository: web2py/web2py

Issue:
Allow the use of firstname and lastname in auth.messages.verify_email 
auth.messages.verify allows only for username to identify people in a name, but username may be the user mail.
It would be nice to allow more personal first and last name.

Other messages may be concerned too.

(I will submit a PR soon).


Discussion:

Resolving patch:
diff --git a/gluon/tools.py b/gluon/tools.py
--- a/gluon/tools.py
+++ b/gluon/tools.py
@@ -3417,7 +3417,9 @@ def register(self,
                 link = self.url(
                     self.settings.function, args=('verify_email', key), scheme=True)
                 d = dict(form.vars)
-                d.update(dict(key=key, link=link, username=form.vars[username]))
+                d.update(dict(key=key, link=link, username=form.vars[username],
+                              firstname=form.vars['firstname'],
+                              lastname=form.vars['lastname']))
                 if not (self.settings.mailer and self.settings.mailer.send(
                         to=form.vars.email,
                         subject=self.messages.verify_email_subject,


Test patch:
Repository: web2py/web2py

Issue:
webclient lose the session when session.forget is used
When `session.forget` is added to an action like `index` we can observe that on subsequent call a logged user is logged out.

To reproduce, modify  `TestWeb.testRegisterAndLogin` in gluon/tests/test_web.py (tryed on  commit e6a3081b42ecd58441419930266baf286561c4c7) so as adding `session.forget(response)` at the first line of the `index` controller.

The test is run with :

```
python2 -m unittest -v gluon.tests.test_web.TestWeb.testRegisterAndLogin
```

And fails with :

```
======================================================================
FAIL: testRegisterAndLogin (gluon.tests.test_web.TestWeb)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "gluon/tests/test_web.py", line 92, in testRegisterAndLogin
    self.assertTrue('Welcome Homer' in client.text)
AssertionError: False is not true

----------------------------------------------------------------------
```

Which seems unexpected according to the google group exchanges about this subject.

I'd like to help, but I have only a rough idea of the expected behaviour of a browser with respect to cookies, sessions and headers… Link to documentation is welcomed.



Discussion:
Here's the relevant discussion: https://groups.google.com/forum/#!topic/web2py/kRMZayGxzHA


Resolving patch:
diff --git a/gluon/contrib/webclient.py b/gluon/contrib/webclient.py
--- a/gluon/contrib/webclient.py
+++ b/gluon/contrib/webclient.py
@@ -43,6 +43,7 @@ def __init__(self,
         self.forms = {}
         self.history = []
         self.cookies = {}
+        self.cookiejar = cookielib.CookieJar()
         self.default_headers = default_headers
         self.sessions = {}
         self.session_regex = session_regex and re.compile(session_regex)
@@ -79,9 +80,8 @@ def post(self, url, data=None, cookies=None,
         cookies = cookies or {}
         headers = headers or {}
 
-        cj = cookielib.CookieJar()
         args = [
-            urllib2.HTTPCookieProcessor(cj),
+            urllib2.HTTPCookieProcessor(self.cookiejar),
             urllib2.HTTPHandler(debuglevel=0)
             ]
         # if required do basic auth


Test patch:
diff --git a/gluon/tests/test_web.py b/gluon/tests/test_web.py
--- a/gluon/tests/test_web.py
+++ b/gluon/tests/test_web.py
@@ -110,7 +110,7 @@ def testRegisterAndLogin(self):
         self.assertTrue('Welcome Homer' in client.text)
 
         client = WebClient('http://127.0.0.1:8000/admin/default/')
-        client.post('index', data=dict(password='hello'))
+        client.post('index', data=dict(password='testpass'))
         client.get('site')
         client.get('design/welcome')