czlll/Loc-Bench_V0.1 huggingface dataset:
Repository: sympy/sympy
Issue category: Bug Report

Converting from `numpy.float32(float('inf'))` throws
sympy==1.13.3
numpy==2.1.3
python 3.10.15

```python
import numpy
import sympy
sympy.Float(np.float32(float('inf')))
```
thows with:
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../lib/python3.10/site-packages/sympy/core/numbers.py", line 805, in __new__
    num = _convert_numpy_types(num)
  File ".../lib/python3.10/site-packages/sympy/core/sympify.py", line 93, in _convert_numpy_types
    p, q = a.as_integer_ratio()
OverflowError: cannot convert Infinity to integer ratio
```


Functions to edit:
sympy/core/sympify.py:_convert_numpy_types

Patch:
diff --git a/sympy/core/sympify.py b/sympy/core/sympify.py
index 0024d0a70a68..716833f15aa7 100644
--- a/sympy/core/sympify.py
+++ b/sympy/core/sympify.py
@@ -100,9 +100,14 @@ def _convert_numpy_types(a, **sympify_args):
         prec = np.finfo(a).nmant + 1
         # E.g. double precision means prec=53 but nmant=52
         # Leading bit of mantissa is always 1, so is not stored
-        p, q = a.as_integer_ratio()
-        a = mlib.from_rational(p, q, prec)
-        return Float(a, precision=prec)
+        if np.isposinf(a):
+            return Float('inf')
+        elif np.isneginf(a):
+            return Float('-inf')
+        else:
+            p, q = a.as_integer_ratio()
+            a = mlib.from_rational(p, q, prec)
+            return Float(a, precision=prec)
 
 
 @overload

Test patch: diff --git a/sympy/core/tests/test_sympify.py b/sympy/core/tests/test_sympify.py
index fc87fa448351..40be30c25d58 100644
--- a/sympy/core/tests/test_sympify.py
+++ b/sympy/core/tests/test_sympify.py
@@ -883,3 +883,10 @@ def test_issue_21536():
     assert u.is_Add and set(u.args) == {4*x, 2}
     assert v.is_Add and set(v.args) == {6*x, 6}
     assert sympify(["x+3*x+2", "2*x+4*x+2+4"]) == [u, v]
+
+def test_issue_27284():
+    if not numpy:
+        skip("numpy not installed.")
+
+    assert Float(numpy.float32(float('inf'))) == S.Infinity
+    assert Float(numpy.float32(float('-inf'))) == S.NegativeInfinity
Repository: jax-ml/jax
Issue category: Bug Report

bincount rejects bool
### Description

[numpy.bincount](https://numpy.org/doc/stable/reference/generated/numpy.bincount.html) accepts bool, but [jax.numpy.bincount](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bincount.html) does not:

```sh
$ py -c "import numpy as np; print(np.bincount(np.ones(3, bool)))"
[0 3]
$ py -c "from jax import numpy as jnp; print(jnp.bincount(jnp.ones(3, bool)))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/carlos/venv/lib/python3.12/site-packages/jax/_src/numpy/lax_numpy.py", line 3068, in bincount
    raise TypeError(f"x argument to bincount must have an integer type; got {_dtype(x)}")
TypeError: x argument to bincount must have an integer type; got bool
```

### System info (python version, jaxlib version, accelerator, etc.)

```
jax:    0.4.35
jaxlib: 0.4.34
numpy:  1.26.4
python: 3.12.7 (main, Oct  1 2024, 02:05:46) [Clang 15.0.0 (clang-1500.3.9.4)]
device info: cpu-1, 1 local devices"
process_count: 1
platform: uname_result(system='Darwin', node='Carloss-MacBook-Pro-2.local', release='23.6.0', version='Darwin Kernel Version 23.6.0: Mon Jul 29 21:14:46 PDT 2024; root:xnu-10063.141.2~1/RELEASE_ARM64_T6031', machine='arm64')
```


Functions to edit:
jax/_src/numpy/lax_numpy.py:bincount

Patch:
diff --git a/jax/_src/numpy/lax_numpy.py b/jax/_src/numpy/lax_numpy.py
index d2e89833915d..b90004e19932 100644
--- a/jax/_src/numpy/lax_numpy.py
+++ b/jax/_src/numpy/lax_numpy.py
@@ -3070,6 +3070,8 @@ def bincount(x: ArrayLike, weights: ArrayLike | None = None,
     Array([2, 1, 0, 1, 0], dtype=int32)
   """
   util.check_arraylike("bincount", x)
+  if _dtype(x) == bool:
+    x = lax.convert_element_type(x, 'int32')
   if not issubdtype(_dtype(x), integer):
     raise TypeError(f"x argument to bincount must have an integer type; got {_dtype(x)}")
   if ndim(x) != 1:
@@ -3080,7 +3082,7 @@ def bincount(x: ArrayLike, weights: ArrayLike | None = None,
     x_arr = core.concrete_or_error(asarray, x,
       "The error occurred because of argument 'x' of jnp.bincount. "
       "To avoid this error, pass a static `length` argument.")
-    length = max(minlength, x_arr.size and int(x_arr.max()) + 1)
+    length = max(minlength, x_arr.size and int(max(0, x_arr.max())) + 1)
   else:
     length = core.concrete_dim_or_error(length,
         "The error occurred because of argument 'length' of jnp.bincount.")

Test patch: diff --git a/tests/lax_numpy_test.py b/tests/lax_numpy_test.py
index 61baa7c97df4..7c2728af415e 100644
--- a/tests/lax_numpy_test.py
+++ b/tests/lax_numpy_test.py
@@ -4905,7 +4905,7 @@ def testAtLeastNdLiterals(self, dtype, op):
 
   @jtu.sample_product(
     shape=[(0,), (5,), (10,)],
-    dtype=int_dtypes,
+    dtype=int_dtypes + bool_dtypes,
     weights=[True, False],
     minlength=[0, 20],
     length=[None, 8],
Repository: jax-ml/jax
Issue category: Performance Issue

jnp.select should use jax.lax.select_n
### Description

jnp.select is a function that's like jnp.where, but selects between n different arrays. jnp.where is a wrapper around jax.lax.select, which makes it more flexible in terms of input shapes and dtypes.

jax.lax.select_n (added in #9482 ) is a generalization of jax.lax.select to pick from n arrays rather than 2; it translates at lower time into a binary tree of jax.lax.select's, which is helpful for efficiency when there are many branches. jnp.select doesn't use this: it linearly chains jnp.where's across the different arrays. It would likely help performance if it did, particularly in the case where the condlist entries have lower ndim than the choicelist.

### System info (python version, jaxlib version, accelerator, etc.)

jax:    0.4.27
jaxlib: 0.4.27
numpy:  1.26.3
python: 3.11.8 (stable, redacted, redacted) [Clang google3-trunk (3b5e7c83a6e226d5bd7ed2e9b67449b64812074c)]
jax.devices (16 total, 16 local): [TpuDevice(id=0, process_index=0, coords=(0,0,0), core_on_chip=0) TpuDevice(id=1, process_index=0, coords=(0,0,0), core_on_chip=1) ... TpuDevice(id=14, process_index=0, coords=(3,1,0), core_on_chip=0) TpuDevice(id=15, process_index=0, coords=(3,1,0), core_on_chip=1)]
process_count: 1
platform: uname_result(system='Linux', node='ebe6e776479e64ea-65d7388ae36.borgtask.google.com', release='5.10.0-smp-1101.33.0.0', version='#1 [v5.10.0-1101.33.0.0] SMP @1708585970', machine='x86_64')



Functions to edit:
jax/_src/numpy/lax_numpy.py:select

Patch:
diff --git a/jax/_src/numpy/lax_numpy.py b/jax/_src/numpy/lax_numpy.py
index 3767633deefc..f7686ec467d6 100644
--- a/jax/_src/numpy/lax_numpy.py
+++ b/jax/_src/numpy/lax_numpy.py
@@ -1162,12 +1162,12 @@ def select(
     raise ValueError(msg.format(len(condlist), len(choicelist)))
   if len(condlist) == 0:
     raise ValueError("condlist must be non-empty")
-  choices = util.promote_dtypes(default, *choicelist)
-  choicelist = choices[1:]
-  output = choices[0]
-  for cond, choice in zip(condlist[::-1], choicelist[::-1]):
-    output = where(cond, choice, output)
-  return output
+  # Put the default at front with condition False because
+  # argmax returns zero for an array of False values.
+  choicelist = util.promote_dtypes(default, *choicelist)
+  conditions = stack(broadcast_arrays(False, *condlist))
+  idx = argmax(conditions.astype(bool), axis=0)
+  return lax.select_n(*broadcast_arrays(idx, *choicelist))
 
 
 @util.implements(np.bincount, lax_description="""\

Test patch: diff --git a/tests/lax_numpy_test.py b/tests/lax_numpy_test.py
index ddc599792e63..ee6c3601a1bb 100644
--- a/tests/lax_numpy_test.py
+++ b/tests/lax_numpy_test.py
@@ -4532,6 +4532,7 @@ def testWhereScalarPromotion(self):
     # maximal set of dtypes.
     dtypes=itertools.combinations_with_replacement(all_dtypes, 3),
   )
+  @jax.numpy_rank_promotion('allow')
   def testSelect(self, n, shapes, dtypes):
     dtypes = dtypes[:n+1]
     rng = jtu.rand_default(self.rng())
Repository: prowler-cloud/prowler
Issue category: Bug Report

rds_service.py error
### Steps to Reproduce

1. Running prowler aws -log-level ERROR
2. AWS
3. Single Account

### Expected behavior

To execute without throwing the error

### Actual Result with Screenshots or Logs

2024-11-28 10:20:18,851 [File: rds_service.py:458] [Module: rds_service] ERROR: eu-west-2 -- KeyError[449]: 'SourceType'

We have an postgress RDS 16.3 instance in eu-west-2 and the script is throwing this error

### How did you install Prowler?

From pip package (pip install prowler)

### Environment Resource

2. ECS Fargate task

### OS used

3. Alpine Linux

### Prowler version

4.6.0

### Pip version

na

### Context

_No response_


Functions to edit:
prowler/providers/aws/services/rds/rds_service.py:RDS._describe_db_event_subscriptions

Patch:
diff --git a/prowler/providers/aws/services/rds/rds_service.py b/prowler/providers/aws/services/rds/rds_service.py
index b4dd5d66ce9..60d24b1cb1b 100644
--- a/prowler/providers/aws/services/rds/rds_service.py
+++ b/prowler/providers/aws/services/rds/rds_service.py
@@ -446,7 +446,7 @@ def _describe_db_event_subscriptions(self, regional_client):
                                     arn=arn,
                                     sns_topic_arn=event["SnsTopicArn"],
                                     status=event["Status"],
-                                    source_type=event["SourceType"],
+                                    source_type=event.get("SourceType", ""),
                                     source_id=event.get("SourceIdsList", []),
                                     event_list=event.get("EventCategoriesList", []),
                                     enabled=event["Enabled"],
Repository: prowler-cloud/prowler
Issue category: Bug Report

Prowler CSV Output no longer outputs Failed Critical Findings
### Steps to Reproduce

Running prowler 4.5.3
Execute prowler aws against an AWS account. 
CSV Outputs PASS critical findings but does output FAIL findings.

Prowler Dashboard does not display any cirtical findings

It was working with 4.3.5 but after I upgraded to 4.5.3 this now fails.

json-ocsf files are fine. These do contain Critical Fail


### Expected behavior

Failed critical findings to be contained in CSV file to use with prowler dashboard

### Actual Result with Screenshots or Logs

prowler aws --output-bucket-no-assume prowler-output-bucket-XXXXXXXXXXXX --output-directory output --slack --role arn:aws:iam::XXXXXXXXXXXX:role/XXXXXXXXXXX --role-session-name XXXXX_XXXXXX

### How did you install Prowler?

From pip package (pip install prowler)

### Environment Resource

2. Fargate Task running python:alpine with python 3.12

### OS used

3. Alpine Linux

### Prowler version

4.5.3

### Pip version

3.12

### Context

_No response_


Functions to edit:
prowler/providers/aws/services/ec2/lib/instance.py:get_instance_public_status

Patch:
diff --git a/prowler/providers/aws/services/ec2/lib/instance.py b/prowler/providers/aws/services/ec2/lib/instance.py
index 150d37db52e..bef05ad7c50 100644
--- a/prowler/providers/aws/services/ec2/lib/instance.py
+++ b/prowler/providers/aws/services/ec2/lib/instance.py
@@ -1,3 +1,4 @@
+from prowler.lib.check.models import Severity
 from prowler.providers.aws.services.ec2.ec2_service import Instance
 from prowler.providers.aws.services.vpc.vpc_service import VpcSubnet
 
@@ -15,13 +16,13 @@ def get_instance_public_status(
         tuple: The status and severity of the instance status.
     """
     status = f"Instance {instance.id} has {service} exposed to 0.0.0.0/0 but with no public IP address."
-    severity = "medium"
+    severity = Severity.medium
 
     if instance.public_ip:
         status = f"Instance {instance.id} has {service} exposed to 0.0.0.0/0 on public IP address {instance.public_ip} but it is placed in a private subnet {instance.subnet_id}."
-        severity = "high"
+        severity = Severity.high
         if vpc_subnets[instance.subnet_id].public:
             status = f"Instance {instance.id} has {service} exposed to 0.0.0.0/0 on public IP address {instance.public_ip} in public subnet {instance.subnet_id}."
-            severity = "critical"
+            severity = Severity.critical
 
     return status, severity
Repository: prowler-cloud/prowler
Issue category: Bug Report

Invalid WAF arn
### Steps to Reproduce

Run prowler on Docker against an account with global WAF enabled.

### Expected behavior

To pass

### Actual Result with Screenshots or Logs

2024-11-18 10:09:43,933 [File: wafv2_service.py:122]    [Module: wafv2_service]  ERROR: us-east-1 -- WAFInvalidParameterException[105]: An error occurred (WAFInvalidParameterException) when calling the ListResourcesForWebACL operation: Error reason: The ARN isn't valid. A valid ARN begins with arn: and includes other information separated by colons or slashes., field: RESOURCE_ARN, parameter: arn:aws:wafv2:us-east-1:xxxxx:global/webacl/xxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx

2024-11-18 10:09:43,934 [File: wafv2_service.py:122]    [Module: wafv2_service]  ERROR: us-east-1 -- WAFInvalidParameterException[105]: An error occurred (WAFInvalidParameterException) when calling the ListResourcesForWebACL operation: Error reason: The ARN isn't valid. A valid ARN begins with arn: and includes other information separated by colons or slashes., field: RESOURCE_ARN, parameter: arn:aws:wafv2:us-east-1:xxxxx:global/webacl/xxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx

2024-11-18 10:09:43,938 [File: wafv2_service.py:122]    [Module: wafv2_service]  ERROR: us-east-1 -- WAFInvalidParameterException[105]: An error occurred (WAFInvalidParameterException) when calling the ListResourcesForWebACL operation: Error reason: The ARN isn't valid. A valid ARN begins with arn: and includes other information separated by colons or slashes., field: RESOURCE_ARN, parameter: arn:aws:wafv2:us-east-1:xxxxx:global/webacl/xxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx

### How did you install Prowler?

Docker (docker pull toniblyx/prowler)

### Environment Resource

3. Docker container locally

### OS used

One inside docker

### Prowler version

4.5.3

### Pip version

one inside docker image

### Context

We have three global WAF, and three regional WAF. The three regional works, and the three global throws an malformed arn error.


Functions to edit:
prowler/providers/aws/services/wafv2/wafv2_service.py:WAFv2._list_resources_for_web_acl

Patch:
diff --git a/prowler/providers/aws/services/wafv2/wafv2_service.py b/prowler/providers/aws/services/wafv2/wafv2_service.py
index 4971f1c4223..85feed76f62 100644
--- a/prowler/providers/aws/services/wafv2/wafv2_service.py
+++ b/prowler/providers/aws/services/wafv2/wafv2_service.py
@@ -99,7 +99,7 @@ def _get_logging_configuration(self, acl):
     def _list_resources_for_web_acl(self, acl):
         logger.info("WAFv2 - Describing resources...")
         try:
-            if acl.scope == Scope.REGIONAL or acl.region in self.regional_clients:
+            if acl.scope == Scope.REGIONAL:
                 for resource in self.regional_clients[
                     acl.region
                 ].list_resources_for_web_acl(
Repository: vllm-project/vllm
Issue category: Bug Report

[Bug]: Different default value for temperature in SamplingParams and ChatCompletionRequest
### Your current environment

<details>
<summary>The output of `python collect_env.py`</summary>

```text
Your output of `python collect_env.py` here
```

</details>


### Model Input Dumps

_No response_

### 🐛 Describe the bug

The default value for `temperature` in `SamplingParams` is `1.0`. https://github.com/vllm-project/vllm/blob/571da8fc431ec36427ee1034a7779b23229b015e/vllm/sampling_params.py#L176

The default value for `temperature` in `ChatCompletionRequest` is `0.7`. https://github.com/vllm-project/vllm/blob/571da8fc431ec36427ee1034a7779b23229b015e/vllm/entrypoints/openai/protocol.py#L173

This can lead to inconsistencies between online and offline inference results.

### Before submitting a new issue...

- [X] Make sure you already searched for relevant issues, and asked the chatbot living at the bottom right corner of the [documentation page](https://docs.vllm.ai/en/latest/), which can answer lots of frequently asked questions.


Functions to edit:
vllm/entrypoints/openai/protocol.py:ChatCompletionRequest
Functions added: vllm/entrypoints/openai/protocol.py:ChatCompletionRequest

Patch:
diff --git a/vllm/entrypoints/openai/protocol.py b/vllm/entrypoints/openai/protocol.py
index dfb7c977dbd43..6ed7c2e9dcd6b 100644
--- a/vllm/entrypoints/openai/protocol.py
+++ b/vllm/entrypoints/openai/protocol.py
@@ -211,7 +211,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
     stop: Optional[Union[str, List[str]]] = Field(default_factory=list)
     stream: Optional[bool] = False
     stream_options: Optional[StreamOptions] = None
-    temperature: Optional[float] = 0.7
+    temperature: Optional[float] = 1.0
     top_p: Optional[float] = 1.0
     tools: Optional[List[ChatCompletionToolsParam]] = None
     tool_choice: Optional[Union[Literal["none"], Literal["auto"],
Repository: vllm-project/vllm
Issue category: Feature Request

[Feature]: Allow Ray placement group more time to wait for resources to be ready
### 🚀 The feature, motivation and pitch

```
ray start --head --dashboard-host 0.0.0.0 --disable-usage-stats --block  --num-gpus 1

python -m vllm.entrypoints.openai.api_server     --model Qwen/Qwen2.5-1.5B-Instruct     --trust-remote-code     --distributed-executor-backend ray     --tensor-parallel-size 2
```

I am using a ray cluster as the distributed executor backend. However, my cluster sometimes takes time to be ready. there are multiple reasons
- image downloading speed is different, some node has image cache and some does not.
- node short of resources, node level autoscaler will make decision to bring up more nodes but it takes time for new ray node to join and form a cluster

I do not want the engine to early exit. 

![image](https://github.com/user-attachments/assets/7a621963-21fb-4f16-9573-71299e951bad)

![image](https://github.com/user-attachments/assets/5b06c173-1465-4675-a5a0-2627a3b8b18d)


### Alternatives

_No response_

### Additional context

_No response_

### Before submitting a new issue...

- [X] Make sure you already searched for relevant issues, and asked the chatbot living at the bottom right corner of the [documentation page](https://docs.vllm.ai/en/latest/), which can answer lots of frequently asked questions.


Functions to edit:
vllm/executor/ray_utils.py:initialize_ray_cluster

Patch:
diff --git a/vllm/executor/ray_utils.py b/vllm/executor/ray_utils.py
index 4f28efd639084..426aa1b5c728f 100644
--- a/vllm/executor/ray_utils.py
+++ b/vllm/executor/ray_utils.py
@@ -277,10 +277,14 @@ def initialize_ray_cluster(
                 f"Total number of devices: {device_bundles}.")
     else:
         num_devices_in_cluster = ray.cluster_resources().get(device_str, 0)
+        # Log a warning message and delay resource allocation failure response.
+        # Avoid immediate rejection to allow user-initiated placement group
+        # created and wait cluster to be ready
         if parallel_config.world_size > num_devices_in_cluster:
-            raise ValueError(
-                f"The number of required {device_str}s exceeds the total "
-                f"number of available {device_str}s in the placement group.")
+            logger.warning(
+                "The number of required %ss exceeds the total "
+                "number of available %ss in the placement group.", device_str,
+                device_str)
         # Create a new placement group
         placement_group_specs: List[Dict[str, float]] = ([{
             device_str: 1.0
Repository: vllm-project/vllm
Issue category: Performance Issue

[Core] Avoid metrics log noise when idle

1a789ae7 [Core] Avoid metrics log noise when idle

commit 1a789ae76695bca801b55c9d4531e5438a3378c4
Author: Russell Bryant <rbryant@redhat.com>
Date:   Thu Sep 26 20:56:41 2024 +0000

    [Core] Avoid metrics log noise when idle
    
    Prior to this change, there was always a log message every 10 seconds,
    even when the system is idle. The noise when the metrics are all zeros
    doesn't seem very interesting, so this change makes it so the log
    message is only emitted while active. It will log a message whenever
    metrics are non-zero, or when returning to idle from non-idle.
    Repeated messages during idle now go to DEBUG instead of INFO.
    
    Signed-off-by: Russell Bryant <rbryant@redhat.com>



Functions to edit:
vllm/engine/metrics.py:LoggingStatLogger.log

Patch:
diff --git a/vllm/engine/metrics.py b/vllm/engine/metrics.py
index 5bfd6a9f4b386..4869557ba9b44 100644
--- a/vllm/engine/metrics.py
+++ b/vllm/engine/metrics.py
@@ -473,13 +473,13 @@ def log(self, stats: Stats) -> None:
             )
             if (stats.cpu_prefix_cache_hit_rate >= 0
                     or stats.gpu_prefix_cache_hit_rate >= 0):
-                logger.info(
+                log_fn(
                     "Prefix cache hit rate: GPU: %.2f%%, CPU: %.2f%%",
                     stats.gpu_prefix_cache_hit_rate * 100,
                     stats.cpu_prefix_cache_hit_rate * 100,
                 )
             if self.spec_decode_metrics is not None:
-                logger.info(
+                log_fn(
                     self._format_spec_decode_metrics_str(
                         self.spec_decode_metrics))
Repository: vllm-project/vllm
Issue category: Bug Report

[Bug]: from vllm.platforms import current_platform infinite loop error with OpenVino Build. 
### Your current environment

Unrelated

### Model Input Dumps

Unrelated

### 🐛 Describe the bug

In OpenVino Build, from vllm.platforms import current_platform for OpenVino will...
 * reference openvino.py in vllm.platforms.openvino.py as OpenVino is identified as current platform
 * openvino.py line 4 will reference from vllm.utils import print_warning_once
 * vllm.utils line 40 will reference from vllm.platforms import current_platform
 * Due to circular self-reference, will throw error

This impacts any vllm functionality on the openvino build due to vllm requiring detection of the current_platform.

Resolution: **removing print_warning_once dependency from openvino.py will fix, either by defining print function locally or removing logging altogether from openvino.py**



### Before submitting a new issue...

- [X] Make sure you already searched for relevant issues, and asked the chatbot living at the bottom right corner of the [documentation page](https://docs.vllm.ai/en/latest/), which can answer lots of frequently asked questions.


Functions to edit:
vllm/platforms/openvino.py:OpenVinoPlatform.is_pin_memory_available

Patch:
diff --git a/vllm/platforms/openvino.py b/vllm/platforms/openvino.py
index 35dbe22abf7ff..31fe3f1fcbfe4 100644
--- a/vllm/platforms/openvino.py
+++ b/vllm/platforms/openvino.py
@@ -1,10 +1,12 @@
 import torch
 
 import vllm.envs as envs
-from vllm.utils import print_warning_once
+from vllm.logger import init_logger
 
 from .interface import Platform, PlatformEnum
 
+logger = init_logger(__name__)
+
 
 class OpenVinoPlatform(Platform):
     _enum = PlatformEnum.OPENVINO
@@ -27,5 +29,5 @@ def is_openvino_gpu(self) -> bool:
 
     @classmethod
     def is_pin_memory_available(self) -> bool:
-        print_warning_once("Pin memory is not supported on OpenViNO.")
+        logger.warning("Pin memory is not supported on OpenViNO.")
         return False
Repository: UKPLab/sentence-transformers
Issue category: Bug Report

CrossEncoder .rank condition error in CrossEncoder.py
I get the following error when I use .rank method:

```
File /usr/local/lib/python3.12/dist-packages/sentence_transformers/cross_encoder/CrossEncoder.py:551, in CrossEncoder.rank(self, query, documents, top_k, return_documents, batch_size, show_progress_bar, num_workers, activation_fct, apply_softmax, convert_to_numpy, convert_to_tensor)
    548     if return_documents:
    549         results[-1].update({"text": documents[i]})
--> 551 results = sorted(results, key=lambda x: x["score"], reverse=True)
    552 return results[:top_k]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
I use sentence_transformers v3.3.0.

A snippet:
```python

cross_encoder = sentence_transformers.CrossEncoder("amberoad/bert-multilingual-passage-reranking-msmarco", device='cpu', max_length=256)
cross_encoder.rank(query, docs)
```



Functions to edit:
sentence_transformers/cross_encoder/CrossEncoder.py:CrossEncoder.rank

Patch:
diff --git a/sentence_transformers/cross_encoder/CrossEncoder.py b/sentence_transformers/cross_encoder/CrossEncoder.py
index c4345017a..3d7ee0abb 100644
--- a/sentence_transformers/cross_encoder/CrossEncoder.py
+++ b/sentence_transformers/cross_encoder/CrossEncoder.py
@@ -527,6 +527,11 @@ def rank(
                 'score': -5.082967,
                 'text': "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era."}]
         """
+        if self.config.num_labels != 1:
+            raise ValueError(
+                "CrossEncoder.rank() only works for models with num_labels=1. "
+                "Consider using CrossEncoder.predict() with input pairs instead."
+            )
         query_doc_pairs = [[query, doc] for doc in documents]
         scores = self.predict(
             sentences=query_doc_pairs,
Repository: UKPLab/sentence-transformers
Issue category: Bug Report

Breaking change for module loading in PyLate
Hello,

Since the version 3.1, the module are loaded with [get_class_from_dynamic_module](https://github.com/UKPLab/sentence-transformers/commit/6257cb00ef87ddc8f445f0e436377ea4c48879b2#diff-b85567d4fdaffe34a3ccd8fe6cd1fcb15a986ebd34af373c71f1f5cf5efff021R1466) when using ```trust_remote_code=True```
However, this function [breaks if the type of the modules contains more than one dot](https://github.com/huggingface/transformers/blob/31299670cda29f25fbc655f6f166e7b8cc21c89f/src/transformers/dynamic_module_utils.py#L536)
The Dense module from PyLate is saved with the type pylate.models.Dense.Dense, [due to this line](https://github.com/UKPLab/sentence-transformers/blob/ba8cb2ef1d7a5ad6b9169eddee469e900456532c/sentence_transformers/SentenceTransformer.py#L1189).

Before 3.1, the type of the module was pylate.models.Dense, but this still break when parsing on the dot. As the PyLate module still loads correctly with the ```import_from_string``` function (that was used to load the modules prior to 3.1), one of the solution is to broaden a bit the exception to prevent crash if the file is not there locally AND also if the parsing fail (```ValueError: too many values to unpack (expected 2)```)
The other possibility is to add ```class_ref.startswith("pylate.")``` to [this test](https://github.com/UKPLab/sentence-transformers/blob/ba8cb2ef1d7a5ad6b9169eddee469e900456532c/sentence_transformers/SentenceTransformer.py#L1550). It is a bit hardcoded but prevents not catching an exception earlier if there is some other ValueError

Let me know what solution you prefer and I can create a PR for this


Functions to edit:
sentence_transformers/SentenceTransformer.py:SentenceTransformer._load_module_class_from_ref

Patch:
diff --git a/sentence_transformers/SentenceTransformer.py b/sentence_transformers/SentenceTransformer.py
index 830564a57..ba02f8bfa 100644
--- a/sentence_transformers/SentenceTransformer.py
+++ b/sentence_transformers/SentenceTransformer.py
@@ -1559,8 +1559,8 @@ def _load_module_class_from_ref(
                     revision=revision,
                     code_revision=code_revision,
                 )
-            except OSError:
-                # Ignore the error if the file does not exist, and fall back to the default import
+            except (OSError, ValueError):
+                # Ignore the error if 1) the file does not exist, or 2) the class_ref is not correctly formatted/found
                 pass
 
         return import_from_string(class_ref)
Repository: UKPLab/sentence-transformers
Issue category: Bug Report

BinaryClassificationEvaluator returns np.float32() and np.float64()
I came across the problem where

```python
output_scores[similarity_fn_name] = {
  "accuracy": acc,
  "accuracy_threshold": acc_threshold,
  "f1": f1,
  "f1_threshold": f1_threshold,
  "precision": precision,
  "recall": recall,
  "ap": ap,
}
```

is returning outputs in `np.float32()` and `np.float64()` which cause problems during model saving, as the `json/encoder.py` sees those types as `not JSON serializable`.

By changing the code snippet to

```python
output_scores[similarity_fn_name] = {
  "accuracy": acc.item(),
  "accuracy_threshold": acc_threshold.item(),
  "f1": f1.item(),
  "f1_threshold": f1_threshold.item(),
  "precision": precision,
  "recall": recall.item(),
  "ap": ap.item(),
}
```

the elements get copied to a standard Python scalar each (note: `precision` already is) and then behave like expected during saving.


Functions to edit:
sentence_transformers/evaluation/BinaryClassificationEvaluator.py:BinaryClassificationEvaluator.compute_metrices

Patch:
diff --git a/sentence_transformers/evaluation/BinaryClassificationEvaluator.py b/sentence_transformers/evaluation/BinaryClassificationEvaluator.py
index e0e00ebc9..4a701279d 100644
--- a/sentence_transformers/evaluation/BinaryClassificationEvaluator.py
+++ b/sentence_transformers/evaluation/BinaryClassificationEvaluator.py
@@ -288,14 +288,14 @@ def compute_metrices(self, model: SentenceTransformer) -> dict[str, dict[str, fl
             logger.info(f"Matthews Correlation with {name}: {mcc * 100:.2f}\n")
 
             output_scores[similarity_fn_name] = {
-                "accuracy": acc,
-                "accuracy_threshold": acc_threshold,
-                "f1": f1,
-                "f1_threshold": f1_threshold,
-                "precision": precision,
-                "recall": recall,
-                "ap": ap,
-                "mcc": mcc,
+                "accuracy": float(acc),
+                "accuracy_threshold": float(acc_threshold),
+                "f1": float(f1),
+                "f1_threshold": float(f1_threshold),
+                "precision": float(precision),
+                "recall": float(recall),
+                "ap": float(ap),
+                "mcc": float(mcc),
             }
 
         return output_scores
Repository: UKPLab/sentence-transformers
Issue category: Bug Report

Same order of training samples with `NoDuplicatesBatchSampler`
It seems that  `NoDuplicatesBatchSampler` produces the same set of batches in the same order regardless of the epoch index.
Indeed, in [this piece of code](https://github.com/UKPLab/sentence-transformers/blob/e156f38b1007e7860218c27223e1d577f3a021fe/sentence_transformers/sampler.py#L184C3-L187C102), the order of the indices in `remaining_indices` does not depend on the random permutation `torch.randperm(len(self.dataset), generator=self.generator)` as it is reset to the ordered range with `set`.

Moreover, the seed in line 185 does not change from one epoch to another (the [`set_epoch`](https://github.com/UKPLab/sentence-transformers/blob/e156f38b1007e7860218c27223e1d577f3a021fe/sentence_transformers/sampler.py#L32) method does not seem to be used...)






Functions to edit:
sentence_transformers/sampler.py:NoDuplicatesBatchSampler.__iter__

Patch:
diff --git a/sentence_transformers/sampler.py b/sentence_transformers/sampler.py
index 7efc19bf1..f3021b42f 100644
--- a/sentence_transformers/sampler.py
+++ b/sentence_transformers/sampler.py
@@ -184,7 +184,10 @@ def __iter__(self) -> Iterator[list[int]]:
         if self.generator and self.seed:
             self.generator.manual_seed(self.seed + self.epoch)
 
-        remaining_indices = set(torch.randperm(len(self.dataset), generator=self.generator).tolist())
+        # We create a dictionary to None because we need a data structure that:
+        # 1. Allows for cheap removal of elements
+        # 2. Preserves the order of elements, i.e. remains random
+        remaining_indices = dict.fromkeys(torch.randperm(len(self.dataset), generator=self.generator).tolist())
         while remaining_indices:
             batch_values = set()
             batch_indices = []
@@ -209,7 +212,8 @@ def __iter__(self) -> Iterator[list[int]]:
                 if not self.drop_last:
                     yield batch_indices
 
-            remaining_indices -= set(batch_indices)
+            for index in batch_indices:
+                del remaining_indices[index]
 
     def __len__(self) -> int:
         if self.drop_last:
Repository: gaogaotiantian/viztracer
Issue category: Bug Report

Cannot import name 'viewer_main' from 'viztracer' in 1.0.0
### Phenomenon:
I've been using viztracer through the viztracer plugin in vscode, but after upgrading to 1.0.0 ,viztracer doesn't work.

### Error message:
```powershell
C:\ProgramData\anaconda3\python.exe -m viztracer --ignore_frozen --open --log_print --quiet -u -- c:\...\something.py
Traceback (most recent call last):
  File "C:\ProgramData\anaconda3\Scripts\vizviewer-script.py", line 6, in <module>
    from viztracer import viewer_main
ImportError: cannot import name 'viewer_main' from 'viztracer' (C:\Users\29267\AppData\Roaming\Python\Python311\site-packages\viztracer\__init__.py)
```


### What I tried:
1. downgraded to 0.17.1 : **works fine**
2. upgraded to 1.0.0    : **bugs still there**





Functions to edit:
src/viztracer/main.py:VizUI.exit_routine

Patch:
diff --git a/src/viztracer/main.py b/src/viztracer/main.py
index 7cbf972c..eb996124 100644
--- a/src/viztracer/main.py
+++ b/src/viztracer/main.py
@@ -676,7 +676,7 @@ def exit_routine(self) -> None:
                 self.save()
                 if self.options.open:  # pragma: no cover
                     import subprocess
-                    subprocess.run(["vizviewer", "--once", os.path.abspath(self.ofile)])
+                    subprocess.run([sys.executable, "-m", "viztracer.viewer", "--once", os.path.abspath(self.ofile)])
 
 
 def main():
Repository: ranaroussi/yfinance
Issue category: Feature Request

Any way to get more news?
`ticker.news` seems to return 8 to 10 news articles.

However, Yahoo Finance can offer many more than 8 to 10 news articles per ticker: https://finance.yahoo.com/quote/MSFT/news/ (keep scrolling down).

Is there a way to get more than 8 to 10 news articles with yfinance? 


Functions to edit:
yfinance/base.py:TickerBase.get_news

Patch:
diff --git a/yfinance/base.py b/yfinance/base.py
index 81733ba9..c3150759 100644
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -30,7 +30,7 @@
 import pandas as pd
 import requests
 
-from . import utils, cache, Search
+from . import utils, cache
 from .data import YfData
 from .exceptions import YFEarningsDateMissing
 from .scrapers.analysis import Analysis
@@ -534,19 +534,45 @@ def get_isin(self, proxy=None) -> Optional[str]:
         self._isin = data.split(search_str)[1].split('"')[0].split('|')[0]
         return self._isin
 
-    def get_news(self, proxy=None) -> list:
+    def get_news(self, count=10, tab="news", proxy=None) -> list:
+        """Allowed options for tab: "news", "all", "press releases"""
         if self._news:
             return self._news
 
-        search = Search(
-            query=self.ticker,
-            news_count=10,
-            session=self.session,
-            proxy=proxy,
-            raise_errors=True
-        )
-        self._news = search.news
+        logger = utils.get_yf_logger()
+
+        tab_queryrefs = {
+            "all": "newsAll",
+            "news": "latestNews",
+            "press releases": "pressRelease",
+        }
+
+        query_ref = tab_queryrefs.get(tab.lower())
+        if not query_ref:
+            raise ValueError(f"Invalid tab name '{tab}'. Choose from: {', '.join(tab_queryrefs.keys())}")
+
+        url = f"{_ROOT_URL_}/xhr/ncp?queryRef={query_ref}&serviceKey=ncp_fin"
+        payload = {
+            "serviceConfig": {
+                "snippetCount": count,
+                "s": [self.ticker]
+            }
+        }
+
+        data = self._data.post(url, body=payload, proxy=proxy)
+        if data is None or "Will be right back" in data.text:
+            raise RuntimeError("*** YAHOO! FINANCE IS CURRENTLY DOWN! ***\n"
+                               "Our engineers are working quickly to resolve "
+                               "the issue. Thank you for your patience.")
+        try:
+            data = data.json()
+        except _json.JSONDecodeError:
+            logger.error(f"{self.ticker}: Failed to retrieve the news and received faulty response instead.")
+            data = {}
+
+        news = data.get("data", {}).get("tickerStream", {}).get("stream", [])
 
+        self._news = [article for article in news if not article.get('ad', [])]
         return self._news
 
     @utils.log_indent_decorator
Repository: scipy/scipy
Issue category: Bug Report

DOC: stats.pearsonr: incorrect `versionadded` for `axis` param
### Issue with current documentation:

Regarding the documentation of function scipy.stats.pearsonr. Typo in the version reference. The axis option is not in v1.13.0. It first appears in v1.14.0

### Idea or request for content:

Correct the version reference in the docstring. 1.13.0 --> 1.14.0

### Additional context (e.g. screenshots, GIFs)

```
def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0):
    r"""
    Pearson correlation coefficient and p-value for testing non-correlation.

    The Pearson correlation coefficient [1]_ measures the linear relationship
    between two datasets. Like other correlation
    coefficients, this one varies between -1 and +1 with 0 implying no
    correlation. Correlations of -1 or +1 imply an exact linear relationship.
    Positive correlations imply that as x increases, so does y. Negative
    correlations imply that as x increases, y decreases.

    This function also performs a test of the null hypothesis that the
    distributions underlying the samples are uncorrelated and normally
    distributed. (See Kowalski [3]_
    for a discussion of the effects of non-normality of the input on the
    distribution of the correlation coefficient.)
    The p-value roughly indicates the probability of an uncorrelated system
    producing datasets that have a Pearson correlation at least as extreme
    as the one computed from these datasets.

    Parameters
    ----------
    x : array_like
        Input array.
    y : array_like
        Input array.
    axis : int or None, default
        Axis along which to perform the calculation. Default is 0.
        If None, ravel both arrays before performing the calculation.

        .. versionadded:: 1.13.0
```


Functions to edit:
scipy/stats/_stats_py.py:pearsonr

Patch:
diff --git a/scipy/stats/_stats_py.py b/scipy/stats/_stats_py.py
index de7be104289b..71ae19acabc2 100644
--- a/scipy/stats/_stats_py.py
+++ b/scipy/stats/_stats_py.py
@@ -4298,7 +4298,7 @@ def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0):
         Axis along which to perform the calculation. Default is 0.
         If None, ravel both arrays before performing the calculation.
 
-        .. versionadded:: 1.13.0
+        .. versionadded:: 1.14.0
     alternative : {'two-sided', 'greater', 'less'}, optional
         Defines the alternative hypothesis. Default is 'two-sided'.
         The following options are available:
Repository: DS4SD/docling
Issue category: Bug Report

Image location in Word Document is wrong
### Bug
The image placeholder in parsed docx documents is wrong. An incorrect index is used resulting in a wrong location for images in downstream export formats like markdown.


### Steps to reproduce
Parsing a simple .docx with docling
[image_within_text.docx](https://github.com/user-attachments/files/17919742/image_within_text.docx)


### Docling version
Docling version: 2.7.0
Docling Core version: 2.4.1
Docling IBM Models version: 2.0.6
Docling Parse version: 2.1.2


### Python version
3.12.4


<!-- ⚠️ ATTENTION: When sharing screenshots, attachments, or other data make sure not to include any sensitive information. -->



Functions to edit:
docling/backend/msword_backend.py:MsWordDocumentBackend.handle_pictures

Patch:
diff --git a/docling/backend/msword_backend.py b/docling/backend/msword_backend.py
index 496bdb7b..05508712 100644
--- a/docling/backend/msword_backend.py
+++ b/docling/backend/msword_backend.py
@@ -507,18 +507,19 @@ def get_docx_image(element, drawing_blip):
 
         image_data = get_docx_image(element, drawing_blip)
         image_bytes = BytesIO(image_data)
+        level = self.get_level()
         # Open the BytesIO object with PIL to create an Image
         try:
             pil_image = Image.open(image_bytes)
             doc.add_picture(
-                parent=self.parents[self.level],
+                parent=self.parents[level - 1],
                 image=ImageRef.from_pil(image=pil_image, dpi=72),
                 caption=None,
             )
         except (UnidentifiedImageError, OSError) as e:
             _log.warning("Warning: image cannot be loaded by Pillow")
             doc.add_picture(
-                parent=self.parents[self.level],
+                parent=self.parents[level - 1],
                 caption=None,
             )
         return
Repository: DS4SD/docling
Issue category: Feature Request

Enable control over log verbosity on the docling CLI
### Requested feature

We need to extend the CLI with some arguments to control the log level, to catch lower-level issues when docling CLI does not work as expected.

Proposal: Add `-v` (loglevel.INFO) and optionally `-vv` for (loglevel.DEBUG)


Functions to edit:
docling/cli/main.py:convert

Patch:
diff --git a/docling/cli/main.py b/docling/cli/main.py
index 60a3c296..b79b7b9f 100644
--- a/docling/cli/main.py
+++ b/docling/cli/main.py
@@ -185,6 +185,15 @@ def convert(
     output: Annotated[
         Path, typer.Option(..., help="Output directory where results are saved.")
     ] = Path("."),
+    verbose: Annotated[
+        int,
+        typer.Option(
+            "--verbose",
+            "-v",
+            count=True,
+            help="Set the verbosity level. -v for info logging, -vv for debug logging.",
+        ),
+    ] = 0,
     version: Annotated[
         Optional[bool],
         typer.Option(
@@ -195,7 +204,12 @@ def convert(
         ),
     ] = None,
 ):
-    logging.basicConfig(level=logging.INFO)
+    if verbose == 0:
+        logging.basicConfig(level=logging.WARNING)
+    elif verbose == 1:
+        logging.basicConfig(level=logging.INFO)
+    elif verbose == 2:
+        logging.basicConfig(level=logging.DEBUG)
 
     if from_formats is None:
         from_formats = [e for e in InputFormat]
Repository: DS4SD/docling
Issue category: Bug Report

Unable to extract code block in HTML page
When I try to extract the content from a webpage using ```docling```,  I found it cannot extract **code blocks** in the webpage.

# Reproduce steps

HTML URL: https://requests.readthedocs.io/en/latest/user/quickstart/
 
```python
from docling.document_converter import DocumentConverter

converter = DocumentConverter()
result = converter.convert('https://requests.readthedocs.io/en/latest/user/quickstart/')
print(result.document.export_to_markdown())
````
The code blocks in the following picture cannot be extracted in the result markdown:
<img width="754" alt="image" src="https://github.com/user-attachments/assets/0175ddce-7516-4786-bdc7-95c3e830fad2">


The result markdown of this part in the above picture is :

```markdown
## Make a Request¶

Making a request with Requests is very simple.

Begin by importing the Requests module:

Now, let’s try to get a webpage. For this example, let’s get GitHub’s public
timeline:

Now, we have a Response object called r. We can
get all the information we need from this object.

Requests’ simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request:

Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple:

That’s all well and good, but it’s also only the start of what Requests can
do.

```



Functions to edit:
docling/backend/html_backend.py:HTMLDocumentBackend.analyse_element
Functions added: docling/backend/html_backend.py:HTMLDocumentBackend.handle_code

Patch:
diff --git a/docling/backend/html_backend.py b/docling/backend/html_backend.py
index 7d14c2eb..9cd1e29b 100644
--- a/docling/backend/html_backend.py
+++ b/docling/backend/html_backend.py
@@ -120,6 +120,8 @@ def analyse_element(self, element, idx, doc):
             self.handle_header(element, idx, doc)
         elif element.name in ["p"]:
             self.handle_paragraph(element, idx, doc)
+        elif element.name in ["pre"]:
+            self.handle_code(element, idx, doc)
         elif element.name in ["ul", "ol"]:
             self.handle_list(element, idx, doc)
         elif element.name in ["li"]:
@@ -205,6 +207,16 @@ def handle_header(self, element, idx, doc):
                 level=hlevel,
             )
 
+    def handle_code(self, element, idx, doc):
+        """Handles monospace code snippets (pre)."""
+        if element.text is None:
+            return
+        text = element.text.strip()
+        label = DocItemLabel.CODE
+        if len(text) == 0:
+            return
+        doc.add_text(parent=self.parents[self.level], label=label, text=text)
+
     def handle_paragraph(self, element, idx, doc):
         """Handles paragraph tags (p)."""
         if element.text is None:
Repository: certbot/certbot
Issue category: Bug Report

Fix regex in finish_release.py
```
(venv) certbot [3.0.0] » python3 tools/finish_release.py 
certbot/tools/finish_release.py:114: SyntaxWarning: invalid escape sequence '\s'
  pattern = f'^\s+{channel}\s+{version}\s+(\d+)\s*'
certbot/tools/finish_release.py:114: SyntaxWarning: invalid escape sequence '\s'
  pattern = f'^\s+{channel}\s+{version}\s+(\d+)\s*'
certbot/tools/finish_release.py:114: SyntaxWarning: invalid escape sequence '\s'
  pattern = f'^\s+{channel}\s+{version}\s+(\d+)\s*'
```


Functions to edit:
tools/finish_release.py:get_snap_revisions

Patch:
diff --git a/tools/finish_release.py b/tools/finish_release.py
index 958d7672bc..56b92d2a1d 100755
--- a/tools/finish_release.py
+++ b/tools/finish_release.py
@@ -111,7 +111,7 @@ def get_snap_revisions(snap, channel, version):
     print('Getting revision numbers for', snap, version)
     cmd = ['snapcraft', 'status', snap]
     process = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, universal_newlines=True)
-    pattern = f'^\s+{channel}\s+{version}\s+(\d+)\s*'
+    pattern = f'^\\s+{channel}\\s+{version}\\s+(\\d+)\\s*'
     revisions = re.findall(pattern, process.stdout, re.MULTILINE)
     assert len(revisions) == SNAP_ARCH_COUNT, f'Unexpected number of snaps found for {channel} {snap} {version} (expected {SNAP_ARCH_COUNT}, found {len(revisions)})'
     return revisions