id stringlengths 30 32 | content stringlengths 139 2.8k |
|---|---|
codereview_new_python_data_5097 | def _analyse_name_as_type(name, pos, env):
if global_entry and global_entry.is_type:
type = global_entry.type
if (not env.in_c_type_context and
- name == 'int' and type == Builtin.int_type):
# While we still support Python2 this needs to be downgraded
# t... |
codereview_new_python_data_5098 | def py_version_hex(major, minor=0, micro=0, release_level=0, release_serial=0):
return (major << 24) | (minor << 16) | (micro << 8) | (release_level << 4) | (release_serial)
# there's a few places where it's useful to iterate over all of these
-used_macros_and_types = [
- ('__Pyx_CyFunction_USED', [cyfuncti... |
codereview_new_python_data_5099 | def __init__(self, stream=None):
def empty(self):
if self.stream.tell():
return False
- return all(child.empty() for child in self.prepended_children)
def getvalue(self):
content = []
I think we can avoid the overhead of a generator expression here.
```suggestion
... |
codereview_new_python_data_5100 | def __init__(self, stream=None):
def empty(self):
if self.stream.tell():
return False
- return all(child.empty() for child in self.prepended_children)
def getvalue(self):
content = []
You can declare this as a `cpdef` method in the pxd file.
def __init__(self, strea... |
codereview_new_python_data_5102 | def py_operation_function(self, code):
class PowNode(NumBinopNode):
# '**' operator.
- cpow = None
cpow_false_changed_result_type = False # was the result type affected by cpow==False
def _check_cpow(self, env):
```suggestion
is_cpow = None
```
def py_operation_function(self, code):
... |
codereview_new_python_data_5104 | def py_operation_function(self, code):
class PowNode(NumBinopNode):
# '**' operator.
- cpow = None
cpow_false_changed_result_type = False # was the result type affected by cpow==False
def _check_cpow(self, env):
Cautious proposal for clearer name - "soft complex" is IMO quite self-descriptive... |
codereview_new_python_data_5105 | class SoftCComplexType(CComplexType):
def __init__(self):
super(SoftCComplexType, self).__init__(c_double_type)
- def declaration_code(self, entity_code,
- for_display = 0, dll_linkage = None, pyrex = 0):
base_result = super(SoftCComplexType, self).declaration_code(
... |
codereview_new_python_data_5106 | def is_reversed_cpp_iteration(self):
This supports C++ classes with reverse_iterator implemented.
"""
- if not isinstance(self.sequence, SimpleCallNode):
return False
func = self.sequence.function
if func.is_name and func.name == "reversed":
```suggestion
... |
codereview_new_python_data_5107 | def is_reversed_cpp_iteration(self):
This supports C++ classes with reverse_iterator implemented.
"""
if not (isinstance(self.sequence, SimpleCallNode) and
- len(self.sequence.args) == 1):
return False
func = self.sequence.function
if func.is_na... |
codereview_new_python_data_5108 | def is_reversed_cpp_iteration(self):
This supports C++ classes with reverse_iterator implemented.
"""
if not (isinstance(self.sequence, SimpleCallNode) and
- self.sequence.args_tuple and len(self.sequence.args_tuple) == 1):
return False
func = self.seque... |
codereview_new_python_data_5109 | def is_reversed_cpp_iteration(self):
This supports C++ classes with reverse_iterator implemented.
"""
if not (isinstance(self.sequence, SimpleCallNode) and
- self.sequence.arg_tuple and len(self.sequence.arg_tuple) == 1):
return False
func = self.sequenc... |
codereview_new_python_data_5110 | def is_reversed_cpp_iteration(self):
This supports C++ classes with reverse_iterator implemented.
"""
- if not (isinstance(self.sequence, SimpleCallNode) and
self.sequence.arg_tuple and len(self.sequence.arg_tuple.args) == 1):
return False
func = self.... |
codereview_new_python_data_5112 |
# tag: openmp
from cython.parallel import parallel
-from cython.cimports.openmp import omp_set_dynamic
num_threads = cython.declare(cython.int)
omp_set_dynamic(1)
with cython.nogil, parallel():
- num_threads = openmp.omp_get_num_threads()
# ...
Presumably this needs to be part of ` from cython.cimp... |
codereview_new_python_data_5113 | def create_args_parser():
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
epilog="""Environment variables:
- CYTHON_FORCE_REGEN: if set to 1, forces cythonize to regenerate the output files regardless of modification times and changes.
- Environment variables accepted... |
codereview_new_python_data_5114 | def create_args_parser():
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
- epilog="""Environment variables:
CYTHON_FORCE_REGEN: if set to 1, forces cythonize to regenerate the output files regardless
of modification times and changes.
Environment variables a... |
codereview_new_python_data_5115 | def add(self, e):
def __bool__(self):
return bool(self._set)
-
# Class decorator that adds a metaclass and recreates the class with it.
# Copied from 'six'.
We still need `__nonzero__` in Py2.
```suggestion
def __bool__(self):
return bool(self._set)
__nonzero__ = __bo... |
codereview_new_python_data_5116 | def __bool__(self):
__nonzero__ = __bool__
# Class decorator that adds a metaclass and recreates the class with it.
# Copied from 'six'.
def add_metaclass(metaclass):
```suggestion
__nonzero__ = __bool__
```
def __bool__(self):
__nonzero__ = __bool__
+
# Class decorator... |
codereview_new_python_data_5117 | def build_hex_version(version_string):
def write_depfile(target, source, dependencies):
- src_base_dir, _ = os.path.split(source)
if not src_base_dir.endswith(os.sep):
src_base_dir += os.sep
# paths below the base_dir are relative, otherwise absolute
I'd also rename `mainfile` to `target_fi... |
codereview_new_python_data_5119 | def get_param(option):
sys.exit(1)
if len(sources) == 0 and not options.show_version:
bad_usage()
- if options.embed and len(sources) > 1:
sys.stderr.write(
"cython: Only one source file allowed when using --embed\n")
sys.exit(1)
```suggestion
if Options.e... |
codereview_new_python_data_5120 | def generate_result_code(self, code):
flags.append('CO_VARARGS')
if self.def_node.starstar_arg:
flags.append('CO_VARKEYWORDS')
- if self.def_node.is_generator and self.def_node.is_coroutine:
flags.append('CO_COROUTINE')
- if self.def_node.is_asyncgen:
-... |
codereview_new_python_data_5122 | def create_to_py_utility_code(self, env):
"module_name": module_name,
"is_flag": True,
},
- outer_module_scope=self.entry.scope # ensure that "name" is findable
))
return True
```suggestion
outer_module_scope=self.... |
codereview_new_python_data_5124 | def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ
base_type = type.base_type
while base_type:
- if type.base_type.is_external and not base_type.objstruct_cname == "PyTypeObject":
# 'type' is special-cased because it is actua... |
codereview_new_python_data_5125 | def generate_result_code(self, code):
res = self.result()
code.putln("%s = (PyObject *) *%s;" % (res, self.buffer_ptr_code))
# NumPy does (occasionally) allow NULL to denote None.
- code.putln("if (%s == NULL) %s = Py_None;" % (res, res))
code.putln("__Pyx... |
codereview_new_python_data_5126 | def p_namedexpr_test(s):
if s.sy == ':=':
position = s.position()
if not lhs.is_name:
- s.error("Left-hand side of assignment expression must be an identifier")
s.next()
rhs = p_test(s)
return ExprNodes.AssignmentExpressionNode(position, lhs=lhs, rhs=rhs)
W... |
codereview_new_python_data_5146 |
import lbann
import lbann.models
import lbann.modules as lm
-
class CosmoFlow(lm.Module):
"""The CosmoFlow neural network.
This file needs a numpy import: `import numpy as np`
import lbann
import lbann.models
import lbann.modules as lm
+import numpy as np
class CosmoFlow(lm.Module):
"""The Cos... |
codereview_new_python_data_5147 | def get_distconv_environment(parallel_io=False, num_io_partitions=1):
return {
'DISTCONV_WS_CAPACITY_FACTOR': 0.8,
-# 'DISTCONV_OVERLAP_HALO_EXCHANGE': 1,
'LBANN_DISTCONV_HALO_EXCHANGE': 'AL',
'LBANN_DISTCONV_TENSOR_SHUFFLER': 'AL',
-# 'LBANN_DISTCONV_HALO_EXCHANGE': 'HY... |
codereview_new_python_data_5149 | def prepend_environment_path(key, prefix):
#set_environment('NCCL_SOCKET_IFNAME', 'hsi')
set_environment('MIOPEN_DEBUG_DISABLE_FIND_DB', '1')
set_environment('MIOPEN_DISABLE_CACHE', '1')
- prepend_environment_path('LD_LIBRARY_PATH', '/opt/rocm-5.3.0/llvm/lib:' + os.getenv("CRAY_LD_LIB... |
codereview_new_python_data_5167 |
# TODO: make the path configurable
CONFIG_FILES = ["config.yaml", "config.yml"]
-def create():
settings = Dynaconf(
settings_files=CONFIG_FILES,
load_dotenv=True,
envvar_prefix="VAST",
)
settings.validators.register(
- Validator("console_verbosity", default="deb... |
codereview_new_python_data_5196 | async def run(self):
logger.warning(f"failed to parse MISP event as STIX: {e}")
continue
finally:
- logger.info(f"terminating MISP")
self.misp = None
socket.setsockopt(zmq.LINGER, 0)
socket.close()
It's terminating th... |
codereview_new_python_data_5197 |
import pyarrow as pa
-class IPAddressType(pa.PyExtensionType):
- def __init__(self):
- pa.PyExtensionType.__init__(self, pa.binary(16))
-
- def __reduce__(self):
- return IPAddressType, ()
-
- def __arrow_ext_scalar_class__(self):
- # TODO: we should probably write our own IP address... |
codereview_new_python_data_5198 |
import pyarrow as pa
-class IPAddressType(pa.PyExtensionType):
- def __init__(self):
- pa.PyExtensionType.__init__(self, pa.binary(16))
-
- def __reduce__(self):
- return IPAddressType, ()
-
- def __arrow_ext_scalar_class__(self):
- # TODO: we should probably write our own IP address... |
codereview_new_python_data_5238 | def request_item(request, locale=None):
template = get_template("teams/email_request_item.jinja")
mail_body = template.render(payload)
EmailMessage(
subject=mail_subject,
body=mail_body,
from_email=settings.LOCALE_REQUEST_FROM_EMAIL,
to=s... |
codereview_new_python_data_5239 | def request_item(request, locale=None):
template = get_template("teams/email_request_item.jinja")
mail_body = template.render(payload)
EmailMessage(
subject=mail_subject,
body=mail_body,
from_email=settings.LOCALE_REQUEST_FROM_EMAIL,
to=s... |
codereview_new_python_data_5240 | def request_item(request, locale=None):
template = get_template("teams/email_request_item.jinja")
mail_body = template.render(payload)
EmailMessage(
subject=mail_subject,
body=mail_body,
from_email=settings.LOCALE_REQUEST_FROM_EMAIL,
to=s... |
codereview_new_python_data_5241 | def request_item(request, locale=None):
body=mail_body,
from_email=settings.LOCALE_REQUEST_FROM_EMAIL,
to=settings.PROJECT_MANAGERS,
- cc=cc,
reply_to=[user.contact_email()],
).send()
else:
Have you removed this check intentionally? I think ... |
codereview_new_python_data_5242 |
def remove_changed_entity_locale_entries_for_repository_projects(apps, schema_editor):
- projects = Project.objects.filter(data_source=Project.DataSource.DATABASE)
- resources = Resource.objects.filter(project__in=projects)
- entities = Entity.objects.filter(resource__in=resources)
- ChangedEntityLoca... |
codereview_new_python_data_5243 | class Migration(migrations.Migration):
operations = [
migrations.RunPython(
code=remove_changed_entity_locale_entries_for_repository_projects,
),
]
Sorry just realized that we must add the `reverse_code` here - [noop](https://docs.djangoproject.com/en/4.1/ref/migration-operati... |
codereview_new_python_data_5244 | class Direction(models.TextChoices):
default=0,
help_text="""
Number of native speakers. Find locale code in CLDR territoryInfo.json:
- https://github.com/unicode-org/cldr-json/blob/main/cldr-json/cldr-core/supplemental/territoryInfo.json
and multiply its "_populationPercent... |
codereview_new_python_data_5245 |
from apscheduler.schedulers.blocking import BlockingScheduler
-# Read dotenv file and inject it's values into the environment
dotenv.load_dotenv(dotenv_path=os.environ.get("DOTENV_PATH"))
# Set the default Django settings module
```suggestion
# Read dotenv file and inject its values into the environment
``... |
codereview_new_python_data_5246 | def mark_system_users(apps, schema_editor):
def revert_mark_system_users(apps, schema_editor):
UserProfile = apps.get_model("base", "UserProfile")
UserProfile.objects.filter(user__email__in=system_user_emails).update(
- system_user=None
)
`None` -> `False` (which is the default value, set b... |
codereview_new_python_data_5247 | def users_with_translations_counts(
# Assign properties to user objects.
contributors = User.objects.filter(pk__in=user_stats.keys())
- # Exclude system users
- contributors = contributors.exclude(profile__system_user=True)
# Exclude deleted users.
contributors = contributors.filter(is_ac... |
codereview_new_python_data_5248 | def get_google_automl_translation(text, locale):
"message": f"{e}",
}
- project_id = "85591518533"
model_id = locale.google_automl_model
location = "us-central1"
parent = f"projects/{project_id}/locations/{location}"
This magic constant should probably be a well commented con... |
codereview_new_python_data_5249 | def get_google_automl_translation(text, locale):
"message": f"{e}",
}
- project_id = "85591518533"
model_id = locale.google_automl_model
location = "us-central1"
parent = f"projects/{project_id}/locations/{location}"
This also looks like a magic constant. At the very least it... |
codereview_new_python_data_5250 | def get_contributions(user, contribution_type=None):
total = sum(contributions.values())
return {
"contributions": json.dumps(contributions),
"title": f"{ intcomma(total) } contribution{ pluralize(total) } in the last year",
}
Why does this need to get double-encoded like this? If t... |
codereview_new_python_data_5251 | class Migration(migrations.Migration):
]
operations = [
- migrations.RemoveField(
model_name="userprofile",
- name="matrix",
- ),
- migrations.AddField(
- model_name="userprofile",
- name="chat",
- field=models.CharField(
- ... |
codereview_new_python_data_5254 | def main(args):
if (conf.commands.reboot == 'when-changed' or
(conf.commands.reboot == 'when-needed' and base.reboot_needed())):
- if os.waitstatus_to_exitcode(os.system(conf.commands.reboot_command)) != 0:
return 1
except dnf.exceptions.Error as ... |
codereview_new_python_data_5255 | def format_line(group):
lines.append(format_line(group))
pkglist_lines.append((action, lines))
# show skipped conflicting packages
- if not self.conf.best and self.base._goal.actions & forward_actions:
lines = []
skipped_conflicts, skipped... |
codereview_new_python_data_5381 | def port(self) -> int:
@port.setter
def port(self, port: int) -> None:
- self.data.port = port
self._update_host_and_authority()
def _update_host_and_authority(self) -> None:
- val = url.hostport(
- self.scheme,
- self.host,
- # test_http.py::T... |
codereview_new_python_data_5382 | def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:
# Implementations MUST ignore and discard any frame that has a type that is unknown.
yield Log(f"Ignoring unknown HTTP/2 frame type: {event.frame.type}")
elif isinstance(event, h2.events.AlternativeServiceAv... |
codereview_new_python_data_5383 | def get(self):
try:
match = flowfilter.parse(self.request.arguments["filter"][0].decode())
- except (KeyError, IndexError, ValueError): # Key+Index: ["filter"][0], Value: parsing problem
match = bool # returns always true
with BytesIO() as bio:
We should return... |
codereview_new_python_data_5384 | def _next_layer(
# handle QUIC connections
first_layer = context.layers[0]
if isinstance(first_layer, quic.QuicLayer):
- if context.client.alpn is None:
- return None # should never happen, as ask is called after handshake
if context.client.alpn == b"h... |
codereview_new_python_data_5385 | def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:
assert isinstance(spec, ReverseMode)
self.context.server.address = spec.address
- if (
- spec.scheme == "https" or spec.scheme == "http3"
- or spec.scheme == "quic" or spec.scheme == "tls" or ... |
codereview_new_python_data_5386 | def load(self, loader):
None,
"""Set the local IP address that mitmproxy should use when connecting to upstream servers.""",
)
- loader.add_option(
- "quic_connection_id_length",
- int,
- 8,
- """The length in bytes of local QUIC con... |
codereview_new_python_data_5387 | def test_parse_specific_modes():
assert ProxyMode.parse("socks5")
assert ProxyMode.parse("dns").resolve_local
assert ProxyMode.parse("dns:reverse:8.8.8.8")
- assert ProxyMode.parse("dtls:reverse:127.0.0.1:0")
with pytest.raises(ValueError, match="invalid port"):
ProxyMode.parse("regul... |
codereview_new_python_data_5630 |
"""Text formatting utilities."""
import io
import re
from functools import partial
```suggestion
"""Text formatting utilities."""
from __future__ import annotations
```
"""Text formatting utilities."""
+from __future__ import annotations
import io
import re
from functools import partial |
codereview_new_python_data_5631 | def _stamp_headers(self, visitor_headers=None, **headers):
else:
headers["stamped_headers"] = stamped_headers
for stamp in headers.keys():
- if stamp != "stamped_headers" and stamp not in headers["stamped_headers"]:
headers["stamped_headers... |
codereview_new_python_data_5632 | def _stamp_headers(self, visitor_headers=None, **headers):
else:
headers["stamped_headers"] = stamped_headers
for stamp in headers.keys():
- if stamp != "stamped_headers" and stamp not in headers["stamped_headers"]:
headers["stamped_headers... |
codereview_new_python_data_5633 | def on_replace(self, sig):
assert headers['header'] == 'value'
@pytest.mark.parametrize('sig_to_replace', [
group(signature('sig1'), signature('sig2')),
chain(signature('sig1'), signature('sig2')),
])
```suggestion
group(signature(f'sig{i}') for i in range(2)),
... |
codereview_new_python_data_5634 | def replace(self, sig):
sig.options['stamped_headers'] = stamped_headers
sig.options.update(stamps)
links = sig.options['link'] if 'link' in sig.options else []
links.extend(sig.options['link_error'] if 'link_error' in sig.options else [])
We should probably add... |
codereview_new_python_data_5635 | def prepare_steps(self, args, kwargs, tasks,
chain(group(signature1, signature2), signature3) --> Upgrades to chord([signature1, signature2], signature3)
The responsibility of this method is to assure that the chain is
- correctly unpacked, and that the correct callbacks are set up along the... |
codereview_new_python_data_5636 | def test_disabling_flag_allow_error_cb_on_chord_header(self, manager, subtests):
# Double check
assert not redis_connection.exists(body_key), 'Chord body was called when it should have not'
- with subtests.test(msg='Confirm there only one errback was called'):
... |
codereview_new_python_data_5637 |
MHcCAQEEIOj98rAhc4ToQkHby+Iegvhm3UBx+3TwpfNza+2Vn8d7oAoGCCqGSM49
AwEHoUQDQgAEhlUYUzS49td6FPnmzbKrdl3u0K83oYwakTb4pJmpO0M/lzvHbdC8
FgXqr9Pwws1YJIFPFoRGm+3xcv6Sw5ny9A==
------END EC PRIVATE KEY-----"""
\ No newline at end of file
```suggestion
-----END EC PRIVATE KEY-----"""
```
MHcCAQEEIOj98rAhc4ToQkHby+Iegv... |
codereview_new_python_data_5638 | def __init__(self, url=None, open=open, unlink=os.unlink, sep=os.sep,
def __reduce__(self, args=(), kwargs=None):
kwargs = {} if not kwargs else kwargs
- return super().__reduce__(args, dict(kwargs, url=self.url))
def _find_path(self, url):
if not url:
```suggestion
ret... |
codereview_new_python_data_5639 | def test_spectral_bisection():
pytest.importorskip("scipy")
G = nx.barbell_graph(3, 0)
C = nx.spectral_bisection(G)
- assert C == [{0, 1, 2}, {3, 4, 5}]
mapping = dict(enumerate("badfec"))
G = nx.relabel_nodes(G, mapping)
C = nx.spectral_bisection(G)
- assert C == [
{mapp... |
codereview_new_python_data_5640 | def spectral_bisection(
import numpy as np
v = nx.fiedler_vector(G, weight=weight)
- node_list = list(G)
- x, y = np.where(v < 0)[0], np.where(v >= 0)[0]
-
- return [
- {node_list[i] for i in x},
- {node_list[i] for i in y},
- ]
Maybe:
```suggestion
nodes = np.array(list(... |
codereview_new_python_data_5641 | def chordal_cycle_graph(p, create_using=None):
def paley_graph(p, create_using=None):
- """Returns the Paley $\\frac{(p-1)}{2}-$regular graph on $p$ nodes.
The returned graph is a graph on $ \\mathbb{Z}/p\\mathbb{Z}$ with edges between $x$ and $y$
if and only if $x-y$ is a nonzero square in $\\math... |
codereview_new_python_data_5642 | def to_latex_raw(
if not isinstance(pos, dict):
pos = nx.get_node_attributes(G, pos)
if not pos:
- # circular layout with radius 1
- pos = {n: f"({round(360.0 * i / len(G), 3)}:10)" for i, n in enumerate(G)}
for node in G:
if node not in pos:
raise nx.Network... |
codereview_new_python_data_5643 | def _dict_product(d1, d2):
return {k: (d1.get(k), d2.get(k)) for k in set(d1) | set(d2)}
-# Generators for producing graph products
def _node_product(G, H):
for u, v in product(G, H):
yield ((u, v), _dict_product(G.nodes[u], H.nodes[v]))
Maybe this isn't a typo. We are indeed "producting" grap... |
codereview_new_python_data_5644 | def could_be_isomorphic(G1, G2):
-----
Checks for matching degree, triangle, and number of cliques sequences.
The triangle sequence contains the number of triangles each node is part of.
- The clique sequence contains for each node the size of the maximal clique
involving that node.
"""
... |
codereview_new_python_data_5645 | def barbell_graph(m1, m2, create_using=None):
Notes
-----
- For $m1 > 2$ and $m2 >= 0$.
Two identical complete graphs $K_{m1}$ form the left and right bells,
and are connected by a path $P_{m2}$.
```suggestion
```
I think we can remove this bit, the information is captured in the Paramete... |
codereview_new_python_data_5646 | def _empty_generator():
def _all_simple_paths_graph(G, source, targets, cutoff):
- visited = dict.fromkeys([source], True)
stack = [iter(G[source])]
while stack:
children = stack[-1]
Would this be more readable?
```suggestion
visited = {source: True}
```
def _empty_generator():
... |
codereview_new_python_data_5647 | def is_simple_path(G, nodes):
False
"""
- assert isinstance(nodes, list), "Object passed as `nodes` must be a list."
-
- # The empty list is not a valid path. Could also return
- # NetworkXPointlessConcept here.
- if not nodes:
- return False
-
# check that all nodes in the list are... |
codereview_new_python_data_5648 | def is_simple_path(G, nodes):
False
"""
- assert isinstance(nodes, list), "Object passed as `nodes` must be a list."
-
- # The empty list is not a valid path. Could also return
- # NetworkXPointlessConcept here.
- if not nodes:
- return False
-
# check that all nodes in the list are... |
codereview_new_python_data_5649 | def draw_networkx_edges(
alpha : float or array of floats (default=None)
The edge transparency. This can be a single alpha value,
- in which case it will be applied to all the nodes of color. Otherwise,
if it is an array, the elements of alpha will be applied to the colors
in ... |
codereview_new_python_data_5650 | def test_dls_labeled_edges_depth_1(self):
edges = list(nx.dfs_labeled_edges(self.G, source=5, depth_limit=1))
forward = [(u, v) for (u, v, d) in edges if d == "forward"]
assert forward == [(5, 5), (5, 4), (5, 6)]
- # Note: reverse-depth_limit edge types were not reported before gh-623... |
codereview_new_python_data_5651 | def test_empty_numpy(self):
nx.eigenvector_centrality_numpy(nx.Graph())
def test_zero_nstart(self):
- G = nx.Graph()
- G.add_nodes_from([1, 2, 3])
- G.add_edges_from([(1, 2), (1, 3), (2, 3)])
- with pytest.raises(nx.NetworkXException):
nx.eigenvector_central... |
codereview_new_python_data_5652 | def test_path_projected_graph(self):
P = bipartite.projected_graph(G, [0, 2])
assert nodes_equal(list(P), [0, 2])
assert edges_equal(list(P.edges()), [(0, 2)])
- with pytest.raises(nx.NetworkXError):
- G = nx.MultiGraph()
- G.add_edge(0, 1)
bipartite... |
codereview_new_python_data_5653 | def test_path_weighted_projected_graph(self):
def test_digraph_conversion(self):
G = nx.DiGraph()
- edges = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 4, 2)]
- G.add_weighted_edges_from(edges)
P = bipartite.overlap_weighted_projected_graph(G, [1, 3])
assert nx.get_edge_attrib... |
codereview_new_python_data_5654 | def test_path_weighted_projected_graph(self):
assert edges_equal(list(P.edges()), [(0, 2)])
P[0][2]["weight"] = 1
- def test_digraph_conversion(self):
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4)])
P = bipartite.overlap_weighted_projected_graph(G, [1, 3])
assert nx.g... |
codereview_new_python_data_5655 | def test_is_frozen(self):
assert G.frozen
def test_node_attributes_are_still_mutable_on_frozen_graph(self):
- G = nx.freeze(self.G)
node = G.nodes[0]
node["node_attribute"] = True
assert node["node_attribute"] == True
def test_edge_attributes_are_still_mutable_o... |
codereview_new_python_data_5656 | def dispersion(G, u=None, v=None, normalized=True, alpha=1.0, b=0.0, c=0.0):
normalized : bool
If True (default) normalize by the embededness of the nodes (u and v).
alpha, b, c : float
- If normalized is True (default), try out different values of alpha, b and, c to obtain maximum
- p... |
codereview_new_python_data_5657 | def test_edge_cases_directed_edge_swap():
graph = nx.path_graph(4, create_using=nx.DiGraph)
with pytest.raises(nx.NetworkXAlgorithmError):
nx.directed_edge_swap(graph, nswap=4, max_tries=10, seed=1)
- graph = nx.DiGraph()
- edges = [(0, 0), (0, 1), (1, 0), (2, 3), (3, 2)]
- graph.add_edges_... |
codereview_new_python_data_5658 | def test_directed_edge_swap():
def test_edge_cases_directed_edge_swap():
e = (
- f"Maximum number of swap attempts \\(11\\) exceeded "
- f"before desired swaps achieved \\(4\\)."
)
- graph = nx.path_graph(4, create_using=nx.DiGraph)
with pytest.raises(nx.NetworkXAlgorithmError, mat... |
codereview_new_python_data_5659 | def test_directed_edge_swap():
def test_edge_cases_directed_edge_swap():
e = (
- f"Maximum number of swap attempts \\(11\\) exceeded "
- f"before desired swaps achieved \\(4\\)."
)
- graph = nx.path_graph(4, create_using=nx.DiGraph)
with pytest.raises(nx.NetworkXAlgorithmError, mat... |
codereview_new_python_data_5660 | def laplacian_spectrum(G, weight="weight"):
Examples
--------
- The multiplicity of O as an eigenvalue of the laplacian matrix is equal
to the number of connected components of G.
>>> import numpy as np
IMO it'd make the example more clear if the reader knew what the graph was (I doubt many... |
codereview_new_python_data_5661 | def laplacian_matrix(G, nodelist=None, weight="weight"):
to a block diagonal matrix where each block is the respective Laplacian
matrix for each component.
- >>> G = nx.graph_atlas(26) #This graph from the Graph Atlas has 2 connected components.
- >>> print(nx.laplacian_matrix(G).todense())
- [[ 1... |
codereview_new_python_data_5662 | def fiedler_vector(
Given a connected graph the signs of the values in the Fiedler vector can be
used to partition the graph into two components.
- >>> G = nx.cycle_graph(4)
- >>> print(nx.fiedler_vector(G, normalized=True, seed = 1))
- [-0.69141345 -0.1481467 0.69141344 0.14814671]
-
- The ... |
codereview_new_python_data_5663 | def algebraic_connectivity(
Examples
--------
For undirected graphs algebraic connectivity can tell us if a graph is connected or not
- G is connected iff :math: `algebraic\_connectivity(G)>0`
>>> #if G is a complete grpah then G is connected
>>> G = nx.complete_graph(5)
Just a nit here... |
codereview_new_python_data_5664 | def test_omega():
for o in omegas:
assert -1 <= o <= 1
-
-def test_graph_no_edges():
G = nx.Graph()
G.add_nodes_from([0, 1, 2, 3])
- pytest.raises(nx.NetworkXError, nx.random_reference, G)
- pytest.raises(nx.NetworkXError, nx.lattice_reference, G)
Test looks good, just a few minor sugg... |
codereview_new_python_data_5665 | def double_edge_swap(G, nswap=1, max_tries=100, seed=None):
------
NetworkXError
If `G` is directed, or
- If nswap > max_tries, or
If there are fewer than 4 nodes or 2 edges in `G`.
NetworkXAlgorithmError
If the number of swap attempts exceeds `max_tries` before `nswap`... |
codereview_new_python_data_5666 | def test_degree_seq_c4():
assert degrees == sorted(d for n, d in G.degree())
-def test_no_edges():
G = nx.DiGraph()
G.add_nodes_from([0, 1, 2])
- pytest.raises(nx.NetworkXError, nx.directed_edge_swap, G)
- G = nx.Graph()
- G.add_nodes_from([0, 1, 2, 3])
- pytest.raises(nx.NetworkXError, ... |
codereview_new_python_data_5667 | def eulerian_path(G, source=None, keys=False):
def eulerize(G):
"""Transforms a graph into an Eulerian graph.
- If `G` is Eulerian the result is `G`, otherwise the result is a smallest
(in terms of the number of edges) multigraph whose underlying simple graph is `G`.
Parameters
Should this perh... |
codereview_new_python_data_5668 | def test_find_cliques_trivial(self):
assert sorted(nx.find_cliques(G)) == []
assert sorted(nx.find_cliques_recursive(G)) == []
- def test_make_max_clique_graph_2(self):
- "Test the create_using parameter"
G = nx.Graph()
G.add_edges_from([(1, 2), (3, 1), (4, 1), (5, 6)])
... |
codereview_new_python_data_5669 | def test_find_cliques_trivial(self):
assert sorted(nx.find_cliques(G)) == []
assert sorted(nx.find_cliques_recursive(G)) == []
- def test_make_max_clique_graph_2(self):
- "Test the create_using parameter"
G = nx.Graph()
G.add_edges_from([(1, 2), (3, 1), (4, 1), (5, 6)])
... |
codereview_new_python_data_5670 | def test_find_cliques_trivial(self):
assert sorted(nx.find_cliques(G)) == []
assert sorted(nx.find_cliques_recursive(G)) == []
- def test_make_max_clique_graph_2(self):
- "Test the create_using parameter"
G = nx.Graph()
G.add_edges_from([(1, 2), (3, 1), (4, 1), (5, 6)])
... |
codereview_new_python_data_5671 | def all_pairs_node_connectivity(G, nbunch=None, cutoff=None):
Examples
--------
- >>> # A 3 node cycle with one extra node attached has connectivity 2 between all
- >>> # nodes in the cycle and connectivity 1 between the extra node and the rest
>>> G = nx.cycle_graph(3)
>>> G.add_edge(2, 3)... |
codereview_new_python_data_5672 | def test_bidirectional_shortest_path(self):
@pytest.mark.parametrize(
("src", "tgt"),
(
- (8, 3),
- (3, 8),
- (8, 10),
- (8, 8),
),
)
def test_bidirectional_shortest_path_src_tgt_not_in_graph(self, src, tgt):
```suggestion
... |
codereview_new_python_data_5673 |
G = nx.path_graph(20) # An example graph
center_node = 5 # Or any other node to be in the center
edge_nodes = set(G) - {center_node}
-pos = nx.circular_layout(
- G.subgraph(edge_nodes)
-) # Ensures the nodes around the circle are evenly distributed
pos[center_node] = np.array([0, 0]) # Or off-center - whate... |
codereview_new_python_data_5674 | def test_add_edge(self):
assert G.adj == {0: {1: {0: {}}}, 1: {0: {0: {}}}}
G = self.Graph()
with pytest.raises(ValueError):
- G.add_edges(None, "anything")
def test_add_edge_conflicting_key(self):
G = self.Graph()
There is a typo here, it should be `add_edge` not... |
codereview_new_python_data_5675 |
preflow_push,
shortest_augmenting_path,
)
-
-flow_funcs_without_cutoff = {
- preflow_push,
-}
flow_funcs = {
boykov_kolmogorov,
can this be imported from `maxflow.py` so that there is a single source of truth?
preflow_push,
shortest_augmenting_path,
)
+from networkx.algorithms.flow.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.