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

Issue:
Speed-up of Graph.__getitem__
The documentation (at  https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html) says:  
"It is usually more convenient (and faster) to access the adjacency dictionary as G[n]".

However, my testing using %timeit showed that is not true.

```python
%timeit G[2]
%timeit list(G.neighbors(2))
```

```
1.08 µs ± 42.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
685 ns ± 37.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
```


Discussion:
We can easily speed up G[u] to be as fast as it used to be. 
(in G.__getitem__ use G._adj, not G.adj) 
This Issue should lead to a PR which does that. That is a much better fix than changing the docs.  
Thank you for bringing it up!  

```python
    %timeit G[2]
    %timeit G.neighbors(2)
    %timeit G._adj[2]        # the fastest: direct access to the data

    %timeit [n for n in G[2]]
    %timeit [n for n in G.neighbors(2)]
    %timeit [n for n in G._adj[2]]
```

With the resulting times

    630 ns ± 6.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    238 ns ± 3.86 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    62.7 ns ± 0.626 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

    13.1 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    12.6 µs ± 123 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    11.9 µs ± 65.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
What was the reason of switching to G.adj if G._adj is faster?
G.adj is read-only as is G.adj[u] and G.adj[u][v] but G.adj[u][v]['attr'] is a read-write dict.
They all use G._adj to look up the info, but they protect against corrupting the data structure.
Whoops...  We can't rewrite ```G.__getitem__``` to return ```G._adj[n]``` because while that is faster, it no longer protects the data structure. 

We'll have to change the docs instead...  :{

Resolving patch:
diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py
--- a/networkx/classes/graph.py
+++ b/networkx/classes/graph.py
@@ -1223,8 +1223,7 @@ def neighbors(self, n):
 
         Notes
         -----
-        It is usually more convenient (and faster) to access the
-        adjacency dictionary as ``G[n]``:
+        Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
 
         >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
         >>> G.add_edge('a', 'b', weight=7)


Test patch:
Repository: networkx/networkx

Issue:
examples/javascript missing files
Hi! 

[examples/javascript](https://networkx.github.io/documentation/networkx-2.2/auto_examples/javascript/force.html#sphx-glr-download-auto-examples-javascript-force-py) shows how to get the graph in html. Webpage allows downloading the python file but doesn't the other related files and folders. One has to go to the github and download the example from the repo. 

Is this just an omission or a bug? I could perhaps fix it with some initial guidance. 

Thanks!


Discussion:

Resolving patch:
diff --git a/examples/javascript/force.py b/examples/javascript/force.py
--- a/examples/javascript/force.py
+++ b/examples/javascript/force.py
@@ -5,6 +5,10 @@
 
 Example of writing JSON format graph data and using the D3 Javascript library
 to produce an HTML/Javascript drawing.
+
+You will need to download the following directory:
+
+- https://github.com/networkx/networkx/tree/master/examples/javascript/force
 """
 import json
 


Test patch:
Repository: networkx/networkx

Issue:
grid_graph says it takes a tuple, but will only take a list
Using the latest master, networkx.grid_graph works when passing in a list, but crashes when passing in a tuple:

```
$ ~/anaconda3/envs/python37env/bin/python --version
Python 3.7.4
$ ~/anaconda3/envs/python37env/bin/python -c "import networkx; networkx.grid_graph([10,5])"
$ ~/anaconda3/envs/python37env/bin/python -c "import networkx; networkx.grid_graph((10,5))"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/networkx/networkx/generators/lattice.py", line 129, in grid_graph
    dlabel = "%s" % dim
TypeError: not all arguments converted during string formatting
```

https://networkx.github.io/documentation/stable/reference/generated/networkx.generators.lattice.grid_graph.html
> dim (list or tuple of numbers...)


Discussion:
That's a bug in grid_graph.  The first line is ```dlabel = "%s" % dim``` and should be ```dlabel = "%s" % (dim,)```.  But I'm not sure why that line is even there... ```dlabel``` is never used.

It looks like that line is a mistake that appeared 2 years ago when taking out the G.name attribute in the grid_graph and moving it to lattice.py.
We should simply remove that line.

As a workaround, you can use:  nx.grid_graph(((2,3),))

Resolving patch:
diff --git a/networkx/generators/lattice.py b/networkx/generators/lattice.py
--- a/networkx/generators/lattice.py
+++ b/networkx/generators/lattice.py
@@ -126,7 +126,6 @@ def grid_graph(dim, periodic=False):
     >>> len(G)
     6
     """
-    dlabel = "%s" % dim
     if not dim:
         return empty_graph(0)
 


Test patch:
Repository: networkx/networkx

Issue:
`minimum_st_node_cut` returns empty list instead of set for adjacent nodes
https://github.com/networkx/networkx/blob/3f4f9c3379a5d70fc58852154aab7b1051ff96d6/networkx/algorithms/connectivity/cuts.py#L284

Should read `return {}`. Was questioning my sanity for a bit there 😉


Discussion:

Resolving patch:
diff --git a/networkx/algorithms/connectivity/cuts.py b/networkx/algorithms/connectivity/cuts.py
--- a/networkx/algorithms/connectivity/cuts.py
+++ b/networkx/algorithms/connectivity/cuts.py
@@ -281,7 +281,7 @@ def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):
     if mapping is None:
         raise nx.NetworkXError('Invalid auxiliary digraph.')
     if G.has_edge(s, t) or G.has_edge(t, s):
-        return []
+        return {}
     kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H)
 
     # The edge cut in the auxiliary digraph corresponds to the node cut in the


Test patch:
diff --git a/networkx/algorithms/connectivity/tests/test_cuts.py b/networkx/algorithms/connectivity/tests/test_cuts.py
--- a/networkx/algorithms/connectivity/tests/test_cuts.py
+++ b/networkx/algorithms/connectivity/tests/test_cuts.py
@@ -268,7 +268,7 @@ def tests_minimum_st_node_cut():
     G.add_nodes_from([0, 1, 2, 3, 7, 8, 11, 12])
     G.add_edges_from([(7, 11), (1, 11), (1, 12), (12, 8), (0, 1)])
     nodelist = minimum_st_node_cut(G, 7, 11)
-    assert(nodelist == [])
+    assert(nodelist == {})
 
 
 def test_invalid_auxiliary():
Repository: networkx/networkx

Issue:
Add support for sets of graph edges
Currently it looks like only tuples and lists of graph edgeds are supported, however with a small change I think it would be easy to add support for any Iterable, providing greater flexibilty to users of the library. Are there any considerations I'd need to take before submitting a PR?


Discussion:

Resolving patch:
diff --git a/networkx/convert.py b/networkx/convert.py
--- a/networkx/convert.py
+++ b/networkx/convert.py
@@ -50,7 +50,7 @@ def to_networkx_graph(data, create_using=None, multigraph_input=False):
          any NetworkX graph
          dict-of-dicts
          dict-of-lists
-         list of edges
+         container (ie set, list, tuple, iterator) of edges
          Pandas DataFrame (row per edge)
          numpy matrix
          numpy ndarray
@@ -108,7 +108,7 @@ def to_networkx_graph(data, create_using=None, multigraph_input=False):
 
     # list or generator of edges
 
-    if isinstance(data, (list, tuple)) or any(
+    if isinstance(data, (list, tuple, set)) or any(
         hasattr(data, attr) for attr in ["_adjdict", "next", "__next__"]
     ):
         try:


Test patch:
Repository: networkx/networkx

Issue:
Pajek export assumes Graph node's id attribute to be int castable
In pajek export it reads https://github.com/networkx/networkx/blob/b0ca6ce081cc6e66d509c5f7fed60728da821c25/networkx/readwrite/pajek.py#L57

I was wondering, since NetworkX supports arbitrary Python objects as Graph nodes where does the assumption come from that a node's `id` attribute is `int` castable? An objects `id` attribute would have nothing to do with Python's builtin `id()`. But I'm not familiar with the Pajek file format so don't know about the relevance and special treatment of `id` in it.

I was working with a Graph whose node's `id` attribute happened to be a string. For it Pajek export failed with
```
ValueError: invalid literal for int() with base 10: 'arn:aws:iam::579763146468:role/aws-service-role/trustedadvisor.amazonaws.com/AWSServiceRoleForTrustedAdvisor'
```



Discussion:
Its not a networkx limitation -- its a Pajek standard.
You can [relabel the nodes](https://networkx.github.io/documentation/stable/reference/relabel.html) to be integers and store the string as an attribute in the Pajek file.
I see, thank you for clarifying! Since this is a limitation always enforced by the Pajek standard, would it make sense to add a try/catch ValueError around the int() cast and add that information together with your suggestion to relabel? Or is there a situation where the raw `ValueError: invalid literal for int()` is a more useful output? I'd send a PR if that makes sense.

That's an excellent idea! 
I think the cost of a try/catch over the casting should be small and the error message probably would help some people a lot.  :}

Resolving patch:
diff --git a/networkx/readwrite/pajek.py b/networkx/readwrite/pajek.py
--- a/networkx/readwrite/pajek.py
+++ b/networkx/readwrite/pajek.py
@@ -54,7 +54,12 @@ def generate_pajek(G):
         na = G.nodes.get(n, {}).copy()
         x = na.pop('x', 0.0)
         y = na.pop('y', 0.0)
-        id = int(na.pop('id', nodenumber[n]))
+        try:
+            id = int(na.pop('id', nodenumber[n]))
+        except ValueError as e:
+            e.args += (("Pajek format requires 'id' to be an int()."
+                        " Refer to the 'Relabeling nodes' section."),)
+            raise
         nodenumber[n] = id
         shape = na.pop('shape', 'ellipse')
         s = ' '.join(map(make_qstr, (id, n, x, y, shape)))


Test patch:
Repository: networkx/networkx

Issue:
gaussian_random_partition_graph constructor optional parameter doesn't work
gaussian_random_partition_graph constructor always returns a directed graph no matter how I set the parameter "directed"


Discussion:
Yes -- indeed the function ```gaussian_random_partition_graph``` calls ```random_partition_graph``` with positional arguments in the wrong order. seed and directed are switched. Would be good to change that call to using keywords:

```python
gaussian_random_partition_graph(sizes, p_in, p_out, directed=directed, seed=seed)
```

Resolving patch:
diff --git a/networkx/generators/community.py b/networkx/generators/community.py
--- a/networkx/generators/community.py
+++ b/networkx/generators/community.py
@@ -300,7 +300,7 @@ def planted_partition_graph(l, k, p_in, p_out, seed=None, directed=False):
     .. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
        Volume 486, Issue 3-5 p. 75-174. https://arxiv.org/abs/0906.0612
     """
-    return random_partition_graph([k] * l, p_in, p_out, seed, directed)
+    return random_partition_graph([k] * l, p_in, p_out, seed=seed, directed=directed)
 
 
 @py_random_state(6)
@@ -377,7 +377,7 @@ def gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False,
             break
         assigned += size
         sizes.append(size)
-    return random_partition_graph(sizes, p_in, p_out, directed, seed)
+    return random_partition_graph(sizes, p_in, p_out, seed=seed, directed=directed)
 
 
 def ring_of_cliques(num_cliques, clique_size):


Test patch:
Repository: networkx/networkx

Issue:
Misleading description in the doc
In this page
https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.structuralholes.effective_size.html
The description of *Return* is "Dictionary with nodes as keys and the constraint on the node as values."
But this is effective size. I think it should be  "Dictionary with nodes as keys and the **effective size of** the node as values."


Discussion:

Resolving patch:
diff --git a/networkx/algorithms/structuralholes.py b/networkx/algorithms/structuralholes.py
--- a/networkx/algorithms/structuralholes.py
+++ b/networkx/algorithms/structuralholes.py
@@ -98,7 +98,7 @@ def effective_size(G, nodes=None, weight=None):
     Returns
     -------
     dict
-        Dictionary with nodes as keys and the constraint on the node as values.
+        Dictionary with nodes as keys and the effective size of the node as values.
 
     Notes
     -----


Test patch:
Repository: networkx/networkx

Issue:
Documentation for approximate_current_flow_betweenness_centrality, edge_current_flow_betweenness_centrality and current_flow_betweenness_centrality does not match
In the documentation the default `solver` of nx.approximate_current_flow_betweenness_centrality nx.edge_current_flow_betweenness_centrality and nx.current_flow_betweenness_centrality is `'lu'`. In the definition of the function the default is however `'full'`.

As `'lu'` is the recommended method and it is the default is in 

- `nx.edge_current_flow_betweenness_centrality_subset`, 
- `nx.current_flow_betweenness_centrality_subset`, 
- `nx.current_flow_closeness_centrality` 

the defaults should be changed here as well.


Discussion:
Can you please change the documentation instead of changing the default?
The history of commits shows that #3981 changed the default to "full".
But it neglected to change the documentation. Let's bring it up-to-date by 
changing the documentation.    Thanks for bringing this issue to light!

Resolving patch:
diff --git a/networkx/algorithms/centrality/current_flow_betweenness.py b/networkx/algorithms/centrality/current_flow_betweenness.py
--- a/networkx/algorithms/centrality/current_flow_betweenness.py
+++ b/networkx/algorithms/centrality/current_flow_betweenness.py
@@ -46,7 +46,7 @@ def approximate_current_flow_betweenness_centrality(G, normalized=True,
       Default data type for internal matrices.
       Set to np.float32 for lower memory consumption.
 
-    solver : string (default='lu')
+    solver : string (default='full')
        Type of linear solver to use for computing the flow matrix.
        Options are "full" (uses most memory), "lu" (recommended), and
        "cg" (uses least memory).
@@ -168,7 +168,7 @@ def current_flow_betweenness_centrality(G, normalized=True, weight=None,
       Default data type for internal matrices.
       Set to np.float32 for lower memory consumption.
 
-    solver : string (default='lu')
+    solver : string (default='full')
        Type of linear solver to use for computing the flow matrix.
        Options are "full" (uses most memory), "lu" (recommended), and
        "cg" (uses least memory).
@@ -273,7 +273,7 @@ def edge_current_flow_betweenness_centrality(G, normalized=True,
       Default data type for internal matrices.
       Set to np.float32 for lower memory consumption.
 
-    solver : string (default='lu')
+    solver : string (default='full')
        Type of linear solver to use for computing the flow matrix.
        Options are "full" (uses most memory), "lu" (recommended), and
        "cg" (uses least memory).


Test patch:
Repository: networkx/networkx

Issue:
Feature Big Picture URLs in documentation 
We should include more links to the documentation landing page and the github repository in our documentation.

Links to the landing page would allow people to switch between docs for different versions and between docs and code.

Links to the github repository would allow people to find the code/issues/PRs from the docs while staying in a browser (not installing source code locally via git).


Discussion:

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -55,7 +55,7 @@
 autosummary_generate = True
 
 # Add any paths that contain templates here, relative to this directory.
-# templates_path = ['']
+templates_path = ['_templates']
 
 suppress_warnings = ["ref.citation", "ref.footnote"]
 


Test patch:
Repository: networkx/networkx

Issue:
documentation for "edge_key" param in nx.from_pandas_edgelist() missing
I just noticed this while working on implementing support for geopandas (I want it to behave as similar to pandas functions). I guess it's for MultiGraphs which I can't really wrap my head around.


Discussion:
Thanks for reporting this!  
That's the result of #4076 which was recently merged after apparently not enough review. :)
It needs to be fixed.

Resolving patch:
diff --git a/networkx/convert_matrix.py b/networkx/convert_matrix.py
--- a/networkx/convert_matrix.py
+++ b/networkx/convert_matrix.py
@@ -312,7 +312,12 @@ def from_pandas_edgelist(
         If `None`, no edge attributes are added to the graph.
 
     create_using : NetworkX graph constructor, optional (default=nx.Graph)
-       Graph type to create. If graph instance, then cleared before populated.
+        Graph type to create. If graph instance, then cleared before populated.
+
+    edge_key : str or None, optional (default=None)
+        A valid column name for the edge keys (for a MultiGraph). The values in
+        this column are used for the edge keys when adding edges if create_using
+        is a multigraph.
 
     See Also
     --------
@@ -352,17 +357,17 @@ def from_pandas_edgelist(
 
     Build multigraph with custom keys:
 
-    >>> edges = pd.DataFrame({'source': [0, 1, 2],
-    ...                       'target': [2, 2, 3],
-    ...                       'key': ['A', 'B', 'C'],
-    ...                       'weight': [3, 4, 5],
-    ...                       'color': ['red', 'blue', 'blue']})
+    >>> edges = pd.DataFrame({'source': [0, 1, 2, 0],
+    ...                       'target': [2, 2, 3, 2],
+    ...                       'my_edge_key': ['A', 'B', 'C', 'D'],
+    ...                       'weight': [3, 4, 5, 6],
+    ...                       'color': ['red', 'blue', 'blue', 'blue']})
     >>> G = nx.from_pandas_edgelist(edges, \
-                                    edge_key='key', \
+                                    edge_key='my_edge_key', \
                                     edge_attr=['weight', 'color'], \
                                     create_using=nx.MultiGraph())
     >>> G[0][2]
-    AtlasView({'A': {'weight': 3, 'color': 'red'}})
+    AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}})
 
 
     """


Test patch:
Repository: networkx/networkx

Issue:
Executing other's people version.py when importing
When I import networkx inside my project it imports my local `version.py` (from `release.py` ).

For example, if I put in my root a `version.py` that looks like
```python
raise RuntimeError('ahhhh!!!')
```

I will get the following stack trace

```
Traceback (most recent call last):
  File "<censured>/venv/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-719b05231e1b>", line 1, in <module>
    import networkx
  File "<censured>/pycharm-2020.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "<censured>/venv/lib/python3.8/site-packages/networkx/__init__.py", line 19, in <module>
    from networkx import release
  File "/<censured>/pycharm-2020.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "<censured>/venv/lib/python3.8/site-packages/networkx/release.py", line 224, in <module>
    date, date_info, version, version_info, vcs_info = get_info()
  File "<censured>/venv/lib/python3.8/site-packages/networkx/release.py", line 151, in get_info
    from version import date, date_info, version, version_info, vcs_info
  File "<censured>/pycharm-2020.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "<censured>/git/storepick-dataset-creation/version.py", line 1, in <module>
    raise RuntimeError('ahhhh!!!')
RuntimeError: ahhhh!!!
```


Discussion:

Resolving patch:
diff --git a/networkx/release.py b/networkx/release.py
--- a/networkx/release.py
+++ b/networkx/release.py
@@ -148,7 +148,13 @@ def get_info(dynamic=True):
         # no vcs information will be provided.
         # sys.path.insert(0, basedir)
         try:
-            from version import date, date_info, version, version_info, vcs_info
+            from networkx.version import (
+                date,
+                date_info,
+                version,
+                version_info,
+                vcs_info,
+            )
         except ImportError:
             import_failed = True
             vcs_info = (None, (None, None))


Test patch:
Repository: networkx/networkx

Issue:
Use a utf8 friendly latex backend
The current sphinx configuration in docs/conf.py defaults to pdflatex. This is causing problems on #4169 which introduces API-level doctests with unicode characters in them. I tried several iterations of lualatex and xelatex to try and get it to work, but latex errors are never the most helpful.

I will open a PR to resolve this shortly. 


Discussion:

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -170,6 +170,8 @@
 # Options for LaTeX output
 # ------------------------
 
+# Use a latex engine that allows for unicode characters in docstrings
+latex_engine = "xelatex"
 # The paper size ('letter' or 'a4').
 latex_paper_size = "letter"
 


Test patch:
Repository: networkx/networkx

Issue:
Update plot_antigraph.py example to remove `_iter` in method name.
`def adjacency_iter(self)` should be `def adjacency(self)`
There may be other places (especially in the examples) where we've missed an ```_iter``` update.


Discussion:

Resolving patch:
diff --git a/examples/subclass/plot_antigraph.py b/examples/subclass/plot_antigraph.py
--- a/examples/subclass/plot_antigraph.py
+++ b/examples/subclass/plot_antigraph.py
@@ -137,7 +137,7 @@ def degree(self, nbunch=None, weight=None):
                 for n, nbrs in nodes_nbrs
             )
 
-    def adjacency_iter(self):
+    def adjacency(self):
         """Return an iterator of (node, adjacency set) tuples for all nodes
            in the dense graph.
 
@@ -149,10 +149,10 @@ def adjacency_iter(self):
         adj_iter : iterator
            An iterator of (node, adjacency set) for all nodes in
            the graph.
-
         """
-        for n in self.adj:
-            yield (n, set(self.adj) - set(self.adj[n]) - {n})
+        nodes = set(self.adj)
+        for n, nbrs in self.adj.items():
+            yield (n, nodes - set(nbrs) - {n})
 
 
 # Build several pairs of graphs, a regular graph


Test patch: