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

Issue:
get_conn_flattened out of bounds indexing
I noticed that if one enables bound-checks in Numba code (which slows it down considerably, so Numba defaults to not performing it) we sometimes index and write data out of bounds in our `get_conn_flattened`.

This is harmless for the given example (we write a zero to some random address) but might cause problems and wrong indexes when working with batches, so it should be fixed ASAP

```python
netket on  pv/lazyop [$] via netket_env via 🐍 system took 4s 
➜ python -c "import netket as nk; nk.operator.spin.sigmap(nk.hilbert.Spin(0.5), 0).to_dense()"
                                                                                                                                                                      
~/Dropbox/Ricerca/Codes/Python/netket pv/lazyop

netket on  pv/lazyop [$] via netket_env via 🐍 system took 5s 
➜ NUMBA_BOUNDSCHECK=1 python -c "import netket as nk; nk.operator.spin.sigmap(nk.hilbert.Spin(0.5), 0).to_dense()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/filippovicentini/Dropbox/Ricerca/Codes/Python/netket/netket/operator/_discrete_operator.py", line 190, in to_dense
    return self.to_sparse().todense().A
  File "/home/filippovicentini/Dropbox/Ricerca/Codes/Python/netket/netket/operator/_discrete_operator.py", line 158, in to_sparse
    x_prime, mels = concrete_op.get_conn_flattened(x, sections)
  File "/home/filippovicentini/Dropbox/Ricerca/Codes/Python/netket/netket/operator/_local_operator.py", line 911, in get_conn_flattened
    return self._get_conn_flattened_kernel(
IndexError: index is out of bounds
```


Discussion:
Maybe we should run our tests with `NUMBA_BOUNDSCHECK=1 `
Ok, it's not a big issue because it just adds 0 to OOB memory, as I had documented in a note left to myself.
Still, it would be nice to avoid doing this.

It's a one line fix

Resolving patch:
diff --git a/netket/operator/_local_operator.py b/netket/operator/_local_operator.py
--- a/netket/operator/_local_operator.py
+++ b/netket/operator/_local_operator.py
@@ -976,12 +976,9 @@ def _get_conn_flattened_kernel(
                 c += 1
 
             for i in range(n_operators):
+                if nonzero_diagonal:
+                    mels[c_diag] += diag_mels[i, xs_n[b, i]]
 
-                # Diagonal part
-                #  If nonzero_diagonal, this goes to c_diag = 0 ....
-                # if zero_diagonal this just sets the last element to 0
-                # so it's not worth it skipping it
-                mels[c_diag] += diag_mels[i, xs_n[b, i]]
                 n_conn_i = n_conns[i, xs_n[b, i]]
 
                 if n_conn_i > 0:


Test patch:
Repository: netket/netket

Issue:
Upgrade `flakehell` in the pre-commit hook
It seems that `flakehell` is not actively maintained, and it is incompatible with `flake8 4.x` released in last October (see flakehell/flakehell#22). That issue is not resolved after a few months. If a new developer of NetKet runs `pre-commit install-hooks`, it will just fail.

We may use [this fix](https://github.com/flakehell/flakehell/pull/23#issuecomment-985879201), or change it to [flakeheaven](https://github.com/flakeheaven/flakeheaven) which seems more actively maintained.


Discussion:
Do we even really need this stuff?

On Thu, Feb 17, 2022, 20:57 Dian Wu ***@***.***> wrote:

> It seems that flakehell is not actively maintained, and it is
> incompatible with flake8 4.x released in last October (see
> flakehell/flakehell#22 <https://github.com/flakehell/flakehell/issues/22>).
> That issue is not resolved after a few months. If a new developer of NetKet
> runs pre-commit install-hooks, it will just fail.
>
> We may use this fix
> <https://github.com/flakehell/flakehell/pull/23#issuecomment-985879201>,
> or change it to flakeheaven <https://github.com/flakeheaven/flakeheaven>
> which seems more actively maintained.
>
> —
> Reply to this email directly, view it on GitHub
> <https://github.com/netket/netket/issues/1111>, or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AGWYRBBMSA5Q3PMATGQY2DTU3VHJNANCNFSM5OVWNAVQ>
> .
> Triage notifications on the go with GitHub Mobile for iOS
> <https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
> or Android
> <https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
>
> You are receiving this because you are subscribed to this thread.Message
> ID: ***@***.***>
>

I think it's helpful to keep the code cleaner and find some potential bugs
I like those things. They can be disabled after all and they catches a few bugs from time to time.


@wdphy16 cant we switch to bare flake8? Even flakeven looks very young and small

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -6,10 +6,9 @@
     "coverage>=5",
     "pytest-cov>=2.10.1",
     "networkx~=2.4",
-    "flaky>=3.7",
-    "pre-commit",
+    "pre-commit>=2.7",
     "black==22.1.0",
-    "flakehell>=0.9",
+    "flake8==4.0.1",
 ]
 MPI_DEPENDENCIES = ["mpi4py>=3.0.1, <4", "mpi4jax~=0.3.1"]
 EXTRA_DEPENDENCIES = ["tensorboardx>=2.0.0", "openfermion>=1.0.0"]


Test patch:
Repository: netket/netket

Issue:
[bug] nk.jax.expect is off by a factor of mpi.n_rank in the backward pass
it's just a multiplicative factor, but still...

discovered by Alessandro Sinibaldi


Discussion:
not an issue

Resolving patch:
diff --git a/netket/jax/_expect.py b/netket/jax/_expect.py
--- a/netket/jax/_expect.py
+++ b/netket/jax/_expect.py
@@ -60,6 +60,50 @@ def expect(
 
     where again, the expectation values are comptued using the sample average.
 
+    .. note::
+
+        When using this function together with MPI, you have to pay particular attention. This is because inside the function `f` that is differentiated
+        a mean over the MPI ranks (`mpi_mean(term1 + term2, axis=0)`) appears. Therefore, when doing the backward pass this results in a division of the outputs
+        from the previous steps by a factor equal to the number of MPI ranks, and so the final gradient on each MPI rank is rescaled as well.
+        To cope with this, it is important to sum over the ranks the gradient computed after AD, for example using the function `nk.utils.mpi.mpi_sum_jax`.
+        See the following example for more details.
+
+    Example:
+        Compute the energy gradient using `nk.jax.expect` on more MPI ranks.
+
+        >>> import netket as nk
+        >>> import jax
+        >>> import jax.numpy as jnp
+        >>>
+        >>> hi = nk.hilbert.Spin(s=0.5, N=20)
+        >>> graph = nk.graph.Chain(length=20)
+        >>> H = nk.operator.IsingJax(hi, graph, h=1.0)
+        >>> vstate = nk.vqs.MCState(sampler=nk.sampler.MetropolisLocal(hi, n_chains_per_rank=16), model=nk.models.RBM(alpha=1, param_dtype=complex), n_samples=100000)
+        >>>
+        >>> afun = vstate._apply_fun
+        >>> pars = vstate.parameters
+        >>> model_state = vstate.model_state
+        >>> log_pdf = lambda params, σ: 2 * afun({"params": params, **model_state}, σ).real
+        >>>
+        >>> σ = vstate.samples
+        >>> σ = σ.reshape(-1, σ.shape[-1])
+        >>> σp, mels = H.get_conn_padded(σ)
+        >>>
+        >>> def expect(pars, σ, σp, mels, model_state):
+        >>>
+        >>>     def expected_fun(pars, σ, σp, mels):
+        >>>         W = {"params": pars, **model_state}
+        >>>         logpsi_σ = afun(W, σ)
+        >>>         logpsi_σp = afun(W, σp)
+        >>>         logHpsi_σ = jax.scipy.special.logsumexp(logpsi_σp, b=mels, axis=1)
+        >>>         return jnp.exp(logHpsi_σ - logpsi_σ)
+        >>>
+        >>>     return nk.jax.expect(log_pdf, expected_fun, pars, σ, σp, mels)[0]
+        >>>
+        >>> E, E_vjp_fun = nk.jax.vjp(expect, pars, σ, σp, mels, model_state)
+        >>> grad = E_vjp_fun(jnp.ones_like(E))[0]
+        >>> grad = jax.tree_util.tree_map(lambda x: nk.utils.mpi.mpi_sum_jax(x)[0], grad)
+
     Args:
         log_pdf: The log-pdf function from which the samples are drawn. This should output real values, and have a signature
             :code:`log_pdf(pars, σ) -> jnp.ndarray`.


Test patch:
Repository: netket/netket

Issue:
Error in fermi-hubbard example
Hello, there.

It seems that the definition of create and annihilation operators are defined reversely in fermi-hubbard model, and results are wrong. [link](https://github.com/netket/netket/blob/26372e3527ae12861cc7953c24654614e8679d87/Examples/Fermions/fermi_hubbard.py#L25C1-L26)


Discussion:
@jwnys wrote those examples...
Jannes, do you agree with the above?
The naming of the functions are just switched (@imi-hub , can you take a look?). What do you mean that the results are wrong though?
By putting the correct definitions of the creation and annihilation operators, the model seems to converge towards the ground state energy. We can compare the variational state (red curve) with the ED results (black lines).
![test_fermions](https://github.com/netket/netket/assets/80409000/3cdcd76e-a0ef-4f6f-a803-8ea75ae964e2)
Could you perhaps explain what type of errors you are getting?
good! Could you please open a quick PR to correct this issue?
the hamiltonian is hermitean, despite the mistake in labeling the functions, the energy should be exactly the same, we just need to swap the names of the functions ! 
Hmm.. just because you are using `.number` instead of doing cdag c.... as  $cc^\dagger = 1-c^\dagger c$. 
But good, at least the result was not wrong.

Resolving patch:
diff --git a/Examples/Fermions/fermi_hubbard.py b/Examples/Fermions/fermi_hubbard.py
--- a/Examples/Fermions/fermi_hubbard.py
+++ b/Examples/Fermions/fermi_hubbard.py
@@ -23,11 +23,11 @@
 # we will create a helper function to abbreviate the creation, destruction and number operators
 # each operator has a site and spin projection (sz) in order to find the right position in the hilbert space samples
 def c(site, sz):
-    return nkx.operator.fermion.create(hi, site, sz=sz)
+    return nkx.operator.fermion.destroy(hi, site, sz=sz)
 
 
 def cdag(site, sz):
-    return nkx.operator.fermion.destroy(hi, site, sz=sz)
+    return nkx.operator.fermion.create(hi, site, sz=sz)
 
 
 def nc(site, sz):


Test patch:
Repository: netket/netket

Issue:
`vs.sample(n_samples=X, chain_length=Y)` does not error and silently ignores one argument
Only one of the two should be specified.
The current setting, instead, [silently ignores `n_samples` if both are specified](https://github.com/netket/netket/blob/758b9380937b6763cc3ed5a6b73cdc3131e5cb05/netket/vqs/mc/mc_state/state.py#L475).

We should throw an error instead.
`vs.sample(n_samples=X, chain_length=Y)` does not error and silently ignores one argument
Only one of the two should be specified.
The current setting, instead, [silently ignores `n_samples` if both are specified](https://github.com/netket/netket/blob/758b9380937b6763cc3ed5a6b73cdc3131e5cb05/netket/vqs/mc/mc_state/state.py#L475).

We should throw an error instead.


Discussion:

Resolving patch:
diff --git a/netket/vqs/mc/mc_state/state.py b/netket/vqs/mc/mc_state/state.py
--- a/netket/vqs/mc/mc_state/state.py
+++ b/netket/vqs/mc/mc_state/state.py
@@ -472,7 +472,9 @@ def sample(
         if n_samples is None and chain_length is None:
             chain_length = self.chain_length
         else:
-            if chain_length is None:
+            if chain_length is not None and n_samples is not None:
+                raise ValueError("Cannot specify both `chain_length` and `n_samples`.")
+            elif chain_length is None:
                 chain_length = compute_chain_length(self.sampler.n_chains, n_samples)
 
             if self.chunk_size is not None:


Test patch:
diff --git a/test/variational/test_variational.py b/test/variational/test_variational.py
--- a/test/variational/test_variational.py
+++ b/test/variational/test_variational.py
@@ -227,6 +227,11 @@ def test_chunk_size_api(vstate, _mpi_size):
     ):
         vstate.sample(n_samples=1008 + 16)
 
+    with raises(
+        ValueError,
+    ):
+        vstate.sample(n_samples=1008, chain_length=100)
+
 
 @common.skipif_mpi
 def test_constructor():
Repository: fossasia/open-event-server

Issue:
filling in any field with link(www.google.com) , after submit form, it will redirect us to link page



Discussion:

Resolving patch:
diff --git a/open_event/forms/admin/microlocation_form.py b/open_event/forms/admin/microlocation_form.py
--- a/open_event/forms/admin/microlocation_form.py
+++ b/open_event/forms/admin/microlocation_form.py
@@ -1,6 +1,6 @@
 """Copyright 2015 Rafal Kowalski"""
 from flask_wtf import Form
-from wtforms import StringField, FloatField, validators
+from wtforms import StringField, FloatField, validators, IntegerField
 from wtforms.ext.sqlalchemy.fields import QuerySelectField
 
 from open_event.models.session import Session
@@ -15,5 +15,5 @@ class MicrolocationForm(Form):
     name = StringField('Name', [validators.DataRequired()])
     latitude = FloatField('Latitude', [validators.DataRequired()])
     longitude = FloatField('Longitude', [validators.DataRequired()])
-    floor = StringField('Floor')
+    floor = IntegerField('Floor', [validators.optional()])
     session = QuerySelectField(query_factory=get_sessions, allow_blank=True)
diff --git a/open_event/views/admin/models_views/event.py b/open_event/views/admin/models_views/event.py
--- a/open_event/views/admin/models_views/event.py
+++ b/open_event/views/admin/models_views/event.py
@@ -3,7 +3,7 @@
 
 from flask.ext.admin.contrib.sqla import ModelView
 from flask.ext.admin import expose
-
+from flask.ext.admin.helpers import get_redirect_target
 from open_event.forms.admin.session_form import SessionForm
 from open_event.forms.admin.speaker_form import SpeakerForm
 from open_event.forms.admin.sponsor_form import SponsorForm
@@ -30,7 +30,9 @@ class EventView(ModelView):
                    'end_time',
                    'latitude',
                    'longitude',
-                   'location_name')
+                   'location_name',
+                   'slogan',
+                   'url')
 
     column_formatters = {
         'name': Formatter.column_formatter,
@@ -50,6 +52,7 @@ def index_view(self):
     @expose('/new/', methods=('GET', 'POST'))
     def create_view(self):
         self._template_args['events'] = Event.query.all()
+        self._template_args['return_url'] = get_redirect_target() or self.get_url('.index_view')
         return super(EventView, self).create_view()
 
     @expose('/edit/', methods=('GET', 'POST'))


Test patch:
Repository: fossasia/open-event-server

Issue:
Add map to New/Edit Event View like Microlocation View
The objective of the task is to add map to New/Edit Event View like Microlocation View. Latitude and Longitude fields should be filled by map pointer position.

Add map to New/Edit Event View like Microlocation View
The objective of the task is to add map to New/Edit Event View like Microlocation View. Latitude and Longitude fields should be filled by map pointer position.



Discussion:

Resolving patch:
diff --git a/open_event/views/admin/models_views/event.py b/open_event/views/admin/models_views/event.py
--- a/open_event/views/admin/models_views/event.py
+++ b/open_event/views/admin/models_views/event.py
@@ -91,7 +91,7 @@ def create_view(self):
                 DataManager.create_event(self.form)
                 flash("Event updated")
                 return redirect(url_for('.index_view'))
-        return self.render('admin/model/create_model.html',
+        return self.render('admin/model/create_event.html',
                            form=self.form,
                            events=events,
                            cancel_url=url_for('.index_view'))
@@ -115,7 +115,7 @@ def edit_view(self):
                 else:
                     flash("You don't have permission!")
                 return redirect(url_for('.index_view', event_id=event_id))
-        return self.render('admin/model/create_model.html',
+        return self.render('admin/model/edit_event.html',
                            form=self.form,
                            event_id=event_id,
                            events=events,


Test patch:
Repository: fossasia/open-event-server

Issue:
Adding a new sponsor with logo does not work
To reproduce:
- Make sure you have the latest commit on master with the `static/sponsor_log` directory
- Go to http://0.0.0.0:8001/admin/event/1/sponsor/new
- Create a new sponsor with an uploaded image
- It will seem to work, but there will be no sponsor row in the UI. Your logs will show this:

```
ERROR:root:DB Exception! (psycopg2.ProgrammingError) can't adapt type 'FileStorage' [SQL: 'INSERT INTO sponsors (name, url, logo, event_id) VALUES (%(name)s, %(url)s, %(logo)s, %(event_id)s) RETURNING sponsors.id'] [parameters: {'event_id': u'1', 'url': u'asfd', 'name': u'fuck fuck', 'logo': <FileStorage: u'1970595_10152735183272501_456061550_n.jpg' ('image/jpeg')>}]
10.0.2.2 - - [18/Dec/2015 02:23:40] "POST /admin/event/1/sponsor/new HTTP/1.1" 302 -
```

NOTE: The file does actually get saved correctly into the `static/sponsor_logo` directory



Discussion:
Well, I think its because that particular event does not have the permission. When I run it locally on my computer it's displaying the image in the UI
![screen shot 2015-12-18 at 22 51 10](https://cloud.githubusercontent.com/assets/15054664/11902725/f6acfcd0-a5d9-11e5-94c9-cbecd40d0a36.png)

@rafalkowalski @creativepsyco can y'all try to create a sponsor with logo and let us know if it works?

I tried using a small 14K PNG as a logo (previously it was a large JPG) and I still get the same error:

```
ERROR:root:DB Exception! (psycopg2.ProgrammingError) can't adapt type 'FileStorage' [SQL: 'INSERT INTO sponsors (name, url, logo, event_id) VALUES (%(name)s, %(url)s, %(logo)s, %(event_id)s) RETURNING sponsors.id'] [parameters: {'event_id': u'1', 'url': u'localhost', 'name': u'BESSEL', 'logo': <FileStorage: u'bessel.png' ('image/png')>}]
```

Nope it doesnt work.


Resolving patch:
diff --git a/open_event/helpers/data.py b/open_event/helpers/data.py
--- a/open_event/helpers/data.py
+++ b/open_event/helpers/data.py
@@ -144,7 +144,7 @@ def create_speaker(form, event_id):
         filename = secure_filename(file.filename)
         file.save(os.path.join(os.path.realpath('.') + '/static/speaker_photos/', filename))
         new_speaker = Speaker(name=form.name.data,
-                              photo=form.photo.data,
+                              photo=filename,
                               biography=form.biography.data,
                               email=form.email.data,
                               web=form.web.data,
@@ -200,7 +200,7 @@ def create_sponsor(form, event_id):
         new_sponsor = Sponsor(name=form.name.data,
                               url=form.url.data,
                               event_id=event_id,
-                              logo=form.logo.data)
+                              logo=filename)
         save_to_db(new_sponsor, "Sponsor saved")
         update_version(event_id, False, "sponsors_ver")
 


Test patch:
Repository: fossasia/open-event-server

Issue:
Search a given event for a session title
Given an event ID X and a string S, search through all session titles at event X and return data about all sessions who have a name matching S.

A JSON array should be returned



Discussion:

Resolving patch:
diff --git a/open_event/views/views.py b/open_event/views/views.py
--- a/open_event/views/views.py
+++ b/open_event/views/views.py
@@ -225,6 +225,7 @@ def get_event_version(event_id):
 @auto.doc()
 @cross_origin()
 def get_sessions_at_event(event_id, session_title):
+    """Returns all the sessions of a particular event which contain session_title string in their title"""
     sessions=Session.query.filter(Session.event_id == event_id,Session.title.contains(session_title))
     return ObjectFormatter.get_json("sessions", sessions, request)
 
@@ -232,6 +233,7 @@ def get_sessions_at_event(event_id, session_title):
 @auto.doc()
 @cross_origin()
 def get_speakers_at_event(event_id, speaker_name):
+    """Returns all the speakers of a particular event which contain speaker_name string in their name"""
     speakers=Speaker.query.filter(Speaker.event_id == event_id,Speaker.name.contains(speaker_name))
     return ObjectFormatter.get_json("speakers", speakers, request)
 


Test patch:
Repository: fossasia/open-event-server

Issue:
fix: deleting an event gives error
How to produce the error:
1. Create an Event
2. Create a sponsor for that event
3. Now try to delete that event.It will give an Internal Server Error.
This will happen when an event has either a sponsor, session, microlocation ,tracks etc...
It will work successfully if only an event is created. Basically this happens because of the ForeignKey constraint on the sponsor,session ,microlocation,etc... objects which prevent the event from deleting. 



Discussion:
This makes it plainly clear that we need API tests, which would hopefully catch something like this.

Yes. We do need to write automated tests for the API to ensure that the code doesn't break.


Resolving patch:
diff --git a/open_event/helpers/data.py b/open_event/helpers/data.py
--- a/open_event/helpers/data.py
+++ b/open_event/helpers/data.py
@@ -461,6 +461,11 @@ def update_event(form, event):
     @staticmethod
     def delete_event(e_id):
         EventsUsers.query.filter_by(event_id=e_id).delete()
+        Sponsor.query.filter_by(id=e_id).delete()
+        Speaker.query.filter_by(id=e_id).delete()
+        Microlocation.query.filter_by(id=e_id).delete()
+        Track.query.filter_by(id=e_id).delete()
+        Session.query.filter_by(id=e_id).delete()
         Event.query.filter_by(id=e_id).delete()
         db.session.commit()
 


Test patch: