id
stringlengths
24
28
content
stringlengths
121
2.08k
codereview_python_data_7885
return self.df.index def time_dtypes(self, shape): - # trigger _compute_dtypes func - self.df._query_compiler._modin_frame._dtypes = None return self.df.dtypes This makes bench strictly engine specific, can we somehow allow it to execute only for pandas backend? return se...
codereview_python_data_7888
@classmethod - def validate(cls, dataset): - if dataset._virtual_vdims: - dimensions = dataset.dimensions('key', label='name') - else: - dimensions = dataset.dimensions(label='name') not_found = [d for d in dimensions if d not in dataset.data] if not_found: ...
codereview_python_data_7891
parser = await self.data_svc.dao.get('core_parser', dict(ability=x['ability'])) if parser: if parser[0]['name'] == 'json': - matched_facts = parsers._json(parser[0], b64decode(x['output']).decode('utf-8')) elif parser[0]['name'] == 'line': -...
codereview_python_data_7892
num_total_samples=num_total_samples) avg_factor = sum(avg_factor) - avg_factor = reduce_mean(avg_factor).item() - if avg_factor < EPS: - avg_factor = 1 losses_bbox = list(map(lambda x: x / avg_factor, losses_bbox)) losses_dfl = list(map(lambda x: x / ...
codereview_python_data_7894
content_id='Scanner Violations' ) scanner_subject = '{} Complete - {} violation(s) found'.format( - total_violations, email_description) self.email_util.send( email_sender=email_sender, email_recipient=email_recipient, I think, the order of t...
codereview_python_data_7896
}; """ - @test.xfail('not sure how to test multi-line semantics, ' - 'as strings no longer preserve original structure') def test_eschema_syntax_type_22(self): """ module test { @vpetrovykh Any suggestions here? }; """ def test_eschema_...
codereview_python_data_7898
prefix = s3_configuration.get("Prefix", "") s3 = connect_to_resource("s3") - batched_data = b"".join([base64.b64decode(r.get("Data") or r["data"]) for r in records]) obj_path = get_s3_object_path(stream_name, prefix) try: nit: I think `Data` may potentially contain an empty string (at least kine...
codereview_python_data_7900
'CTX', # Centauri coin but CarTaxi in CC ethaddress_to_identifier('0xf14922001A2FB8541a433905437ae954419C2439'), # noqa: E501 # Direct insurance token but DitCoin in CC 'DRM', # Dreamcoin but Dreamchain in CC - ethaddress_to_identifier('0x82fdedfB7635441aA5A92791D001fA7388da80...
codereview_python_data_7904
:param content: what gets written into the file :return: None """ - try: - with open(filename, 'w') as f: - f.write(content) - except Exception as e: - raise def print_stdout(line): What the point of catching the exception to re-raise it right away? :param content: ...
codereview_python_data_7907
""" Finds any applicable compositor and applies it. """ - from .overlay import Overlay while True: match = cls.strongest_match(overlay, mode) if match is None: return overlay Not looked ahead yet - I'm hoping to see some new tests showing this new co...
codereview_python_data_7908
return "<" + repr(self.__class__.__name__) + ">" class FullSelgroupSelection(Selection): def __init__(self, selgroup): - warnings.warn("Use of 'fullgroup' in selections is deprecated " - "in MDAnalysis '0.11' and will be removed entirely in upcoming " - "releases. Use...
codereview_python_data_7912
self.assertEqual(hit11, query["hit1"]) self.assertEqual(hit11, query["alt1"]) self.assertEqual(hit11, query["alt11"]) - self.assertEqual(hit11.id, "alt1") - self.assertEqual(hit11.id, "alt11") hit11._id_alt = [] def test_setitem_ok_alt_existing(self): These should...
codereview_python_data_7914
import numpy as np from numpy.testing import assert_allclose, assert_equal - import random from MDAnalysis.lib import transformations as t +1 for removing `TestCase`. I don't understand why we actually need it, even under `nose`, since a test class inheriting from `object` will work fine, even with fixtures like `...
codereview_python_data_7922
db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'create_indexes.sql')) def drop_tables(self): db.run_sql_script(os.path.join(ADMIN_SQL_DIR, 'drop_tables.sql')) def drop_schema(self): I learned recently that you can use `DROP SCHEMA CASCADE` to drop all tables in a schema. As we have mostly sc...
codereview_python_data_7923
return interpreter -def get_execute_command(file_to_execute, is_blackbox_fuzzer=False): """Return command to execute |file_to_execute|.""" - interpreter_path = get_interpreter( - file_to_execute, is_blackbox_fuzzer=is_blackbox_fuzzer) # Hack for Java scripts. file_to_execute = file_to_execute.replace(...
codereview_python_data_7924
yield source - def get_keystore_config(self): - return self.get(self.FIELD_KEYSTORE_CONFIG) - def get_requests(self, parser=RequestParser, require_url=True): """ Generator object to read requests This is JMeter-specific thing, it can't be in the core yield so...
codereview_python_data_7928
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; """ In addition to this here, we also should have the entirety of the unparsed (i.e. raw) Member response stored in one big chunk in a separate table, with a 1:1 relation to Groups. Please take a look at the RAW_PROJECT_IAM_POLICIES_TABLE. Okay, t...
codereview_python_data_7941
# the fd from epoll(7) anymore, causing a 100% CPU poll loop. fd = proc._sentinel_poll = os.dup(proc._popen.sentinel) # Safely call hub.add_reader for the determined fd - self.iterate_file_descriptors_safely( [fd], None, hub.add_reader, self._event_pro...
codereview_python_data_7942
class new_build_ext(_build_ext, object): - user_options = _build_ext.user_options[:] - - user_options.extend([ ('c-build-dir=', None, "directory for generated c files"), - ]) def initialize_options(self): _build_ext.initialize_options(self) This can be simplified. ```suggestion user_op...
codereview_python_data_7947
self._dump_slack_output(violation.get('violation_data'), 1)) # Wait 30 seconds before retrying: https://api.slack.com/docs/rate-limits - @retry(wait_exponential_multiplier=30000, wait_exponential_max=60000, stop_max_attempt_number=2) def _send(self, payload): """Sends ...
codereview_python_data_7949
-------- >>> G = nx.Graph() >>> G.add_path([0, 1, 2, 3, 4]) - >>> print(list(nx.dfs_preorder_nodes(G,0))) [0, 1, 2, 3, 4] - >>> print(list(nx.dfs_preorder_nodes(G,0,2))) [0, 1, 2] Notes You don't need to have `print` here, just do `list(...)`, since it is part of an interactive shel...
codereview_python_data_7951
objects. index (pandas.Index, list, ObjectID): The row index for this DataFrame. - columns (pandas.Index): The column names for this pandas, in pandas Index object. dtype: Data type to force. Only a single dtype is allowed. ...
codereview_python_data_7958
validator_info.get_action_id(): AuthConstraintOr([AuthConstraint(TRUSTEE, 1), AuthConstraint(STEWARD, 1), AuthConstraint(NETWORK_MONITOR, 1)]), - create_revoc_reg_def.get_action_id(): trust_anchor_or_st...
codereview_python_data_7959
if fields[0].strip() == "GROUP": return self.__parse_group(fields) elif fields[0].strip() == "REQUEST": - if self.guessed_gatling_version == "3.X": - fields.insert(1, 'Taurus Scenario') return self.__parse_request(fields) else: ...
codereview_python_data_7969
if columns is None: columns = {} - for term in columns.values(): if not isinstance(term, ComputableTerm): raise TypeError( - '"{term}" is not a valid pipeline column. Did you mean ' - 'to add ".latest"?'.format(term=term) ...
codereview_python_data_7971
(['redhat', '7.7.1908', 'Core'], False), (['bigip', '15.0.1', 'Final'], False), (['gaia', '273.562', 'R80.30'], False), - (['debian' '9.1', ''], False), # pylint: disable=implicit-str-concat,implicit-str-concat-in-sequence ] for (distro, supported) in ...
codereview_python_data_7973
Discrete Algorithms, 132--139, 2003. """ - def _choose_node(candidates, n_nodes, delta): if delta > 0: - bias_sum = n_nodes * delta p_delta = bias_sum / (bias_sum + len(candidates)) if seed.random() < p_delta: - return seed.randint(0, n_no...
codereview_python_data_7976
self.assertEqual(str(e.exception), expected) -class TestDownsampledRowwiseOperation(WithSeededRandomPipelineEngine, - ZiplineTestCase): T = partial(pd.Timestamp, tz='utc') - START_DATE = T('2014-01-02') - END_DATE = T('2014-02-03') HALF_WAY_POINT = T('2014-0...
codereview_python_data_7979
summary='Retrieve Facts', description='Retrieve facts by criteria. Use fields from the `FactSchema` in the request body to filter retrieved facts.') @aiohttp_apispec.querystring_schema(BaseGetAllQuerySchema) - @aiohttp_apispec.response_schema(FactSchema(many...
codereview_python_data_7985
self.log = log.getChild(self.__class__.__name__) if parent: - for method, args, kwargs in parent.get_queue(): - self._queue.append((self.__getattribute__(method), args, kwargs)) - - pass def get_queue(self): - for method, args, kwargs in self._queue: - ...
codereview_python_data_7992
def __init__( self, name: str, default: typing.Any, - typespec: typing.Type, help: str, choices: typing.Optional[typing.Sequence[str]] ) -> None: typecheck.check_type(name, default, typespec) self.name = name - self._default = defaul...
codereview_python_data_7995
DataFrame with asset_id as index and 'start_date'/'end_date' columns. calendar : pd.DatetimeIndex The trading calendar to use. - holes : dict[int -> tuple[pd.Timestamps]] A dict mapping asset ids to the tuple of dates that should have - no data for that asset in the output. ...
codereview_python_data_8002
def parseTimeReference(ref, now): - if not ref or ref == 'now': return datetime.utcnow().replace(tzinfo=pytz.utc) #Time-of-day reference i = ref.find(':') hour,min = 0,0 Instead of `datetime.utcnow().replace(tzinfo=pytz.utc)` you can do ``` python from django.utils import timezone timezone.now() # returns t...
codereview_python_data_8006
# This is temporary, until we implement `subtransaction` # functionality of RFC1004 - warnings.filterwarnings('ignore', message=r'The "transaction\(\)" method is deprecated' r' and is scheduled to be removed', category=Depre...
codereview_python_data_8007
-"""Tests for google3.experimental.users.ahoying.forseti-security.tests.services.inventory.cai_temporary_storage.""" from future import standard_library standard_library.install_aliases() We might want to remove the ref to google3 here +"""Tests for google.services.inventory.cai_temporary_storage.""" from future i...
codereview_python_data_8009
base = '%s_%s' % (product.id, stockrecord.id) if not options: return base - repr_options = [(repr(option['option']), repr(option['value'])) - for option in options] - repr_options.sort() return "%s_%s" % (base, zlib.crc32(repr(repr_options).en...
codereview_python_data_8011
Number of pixels to spread on all sides.""") def _apply_spreading(self, array): - replace_none_how = ds_version <= '0.11.1' and (self.p.how is None) - how = 'source' if replace_none_how else self.p.how - return tf.spread(array, px=self.p.px, how=how, shape=self.p.shape) class dynspre...
codereview_python_data_8027
TelemetryEventParam(CommonTelemetryEventSchema.TaskName, threading.current_thread().getName()), TelemetryEventParam(CommonTelemetryEventSchema.KeywordName, '')] - if event.eventId in (None, TELEMETRY_EVENT_EVENT_ID) and event.providerId in (None, TELEMETRY_EVEN...
codereview_python_data_8033
"""A SCOP domain. A leaf node in the Scop hierarchy. - sid -- The SCOP domain identifier. e.g. ``"d5hbib_"`` - - residues -- A Residue object. It defines the collection of PDB atoms that make up this domain. """ This extra white space is why the TravisCI style check ...
codereview_python_data_8041
if sys.version_info >= (3, 0): from io import BytesIO as StringIO else: - try: - from cStringIO import StringIO - except ImportError: - from StringIO import StringIO - INFINITY = float('inf') We can eliminate the try/except here since we don't need to support <2.7 if sys.version_info >= (3, 0): from...
codereview_python_data_8042
"""Test that we can query bisq for market prices""" price = get_bisq_market_price(A_BSQ) assert price != Price(ZERO) - # Test that error is correctly rised when there is no market with pytest.raises(RemoteError): get_bisq_market_price(A_3CRV) ```suggestion # Test that error is correctly...
codereview_python_data_8047
if self.orig_bases: # update __orig_bases__ if needed code.putln("if (%s != %s) {" % (self.bases.result(), self.orig_bases.result())) - code.putln('PyDict_SetItemString(%s, "__orig_bases__", %s);' % ( - self.dict.result(), self.orig_bases.result())) ...
codereview_python_data_8048
@abc.abstractmethod def fetch_bigquery_iam_policy(self, project_number, dataset_id): - """Gets IAM policy if a bigquery dataset from gcp API call. Args: project_number (str): number of the project to query. typo: if -> of @abc.abstractmethod def fetch_bigquery_iam_poli...
codereview_python_data_8054
location=Location.KRAKEN, location_label=self.name, ) - trades_raw, _ = self.db.get_history_events(filter_query) trades, max_ts = self.process_kraken_trades(trades_raw) queried_range = (start_ts, Timestamp(max_ts)) if with_errors else (start_ts, end_ts) ...
codereview_python_data_8063
if i % 10 == 0: print(bst.eval_train(), bst.eval_valid()) self.assertEqual(bst.current_iteration(), 20) self.assertEqual(bst.num_trees(), 20) self.assertEqual(bst.num_model_per_iteration(), 1) `places=2` seems to be very poor comparison. Do you have any thoughts...
codereview_python_data_8074
from nose.plugins.attrib import attr from numpy.testing import (assert_equal, assert_almost_equal, dec, assert_array_almost_equal, assert_raises, - assert_) from unittest import TestCase import tempdir `assert_` is not used from nose.plugins.attrib import att...
codereview_python_data_8079
@property def pickle_protocol(self): - return configuration.get_config().getint(self.spark_version, "pickle-protocol", pickle.DEFAULT_PROTOCOL) def setup(self, conf): """ why is this pulling from `self.spark_version` config section rather than the `spark` config section (`py-packages` ap...
codereview_python_data_8086
self.rate_average = rate_average def message(self, msg): - dnf.util._terminal_messenger('write', msg, self.fo) - dnf.util._terminal_messenger('flush', out=self.fo) def start(self, total_files, total_size): self.total_files = total_files There is no need for 'message', if there...
codereview_python_data_8087
augment images. Examples: - TODO: Implement 'Shear', 'Sharpness' and 'Rotate' transforms >>> replace = (104, 116, 124) >>> policies = [ >>> [ We may move this TODO to Line15. augment images. Examples: >>> replace = (104, 116, 124) ...
codereview_python_data_8089
Examples -------- - How DSSP could be use:: from Bio.PDB import PDBParser from Bio.PDB.DSSP import DSSP used --> used Examples -------- + How DSSP could be used:: from Bio.PDB import PDBParser from Bio.PDB.DSSP import DSSP
codereview_python_data_8091
subctx.implicit_tid_in_shapes = False viewgen.compile_view_shapes(ir_set, ctx=subctx) elif (orig_stype.issubclass(ctx.env.schema, json_t) - and new_stype.is_enum(ctx.env.schema)): # Casts from json to enums need some special handling # he...
codereview_python_data_8097
doc_table += formater.format('', '', '', '', '', '', op_name_max_len = op_name_max_len, c='=') for op in sorted(all_ops, key=lambda v: str(v).lower()): schema = b.GetSchema(op) - op_full_name = op - if not op_full_name.startswith('_'): - op_full_name = op_full_name.replace('_...
codereview_python_data_8099
"""Initialize layers of the head.""" self.cls_convs = nn.ModuleList() self.reg_convs = nn.ModuleList() conv = DepthwiseSeparableConvModule \ if self.use_depthwise else ConvModule May add a TODO here, indicating that we will use the registry to choose either DepthwseSepa...
codereview_python_data_8100
start = 0 for n in num_levels: end = start + n - level_targets.append(target[:, start:end].squeeze(0)) start = end return level_targets Maybe we can directly use `utils.py` as the filename under the anchor dir. start = 0 for n in num_levels: end = start + n +...
codereview_python_data_8101
if __name__ == '__main__': - print(0) test_basic() - print(1) test_copy() - print(2) test_apply_nodes() - print(3) test_apply_edges() - print(4) test_flow_compute() - print(5) test_prop_flows() could you remove the prints? if __name__ == '__main__': test_basic() ...
codereview_python_data_8113
# -*- coding: utf-8 -*- from decimal import Decimal as D -from django.utils import translation -from django.test import TestCase from django import template def render(template_string, ctx): Minor nitpick, could you alphabetically sort these three imports? # -*- coding: utf-8 -*- from decimal import Decimal as ...
codereview_python_data_8131
import unittest -from crypto_square import ciphertext # Tests adapted from `problem-specifications//canonical-data.json` @ v3.2.0 Seems your template is checking the incorrect key here. import unittest +from crypto_square import cipher_text # Tests adapted from `problem-specifications//canonical-data.json` @ v3.2...
codereview_python_data_8144
self, type1, type2) def py_operation_function(self, code): type1, type2 = self.operand1.type, self.operand2.type - is_unicode_concat = type1 is unicode_type and type2 is unicode_type if is_unicode_concat: if self.operand1.may_be_none() or self.operand2.may_be_...
codereview_python_data_8146
self, key: str, lock: Union[threading.Semaphore, threading.Lock] ) -> Union[threading.Semaphore, threading.Lock]: with self.creation_lock: - if key not in self.locks: - self.locks[key] = lock - return self.locks[key] LAMBDA_ASYNC_LOCKS = LambdaAsyncLocks() n...
codereview_python_data_8148
def hausdorff_wavg(P, Q): - r"""Calculate the weighted average (undirected) Hausdorff distance between - two paths. *P* (*Q*) is a :class:`numpy.ndarray` of :math:`N_p` (:math:`N_q`) time steps, :math:`N` atoms, and :math:`3N` coordinates (e.g., ~~symmetric~~ - omit "(undirected)" def hausdorff_wavg...
codereview_python_data_8158
if isinstance(filepath_or_buffer, str): if "*" not in filepath_or_buffer: warnings.warn( - f"'*' symbol not found in filename: '{filepath_or_buffer}'" ) if not cls.file_exists(filepath_or_buffer): return cls.single_...
codereview_python_data_8161
yield finally: try: - if os.path.exists(filepath): - os.remove(filepath) except OSError as e: log.misc.error(f"Failed to delete tempfile {filepath} ({e})!") I still don't think this is needed because we handle `OSError` anyways: ```pycon >>> try: ....
codereview_python_data_8165
@click.option( '--trading-calendar', metavar='TRADING-CALENDAR', - default='XNYS', - help="The calendar you want to use e.g. XLON. XNYS is the default." ) @click.option( '--print-algo/--no-print-algo', I'd probably leave this be for now. This is part of the public-facing API of the CLI, and mor...
codereview_python_data_8167
external_updates_subscription='subscription').put() data_types.Job(name='job').put() - self.testcase_0 = data_types.Testcase( open=True, status='Processed', job_type='external_job', nit: just testcase instead of testcase_0 external_updates_subscription='subscriptio...
codereview_python_data_8177
for i, (atom, element) in enumerate(zip(ag, elements)): # create atom - rdatom = Chem.Atom(element) # disable adding H to the molecule rdatom.SetNoImplicit(True) # add PDB-like properties @jbarnoud didn't you already write code to this effect in t...
codereview_python_data_8180
except ValueError as e: signals.status_message.send(message=str(e)) return - if not parts: - signals.status_message.send(message="Invalid Url") - return scheme, host, port, path = parts f = self.master.create_request(method, scheme, host,...
codereview_python_data_8181
scale_factor = 1.0 for i in range(bboxes.shape[0]): - if not isinstance(scale_factor, float) and not isinstance( - scale_factor, np.ndarray): scale_factor = scale_factor.cpu().numpy() bbox = (bboxes[i, :] / scale_factor).astype(np.int32) ...
codereview_python_data_8188
mode = os.fstat(file_obj.fileno()).st_mode return stat.S_ISFIFO(mode) or stat.S_ISREG(mode) - -def is_tty(): - return sys.stdout.isatty() This single instruction func not worth to exist mode = os.fstat(file_obj.fileno()).st_mode return stat.S_ISFIFO(mode) or stat.S_ISREG(mode)
codereview_python_data_8194
annotations. """ -raise RuntimeError("Bio.Alphabet has been removed from Biopython. In many cases, the alphabet can simply be ignored and removed from scripts. In a few cases, you may need to specify the ``molecule_type`` as an annotation on a SeqRecord for your script to work correctly. Please see https://github.com...
codereview_python_data_8196
"""Get a list of assets from the assets table. Args: - asset_ids (list): a of list of ids for the assets to be retrieved from the database. Returns: a of list --> a list? :smile: """Get a list of assets from the assets table. Args: + asset_ids (list): a list of ids for ...
codereview_python_data_8203
@contextmanager -def rc_context(rcparams): """ Context manager that temporarily overrides the pyplot rcParams. """ To avoid confusion maybe this should be ``_rc_context`` if we expect to use the decorator and not this context manager directly. Perhaps you could even inline this context manager inside `...
codereview_python_data_8204
def generate_c_code(self, env, options, result): # Check for a common gotcha for new users: naming your .pyx file after the .c file you want to wrap - if not is_cython_generated_file(result.c_file, allow_failed=True): - error(self.pos, 'The output file already exists and does not look li...
codereview_python_data_8206
arrowsize : int or list (default=10) For directed graphs, choose the size of the arrow head's length and - width. - If `list`, assign different size on each arrow head's length and width. See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info....
codereview_python_data_8207
os.utime(file_path, None) if os.path.exists(file_path): API_FILE_PATHS[api] = file_path - chmod_r(file_path, 0o777) return API_FILE_PATHS.get(api) I think we can remove this `chmod_r` from here now (shouldn't be required anymore). os.utime(file_path,...
codereview_python_data_8208
query = QueryResult([hit11]) self.assertEqual(hit11, query["hit1"]) self.assertEqual(hit11, query["alt1"]) - self.assertEqual(hit11.id, "alt1") hit11._id_alt = [] def test_delitem_string_ok(self): The comparison here becomes incorrect. It should be `assertNotEqual` ...
codereview_python_data_8211
rst = graph.dstdata['ft'] # residual if self.res_fc is not None: - resval = self.res_fc(h_dst).view(h_dst.shape[0], -1, self._out_feats) rst = rst + resval # bias if self.bias is not None: - rst = rst + self....
codereview_python_data_8212
def __init__(self, elements): SearchStrategy.__init__(self) - self.elements = d.check_sample(elements, SampledFromStrategy.__name__) assert self.elements def calc_has_reusable_values(self, recur): The name here can just be the string `'sampled_from'`, as that's the user-facing API. S...
codereview_python_data_8217
elif '.m3u8' in video_url: for stream in HLSStream.parse_variant_playlist(self.session, video_url).items(): yield stream - elif '.mp4' in video_url: match = self._mp4_bitrate_re.match(video_url) if match is not None: ...
codereview_python_data_8219
import torch -from ..bbox import assign_and_sample, bbox2delta, build_assigner -from ..bbox.samplers.pseudo_sampler import PseudoSampler from ..utils import multi_apply `PseudoSampler` can also be imported from `..bbox` import torch +from ..bbox import PseudoSampler, assign_and_sample, bbox2delta, build_assigner ...
codereview_python_data_8220
# Get maximum scores for foreground classes. if self.use_sigmoid_cls: - max_scores, _ = scores.max(dim=2) else: # remind that we set FG labels to [0, num_class-1] # since mmdet v2.0 # BG ...
codereview_python_data_8221
new_index = pandas.RangeIndex(len(self.index)) if not axis else self.index new_columns = self.columns if not axis else pandas.RangeIndex(len(self.columns)) new_dtypes = self._dtype_cache - new_dtypes.index = new_columns return self.__constructor__( new_data, new_i...
codereview_python_data_8229
def test_method(self): q = self.req() - self.resp() assert self.q("~m get", q) assert not self.q("~m post", q) remove entirely? (same below) def test_method(self): q = self.req() assert self.q("~m get", q) assert not self.q("~m post", q)
codereview_python_data_8230
stop_price=None, style=None): """ - Place an order for a fixed amount of value. Equivalent to ``order(asset, value / data.current(asset, 'price'))``. "amount of value" sounds a little weird. Maybe just "value"? stop_price=None, ...
codereview_python_data_8231
""" Return the file content hash for a file. """ - with open(file_path, 'rb') as content: hasher = hashlib.sha256() hasher.update(content.read()) return hasher.hexdigest() ```suggestion with open(file_path, 'rb', encoding='utf-8', errors='ignore') as content: ``` Please fix...
codereview_python_data_8233
complex = 0, longness = 0, is_self_arg = cmethod_flag, templates = None) else: - base_type = p_c_base_type(s, nonempty = nonempty) declarator = p_c_declarator(s, ctx, nonempty = nonempty) if s.sy in ('not', 'or') and not s.in_python_file: kind = s.sy ```suggesti...
codereview_python_data_8235
], f'Invalid crop_type {crop_type}.' if crop_type in ['absolute', 'absolute_range']: assert crop_size[0] > 0 and crop_size[1] > 0 else: assert 0 < crop_size[0] <= 1 and 0 < crop_size[1] <= 1 self.crop_size = crop_size we should also ensure that they are int...
codereview_python_data_8236
dali_cflags, dali_lflags = get_dali_build_flags() tf_cflags, tf_lflags = get_tf_build_flags() cuda_cflags, cuda_lflags = get_cuda_build_flags() - plugin_src = self.src_path + '/daliop.cc' + ' ' + self.src_path + '/dali_dataset_op.cc' lib_path = self.plugin_dest_dir + '/libdali...
codereview_python_data_8241
maximum_ball = ITEM_ULTRABALL if is_vip else ITEM_GREATBALL ideal_catch_rate_before_throw = 0.9 if is_vip else 0.35 - while True: - self.bot.latest_inventory = None - berry_count = self.bot.item_inventory_count(berry_id) - items_stock = self.bot.current_inventor...
codereview_python_data_8248
d = th.cdist(x, x).to(F.cpu()) def check_knn(g, x, start, end): g = g.to(F.cpu()) for v in range(start, end): src, _ = g.in_edges(v) Probably also assert the context of `kg` and `x` before sending to cpu. d = th.cdist(x, x).to(F.cpu()) def check_knn(g, x, start, end)...
codereview_python_data_8249
Test support of python object in annotations >>> test_cdef_return_object(3) 3 """ - return x For the sake of completeness could be a test that the exception raises correctly: ``` if x: return x else: raise RuntimeError() ``` and a test of both pathways in the doctest Test support of python...
codereview_python_data_8251
# GI:160837788 aka NP_075631.2 # the actin related protein 2/3 complex, subunit 1B [Mus musculus] self.run_qblast("blastp", "nr", "NP_075631.2", 0.001, - "rat [ORGN]", dict(megablast='FALSE'), ['9506405', '13592137', '37589612', '149064087', '56912225']) def test_p...
codereview_python_data_8257
from indy_common.authorize.auth_actions import AuthActionAdd, AuthActionEdit from indy_common.authorize.auth_constraints import AuthConstraint, AuthConstraintOr, accepted_roles, IDENTITY_OWNER from indy_common.constants import TRUST_ANCHOR, POOL_CONFIG, VALIDATOR_INFO, POOL_UPGRADE, POOL_RESTART, NODE, \ - CLAIM_...
codereview_python_data_8263
return outs[0] else: return tuple(outs) This will cause BC-breaking if we simply remove L2Norm from this file. return outs[0] else: return tuple(outs) + + +class L2Norm(ssd_neck.L2Norm): + + def __init__(self, **kwargs): + super(L2Norm, s...
codereview_python_data_8270
self.modules = {"__builtin__" : Builtin.builtin_scope} self.cython_scope = CythonScope.create_cython_scope(self) self.modules["cython"] = self.cython_scope - self.include_directories = tuple(include_directories) self.future_directives = set() self.compiler_directives ...
codereview_python_data_8274
def create_sqs_message_attributes(subscriber, attributes): - if subscriber['RawMessageDelivery'] == 'false': return {} message_attributes = {} If the key `"RawMessageDelivery"` is missing in `subscriber`, this would raise a `KeyError`. Perhaps we can change it to: ``` if subscriber.get('RawMessageDel...
codereview_python_data_8276
kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) # Choose a node with minimum degree. - deg = G.degree() - v = next(n for n, d in deg.items() if d == min(deg.values())) # Initial node cutset is all neighbors of the node with minimum degree. min_cut = set(G[v]) # Compute st node...
codereview_python_data_8282
from tests.test_libs import test_utils -@unittest.skipIf(sys.version_info.major != 3, 'Python 3 only') @test_utils.with_cloud_emulators('datastore') class OssFuzzGenerateCertsTest(unittest.TestCase): """Test oss_fuzz_generate_certs.""" there was some helper decorator for this ? from tests.test_libs import test...
codereview_python_data_8286
# skip the image if there is no valid gt bbox if len(gt_bboxes) == 0 and self.skip_img_without_anno: - warnings.warn('Skip the image that has no valid gt bbox') return None # extra augmentation Maybe also print the filename? # skip the image if there is no v...
codereview_python_data_8287
import unittest from rational_numbers import Rational For now, we still need this import to pass tests in Python 2. +from __future__ import division import unittest from rational_numbers import Rational
codereview_python_data_8288
type=float, default=15.0 ) - parser.add_argument( - "-hr", - "--health_record", - help="Send anonymous bot event to GA for bot heath record, furthur ML will depend on it. Set \"health_record\":false if you need disable it.", - type=bool, - default=True - )...