language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
input_dummy, input_lengths, spec, spec_lengths, waveform, aux_input={"speaker_ids": speaker_ids, "language_ids": lang_ids}, ) self._check_forward_outputs(config, output_dict, speaker_encoder_config) def _check_inference_outputs(self, confi...
Review this code and list any quality issues.
[]
0
python
return deployment_to_replicas_to_stop def _schedule_with_pack_strategy(self): """Tries to schedule pending replicas using PACK strategy.""" # Flatten dict of deployment replicas into all replicas, # then sort by decreasing resource size all_scheduling_requests = sorted( ...
Review this code and list any quality issues.
[ { "issue": "Should `node_to_running_replicas` be updated to include the `target_node` when we return from `_pack_schedule_replica` below? If it's not in the `node_to_running_replicas` mapping prior to the below for loop, it's not included in the non-idle nodes when we check `if len(node_to_running_replicas.get(...
1
python
def _run_process(self)->bool: try: is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0]) if is_ffmpeg: self.process = subprocess.Popen( self.cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, ...
Review this code and list any quality issues.
[]
0
python
_API_URL = 'https://api.bili{}/intl/gateway{}' def _call_api(self, type, endpoint, id): return self._download_json(self._API_URL.format(type, endpoint), id)['data'] def _get_subtitles(self, type, ep_id): sub_json = self._call_api(type, f'/m/subtitle?ep_id={ep_id}&platform=web', ep_id) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n video_info = vid.get('stream_info') or {}\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from packaging import version as pkg_version import torch def required_torch_version(min_version=None, max_version=None): assert min_version or max_version, "Must provide a min_version or max_version argument" to...
Review this code and list any quality issues.
[]
0
python
})), } class IdagioRecordingIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?app\.idagio\.com/recordings/(?P<id>[0-9]+)($|\?(?!trackId=[0-9]+))' _TESTS = [{ 'url': 'https://app.idagio.com/recordings/30576934', 'info_dict': { 'id': '30576934', 'title': 'Varia...
Review this code and list any quality issues.
[ { "issue": "If the recording info is mandatory, we can make this fatal\r\n```suggestion\r\n recording_id = self._match_id(url)\r\n recording_info = self._download_json(\r\n f'https://api.idagio.com/v2.0/metadata/recordings/{recording_id}',\r\n recording_id)['result']\r\n```",...
1
python
return cls.from_patterns( patterns, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config ) @classmethod def from_patterns( cls, patterns: List[str], base_path: Optional[str] = None, allowed_extensions: Optional[List[str]...
Review this code and list any quality issues.
[ { "issue": "The `glob` module has the `has_magic` method (public, but not documented IIRC; e.g., `fsspec` uses it) to check this:\r\n```suggestion\r\n if has_magic(pattern):\r\n```\r\n\r\nBut feel free to decide which one you prefer.", "severity": "minor", "line": 26 } ]
1
python
for img_data_prev, img_data in zip(frames_prev, frame_data): assert np.sum(np.abs(img_data_prev - img_data) > np.finfo(np.float32).eps) > DIFF_TOL * img_data.size frames_prev = frame_data # Add current frame to monitor video rgb_debug, *_ = cam_debug.render(rgb=True, depth=False...
Review this code and list any quality issues.
[ { "issue": "I guess (128, 128) should be good enough?", "severity": "minor", "line": 26 } ]
1
python
local_ds.xyz.append([3, 4, 5]) expected_tensor_diff_from_a["xyz"]["data_added"] = [0, 1] local_ds.rename_tensor("xyz", "efg") expected_dataset_diff_from_a["renamed"]["xyz"] = "efg" expected_tensor_diff_from_a["efg"] = expected_tensor_diff_from_a.pop("xyz") local_ds.rename_tensor(...
Review this code and list any quality issues.
[]
0
python
BACKEND_AUTO = "auto" E_MISSING_RULES = 10 E_MISSING_FILE = 11 E_INVALID_RULE = 12 E_CORRUPT_FILE = 13 E_FILE_LIMITATION = 14 E_INVALID_SIG = 15 E_INVALID_FILE_TYPE = 16 E_INVALID_FILE_ARCH = 17 E_INVALID_FILE_OS = 18 E_UNSUPPORTED_IDA_VERSION = 19 E_UNSUPPORTED_GHIDRA_VERSION = 20 E_MISSING_CAPE_STATIC_ANALYSIS = 21 ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n processes: Set[int]\r\n functions: Set[int]\r\n```\r\n\r\nindexing `set` as a type hint was added in Python 3.9, whereas we still support 3.8 for a little longer.\r\nhttps://docs.python.org/3/library/typing.html#typing.Set", "severity": "minor", "line": 26 } ]
1
python
async def process_pipeline_check( dataset: Dataset, data: list[Data], pipeline_name: str ) -> [None, PipelineRunStarted, PipelineRunCompleted]: """ Function used to determine if pipeline is currently being processed or was already processed. In case pipeline was or is being processed return value is ret...
Review this code and list any quality issues.
[ { "issue": "The else case assigns a list to task_status and here we access it like a dict. I mean probably never gonna happen but still. Am not 100% familiar what do we do in the case of the fallback (I assume we skip this whole if and just return None btu then why do we even need an else. Why not initialiting ...
1
python
self.interfaces.append(a2a_interface) self._add_router(app, a2a_interface.get_router()) def _check_duplicate_ids( self, entities: Optional[List[Any]], ) -> None: """Check for duplicate IDs in a list of entities. Args: entities: List of agents, teams, or ...
Review this code and list any quality issues.
[ { "issue": "better to let the entities initialize and then check for duplicates, because\n\n1. the logic there could change, outdating this bit\n2. we would now be running this id generation stuff twice in the happy path, no need", "severity": "major", "line": 26 } ]
1
python
""" if self._provider_response_id is not None: # pragma: no cover self.provider_response_id = self._provider_response_id chunk: ConverseStreamOutputTypeDef tool_id: str | None = None async for chunk in _AsyncIteratorWrapper(self._event_stream): match chunk: ...
Review this code and list any quality issues.
[ { "issue": "`download_item` currently has logic gating for `gs://` URLs; let's check `s3://` URLs there as well", "severity": "minor", "line": 26 } ]
1
python
super().__init__() def config(self, **kwargs): """ configuration of data. # what data to be loaded from data source This method will be used when loading pickled handler from dataset. The data will be initialized with different time range. """ attr_list = {...
Review this code and list any quality issues.
[ { "issue": "` it will do nothing for the second time` is no longer the right docs", "severity": "minor", "line": 26 } ]
1
python
f([0]*3, axis=None) def test_empty(self): for f, tgt_value in zip(self.nanfuncs, [0, 1]): mat = np.zeros((0, 3)) tgt = tgt_value*np.ones((0, 3)) res = f(mat, axis=0) assert_equal(res, tgt) tgt = mat res = f(mat, axis=1) ass...
Review this code and list any quality issues.
[]
0
python
example 1. json.decoder.JSONDecodeError: Expecting ',' delimiter: line 154 column 1 (char 2765) example 2. xxx.JSONDecodeError: Expecting property name enclosed in double quotes: line 14 column 1 (char 266) """ pattern = r"line ([0-9]+) column ([0-9]+)" matches = re.findall(pattern, error, re.DOTAL...
Review this code and list any quality issues.
[ { "issue": "since you have removed comments in the repair pipeline in `repair_json_format` , there is no need to do it again here.", "severity": "minor", "line": 26 } ]
1
python
if decimal_only: # dont use scientific notation. final_amount = f"{amount / scale:.12f}" else: final_amount = f"{amount / scale}" ret = f"{final_amount} {address_prefix} " if scale > 1: ret += f"({amount} mojo)" return ret async def print_balances( root_path: pathlib.Path,...
Review this code and list any quality issues.
[]
0
python
@pytest.mark.usefixtures("_patch_for_completion") def test_context_settings(runner): def complete(ctx, param, incomplete): return ctx.obj["choices"] cli = Command("cli", params=[Argument("x", shell_complete=complete)]) result = runner.invoke( cli, obj={"choices": ["a", "b"]}, ...
Review this code and list any quality issues.
[ { "issue": "This is a risky move.\r\n\r\nBy clearing `_available_shells` you are clearing also all the pre-defined shells that's in there before the test.\r\n\r\nA better way to go is to:\r\n1. Save the previous content of `_available_shells` in a separted list\r\n2. Clear `_available_shells`\r\n3. Run the test...
1
python
# if no skip events are available, a 403 xml error is returned skip_events = self._download_json( f'https://static.crunchyroll.com/skip-events/production/{internal_id}.json', internal_id, note='Downloading chapter info', fatal=False, errnote=False) if not skip_events: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n display_id, note='Downloading stream info', headers=CrunchyrollBaseIE._AUTH_HEADERS)\r\n```", "severity": "critical", "line": 26 } ]
1
python
if changed is not Changed.CACHED and format_file_in_place( src, fast=fast, write_back=write_back, mode=mode ): changed = Changed.YES if (write_back is WriteBack.YES and changed is not Changed.CACHED) or ( write_back is WriteBack.CHECK and changed i...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n worker_count: int = os.cpu_count(),\r\n```\r\n\r\nThis way we could just explicitly send in the worker_count as an argument.\r\n\r\nOnly worry is potentially people using the API could break - so a default argument helps there ...", "severity": "minor", "line": 26 } ]
1
python
node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err]) # both specified, also ok prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"] node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err]) # redeemScript mismatch to witnessScript prevt...
Review this code and list any quality issues.
[ { "issue": "For readability\r\n```suggestion\r\n full_signed_tx = node2.combinerawtransaction([rawtx2[\"hex\"], rawtx3[\"hex\"]])\r\n```", "severity": "minor", "line": 26 } ]
1
python
"""Raise a FixtureLookupError exception. :param msg: An optional custom error message. """ raise FixtureLookupError(None, self, msg) def getfixturevalue(self, argname: str) -> Any: """Dynamically run a named fixture function. Declaring fixtures via function arg...
Review this code and list any quality issues.
[ { "issue": "It's now also used in `pytest_fixture_setup` :)", "severity": "minor", "line": 26 } ]
1
python
response_cookies[context.session.id] = response_data.get('cookies') if context.request.user_data.get('retire_session'): context.session.retire() await crawler.run( [ # The first request sets the cookie in the session str(server_url.with_path('set_cookies').exten...
Review this code and list any quality issues.
[]
0
python
The rendered RGB image(s). depth_arr : np.ndarray The rendered depth image(s). seg_arr : np.ndarray The rendered segmentation mask(s). normal_arr : np.ndarray The rendered surface normal(s). """ rgb_arr, depth_arr, seg_arr, seg_color_arr, norma...
Review this code and list any quality issues.
[ { "issue": "Remove this message, or using debug logging.", "severity": "critical", "line": 26 } ]
1
python
peers_with_tx: dict[bytes32, PeerWithTx] = field(default_factory=dict, compare=False) done: ValuedEvent[tuple[MempoolInclusionStatus, Err | None]] = field( default_factory=ValuedEvent, compare=False, ) @dataclass class TransactionQueue: """ This class replaces one queue by using a high...
Review this code and list any quality issues.
[ { "issue": "isn't `_queue_dict` also a map of the same peer IDs?\nIt would seem cheaper and simpler to stick this `int` in that dict instead. Am I missing something?", "severity": "minor", "line": 26 } ]
1
python
jwt = meta.get('jwt') if not jwt: raise ExtractorError('Site did not provide an authentication token, cannot proceed.') media = self._download_json(self._API_BASE.format('getMedia', v_id) + f'&jwt={jwt}', v_id).get('response') formats = [] if media.get('addaptiveMedia', Fal...
Review this code and list any quality issues.
[ { "issue": "```py\r\nurl = ...\r\nif url:\r\n```", "severity": "minor", "line": 26 } ]
1
python
) llm = self.get_llm() # FIXME: In case of iteration, parse_task depends on the context (files, tasks, etc) set there. # Ideally this prompt would be self-contained. convo = ( AgentConvo(self) .template( "iteration", current_task=se...
Review this code and list any quality issues.
[ { "issue": "why do we complete the task if the reviewer added steps?", "severity": "minor", "line": 26 } ]
1
python
if self.registry_lock: with self.registry_lock: self.checksum_registry[key] = checksum self.logger.info( f"[REMOTE_AUDIT][{self.real_connector}]:PUT|SUCCESS|Size:{data_size}|" f"Checksum:{checksum[:8]}|Cost:{cost:.6f}ms|Saved:" ...
Review this code and list any quality issues.
[]
0
python
with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values works best when :math:`a \leq \text{mean} \leq b`. Args: tensor: an n-dimensional `torch.Tensor` mean: the mean of the normal distribution std: the standard d...
Review this code and list any quality issues.
[ { "issue": "Adding a reference of this \"Attention\" here.\r\nI suggest naming it \"RelativePositionAttention\".", "severity": "minor", "line": 26 } ]
1
python
""" # %% # Array API support # ----------------- # In scikit-learn 1.8, several estimators and functions have been updated to # support array API compatible inputs, for example PyTorch tensors and CuPy arrays. # # Array API support was added to the following estimators: # :class:`preprocessing.StandardScaler`, :class:...
Review this code and list any quality issues.
[ { "issue": "That's a good idea. We could prepare such a notebook against a nightly build of scikit-learn and update it after the release to point to the stable wheels instead.", "severity": "minor", "line": 26 } ]
1
python
if key_id is None: # Try to extract key_id from the token's header try: jwe_obj = jwcrypto_jwe.JWE() jwe_obj.deserialize(token) protected_header = json.loads(jwe_obj.objects['protected']) key_id = protected_header.get('kid') ...
Review this code and list any quality issues.
[ { "issue": "🔴 **CRITICAL - Data Structure**: You deserialize the token here to extract `kid`, then throw away the `jwe_obj` and deserialize it AGAIN on line 232. This is wasteful and shows you did not think about the data flow.\n\n**Why it matters:** Deserialization is not free. You parse the JWE structure, ba...
1
python
We build a chain that includes and invalid signature for one of the transactions: 0: genesis block 1: block 1 with coinbase transaction output. 2-101: bury that block with 100 blocks so the coinbase transaction output can be spent 102: a block containing a transactio...
Review this code and list any quality issues.
[ { "issue": "nit:\r\n```suggestion\r\n - node5 starts with no -assumevalid parameter. Reindex to deterministically hit\r\n \"assumevalid hash not in headers\" and \"below minimum chainwork\".\r\n```", "severity": "minor", "line": 26 } ]
1
python
expected, msg, path, 'element', ) @assert_equal.register(np.ndarray, np.ndarray) def assert_array_equal(result, expected, path=(), msg='', array_verbose=True, array_decimal=No...
Review this code and list any quality issues.
[ { "issue": "Hmm. One thing we might want to handle here is if result and expected are both datetime dtype, but have different units. I'm not sure if we'd want those to compare the same.", "severity": "minor", "line": 26 } ]
1
python
return_view: bool = False, ) -> Union[Dict, DeepLakeDataset]: """Generalized search algorithm that uses indra. It combines vector search and other TQL queries. Args: query_embedding (Optional[Union[List[float], np.ndarray): embedding representation of the query. distance_metric (str): Distance ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n try:\r\n from indra import api # type: ignore\r\n INDRA_INSTALLED = True\r\n except ImportError:\r\n INDRA_INSTALLED = False\r\n pass\r\n```\r\n\r\nthen on line 64 do this:\r\n```\r\nif not INDRA_INSTALLED:\r\n raise ImportError(\"this is enter...
1
python
slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"] ), format_tools=ToolFormatter(tool_format="qwen"), default_system="You are a helpful assistant.", stop_words=["<|im_end|>"], replace_eos=True, mm_plugin=get_mm_plugin(name="qwen2_vl", im...
Review this code and list any quality issues.
[ { "issue": "I think we also need a non-thinking template for qwen3vl. WDYT?", "severity": "minor", "line": 26 } ]
1
python
half = (size[0] * 0.5, size[1] * 0.5) verts = np.array( [ [-half[0], -half[1], 0.0], [half[0], -half[1], 0.0], [half[0], half[1], 0.0], [-half[0], -half[1], 0.0], [half[0], half[1], 0.0], [-half[0], half[1], 0.0], ], dty...
Review this code and list any quality issues.
[ { "issue": "Same. I would rather export `x` and `y` components. More readable I think.", "severity": "minor", "line": 26 } ]
1
python
df_new = pd.DataFrame(data) df_existing = self.handler._read_file(self.dropbox_path) df_combined = pd.concat([df_existing, df_new], ignore_index=True) self.handler._write_file(self.dropbox_path, df_combined) class DropboxHandler(APIHandler): name = "dropbox" supported_file_formats = [...
Review this code and list any quality issues.
[ { "issue": "Maybe wrap this in try/except to catch some specific Auth errors?", "severity": "critical", "line": 26 } ]
1
python
def include_paths(self): includes = ['csrc/cpu/includes'] return includes def cxx_args(self): return ['-O2', '-fopenmp'] def is_compatible(self, verbose=False): # TODO: add soft compatibility check for private binary release. # a soft check, as in we know it can be tri...
Review this code and list any quality issues.
[ { "issue": "`machine` should be a member of `CPUOpBuilder`. Suggest to define `machine` in `CPUOpBuilder`, then use `super().machine` where `self.machine` is used.", "severity": "minor", "line": 26 } ]
1
python
def docstring_with_inline_tabs_and_space_indentation(): """hey tab separated value tab at start of line and then a tab separated value multiple tabs at the beginning and inline mixed tabs and spaces at beginning. next line has mixed tabs and spaces only. line ends with ...
Review this code and list any quality issues.
[]
0
python
return FireworksProvider elif provider == 'together': from .together import TogetherProvider return TogetherProvider elif provider == 'heroku': from .heroku import HerokuProvider return HerokuProvider elif provider == 'huggingface': from .huggingface import HuggingF...
Review this code and list any quality issues.
[ { "issue": "Should we also add this to `infer_model` so the user can do `Agent('litellm:<model name>')`?", "severity": "minor", "line": 26 } ]
1
python
return process_transformers_v5_panoptic_segmentation_result( segmentation_array, id2label ) return process_transformers_v5_semantic_or_instance_segmentation_result( segmentation_result, id2label ) def process_transformers_v5_semantic_or_instance_segmentation_result( segmentati...
Review this code and list any quality issues.
[]
0
python
comment_list = [] for page in itertools.count(1): comments_json = self._call_api(vid, data={ 'operationName': 'getCommentList', 'variables': { 'params': { 'appInfo': { 'postID': vid, ...
Review this code and list any quality issues.
[ { "issue": "Since comment extraction needs extra requests, move it into `_get_comments` and return `'__post_extractor': self.extract_comments(...)`", "severity": "major", "line": 26 } ]
1
python
lookat=(0.0, 0.0, 0.5), fov=45, GUI=False, ) scene.add_light( pos=[0.0, 0.0, 1.5], dir=[1.0, 1.0, -2.0], directional=1, castshadow=1, cutoff=45.0, intensity=0.5, ) scene.build() # Cre...
Review this code and list any quality issues.
[ { "issue": "Remove all the comments. This test is simple. No need to explain what is going on.", "severity": "minor", "line": 26 } ]
1
python
strict : bool Should failure to load an extension raise. If this is false it will still warn. environ : mapping The environment to use to find the default extension path. reload : bool, optional Reload any extensions that have already been loaded. """ if default: ...
Review this code and list any quality issues.
[]
0
python
with console.status("Analyzing program...", spinner="dots"): bv: BinaryView = binaryninja.load(str(input_path)) if bv is None: raise RuntimeError(f"Binary Ninja cannot open file {input_path}") return capa.features.extractors.binja.extractor.BinjaFeatureExtractor(bv) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n with console.status(\"analyzing program...\", spinner=\"dots\"):\r\n```", "severity": "minor", "line": 26 } ]
1
python
assert [[3], [], [], [1, 1]] == _generate_per_block_split_indices( [3, 3, 3, 1], [3, 10, 10] ) assert [[], [], [], []] == _generate_per_block_split_indices([3, 3, 3, 1], []) def _create_meta(num_rows): return BlockMetadata( num_rows=num_rows, size_bytes=None, input_files=No...
Review this code and list any quality issues.
[]
0
python
detections (Detections): Object detections to annotate. custom_color_lookup (Optional[np.ndarray]): Custom color lookup array. Allows to override the default color mapping strategy. Returns: The annotated image, matching the type of `scene` (`numpy.ndarray` ...
Review this code and list any quality issues.
[ { "issue": "This is a lot of logic for a small change.\r\n\r\nA more efficient method involve using `cv2.polylines`.\r\nThere you can specify thickness and draw another shape behind the original triangle.\r\n\r\nI wouldn't expect to have two very different if-else branches.", "severity": "major", "line"...
1
python
import functools from .common import InfoExtractor from ..utils import ( OnDemandPagedList, extract_attributes, get_element_by_class, get_element_html_by_class, get_element_text_and_html_by_tag, get_elements_html_by_class, int_or_none, join_nonempty, try_call, unified_strdate, ...
Review this code and list any quality issues.
[ { "issue": "Having `/` in the character class defeats the purpose of that group at the end of the pattern. We are not doing a `fullmatch` with this pattern, only a `match`. Also, `|` is not needed inside a character class\r\n```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?radiocomercial\\.pt/podcasts/[^...
1
python
# the dimensions are too large ii = idx % dim[0] jj = idx // dim[0] else: # idx is an array of size of A.shape[ax]; # check the max index to make sure no overflows # we encountered assert np.count_nonzero(idx) == A.nnz ii, jj = np.max(idx), np.argmax(idx) ...
Review this code and list any quality issues.
[ { "issue": "Let's leave a comment here that refers to the related issue.", "severity": "minor", "line": 26 } ]
1
python
mp4_sources = media_sources.get('mp4', {}) for format_id, mp4_url in mp4_sources.items(): if not mp4_url: continue height_str = format_id.split('_')[-1] height = int(height_str) if height_str.isdigit() else None formats.append({ '...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'formats': formats,\r\n 'subtitles': subtitles,\r\n```", "severity": "minor", "line": 26 } ]
1
python
Example: .. code-block:: python import torch from monai.losses import DiceLoss from monai.metrics import LossMetric dice_loss = DiceLoss(include_background=True) loss_metric = LossMetric(loss_fn=dice_loss) # first iteration y_pred = torch.tensor([[[[1.0, 0...
Review this code and list any quality issues.
[]
0
python
discontinuity_count = 0 frag_index = 0 ad_frag_next = False for line in s.splitlines(): line = line.strip() if line: if not line.startswith('#'): if format_index and discontinuity_count != format_index: continue ...
Review this code and list any quality issues.
[]
0
python
else: formats.append({ 'url': stream_url, }) if not formats: if not self.get_param('allow_unplayable_formats') and drm: self.report_drm(video_id) info = { 'id': video_id, 'title': video_id, ...
Review this code and list any quality issues.
[ { "issue": "You are sure this is no longer used by any video?", "severity": "minor", "line": 26 } ]
1
python
) @torch.no_grad() def inference(model_name, model, config, ap, text_input, text_lengths, mel_input, mel_lengths, attn_mask=None, speaker_ids=None, speaker_embeddings=None): if model_name == "glow_tts": mel_input = mel_input.permute(0, 2, 1) # B x D x T speaker_c = None if speaker_ids is no...
Review this code and list any quality issues.
[ { "issue": "you can replace these lines with `*_`", "severity": "minor", "line": 26 } ]
1
python
get_pyarrow_version() < parse_version("20.0.0"), reason="with_column requires PyArrow >= 20.0.0", ) def test_cast_expression_multiple_types( ray_start_regular_shared, target_max_block_size_infinite_or_default ): """Test casting with multiple different target types.""" ds = ray.data.from_items([{"id": 42...
Review this code and list any quality issues.
[ { "issue": "Please ensure to use `rows_same`", "severity": "minor", "line": 26 } ]
1
python
if all_data: users_query = select(User) users = (await session.execute(users_query)).scalars().all() users_ids = [u.id for u in users] user_count = len(users_ids) dataset_count = ( await session.execute(select(func.count()).select_from(Da...
Review this code and list any quality issues.
[ { "issue": "Let's simplify this.\n\nSince `all_data` means everything will be deleted, you can just get the total counts of users/datasets/data without doing things like querying for datasets for a given user.", "severity": "major", "line": 26 } ]
1
python
scene.build() cam1.read() cam2.read() shared_metadata = cam1._shared_metadata offscreen_renderer = shared_metadata.renderer._renderer offscreen_renderer_ref = weakref.ref(offscreen_renderer) scene.destroy() assert shared_metadata.renderer is None assert shared_metadata.sensors is None...
Review this code and list any quality issues.
[ { "issue": "I don't think adding this is relevant.", "severity": "minor", "line": 26 } ]
1
python
'url': 'https://www.instagram.com/stories/highlights/18090946048123978/', 'info_dict': { 'id': '18090946048123978', 'title': 'Rare', }, 'playlist_mincount': 50, }, { 'url': 'https://www.instagram.com/stories/fruits_zipper/3570766765028588805/', 'only_m...
Review this code and list any quality issues.
[ { "issue": "Let's move these two lines up before the webpage request; we should raise before making a pointless request", "severity": "minor", "line": 26 } ]
1
python
out=stdout, error=sys.stderr, screen=sys.stderr if self.params.get('quiet') else stdout, console=None if compat_os_name == 'nt' else next( filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None) ) try: windows_enable_vt_mode()...
Review this code and list any quality issues.
[ { "issue": "Pls add back the assert. We don't want to support arbitrary values. Also, I don't think `{str}` is needed.", "severity": "minor", "line": 26 } ]
1
python
video_id = self._match_id(url) data = self._download_json( f'https://odkmedia.io/odx/api/v3/playback/{video_id}/', video_id, fatal=False, headers={'service-name': 'odk'}, query={'did': str(uuid.uuid4())}, expected_status=(403, 404)) if not traverse_obj(data, ('result', {dict})):...
Review this code and list any quality issues.
[ { "issue": "On second look, I think it'd be better to keep the network requests out of the traversal:\r\n```suggestion\r\n formats = []\r\n for m3u8_url in traverse_obj(data, (('sources', 'manifest'), ..., 'url', {url_or_none}, {try_geo_bypass}):\r\n formats.extend(self._extract_m3u8_fo...
1
python
Example: ```python >>> import supervision as sv >>> cd = sv.ClassificationDataset.from_multiclass_folder_structure( ... root_directory_path="./dataset", ... ) """ classes = os.listdir(root_directory_path) classes = list(set(classe...
Review this code and list any quality issues.
[ { "issue": "You can calculate `classes.index(class_name)` at the top of the first for loop, it will not get changed until next `class_name`.", "severity": "minor", "line": 26 } ]
1
python
def __init__(self, model_name:str=None, progress_bar:bool=True, gpu=False): """🐸TTS python interface that allows to load and use the released models. Args: model_name (str, optional): Model name to load. You can list models by ```tts.models```. Defaults to None. progress_bar (b...
Review this code and list any quality issues.
[ { "issue": "I don't know a good solution, but it would be nice to be able to have that list of model before instantiating that class with the model name.", "severity": "minor", "line": 26 } ]
1
python
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import unittest import torch from pa...
Review this code and list any quality issues.
[]
0
python
#export trial data parser_trial_export = parser_experiment_subparsers.add_parser('export', help='export trial job results to csv or json') parser_trial_export.add_argument('id', nargs='?', help='the id of experiment') parser_trial_export.add_argument('--type', '-t', choices=['json', 'csv'], required=True, d...
Review this code and list any quality issues.
[ { "issue": "I'm a little confused. Where is the old `view`? As far as I remembered, there has already been a `view`.", "severity": "minor", "line": 26 } ]
1
python
payload, lambda x: x['content']['bbcMedia']['playlist'], dict) if bbc3_playlist: playlist_title = bbc3_playlist.get('title') or playlist_title thumbnail = bbc3_playlist.get('holdingImageURL') entries = [] for bbc3_item in bbc3_p...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Extract single video from model structure\"\"\"\r\n```", "severity": "major", "line": 26 } ]
1
python
>>> from sympy.abc import x, y >>> n = Symbol('n') >>> refine_sin_cos(cos(n*pi), Q.even(n)) (-1)**n >>> refine_sin_cos(sin(n*pi/2), Q.odd(n) & Q.odd((n-1)/2)) (-1)**(n/2 - 1/2) >>> refine_sin_cos(sin(x + n*pi/2), Q.odd(n)) (-1)**(n/2 - 1/2)*cos(x) >>> refine_sin_cos(cos(x + n*pi/2), Q.ev...
Review this code and list any quality issues.
[ { "issue": "> integral\n\nUsing this word is confusing here - it would be better to just use \"integer\"", "severity": "minor", "line": 26 } ]
1
python
arr = np.arange(6) check_array(arr) # 1-D, non-contiguous check_array(arr[::2]) # 2-D, C-contiguous arr = np.arange(12).reshape((3, 4)) check_array(arr) # 2-D, F-contiguous check_array(arr.T) # 2-D, non-contiguous check_array(arr[::2]) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n def do_test_concurrent_mutation_in_buffer_callback(self, factory):\n # See: https://github.com/python/cpython/issues/143308.\n```", "severity": "minor", "line": 26 } ]
1
python
self._LOGIN_URL, None, note='Downloading login page', errnote='Downloading login page failed') login_form = self._hidden_inputs(login_page) login_form.update({ '_email': username, '_password': password}) profile_select_html, login_handle = self._download_we...
Review this code and list any quality issues.
[ { "issue": "Use `query` param of _download_webpage_handle", "severity": "minor", "line": 26 } ]
1
python
Build environment dictionary, hiding potentially sensitive information such as passwords or keys. """ hidden_re = re.compile(r'API|TOKEN|KEY|SECRET|PASS', re.I) urlpass_re = re.compile(r'^.*?://[^:]+:(.*?)@.*?$') safe_env = dict(env) for k, v in safe_env.items(): if k == 'AWS_ACCESS_KEY_...
Review this code and list any quality issues.
[ { "issue": "In this case, we should use the existing check `actor.has_obj_perm(self.organization, 'view')` so that standalone remains functional.\r\n\r\nMight do best to move that out of this function, your call.", "severity": "minor", "line": 26 } ]
1
python
assert Asp.pop((0, 1)) == 1 assert d.items() == Asp.items() assert Asp.pop((22, 21), None) is None assert Asp.pop((22, 21), "other") == "other" with pytest.raises(KeyError, match="(22, 21)"): Asp.pop((22, 21)) with pytest.raises(TypeError, match="got an unexpected keyword argument"): ...
Review this code and list any quality issues.
[]
0
python
REAUTH_SCHEMA = vol.Schema( { vol.Required( CONF_ACCESS_TOKEN, ): TextSelector(TextSelectorConfig(type=TextSelectorType.PASSWORD)), } ) EXAMPLE_URL = "https://mastodon.social" def base_url_from_url(url: str) -> str: """Return the base url from a url.""" return str(URL(url)...
Review this code and list any quality issues.
[ { "issue": "Do they need a default value?\n\n```suggestion\n base_url: str\n client_id: str\n client_secret: str\n access_token: str\n```", "severity": "critical", "line": 26 } ]
1
python
node_network: Mapping[NodeId, NodeNetworkInfo], ) -> AsyncGenerator[tuple[str, NodeId], None]: """Yield (ip, node_id) pairs as reachability probes complete.""" send, recv = channel[tuple[str, NodeId]]() # these are intentionally httpx's defaults so we can tune them later timeout = httpx.Timeout(timeou...
Review this code and list any quality issues.
[ { "issue": "a channel! be still my beating heart! even if its immediately yielding into a generator...\n\nanyway, can you inline the _run_probes into the main task group? it seems a little silly to write this function just to call it", "severity": "minor", "line": 26 } ]
1
python
func_name: str | None def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]: """Make a unique identifier for each ParameterSet, that may be used to identify the parametrization in a node ID. Format is <prm_1_token>-...-<prm_n_token>[counter], where prm_x_token is - use...
Review this code and list any quality issues.
[ { "issue": "Perhaps make it sound more error like. Something like:\n\nThe test has multiple parameter sets with the same ID, but `--require-unique-paramset-ids` is set.\n\nA second sentence can maybe explain how to resolve the problem.", "severity": "minor", "line": 26 } ]
1
python
converted_state_dict = self._match_state_dict(list(model.state_dict().values()), dict(converted_model.state_dict())) converted_model.load_state_dict(converted_state_dict) with torch.no_grad(): expected_output = model.eval()(*input) ...
Review this code and list any quality issues.
[]
0
python
# Copyright 2021-2024 Avaiga Private Limited # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\noptions = [(\"a\", \"Option A\"), (\"b\", \"Option B\"), (\"c\", \"Option C\"), (\"d\", \"Option D\")]\r\n```\r\nShorter is better", "severity": "minor", "line": 18 } ]
1
python
return hash_pandas_object(dfs, index=False) # --------------------------------- # group_scatter # --------------------------------- group_scatter_dispatch = Dispatch("group_scatter") def group_scatter(dfs, ind, stage, k, npartitions): """Scatter dataframe into "k" parts, using index "ind" """ func = g...
Review this code and list any quality issues.
[ { "issue": "I think that the lines above are fairly tied to the algorithm that dask is using. We might want to pull them out of this function.", "severity": "minor", "line": 26 } ]
1
python
_new_hparam_key = cls.CHECKPOINT_HYPER_PARAMS_KEY cls_kwargs_loaded.update(checkpoint.get(_new_hparam_key)) # 3. Ensure that `cls_kwargs_old` has the right type, back compatibility between dict and Namespace cls_kwargs_loaded = _convert_loaded_hparams(cls_kwargs_loaded, checkpoint.g...
Review this code and list any quality issues.
[]
0
python
return q_idx >= kv_idx # ===== torch op registrations ===== # Registrations are required for fullgraph tracing compatibility # TODO: this is only required because the beta release FA3 does not have it. There is a PR adding # this but it was never merged: https://github.com/Dao-AILab/flash-attention/pull/1590 @_cust...
Review this code and list any quality issues.
[ { "issue": "(nit)\r\n\r\n```suggestion\r\n@_custom_op(\"vllm_flash_attn3::flash_attn\", mutates_args=(), device_types=\"cuda\")\r\n```\r\n\r\nbecause this calls an autograd function that has both forward and backward: https://huggingface.co/kernels-community/vllm-flash-attn3/blob/main/torch-ext/vllm_flash_attn3...
1
python
surf_idx, inv = np.unique(triangles.flat, return_inverse=True) triangles = inv.reshape(triangles.shape) vertices = vertices[surf_idx] mesh = trimesh.Trimesh(vertices, triangles, process=False) mesh.visual = mu.surface_uvs_t...
Review this code and list any quality issues.
[ { "issue": "Remove the entire computation.", "severity": "minor", "line": 26 } ]
1
python
tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: """ Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Currently, \"###\" is tokenized into 2 tokens in the whole conversation,\r\n # and 1 token in a single sentence, so we do not need to use the code below.\r\n # tokenized_lens = [l-1 for l in tokenized_lens]\r\n```", "severity": "minor", "line": 26 }...
1
python
PathSamplingLayer.mutate, PathSamplingInput.mutate, PathSamplingRepeat.mutate, PathSamplingCell.mutate, ] hooks += [operation.mutate for operation in NATIVE_MIXED_OPERATIONS] hooks.append(no_default_hook) return hooks def mutate_kwargs(self): ...
Review this code and list any quality issues.
[ { "issue": "-> Sampling the best architecture from this well trained supernet is another search process, users can use the supernet's checkpoint to do another search.", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor from ..utils import ( ExtractorError, try_call, unified_timestamp, ) class EplusIbIE(InfoExtractor): IE_NAME = 'eplus:inbound' IE_DESC = 'e+ (イープラス) overseas' _VALID_URL = r'https?://live\.eplus\.jp/ex/player\?ib=(?P<id>(?:\w|%2B|%2F){86}%3D%3D)' _TESTS = ...
Review this code and list any quality issues.
[ { "issue": "Update test; need to remove `timestamp`", "severity": "minor", "line": 20 } ]
1
python
return ChatSession.new(user_id) @tools_router.post(path="/find-agent") async def find_agent( request: FindAgentRequest, api_key: APIKeyInfo = Security(require_permission(APIKeyPermission.USE_TOOLS)), ) -> dict[str, Any]: """ Search for agents in the marketplace based on capabilities and user needs. ...
Review this code and list any quality issues.
[]
0
python
from ..utils import ( js_to_json, urlencode_postdata, ) class JioSaavnBaseInfoExtractor(InfoExtractor): def extract_initial_data_as_json(self, url, id): webpage = self._download_webpage(url, id) init_data_re = r'window.__INITIAL_DATA__\s*=\s*(?P<json>.+?);*\s*\</script>' init_data...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?(?:jiosaavn\\.com/song/[^/?#]+/|saavn\\.com/s/song/(?:[^/?#]+/){3})(?P<id>[^/?#]+)'\r\n```", "severity": "minor", "line": 26 } ]
1
python
} }] def _extract_episode(self, podcast, episode): return { 'id': str(episode.get('id')), 'title': episode.get('title'), 'description': episode.get('description'), 'url': episode.get('audio_url'), 'thumbnail': episode.get('image_url'), ...
Review this code and list any quality issues.
[ { "issue": "Extractors should only inherit from a base extractor. Like:\r\n```py\r\nclass PodchaserBaseIE(InfoExtractor):\r\n def _extract_episode(...): ...\r\n\r\nclass PodchaserIE(PodchaserBaseIE):\r\n ...\r\n\r\nclass PodchaserFeedIE(PodchaserBaseIE):\r\n ...\r\n```\r\n\r\nBut here, inheritence isn'...
1
python
import warnings from typing import List, Optional, Type from jina import Deployment from jina.excepts import BadYAMLVersion from jina.jaml import JAMLCompatible from jina.jaml.parsers.base import VersionedYAMLParser from jina.serve.gateway import BaseGateway def _get_all_parser(cls: Type['JAMLCompatible']): """G...
Review this code and list any quality issues.
[ { "issue": "can we avoid importing directly from `jina`? Import from its own module", "severity": "minor", "line": 4 } ]
1
python
register_conv_template( Conversation( name="openchat_3.5", roles=("GPT4 Correct User", "GPT4 Correct Assistant"), sep_style=SeparatorStyle.FALCON_CHAT, sep="<|end_of_turn|>", ) ) # Deepseek code default template register_conv_template( Conversation( name="deepseek", ...
Review this code and list any quality issues.
[ { "issue": "so deepseek-coder's sep_style is different from deepseek?\r\n```\r\n sep_style=SeparatorStyle.DEEPSEEK_CHAT,\r\n```", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor from .dailymotion import DailymotionIE from ..utils import smuggle_url, traverse_obj class NetverseBaseIE(InfoExtractor): _ENDPOINTS = { 'watch': 'watchvideo', 'video': 'watchvideo', 'webseries': 'webseries', 'season': 'webseason_videos', } ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n sites_type, display_id = endpoint, slug\r\n```", "severity": "minor", "line": 22 } ]
1
python
return val if isinstance(val, str): if val.strip().lower() == "true": return True if val.strip().lower() == "false": return False return None class AsyncKubernetesHook(KubernetesHook): """Hook to use Kubernetes SDK asynchronously.""" def __init__( self,...
Review this code and list any quality issues.
[ { "issue": "Instead of an internal flag, would it be easier to use the `@cache` decorator?", "severity": "major", "line": 26 } ]
1
python
scenario_1_cfg = Config.configure_scenario(name="C_scenario", id="scenario_3", tags=["banana", "kiwi"]) scenario_2_cfg = Config.configure_scenario(name="B_scenario", id="scenario_1", tags=["apple", "banana"]) scenario_1 = _ScenarioManager._create(scenario_1_cfg) scenario_2 = _ScenarioManager._create(scenar...
Review this code and list any quality issues.
[ { "issue": "A few remarks: \r\n1. I believe it would be interesting to test what happens when some scenarios have the same value\r\n2. I believe the following way of configuring and creating scenarios is more representative.\r\n- 2 scenario configs.\r\n- 1 scenario from the first config\r\n- 2 scenarios from th...
1
python
logger = get_logger() async def process_and_search(num_of_searches): start_time = time.time() await cognee.cognify() await asyncio.gather( *[ cognee.search(query_text="Tell me about AI", query_type=SearchType.GRAPH_COMPLETION) for _ in range(num_of_searches) ] ...
Review this code and list any quality issues.
[ { "issue": "You don't need `pathlib.Path` to wrap `join`.", "severity": "minor", "line": 26 } ]
1
python
additional_parts['u'] = user_session_id yt_sapisid, yt_1psapisid, yt_3psapisid = self._get_sid_cookies() for scheme, sid in (('SAPISIDHASH', yt_sapisid), ('SAPISID1PHASH', yt_1psapisid), ('SAPISID3PHASH', yt_3psapisid)): if sid: ...
Review this code and list any quality issues.
[ { "issue": "this? since otherwise we could return the value of `yt_sapisid` etc\r\n```suggestion\r\n return bool(has_login_info and (yt_sapisid or yt_1psapisid or yt_3psapisid))\r\n```", "severity": "minor", "line": 26 } ]
1
python
("s3://some/example#filename", ("s3", "some/example#filename")), ("s3://some/example?query=query", ("s3", "some/example?query=query")), ], ) def test_get_protocol_and_path(self, filepath, expected_result): assert get_protocol_and_path(filepath) == expected_result @pytest.mark.pa...
Review this code and list any quality issues.
[]
0
python
self, model_name: OpenAIEmbeddingModelName, *, provider: OpenAIEmbeddingsCompatibleProvider | Literal['openai'] | Provider[AsyncOpenAI] = 'openai', settings: EmbeddingSettings | None = None, ): """Initialize an OpenAI embedding model. Args: model_name: Th...
Review this code and list any quality issues.
[]
0
python
def directory_size(path: str) -> int | float: size = 0.0 for root, _dirs, files in os.walk(path): for filename in files: file_path = os.path.join(root, filename) size += file_size(file_path) return size def format_directory_size(path: str) -> str: return format_size(dir...
Review this code and list any quality issues.
[ { "issue": "There is a fair bit of duplication. IMO, it'd nicer to extract the common logic into a generic helper function:\r\n\r\n```diff\r\ndiff --git a/src/pip/_internal/utils/filesystem.py b/src/pip/_internal/utils/filesystem.py\r\nindex 014d1a271..52eb78f42 100644\r\n--- a/src/pip/_internal/utils/filesyste...
1
python
else: key = slice(*map(int_or_none, key.split(':'))) if not casesense and isinstance(key, str): key = key.casefold() if __debug__ and callable(key): # Verify function signature inspect.signature(key).bind(None, None) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n results = LazyList(item for item in results if item or item in (0, False))\r\n```\r\nMaybe we should allow `''` too? We really only want to block `{}`/`None`, right?", "severity": "minor", "line": 26 } ]
1
python
X = check_array(X, dtype=[X_DTYPE], ensure_all_finite=False) max_bins = self.n_bins - 1 rng = check_random_state(self.random_state) if self.subsample is not None and X.shape[0] > self.subsample: subsampling_probabilities = None if sample_weight is not None: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n X.shape[0], self.subsample, p=subsampling_probabilities, replace=False\r\n```\r\nPreserve current behavior with `sample_weight=None`.", "severity": "minor", "line": 26 } ]
1
python
shapes: Mobject, scale_factor: float = 8, fade_in_fraction=0.3, **kwargs, ) -> None: self.shapes = shapes self.scale_factor = scale_factor self.shape_center = shapes.get_center() self.fade_in_fraction = fade_in_fraction for shape in shapes: ...
Review this code and list any quality issues.
[ { "issue": "I'm not sure this is the correct solution here as it modifies the fill opacity of a given mobject -- this actually also happens in the test that you added; at the end of `SpiralIn`, the mobjects should be added to the scene with the opacity values they have been initialized with.\r\n\r\nMy suggestio...
1
python
intlist_to_bytes, ) class ShemarooMeIE(InfoExtractor): _VALID_URL = r'(?:https?://)(?:www\.)?shemaroome\.com/(?:movies|shows)/(?P<id>\S+)' _TESTS = [{ 'url': 'https://www.shemaroome.com/movies/dil-hai-tumhaara', 'info_dict': { 'id': 'dil-hai-tumhaara', 'ext': 'mp4', ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n iv = [0] * 16\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Do not want AWX to ask interactive questions and want it to be friendly with # reprovisioning ANSIBLE_HOST_KEY_CHECKING = False # RHEL has too old of an SSH so ansible will select paramiko and this is VERY # slow. ANSIBLE_PARAMIKO_RECORD_HOST_KEYS = False # Force ansible in color even if we don't have a TTY so we c...
Review this code and list any quality issues.
[]
0