id
stringlengths
24
28
content
stringlengths
121
2.08k
codereview_python_data_6437
for ace_contig in Ace.parse(source): # Convert the ACE contig record into a SeqRecord... consensus_seq_str = ace_contig.sequence - # Assume its DNA unless there is a U in it, - molecule_type = "DNA" - if "U" in consensus_seq_str and "T" not in consensus_seq_str: - ...
codereview_python_data_6442
assert not bias assert in_channels % groups == 0, \ - f'in_channels {in_channels} cannot be divisible by groups {groups}' assert out_channels % groups == 0, \ - f'out_channels {out_channels} cannot be divisible ' \ f'by groups {groups}' self.in_chan...
codereview_python_data_6446
The value of each BigchainDB Server configuration setting is determined according to the following rules: -* If it’s set by an environment variable, then use that value -* Otherwise, if it’s set in a local config file, then use that value * Otherwise, use the default value (contained in ``bigchaindb.__init__`...
codereview_python_data_6452
self.barrier() shape = list(shape) # One of the clients in each machine will issue requests to the local server. - if self._client_id % part_policy.partition_book.num_partitions() == 0: part_shape = shape.copy() part_shape[0] = part_policy.get_data_size() ...
codereview_python_data_6453
# See the License for the specific language governing permissions and # limitations under the License. # -from .getter import get_config from .cfg_parser import LuigiConfigParser from .toml_parser import LuigiTomlParser -__all__ = ['get_config', 'LuigiConfigParser', 'LuigiTomlParser'] Shouldn't these dates includ...
codereview_python_data_6461
'B' * config.FILE_TRANSFER_CHUNK_SIZE + 'C' * (config.FILE_TRANSFER_CHUNK_SIZE / 2)) -TEST_BUCKET_BUNDLE = 'cf_test_bundle' def _dirs_equal(dircmp): nit: maybe just bundle-bucket to match others ? 'B' * config.FILE_TRANSFER_CHUNK_SIZE + ...
codereview_python_data_6463
def calculate(self, basket): base_charge = self.method.calculate(basket) - discount = self.offer.shipping_discount(base_charge.excl_tax, basket.currency) excl_tax = base_charge.excl_tax - discount return prices.Price( currency=base_charge.currency, I think passing `b...
codereview_python_data_6467
-import os, sys, math, time, uuid, json, warnings from unittest import SkipTest -import numpy as np - -from matplotlib import pyplot as plt -from matplotlib.backends.backend_nbagg import CommSocket, new_figure_manager_given_figure try: import IPython Have you tested this with IPython 3? As we sure this will be ...
codereview_python_data_6470
def abbreviate(words): - regex = '[A-Z]+[\'a-z]*|[\'a-z]+' return ''.join(word[0].upper() for word in re.findall(regex, words)) Again, switching to double quotes for this string literal removes the need for escaping apostrophes. def abbreviate(words): + regex = "[A-Z]+['a-z]*|['a-z]+" return ''.join...
codereview_python_data_6475
'Unable to read artifact definitions from: {0:s} with error: ' '{1!s}').format(custom_artifacts_path, exception)) - setattr(configuration_object, '_artifacts_registry', registry) setattr(configuration_object, '_artifact_definitions_path', artifacts_path) setattr( configur...
codereview_python_data_6477
self.log = logging.getLogger('') self.prev_errors = BetterDict() self.cur_errors = BetterDict() - self.treat_errors = True def _get_err_diff(self): # find diff of self.prev_errors and self.cur_errors can we refactor out this if-else? looks too nested... self.lo...
codereview_python_data_6481
def get_container_network_for_lambda(): global LAMBDA_CONTAINER_NETWORK - if not config.LAMBDA_DOCKER_NETWORK and LAMBDA_CONTAINER_NETWORK is None: try: if config.is_in_docker: networks = DOCKER_CLIENT.get_networks(bootstrap.get_main_container_name()) tiny nit: We could ...
codereview_python_data_6482
# - deck_cost is a computable based on sum # - count also has cardinality 1 of the return set <int64>(F.deck_cost / count(F.deck)) ); ''', [ [ Missing `LIMIT 1` # - deck_cost is a...
codereview_python_data_6488
Does validations common to vmSettings and ExtensionsConfig """ if self._status_upload_blob_type not in ["BlockBlob", "PageBlob"]: - logger.info("Status Blob type '{0}' is ot valid, assuming BlockBlob", self._status_upload_blob) self._status_upload_blob_type = "BlockBlo...
codereview_python_data_6497
from __future__ import print_function import tensorflow as tf -from tensorflow.python.framework import tensor_shape # TODO: better import? EPSILON = 0.0000000001 I'd suppose we could access the static shape directly, and thus, there is no need to import `tensor_shape`. Like ```python if train.shape[-1] is None: ``...
codereview_python_data_6498
class SeqFileRandomAccess(_IndexedSeqFileProxy): - """Random Access File generic.""" def __init__(self, filename, format, alphabet): """Initialize the class.""" How about something more like this?: ``Base class for defining random access to sequence files.`` class SeqFileRandomAccess(_IndexedSeqFil...
codereview_python_data_6499
for i in range(len(other)): - # TODO: If we don't need to reindex, don't. It is expensive. - # The challenge with avoiding reindexing is that we need to make sure that - # the internal indices line up (i.e. if a drop or a select was just - # performed, the internal i...
codereview_python_data_6504
from .. import utils __all__ = [ - 'random_walk'] -def random_walk(g, nodes, *, metapath=None, length=None, prob=None): """Generate random walk traces from an array of seed nodes (or starting nodes), based on the given metapath. Give a simple code example in the docstring. from .. import utils __all_...
codereview_python_data_6507
verbose = 0 -standard_include_path = os.path.abspath(os.path.normpath( - os.path.join(os.path.dirname(__file__), os.path.pardir, 'Includes'))) class Context(object): # This class encapsulates the context needed for compiling I don't think you need `os.path.normpath` here. verbose = 0 +standard_include...
codereview_python_data_6512
assert(np.array_equal(outputs, reference)) def test_one_hot_operator(): for i in range(10): premade_batch = [np.array([np.random.randint(0, sample_size)], dtype=np.int32) for x in range(sample_size)] yield check_one_hot_operator, premade_batch I think it would be good to set `np.random.see...
codereview_python_data_6513
slow_step_size: A floating point value. The ratio for updating the slow weights. name: Optional name for the operations created when applying - gradients. Defaults to "RectifiedAdam". **kwargs: keyword arguments. Allowed to be {`clipnorm`, ...
codereview_python_data_6517
self.scanner_configs.get('output_path')): os.makedirs(output_path) output_path = os.path.abspath(output_path) - base_scanner.upload_csv(output_path, now_utc, output_csv_name) # Send summary email. ...
codereview_python_data_6520
def loss_single(self, cls_score, bbox_pred, labels, label_weights, bbox_targets, bbox_weights, num_total_samples, cfg): # classification loss - if self.use_sigmoid_cls: - labels = labels.reshape(-1, 1) - label_weights = label_weights.reshape(-1, 1) - ...
codereview_python_data_6530
n = len(line) idx = int(line[0]) - 1 if n in (7, 10): - x, y, z = map(float, line[4:7]) elif n in (6, 9): - x, y, z = map(float, line[3:6]) - pos[idx] = x, y, z def _parse_vel(self, datalines, vel): """Strip veloc...
codereview_python_data_6535
network = network_and_project.group(2) if not network_interface.access_configs: - LOGGER.warn('Network interface: %s, doesn\'t ' 'have access_configs.', network_interface.full_name) continue I would like...
codereview_python_data_6541
def framewise(self): """ Property to determine whether the current frame should have - framewise normalization enabled. """ current_frames = [el for f in self.traverse(lambda x: x.current_frame) for el in (f.traverse(lambda x: x, [Element]) Doc...
codereview_python_data_6545
decl = attr_type.cpp_optional_declaration_code(attr.cname) else: decl = attr_type.declaration_code(attr.cname) - if attr.utility_code_definition: - type.scope.use_utility_code(attr.utility_code_definition) code.putln("%s;" % decl) ...
codereview_python_data_6548
>>> ag.groupby('resnames', 'masses')['ALA'][15.999] <AtomGroup with 19 atoms> - .. versionadded:: """ res = {} The version number disappeared here. Also, you should add a line indicating that the function changed in version 0.18.0: ``` .. versionchanged:: 0.18.0 The fun...
codereview_python_data_6557
# perform the analysis iteratively? # # To address the evolution of the graphs, you generate a variety of graph samples. In other words, you need -# **generative models** of graphs. Instead of and/or, in-addition to learning # node and edge features, you would need to model the distribution of arbitrary graphs. # ...
codereview_python_data_6558
# This prevents a race condition between two threads deserializing functions # and trying to import pandas at the same time. def import_pandas(*args): - import pandas ray.worker.global_worker.run_function_on_all_workers(import_pandas) Can you please change the line like t...
codereview_python_data_6561
return ''.join(map(lambda s: s.decode('utf-8'), file_object.readlines())) def build_tracking_url(self, logs_output): return logs_output def run(self): Sorry for going back and forth. Adding docstring here would be very helpful for others to understand the need of this method. retu...
codereview_python_data_6562
f_elems = str(elems) else: f_elems = f"[{elems[0]}, {elems[1]}, ..., {elems[-2]}, {elems[-1]}]" - types = tuple({type(e) for e in elems}) f_types = f"type {types[0]}" if len(types) == 1 else f"types {types}" rais...
codereview_python_data_6565
content_type='text/html') LOGGER.debug('Inventory summary sent successfully by email.') except util_errors.EmailSendError: - LOGGER.exception('Unable to send Violations email') @staticmethod def transform_to_template(data): This is the invent...
codereview_python_data_6571
self.dialect.load(file_to_convert) base_script = {"scenarios": {}, EXEC: []} self.log.debug("Processing thread groups...") tg_etree_elements = self.dialect.tree.findall(".//ThreadGroup") - tg_etree_elements.extend(self.dialect.tree.findall(".//com.blazemeter.jmeter.threads.con...
codereview_python_data_6572
return float(tokens.number.scientific[0]) elif tokens.string: - return unicode(tokens.string)[1:-1] elif tokens.boolean: return tokens.boolean[0] == 'true' Just `return tokens.string[1:-1]` is enough return float(tokens.number.scientific[0]) elif tokens.string: + return tokens.string...
codereview_python_data_6576
relevant_facts.append(variable_facts) return relevant_facts @staticmethod async def _build_single_test_variant(copy_test, clean_test, combo): """ really good PR idea here & nice clean approach to your code. two things i think it could use: 1) at line 81, since we're starting to...
codereview_python_data_6578
"""Redis result store backend.""" from __future__ import absolute_import, unicode_literals -import threading from functools import partial from ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from kombu.utils.functional import retry_over_time from kombu.utils.objects import cached_property Please ensure impor...
codereview_python_data_6587
norm_eval=True, dcn=None, stage_with_dcn=(False, False, False, False), - plugin=None, - stage_with_plugin=(False, False, False, False), with_cp=False, zero_init_residual=True): super(ResNet...
codereview_python_data_6611
@property def is_reactant(self): - """Return true if this Entry participate in any reaction in its parent pathway.""" for rxn in self._pathway.reactions: if self._id in rxn.reactant_ids: return True Can you change this to: ```python """Return true if this Entry p...
codereview_python_data_6613
default_profile = QWebEngineProfile.defaultProfile() init_user_agent() - manager = notification.DBusNotificationManager() - manager.set_as_presenter_for(default_profile) default_profile.setter = ProfileSetter( # type: ignore[attr-defined] default_profile) This would probably fit better i...
codereview_python_data_6621
'create', help='Start a new inventory') create_inventory_parser.add_argument( - 'import_as', metavar=('MODEL_NAME',), - nargs='?', help='Import the inventory when complete, requires a model name') create_inventory_parser.add_argument( '--background', ...
codereview_python_data_6627
-from __future__ import absolute_import - import pytest from pontoon.tags.models import Tag Why do you need this? import pytest from pontoon.tags.models import Tag
codereview_python_data_6628
logGroupName='/aws/lambda/{}'.format(function_name) ) - try: - return rs['logStreams'][0]['logStreamName'] - except Exception: - raise def get_event_message(events): nit: I think we can remove this `try-except` check here. logGroupName='/aws/lambda/{}'.format(function_name)...
codereview_python_data_6629
def compactHash(string): hash = md5() - hash.update(string.encode('unicode_escape')) return hash.hexdigest() `string.encode('utf-8')` is more common but I guess this is mostly cosmetic :) def compactHash(string): hash = md5() + hash.update(string.encode('utf-8')) return hash.hexdigest()
codereview_python_data_6630
# # from stp_core.loop.eventually import eventually # from plenum.common.util import randomString # from plenum.test.test_node import checkNodesConnected # from plenum.test.node_catchup.helper import checkNodeLedgersForEquality # Please remove the test if it isn't needed anymore # # from stp_core.loop.eventua...
codereview_python_data_6639
recommendation_top_artist_limit, recommendation_similar_artist_limit) - ti = time.monotonic() - messages = get_recommendations_for_all(params, users, ti) # persisted data must be cleared from memory after usage to avoid OOM recordings...
codereview_python_data_6643
def update_symbolizer_options(tool_options, symbolize_inline_frames=False): """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( ...
codereview_python_data_6649
return RateLimiter(FLAGS.max_admin_api_calls_per_day, self.DEFAULT_QUOTA_TIMESPAN_PER_SECONDS) - def get_group_members(self, group): """Get all the members for specified groups. Args: - groups: A group key, e.g. it's email address. Returns: ...
codereview_python_data_6651
in the array :attr:`RMSD.rmsd`. .. versionchanged:: 1.0.0 - ``save()`` method was removed, use ``np.savetxt()`` on :attr:`rmsd` - instead. """ def __init__(self, atomgroup, reference=None, select='all', Should the references point explicitly to the class (e.g. :attr:`RMSD.rmsd` rather t...
codereview_python_data_6652
def _email_error(self, task, formatted_traceback, subject, headline): formatted_subject = subject.format(task=task, host=self.host) - command = ' '.join("'{}'".format(arg) for arg in sys.argv) message = notifications.format_task_error(headline, task, command, formatted_traceback) ...
codereview_python_data_6657
import time def SoftRelationPartition(edges, n, threshold=0.05): - """This partitions a list of edges based in to n partitions that - SMALL relations (which has only small number of edges) will be put - into a single LARGE partition (relations with large number of edges) - will be evenly divided into a...
codereview_python_data_6662
class InsertStmt(MutatingStmt): - on_conflict: typing.Optional[typing.List[PointerRef]] = None class UpdateStmt(MutatingStmt, FilteredStmt): SQL `ON CONFLICT` accepts constraint names as conflict targets, let's use a constraint object directly. I suggest adding a `ConstraintRef` to IR: ```python class ConstraintR...
codereview_python_data_6663
self.get_organization() self.check_billing_enabled() self.has_permissions() - self.get_host_project() self.enable_apis() This method name might be better as ```check_network_host_project_id()```. I know that other methods here also uses ```get``` naming, but I opened issue #8...
codereview_python_data_6670
step_time = int(load.ramp_up / load.steps) thread_groups = jmx.tree.findall(".//ThreadGroup") for thread_group in thread_groups: - thread_cnc = int(thread_group.find(".//stringProp[@name='ThreadGroup.num_threads']").text) tg_name = thread_group.attrib["testname"] ...
codereview_python_data_6674
rule_bigquery_acl.role: bigquery_acl.role, } - return all([ - re.match(rule_regex, acl_val) - for (rule_regex, acl_val) in rule_regex_to_val.iteritems() - ]) # TODO: The naming is confusing and needs to be fixed in all scanners. def find_policy_violati...
codereview_python_data_6681
else: self.bot.sniper_disabled_global_warning = False targets = [] - target = {} # Retrieve the targets if self.mode == SniperMode.SOCIAL: Seems nowhere to use 'target' in the following code. else: self.bot.sniper_disabled_g...
codereview_python_data_6682
sockdir, dir_stat.st_uid, dir_stat.st_mode)) print('sockfile: {} / owner {} / mode {:o}'.format( sockfile, file_stat.st_uid, file_stat.st_mode)) - # pylint: enable=no-member,useless-suppression assert file_owner_ok or dir_owner_ok assert file_mode_ok or dir_mo...
codereview_python_data_6692
Raises: ApiExecutionError: ApiExecutionError is raised if the call to the GCP API fails """ try: nit: purely a matter of personal taste, it would be nicer if the `location` condition is first to make its precedence more clear; the condition also seems simpler to...
codereview_python_data_6704
.. Note:: This option does not perform a true mass weighting but weighting by the number of atoms in each residue; the name of the parameter exists for historical reasons and will - be removed in 0.17.0. .. SeeAlso:: :class:`GNMAnalysis` shou...
codereview_python_data_6708
import subprocess import posixpath import functools -from xml.etree import ElementTree from PyQt5.QtWebKit import QWebSettings from PyQt5.QtWidgets import QApplication, QTabBar I'd prefer just `import xml.etree` here and then using `xml.etree.ElementTree` etc. so it's clear which module this is coming from. imp...
codereview_python_data_6712
Returns: bool: True if using a composite root, else False. """ - return bool(not self.root_resource_id) def get_root_resource_id(self): """Return the configured root resource id. nit: not self.root_resource_id is a boolean so the casting is not be needed. R...
codereview_python_data_6721
POSTGRES_ADMIN_URI="postgresql://postgres@db/template1" -# Other postgres configuration options -# Oldest listens which can be stored in the database, in days. -MAX_POSTGRES_LISTEN_HISTORY = "-1" -# Log Postgres queries if they execeed this time, in milliseconds. -PG_QUERY_TIMEOUT = "3000" -# Set to True to enable 'sy...
codereview_python_data_6723
'FORSETI_BUCKET': bucket_name[len('gs://'):], 'BUCKET_LOCATION': self.config.bucket_location, 'GCP_CLIENT_SERVICE_ACCOUNT': self.gcp_service_acct_email, - 'FORSETI_TARGET': 'forseti-target: "{}"'.format(self.branch), 'FORSETI_SERVER_ZONE': self.server_zone ...
codereview_python_data_6726
if labels.numel() == 0: return bboxes, labels - out_bboxes, keep = batched_nms(bboxes[:, :4], bboxes[:, -1].contiguous(), labels, cfg.nms_cfg) out_labels = labels[keep] To be on the safe side, it is best to add contiguous to bboxes. ...
codereview_python_data_6727
TODO: Memory tracking """ try: - extension_slice_name = SystemdCgroupsApi.get_extension_cgroup_name(extension_name) + ".slice" cgroup_relative_path = os.path.join('azure.slice/azure-vmextensions.slice', - ...
codereview_python_data_6729
class BigQueryTarget(luigi.target.Target): def __init__(self, project_id, dataset_id, table_id, client=None, location=None, enable_chunking=False, chunk_size_gb=1000): self.table = BQTable(project_id=project_id, dataset_id=dataset_id, table_id=table_id, location=location) self.client = client or...
codereview_python_data_6735
self._default_cuda_stream_priority) self._pipe.SetExecutionTypes(self._exec_pipelined, self._exec_separated, self._exec_async) self._pipe.SetQueueSizes(self._cpu_queue_size, self._gpu_queue_size) - self._pipe.EnableOperatorOutputMemoryStatistics(self._get_memory...
codereview_python_data_6736
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4421-SEA 1645542567 1515473453</p> <hr> <p>Varnish cache server</p> </body> if you're going to do this inline you may as well use kwargs <h1>Error 503 Backend is unhe...
codereview_python_data_6737
class DistOptimizerHook(OptimizerHook): """Deprecated optimizer hook for distributed training""" - pass We may raise a warning. class DistOptimizerHook(OptimizerHook): """Deprecated optimizer hook for distributed training""" + + def __init__(self, *args, **kwargs): + warnings.warn( + ...
codereview_python_data_6741
import bigchaindb from bigchaindb.consensus import AbstractConsensusRules -# logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) CONFIG_DEFAULT_PATH = os.environ.setdefault( This should be removed if not used import bigchaindb from bigchaindb.consensus import AbstractConsensusRules lo...
codereview_python_data_6743
self.s = Seq.UnknownSeq(6) self.u = Seq.Seq(None, length=6) def test_unknownseq_construction(self): self.assertEqual("??????", Seq.UnknownSeq(6)) self.assertEqual("NNNNNN", Seq.UnknownSeq(6, character="N")) What scope does this have? i.e. side effects after this class has been ...
codereview_python_data_6747
-_base_ = ['deformable_detr_r50_8x2_50e_coco.py'] model = dict(bbox_head=dict(with_box_refine=True)) directly use string rather than list[str] +_base_ = 'deformable_detr_r50_8x2_50e_coco.py' model = dict(bbox_head=dict(with_box_refine=True))
codereview_python_data_6748
Input tensor dictionaries reducer : str or callable function One of "sum", "max", "min", "mean", "stack" or a callable function. - If a callable function is provided, the input arguments is a list of tensors - from cross types, and the output of function must be a single tensor ...
codereview_python_data_6756
row['run_count'] } bigquery_data.append(big_query.Insert(row=bigquery_row, insert_id=None)) if bigquery_data: client = big_query.Client( dataset_id='main', table_id='fuzz_strategy_experiments') client.insert(bigquery_data) def _query_and_upload_strategy_probabilities(): Do...
codereview_python_data_6763
] ]) - @unittest.expectedFailure - async def test_edgeql_scope_tuple_08(self): await self.assert_query_result(r''' # compare to test_edgeql_scope_filter_03 to see how it # works out without tuples `FILTER` should refer to `_.1.name` and this will pass. ...
codereview_python_data_6767
try: os.makedirs(os.path.dirname(self._filename)) except OSError as e: - # Unlikely, but could be created before - # we get a chance to create it. - if e.errno != errno.EEXIST: - raise self.basename = os.path.basename(self._filename...
codereview_python_data_6769
capping_ace = resource_filename(__name__, "data/capping/ace.pdb") capping_nma = resource_filename(__name__, "data/capping/nma.pdb") -contacts_villin_folded = resource_filename(__name__, "data/contacts/villin_folded.gro") -contacts_villin_unfolded = resource_filename(__name__, "data/contacts/villin_unfolded.gro") con...
codereview_python_data_6777
``p_components``, ``cumulated_variance`` will not sum to 1. ``align=True`` now correctly aligns the trajectory and computes the correct means and covariance matrix. - - .. versionchanged:: 0.19.0 - The start frame is used when performing selections and calculating - mean positions...
codereview_python_data_6792
value = so.SchemaField( str, compcoef=0.909) - # Overloaded to mark it as not inheritable, since I found it - # basically impossible to get the inherited behavior to work right - # otherwise. - final = so.SchemaField( - bool, - inheritable=False, - compcoef=0.909, - ) -...
codereview_python_data_6800
@pytest.mark.parametrize('number_of_eth_accounts', [0]) def test_data_import_shapeshift_trades(rotkehlchen_api_server): - """Test that the data import endpoint works successfully for blockfi trades""" rotki = rotkehlchen_api_server.rest_api.rotkehlchen dir_path = Path(__file__).resolve().parent.parent ...
codereview_python_data_6801
level with shape (N, num_anchors * 4, H, W) img_metas (list[dict]): Meta information of each image, e.g., image size, scaling factor, etc. - imgs (list[torch.Tensor]): List of multiple images cfg (mmcv.Config | None): Test / postprocessing configura...
codereview_python_data_6809
if __name__ == "__main__": from Bio._utils import run_doctest run_doctest(verbose=0) You'd need to expand the existing example in order to make it a self-contained doctest, this alone will fail: ``` python >>> model = structure[0] >>> fm = FragmentMapper(model, lsize=10, flength=5, dir="fragment_data") >>> ...
codereview_python_data_6817
schema: s_schema.Schema ) -> s_types.Type: from . import types as s_types - source = self.get_source(schema) - if not isinstance(source, s_types.Type): - raise TypeError('Source is expected to be a Type') return source def compare( Let's use an `assert` s...
codereview_python_data_6818
@qutescheme.add_handler('testdata') def handler(url): # pylint: disable=unused-variable file_abs = os.path.abspath(os.path.dirname(__file__)) - filename = os.path.join(file_abs, '..', 'end2end', url.path().lstrip('/')) with open(filename, 'rb') as f: ...
codereview_python_data_6821
def test_tf_dataset_mismatched_input_type(): input_dataset = tf.data.Dataset.from_tensors(np.full((2, 2), 42)).repeat() - for wrong_input_dataset in ["str", [input_dataset], input_dataset]: - for wrong_input_name in [42, ["a"]]: - yield check_tf_dataset_mismatched_input_type, wrong_input_data...
codereview_python_data_6823
''' G = nx.Graph() G.add_edge('a', 'b') - assert_equal(list(bridges(G)), [('a', 'b')]) def test_twoDisconnectedComponents(self): ''' I would delete this line, so that the tests work on Python 3.x as well. ''' G = nx.Graph() G.add_edge('a', 'b'...
codereview_python_data_6826
"%(status_filter)s") paginate_by = 25 description = '' - actions = ('download_selected_orders',) current_view = 'dashboard:order-list' - order_actions = ('save_note', 'delete_note', 'change_order_statuses', 'create_order_payment_event') def dispatch...
codereview_python_data_6828
kms_master_key_id = long_uid() sse_specification = {"Enabled": True, "SSEType": "KMS", "KMSMasterKeyId": kms_master_key_id} - kms_master_key_arn = "arn:aws:kms:%s:%s:key/%s" % ( - aws_stack.get_local_region(), - TEST_AWS_ACCOUNT_ID, - kms_master_key_id, - ...
codereview_python_data_6832
ExpandInplaceOperators(context), IterationTransform(context), SwitchTransform(context), - OptimizeBuiltinCalls(context), CreateClosureClasses(context), ## After all lookups and type inference CalculateQualifiedNamesTransform(context), ConsolidateOverflowChec...
codereview_python_data_6833
self._edges = edges self._arange = arange self._bins = bins - self.results = Results() self.results.density = None def _single_frame(self): This line can be removed since `AnalysisBase` already initializes the results attribute. self._edges = edges sel...
codereview_python_data_6836
:return: Tuple (activity_id, correlation_id, gs_created_timestamp) or "NA" for any property that's not available """ - def parse_value(parse_fn, value): try: if value not in (None, ""): Rather than logging "NA" for None, empty string or unparsable time we should j...
codereview_python_data_6838
no_visible_projects = locale.project_set.visible().count() == 0 - has_projects_to_request = projects.visible().exclude(locales=locale).count() > 0 if not projects: raise Http404 Why use `.visible()` here? Above you'll see that `projects` already includes `Project.objects.visible()`. no_visi...
codereview_python_data_6848
# If we are not able to query properly, draw randomly according to # probability parameters. if not distribution: - logs.log('Cannot use weighted strategy pool. Generating default strategy pool.') return generate_default_strategy_pool() # Change the distribution to a list of named tuples rather than...
codereview_python_data_6850
# REALLY Needs to use columns! print(fmt % (fill_exact_width(_("ID"), 6, 6), fill_exact_width(_("Action(s)"), 14, 14), - fill_exact_width(P_("Package", "Package", 1), 53, 53))) print("-" * 79) fmt = "%6u | %s | %-50s" num = 0 should...
codereview_python_data_6852
Returns: A FuzzOptions object. """ - executable_path = environment.get_value('FUZZER_EXECUTABLE_PATH') - arguments = [executable_path] - return engine.FuzzOptions(corpus_dir, arguments, {}) # TODO(mbarbella): As implemented, this will not work for untrusted workers. # We would need to co...
codereview_python_data_6867
command line by setting the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables. - The project ARN is determined by the PROJECT_ARN environment variable. """ devicefarm_client = boto3.client("devicefarm") project_arn = os.environ.get("PROJECT_ARN", None) ARN -...
codereview_python_data_6869
def event_report(self): for event, (color, parameters) in self._registered_events.iteritems(): - print '-'*80 - print 'Event: {}'.format(event) if parameters: print 'Parameters:' for parameter in parameters: There is still this print an...
codereview_python_data_6870
break # pylint: enable=compare-to-zero - print 'XXX: Returning violations: %r' % violations return violations I realize this might be for debugging purposes, but would you like to turn this into a LOGGER.debug at some point? break # pylint: e...
codereview_python_data_6871
def _cmp_key(self): """Unique key for the object to be used to generate the object hash""" # This key must be equal for two object considered as equal by __eq__ - return '_'.join(map(str, sorted(self.indices))) def __hash__(self): """Makes the object hashable""" I don't thin...
codereview_python_data_6876
from MDAnalysisTests.datafiles import (COORDINATES_XTC, COORDINATES_TOPOLOGY) -@pytest.mark.raises(exception=ValueError) def test_get_bad_auxreader_format_raises_ValueError(): # should raise a ValueError when no AuxReaders with match the specified format - mda.auxiliary.core.get_auxreader_for(format='bad-form...