HashBigBro/cerebras_swe_bench huggingface dataset:
Repository: sqlfluff/sqlfluff

Issue:
TSQL - L031 incorrectly triggers "Avoid using aliases in join condition" when no join present
## Expected Behaviour

Both of these queries should pass, the only difference is the addition of a table alias 'a':

1/ no alias

```
SELECT [hello]
FROM
    mytable
```

2/ same query with alias

```
SELECT a.[hello]
FROM
    mytable AS a
```

## Observed Behaviour

1/ passes
2/ fails with: L031: Avoid using aliases in join condition.

But there is no join condition :-)

## Steps to Reproduce

Lint queries above

## Dialect

TSQL

## Version

sqlfluff 0.6.9
Python 3.6.9

## Configuration

N/A


Discussion:
Actually, re-reading the docs I think this is the intended behaviour... closing

Patch:
diff --git a/src/sqlfluff/rules/L031.py b/src/sqlfluff/rules/L031.py
--- a/src/sqlfluff/rules/L031.py
+++ b/src/sqlfluff/rules/L031.py
@@ -211,7 +211,7 @@ def _lint_aliases_in_join(
             violation_buff.append(
                 LintResult(
                     anchor=alias_info.alias_identifier_ref,
-                    description="Avoid using aliases in join condition",
+                    description="Avoid aliases in from clauses and join conditions.",
                     fixes=fixes,
                 )
             )


Test patch:
diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py
--- a/test/cli/commands_test.py
+++ b/test/cli/commands_test.py
@@ -49,7 +49,7 @@ def invoke_assert_code(
 expected_output = """== [test/fixtures/linter/indentation_error_simple.sql] FAIL
 L:   2 | P:   4 | L003 | Indentation not hanging or a multiple of 4 spaces
 L:   5 | P:  10 | L010 | Keywords must be consistently upper case.
-L:   5 | P:  13 | L031 | Avoid using aliases in join condition
+L:   5 | P:  13 | L031 | Avoid aliases in from clauses and join conditions.
 """
Repository: sqlfluff/sqlfluff

Issue:
Rule L060 could give a specific error message
At the moment rule L060 flags something like this:

```
L:  21 | P:   9 | L060 | Use 'COALESCE' instead of 'IFNULL' or 'NVL'.
```

Since we likely know the wrong word, it might be nice to actually flag that instead of both `IFNULL` and `NVL` - like most of the other rules do.

That is it should flag this:

```
L:  21 | P:   9 | L060 | Use 'COALESCE' instead of 'IFNULL'.
```
 Or this:

```
L:  21 | P:   9 | L060 | Use 'COALESCE' instead of 'NVL'.
```

As appropriate.

What do you think @jpy-git ?



Discussion:
@tunetheweb Yeah definitely, should be a pretty quick change 😊

Patch:
diff --git a/src/sqlfluff/rules/L060.py b/src/sqlfluff/rules/L060.py
--- a/src/sqlfluff/rules/L060.py
+++ b/src/sqlfluff/rules/L060.py
@@ -59,4 +59,8 @@ def _eval(self, context: RuleContext) -> Optional[LintResult]:
             ],
         )
 
-        return LintResult(context.segment, [fix])
+        return LintResult(
+            anchor=context.segment,
+            fixes=[fix],
+            description=f"Use 'COALESCE' instead of '{context.segment.raw_upper}'.",
+        )


Test patch:
diff --git a/test/rules/std_L060_test.py b/test/rules/std_L060_test.py
new file mode 100644
--- /dev/null
+++ b/test/rules/std_L060_test.py
@@ -0,0 +1,12 @@
+"""Tests the python routines within L060."""
+import sqlfluff
+
+
+def test__rules__std_L060_raised() -> None:
+    """L060 is raised for use of ``IFNULL`` or ``NVL``."""
+    sql = "SELECT\n\tIFNULL(NULL, 100),\n\tNVL(NULL,100);"
+    result = sqlfluff.lint(sql, rules=["L060"])
+
+    assert len(result) == 2
+    assert result[0]["description"] == "Use 'COALESCE' instead of 'IFNULL'."
+    assert result[1]["description"] == "Use 'COALESCE' instead of 'NVL'."
Repository: pvlib/pvlib-python

Issue:
regression: iam.physical returns nan for aoi > 90° when n = 1
**Describe the bug**
For pvlib==0.9.5, when n = 1 (no reflection) and aoi > 90°, we get nan as result.

**To Reproduce**
```python
import pvlib
pvlib.iam.physical(aoi=100, n=1)
```
returns `nan`.

**Expected behavior**
The result should be `0`, as it was for pvlib <= 0.9.4.


**Versions:**
 - ``pvlib.__version__``: '0.9.5'
 - ``pandas.__version__``:  '1.5.3'
 - python: 3.10.4



Discussion:

Patch:
diff --git a/pvlib/iam.py b/pvlib/iam.py
--- a/pvlib/iam.py
+++ b/pvlib/iam.py
@@ -175,8 +175,12 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None):
     n2costheta2 = n2 * costheta
 
     # reflectance of s-, p-polarized, and normal light by the first interface
-    rho12_s = ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2
-    rho12_p = ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2
+    with np.errstate(divide='ignore', invalid='ignore'):
+        rho12_s = \
+            ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2
+        rho12_p = \
+            ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2
+
     rho12_0 = ((n1 - n2) / (n1 + n2)) ** 2
 
     # transmittance through the first interface
@@ -208,13 +212,22 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None):
         tau_0 *= (1 - rho23_0) / (1 - rho23_0 * rho12_0)
 
     # transmittance after absorption in the glass
-    tau_s *= np.exp(-K * L / costheta)
-    tau_p *= np.exp(-K * L / costheta)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        tau_s *= np.exp(-K * L / costheta)
+        tau_p *= np.exp(-K * L / costheta)
+
     tau_0 *= np.exp(-K * L)
 
     # incidence angle modifier
     iam = (tau_s + tau_p) / 2 / tau_0
 
+    # for light coming from behind the plane, none can enter the module
+    # when n2 > 1, this is already the case
+    if np.isclose(n2, 1).any():
+        iam = np.where(aoi >= 90, 0, iam)
+        if isinstance(aoi, pd.Series):
+            iam = pd.Series(iam, index=aoi.index)
+
     return iam
 
 


Test patch:
diff --git a/pvlib/tests/test_iam.py b/pvlib/tests/test_iam.py
--- a/pvlib/tests/test_iam.py
+++ b/pvlib/tests/test_iam.py
@@ -51,6 +51,18 @@ def test_physical():
     assert_series_equal(iam, expected)
 
 
+def test_physical_n1_L0():
+    aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])
+    expected = np.array([1, 1, 1, 1, 0, 0, np.nan])
+    iam = _iam.physical(aoi, n=1, L=0)
+    assert_allclose(iam, expected, equal_nan=True)
+
+    aoi = pd.Series(aoi)
+    expected = pd.Series(expected)
+    iam = _iam.physical(aoi, n=1, L=0)
+    assert_series_equal(iam, expected)
+
+
 def test_physical_ar():
     aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])
     expected = np.array([1, 0.99944171, 0.9917463, 0.91506158, 0, 0, np.nan])
Repository: pvlib/pvlib-python

Issue:
`pvsystem.calcparams_cec()` does not propagate parameters
**Describe the bug**

The function calls `calcparams_desoto` with hardcoded reference values.

https://github.com/pvlib/pvlib-python/blob/40ba4bd5c8b91754aa73e638ed984ab9657847cd/pvlib/pvsystem.py#L1850-L1855

This means the function is silently ignoring its inputs, yielding incorrect results that may go unnoticed.


**Expected behavior**

The function parameters are propagated into the `calcparams_desoto` call. In particular: `EgRef`, `dEgdT`, `irrad_ref`, `temp_ref`


Discussion:

Patch:
diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py
--- a/pvlib/pvsystem.py
+++ b/pvlib/pvsystem.py
@@ -1994,8 +1994,8 @@ def calcparams_cec(effective_irradiance, temp_cell,
                              alpha_sc*(1.0 - Adjust/100),
                              a_ref, I_L_ref, I_o_ref,
                              R_sh_ref, R_s,
-                             EgRef=1.121, dEgdT=-0.0002677,
-                             irrad_ref=1000, temp_ref=25)
+                             EgRef=EgRef, dEgdT=dEgdT,
+                             irrad_ref=irrad_ref, temp_ref=temp_ref)
 
 
 def calcparams_pvsyst(effective_irradiance, temp_cell,


Test patch:
diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py
--- a/pvlib/tests/test_pvsystem.py
+++ b/pvlib/tests/test_pvsystem.py
@@ -792,6 +792,43 @@ def test_calcparams_cec(cec_module_params):
                         check_less_precise=3)
 
 
+def test_calcparams_cec_extra_params_propagation(cec_module_params, mocker):
+    """
+    See bug #1215.
+
+    When calling `calcparams_cec`, the parameters `EgRef`, `dEgdT`, `irrad_ref`
+    and `temp_ref` must not be ignored.
+
+    Since, internally, this function is calling `calcparams_desoto`, this test
+    checks that the latter is called with the expected parameters instead of
+    some default values.
+    """
+    times = pd.date_range(start='2015-01-01', periods=3, freq='12H')
+    effective_irradiance = pd.Series([0.0, 800.0, 800.0], index=times)
+    temp_cell = pd.Series([25, 25, 50], index=times)
+    extra_parameters = dict(
+        EgRef=1.123,
+        dEgdT=-0.0002688,
+        irrad_ref=1100,
+        temp_ref=23,
+    )
+    m = mocker.spy(pvsystem, 'calcparams_desoto')
+    pvsystem.calcparams_cec(
+        effective_irradiance=effective_irradiance,
+        temp_cell=temp_cell,
+        alpha_sc=cec_module_params['alpha_sc'],
+        a_ref=cec_module_params['a_ref'],
+        I_L_ref=cec_module_params['I_L_ref'],
+        I_o_ref=cec_module_params['I_o_ref'],
+        R_sh_ref=cec_module_params['R_sh_ref'],
+        R_s=cec_module_params['R_s'],
+        Adjust=cec_module_params['Adjust'],
+        **extra_parameters,
+    )
+    assert m.call_count == 1
+    assert m.call_args[1] == extra_parameters
+
+
 def test_calcparams_pvsyst(pvsyst_module_params):
     times = pd.date_range(start='2015-01-01', periods=2, freq='12H')
     effective_irradiance = pd.Series([0.0, 800.0], index=times)
Repository: pvlib/pvlib-python

Issue:
ModelChain.prepare_inputs can succeed with missing dhi
From the docstring for `ModelChain.prepare_inputs()` I believe the method should fail if `weather` does not have a `dhi` column.

The validation checks for `'ghi'` twice, but not `'dhi`'

https://github.com/pvlib/pvlib-python/blob/11c356f9a89fc88b4d3ff368ce1aae170a97ebd7/pvlib/modelchain.py#L1136


Discussion:

Patch:
diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py
--- a/pvlib/modelchain.py
+++ b/pvlib/modelchain.py
@@ -1133,7 +1133,7 @@ def prepare_inputs(self, weather):
         ModelChain.complete_irradiance
         """
 
-        self._verify_df(weather, required=['ghi', 'dni', 'ghi'])
+        self._verify_df(weather, required=['ghi', 'dni', 'dhi'])
         self._assign_weather(weather)
 
         self.times = self.weather.index


Test patch:
diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py
--- a/pvlib/tests/test_modelchain.py
+++ b/pvlib/tests/test_modelchain.py
@@ -249,6 +249,16 @@ def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):
         mc.prepare_inputs(weather)
 
 
+@pytest.mark.parametrize("missing", ['dhi', 'ghi', 'dni'])
+def test_prepare_inputs_missing_irrad_component(
+        sapm_dc_snl_ac_system, location, missing):
+    mc = ModelChain(sapm_dc_snl_ac_system, location)
+    weather = pd.DataFrame({'dhi': [1, 2], 'dni': [1, 2], 'ghi': [1, 2]})
+    weather.drop(columns=missing, inplace=True)
+    with pytest.raises(ValueError):
+        mc.prepare_inputs(weather)
+
+
 def test_run_model_perez(sapm_dc_snl_ac_system, location):
     mc = ModelChain(sapm_dc_snl_ac_system, location,
                     transposition_model='perez')
Repository: pvlib/pvlib-python

Issue:
It should be impossible to instantiate a PVSystem with no Arrays
**Describe the bug**
It should be impossible to instantiate a `PVSystem` with no `Arrays`. Currently this is possible via `PVSystem(arrays=[])`.

**To Reproduce**
Steps to reproduce the behavior:
```python
from pvlib import pvsystem
pvsystem.PVSystem(arrays=[])
```
results in this PVSystem:
```
PVSystem:
  name: None
  inverter: None
```
**Expected behavior**
A `ValueError` should be raised indicating that a PVSystem must have at least one `Array` and suggesting that a system with an arbitrary default array can be constructed by passing `arrays=None` or not passing the `arrays` parameter at all.

**Versions:**
 - ``pvlib.__version__``: 0.8.1+




Discussion:

Patch:
diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py
--- a/pvlib/pvsystem.py
+++ b/pvlib/pvsystem.py
@@ -98,8 +98,9 @@ class PVSystem:
     arrays : iterable of Array, optional
         List of arrays that are part of the system. If not specified
         a single array is created from the other parameters (e.g.
-        `surface_tilt`, `surface_azimuth`). If `arrays` is specified
-        the following parameters are ignored:
+        `surface_tilt`, `surface_azimuth`). Must contain at least one Array,
+        if length of arrays is 0 a ValueError is raised. If `arrays` is
+        specified the following parameters are ignored:
 
         - `surface_tilt`
         - `surface_azimuth`
@@ -173,6 +174,11 @@ class PVSystem:
         Arbitrary keyword arguments.
         Included for compatibility, but not used.
 
+    Raises
+    ------
+    ValueError
+        If `arrays` is not None and has length 0.
+
     See also
     --------
     pvlib.location.Location
@@ -210,6 +216,12 @@ def __init__(self,
                 racking_model,
                 array_losses_parameters,
             ),)
+        elif len(arrays) == 0:
+            raise ValueError("PVSystem must have at least one Array. "
+                             "If you want to create a PVSystem instance "
+                             "with a single Array pass `arrays=None` and pass "
+                             "values directly to PVSystem attributes, e.g., "
+                             "`surface_tilt=30`")
         else:
             self.arrays = tuple(arrays)
 


Test patch:
diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py
--- a/pvlib/tests/test_pvsystem.py
+++ b/pvlib/tests/test_pvsystem.py
@@ -2084,6 +2084,12 @@ def test_PVSystem_num_arrays():
     assert system_two.num_arrays == 2
 
 
+def test_PVSystem_at_least_one_array():
+    with pytest.raises(ValueError,
+                       match="PVSystem must have at least one Array"):
+        pvsystem.PVSystem(arrays=[])
+
+
 def test_combine_loss_factors():
     test_index = pd.date_range(start='1990/01/01T12:00', periods=365, freq='D')
     loss_1 = pd.Series(.10, index=test_index)
Repository: pvlib/pvlib-python

Issue:
pvlib.irradiance.reindl() model generates NaNs when GHI = 0
**Describe the bug**
The reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to "term3" having a quotient that divides by GHI.  

**Expected behavior**
The reindl function should result in zero sky diffuse when GHI is zero.


pvlib.irradiance.reindl() model generates NaNs when GHI = 0
**Describe the bug**
The reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to "term3" having a quotient that divides by GHI.  

**Expected behavior**
The reindl function should result in zero sky diffuse when GHI is zero.




Discussion:
Verified. Looks like an easy fix.
Verified. Looks like an easy fix.

Patch:
diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py
--- a/pvlib/irradiance.py
+++ b/pvlib/irradiance.py
@@ -886,8 +886,9 @@ def reindl(surface_tilt, surface_azimuth, dhi, dni, ghi, dni_extra,
     # these are the () and [] sub-terms of the second term of eqn 8
     term1 = 1 - AI
     term2 = 0.5 * (1 + tools.cosd(surface_tilt))
-    term3 = 1 + np.sqrt(HB / ghi) * (tools.sind(0.5 * surface_tilt) ** 3)
-
+    with np.errstate(invalid='ignore', divide='ignore'):
+        hb_to_ghi = np.where(ghi == 0, 0, np.divide(HB, ghi))
+    term3 = 1 + np.sqrt(hb_to_ghi) * (tools.sind(0.5 * surface_tilt)**3)
     sky_diffuse = dhi * (AI * Rb + term1 * term2 * term3)
     sky_diffuse = np.maximum(sky_diffuse, 0)
 


Test patch:
diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py
--- a/pvlib/tests/test_irradiance.py
+++ b/pvlib/tests/test_irradiance.py
@@ -203,7 +203,7 @@ def test_reindl(irrad_data, ephem_data, dni_et):
         40, 180, irrad_data['dhi'], irrad_data['dni'], irrad_data['ghi'],
         dni_et, ephem_data['apparent_zenith'], ephem_data['azimuth'])
     # values from matlab 1.4 code
-    assert_allclose(result, [np.nan, 27.9412, 104.1317, 34.1663], atol=1e-4)
+    assert_allclose(result, [0., 27.9412, 104.1317, 34.1663], atol=1e-4)
 
 
 def test_king(irrad_data, ephem_data):
Repository: pylint-dev/astroid

Issue:
Infer calls to str.format() on names
Future enhancement could infer this value instead of giving an empty string:

```python
from astroid import extract_node
call = extract_node("""
x = 'python is {}'
x.format('helpful sometimes')
""")
call.inferred()[0].value  # gives ""
```

_Originally posted by @jacobtylerwalls in https://github.com/PyCQA/astroid/pull/1602#discussion_r893423433_


Discussion:

Patch:
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -913,12 +913,15 @@ def _infer_copy_method(
 
 def _is_str_format_call(node: nodes.Call) -> bool:
     """Catch calls to str.format()."""
-    return (
-        isinstance(node.func, nodes.Attribute)
-        and node.func.attrname == "format"
-        and isinstance(node.func.expr, nodes.Const)
-        and isinstance(node.func.expr.value, str)
-    )
+    if not isinstance(node.func, nodes.Attribute) or not node.func.attrname == "format":
+        return False
+
+    if isinstance(node.func.expr, nodes.Name):
+        value = helpers.safe_infer(node.func.expr)
+    else:
+        value = node.func.expr
+
+    return isinstance(value, nodes.Const) and isinstance(value.value, str)
 
 
 def _infer_str_format_call(
@@ -926,7 +929,12 @@ def _infer_str_format_call(
 ) -> Iterator[nodes.Const | type[util.Uninferable]]:
     """Return a Const node based on the template and passed arguments."""
     call = arguments.CallSite.from_call(node, context=context)
-    format_template: str = node.func.expr.value
+    if isinstance(node.func.expr, nodes.Name):
+        value: nodes.Const = helpers.safe_infer(node.func.expr)
+    else:
+        value = node.func.expr
+
+    format_template = value.value
 
     # Get the positional arguments passed
     inferred_positional = [


Test patch:
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py
--- a/tests/unittest_brain_builtin.py
+++ b/tests/unittest_brain_builtin.py
@@ -66,6 +66,13 @@ class TestStringNodes:
         """,
                 id="mixed-indexes-from-mixed",
             ),
+            pytest.param(
+                """
+        string = "My name is {}, I'm {}"
+        string.format("Daniel", 12)
+        """,
+                id="empty-indexes-on-variable",
+            ),
         ],
     )
     def test_string_format(self, format_string: str) -> None:
Repository: pylint-dev/astroid

Issue:
Unhandled AttributeError during str.format template evaluation
### Steps to reproduce

1. Use `astroid` to parse code that provides arguments to a `str.format` template that attempts to access non-existent attributes

```py
daniel_age = 12
"My name is {0.name}".format(daniel_age)  # int literal has no 'name' attribute
```

### Current behavior

1. unhandled `AttributeError` when it attempts to [evaluate the templated string](https://github.com/PyCQA/astroid/blob/8bdec591f228e7db6a0be66b6ca814227ff50001/astroid/brain/brain_builtin_inference.py#L956)

### Expected behavior

1. could raise an `AstroidTypeError` to indicate that the template formatting is invalid

### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output

`2.13.0-dev0`

Relates to pycqa/pylint#7939.
Unhandled AttributeError during str.format template evaluation
### Steps to reproduce

1. Use `astroid` to parse code that provides arguments to a `str.format` template that attempts to access non-existent attributes

```py
daniel_age = 12
"My name is {0.name}".format(daniel_age)  # int literal has no 'name' attribute
```

### Current behavior

1. unhandled `AttributeError` when it attempts to [evaluate the templated string](https://github.com/PyCQA/astroid/blob/8bdec591f228e7db6a0be66b6ca814227ff50001/astroid/brain/brain_builtin_inference.py#L956)

### Expected behavior

1. could raise an `AstroidTypeError` to indicate that the template formatting is invalid

### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output

`2.13.0-dev0`

Relates to pycqa/pylint#7939.


Discussion:

Patch:
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -952,7 +952,8 @@ def _infer_str_format_call(
 
     try:
         formatted_string = format_template.format(*pos_values, **keyword_values)
-    except (IndexError, KeyError, TypeError, ValueError):
+    except (AttributeError, IndexError, KeyError, TypeError, ValueError):
+        # AttributeError: processing a replacement field using the arguments failed
         # IndexError: there are too few arguments to interpolate
         # TypeError: Unsupported format string
         # ValueError: Unknown format code


Test patch:
diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py
--- a/tests/unittest_brain_builtin.py
+++ b/tests/unittest_brain_builtin.py
@@ -109,6 +109,10 @@ def test_string_format(self, format_string: str) -> None:
             """
             "My hex format is {:4x}".format('1')
             """,
+            """
+            daniel_age = 12
+            "My name is {0.name}".format(daniel_age)
+            """,
         ],
     )
     def test_string_format_uninferable(self, format_string: str) -> None:
Repository: pylint-dev/astroid

Issue:
'AsStringVisitor' object has no attribute 'visit_unknown'
```python
>>> import astroid
>>> astroid.nodes.Unknown().as_string()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 609, in as_string
    return AsStringVisitor()(self)
  File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py", line 56, in __call__
    return node.accept(self).replace(DOC_NEWLINE, "\n")
  File "/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py", line 220, in accept
    func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
AttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'
>>> 
```
### `python -c "from astroid import __pkginfo__; print(__pkginfo__.version)"` output

2.8.6-dev0


Discussion:
Thank you for opening the issue.
I don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.
Probably just `'Unknown'`.
It's mostly only a problem when we do something like this:

```python
inferred = infer(node)
if inferred is not Uninferable:
    if inferred.as_string().contains(some_value):
        ...
```
So for the most part, as long as it doesn't crash we're good.

Patch:
diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py
--- a/astroid/nodes/as_string.py
+++ b/astroid/nodes/as_string.py
@@ -36,6 +36,7 @@
         MatchSingleton,
         MatchStar,
         MatchValue,
+        Unknown,
     )
 
 # pylint: disable=unused-argument
@@ -643,6 +644,9 @@ def visit_property(self, node):
     def visit_evaluatedobject(self, node):
         return node.original.accept(self)
 
+    def visit_unknown(self, node: "Unknown") -> str:
+        return str(node)
+
 
 def _import_string(names):
     """return a list of (name, asname) formatted as a string"""


Test patch:
diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py
--- a/tests/unittest_nodes.py
+++ b/tests/unittest_nodes.py
@@ -306,6 +306,11 @@ def test_f_strings(self):
         ast = abuilder.string_build(code)
         self.assertEqual(ast.as_string().strip(), code.strip())
 
+    @staticmethod
+    def test_as_string_unknown() -> None:
+        assert nodes.Unknown().as_string() == "Unknown.Unknown()"
+        assert nodes.Unknown(lineno=1, col_offset=0).as_string() == "Unknown.Unknown()"
+
 
 class _NodeTest(unittest.TestCase):
     """test transformation of If Node"""
Repository: pylint-dev/astroid

Issue:
``nodes.Module`` don't have a ``end_lineno`` and ``end_col_offset``
### Steps to reproduce

```python
import astroid

code = """
    print("a module")
    """

module = astroid.parse(code)
print(module.end_lineno)
print(module.end_col_offset)
```

### Current behavior

`AttributeError` on both of the last lines.

### Expected behavior

@cdce8p Let me know if I misunderstood you, but I thought we wanted these to be accessible on all nodes, just initialised as `None`.
If that was not the case, I would make the case to do so as it allows you to do `node.end_lineno` without running in to `AttributeError`'s.

### Version

Latest `main`.



Discussion:

Patch:
diff --git a/astroid/nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes.py
--- a/astroid/nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes.py
@@ -389,10 +389,8 @@ class Module(LocalsDictNodeNG):
 
     :type: int or None
     """
-    lineno = 0
+    lineno: Literal[0] = 0
     """The line that this node appears on in the source code.
-
-    :type: int or None
     """
 
     # attributes below are set by the builder module or by raw factories
@@ -469,7 +467,6 @@ class Module(LocalsDictNodeNG):
     )
     _other_other_fields = ("locals", "globals")
 
-    lineno: None
     col_offset: None
     end_lineno: None
     end_col_offset: None
@@ -512,7 +509,6 @@ def __init__(
         self.file = file
         self.path = path
         self.package = package
-        self.parent = parent
         self.pure_python = pure_python
         self.locals = self.globals = {}
         """A map of the name of a local variable to the node defining the local.
@@ -526,6 +522,8 @@ def __init__(
         """
         self.future_imports = set()
 
+        super().__init__(lineno=0, parent=parent)
+
     # pylint: enable=redefined-builtin
 
     def postinit(self, body=None):


Test patch:
diff --git a/tests/unittest_nodes_lineno.py b/tests/unittest_nodes_lineno.py
--- a/tests/unittest_nodes_lineno.py
+++ b/tests/unittest_nodes_lineno.py
@@ -2,6 +2,7 @@
 
 import pytest
 
+import astroid
 from astroid import builder, nodes
 from astroid.const import PY38_PLUS, PY39_PLUS, PY310_PLUS
 
@@ -1221,3 +1222,14 @@ class X(Parent, var=42):
         assert (c1.body[0].lineno, c1.body[0].col_offset) == (4, 4)
         assert (c1.body[0].end_lineno, c1.body[0].end_col_offset) == (4, 8)
         # fmt: on
+
+    @staticmethod
+    def test_end_lineno_module() -> None:
+        """Tests for Module"""
+        code = """print()"""
+        module = astroid.parse(code)
+        assert isinstance(module, nodes.Module)
+        assert module.lineno == 0
+        assert module.col_offset is None
+        assert module.end_lineno is None
+        assert module.end_col_offset is None
Repository: pydicom/pydicom

Issue:
Segmented LUTs are incorrectly expanded
**Describe the bug**
`pydicom.pixel_data_handlers.util._expand_segmented_lut()` expands segmented LUTs to an incorrect length.

**Expected behavior**
A correct length LUT to be produced.

**Steps To Reproduce**
Initialize the following variables.
```
import numpy as np
length = 48
y0 = 163
y1 = 255
```

Run the following two lines from [`pydicom.pixel_data_handlers.util._expand_segmented_lut()`](https://github.com/pydicom/pydicom/blob/699c9f0a8e190d463dd828822106250523d38154/pydicom/pixel_data_handlers/util.py#L875
)
```
step = (y1 - y0) / length
vals = np.around(np.arange(y0 + step, y1 + step, step))
```

Confirm that variable `vals` if of incorrect length
```
print(len(vals) == length)
> False
```

Alternatively, the code below produces similarly false results

```
from pydicom.pixel_data_handlers.util import _expand_segmented_lut 
lut = _expand_segmented_lut(([0, 1, 163, 1, 48, 255]), "B")
print(len(lut) == (1+48))
> False
```

`np.arange` [explicitly states](https://numpy.org/doc/stable/reference/generated/numpy.arange.html) that it's "results will often not be consistent" when using "non-integer step", which is a very possible scenario in this function. The following alternative code does function correctly:

```
vals = np.around(np.linspace(y0 + step, y1, length))
```

**Your environment**
```bash
$ python -m pydicom.env_info
module       | version
------       | -------
platform     | Darwin-20.5.0-x86_64-i386-64bit
Python       | 3.7.10 (default, Feb 26 2021, 10:16:00)  [Clang 10.0.0 ]
pydicom      | 2.1.2
gdcm         | _module not found_
jpeg_ls      | _module not found_
numpy        | 1.20.3
PIL          | 8.2.0
```


Discussion:
PRs welcome!

More test data, too

Patch:
diff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py
--- a/pydicom/pixel_data_handlers/util.py
+++ b/pydicom/pixel_data_handlers/util.py
@@ -873,7 +873,7 @@ def _expand_segmented_lut(
                 lut.extend([y1] * length)
             else:
                 step = (y1 - y0) / length
-                vals = np.around(np.arange(y0 + step, y1 + step, step))
+                vals = np.around(np.linspace(y0 + step, y1, length))
                 lut.extend([int(vv) for vv in vals])
         elif opcode == 2:
             # C.7.9.2.3: Indirect segment


Test patch:
diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py
--- a/pydicom/tests/test_handler_util.py
+++ b/pydicom/tests/test_handler_util.py
@@ -1252,6 +1252,11 @@ def test_linear(self):
         out = _expand_segmented_lut(data, 'H')
         assert [-400, -320, -240, -160, -80, 0] == out
 
+        # Positive slope, floating point steps
+        data = (0, 1, 163, 1, 48, 255)
+        out = _expand_segmented_lut(data, 'H')
+        assert (1 + 48) == len(out)
+
         # No slope
         data = (0, 2, 0, 28672, 1, 5, 28672)
         out = _expand_segmented_lut(data, 'H')
Repository: pydicom/pydicom

Issue:
apply_color_lut() incorrect exception when missing RedPaletteColorLUTDescriptor
**Describe the bug**
`AttributeError` when used on a dataset without `RedPaletteColorLookupTableDescriptor `

**Expected behavior**
Should raise `ValueError` for consistency with later exceptions

**Steps To Reproduce**
```python
from pydicom.pixel_data_handlers.util import apply_color_lut
ds = dcmread("CT_small.dcm")
arr = ds.apply_color_lut(arr, ds)
```
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../pydicom/pixel_data_handlers/util.py", line 116, in apply_color_lut
    lut_desc = ds.RedPaletteColorLookupTableDescriptor
  File ".../pydicom/dataset.py", line 768, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'FileDataset' object has no attribute 'RedPaletteColorLookupTableDescriptor'
```


Discussion:

Patch:
diff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py
--- a/pydicom/pixel_data_handlers/util.py
+++ b/pydicom/pixel_data_handlers/util.py
@@ -112,6 +112,9 @@ def apply_color_lut(arr, ds=None, palette=None):
             "Table Module is not currently supported"
         )
 
+    if 'RedPaletteColorLookupTableDescriptor' not in ds:
+        raise ValueError("No suitable Palette Color Lookup Table Module found")
+
     # All channels are supposed to be identical
     lut_desc = ds.RedPaletteColorLookupTableDescriptor
     # A value of 0 = 2^16 entries


Test patch:
diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py
--- a/pydicom/tests/test_handler_util.py
+++ b/pydicom/tests/test_handler_util.py
@@ -1150,6 +1150,15 @@ def test_first_map_negative(self):
         assert [60160, 25600, 37376] == list(rgb[arr == 130][0])
         assert ([60160, 25600, 37376] == rgb[arr == 130]).all()
 
+    def test_unchanged(self):
+        """Test dataset with no LUT is unchanged."""
+        # Regression test for #1068
+        ds = dcmread(MOD_16, force=True)
+        assert 'RedPaletteColorLookupTableDescriptor' not in ds
+        msg = r"No suitable Palette Color Lookup Table Module found"
+        with pytest.raises(ValueError, match=msg):
+            apply_color_lut(ds.pixel_array, ds)
+
 
 @pytest.mark.skipif(not HAVE_NP, reason="Numpy is not available")
 class TestNumpy_ExpandSegmentedLUT(object):
Repository: pydicom/pydicom

Issue:
from_json does not correctly convert BulkDataURI's in SQ data elements
**Describe the bug**
When a DICOM object contains large data elements in SQ elements and is converted to JSON, those elements are correctly turned into BulkDataURI's. However, when the JSON is converted back to DICOM using from_json, the BulkDataURI's in SQ data elements are not converted back and warnings are thrown.

**Expected behavior**
The BulkDataURI's in SQ data elements get converted back correctly.

**Steps To Reproduce**
Take the `waveform_ecg.dcm` in the test data, convert it to JSON, and then convert the JSON to DICOM

**Your environment**
module       | version
------       | -------
platform     | macOS-10.15.7-x86_64-i386-64bit
Python       | 3.8.2 (v3.8.2:7b3ab5921f, Feb 24 2020, 17:52:18)  [Clang 6.0 (clang-600.0.57)]
pydicom      | 2.1.0
gdcm         | _module not found_
jpeg_ls      | _module not found_
numpy        | _module not found_
PIL          | _module not found_

The problem is in `jsonrep.py` at line 227. I plan on submitting a pull-request today for this.


Discussion:

Patch:
diff --git a/pydicom/jsonrep.py b/pydicom/jsonrep.py
--- a/pydicom/jsonrep.py
+++ b/pydicom/jsonrep.py
@@ -226,7 +226,8 @@ def get_sequence_item(self, value):
                     value_key = unique_value_keys[0]
                     elem = DataElement.from_json(
                         self.dataset_class, key, vr,
-                        val[value_key], value_key
+                        val[value_key], value_key,
+                        self.bulk_data_element_handler
                     )
                 ds.add(elem)
         return ds


Test patch:
diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py
--- a/pydicom/tests/test_json.py
+++ b/pydicom/tests/test_json.py
@@ -354,3 +354,25 @@ def bulk_data_reader(tag, vr, value):
         ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)
 
         assert b'xyzzy' == ds[0x00091002].value
+
+    def test_bulk_data_reader_is_called_within_SQ(self):
+        def bulk_data_reader(_):
+            return b'xyzzy'
+
+        json_data = {
+            "003a0200": {
+                "vr": "SQ", 
+                "Value": [
+                    {
+                        "54001010": {
+                            "vr": "OW",
+                            "BulkDataURI": "https://a.dummy.url"
+                        }
+                    }
+                ]
+            }
+        }
+
+        ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)
+
+        assert b'xyzzy' == ds[0x003a0200].value[0][0x54001010].value