id stringlengths 24 28 | content stringlengths 121 2.08k |
|---|---|
codereview_python_data_5106 | ordering = ['-date_created']
def __str__(self):
- return '{order} has changed status from {old_status} to {new_status}'.format(
order=self.order, old_status=self.old_status, new_status=self.new_status
)
This string needs to be translated.
ordering = ['-date_created'... |
codereview_python_data_5107 | # Copyright 2006-2016 by Peter Cock. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
Should you add revisions 2021 copyright you?
# Copyright 2006-2016 by Peter Cock. All rights reserved.
... |
codereview_python_data_5113 | def test_modularity_communities_weighted():
G = nx.balanced_tree(2, 3)
for (a, b) in G.edges:
- if ((a == 1) | (a == 2)) & (b != 0):
G[a][b]["weight"] = 10.0
else:
G[a][b]["weight"] = 1.0
Just a nit, but I think logical operators should be used here instead of bitwi... |
codereview_python_data_5127 | if server_extensions:
server_extensions[0].finalize(handshake_flow.response.headers['Sec-WebSocket-Extensions'])
- request = Request(extensions = client_extensions, host = handshake_flow.request.host, target = handshake_flow.request.path)
data = self.connections[self.server_conn].s... |
codereview_python_data_5130 | product_detail_page = self.get(self.product.get_absolute_url())
self.assertContains(product_detail_page, 'Add to wish list')
def test_wishlists_disabled(self):
- self.installed_apps_setting.remove('oscar.apps.wishlists.apps.WishlistsConfig')
- with self.settings(INSTALLED_APPS=self.... |
codereview_python_data_5139 | from tensorflow_addons.image.distort_image_ops import adjust_hsv_in_yiq
from tensorflow_addons.image.distort_image_ops import random_hsv_in_yiq
-from tensorflow_addons.image.transform_ops import transform, rotate
Imports should usually be on separate lines :-)
from tensorflow_addons.image.distort_image_ops import ... |
codereview_python_data_5142 | ['gcloud', 'deployment-manager', 'deployments', 'describe',
deployment_name, '--format=json'])
- deployment_err_msg = 'Error occurred during the deployment, exiting...'
-
if return_code:
print(err)
- print(deployment_err_msg)
sys.exit(1)
deployment_info = json.lo... |
codereview_python_data_5143 | with warnings.catch_warnings():
# e.g. BiopythonParserWarning: Dropping bond qualifier in feature
# location
warnings.simplefilter("ignore", BiopythonParserWarning)
# e.g. WARNING: Chain C is discontinuous at line 2645
warnings.simplefilter("ignore", PDBConstructionWarn... |
codereview_python_data_5145 | pos_weight=-1,
smoothl1_beta=1 / 9.0,
debug=False),
rcnn=dict(
assigner=dict(
type='MaxIoUAssigner',
`TensorboardLoggerHook` may not be used by default.
pos_weight=-1,
smoothl1_beta=1 / 9.0,
debug=False),
+ rpn_proposal=dict(
+ ... |
codereview_python_data_5146 | file_that_does_not_exist_in_fs = "some/random/file"
for file in [file_that_exists_in_fs, file_that_does_not_exist_in_fs]:
- with patch("azurelinuxagent.common.osutil.factory.UBUNTU_20_04_IMAGE_PATH", file):
with patch.object(ExtHandlerInstance, "load_manifest", return_value... |
codereview_python_data_5147 | log.init.debug("Initializing cookies...")
cookies.init(q_app)
- log.init.debug("Initializing websettings...")
- websettings.init(args)
- quitter.instance.shutting_down.connect(websettings.shutdown)
-
log.init.debug("Initializing cache...")
cache.init(q_app)
Can you elaborate why you moved ... |
codereview_python_data_5148 | # Fuchsia specific.
r'^CrashTrampolineAsm',
- r'^libc_io_functions_not_implemented_use_fdio_instead',
- r'^\<libclang_rt.asan.so\>',
- r'^__zx_panic',
r'^syslog\:\:LogMessage',
]
nit: for python 2, _ needs to be escaped in all these entries.
# Fuchsia specific.
r'^CrashTrampolineAsm... |
codereview_python_data_5154 | from say import say
-# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0
-
class SayTest(unittest.TestCase):
def test_zero(self):
Please remove this blank line.
from say import say
+# Tests adapted from `problem-specifications//canonical-data.json` @ v1.2.0
class SayTest(unittest.Test... |
codereview_python_data_5158 | @command('wp')
async def payto(self, destination, amount, fee=None, feerate=None, from_addr=None, from_coins=None, change_addr=None,
- nocheck=False, unsigned=False, rbf=None, password=None, locktime=None, addtransaction=True, wallet: Abstract_Wallet = None):
"""Create a transactio... |
codereview_python_data_5161 | (u'negative_probability', u'subnormal_probability')
)
- def __init__(self, allow_nan=True):
super(FullRangeFloats, self).__init__()
self.allow_nan = allow_nan
def draw_parameter(self, random):
return self.Parameter(
It took me a moment to figure out why there wasn't a s... |
codereview_python_data_5163 | try:
tar.extract(member)
except TarError as err:
- current_app.logger.error("{} while extracting {}, aborting import".format(
- type(err).__name__, member.name), exc_info=True)
# Cleanup
... |
codereview_python_data_5168 | - email Set the Entrez email parameter (default is not set).
- tool Set the Entrez tool parameter (default is ``biopython``).
- api_key Personal API key from NCBI. If not set, only 3 queries per
- second are allowed. 10 queries per seconds otherwise with a
- ... |
codereview_python_data_5175 | continue
if key == "molecule_type":
# EMBL allows e.g. "genomics DNA" where GenBank is limited.
- common_words = set(old.annotations[key].split()).intersection(
- new.annotations[key].split()
- )
if not common_words:
r... |
codereview_python_data_5184 | if stats is None:
return '', 204
- if count is None:
- count = DEFAULT_ITEMS_PER_GET
count = min(count, MAX_ITEMS_PER_GET)
count = count + offset
artist_list = stats['artist']['all_time']['artists'][offset:count]
instead of doing this check here, we could just do `count = _get_no... |
codereview_python_data_5186 | ;
""") # noqa : W291
- @staticmethod
- def test_write_alignment():
# Default causes no interleave (columns <= 1000)
records = [SeqRecord(Seq("ATGCTGCTGA" * 90, alphabet=ambiguous_dna), id=_id) for _id in ["foo", "bar", "baz"]]
a = MultipleSeqAlignment(records, alphabet=ambiguous_dna)... |
codereview_python_data_5190 | import pkg_resources
from PyQt5.QtCore import QUrlQuery, QUrl
import qutebrowser
from qutebrowser.config import config, configdata, configexc, configdiff
from qutebrowser.utils import (version, utils, jinja, log, message, docutils,
objreg, urlutils)
from qutebrowser.misc import obj... |
codereview_python_data_5200 | "if you use dict, the index should start from 0")
if eval_at is not None:
- self.eval_at = eval_at
super(LGBMRanker, self).fit(X, y, sample_weight=sample_weight,
init_score=init_score, group=group,
... |
codereview_python_data_5206 | high_pokemon['iv']), 'green')
if keep_for_evo and len(group) > 0:
if candies == {}:
logger.log("Api call for candies failed, try again")
Pokemon with 2 evolutions always use candy of th... |
codereview_python_data_5208 | and_(SuppressBug.run_id == action.run_id,
SuppressBug.hash == bug_hash,
SuppressBug.type == bug_hash_type,
- SuppressBug.file_name == ''))) \
... |
codereview_python_data_5219 | from libcodechecker.logger import LoggerFactory
LOG = LoggerFactory.get_new_logger('ANALYZE')
-CTU_FUNC_MAP_CMD = 'clang-func-mapping'
class OrderedCheckersAction(argparse.Action):
This default variable should be moved into a config variable, created by `package_context`, and read from `config\package_layout.json`.... |
codereview_python_data_5227 | try:
with timescale.engine.connect() as connection:
result = connection.execute(sqlalchemy.text("SELECT SUM(count) FROM listen_count"))
- count = result.fetchone()["sum"] or 0
except psycopg2.OperationalError as e:
self.log.error("Cannot query... |
codereview_python_data_5228 | return_counts=True,
return_inverse=True,
)
- out[:] = where(
- group_labels != null_label,
- counts[inverse],
- self.missing_value,
- )
# Convenience aliases
I think slightly more efficient here would be: ```python np.copyto(out, counts... |
codereview_python_data_5243 | :param bucket_name: The name of the bucket that receives the posted object.
:param object_key: The object key to identify the uploaded object.
- :param expires_in: The number of seconds the presigned POST is valid for.
:return: A dictionary that contains the URL and form fields that contain
... |
codereview_python_data_5248 | self._scheduler.add_worker(self._id, {'workers': self.worker_processes})
@rpc_message_callback
- def dispatch_scheduler_message(self, task_id, message):
if not self._config.receive_messages:
return
add `, **kwargs):` so that we can add more things in the future (without breaking ... |
codereview_python_data_5253 | import sys
import getopt
import distutils
from distutils import dir_util
from distutils import file_util
from setuptools import find_packages, setup
if __name__ == "__main__":
if (8 * struct.calcsize("P")) != 64:
raise Exception('Cannot install LightGBM in 32-bit python, please use 64-bit python in... |
codereview_python_data_5254 | else:
return exec_command(logfile)
finally:
- logfile.close()
def _send_logs(self):
msg = None
I'm debating if we need to log it directly to the log file or pass it as a parameter to our logger to make sure we capture the other metadata too (datetime, thread name... |
codereview_python_data_5262 | line[24:33], line[33:40],
line[40:47], line[47:54]]
except ValueError:
- warnings.warn("Failed to read CRYST entry, got:\n{}"
"".format(line))
# check... |
codereview_python_data_5266 | bootstrap = Flag(
doc="Debug server catalog bootstrap.")
- cache_yolo = Flag(
- doc="Disable consistency check.")
edgeql_parser = Flag(
doc="Debug EdgeQL parser (rebuild grammar verbosly).")
perhaps `bootstrap_cache_yolo` or do you mean for this to apply to all cache everywhere?
... |
codereview_python_data_5272 | """
)
general.add_argument(
- "--can-handle-url-nohead",
metavar="URL",
help="""
- Same as --can-handle-url but without HTTP operations involved.
"""
)
general.add_argument(
Maybe `Same as --can-handle-url but without following redirects when looking up the URL` is more clear about the in... |
codereview_python_data_5276 | num_nodes=(num_nodes_dict[srctype], num_nodes_dict[dsttype]),
validate=False, index_dtype=index_dtype))
- return hetero_from_relations(rel_graphs, num_nodes_dict,
- index_dtype=index_dtype)
def to_hetero(G, ntypes, etypes, ntype_field=NTYPE, etype_fi... |
codereview_python_data_5279 | import torch as th
from ...dist_tensor import DistTensor
-from ...sparse_emb import NodeEmbedding
from .utils import alltoallv_cpu, alltoall_cpu
class DistSparseGradOptimizer(abc.ABC):
this is synchronized update. we should keep the async update so that we can make a comparison between them.
import torch as th
... |
codereview_python_data_5281 | box=self.u.dimensions)
# Maybe exclude same molecule distances
if self._exclusion_block is not None:
- idxA = pairs[:, 0]//self._exclusion_block[0],
idxB = pairs[:, 1]//self._exclusion_block[1]
mask = np.where(idxA !... |
codereview_python_data_5284 | if number == 1:
return "1 bottle"
else:
- return f"{number} bottles"
def _next_verse(current_verse):
```suggestion return f'{number} bottles' ```
if number == 1:
return "1 bottle"
else:
+ return f'{number} bottles'
def _next_verse(current_verse): |
codereview_python_data_5291 | return False
def get_status(self, bigchain):
- concluded = self.get_election(self.id, bigchain)
- if concluded:
return self.CONCLUDED
return self.INCONCLUSIVE if self.has_validator_set_changed(bigchain) else self.ONGOING
Why is this approach preferable over checking th... |
codereview_python_data_5296 | """Set up the async update subprocess.
"""
self.async_q = Queue(1)
- self.async_p = mp.Process(target=async_update, args=(None, self, self.async_q))
self.async_p.start()
def finish_async_update(self):
looks like this piece of code is replicated?
"""Set up the a... |
codereview_python_data_5298 | from mmcv import Config, DictAction
from mmdet.core.evaluation import eval_map
-from mmdet.core.mask.structures import (BitmapMasks, PolygonMasks,
- polygon_to_bitmap)
from mmdet.core.visualization.image import imshow_det_bboxes
from mmdet.datasets import build_dataset, retrie... |
codereview_python_data_5305 | with open(path) as f:
return _sanitize_markdown(f.read())
except Exception as err:
- raise RuntimeError(f'Makrdown file "{path}" could not be loaded: {err}')
def _load_skill(path, course):
hmm, in this case perhaps the whole try-except could be removed altogether? because if the file... |
codereview_python_data_5313 | def check_operator_multipaste(bs, pastes, in_size, out_size, even_paste_count, no_intersections, full_input, in_anchor_top_left,
- out_anchor_top_left, out_dtype, use_gpu):
pipe, in_idx_l, in_anchors_l, shapes_l, out_anchors_l = get_pipeline(
batch_size=bs,
in_size=i... |
codereview_python_data_5314 | if type(axes) is list:
axes = tuple(axes)
if mean is None:
mean = x.mean(axis = axes, keepdims = True)
if stddev is None:
- factor = np.prod([x.shape[a] for a in axes]) - ddof if axes else x.size - ddof
sqr = (x - mean).astype(np.float)**2
var = np.sum(sqr, axis... |
codereview_python_data_5317 | continue
if not crash_analyzer.is_memory_tool_crash(result.output):
- # Didn't crash or time out.
continue
# Get memory tool crash information.
Remove "time out"
continue
if not crash_analyzer.is_memory_tool_crash(result.output):
+ # Didn't crash.
... |
codereview_python_data_5324 | state['handle'] = handle
self.__dict__.update(state)
- def _reverse_update_params(self):
- self.train_set._reverse_update_params()
- for valid_set in self.valid_sets:
- valid_set._reverse_update_params()
-
def free_dataset(self):
self.__dict__.pop('train_s... |
codereview_python_data_5327 | s.next()
base_type = p_c_base_type(s)
is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode)
- is_template = isinstance(base_type, Nodes.TemplatedTypeNode)
- is_const_volatile = isinstance(base_type, Nodes.CConstOrVolatileTypeNode)
- is_ctuple = isinstance(base_type, Nodes.CTupleBase... |
codereview_python_data_5328 | if self.selection_expr is None:
return data
if not isinstance(data, Dataset):
- raw = True
data = Dataset(data)
return data[self.selection_expr.apply(Dataset(data))]
What does this line achieve?
if self.selection_expr is None:
retur... |
codereview_python_data_5329 | Translate.
random_negative_prob (float): The probability that turns the
offset negative.
- interpolation (str): Same as :func:`mmcv.imtranslate`.
min_size (int | float): The minimum pixel for filtering
invalid bboxes after the translation.
"""
interp... |
codereview_python_data_5332 | --------
>>> G = nx.Graph()
>>> G.add_path([0,1,2,3,4])
- >>> print(list(nx.dfs_postorder_nodes(G,0)))
[4, 3, 2, 1, 0]
- >>> print(list(nx.dfs_postorder_nodes(G,0,2)))
[1, 0]
Notes
Missing a space after the comma; run PEP8 checks again.
--------
>>> G = nx.Graph()
>>... |
codereview_python_data_5333 | if count:
return int(count)
- if "PYTEST_CURRENT_TEST" in os.environ:
- # pytest sets the environment variable PYTEST_CURRENT_TEST. If the variable is set
- # then return exact listen count using count(*) for listens corresponding to the
- # user_nam... |
codereview_python_data_5335 | >>> from Bio import TogoWS
>>> for id in TogoWS.search_iter("pubmed", "diabetes+human", limit=10):
... print("PubMed ID: %s" %id) # maybe fetch data with entry?
- PubMed ID: 27374092
Internally this first calls the Bio.TogoWS.search_count() and then
uses Bio.TogoWS.search() to get the re... |
codereview_python_data_5336 | assert self._tempdir is not None # for mypy
modified_src = self._tempdir / src.name
- shutil.copy(os.path.join(REPO_ROOT, 'www/header.asciidoc'), modified_src)
outfp = io.StringIO()
```suggestion shutil.copy(str(REPO_ROOT / 'www' / 'header.asciidoc'), modified_src) ```
as... |
codereview_python_data_5344 | p["A02"] = p["A02"]
for w in p:
pass
- self.assertTrue("A01" in p)
- self.assertFalse("test" in p)
self.assertRaises(ValueError, next, p.get_row("test"))
self.assertEqual(next(p.get_row("A")), p["A01"])
self.assertRaises(ValueError, next, p.get_col... |
codereview_python_data_5346 | self.__add_result_listeners(jmx)
if not is_jmx_generated:
self.__force_tran_parent_sample(jmx)
- self.__force_hc4_cookie_handler(jmx)
self.__fill_empty_delimiters(jmx)
return jmx
What if user uses older JMeter and does not want to force HC4 cookie manager?
... |
codereview_python_data_5350 | return get_model(app_label, model_name)
-def get_installed_app_config(app_label):
- try:
- return apps.get_app_config(app_label)
- except LookupError:
- pass
-
-
def get_model(app_label, model_name):
"""
Fetches a Django model using the app registry.
Just let the users call `apps.ge... |
codereview_python_data_5355 | ('colors', 'tab.indicator.stop'): 'tabs.indicator.stop',
('colors', 'tab.indicator.error'): 'tabs.indicator.error',
('colors', 'tab.indicator.system'): 'tabs.indicator.system',
- ('tabs', 'always-hide'): 'hide-always',
('tabs', 'auto-hide'): 'hide-auto',
}
DELETED_OP... |
codereview_python_data_5356 | """Receive on layer 3"""
r = SuperSocket.recv(self, x)
if r:
- ts = r.time
- r = r.payload
- r.time = ts
return r
def send(self, pkt):
No need for a temporary variable here or another variable assignment: ```suggestion r.payload.time = r.time re... |
codereview_python_data_5358 | try:
resp.content # Consume socket so it can be released
except (ContentDecodingError, RuntimeError):
- pass # It seems to have already been consumed.
if i >= self.max_redirects:
raise TooManyRedirects('Exceeded %s redirects.' % s... |
codereview_python_data_5360 | <h1>Error 503 Backend is unhealthy</h1>
<p>Backend is unhealthy</p>
<h3>Guru Mediation:</h3>
- <p>Details: cache-sea4470-SEA 1645543044 2832070395</p>
<hr>
<p>Varnish cache server</p>
</body>
don't need types in docstring if they're in the method args
<h1>Error 503 Backend is unhea... |
codereview_python_data_5373 | code.mark_pos(self.pos)
self.expr.result_is_used = False # hint that .result() may safely be left empty
self.expr.generate_evaluation_code(code)
- result = self.expr.result()
- if not self.expr.is_temp and result:
if not self.expr.type.is_void:
res... |
codereview_python_data_5374 | finding.get('source_properties').get('violation_data'))
raise api_errors.ApiExecutionError(violation_data, e)
- # pylint: disable=logging-too-many-args
def list_findings(self, source_id):
"""Lists all the findings in CSCC.
why is this pylint disable needed?
... |
codereview_python_data_5381 | if len(transactions) + len(current_spent_transactions) > 1:
raise DoubleSpend('tx "{}" spends inputs twice'.format(txid))
elif transactions:
- transaction = operation_class(transactions[0]).from_db(self, transactions[0])
elif current_spent_transactions:
tr... |
codereview_python_data_5388 | if role not in accepted_roles:
raise ValueError("Role {} is not acceptable".format(role))
if not need_to_be_on_ledger and role != "*":
- raise ValueError("It has point to set 'need_to_be_on_ledger' flag, only if '*' role set. "
- "Got {} role instead... |
codereview_python_data_5392 | """Checks and updates the necessary symbolizer options such as
`external_symbolizer_path` and `symbolize_inline_frames`."""
if 'external_symbolizer_path' not in tool_options:
- llvm_symbolizer_path_arg = _quote_value_if_needed(
- get_llvm_symbolizer_path())
- if llvm_symbolizer_path_arg:
to... |
codereview_python_data_5397 | """Instead of reading a file, just parse a config entry."""
def locked_get(self):
- """ TODO ADD DOC-STRING"""
content = db_config.get_value('client_credentials')
if not content:
return None
Add a docstring. Return credentials ?
"""Instead of reading a file, just parse a config entry."""
... |
codereview_python_data_5402 | @property
def _pubsub(self):
- return getattr(self._thread, "_pubsub", None)
@_pubsub.setter
def _pubsub(self, value):
If I understand the proposal of @thedrow : ```python @property def pubsub(self): if self._thread.pubsub is None: # Create pubsub client instance here self._thread.pubsub = p... |
codereview_python_data_5405 | def auto_fp16_wrapper(old_func):
def new_func(*args, **kwargs):
args_info = getfullargspec(old_func)
num_args = len(args)
num_kwargs = len(kwargs)
The dimension check is unnecessary since we use the `auto_fp16` decorator to specify tensors to converted.
def au... |
codereview_python_data_5420 | _log_inited = True
-def change(filters):
- console.addFilter(LogFilter(filters.split(',')))
-
-
def _init_py_warnings():
"""Initialize Python warning handling."""
warnings.simplefilter('default')
Instead of adding a new filter (which means I won't be able to change the filter I set on the command li... |
codereview_python_data_5426 | rescale (bool): If True, return boxes in original image space.
Returns:
- Tensor: Labeled boxes in shape (n, 5), where the first 4 columns
- are bounding box positions (tl_x, tl_y, br_x, br_y) and the
- 5-th column is a score between 0 and 1.
"""
... |
codereview_python_data_5429 | create_path(dump_path)
db_dump.dump_postgres_db(dump_path, time_now, threads)
ls.dump_listens(dump_path, time_now, threads)
- write_hashes(dump_path)
@cli.command()
There is no error handling here. If the disk runs out of space during hash creation, the hash creation fails silently.
create_pat... |
codereview_python_data_5432 | # and remove those addresses from being asked about again. Here
# any value of None means the address hasn't been set.
- values = current_context.get_if_set(reads)
addresses_not_found = []
for address, value in zip(reads, values):
if value ... |
codereview_python_data_5450 | -def Score(x, y):
pass
Method names should start with lowercase. ```suggestion def score(x, y): ```
+def score(x, y):
pass |
codereview_python_data_5451 | super(_ExtensionsGoalStateFromExtensionsConfig, self).__init__()
self._id = incarnation
self._text = xml_text
- self._parse_extensions_config(xml_text)
try:
self._do_common_validations()
except Exception as e:
- raise ExtensionsConfigError("Err... |
codereview_python_data_5452 | del othercid['spam']
assert cid != othercid
assert cid == {'spam': 'blueval', 'eggs': 'redval'}
- assert cid.__eq__(object()) == NotImplemented
def test_setdefault(self):
cid = CaseInsensitiveDict({'Spam': 'blueval'})
Shouldn't this be ``` py with pytest.raises(NotImplem... |
codereview_python_data_5456 | class LeafNode(Node):
- __slots__ = ('reader', 'is_leaf')
def __init__(self, path, reader):
Node.__init__(self, path)
`is_leaf` is already defined in `Node.__slots__`
class LeafNode(Node):
+ __slots__ = ('reader', )
def __init__(self, path, reader):
Node.__init__(self, path) |
codereview_python_data_5457 | try:
backup_archive_path = shutil.make_archive(backup_archive_path,
BACKUP_ARCHIVE_FORMAT, directory)
- logs.log('Created corpus backup file.',
- backup_archive_path=backup_archive_path,
- directory=directory,
- size=os.path.g... |
codereview_python_data_5459 | def choose_loader(column):
if column in USEquityPricing.columns:
return pipeline_loader
- elif column in loaders:
- return loaders[column]
else:
raise ValueError(
"No PipelineLoader registered for column ... |
codereview_python_data_5462 | def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None, ordered=True) -> List[Tensor]:
"Return predictions and targets on the valid, train, or test set, depending on `ds_type`."
- lf = self.loss_func if with_loss else No... |
codereview_python_data_5467 | .. [1] https://en.wikipedia.org/wiki/Graph_minor
"""
-from networkx.algorithms.minors import contraction
-
from networkx.algorithms.minors.contraction import (
contracted_edge,
contracted_nodes,
I guess my only remaining question is: do we want to add this module to the top-level namespace, or only the fu... |
codereview_python_data_5468 | try:
remote = cache[__method_name__]
except KeyError:
- cache[__method_name__] = remote = getattr(remote_cls, __method_name__)
return remote(self.__remote_end__, *args, **kw)
wrapper.__name__ = method
You probably should do the same as in ... |
codereview_python_data_5470 | self.populations = []
def __str__(self):
- """Return (reconstructs) a GenePop textual representation."""
rep = [self.comment_line + '\n']
rep.append('\n'.join(self.loci_list) + '\n')
for pop in self.populations:
You should change this to "reconstruct" as well (to match t... |
codereview_python_data_5475 | # Code based on
# https://bitbucket.org/bedwards/networkx-community/src/370bd69fc02f/networkx/algorithms/community/
def directed_laplacian(G, nodelist=None, weight='weight', walk_type=None, alpha=0.95):
r"""Return the directed Laplacian matrix of G.
You could use the decorator `require' from networkx/utils/dec... |
codereview_python_data_5476 | >>> list(TR.edges)
[(1, 2), (2, 3)]
To perform transitive reduction on a DiGraph and transfer node/edge data:
>>> DG = nx.DiGraph()
It might be good to have the explanation that's in the notes section in the example instead to provide a bit more context for the example. ```suggestion To avoid unnec... |
codereview_python_data_5488 | class TestCRDWriterMissingAttrs(object):
# All required attributes with the default value
- req_attrs = {'resnames': 'UNK',
- 'resids': 1,
- 'names': 'X',
- 'tempfactors': 0.0,
- }
@pytest.mark.parametrize('missing_attr', req_attrs)
def ... |
codereview_python_data_5498 | if set_tasks["ever_failed"]:
if not set_tasks["failed"]:
smiley = ":)"
- reason = "there were failed tasks but suceeded in retry"
else:
smiley = ":("
reason = "there were failed tasks"
perhaps change to "there were failed tasks but **they all** s... |
codereview_python_data_5499 | avg_count = torch.mean((ranks <= hit).float())
print("Hits (filtered) @ {}: {:.6f}".format(hit, avg_count.item()))
return mrr.item()
You should move this for loop into calc_filtered_mrr. Otherwise there will be two print output of "test triplet {} / {}" in both perturb_s_and_get_filtered... |
codereview_python_data_5504 | self.db = db
self.db_ledger = DBLedgerActions(self.db, self.db.msg_aggregator)
- def _consume_cointracking_entry(
- self,
- csv_row: Dict[str, Any],
- extra_parameters: Dict[str, Any],
- ) -> None:
"""Consumes a cointracking entry row from the CSV and adds it into t... |
codereview_python_data_5505 | if email:
try:
ProductAlert.objects.get(
- product=self.product, email=email, status=ProductAlert.ACTIVE)
except ProductAlert.DoesNotExist:
pass
else:
raise forms.ValidationError(_(
... |
codereview_python_data_5506 | if self.bot.config.release.get('all'):
group = [p for p in inventory.pokemons().all()
- if not p.in_fort and not p.is_favorite and not (p.unique_id == self.buddy['id'])]
self._release_pokemon_worst_in_group(group, 'all')
def _should_work(self):
If there is no... |
codereview_python_data_5508 | mosaic_bboxes = np.concatenate(mosaic_bboxes, 0)
mosaic_labels = np.concatenate(mosaic_labels, 0)
if self.bbox_clip_border:
mosaic_bboxes[:, 0::2] = np.clip(mosaic_bboxes[:, 0::2], 0,
2 * self.img_scale[1])
The or... |
codereview_python_data_5516 | docstring_arborescence.format(kind='maximum', style='spanning arborescence')
minimum_spanning_arborescence.__doc__ = \
- docstring_arborescence.format(kind='minimum', style='spanning arborescence')
\ No newline at end of file
Don't remove the newline at the end of the file.
docstring_arborescence.format... |
codereview_python_data_5520 | def __call__(self, data, **metadata):
opts = jsbeautifier.default_options()
opts.indent_size = 2
- res = jsbeautifier.beautify(strutils.native(data), opts)
return "JavaScript", format_text(res)
This is going to fail for any non-valid utf8 :wink:
def __call__(self, data, **m... |
codereview_python_data_5527 | ('BRENDA, the Enzyme Database', ['1.1.1.1']),
('CAS', ['9031-72-5'])])
self.assertEqual(records[-1].entry, "2.7.2.1")
- self.assertEqual(records[-1].__str__().replace(" ", "").split("\n")[:10],
['ENTRYEC2.7.2.1', 'NAMEacetat... |
codereview_python_data_5534 | else:
url = "https://{0}.twitch.tv{1}".format(self.subdomain, path)
- headers = {'Client-ID': TWITCH_CLIENT_ID}
- if "/kraken/channels/" not in path:
- headers['Accept'] = 'application/vnd.twitchtv.v{0}+json'.format(self.version)
# The certificate used by Twitch c... |
codereview_python_data_5559 | @pytest.mark.skipif(not hasattr(typing, 'NewType'), reason='test for NewType')
def test_resolves_NewType():
- for t in [
- typing.NewType('T', int),
- typing.NewType('UnionT', typing.Optional[int]),
- typing.NewType('NestedT', typing.NewType('T', int)),
- ]:
- from_type(t).example()
... |
codereview_python_data_5564 | self.opts.packages_action = self.opts._packages_action
if self.opts.obsoletes:
if self.opts._packages_action:
- raise dnf.exceptions.Error(_("argument {}: not allowed with argument {}".format(
- "--obsoletes", "--" + self.opts._packages_action)))
... |
codereview_python_data_5571 | return RateLimiter(FLAGS.max_bigquery_api_calls_per_100_seconds,
self.DEFAULT_QUOTA_TIMESPAN_PER_SECONDS)
- def get_bigquery_projectids(self, key='projects'):
"""Request and page through bigquery projectids.
Returns: A list of project_ids enabled for bigquery.
... |
codereview_python_data_5572 | with tempdir.in_tempdir():
reference.trajectory[-1]
x = align.AlignTraj(universe, reference)
- os.remove(x.filename)
- assert os.path.basename(x.filename) == 'rmsfit_adk_dims.dcd'
def test_AlignTraj_outfile_default_exists(self, universe, reference, tmpdir):
... |
codereview_python_data_5576 | def _enable_amqheartbeats(timer, connection, rate=2.0):
- heartbeat_error = [None]
if not connection:
return heartbeat_error
I'm not seeing why this is a `list` instead of just `None`. What benefit is there by making this a list and sometimes modifying the first value?
def _enable_amqheartbeats(tim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.