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

Issue:
tn.reachable breaks when given tuples containing edges
Here's a minimal working example to show what goes wrong:

```python
import numpy as np
import tensornetwork as tn

node = tn.Node(np.eye(2))
edge_tuple = (node[0], node[1])
reachable_nodes = tn.reachable(edge_tuple)
```

Everything works fine when I use a list for edges, and it appears the issue is `tn.reachable` assuming that any list-like collection of edges is necessarily a list. Should be an easy fix, thanks :)


Discussion:

Resolving patch:
diff --git a/tensornetwork/network_operations.py b/tensornetwork/network_operations.py
--- a/tensornetwork/network_operations.py
+++ b/tensornetwork/network_operations.py
@@ -613,20 +613,29 @@ def reachable(
 
   Args:
     inputs: A `AbstractNode`/`Edge` or collection of `AbstractNodes`/`Edges`
+
   Returns:
     A set of `AbstractNode` objects that can be reached from `node`
     via connected edges.
+
   Raises:
-    ValueError: If an unknown value for `strategy` is passed.
+    TypeError: If inputs contains other then `Edge` or `Node`.
   """
 
   if isinstance(inputs, AbstractNode):
     inputs = {inputs}
-  elif isinstance(inputs, Edge):
+  if isinstance(inputs, Edge):
     inputs = {inputs.node1}  # pytype: disable=attribute-error
-  elif isinstance(inputs, list) and all(isinstance(x, Edge) for x in inputs):
-    inputs = {x.node1 for x in inputs}
-  return _reachable(set(inputs))
+  processed_inputs = set()
+  for inp in inputs:
+    if isinstance(inp, AbstractNode):
+      processed_inputs |= {inp}
+    elif isinstance(inp, Edge):
+      processed_inputs |= {inp.node1}
+    else:
+      raise TypeError(f"input to `reachable` has to be an iterable of "
+                      f"Nodes or Edges, got {type(inp)} instead.")
+  return _reachable(set(processed_inputs))
 
 
 def check_correct(nodes: Iterable[AbstractNode],


Test patch:
diff --git a/tensornetwork/tests/network_operations_test.py b/tensornetwork/tests/network_operations_test.py
--- a/tensornetwork/tests/network_operations_test.py
+++ b/tensornetwork/tests/network_operations_test.py
@@ -294,6 +294,11 @@ def test_reachable_disconnected_2(backend):
   nodes[2][1] ^ nodes[3][0]  # connect third and fourth node
   assert set(tn.reachable([nodes[0], nodes[1]])) == set(nodes)
 
+def test_reachable_raises(backend):
+  nodes = [tn.Node(np.random.rand(2, 2, 2), backend=backend), 5]
+  with pytest.raises(TypeError):
+    tn.reachable(nodes)
+
 
 def test_subgraph_sanity(backend):
   a = tn.Node(np.eye(2), backend=backend)
Repository: google/TensorNetwork

Issue:
Flaky Test when seed not used
The test `test_max_truncation_error` in `tensornetwork/backends/symmetric/decompositions_test.py` [link](https://github.com/google/TensorNetwork/blob/edf3f345640c64595b4ad1002bebf4a008988b3e/tensornetwork/backends/symmetric/decompositions_test.py#L90) almost always fails when the seed [here](https://github.com/google/TensorNetwork/blob/edf3f345640c64595b4ad1002bebf4a008988b3e/tensornetwork/backends/symmetric/decompositions_test.py#L91) is removed. This happens only for `[3-float64]` and `[4-complex128]` parameters. The test failed 500/500 times for me for both these parameters.

From the error message it seems `svals[mask][::-1]` is always empty whereas `S2.data` most often has an element of size 1(except when using the seed). Is this expected? Or is this indicative of a bug?

Please let me know if you need more details. I will be happy to raise a PR if you have any suggestions on how to fix it.

Test failure message:
```
>     np.testing.assert_allclose(S2.data, svals[mask][::-1])
E     AssertionError:
E     Not equal to tolerance rtol=1e-07, atol=0
E
E     (shapes (1,), (0,) mismatch)
E      x: array([1.])
E      y: array([], dtype=float64)

tensornetwork/backends/symmetric/decompositions_test.py:112: AssertionError
```

Environment:
```
Anaconda python 3.6
tensorflow==2.6.0
numpy==1.19.5
scipy==1.5.4
```



Discussion:

Resolving patch:
diff --git a/tensornetwork/backends/symmetric/decompositions.py b/tensornetwork/backends/symmetric/decompositions.py
--- a/tensornetwork/backends/symmetric/decompositions.py
+++ b/tensornetwork/backends/symmetric/decompositions.py
@@ -84,10 +84,6 @@ def svd(
     #sort singular values
     inds = np.argsort(extended_flat_singvals, kind='stable')
     discarded_inds = np.zeros(0, dtype=SIZE_T)
-    if inds.shape[0] > 0:
-      maxind = inds[-1]
-    else:
-      maxind = 0
     if max_truncation_error is not None:
       if relative and (len(singvals) > 0):
         max_truncation_error = max_truncation_error * np.max(
@@ -114,9 +110,7 @@ def svd(
 
     if len(inds) == 0:
       #special case of truncation to 0 dimension;
-      warnings.warn("svd_decomposition truncated to 0 dimensions. "
-                    "Adjusting to `max_singular_values = 1`")
-      inds = np.asarray([maxind])
+      warnings.warn("svd_decomposition truncated to 0 dimensions.")
 
     if extended_singvals.shape[1] > 0:
       #pylint: disable=no-member


Test patch:
diff --git a/tensornetwork/backends/symmetric/decompositions_test.py b/tensornetwork/backends/symmetric/decompositions_test.py
--- a/tensornetwork/backends/symmetric/decompositions_test.py
+++ b/tensornetwork/backends/symmetric/decompositions_test.py
@@ -87,8 +87,9 @@ def test_max_singular_values(dtype, R, R1, num_charges):
 
 @pytest.mark.parametrize("dtype", np_dtypes)
 @pytest.mark.parametrize("num_charges", [1, 2, 3])
-def test_max_truncation_error(dtype, num_charges):
-  np.random.seed(10)
+@pytest.mark.parametrize("seed", np.arange(20))
+def test_max_truncation_error(dtype, num_charges, seed):
+  np.random.seed(seed)
   R = 2
   D = 30
   charges = [
Repository: ContinualAI/avalanche

Issue:
LWF "warmup_train" fun never used
Hi @AntonioCarta, I've noticed this function in the `LearningWithoutForgetting` class is never used, do we need it?


Discussion:

Resolving patch:
diff --git a/avalanche/training/strategies/lwf/lwf.py b/avalanche/training/strategies/lwf/lwf.py
--- a/avalanche/training/strategies/lwf/lwf.py
+++ b/avalanche/training/strategies/lwf/lwf.py
@@ -39,7 +39,7 @@ def distillation_loss(y_pred, y_teacher, temperature):
 
 
 class LearningWithoutForgetting(Strategy):
-    def __init__(self, model, classes_per_task, alpha=0.5, distillation_loss_T=2, warmup_epochs=2, optimizer=None,
+    def __init__(self, model, classes_per_task, alpha=0.5, distillation_loss_T=2, warmup_epochs=0, optimizer=None,
                  criterion=torch.nn.CrossEntropyLoss(), mb_size=256,
                  train_ep=2, device=None, preproc=None,
                  eval_protocol=EvalProtocol(metrics=[ACC()])):
@@ -78,7 +78,7 @@ def warmup_train(self):
 
         train_x = torch.tensor(train_x, dtype=torch.float)
         train_y = torch.tensor(train_y, dtype=torch.long)
-        for ep in range(self.train_ep):
+        for ep in range(self.warmup_epochs):
             for it in range(it_x_ep):
                 start = it * self.mb_size
                 end = (it + 1) * self.mb_size
@@ -108,6 +108,9 @@ def compute_loss(self, logits, y_mb):
             loss = self.criterion(logits, y_mb)
         return loss
 
+    def before_train(self):
+        self.warmup_train()
+
     def after_train(self):
         self.prev_model = copy.deepcopy(self.model)
 


Test patch:
Repository: ContinualAI/avalanche

Issue:
CPU/GPU process usage Metric
We need to add the metric related to the CPU/GPU consumption over time.


Discussion:

Resolving patch:
diff --git a/avalanche/evaluation/eval_protocol.py b/avalanche/evaluation/eval_protocol.py
--- a/avalanche/evaluation/eval_protocol.py
+++ b/avalanche/evaluation/eval_protocol.py
@@ -19,7 +19,7 @@
 from __future__ import division
 from __future__ import absolute_import
 
-from .metrics import ACC, CF, RAMU, CM, CPUUsage
+from .metrics import ACC, CF, RAMU, CM, CPUUsage, GPUUsage
 import numpy as np
 from .tensorboard import TensorboardLogging
 
@@ -55,6 +55,8 @@ def get_results(self, true_y, y_hat, train_t, test_t):
                 results[CM] = metric.compute(true_y, y_hat)
             elif isinstance(metric, CPUUsage):
                 results[CPUUsage] = metric.compute(train_t)
+            elif isinstance(metric, GPUUsage):
+                results[GPUUsage] = metric.compute(train_t)
             else:
                 raise ValueError("Unknown metric")
 
diff --git a/avalanche/evaluation/metrics.py b/avalanche/evaluation/metrics.py
--- a/avalanche/evaluation/metrics.py
+++ b/avalanche/evaluation/metrics.py
@@ -32,6 +32,52 @@
 from torchvision.transforms import ToTensor
 from sklearn.utils.multiclass import unique_labels
 import io
+import queue
+import subprocess
+import threading
+
+
+class GPUUsage:
+    """
+        GPU usage metric measured as average usage percentage over time.
+
+        :param gpu_id: GPU device ID
+        :param every: time delay (in seconds) between measurements
+    """
+    def __init__(self, gpu_id, every=10):
+        # 'nvidia-smi --loop=1 --query-gpu=utilization.gpu --format=csv'
+        cmd = ['nvidia-smi', f'--loop={every}', '--query-gpu=utilization.gpu', '--format=csv', f'--id={gpu_id}']
+        self.p = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE)  # something long running
+        self.lines_queue = queue.Queue()
+        self.read_thread = threading.Thread(target=GPUUsage.push_lines, args=(self,), daemon=True)
+        self.read_thread.start()
+
+        self.n_measurements = 0
+        self.avg_usage = 0
+
+    def compute(self, t):
+        """
+        Compute CPU usage measured in seconds.
+
+        :param t: task id
+        :return: tuple (float): average GPU usage
+        """
+        while not self.lines_queue.empty():
+            line = self.lines_queue.get()
+            if line[0] == 'u':  # skip first line 'utilization.gpu [%]'
+                continue
+            usage = int(line.strip()[:-1])
+            self.n_measurements += 1
+            self.avg_usage += usage
+        print(f"Train Task {t} - average GPU usage: {self.avg_usage}%")
+
+    def push_lines(self):
+        while True:
+            line = self.p.stdout.readline()
+            self.lines_queue.put(line.decode('ascii'))
+
+    def close(self):
+        self.p.terminate()
 
 
 class CPUUsage:


Test patch:
Repository: ContinualAI/avalanche

Issue:
Multi-head should use task_labels instead of current_step ids
 


Discussion:

Resolving patch:
diff --git a/avalanche/training/plugins.py b/avalanche/training/plugins.py
--- a/avalanche/training/plugins.py
+++ b/avalanche/training/plugins.py
@@ -521,11 +521,11 @@ def __init__(self, model, classifier_field: str = 'classifier',
         if keep_initial_layer:
             self.task_layers[0] = getattr(model, classifier_field)
 
-    def before_training_step(self, strategy, **kwargs):
+    def before_training_iteration(self, strategy, **kwargs):
         self._optimizer = strategy.optimizer
         self.set_task_layer(strategy, strategy.step_info)
 
-    def before_test_step(self, strategy, **kwargs):
+    def before_test_iteration(self, strategy, **kwargs):
         self._optimizer = strategy.optimizer
         self.set_task_layer(strategy, strategy.step_info)
 
@@ -540,7 +540,12 @@ def set_task_layer(self, strategy, step_info: IStepInfo):
         :return: None
         """
 
-        task_label = step_info.task_label
+        # task label is set depending on the type of scenario
+        # multitask or others
+        if hasattr(strategy, 'mb_task_id'):
+            task_label = strategy.mb_task_id
+        else:
+            task_label = step_info.task_label
         n_output_units = max(step_info.dataset.targets) + 1
 
         if task_label not in self.task_layers:


Test patch:
Repository: hydroshare/hydroshare

Issue:
"Web App" needs a space (not "WebApp")
On the open web app button there needs to be a space:

![image](https://cloud.githubusercontent.com/assets/3472628/20719429/1836b5f8-b619-11e6-9d5d-74611fdb5fe7.png)



Discussion:

Resolving patch:
diff --git a/hs_tools_resource/migrations/0010_auto_20161203_1913.py b/hs_tools_resource/migrations/0010_auto_20161203_1913.py
--- a/hs_tools_resource/migrations/0010_auto_20161203_1913.py
+++ b/hs_tools_resource/migrations/0010_auto_20161203_1913.py
@@ -11,14 +11,15 @@ class Migration(migrations.Migration):
     ]
 
     operations = [
-        migrations.RemoveField(
+        migrations.AlterField(
             model_name='toolicon',
             name='url',
+            field=models.CharField(default=b'', max_length=1024, blank=True),
         ),
-        migrations.AddField(
+        migrations.RenameField(
             model_name='toolicon',
-            name='value',
-            field=models.CharField(default=b'', max_length=1024, blank=True),
+            old_name='url',
+            new_name='value'
         ),
         migrations.AlterField(
             model_name='apphomepageurl',


Test patch:
Repository: hydroshare/hydroshare

Issue:
Rename userInfo/ API endpoint to user/
Placeholder ticket


Discussion:

Resolving patch:
diff --git a/hs_rest_api/urls.py b/hs_rest_api/urls.py
--- a/hs_rest_api/urls.py
+++ b/hs_rest_api/urls.py
@@ -119,6 +119,9 @@
         views.resource_rest_api.CheckTaskStatus.as_view(),
         name='get_task_status'),
 
+    url(r'^user/$',
+        views.user_rest_api.UserInfo.as_view(), name='get_logged_in_user_info'),
+
     url(r'^userInfo/$',
         views.user_rest_api.UserInfo.as_view(), name='get_logged_in_user_info'),
 


Test patch:
Repository: hydroshare/hydroshare

Issue:
moving a public resource to discoverable is currently not working
If you want to change a public resource to discoverable you have to make it private and then discoverable. You can't directly change a public resource to discoverable. 


Discussion:
Thanks @miguelcleon, I'll take a look

Resolving patch:
diff --git a/hs_core/models.py b/hs_core/models.py
--- a/hs_core/models.py
+++ b/hs_core/models.py
@@ -1690,8 +1690,7 @@ def set_discoverable(self, value, user=None):
         else:  # state change is allowed
             self.raccess.discoverable = value
             self.raccess.save()
-            if not value:  # not discoverable means also not public
-                self.set_public(value)  # This must be called, as it sets the AVU isPublic
+            self.set_public(False)
 
     def set_public(self, value, user=None):
         """Set the public flag for a resource.


Test patch:
Repository: hydroshare/hydroshare

Issue:
Metadata strings updated through hs_restclient are parsed incorrectly
When using the hs_restclient to update metadata for Generic and Composite resources (I haven't tested other types), string values are updated as a unicode string inside an array (e.g. [u'some_string'] ). 

Here's an example code snippet:
`
put_data = {"title": "New Title", "description": "New Description"}
client.updateScienceMetadata('f44c00556cd847b98dd47f3a6279014d', put_data)
`

Two resources that show this issue:
![image](https://user-images.githubusercontent.com/8953221/28534607-84703f50-705e-11e7-9e73-5edd5058368f.png)
![image](https://user-images.githubusercontent.com/8953221/28534643-984a8530-705e-11e7-84d7-df0ba05379f5.png)




Discussion:
@aphelionz - do you have any ideas on this? Is this something that we are doing incorrectly on our end?
I believe the hs_restclient is transliterating the string "New Title" to the python unicode, and then back to a normal string again, which would be represented as "[u'New Title']," which is then passed to the REST api. I'll take a look.
@aphelionz - any additional feedback on this issue? @fryarludwig is working on a tool to move data from a CUAHSI HydroServer into HydroShare, and we've got nearly the whole thing working - except updating individual metadata elements through the API. This seems like a pretty big issue with metadata updating in the API?
@horsburgh I will prioritize this next!

Resolving patch:
diff --git a/hs_core/views/resource_metadata_rest_api.py b/hs_core/views/resource_metadata_rest_api.py
--- a/hs_core/views/resource_metadata_rest_api.py
+++ b/hs_core/views/resource_metadata_rest_api.py
@@ -1,5 +1,7 @@
 import logging
 
+from django.http import QueryDict
+
 from rest_framework.response import Response
 from rest_framework.exceptions import ValidationError
 from rest_framework import status
@@ -192,6 +194,10 @@ def put(self, request, pk):
         metadata = []
         put_data = request.data.copy()
 
+        # convert the QueryDict to dict
+        if isinstance(put_data, QueryDict):
+            put_data = put_data.dict()
+
         try:
             resource.metadata.parse_for_bulk_update(put_data, metadata)
             hydroshare.update_science_metadata(pk=pk, metadata=metadata, user=request.user)


Test patch:
Repository: hydroshare/hydroshare

Issue:
Discover page: search box does NOT obey SOLR syntax
The helpful text that suggests that SOLR syntax works in the search box has been wrong for over a year. It now tokenizes terms and is not compatible with SOLR syntax. 


Discussion:

Resolving patch:
diff --git a/hs_core/discovery_form.py b/hs_core/discovery_form.py
--- a/hs_core/discovery_form.py
+++ b/hs_core/discovery_form.py
@@ -1,7 +1,5 @@
 from haystack.forms import FacetedSearchForm
-from haystack.query import SQ, SearchQuerySet
-from crispy_forms.layout import *
-from crispy_forms.bootstrap import *
+from haystack.query import SQ
 from django import forms
 
 class DiscoveryForm(FacetedSearchForm):


Test patch:
Repository: hydroshare/hydroshare

Issue:
Can't add user via admin panel



Discussion:

Resolving patch:
diff --git a/hs_core/admin.py b/hs_core/admin.py
--- a/hs_core/admin.py
+++ b/hs_core/admin.py
@@ -1,12 +1,35 @@
-from mezzanine.pages.admin import PageAdmin
+from django import forms
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.auth.forms import UserCreationForm
+from django.contrib.auth.models import User
 from django.contrib.gis import admin
 from django.contrib.contenttypes.admin import GenericTabularInline
+from django.utils.translation import ugettext_lazy as _
+
+from mezzanine.pages.admin import PageAdmin
+
 from .models import *
 
+
+class UserCreationFormExtended(UserCreationForm):
+    def __init__(self, *args, **kwargs):
+        super(UserCreationFormExtended, self).__init__(*args, **kwargs)
+        self.fields['email'] = forms.EmailField(label=_("E-mail"), max_length=75)
+
+UserAdmin.add_form = UserCreationFormExtended
+UserAdmin.add_fieldsets = (
+    (None, {
+        'classes': ('wide',),
+        'fields': ('email', 'username', 'password1', 'password2',)
+    }),
+)
+
 class InlineResourceFiles(GenericTabularInline):
     model = ResourceFile
 
 class GenericResourceAdmin(PageAdmin):
     inlines = PageAdmin.inlines + [InlineResourceFiles]
 
+admin.site.unregister(User)
+admin.site.register(User, UserAdmin)
 admin.site.register(GenericResource, GenericResourceAdmin)


Test patch:
Repository: hydroshare/hydroshare

Issue:
Permissions for Creating Folders?
Hello,

I'm working on HydroShare export functionality for Model My Watershed. I am now able to successfully create resources and add files to them (for example: [66ce7b01a1e7490383e37a407979631c](https://beta.hydroshare.org/resource/66ce7b01a1e7490383e37a407979631c/)). So far I am using `hs_restclient`'s `createResource` and `addResourceFile` methods, which work very well. However, if I try to create a folder with `createResourceFolder`, I get a HydroShareNotAuthorized exception:

```
HydroShareNotAuthorized at /export/hydroshare/
Not authorized to perform PUT on https://beta.hydroshare.org/hsapi/resource/3c741c66702649f689aedcd580e23f9b/folders/area-of-interest.
```

I am able to create folders using the HydroShare UI, so it seems I just don't have the permission in the REST API, which seems odd.

Here's what my code looks like (messy, early draft):

```python
resource = hs.createResource(
    'CompositeResource',
    params.get('title', project.name),
    abstract=params.get('abstract', ''),
    keywords=('mmw', 'model-my-watershed')
)

aoi_folder = 'area-of-interest'
hs.createResourceFolder(resource, pathname=aoi_folder)

# AoI GeoJSON
aoi_geojson = GEOSGeometry(project.area_of_interest).geojson
aoi_file = StringIO.StringIO()
aoi_file.write(aoi_geojson)
hs.addResourceFile(resource, aoi_file,
                   '{}/{}'.format(aoi_folder, 'shape.geojson'))

# AoI Shapefile
aoi_json = json.loads(aoi_geojson)
crs = {'no_defs': True, 'proj': 'longlat',
       'ellps': 'WGS84', 'datum': 'WGS84'}
schema = {'geometry': aoi_json['type'], 'properties': {}}
with fiona.open('/tmp/{}.shp'.format(resource), 'w',
                driver='ESRI Shapefile',
                crs=crs, schema=schema) as shapefile:
    shapefile.write({'geometry': aoi_json, 'properties': {}})

for ext in SHAPEFILE_EXTENSIONS:
    with open('/tmp/{}.{}'.format(resource, ext)) as shapefile:
        hs.addResourceFile(resource, shapefile,
                           '{}/shape.{}'.format(aoi_folder, ext))
```


Discussion:
Hi @rajadain thanks for reporting this. I should be able to get to this later this week.

Resolving patch:
diff --git a/hs_composite_resource/models.py b/hs_composite_resource/models.py
--- a/hs_composite_resource/models.py
+++ b/hs_composite_resource/models.py
@@ -37,6 +37,11 @@ def set_default_logical_file(self):
                 res_file.logical_file_content_object = logical_file
                 res_file.save()
 
+    @property
+    def supports_folders(self):
+        """ allow folders for CompositeResources """
+        return True
+
     @property
     def supports_logical_file(self):
         """ if this resource allows associating resource file objects with logical file"""


Test patch: