anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: inventree/inventree
Issue: [BUG] could not serialize access due to concurrent update

could not serialize access due to concurrent update

and just crash....

Changed files:
InvenTree/InvenTree/exchange.py

diff --git a/InvenTree/InvenTree/exchange.py b/InvenTree/InvenTree/exchange.py
index 9981e52ff..936dd7a76 100644
--- a/InvenTree/InvenTree/exchange.py
+++ b/InvenTree/InvenTree/exchange.py
@@ -2,6 +2,7 @@ from common.settings import currency_code_default, currency_codes
 from urllib.error import HTTPError, URLError
 
 from djmoney.contrib.exchange.backends.base import SimpleExchangeBackend
+from django.db.utils import OperationalError
 
 
 class InvenTreeExchange(SimpleExchangeBackend):
@@ -32,3 +33,12 @@ class InvenTreeExchange(SimpleExchangeBackend):
         # catch connection errors
         except (HTTPError, URLError):
             print('Encountered connection error while updating')
+        except OperationalError as e:
+            if 'SerializationFailure' in e.__cause__.__class__.__name__:
+                print('Serialization Failure while updating exchange rates')
+                # We are just going to swallow this exception because the
+                # exchange rates will be updated later by the scheduled task
+            else:
+                # Other operational errors probably are still show stoppers
+                # so reraise them so that the log contains the stacktrace
+                raise
Repository: inventree/inventree
Issue: [BUG] Demo Instance Javascript Language

Javascript files for the demo instance seem to be "stuck" on the german translation.

Changed files:
InvenTree/part/templatetags/inventree_extras.py

diff --git a/InvenTree/part/templatetags/inventree_extras.py b/InvenTree/part/templatetags/inventree_extras.py
index e2faedfd9..64b8b8536 100644
--- a/InvenTree/part/templatetags/inventree_extras.py
+++ b/InvenTree/part/templatetags/inventree_extras.py
@@ -451,8 +451,17 @@ class I18nStaticNode(StaticNode):
     replaces a variable named *lng* in the path with the current language
     """
     def render(self, context):
-        self.path.var = self.path.var.format(lng=context.request.LANGUAGE_CODE)
+
+        self.original = getattr(self, 'original', None)
+
+        if not self.original:
+            # Store the original (un-rendered) path template, as it gets overwritten below
+            self.original = self.path.var
+
+        self.path.var = self.original.format(lng=context.request.LANGUAGE_CODE)
+
         ret = super().render(context)
+
         return ret
 
 
@@ -480,4 +489,5 @@ else:
         # change path to called ressource
         bits[1] = f"'{loc_name}/{{lng}}.{bits[1][1:-1]}'"
         token.contents = ' '.join(bits)
+
         return I18nStaticNode.handle_token(parser, token)
Repository: inventree/inventree
Issue: [BUG] Exception thrown when opening part "'NoneType' object has no attribute 'strftime'"

<!---
Everything inside these brackets is hidden - please remove them where you fill out information.
--->


I entered a new part yesterday, complete with picture and all. Attached it to an order, and issued the order.
I.e. on all accounts the part was fine yesterday.
I started the server again today, and now opening the part overview page, I get "'NoneType' object has no attribute 'strftime'".
I have attached the traceback.

I can open the part in the admin site. There it looks fine.
 I tried updating an attribute on the part there and save, but it didn't resolve the issue.

How the part got into this state, I don't know. Unfortunately, I can't retrace the steps I may have done to cause this issue.

I'm running the main branch on bare metal.

[traceback.txt](https://github.com/inventree/InvenTree/files/7627107/traceback.txt)




Changed files:
InvenTree/part/views.py

diff --git a/InvenTree/part/views.py b/InvenTree/part/views.py
index cd9ea6b41..6e742dc57 100644
--- a/InvenTree/part/views.py
+++ b/InvenTree/part/views.py
@@ -439,10 +439,14 @@ class PartDetail(InvenTreeRoleMixin, DetailView):
                         line['price_part'] = stock_item.supplier_part.unit_pricing
 
                 # set date for graph labels
-                if stock_item.purchase_order:
+                if stock_item.purchase_order and stock_item.purchase_order.issue_date:
                     line['date'] = stock_item.purchase_order.issue_date.strftime('%d.%m.%Y')
-                else:
+                elif stock_item.tracking_info.count() > 0:
                     line['date'] = stock_item.tracking_info.first().date.strftime('%d.%m.%Y')
+                else:
+                    # Not enough information
+                    continue
+
                 price_history.append(line)
 
             ctx['price_history'] = price_history
Repository: inventree/inventree
Issue: Validate barcode hashing

It appears that barcode hashing from different sources (e.g. app and zebra barcode scanner) can provide different hash values for the same barcode! This needs to be investigated and fixed.

Changed files:
InvenTree/barcode/barcode.py

diff --git a/InvenTree/barcode/barcode.py b/InvenTree/barcode/barcode.py
index 87235db19..3837fef59 100644
--- a/InvenTree/barcode/barcode.py
+++ b/InvenTree/barcode/barcode.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
 
+import string
 import hashlib
 import logging
 
@@ -16,9 +17,18 @@ logger = logging.getLogger(__name__)
 
 def hash_barcode(barcode_data):
     """
-    Calculate an MD5 hash of barcode data
+    Calculate an MD5 hash of barcode data.
+
+    HACK: Remove any 'non printable' characters from the hash,
+          as it seems browers will remove special control characters...
+        
+    TODO: Work out a way around this!
     """
 
+    printable_chars = filter(lambda x: x in string.printable, barcode_data)
+
+    barcode_data = ''.join(list(printable_chars))
+
     hash = hashlib.md5(str(barcode_data).encode())
     return str(hash.hexdigest())
Repository: inventree/inventree
Issue: [BUG] "Available Stock" field is not presented correctly when exporting BOM 

### Error

- "Available Stock" reported as e.g. 1.00000
- Should be normalized e.g. 1

- Specifically found in `.xslx` export format
- Need to try other formats

Changed files:
InvenTree/part/bom.py

diff --git a/InvenTree/part/bom.py b/InvenTree/part/bom.py
index d09cc5130..fd31aba33 100644
--- a/InvenTree/part/bom.py
+++ b/InvenTree/part/bom.py
@@ -7,7 +7,7 @@ from collections import OrderedDict
 
 from django.utils.translation import gettext as _
 
-from InvenTree.helpers import DownloadFile, GetExportFormats
+from InvenTree.helpers import DownloadFile, GetExportFormats, normalize
 
 from .admin import BomItemResource
 from .models import BomItem
@@ -59,7 +59,7 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa
 
     uids = []
 
-    def add_items(items, level):
+    def add_items(items, level, cascade):
         # Add items at a given layer
         for item in items:
 
@@ -71,21 +71,13 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa
 
             bom_items.append(item)
 
-            if item.sub_part.assembly:
+            if cascade and item.sub_part.assembly:
                 if max_levels is None or level < max_levels:
                     add_items(item.sub_part.bom_items.all().order_by('id'), level + 1)
 
-    if cascade:
-        # Cascading (multi-level) BOM
+    top_level_items = part.get_bom_items().order_by('id')
 
-        # Start with the top level
-        items_to_process = part.bom_items.all().order_by('id')
-
-        add_items(items_to_process, 1)
-
-    else:
-        # No cascading needed - just the top-level items
-        bom_items = [item for item in part.bom_items.all().order_by('id')]
+    add_items(top_level_items, 1, cascade)
 
     dataset = BomItemResource().export(queryset=bom_items, cascade=cascade)
 
@@ -148,8 +140,9 @@ def ExportBom(part, fmt='csv', cascade=False, max_levels=None, parameter_data=Fa
                     stock_data.append('')
             except AttributeError:
                 stock_data.append('')
+
             # Get part current stock
-            stock_data.append(str(bom_item.sub_part.available_stock))
+            stock_data.append(str(normalize(bom_item.sub_part.available_stock)))
 
             for s_idx, header in enumerate(stock_headers):
                 try:
Repository: inventree/inventree
Issue: Admin interface can be super slow

Some pages on the admin interface takes ages (like, 10 seconds) to render.. 

Need to profile them to work out where the inefficiencies are.

Changed files:
InvenTree/company/models.py, InvenTree/order/admin.py, InvenTree/company/api.py

diff --git a/InvenTree/company/api.py b/InvenTree/company/api.py
index 2c05c98d9..76b08ec27 100644
--- a/InvenTree/company/api.py
+++ b/InvenTree/company/api.py
@@ -263,11 +263,7 @@ class SupplierPartList(generics.ListCreateAPIView):
     - POST: Create a new SupplierPart object
     """
 
-    queryset = SupplierPart.objects.all().prefetch_related(
-        'part',
-        'supplier',
-        'manufacturer_part__manufacturer',
-    )
+    queryset = SupplierPart.objects.all()
 
     def get_queryset(self):
 
diff --git a/InvenTree/company/models.py b/InvenTree/company/models.py
index 378653131..778e00cde 100644
--- a/InvenTree/company/models.py
+++ b/InvenTree/company/models.py
@@ -430,6 +430,22 @@ class ManufacturerPartParameter(models.Model):
     )
 
 
+class SupplierPartManager(models.Manager):
+    """ Define custom SupplierPart objects manager
+
+        The main purpose of this manager is to improve database hit as the
+        SupplierPart model involves A LOT of foreign keys lookups
+    """
+
+    def get_queryset(self):
+        # Always prefetch related models
+        return super().get_queryset().prefetch_related(
+            'part',
+            'supplier',
+            'manufacturer_part__manufacturer',
+        )
+
+
 class SupplierPart(models.Model):
     """ Represents a unique part as provided by a Supplier
     Each SupplierPart is identified by a SKU (Supplier Part Number)
@@ -450,6 +466,8 @@ class SupplierPart(models.Model):
         packaging: packaging that the part is supplied in, e.g. "Reel"
     """
 
+    objects = SupplierPartManager()
+
     @staticmethod
     def get_api_url():
         return reverse('api-supplier-part-list')
diff --git a/InvenTree/order/admin.py b/InvenTree/order/admin.py
index 1e7b20e5a..5d843fc62 100644
--- a/InvenTree/order/admin.py
+++ b/InvenTree/order/admin.py
@@ -15,6 +15,7 @@ from .models import SalesOrderAllocation
 
 class PurchaseOrderLineItemInlineAdmin(admin.StackedInline):
     model = PurchaseOrderLineItem
+    extra = 0
 
 
 class PurchaseOrderAdmin(ImportExportModelAdmin):
Repository: inventree/inventree
Issue: Migration warns for phantom part changes 

Here is the warning:

```
Your models in app(s): 'part' have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
```

Running `manage.py makemigrations` does **not** generate new migration file...

Running `manage.py showmigrations part` shows all part migrations are complete.

I found this warning both with PostGreSQL and SQLite3, if that has anything to do with backend dependency.

Changed files:
InvenTree/InvenTree/fields.py

diff --git a/InvenTree/InvenTree/fields.py b/InvenTree/InvenTree/fields.py
index 462d2b0e0..cd98bf50c 100644
--- a/InvenTree/InvenTree/fields.py
+++ b/InvenTree/InvenTree/fields.py
@@ -55,7 +55,7 @@ class InvenTreeModelMoneyField(ModelMoneyField):
     
     def __init__(self, **kwargs):
         # detect if creating migration
-        if 'makemigrations' in sys.argv:
+        if 'migrate' in sys.argv or 'makemigrations' in sys.argv:
             # remove currency information for a clean migration
             kwargs['default_currency'] = ''
             kwargs['currency_choices'] = []
Repository: inventree/inventree
Issue: [BUG] maintenance_mode_state.txt permissions

@matmair I've had some issues updating an InvenTree instance to latest master after the plugin merge.

The error was the user which runs the server does did not have permissions to write to this file:

`./InvenTree/InvenTree/maintenance_mode_state_.txt`

I sorted the permissions out, but I am wondering if this file needs to be brought out of the source directory as it is a "user configurable" (or at least run-time configurable) file.

For example we bring "config.yaml" out into a separate directory.

Could this file path be specified as part of the InvenTree run-time settings? Either as an environment variable or a variable within config.yaml?

Changed files:
InvenTree/InvenTree/settings.py

diff --git a/InvenTree/InvenTree/settings.py b/InvenTree/InvenTree/settings.py
index 70447371f..19e5518eb 100644
--- a/InvenTree/InvenTree/settings.py
+++ b/InvenTree/InvenTree/settings.py
@@ -215,10 +215,6 @@ MAINTENANCE_MODE_STATE_FILE_PATH = os.path.join(
     'maintenance_mode_state.txt',
 )
 
-MAINTENANCE_MODE_IGNORE_ADMIN_SITE = True
-
-MAINTENANCE_MODE_IGNORE_SUPERUSER = True
-
 # List of allowed hosts (default = allow all)
 ALLOWED_HOSTS = CONFIG.get('allowed_hosts', ['*'])
Repository: gee-community/geemap
Issue: Impossible to load 1 band from a multi-band raster using add_raster method

### Environment Information

-   geemap version: 0.8.15
-   Python version: 3.6.9
-   Operating System: Linux Debian

### Description

when using a multi-band raster where 1,2 and 3 are not representing satellites bands but grid information (in my case the first band is the magnitude of change in the pixel during a monitoring period and the second one is the day of the break in julian days). 

what I'm doing is using the `add_raster` method as follow: 

```python
Map.add_raster( image_path, bands=1, layer_name='magnitude', colormap='viridis')
```

But my map is always displayed in RGB flavour. 

Looking at the code I found this `if` statement https://github.com/giswqs/geemap/blob/681d757d29f278a370882646a3ab5f7f0ce5bc28/geemap/geemap.py#L3201 :

```python
 multi_band = False
 if len(da.band) > 1:
     multi_band = True
     if bands is None:
         bands = [3, 2, 1]
else:
    bands = 1        

if multi_band:
    da = da.rio.write_nodata(0)
else:
    da = da.rio.write_nodata(np.nan)
da = da.sel(band=bands)
```

So in my case as the file is multiband the  `multi_band` bool will end up as `True`. Problem is that in the call to xarrayleaflet, the `rgb_dim="band"`will be used instead of `colormap`


Changed files:
geemap/geemap.py

diff --git a/geemap/geemap.py b/geemap/geemap.py
index 73846756..597f6dab 100644
--- a/geemap/geemap.py
+++ b/geemap/geemap.py
@@ -3220,7 +3220,7 @@ class Map(ipyleaflet.Map):
         # da = da.rio.write_nodata(0)
         # da = da.rio.write_crs(crs)
 
-        if multi_band:
+        if multi_band and type(bands) == list:
             layer = da.leaflet.plot(self, x_dim=x_dim, y_dim=y_dim, rgb_dim="band")
         else:
             layer = da.leaflet.plot(self, x_dim=x_dim, y_dim=y_dim, colormap=colormap)
Repository: asottile/pyupgrade
Issue: Broken imports

When rewriting the following code

```python
from typing import Optional, Sequence as SequenceType
```

pyupgrade duplicates the `as SequenceType`:

```python
from typing import Optional as SequenceType
from collections.abc import Sequence as SequenceType
```

I've ran it with `pyupgrade --py39-plus tmp.py`.  Happens with both the current release (3.3.1) and the main branch.

Changed files:
tests/features/import_replaces_test.py, pyupgrade/_plugins/imports.py

diff --git a/pyupgrade/_plugins/imports.py b/pyupgrade/_plugins/imports.py
index f6e0359..823d634 100644
--- a/pyupgrade/_plugins/imports.py
+++ b/pyupgrade/_plugins/imports.py
@@ -281,6 +281,7 @@ class FromImport(NamedTuple):
     mod_start: int
     mod_end: int
     names: tuple[int, ...]
+    ends: tuple[int, ...]
     end: int
 
     @classmethod
@@ -310,11 +311,14 @@ class FromImport(NamedTuple):
             for j in range(import_token + 1, end)
             if tokens[j].name == 'NAME'
         ]
+        ends_by_offset = {}
         for i in reversed(range(len(names))):
             if tokens[names[i]].src == 'as':
+                ends_by_offset[names[i - 1]] = names[i + 1]
                 del names[i:i + 2]
+        ends = tuple(ends_by_offset.get(pos, pos) for pos in names)
 
-        return cls(start, mod_start, mod_end + 1, tuple(names), end)
+        return cls(start, mod_start, mod_end + 1, tuple(names), ends, end)
 
     def remove_self(self, tokens: list[Token]) -> None:
         del tokens[self.start:self.end]
@@ -327,10 +331,10 @@ class FromImport(NamedTuple):
             if idx == 0:  # look forward until next name and del
                 del tokens[self.names[idx]:self.names[idx + 1]]
             else:  # look backward for comma and del
-                j = end = self.names[idx]
+                j = self.names[idx]
                 while tokens[j].src != ',':
                     j -= 1
-                del tokens[j:end + 1]
+                del tokens[j:self.ends[idx] + 1]
 
 
 def _alias_to_s(alias: ast.alias) -> str:
diff --git a/tests/features/import_replaces_test.py b/tests/features/import_replaces_test.py
index 386afdb..07bc228 100644
--- a/tests/features/import_replaces_test.py
+++ b/tests/features/import_replaces_test.py
@@ -305,6 +305,13 @@ def test_mock_noop_keep_mock():
             'from collections.abc import Callable\\n',
             id='typing.Callable is rewritable in 3.10+ only',
         ),
+        pytest.param(
+            'from typing import Optional, Sequence as S\\n',
+            (3, 10),
+            'from typing import Optional\\n'
+            'from collections.abc import Sequence as S\\n',
+            id='aliasing in multi from import',
+        ),
     ),
 )
 def test_import_replaces(s, min_version, expected):
Repository: microsoft/onefuzz
Issue: `target_timeout` not set when creating task with libfuzzer template

<!-- Please read our Rules of Conduct: https://opensource.microsoft.com/codeofconduct/ -->
<!-- Please search existing issues to avoid creating duplicates. -->

## Information

- Onefuzz version: 8.5
- OS: N/A

## Provide detailed reproduction steps (if any)

1. Create a new job with `onefuzz libfuzzer template basic .... --target_timeout 360`
2. Get the a task that was created `onefuzz tasks get {task id}`
3. Notice the `target_timeout` isn't present in the response

It's not in the storage table either so we never store it

### Expected result

_What is the expected result of the above steps?_

### Actual result

_What is the actual result of the above steps?_


[AB#162552](https://fuzzfest.visualstudio.com/5eaacf23-2084-4d62-8fbe-7d37326a8b74/_workitems/edit/162552)

Changed files:
src/cli/onefuzz/templates/libfuzzer.py

diff --git a/src/cli/onefuzz/templates/libfuzzer.py b/src/cli/onefuzz/templates/libfuzzer.py
index ceb9ac1c..2dd1891e 100644
--- a/src/cli/onefuzz/templates/libfuzzer.py
+++ b/src/cli/onefuzz/templates/libfuzzer.py
@@ -500,6 +500,7 @@ class Libfuzzer(Command):
             analyzer_env=analyzer_env,
             tools=tools,
             task_env=task_env,
+            target_timeout=target_timeout,
         )
 
         self.logger.info("done creating tasks")
Repository: microsoft/onefuzz
Issue: CLI Libfuzzer template does not parse list of fuzzer target arguments correctly

trying to parse

onefuzz template libfuzzer basic --minimized_stack_depth 4 --duration 48 --fuzzing_target_options **-runs=10000 -rss_limit_mb=4096** -colocate_all_tasks 


onefuzz fails with

onefuzz.exe: error: unrecognized arguments: -runs=10000 -rss_limit_mb=4096

AB#40383116

Changed files:
src/cli/onefuzz/templates/libfuzzer.py

diff --git a/src/cli/onefuzz/templates/libfuzzer.py b/src/cli/onefuzz/templates/libfuzzer.py
index adf766be..c25ddea4 100644
--- a/src/cli/onefuzz/templates/libfuzzer.py
+++ b/src/cli/onefuzz/templates/libfuzzer.py
@@ -130,7 +130,13 @@ class Libfuzzer(Command):
         libfuzzer_fuzz_target_options = target_options.copy()
 
         if fuzzing_target_options:
-            libfuzzer_fuzz_target_options += fuzzing_target_options
+            # Add each _fuzzing-only_ target option to the `target_options` for the fuzzing task.
+            #
+            # Trim any surrounding whitespace to allow users to quote multiple options with extra
+            # whitespace as a workaround for CLI argument parsing limitations. Trimming is needed
+            # to ensure that the fuzzer binary eventually parses the arguments as options.
+            for option in fuzzing_target_options:
+                libfuzzer_fuzz_target_options.append(option.strip())
 
         fuzzer_task = self.onefuzz.tasks.create(
             job.job_id,
Repository: mljar/mljar-supervised
Issue: Regression metric to be optimized

RF is optimizing MSE but we report in the print the RMSE. Please verify this.

Changed files:
supervised/algorithms/sklearn.py

diff --git a/supervised/algorithms/sklearn.py b/supervised/algorithms/sklearn.py
index aaaef0a..1fc72f6 100644
--- a/supervised/algorithms/sklearn.py
+++ b/supervised/algorithms/sklearn.py
@@ -144,5 +144,5 @@ def predict_function(estimator, X):
 class SklearnTreesEnsembleRegressorAlgorithm(SklearnTreesEnsembleClassifierAlgorithm):
     def __init__(self, params):
         super(SklearnTreesEnsembleRegressorAlgorithm, self).__init__(params)
-        self.log_metric = Metric({"name": "rmse"})
+        self.log_metric = Metric({"name": "mse"})
         self.predict_function = predict_function