id
stringlengths
24
28
content
stringlengths
121
2.08k
codereview_python_data_4587
_req_types = ["121"] def _rand_data(self): - return ('1', 'ADD', 'role') async def _gen_req(self, submitter_did, req_data): - return await ledger.build_get_auth_rule_request(None, req_data[0], req_data[1], req_data[2], None, None) I think it would be better (more close to production use ca...
codereview_python_data_4591
self._settings.setDefaultTextEncoding(encoding) return old_value != encoding - def set_unknown_url_scheme_policy(self, policy: int) -> bool: - """Set the UnknownUrlSchemePolicy to use. - - Return: - True if there was a change, False otherwise. - """ - assert p...
codereview_python_data_4593
if len(amf_response.messages) != 1 or amf_response.messages[0].target_uri != "/1/onResult": raise PluginError("unexpected response from amf gate") - stream_source_info = parse_json(json.dumps(amf_response.messages[0].value), schema=amf_msg_schema) self.logger.debug("source stream i...
codereview_python_data_4599
return self.set_font_family(setting, value) elif setting == 'content.default_encoding': return self.set_default_text_encoding(value) - elif setting == 'unknown_url.scheme.policy': - # QtWebKit and QWebEngine < 5.11 doesn't provide interfaces - # for proces...
codereview_python_data_4600
def destroy(self): self._write_vagrant_file() - for status in self._vagrant.status(): - if status[1] == 'running': - self._vagrant.destroy(vm_name=status[0]) os.remove(self.m._config.config['molecule']['vagrantfile_file']) Would be nice if we can look at the stat...
codereview_python_data_4601
import pytest from tests.common.utils import raises, capture_out from hypothesis.internal.compat import print_unicode -from hypothesis.tests.cover.test_stateful import bad_machines @pytest.mark.parametrize( This should just be `from tests.cover.test_stateful import bad_machines` import pytest from tests.common....
codereview_python_data_4603
updated_goal = Goal(target='updated target', value='complete') objective_data.update(dict(name='an updated test objective', description='a test objective that has been updated', - goals=[updated_goal.schema.dump(test_goal)])) return objective_...
codereview_python_data_4604
return '%s(%r)' % (self.__class__.__name__, dict(self.items())) def __str__(self): - return '%s' % (dict(self.items())) class LookupDict(dict): This could be more simply: ``` python def __str__(self): return str(dict(self.items())) ``` This isn't a merge blocker though. return '%s(%r)' ...
codereview_python_data_4610
init_db_connection(app) messybrainz.db.init_db_engine(app.config['MESSYBRAINZ_SQLALCHEMY_DATABASE_URI']) - # Connections to external servers - @app.before_request - def before_reqeust(): - g.kafka = kafka_connection.init_kafka_connection(app.config['KAFKA_CONNECT']) - g.listenstore = li...
codereview_python_data_4619
name: str """Parameter name""" - optional: bool """Whether parameter is OPTIONAL or REQUIRED""" schema_type: s_types.Type Let's use `required: bool` instead for consistency with pointers and the cardinality inference machinery. name: str """Parameter name""" + required: bool "...
codereview_python_data_4620
} def to_query(self): - if self.txid is None and self.output is None: - return None - else: - return [{'transaction_id': self.txid, - 'output_index': self.output}, - {'output_index': self.output, - 'transact...
codereview_python_data_4621
raise TypeError('Data must be either Dask array or dataframe. Got %s.' % str(type(data))) -class _LGBMModel: def _fit(self, model_factory, X, y, sample_weight=None, group=None, client=None, **kwargs): if not all((DASK_INSTALLED, PANDAS_INSTALLED, SKLEARN_INSTALLED)): raise LightGBMEr...
codereview_python_data_4622
builds() - that is, a tuple of values and a dict of names: values. """ try: - spec = getfullargspec( - target.__init__ if inspect.isclass(target) and '__init__' in target.__dict__ else target) except TypeError: # pragma: no cover return None # self appears in the arg...
codereview_python_data_4623
response = self.client.get(creation_url) self.assertEqual(response.status_code, 200) - if sys.version_info[0] >= 3: - # Python 3: 'strings' - expected_re = b'^<html>.+<title>Events</title>.+Something happened.+<td>\\[&#39;foo&#39;, &#39;bar&#39;\\]</td>.+</html>$' - ...
codereview_python_data_4624
for i in range(num_samples): grads0 = tf.constant(db_grad[i]) cg_opt.apply_gradients(zip([grads0], [var0])) - np.allclose(np.array(db_out[i]), var0.numpy()) @pytest.mark.usefixtures("maybe_run_functions_eagerly") ```suggestion np.testing.assert_allclose(np.array(db_out[i]), var0.numpy())...
codereview_python_data_4627
@api_bp.route('/2.0/', methods=['POST', 'GET']) @ratelimit() -@api_listenstore_needed def api_methods(): """ Receives both (GET & POST)-API calls and redirects them to appropriate methods. """ data = request.args if request.method == 'GET' else request.form method = data['method'].lower() if...
codereview_python_data_4629
logger = logging.getLogger() logger.info('load model from: {}'.format(pretrained)) - @auto_fp16(apply_to=('img', )) def forward_test(self, imgs, img_metas, **kwargs): for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]: if not isinstance(var, list): This ...
codereview_python_data_4636
@staticmethod def test_PDB_atom_repr(): - u = mda.Universe(PDB) # should execute without error u.atoms[0].__repr__() Can we use one of the cheaper PDB universes? This is 47k atoms iirc @staticmethod def test_PDB_atom_repr(): + u = mda.Universe(PDB_small) # ...
codereview_python_data_4649
_base_ = '../fcos/fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py' -img_norm_cfg = dict( - mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) model = dict( pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( This will not change the real img_norm_cfg used during training and tes...
codereview_python_data_4663
kwargs['proposals'] = kwargs['proposals'][0] return self.simple_test(imgs[0], img_metas[0], **kwargs) else: - assert imgs[0].size(0) == 1, 'aug test does not support batch ' \ - 'inference' # TODO: support test augmen...
codereview_python_data_4665
class UnicodeProcessRunner(UnicodeProcessRunnerMixin, ProcessRunner): """ProcessRunner which always returns unicode output.""" - - def run_and_wait(self, *args, **kwargs): # pylint: disable=arguments-differ - """Overridden run_and_wait which always decodes the output.""" - result = ProcessRunner.run_and_wai...
codereview_python_data_4668
return {'new_feat': h} -class GraphOp(nn.Module): """ The Transition Down Module """ def __init__(self, in_channels, out_channels, n_neighbor=64): - super(GraphOp, self).__init__() self.frnn_graph = KNNGraphBuilder(n_neighbor) self.message = KNNMessage(n_neighbor) ...
codereview_python_data_4669
help='The schema of the graph') parser.add_argument('--num-parts', required=True, type=int, help='The number of partitions') parser.add_argument('--num-node-weights', required=True, type=int, help='The number of node weights used by METIS.') parser.add_a...
codereview_python_data_4674
logger = logging.getLogger() logger.setLevel(logging.INFO) -# Define a list of lambdas that are called by our Lambda. ACTIONS = { 'square': lambda x: x * x, 'square root': lambda x: math.sqrt(x), ...of **Lambda functions** that are....our **Lambda function** logger = logging.getLogger() logger.setLevel...
codereview_python_data_4676
A dictionary containing the keys 'name' and 'ident' which are mapped to the 'name' and 'id' node elements in cyjs format. All other keys are ignored. Default is `None` which results in the default mapping - ``{name="name", ident="id"}``. Returns ------- Should this be ``if a...
codereview_python_data_4678
self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} # send cat ids to the get img id # in case we only need to train on several classes - if self.custom_classes: - self.img_ids = self.get_imgs_by_cat(catIds=self.cat_ids) - else: - self.img...
codereview_python_data_4682
mock_issue = self._make_mock_issue() issue_filer.update_issue_impact_labels(self.testcase, mock_issue) - six.assertCountEqual(self, ['Security_Impact-ExtendedStable'], mock_issue.labels.added) six.assertCountEqual(self, [], mock_issue.labels.removed) Can you update the funct...
codereview_python_data_4687
class _Action(_Token): - code: str = None - help: str = None @classmethod def make(klass, s, loc, toks): A bit adjacent to this PR, is there a particular use case for this? class _Action(_Token): + code: ClassVar[str] + help: ClassVar[str] @classmethod def make(klass, s, loc, toks):
codereview_python_data_4689
e_repr = np.zeros((4, 5)) n_repr[[1, 3]] = 1 e_repr[[1, 3]] = 1 - n_repr = F.zerocopy_from_numpy(n_repr) - e_repr = F.zerocopy_from_numpy(e_repr) g.ndata['a'] = n_repr g.edata['a'] = e_repr Why change this? F.zeros should enable allocating the tensors on GPU for the corresponding unit te...
codereview_python_data_4692
# limitations under the License. """Wrapper for Admin Directory API client.""" -from httplib2 import HttpLib2Error from googleapiclient import errors from google.cloud.forseti.common.gcp_api import _base_repository from google.cloud.forseti.common.gcp_api import api_helpers Why is this under httplib2? Should be ...
codereview_python_data_4696
cloudsql_acl.ssl_enabled) should_raise_violation = ( - (is_instance_name_violated is not None and\ - is_instance_name_violated) and\ - (is_authorized_networks_violated is not None and\ is_authorized_networks_violated) and ...
codereview_python_data_4697
overwrite_path_rvar: bool=False, pull_namespace: bool=True, flavor: str='normal', - aspects: Optional[Collection[str]]=None, ctx: context.CompilerContextLevel) -> pgast.PathRangeVar: """Ensure that *rvar* is visible in *stmt* as a value/source aspect. Alas, `Collection[s...
codereview_python_data_4701
create_node_and_not_start): node = create_node_and_not_start req_entry = build_txn_for_revoc_def_entry_by_default - req_handler = node.init_domain_req_handler() req_handler.apply(Request(**req_entry), int(time.time())) with pytest.raises(InvalidClientRequest, match="must be equal to the ...
codereview_python_data_4704
# TODO: Reactor LIMITED_API struct decl closer to the static decl code.putln("#if CYTHON_COMPILING_IN_LIMITED_API") code.putln('typedef struct {') - code.putln('PyObject *__pyx_CyFunctionType;') - code.putln('PyObject *__pyx_FusedFunctionType;') code.putln('PyObject *%s...
codereview_python_data_4705
worker_count: int = 4, head_node_type: str = None, worker_node_type: str = None, - conda_environment: list = None, ): """ Prepare the cluster manager. It needs to know a few things: I would suggest renaming to `add_conda_packages` or smth similar worke...
codereview_python_data_4712
super(CloudProvisioning, self).startup() self.client.start_taurus(self.test_id) self.log.info("Started cloud test: %s", self.client.results_url) - if not self.detach and self.client.results_url: if self.browser_open in ('start', 'both'): open_browser(self....
codereview_python_data_4713
(r"/settings", Settings), (r"/clear", ClearAll), (r"/options", Options), - (r"/options/dump", DumpOptions) ] settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), Really no strong opinion, just curious - why...
codereview_python_data_4714
def test_requests_history_is_saved(self): r = requests.get('https://httpbin.org/redirect/5') - count = 0 for item in r.history: - assert len(item.history) == count - count = count + 1 class TestContentEncodingDetection(unittest.TestCase): Can we make this test a bit...
codereview_python_data_4722
def random_id(stream_arn, kinesis_shard_id): - if six.PY2: - kinesis_shard_id = kinesis_shard_id.encode('utf-8') namespace = uuid.UUID(bytes=hashlib.sha1(stream_arn.encode('utf-8')).digest()[:16]) - return uuid.uuid5(namespace, kinesis_shard_id).hex def shard_id(stream_arn, kinesis_shard_id): Can w...
codereview_python_data_4723
self.cloudsql_instance = '{}-{}'.format( 'forseti-security', self.datetimestamp) - self.cloudsql_region = kwargs.get('cloudsql_region') or 'us-central1' # forseti_conf_server.yaml.in properties self.sendgrid_api_key = kwargs.get('sendgrid_api_key') After disc...
codereview_python_data_4731
An HDF5 daily pricing file. """ return cls({ - country: HDF5DailyBarReader(h5_file[country]) for country in h5_file.keys() }) Should we use `HDF5DailyBarReader.from_file()`? An HDF5 daily pricing file. """ return cls({ + ...
codereview_python_data_4732
total = self.squared_sum - self.sum * mean raw_scores = 1 - (self.res / total) raw_scores = tf.where( - tf.equal(raw_scores, float("-inf")), tf.zeros_like(raw_scores), raw_scores ) if self.multioutput == "raw_values": Probably you could use ``` raw_scores = tf.wh...
codereview_python_data_4733
for name, info in executors.items(): for e in name.split(','): encoded_test = b64encode(info['command'].strip().encode('utf-8')) - creates_fact_relationship = dict(property1=ab['relationships'].split(',')[0].strip(), -...
codereview_python_data_4735
class Impact(object): """Represents impact on a build type.""" - def __init__(self, - version='', - likely=False, - extra_trace='', - milestone_only=False): self.version = str(version) self.likely = likely self.extra_trace = extra_trace - se...
codereview_python_data_4736
passed value. """ for feature in self.features.values(): - try: # If the feature has the attribute, set it to the passed value setattr(feature, attr, value) - except AttributeError: - pass # For backwards compatib...
codereview_python_data_4749
def __init__(self, filename, **kwargs): super(XYZReader, self).__init__(filename, **kwargs) - - # the filename has been parsed to be either be foo.xyz or foo.xyz.bz2 by - # coordinates::core.py so the last file extension will tell us if it is - # bzipped or not - if util.isstre...
codereview_python_data_4772
return [qresult] def _unique_hit_id(self, hit_id, existing_ids, separator='_'): - """Return a unique hit id. (PRIVATE). Always append a numeric id to each hit as there may be multiple with the same id. """ Minor, but you can remove the full stop after "id" here. return ...
codereview_python_data_4773
return st.just(param.default) # If there's no annotation and no default value, we check against a table # of guesses of simple strategies for common argument names. - if "string" in param.name: return st.text() for strategy, names in _GUESS_STRATEGIES_BY_NAME: if param.name ...
codereview_python_data_4792
# # Skeleton file for the Python "Bob" exercise, to get you coding more quickly. # -def hey(stimulus) return Could we have a less interesting argument name than `stimulus`? I'm worried that if we provide a name that is already good, people won't spend any time thinking about it themselves. Maybe something as ter...
codereview_python_data_4793
return res class CircularLR_beta(LR_Updater): - ''' - ??? highly unsure ??? - CLR learning rate updater, but not using pct percentage of data. - ''' def __init__(self, layer_opt, nb, div=10, pct=10, on_cycle_end=None, momentums=None): self.nb,self.div,self.pct,self.on_cycle_end = nb...
codereview_python_data_4796
}, { 'source': 'gs://bucket-dbg/projects.json', - 'suffix': '_dbg', 'build_type': 'FUZZ_TARGET_BUILD_BUCKET_PATH', 'build_buckets': { 'afl': 'clusterfuzz-builds-afl-dbg', suffix feels too generic ? maybe na...
codereview_python_data_4812
@hook def receive_menu(self, menu, addrs, wallet): - keystore = wallet.get_keystore() if len(addrs) != 1: return for keystore in wallet.get_keystores(): This line is no longer needed as the loop below overwrites the value of `keystore`. @hook def receive_menu(...
codereview_python_data_4817
i.split(split_by_first)[-1].split(split_by_second)[-1], ] ) - for i in content.split("+ python3 -m pytest -n=48 ") ) if len(full_comment) > 65_000: full_comment = full_comment[-65_000:] + "\n\n<b>Remaining output truncated<b>\n\n" Is it possible not to h...
codereview_python_data_4826
formatted='Server is throttling, reconnecting in {:d} seconds'.format(wait_time) ) time.sleep(wait_time) -# sys.exit() except PermaBannedException: bot.event_manager.emit( 'api_error', should be re...
codereview_python_data_4834
'atime': atime, 'redirect': redirect}) - if any(pattern.matches(url) - for pattern in config.val.history.exclude): - return if redirect: return self.completion.insert({ ...
codereview_python_data_4848
props.merge(self._get_load_props()) props.merge(self._get_scenario_props()) for key in sorted(props.keys()): - if isinstance(props[key], string_types): - self.env.add_java_param({"JAVA_OPTS": "-D%s='%s'" % (key, props[key])}) - else: - self....
codereview_python_data_4851
assert contents == ref_contents(fnames[index]) -alias_batch_size=64 -@pipeline_def(batch_size=alias_batch_size, device_id=0, num_threads=4) def file_pipe(file_op, file_list): files, labels = file_op(file_list=file_list) return files, labels I think that in general a smaller batch_size would do ...
codereview_python_data_4858
access_target = None target_id = None user_can_grant_roles = True - firewall_rules_to_be_deleted = ["default-allow-icmp", "default-allow-internal", "default-allow-rdp", "default-allow-ssh"] def __init__(self, config, previous_installer=None): """Init. This exceeds the 80-char limiit. Yo...
codereview_python_data_4860
self.app_svc.application.router.add_route('POST', '/file/upload', self.upload_exfil_http) async def get_endpoint_by_access(self, request, endpoint): - allowed = [p for p in await self.auth_svc.get_permissions(request) if p in self.modules] - for a in allowed: try: - ...
codereview_python_data_4862
cmdutils.check_overflow(new_idx, 'int') self._tabbed_browser.tabBar().moveTab(cur_idx, new_idx) - @cmdutils.register(instance='command-dispatcher', scope='window', - debug=True) @cmdutils.argument('choice', completion=miscmodels.suggest) def suggest(self, command: st...
codereview_python_data_4870
response = self.client.datasets().get(projectId=dataset.project_id, datasetId=dataset.dataset_id).execute() if dataset.location is not None: - fetched_location = response.get('location', '') - if not fetched_locat...
codereview_python_data_4871
return getattr(self._handle, attr) def __enter__(self): - """Open File handle with WITH statement.""" return self def __exit__(self, type, value, traceback): - """Close File handle with WITH statement.""" self._handle.close() Repetitive use of the word 'with' here and...
codereview_python_data_4877
max_clique = max(max_clique,len(clique)) return max_clique - 1 def chordal_simplicial_vertex(G): """Returns the simplicial vertex of the chordal graph G. - Parameters ---------- G : graph Use the decorator `@not_implemnted_for('directed','multigraph')` here. This will raise `Networ...
codereview_python_data_4885
GTTGCTTCTGGCGTGGGTGGGGGGG <BLANKLINE> """ - in_mode = "rb" if in_format in _BinaryFormats else "rU" out_mode = "wb" if out_format in _BinaryFormats else "w" I believe `"rU"` should be `"r"`. GTTGCTTCTGGCGTGGGTGGGGGGG <BLANKLINE> """ + in_mode = "rb" if in_format in _BinaryForm...
codereview_python_data_4889
self._on_msg(self.decode(msg)) -class SimpleJupyterComm(Comm): """ - SimpleJupyterComm provides a Comm for simple unidirectional communication from the python process to a frontend. The Comm is opened before the first event is sent to the frontend. """ How about calling it `JupyterP...
codereview_python_data_4892
f.write('value = 1\n') - # The number of dependencies should be 2: "a.pxd" and "a.pyx" - self.assertEqual(2, len(dep_tree.all_dependencies(a_pyx))) # Cythonize to create a.c fresh_cythonize(a_pyx) So, why not check for the two file names instead of just their count? ...
codereview_python_data_4903
try: avg_size_of_message //= num_of_messages except ZeroDivisionError: current_app.logger.warn("No messages calculated", exc_info=True) current_app.logger.info("Done!") If you get to this line avg_size_of_message is an undefined value, yet you use it below. You you ...
codereview_python_data_4905
no_cmd_split: If true, ';;' to split sub-commands is ignored. backend: Which backend the command works with (or None if it works with both) - no_replace_variables: Whether or not to replace variables like {url} _qute_args: The saved data from @cmdutils.argument ...
codereview_python_data_4906
default value of ``False``. """ def __init__(self, *args, **kwargs): super(BoolParameter, self).__init__(*args, **kwargs) if self._default == _no_value: self._default = False What is the importance of `nargs` and `const`? default value of ``False``. """ + imp...
codereview_python_data_4911
def main(): """ Main function """ - pub = '9RaWxppkP9UyYWA7NJb5FcgkzfJNPfvPX3FCNw2T5Pwb' asset = Asset(None, 'e6969f87-4fc9-4467-b62a-f0dfa1c85002') - tx = Transaction.create([pub], [([pub], 1)], asset=asset) tx_json = json.dumps(tx.to_dict(), indent=2, sort_keys=True) base_path = os.path.joi...
codereview_python_data_4916
@staticmethod def get_file_handler(file_name): file_fmt = Formatter("[%(asctime)s %(levelname)s %(name)s] %(message)s") - file_handler = logging.FileHandler(file_name) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(file_fmt) return file_handler Why c...
codereview_python_data_4925
def authenticate_presign_url_signv4(method, path, headers, data, url, query_params, request_dict): # Calculating Signature - LOGGER.debug('Calculating the version 4 signature.') aws_request = create_request_object(request_dict) ReadOnlyCredentials = namedtuple('ReadOnlyCredentials', ...
codereview_python_data_4926
# IO of PDB files (including flexible selective output) from .PDBIO import PDBIO, Select -from .MMCIFIO import MMCIFIO - # Some methods to eg. get a list of Residues # from a list of Atoms. from . import Selection Is this needed? The ``Bio.PDB`` module already does too many automatic imports (and name shadowing) ...
codereview_python_data_4935
def test_percentchange(self, seed_value, window_length): pct_change = PercentChange( - inputs=(), window_length=window_length, ) I think we still probably want a length-1 list of inputs here rather than an empty tuple. Ideally, we'd use `SingleInputMixin` to require exact...
codereview_python_data_4943
# add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import sphinx from sphinx.errors import VersionRequirementError -import datetime curr_path = os.path.dirname(os.path.realpath(__fil...
codereview_python_data_4953
def __init__(self, mode): super(CornerPool, self).__init__() assert mode in self.pool_functions - if torch.__version__ >= '1.5.0': - self.corner_pool = self.cummax_dim_flip[mode] - else: - self.corner_pool = self.pool_functions[mode] def forward(self, x): ...
codereview_python_data_4960
self.is_rnn = isinstance(self.layer, tf.keras.layers.RNN) if self.data_init and self.is_rnn: - print( - "WeightNormalization: Using `data_init=True` with RNNs is not advised" - ) def build(self, input_shape): """Build `Layer`""" Might be better to us...
codereview_python_data_4966
def handle_put_rule(data): schedule = data.get('ScheduleExpression') - enabled = True - if data.get('State') and data.get('State') == 'DISABLED': - enabled = False if schedule: job_func = get_scheduled_rule_func(data) nitpick: lines 85-87 could be simplified to: ``` enabled = data.get(...
codereview_python_data_4967
__all__ = ['gsddmm', 'copy_u', 'copy_v', 'copy_e'] def reshape_lhs_rhs(lhs_data, rhs_data): - r""" Reshape the dimension of lhs and rhs data Parameters ---------- can you give an example of the output shape? it seems you add a new dimension in the tensor, but the value of the added dimension isn't 1. ...
codereview_python_data_4972
""" proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme if proxy: proxy_scheme = urlparse(proxy).scheme You conditionally create `proxy_scheme` but unconditionally reference it here unless my coffee hasn't kicked in. Shouldn't this block loo...
codereview_python_data_4978
# Initalizing THttpClient may raise an exception if proxy settings # are used but the port number is not a valid integer. pass - finally: - # Thrift do not handle the use case when invalid proxy format is - # used (e.g.: no schema is specified). For th...
codereview_python_data_4981
G = nx.cycle_graph(7) C = [[0, 1, 6], [0, 1, 5]] b = nx.group_betweenness_centrality( - G, C, weight=None, endpoints=False, normalized=False ) b_answer = [0.0, 6.0] assert b == b_answer Do you need to put `endpoints=False` on these tests? It is the defau...
codereview_python_data_4983
"""Get machine ID""" return self._machine_id - @property - def num_clients(self): - """Get total number of clients""" - return self._num_clients - def barrier(self): """Barrier for all client nodes. is this necessary? we can call rpc.get_num_client to get the number ...
codereview_python_data_4986
with tf.compat.v1.Session() as sess: sess.run(initializers) - try: for _ in range(iterations): dataset_results.append(sess.run(ops_to_run)) - except tf.errors.OutOfRangeError: - if to_stop_iter: - return dataset_results - els...
codereview_python_data_4994
-# Copyright 2016 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. this is already in consensus/poet/core/sawtooth_poet/journal/block_wrapper.py isn't it? +# Copyright 2018 Intel Corporation # # Licensed under...
codereview_python_data_4995
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4458-SEA 1645545158 1857731548</p> <hr> <p>Varnish cache server</p> </body> User `Timer` instead? Though I understand the time measured this way is correct in end-to-end se...
codereview_python_data_5000
# filter and crop the masks if 'gt_masks' in results: valid_gt_masks = [] - for i, is_valid in enumerate(valid_inds): - if is_valid: - gt_mask = results['gt_masks'][i] - valid_gt_masks.append( - ...
codereview_python_data_5009
'stream parameter of the same name' % v) return mapping - def _listener(self, *events): self._memoize = not any(e.type == 'triggered' for e in events) self.trigger([self]) self._memoize = True I think it might be clearer if this method were called ...
codereview_python_data_5018
else: raise TypeError('eval_sample_weight, eval_class_weight, eval_init_score, and eval_group should be dict or list') valid_weight = get_meta_data(eval_sample_weight, i) - if self.class_weight is not None: ...
codereview_python_data_5032
"hyperframe>=5.0, <6", "jsbeautifier>=1.6.3, <1.7", "kaitaistruct>=0.7, <0.8", - "ldap3>=2.2.0, <2.2.1", "passlib>=1.6.5, <1.8", "pyasn1>=0.1.9, <0.3", "pyOpenSSL>=16.0, <17.1", Is there any issue with 2.2.3? If not this should be `<2.3`. "hyperf...
codereview_python_data_5039
'%s%s' % (constants.COLLECT_DATA_FLOW_FLAG, dataflow_binary_path)) fuzzing_strategies.append(strategy.DATAFLOW_TRACING_STRATEGY.name) else: - logs.log_warn('Fuzz target is not found in dataflow build.') # DataFlow Tracing requires fork mode, always use it with DFT strategy. if use_data...
codereview_python_data_5040
params = dict(get_param_values(element), kdims=[x, y], datatype=['xarray'], bounds=bounds) - if self.vdim_prefix is not None: kdim_list = '_'.join(str(kd) for kd in params['kdims']) vdim_prefix = self.vdim_prefix.format(kdims=kdim_list) else: No...
codereview_python_data_5054
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4479-SEA 1645523384 2894604451</p> <hr> <p>Varnish cache server</p> </body> Instead of `success`, this should be more clear as `is_success`, so that we can avoid something ...
codereview_python_data_5059
Inquirer()._ethereum = ethereum @staticmethod - def is_cache_valid(cache: CachedPriceEntry) -> bool: - return ts_now() - cache.time <= CURRENT_PRICE_CACHE_SECS @staticmethod def set_oracles_order(oracles: List[CurrentPriceOracle]) -> None: Since you went ahead and made a function then...
codereview_python_data_5066
self.logger.info("Not a valid room url.") return - if room["status"] != 4: - self.logger.info("Stream current unavailable.") return hls_url = "http://dlhls.cdn.zhanqi.tv/zqlive/{room[videoId]}_1024/index.m3u8?Dnion_vsnae={room[videoId]}".format(room=room...
codereview_python_data_5083
from future import standard_library standard_library.install_aliases() -from urllib import parse from config import db_config from datastore import data_handler we usually do "import urllib.parse" in other places so that a generic parse function can't conflict. from future import standard_library standard_libra...
codereview_python_data_5094
## Load our local_settings try: SETTINGS_MODULE = os.environ['GRAPHITE_SETTINGS_MODULE'] -except: SETTINGS_MODULE = 'graphite.local_settings' try: Agreed with Codacy here - please specify exception type here ## Load our local_settings try: SETTINGS_MODULE = os.environ['GRAPHITE_SETTINGS_MODULE'] +except...
codereview_python_data_5099
name = models.CharField(_('Name'), max_length=255, db_index=True) description = models.TextField(_('Description'), blank=True) - meta_title = models.CharField(_('Meta Title'), max_length=255, db_index=True) meta_description = models.TextField(_('Meta Description'), blank=True) image = models.Imag...
codereview_python_data_5104
else: msg = f'Unexpected {token.text()!r}' elif rule == 'for iterator': - msg = ("Complex expressions in a FOR query must be " - "parenthesized") if i > 0: context = ...
codereview_python_data_5105
def _format_msg(msg: str) -> str: """Convert message to HTML suitable for rendering.""" - ret = msg - ret = html.escape(ret) - ret = ret.strip() - ret = ret.replace('\n', '<br />') - return ret def javascript_confirm(url, js_msg, abort_on): Why not use `msg` directly below? def _format_msg(msg:...