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

Issue:
PythonRandomInterface seed initialized to None 
https://github.com/networkx/networkx/blob/087ed3b9ff9d92cf97a1d5a5cb3afd1c8b78298d/networkx/utils/misc.py#L341

When `None` is passed as seed, the code flow initializes to a `RandomState()` then sets it back to `None`. Maybe an else is missing? 


Discussion:
That's clearly a bug.  I agree that it is likely a missing else statement.

But there is more of a problem here.  The try/catch surrounds the entire `__init__` function, so it is "try"ing to define the function -- not run it.  So, really the `import numpy` part of the code is broken.  The try should be inside the if statement and only around the import numpy statement.  AND there needs to be an else clause...

Thanks very much!!

Resolving patch:
diff --git a/networkx/utils/misc.py b/networkx/utils/misc.py
--- a/networkx/utils/misc.py
+++ b/networkx/utils/misc.py
@@ -333,19 +333,18 @@ def create_random_state(random_state=None):
 
 
 class PythonRandomInterface:
-    try:
-
-        def __init__(self, rng=None):
+    def __init__(self, rng=None):
+        try:
             import numpy
+        except ImportError:
+            msg = "numpy not found, only random.random available."
+            warnings.warn(msg, ImportWarning)
 
-            if rng is None:
-                self._rng = numpy.random.mtrand._rand
+        if rng is None:
+            self._rng = numpy.random.mtrand._rand
+        else:
             self._rng = rng
 
-    except ImportError:
-        msg = "numpy not found, only random.random available."
-        warnings.warn(msg, ImportWarning)
-
     def random(self):
         return self._rng.random_sample()
 


Test patch:
Repository: networkx/networkx

Issue:
how to draw the node-A to the node-A by networkx



Discussion:
An edge from node A to node A is called a self-loop.
We recently had a nice addition #4370  to NetworkX that draws these loops, but it has not yet been released.
You can install the development version of NetworkX off of Github or wait a month and the next release will have that feature.

Resolving patch:
diff --git a/examples/drawing/plot_selfloops.py b/examples/drawing/plot_selfloops.py
new file mode 100644
--- /dev/null
+++ b/examples/drawing/plot_selfloops.py
@@ -0,0 +1,29 @@
+"""
+==========
+Self-loops
+==========
+
+A self-loop is an edge that originates from and terminates the same node.
+This example shows how to draw self-loops with `nx_pylab`.
+
+"""
+import networkx as nx
+import matplotlib.pyplot as plt
+
+# Create a graph and add a self-loop to node 0
+G = nx.complete_graph(3, create_using=nx.DiGraph)
+G.add_edge(0, 0)
+pos = nx.circular_layout(G)
+
+# As of version 2.6, self-loops are drawn by default with the same styling as
+# other edges
+nx.draw(G, pos, with_labels=True)
+
+# Add self-loops to the remaining nodes
+edgelist = [(1, 1), (2, 2)]
+G.add_edges_from(edgelist)
+
+# Draw the newly added self-loops with different formatting
+nx.draw_networkx_edges(G, pos, edgelist=edgelist, arrowstyle="<|-", style="dashed")
+
+plt.show()


Test patch:
Repository: networkx/networkx

Issue:
Documentation: Make classes AtlasView et. al. from networkx/classes/coreviews.py accessible from documentation
Lest I seem ungrateful, I like networkx a lot, and rely on it for two of my main personal projects [fake-data-for-learning](https://github.com/munichpavel/fake-data-for-learning) and the WIP [clovek-ne-jezi-se](https://github.com/munichpavel/clovek-ne-jezi-se).

As I was trying to understand `AtlasView`s, I could find only examples in the documentation (see [this search](https://networkx.org/documentation/stable//search.html?q=AtlasView&check_keywords=yes&area=default#)), none of which pointed to the (well-documented) source code [networkx/classes/coreviews.py](https://github.com/networkx/networkx/blob/master/networkx/classes/coreviews.py).

I think the fix should just be a matter of tweaking how you have configured Sphinx to run.


Discussion:
Yes!  Thank you for this nudge. They should have been included in the sphinx docs and never were...

Resolving patch:
diff --git a/networkx/classes/coreviews.py b/networkx/classes/coreviews.py
--- a/networkx/classes/coreviews.py
+++ b/networkx/classes/coreviews.py
@@ -1,4 +1,6 @@
-"""
+"""Views of core data structures such as nested Mappings (e.g. dict-of-dicts).
+These ``Views`` often restrict element access, with either the entire view or
+layers of nested mappings being read-only.
 """
 import warnings
 from collections.abc import Mapping


Test patch:
Repository: networkx/networkx

Issue:
Support for disjunctive graph?
I am about to solve FJSSP using oriented disjunctive graph with conjunctive/disjuncted graph arcs. The way I see it, MultiDiGraph structure would be suitable: is the simplex method (Dantzig) - I presume _network_simplex_ method - applyable in this case? Thanks.


Discussion:
MultiDiGraph structures are supported as of #1280 (about 6 years ago).
But it looks like the doc_string should be updated to reflect this!! 
I'm not sure what Dantzig actually refers to in terms of an algorithm, but there are [citations in the docs](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.flow.network_simplex.html) to papers describing the algorithm.
Dantzig's simplex algorithm = Simplex method. I just wanted to know if MultiDiGraph instance was supported, which it is. Thank you.
Good!   I'm going to leave this open as a reminder to change the docs for simplex_method (and maybe others in that module) to remove text stating an error is raised for multigraphs when it actually isn't true.

Resolving patch:
diff --git a/networkx/algorithms/flow/networksimplex.py b/networkx/algorithms/flow/networksimplex.py
--- a/networkx/algorithms/flow/networksimplex.py
+++ b/networkx/algorithms/flow/networksimplex.py
@@ -62,8 +62,8 @@ def network_simplex(G, demand="demand", capacity="capacity", weight="weight"):
     Raises
     ------
     NetworkXError
-        This exception is raised if the input graph is not directed,
-        not connected or is a multigraph.
+        This exception is raised if the input graph is not directed or
+        not connected.
 
     NetworkXUnfeasible
         This exception is raised in the following situations:


Test patch:
Repository: networkx/networkx

Issue:
Allow binomial_tree() to create directed graphs (via create_using parameter)
`binomial_tree() ` doesn't seem to allow the `create_using` parameter to get passed and as a result, one can't create a directed binomial graph. 

This seem like a inadvertent omission and easy to fix. I will put in a PR to address this soon.


Discussion:

Resolving patch:
diff --git a/networkx/generators/classic.py b/networkx/generators/classic.py
--- a/networkx/generators/classic.py
+++ b/networkx/generators/classic.py
@@ -188,7 +188,7 @@ def barbell_graph(m1, m2, create_using=None):
     return G
 
 
-def binomial_tree(n):
+def binomial_tree(n, create_using=None):
     """Returns the Binomial Tree of order n.
 
     The binomial tree of order 0 consists of a single node. A binomial tree of order k
@@ -200,16 +200,21 @@ def binomial_tree(n):
     n : int
         Order of the binomial tree.
 
+    create_using : NetworkX graph constructor, optional (default=nx.Graph)
+       Graph type to create. If graph instance, then cleared before populated.
+
     Returns
     -------
     G : NetworkX graph
         A binomial tree of $2^n$ nodes and $2^n - 1$ edges.
 
     """
-    G = nx.empty_graph(1)
+    G = nx.empty_graph(1, create_using)
+
     N = 1
     for i in range(n):
-        edges = [(u + N, v + N) for (u, v) in G.edges]
+        # Use G.edges() to ensure 2-tuples. G.edges is 3-tuple for MultiGraph
+        edges = [(u + N, v + N) for (u, v) in G.edges()]
         G.add_edges_from(edges)
         G.add_edge(0, N)
         N *= 2


Test patch:
diff --git a/networkx/generators/tests/test_classic.py b/networkx/generators/tests/test_classic.py
--- a/networkx/generators/tests/test_classic.py
+++ b/networkx/generators/tests/test_classic.py
@@ -138,10 +138,12 @@ def test_barbell_graph(self):
         assert_edges_equal(mb.edges(), b.edges())
 
     def test_binomial_tree(self):
-        for n in range(0, 4):
-            b = nx.binomial_tree(n)
-            assert nx.number_of_nodes(b) == 2 ** n
-            assert nx.number_of_edges(b) == (2 ** n - 1)
+        graphs = (None, nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
+        for create_using in graphs:
+            for n in range(0, 4):
+                b = nx.binomial_tree(n, create_using)
+                assert nx.number_of_nodes(b) == 2 ** n
+                assert nx.number_of_edges(b) == (2 ** n - 1)
 
     def test_complete_graph(self):
         # complete_graph(m) is a connected graph with
Repository: networkx/networkx

Issue:
Improve nx_pylab testing
Currently our visualization test suite are smoke tests.  We should investigate using ``pytest-mpl``
- https://github.com/matplotlib/pytest-mpl

See #4375.


Discussion:
I ran into an issue while debugging a hang in `test_pylab` due to the recent addition of non-smoke tests (i.e. tests that assert things about axis geometries) in f559558 (#4374):

The default behavior for the `nx_pylab` functions when the `ax` kwarg is `None` (the default value) is to call `plt.gca()`. Note that axis objects created in unit tests persist across function boundaries! 

```python
def test_1():
    fig, ax = plt.subplots()

def test_2():
    ax = plt.gca()   # This is the axis object created in test_1!
```

This crosstalk between tests can lead to unstable/unexpected test behavior, so it's important to recognize. The solution used in #4374 is to call `plt.delaxes` as a "cleanup" step in the unit tests that create axes objects. There's probably a better solution to this, and something to keep in mind as the `nx_pylab` tests are improved.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -146,7 +146,7 @@
     "networkx.algorithms.tree": ["tests/*.py"],
     "networkx.classes": ["tests/*.py"],
     "networkx.generators": ["tests/*.py", "atlas.dat.gz"],
-    "networkx.drawing": ["tests/*.py"],
+    "networkx.drawing": ["tests/*.py", "tests/baseline/*png"],
     "networkx.linalg": ["tests/*.py"],
     "networkx.readwrite": ["tests/*.py"],
     "networkx.readwrite.json_graph": ["tests/*.py"],


Test patch:
diff --git a/networkx/drawing/tests/baseline/test_house_with_colors.png b/networkx/drawing/tests/baseline/test_house_with_colors.png
new file mode 100644
Binary files /dev/null and b/networkx/drawing/tests/baseline/test_house_with_colors.png differ
diff --git a/networkx/drawing/tests/test_pylab.py b/networkx/drawing/tests/test_pylab.py
--- a/networkx/drawing/tests/test_pylab.py
+++ b/networkx/drawing/tests/test_pylab.py
@@ -416,6 +416,32 @@ def test_labels_and_colors():
     # plt.show()
 
 
+@pytest.mark.mpl_image_compare
+def test_house_with_colors():
+    G = nx.house_graph()
+    # explicitly set positions
+    fig, ax = plt.subplots()
+    pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
+
+    # Plot nodes with different properties for the "wall" and "roof" nodes
+    nx.draw_networkx_nodes(
+        G,
+        pos,
+        node_size=3000,
+        nodelist=[0, 1, 2, 3],
+        node_color="tab:blue",
+    )
+    nx.draw_networkx_nodes(
+        G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
+    )
+    nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
+    # Customize axes
+    ax.margins(0.11)
+    plt.tight_layout()
+    plt.axis("off")
+    return fig
+
+
 def test_axes():
     fig, ax = plt.subplots()
     nx.draw(barbell, ax=ax)
diff --git a/requirements/test.txt b/requirements/test.txt
--- a/requirements/test.txt
+++ b/requirements/test.txt
@@ -1,3 +1,4 @@
 pytest>=7.0
 pytest-cov>=3.0
+pytest-mpl>=0.14; platform_python_implementation!='PyPy'
 codecov>=2.1
Repository: networkx/networkx

Issue:
Incorrect link to the paper in katz_centrality documentation
### Current Behavior

Link [2] in katz_centrality documentation directs to the incorrect paper: 'Universal Behavior of Load Distribution in Scale-Free Networks'

### Expected Behavior
Link [2] in katz_centrality documentation directs to the correct paper: 'A New Status Index Derived from Sociometric Index'

### Steps to Reproduce
Open the page https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.katz_centrality.html

### Additional context
I guess the correct link is https://link.springer.com/content/pdf/10.1007/BF02289026.pdf



Discussion:
Looks like that spurious link appears twice in that module/file.  Thanks!


Resolving patch:
diff --git a/networkx/algorithms/centrality/katz.py b/networkx/algorithms/centrality/katz.py
--- a/networkx/algorithms/centrality/katz.py
+++ b/networkx/algorithms/centrality/katz.py
@@ -142,7 +142,7 @@ def katz_centrality(
     .. [2] Leo Katz:
        A New Status Index Derived from Sociometric Index.
        Psychometrika 18(1):39–43, 1953
-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
     """
     if len(G) == 0:
         return {}
@@ -302,7 +302,7 @@ def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
     .. [2] Leo Katz:
        A New Status Index Derived from Sociometric Index.
        Psychometrika 18(1):39–43, 1953
-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
     """
     import numpy as np
 


Test patch:
Repository: networkx/networkx

Issue:
`networkx.utils.misc` missing `__all__`
The `misc` module in the `utils` package doesn't define an `__all__`. As a consequence, some non-networkx functionality including e.g. objects from `collections` and builtin modules are incorrectly exposed in the `networkx.utils` namespace, including networkx itself:

```python
from networkx.utils import nx  # yikes
```


Discussion:

Resolving patch:
diff --git a/networkx/utils/misc.py b/networkx/utils/misc.py
--- a/networkx/utils/misc.py
+++ b/networkx/utils/misc.py
@@ -19,6 +19,30 @@
 from itertools import tee, chain
 import networkx as nx
 
+__all__ = [
+    "is_string_like",
+    "iterable",
+    "empty_generator",
+    "flatten",
+    "make_list_of_ints",
+    "is_list_of_ints",
+    "make_str",
+    "generate_unique_node",
+    "default_opener",
+    "dict_to_numpy_array",
+    "dict_to_numpy_array1",
+    "dict_to_numpy_array2",
+    "is_iterator",
+    "arbitrary_element",
+    "consume",
+    "pairwise",
+    "groups",
+    "to_tuple",
+    "create_random_state",
+    "create_py_random_state",
+    "PythonRandomInterface",
+]
+
 
 # some cookbook stuff
 # used in deciding whether something is a bunch of nodes, edges, etc.
diff --git a/networkx/utils/random_sequence.py b/networkx/utils/random_sequence.py
--- a/networkx/utils/random_sequence.py
+++ b/networkx/utils/random_sequence.py
@@ -7,6 +7,16 @@
 from networkx.utils import py_random_state
 
 
+__all__ = [
+    "powerlaw_sequence",
+    "zipf_rv",
+    "cumulative_distribution",
+    "discrete_sequence",
+    "random_weighted_sample",
+    "weighted_choice",
+]
+
+
 # The same helpers for choosing random sequences from distributions
 # uses Python's random module
 # https://docs.python.org/3/library/random.html


Test patch:
diff --git a/networkx/utils/tests/test__init.py b/networkx/utils/tests/test__init.py
new file mode 100644
--- /dev/null
+++ b/networkx/utils/tests/test__init.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+def test_utils_namespace():
+    """Ensure objects are not unintentionally exposed in utils namespace."""
+    with pytest.raises(ImportError):
+        from networkx.utils import nx
+    with pytest.raises(ImportError):
+        from networkx.utils import sys
+    with pytest.raises(ImportError):
+        from networkx.utils import defaultdict, deque
Repository: networkx/networkx

Issue:
Remove function utils.preserve_random_state
Remove and appropriately deprecate utils.preserve_random_state which as mentioned in #4732 looks like it was moved to utils in the same PR that its use was removed from networkx.

Needs:  (anything else?)
- [ ] Deprecate warning in the function itself. 
- [ ] Note in the list of deprecations to handle for v3.0.


Discussion:

Resolving patch:
diff --git a/networkx/conftest.py b/networkx/conftest.py
--- a/networkx/conftest.py
+++ b/networkx/conftest.py
@@ -133,6 +133,9 @@ def set_warnings():
     warnings.filterwarnings(
         "ignore", category=DeprecationWarning, message="\nThe `attrs` keyword"
     )
+    warnings.filterwarnings(
+        "ignore", category=DeprecationWarning, message="preserve_random_state"
+    )
 
 
 @pytest.fixture(autouse=True)
diff --git a/networkx/utils/decorators.py b/networkx/utils/decorators.py
--- a/networkx/utils/decorators.py
+++ b/networkx/utils/decorators.py
@@ -2,6 +2,7 @@
 from os.path import splitext
 from contextlib import contextmanager
 from pathlib import Path
+import warnings
 
 import networkx as nx
 from decorator import decorator
@@ -331,6 +332,9 @@ def do_random_stuff(x, y):
     -----
     If numpy.random is not importable, the state is not saved or restored.
     """
+    msg = "preserve_random_state is deprecated and will be removed in 3.0."
+    warnings.warn(msg, DeprecationWarning)
+
     try:
         import numpy as np
 


Test patch:
Repository: networkx/networkx

Issue:
k_crust(G, k) behavior is misleading when combined to k_core(G, k)
With reference to the documentation, k_crust(G, k) returns in fact the complement of k_core(G, k+1).
But this behavior is very misleading.
What is the reason of such behavior for k_crust when k is specified?
Thanks


Discussion:
It looks like ```k_crust``` removes the k-core and so is the complement of k_core(G,k).
I think the documentation says: 
```The k-crust is the graph G with the k-core removed.```
Also ```Note: This definition of k-crust is different than the definition in [1]. The k-crust in [1] is equivalent to the k+1 crust of this algorithm.```

Are you saying the function doesn't do what it's documentation says?
Or that it agrees with the documentation but should be defined differently?
As far as I understand the documentation about the k_crust(G, k), the code is working as explained. However, it is misleading to run :
nx.k_core(G, k=i).nodes()
nx.k_crust(G, k=i).nodes()
and to see nodes belonging to the two sets.... or I do not understand the math concept...
Ahhh... I think I see the confusion now:
The docs say the k-crust is G with the k-core removed. 
But it's not clear there whether we remove the nodes or the edges of the k-core.

We remove the edges as well as any isolated nodes after those edges are gone.
This seems reasonable, but I can believe there are reasons to return all nodes, and only the edges not in the k_core.

But we should not return only the nodes not in the k-core. That removes too much.
I do believe that the k_core and the k_crust must have some nodes in common. It's the edges that are the focus of this way of looking at graph structure.


Resolving patch:
diff --git a/networkx/algorithms/core.py b/networkx/algorithms/core.py
--- a/networkx/algorithms/core.py
+++ b/networkx/algorithms/core.py
@@ -259,7 +259,8 @@ def k_filter(v, k, c):
 def k_crust(G, k=None, core_number=None):
     """Returns the k-crust of G.
 
-    The k-crust is the graph G with the k-core removed.
+    The k-crust is the graph G with the edges of the k-core removed
+    and isolated nodes found after the removal of edges are also removed.
 
     Parameters
     ----------


Test patch:
Repository: networkx/networkx

Issue:
Getting 403 Forbidden errors when running plot_custom_node_icons example
The way `plot_custom_node_icons` is currently set up, we grab resources from `materialsui.com` every time anyone runs this example which of course includes our own CI runs. We are now getting 403 forbidden errors (rightly so) since we are accessing these resources programatically. I can think of 2 ways around this:
 1) Store the icon png's locally so we're not constantly having to download them from an external source
 2) Add header spoofing to the url request.

Though it makes the example a bit larger, I prefer option 1). The second option would add boilerplate to the example, and isn't exactly setting an example of good web citizenship. I'm certainly open to other ideas though!


Discussion:

Resolving patch:
diff --git a/examples/drawing/plot_custom_node_icons.py b/examples/drawing/plot_custom_node_icons.py
--- a/examples/drawing/plot_custom_node_icons.py
+++ b/examples/drawing/plot_custom_node_icons.py
@@ -4,24 +4,23 @@
 =================
 
 Example of using custom icons to represent nodes with matplotlib.
+
+Images for node icons courtesy of www.materialui.co
 """
 
 import matplotlib.pyplot as plt
 import networkx as nx
 import PIL
-import urllib.request
 
 # Image URLs for graph nodes
-icon_urls = {
-    "router": "https://www.materialui.co/materialIcons/hardware/router_black_144x144.png",
-    "switch": "https://www.materialui.co/materialIcons/action/dns_black_144x144.png",
-    "PC": "https://www.materialui.co/materialIcons/hardware/computer_black_144x144.png",
+icons = {
+    "router": "icons/router_black_144x144.png",
+    "switch": "icons/switch_black_144x144.png",
+    "PC": "icons/computer_black_144x144.png",
 }
 
-# Load images from web
-images = {
-    k: PIL.Image.open(urllib.request.urlopen(url)) for k, url in icon_urls.items()
-}
+# Load images
+images = {k: PIL.Image.open(fname) for k, fname in icons.items()}
 
 # Generate the computer network graph
 G = nx.Graph()
@@ -39,10 +38,22 @@
     for v in range(1, 4):
         G.add_edge("switch_" + str(u), "PC_" + str(u) + "_" + str(v))
 
-# get layout and draw edges
-pos = nx.spring_layout(G)
+# Get a reproducible layout and create figure
+pos = nx.spring_layout(G, seed=1734289230)
 fig, ax = plt.subplots()
-nx.draw_networkx_edges(G, pos=pos, ax=ax, min_source_margin=15, min_target_margin=15)
+
+# Note: the min_source/target_margin kwargs only work with FancyArrowPatch objects.
+# Force the use of FancyArrowPatch for edge drawing by setting `arrows=True`,
+# but suppress arrowheads with `arrowstyle="-"`
+nx.draw_networkx_edges(
+    G,
+    pos=pos,
+    ax=ax,
+    arrows=True,
+    arrowstyle="-",
+    min_source_margin=15,
+    min_target_margin=15,
+)
 
 # Transform from data coordinates (scaled between xlim and ylim) to display coordinates
 tr_figure = ax.transData.transform


Test patch:
Repository: networkx/networkx

Issue:
Add destringizer example to read_gml docstring
IMO it would be a nice addition to add a simple example of the `destringizer` parameter to the `read_gml` docstring. See #4854 for inspiration.


Discussion:
Adding this with pull request #4916
Thanks @randallwvr90, the rewording is indeed more clear --- it would still be nice to add a detailed example demonstrating the results of loading w/ and w/out the destringizer, so I propose to leave this open.

Resolving patch:
diff --git a/networkx/readwrite/gml.py b/networkx/readwrite/gml.py
--- a/networkx/readwrite/gml.py
+++ b/networkx/readwrite/gml.py
@@ -163,8 +163,20 @@ def read_gml(path, label="label", destringizer=None):
     --------
     >>> G = nx.path_graph(4)
     >>> nx.write_gml(G, "test.gml")
+
+    GML values are interpreted as strings by default:
+
     >>> H = nx.read_gml("test.gml")
-    >>> I = nx.read_gml("test.gml", destringizer=int)
+    >>> H.nodes
+    NodeView(('0', '1', '2', '3'))
+
+    When a `destringizer` is provided, GML values are converted to the provided type.
+    For example, integer nodes can be recovered as shown below:
+
+    >>> J = nx.read_gml("test.gml", destringizer=int)
+    >>> J.nodes
+    NodeView((0, 1, 2, 3))
+
     """
 
     def filter_lines(lines):


Test patch: