language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
mock_request_acks_early = Mock(id='3') mock_request_acks_early.task.acks_late = False mock_request_acks_early.acknowledged = False active_requests.add(mock_request_acks_late_not_acknowledged) active_requests.add(mock_request_acks_late_acknowledged) active_requests.add(mock_reque...
Review this code and list any quality issues.
[]
0
python
"python_version": sys.version, "os": sys.platform, "os_version": platform.version(), "os_release": platform.release(), "processor": platform.processor(), "machine": platform.machine(), **properties, } distinct_id = self.user_id if u...
Review this code and list any quality issues.
[ { "issue": "Can we not reuse the project_api_key and host?", "severity": "minor", "line": 26 } ]
1
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": "I don't understand this.\r\n\r\n\"The role of the subclasses of `Section^` is to define...\"?", "severity": "minor", "line": 23 } ]
1
python
Header encoding is mandated as ascii, but we allow fallbacks to utf-8 or iso-8859-1. """ if self._encoding is None: for encoding in ["ascii", "utf-8"]: for key, value in self.raw: try: key.decode(encoding) ...
Review this code and list any quality issues.
[ { "issue": "Is now a good time to review this? Eg does flask provide similar behaviour onto its headers data structures? Does Django?\n\n(Possibly too off topic??)", "severity": "minor", "line": 26 } ]
1
python
except (ValueError, RuntimeError) as exc: self.logger.warning( f' The runtime {self.__class__.__name__} will not be able to handle termination signals. ' f' {repr(exc)}' ) else: with ImportExtensions( require...
Review this code and list any quality issues.
[ { "issue": "I think it's better to have function `_get_telemetry_extra_kwargs` and override it in gateway runtime to flow id.\r\nI don't like much how we set a `None` flow id for all pods.\r\nI'm also okay with renaming to `pod_id` and then each runtime can implement it on his own", "severity": "minor", ...
1
python
showextrema=True, showmedians=True, side=side) def violin_plot_stats(): datetimes = [ datetime.datetime(2023, 2, 10), datetime.datetime(2023, 5, 18), datetime.datetime(2023, 6, 6) ] return [{ 'coords': datetimes, 'vals': [0.1, 0.5, 0.2], 'mean': datetimes[1]...
Review this code and list any quality issues.
[ { "issue": "This PR handles date aspects on x-axis-related quantities. The stats refer to the y-axis and their unit does not matter in this PR. For simplicity and clarity, let's not use dates for them.", "severity": "minor", "line": 26 } ]
1
python
from .const import DOMAIN from .coordinator import YardianUpdateCoordinator, YardianZone @dataclass(kw_only=True, frozen=True) class YardianBinarySensorEntityDescription(BinarySensorEntityDescription): """Entity description for Yardian binary sensors.""" value_fn: Callable[[YardianUpdateCoordinator], bool | ...
Review this code and list any quality issues.
[ { "issue": "You just updated the code, it literally can't return anything else than a YardianZone, so you can just keep using the old method but then without `[1]` but with `.is_enabled`", "severity": "minor", "line": 26 } ]
1
python
assert expected_message in "".join(caplog.messages).strip("\n") def test_logger_without_rich_markup(): class CustomHandler(logging.Handler): def __init__(self): super().__init__() self.records = [] def emit(self, record): self.records.append(record) data =...
Review this code and list any quality issues.
[ { "issue": "This should sufficiently show that even with a dummy handler, it still capture the rich markup.\r\n@astrojuanlu", "severity": "minor", "line": 26 } ]
1
python
return len(self.dataset_list) def __getitem__(self, idx): context, completions = self.dataset_list[idx].values() return [context], completions class HFDataset(Dataset): """ Dataset class to use data from openai/summarize_from_feedback for Reward modeling. Summaries ranked by overall s...
Review this code and list any quality issues.
[]
0
python
'upper center': 9, 'center': 10, } def __init__(self, loc, *, pad=0.4, borderpad=0.5, child=None, prop=None, frameon=True, bbox_to_anchor=None, bbox_transform=None, **kwargs): """ Paramete...
Review this code and list any quality issues.
[ { "issue": "The indent should be 4 spaces wrt. to the parameter name. Please fix.", "severity": "minor", "line": 26 } ]
1
python
assert s._tasks_since_sync == 0 self.app.conf.beat_sync_every = 0 @patch('celery.app.base.Celery.send_task') def test_send_task(self, send_task): b = beat.Scheduler(app=self.app) b.send_task('tasks.add', countdown=10) send_task.assert_called_with('tasks.add', countdown=10) ...
Review this code and list any quality issues.
[ { "issue": "oh woops - this syntax (parenthesized context managers) was not available in older python versions. fixing now...", "severity": "minor", "line": 26 } ]
1
python
# Launch the server process using SGLang's utility logger.info(f"Starting SGLang server with command: {launch_cmd}") try: # Use the SGLang utility to launch the server self.server_process, _ = launch_server_cmd(launch_cmd) # Register cleanup handler to terminate serv...
Review this code and list any quality issues.
[ { "issue": "sure. I love `launch_server_cmd`. but what about `wait_for_server`?", "severity": "minor", "line": 26 } ]
1
python
categories=traverse_obj(series_info, ('styles', ..., 'title'), expected_type=str_or_none), thumbnail=url_or_none(series_info.get('horizontal_cover')), view_count=parse_count(series_info.get('view'))) class BiliLiveIE(InfoExtractor): _VALID_URL = r'https?://live.bilibili.com/(?P<room_id>\d+)' _TES...
Review this code and list any quality issues.
[ { "issue": "json is the name of a std lib. Use different name", "severity": "minor", "line": 26 } ]
1
python
oidc_config["jwt_keys"][key_id] = ECAlgorithm.from_jwk(json.dumps(k)) oidc_config["aud"] = config.get( "get_user_by_aws_alb_auth_settings.access_token_validation.client_id" ) return oidc_config async def authenticate_user_by_alb_auth(request): aws_alb_auth_header_name = config.get( "ge...
Review this code and list any quality issues.
[]
0
python
data_schema=vol.Schema({}), description_placeholders=description_placeholders, ) async def _async_step_confirm(self) -> data_entry_flow.FlowResult: """Handle the confirm step of a fix flow.""" raise NotImplementedError class CoiotConfigureFlow(ShellyBlockRepairsFlow): """H...
Review this code and list any quality issues.
[ { "issue": "The `get_coiot_address` function can return `None` when the URL is not available (line 730). However, in the repair flow at line 285, this None value is not handled before being used in the HTTP request parameters at line 290. This could result in sending \"None\" as a string to the device, which wo...
1
python
elif error_code == 'needUnlimitItem': raise ExtractorError('Ticket purchase is required for this stream', expected=True) elif error_code == 'needPw': raise ExtractorError('Password protected video, use --video-password <password>', expected=True) elif error_code =...
Review this code and list any quality issues.
[ { "issue": "are upcoming streams promoted on the website? i.e. is there a `release_timestamp` / `startTime` available before the stream starts?", "severity": "minor", "line": 26 } ]
1
python
# Perform actual refresh if self.redis.expire(self.key, self.timeout): with self._refresh_lock: self._last_refresh = current_time return True with self._refresh_lock: self._last_refresh = 0 return False exc...
Review this code and list any quality issues.
[]
0
python
def __enter__(self): """Acquire the import lock.""" _imp.acquire_lock() def __exit__(self, exc_type, exc_value, exc_traceback): """Release the import lock regardless of any raised exceptions.""" _imp.release_lock() def _resolve_name(name, package, level): """Resolve a relative...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # gh-130094: Copy sys.meta_path so that we have a consistent view of the\r\n```", "severity": "minor", "line": 26 } ]
1
python
multiplicity of the item in the sequence. Examples ======== >>> from sympy.utilities.iterables import multiset >>> multiset('mississippi') {'i': 4, 'm': 1, 'p': 2, 's': 4} See Also ======== group """ return dict(Counter(seq).items()) @overload def ibin( n: int, b...
Review this code and list any quality issues.
[ { "issue": "There should not be a space before list and not after list and also the `)` line should not be indented e.g.:\r\n```\r\n@overload\r\ndef ibin(\r\n n: int,\r\n bits: int|None,\r\n str: Literal[False],\r\n) -> list[int]: ...\r\n```\r\nThis applies everywhere though.\r\n\r\nPlease read PEP 8 a...
1
python
): """Checks all credentials for all nodes of the graph""" for node in graph.nodes: block = node.block # Find any fields of type CredentialsMetaInput credentials_fields = cast( type[BlockSchema], block.input_schema ).get_credentials_fields() if not credentia...
Review this code and list any quality issues.
[]
0
python
return None @classmethod def _get_all_by_tag(cls, tag: str) -> List[Scenario]: return [scenario for scenario in cls._get_all() if scenario.has_tag(tag)] @classmethod def _get_all_by_cycle(cls, cycle: Cycle) -> List[Scenario]: filters = cls._build_filters_with_version("all") if...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n sort_key: Literal[\"name\", \"id\", \"config_id\", \"creation_date\", \"tags\"] = \"name\",\r\n```\r\n`sort_key` doesn't accept `None` as a possible value, so it should not be an `Optional` type.", "severity": "minor", "line": 26 } ]
1
python
hls_manifest_url = 'hls' not in skip_manifests and sd.get('hlsManifestUrl') if hls_manifest_url: pot_policy: GvsPoTokenPolicy = self._get_default_ytcfg(client_name).get('GVS_PO_TOKEN_POLICY')[StreamingProtocol.HLS] require_po_token = pot_required(pot_policy, is_premium_subscr...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n pot_policy: GvsPoTokenPolicy = self._get_default_ytcfg(\r\n client_name)['GVS_PO_TOKEN_POLICY'][StreamingProtocol.DASH]\r\n```", "severity": "minor", "line": 26 } ]
1
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\nvalue = \"\"\r\n```\r\nCapitals are somehow reserved for class members or constants.", "severity": "minor", "line": 23 } ]
1
python
"testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ], ) author_with_m2m_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=...
Review this code and list any quality issues.
[ { "issue": "I think we only need a variable for something we need to use more than once.\n```suggestion\n other_publisher = ModelState(\n \"testapp\",\n \"OtherPublisher\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n ],\n )\n```", "severity": "minor", ...
1
python
_VALID_URL = r'https?://vkplay\.live/(?P<username>[^/]+)/record/(?P<id>[a-f0-9\-]+)' _TESTS = [{ 'url': 'https://vkplay.live/zitsmann/record/f5e6e3b5-dc52-4d14-965d-0680dd2882da', 'info_dict': { 'id': 'f5e6e3b5-dc52-4d14-965d-0680dd2882da', 'ext': 'mp4', 'title': ...
Review this code and list any quality issues.
[ { "issue": "can check expected_type like this to save on typing/reading\r\n```suggestion\r\n ('data', 'record', {dict}))\r\n```", "severity": "minor", "line": 26 } ]
1
python
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class PeerTVIE(InfoExtractor): IE_NAME = 'peer.tv' _VALID_URL = r'https?://(?:www\.)?peer\.tv/(?:de|it|en)/(?P<id>\d+)' _TESTS = [{ 'url': 'https://www.peer.tv/de/841', # md5 hash changes 'in...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'info_dict': {\r\n 'id': '841',\r\n 'ext': 'mp4',\r\n 'title': 'Die Brunnenburg',\r\n 'description': 'md5:4395f6142b090338340ab88a3aae24ed',\r\n },\r\n 'params': {'skip_download': 'm3u8'}\r\n```\r\nsame for other test...
1
python
arg = index_or_string if isinstance(arg, str): part = self.get_part_by_tex(arg) elif isinstance(arg, int): part = self.submobjects[arg] else: raise TypeError(f"Expected int or string, got {arg}") for other_part in self.submobjects: if other...
Review this code and list any quality issues.
[ { "issue": "Is this play call here really necessary? I don't particularly like play calls in examples that are rendered as images anyways.", "severity": "minor", "line": 26 } ]
1
python
_ResponseType = Union[ClientResponse, Response] from .interactions import Interaction __all__ = ( 'DiscordException', 'ClientException', 'GatewayNotFound', 'HTTPException', 'RateLimited', 'Forbidden', 'NotFound', 'DiscordServerError', 'InvalidData', 'LoginFailure', 'Con...
Review this code and list any quality issues.
[ { "issue": "This change should be reverted as errors.py passes CI checks on master.", "severity": "minor", "line": 26 } ]
1
python
s1 = sin_theta / sin_theta_0 new_q = s0 * q0 + s1 * q1 out = np.where(small_mask, lerp, new_q) return out[0] if scalar_output else out @torch.jit.script def _tc_slerp(q0, q1, t): scalar_output = q0.ndim == 1 and (t.ndim == 0 or (t.ndim == 1 and t.shape[0] == 1)) if q0.ndim == 1: q0 = q0.u...
Review this code and list any quality issues.
[ { "issue": "I'm surprised it is not impossible to replace this by 2 lines of code.", "severity": "minor", "line": 26 } ]
1
python
self.calendar.next_minute(minute) ) self.assertEqual( all_minutes[idx], self.calendar.previous_minute(minute) ) # test a couple of non-market minutes if self.GAPS_BETWEEN_SESSIONS: for open_minute in self.answers.market_op...
Review this code and list any quality issues.
[]
0
python
from __future__ import annotations from functools import partial import json import re import string from typing import Any import voluptuous as vol from voluptuous.humanize import humanize_error import homeassistant.helpers.config_validation as cv from script.translations import upload from .model import Config, I...
Review this code and list any quality issues.
[ { "issue": "why the homeassistant protocol?", "severity": "minor", "line": 26 } ]
1
python
from homeassistant.components import system_health from homeassistant.core import HomeAssistant, callback from .const import DOMAIN from .coordinator import AccuWeatherConfigEntry @callback def async_register( hass: HomeAssistant, register: system_health.SystemHealthRegistration ) -> None: """Register system...
Review this code and list any quality issues.
[ { "issue": "`async_check_can_reach_url` expects an absolute URL string. Passing `ENDPOINT.path` will typically be just `'/'`, which causes the reachability check to always fail (aiohttp raises an invalid/relative URL error and it's caught as unreachable). Use the full endpoint instead (for example `str(ENDPOINT...
1
python
from unittest.mock import Mock, PropertyMock from http.client import NOT_FOUND import pytest from awxkit.api.pages import Base from awxkit.config import config @pytest.fixture(autouse=True) def setup_config(): config.credentials = {"default": {"username": "foo", "password": "bar"}} config.base_url = "" @p...
Review this code and list any quality issues.
[ { "issue": "Make sure that the patching is undone once testing this module is complete. We should be careful not to create side effects for any other tests:\r\n```suggestion\r\ndef setup_config(monkeypatch: pytest.MonkeyPatch) -> None:\r\n monkeypatch.setattr(\r\n \"credentials\",\r\n {\"defaul...
1
python
all_episodes = [ self.url_result(smuggle_url( self._URL_TEMPLATE % (content_type, episode['content_id']), {'force_noplaylist': True})) # To prevent infinite recursion for episode in traverse_obj(playlist_data, ('seasons', ..., 'episodes', lambda _, v: v['content_...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n playlist_data = traverse_obj(vod_data, ('props', 'pageProps', 'seriesTree'))\r\n if playlist_data and self._yes_playlist(program_info.get('series_id'), video_id, smuggled_data):\r\n```", "severity": "minor", "line": 26 } ]
1
python
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test error handling when entry is not loaded.""" mock_config_entry2 = MockConfigEntry(domain=DOMAIN) mock_config_entry2.add_to_hass(hass) with pytest.raises(ServiceValidationError, match="...
Review this code and list any quality issues.
[ { "issue": "This test name/docstring still refers to the integration not being in the registry, but the new behavior being exercised is an invalid `config_entry_id` (raised as `service_config_entry_not_found`). Please rename the test and update the docstring to reflect the actual error case to keep the test int...
1
python
def _demucs_voice(self)->tuple[bool, str]: try: cmd = [ "demucs", "--verbose", "--two-stems=vocals", "--out", self.output_dir, self.wav_file ] try: process = subprocess.run(cmd, ch...
Review this code and list any quality issues.
[ { "issue": "The exception is caught and an error message is set, but the exception is not re-raised and execution continues to the next except block. This means `FileNotFoundError` will never be properly handled. Either remove this except block if it's no longer needed, or ensure the error is properly returned ...
1
python
H = FpGroup(F, [b**3, a**2]) assert is_isomorphic(G, H) # Trivial Case # FpGroup -> FpGroup H = FpGroup(F, [a**3, b**3, (a*b)**2]) F, c, d = free_group("c, d") G = FpGroup(F, [c**3, d**3, (c*d)**2]) check, T = group_isomorphism(G, H) assert check assert T(c**3*d**2) == a**3*b**2 ...
Review this code and list any quality issues.
[]
0
python
images = multi_modal_data.get("images") videos = multi_modal_data.get("videos") param_version = kwargs.get("param_version", 0) metrics = {} request_id = uuid4().hex param_version_start = param_version param_version_end = param_version if not output: ...
Review this code and list any quality issues.
[]
0
python
[1, 5, 7], [8, 5, 1], [7, 3, 5], [5, 9, 3], [8, 9, 5], [3, 2, 9], [9, 4, 2], [8, 4, 9], [0, 4, 8], [6, 4, 0], [6, 2, 4], [11, 2, 6], ...
Review this code and list any quality issues.
[ { "issue": "It might be useful to note how many sides the Polyhedron has.\r\n```suggestion\r\n \"\"\"A dodecahedron, one of the five platonic solids, and one with twelve faces.\r\n```\r\nor\r\n```suggestion\r\n \"\"\"A dodecahedron, the polyhedron with twelve faces.\r\n```", "severity": "minor", "...
1
python
total += len(author['name']) return total def __bool__(self) -> bool: return any( ( self.title, self.url, self.description, self.colour, self.fields, self.timestamp, self.aut...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n self.type == other.type,\r\n self.title == other.title,\r\n```", "severity": "minor", "line": 26 } ]
1
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": "Mixing 'filter' and styling to me is confusing.", "severity": "minor", "line": 1 } ]
1
python
description: - >- Credential inputs where the keys are var names used in templating. Refer to the Automation Platform Controller documentation for example syntax. - authorize (use this for net type) - authorize_password (password for net credentials that require authorize) ...
Review this code and list any quality issues.
[ { "issue": "Does this actually change anything, functionally? Or is this just docs-impacting?", "severity": "minor", "line": 26 } ]
1
python
""" import contextlib import typing from types import TracebackType import httpcore from httpx import URL from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context from .._exceptions import ( ConnectError, ConnectTimeout, LocalProtocolError, NetworkError, PoolTimeout, ProtocolEr...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nfrom .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream, VerifyTypes\r\nfrom .._urls import URL\r\n```", "severity": "minor", "line": 26 } ]
1
python
self._kernel_set_geom_friction(geoms_idx, friction) @ti.kernel def _kernel_set_geom_friction(self, geoms_idx: ti.i32, friction: ti.f32): self.geoms_info[geoms_idx].friction = friction def set_geoms_friction(self, friction, geoms_idx=None, *, unsafe=False): friction, geoms_idx, _ = self._sa...
Review this code and list any quality issues.
[ { "issue": "missing `skip_allocation=True`", "severity": "minor", "line": 26 } ]
1
python
encoding_image_processor, original_sizes, input_points=None, input_labels=None, input_boxes=None, return_tensors="pt", point_pad_value=-10, ): """ Normalize and convert the image processor output to the expected format. """ # Process in...
Review this code and list any quality issues.
[]
0
python
last_edit_date: Optional[datetime] = None, edits: Optional[List[Edit]] = None, version: Optional[str] = None, validity_period: Optional[timedelta] = None, edit_in_progress: bool = False, editor_id: Optional[str] = None, editor_expiration_date: Optional[datetime] = None, ...
Review this code and list any quality issues.
[ { "issue": "I believe we don't need this anymore. Am I correct?", "severity": "minor", "line": 26 } ]
1
python
import torch.distributed as dist from torch.multiprocessing import Manager from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig import colossalai from colossalai.inference.config import _DEFAULT_PROMPT_TEMPLATES, InferenceConfig from colossalai.inference.core.engine import InferenceEngine fro...
Review this code and list any quality issues.
[ { "issue": "Actually does not make a difference", "severity": "minor", "line": 26 } ]
1
python
annotations={name: self.annotations[name] for name in train_names}, ) test_dataset = ClassificationDataset( classes=self.classes, images={name: self.images[name] for name in test_names}, annotations={name: self.annotations[name] for name in test_names}, ) ...
Review this code and list any quality issues.
[ { "issue": "You are missing ``` at the end of the code snippet here.", "severity": "minor", "line": 26 } ]
1
python
resp.raise_for_status() else: raise ValueError("NGC API requires requests package. Please install it.") model_info = json.loads(resp.text) return model_info["model"]["latestVersionIdStr"] def _examine_monai_version(monai_version: str) -> tuple[bool, str]: """Examine if the package version is c...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Get the `monai_version` from the metadata.json and compare if it is smaller than the installed `monai` package version\"\"\"\r\n```", "severity": "minor", "line": 26 } ]
1
python
}''' % display_id, })['data']['mediaPlayback'][0] class MLBTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?mlb\.com/tv/g(?P<id>\d{6})' _NETRC_MACHINE = 'mlb' _TESTS = [{ 'url': 'https://www.mlb.com/tv/g661581/vee2eff5f-a7df-4c20-bdb4-7b926fa12638', 'info_dict': { ...
Review this code and list any quality issues.
[ { "issue": "All video on the site needs account, correct? Do this to give users a proper error message if try try without `-u`.\r\n```suggestion\r\n _access_token = None\r\n \r\n def _real_initialize(self):\r\n if not self._access_token:\r\n self.raise_login_required(\r\n ...
1
python
class MastodonConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VERSION = 1 MINOR_VERSION = 2 base_url: str | None = None client_id: str | None = None client_secret: str | None = None access_token: str | None = None def check_connection( self, ) -> tuple[ ...
Review this code and list any quality issues.
[ { "issue": "Shouldn't be needed\n```suggestion\n```", "severity": "minor", "line": 26 } ]
1
python
@property def color(self) -> RGBColor | None: """Return the color of the calendar entity as RGBColor.""" return self._attr_color @property def event(self) -> CalendarEvent | None: """Return the next upcoming event.""" raise NotImplementedError @final @property d...
Review this code and list any quality issues.
[ { "issue": "I'm not sure this meets the style guide so i think it may need to be done as a variable", "severity": "minor", "line": 26 } ]
1
python
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:: class GenProto[T](Protocol): ...
Review this code and list any quality issues.
[ { "issue": "I feel like we should give this a dunder name like `__typing_is_deprecated_inherited_runtime_protocol__`, because dunder names are reserved for the interpreter, and somebody could theoretically use the existing name in their own class.\r\n\r\n(I know `_is_protocol` and `_is_runtime_protocol` have th...
1
python
"""Manim's init subcommand. Manim's init subcommand is accessed in the command-line interface via ``manim init``. Here you can specify options, subcommands, and subgroups for the init group. """ from pathlib import Path import click from ...constants import CONTEXT_SETTINGS, EPILOG from ...utils.file_ops import cop...
Review this code and list any quality issues.
[ { "issue": "Nitpick. I'm pretty sure the default for this is false so this is not needed.\r\n```suggestion\r\n```", "severity": "minor", "line": 18 } ]
1
python
], } dataroot = '/datasets' # the directory where you have the image files (nii.gz) DataAnalyzer(datalist, dataroot) Notes: The module can also be called from the command line interface (CLI). For example: .. code-block:: bash python -m monai.apps.aut...
Review this code and list any quality issues.
[ { "issue": "why renaming back? we always use \"datastats.yaml\"", "severity": "minor", "line": 26 } ]
1
python
): return pyproject_path # Stop after first reasonable file break except Exception: # noqa: S112 continue except Exception: return None return None def _pypr...
Review this code and list any quality issues.
[]
0
python
@staticmethod def load(data): assert data.startswith(MAGIC + VERSION) id = data[0x8:0x48].decode("ascii") cache = pickle.loads(zlib.decompress(data[0x48:])) assert isinstance(cache, RuleCache) assert cache.id == id return cache def get_ruleset_content(ruleset: ca...
Review this code and list any quality issues.
[ { "issue": "we should probably try/catch this to not fail running if something goes wrong", "severity": "critical", "line": 26 } ]
1
python
collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, worker_init_fn=seed_worker, ) return dataloader def argument_parsing(notebook=False, notebook_ar...
Review this code and list any quality issues.
[]
0
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. import bitsandbytes import pytest from llamafactory.v1.config.model_args...
Review this code and list any quality issues.
[ { "issue": "bnb can only be installed on gpu or npu machine. add `runs_on` marker here. we also need to install bnb during the test phase", "severity": "minor", "line": 26 } ]
1
python
'hd video url', default='', group='options'), video_id, fatal=False) if options: duration = int_or_none(options.get('duration')) hd_url = options.get('hdUrl') if hd_url: # there are multiple formats; extract them ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if not media_json.get('url') and not video_url and not iframe_url:\r\n```", "severity": "minor", "line": 26 } ]
1
python
url = file['file_name'] info['id'] = programme_id + '_' + headline['headline_id'] info['formats'] = self._extract_m3u8_formats(url, info['id']) info['title'] = file.get('file_title') info['description'] = file.get('file_title_sub') # info['webpage_url'] = file.get('share_url') ...
Review this code and list any quality issues.
[ { "issue": "one-time use variable can just be the argument instead\r\n```suggestion\r\n meta = self._download_json(\r\n f'https://www.nhk.or.jp/radioondemand/json/{site_id}/bangumi_{programme_id}.json',\r\n programme_id)['main']\r\n```", "severity": "minor", "line": 26 } ]
1
python
training_args: "Seq2SeqTrainingArguments", finetuning_args: "FinetuningArguments", ) -> "torch.optim.Optimizer": if len(finetuning_args.galore_target) == 1 and finetuning_args.galore_target[0] == "all": galore_targets = find_all_linear_modules(model) else: galore_targets = finetuning_args.ga...
Review this code and list any quality issues.
[]
0
python
if non_blocking: torch.cuda.current_stream().synchronize() # account for any overlapping sections for ss in range(len(output_image_list)): output_image_list[ss] /= count_map_list.pop(0) # remove padding if image_size smaller than roi_size if any(pad_size): for ss, output_i in e...
Review this code and list any quality issues.
[ { "issue": "Should the type hint of `inputs` (in https://github.com/Project-MONAI/MONAI/blob/c8735079a8ab6f64881a9b0205d4ac7367662864/monai/inferers/utils.py#L44) be:\r\n```\r\ntorch.Tensor | MetaTensor\r\n```\r\nIike we used in: https://github.com/Project-MONAI/MONAI/blob/c8735079a8ab6f64881a9b0205d4ac73676628...
1
python
): if url: formats.append({ 'format_id': ['sd-wmk', 'sd', 'hd-wmk', 'hd'][i], 'format_note': ['SD, watermarked', None, 'HD, watermarked', None][i], 'url': url, 'ext...
Review this code and list any quality issues.
[ { "issue": "use `traverse_obj()` and make everything non-fatal", "severity": "minor", "line": 26 } ]
1
python
if isinstance(e.cause, HTTPError) and e.cause.status == 401: resp = self._parse_json( e.cause.response.read().decode(), None, fatal=False) or {} message = resp.get('message') or resp.get('code') self.report_warning(message or self._LOGIN_ERR_MESSAGE) ...
Review this code and list any quality issues.
[ { "issue": "same as above\r\n```suggestion\r\n user = options['user']\r\n```", "severity": "minor", "line": 26 } ]
1
python
import os from dotenv import load_dotenv # from vanna.pgvector import PG_VectorStore # from vanna.openai import OpenAI_Chat # assume .env file placed next to file with provided env vars load_dotenv() # def get_vanna_connection_string(): # server = os.environ.get("PG_SERVER") # driver = "psycopg" # port ...
Review this code and list any quality issues.
[]
0
python
ti_carrier = Trace.inject() ti.context_carrier = ti_carrier ti.span_status = SpanStatus.ACTIVE self.active_spans.set("ti:" + ti.id, ti_span) else: self.log.debug( "Found span_status '%s', ...
Review this code and list any quality issues.
[]
0
python
state = hass.states.get("switch.outdoor_smart_plug_relay") assert state is not None assert state.state == "on" # Test with state = 0.0 (off) await update_callback(StateChange(state=0.0)) await hass.async_block_till_done() state = hass.states.get("switch.outdoor_smart_plug_relay") assert st...
Review this code and list any quality issues.
[]
0
python
``np.histogram_bin_edges`` chooses 1 bin instead, which may not be optimal. If the IQR is 0, it's unlikely any variance-based estimators will be of use, so we revert to the Sturges estimator, which only uses the size of the dataset in its calculation. Parameters ---------- x : array_like ...
Review this code and list any quality issues.
[ { "issue": "Two comments:\r\n1. The logarithm rule is basically the sturges rule, I think. So I think you could just re-use that directly with some factor? (I don't have an intuition for how the two rules behave, so not sure what this changes in practice yet.)\r\n There might be a fun difference, in that yo...
1
python
n_samples: number of patch samples r_state: a random state container Returns: a list of `n_samples` N-D integers representing the spatial sampling location of patches. """ check_non_lazy_pending_ops(w, name="weighted_patch_samples") if w is None: raise ValueError("w must be an ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n r_samples = r_state.random(n_samples)\r\n r, *_ = convert_to_dst_type(r_samples, v, dtype=r_samples.dtype)\r\n```\r\n\r\nWould this not be equivalent to what you're wanting to accomplish? I think `convert_to_dst_type` is getting rather complicated now with various opt...
1
python
import http.client from anyio import create_task_group, to_thread from loguru import logger from exo.shared.topology import Topology from exo.shared.types.common import NodeId async def check_reachability( target_ip: str, expected_node_id: NodeId, self_node_id: NodeId, out: dict[NodeId, set[str]], )...
Review this code and list any quality issues.
[ { "issue": "Related to above, hardcoding 52415 here could be problematic since technically we give the ability to override the api port.", "severity": "minor", "line": 19 } ]
1
python
logger.error('Automation Analytics TAR not found') return False if not os.path.exists(path): logger.error('Automation Analytics TAR {} not found'.format(path)) return False if "Error:" in str(path): return False logger.debug('shipping analytics file: {}'.format(path)) ur...
Review this code and list any quality issues.
[ { "issue": "the 3rd parameter to OICClient is token_url, not the url we wish to make a request to in `make_request`. This can be hardcoded like we did here https://github.com/ansible/awx/blob/4487f2afa702e7740119ad50fc0d793abf017201/awx/playbooks/action_plugins/insights.py#L12", "severity": "minor", "li...
1
python
#!/usr/bin/env python2 """ Copyright (C) 2023 Mandiant, Inc. All Rights Reserved. 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: [package root]/LICENSE.txt Unless required by applicable law or agr...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n#!/usr/bin/env python3\r\n```", "severity": "minor", "line": 1 } ]
1
python
1/(x**2 + 2*x + 2)**(S(3)/2), manualintegrate(1/(x**2 + 2*x + 2)**(S(3)/2), x) ) # Recursive Case: n = -5 assert_is_integral_of( 1/(x**2 + 1)**(S(5)/2), manualintegrate(1/(x**2 + 1)**(S(5)/2), x) ) assert_is_integral_of( 5/(x**2 + 1)**(S(5)/2), manualintegrat...
Review this code and list any quality issues.
[ { "issue": "We don't need the `factor` test if `assert_is_integral_of` succeeds.", "severity": "minor", "line": 26 } ]
1
python
r'window\.__INITIAL_STATE__\s*=', webpage, 'window.__INITIAL_STATE__', display_id)['content']['clipDetails'] video_data = self._download_json( f'https://um.viuapi.io/drm/v1/content/{display_id}', display_id, data=b'', headers={'Authorization': ViuOTTNewBaseIE._TOKEN, **self._...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'title': (traverse_obj(initial_state_json, 'title', 'display_title')\r\n or episode_json.get('name')),\r\n```\r\nsame below", "severity": "minor", "line": 26 } ]
1
python
return cls.COLOR_DIFF return cls.DIFF if diff else cls.YES # Legacy name, left for integrations. FileMode = Mode def read_pyproject_toml( ctx: click.Context, param: click.Parameter, value: Optional[str] ) -> Optional[str]: """Inject Black configuration from "pyproject.toml" into defaults in `ctx`. ...
Review this code and list any quality issues.
[ { "issue": "What is the reason for this change?", "severity": "minor", "line": 26 } ]
1
python
self._client = chromadb.PersistentClient( path=self.persist_directory, settings=Settings(anonymized_telemetry=False, allow_reset=True), ) return self._client def _get_embedding_function(self): """Get or create the embedding function. If no embedd...
Review this code and list any quality issues.
[ { "issue": "The comment states \"ChromaDB will use the embedding function that was stored with the collection\" but this is only partially accurate. ChromaDB stores the embedding function configuration, but when you call collection methods that require embeddings (like query with text), the collection needs acc...
1
python
.. code-block:: config.assessor.name = 'Medianstop' config.tuner.class_args = { 'optimize_mode': 'maximize', 'start_step': 5 } Parameters ---------- optimize_mode Whether optimize to minimize or maximize trial result. start_step A trial i...
Review this code and list any quality issues.
[]
0
python
# # 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 agreed to in writing, software # distributed under ...
Review this code and list any quality issues.
[ { "issue": "@ctseng777 I believe the imports should change too!", "severity": "minor", "line": 26 } ]
1
python
class Mobject(Container): """Mathematical Object: base class for objects that can be displayed on screen. There is a compatibility layer that allows for getting and setting generic attributes with ``get_*`` and ``set_*`` methods. See :meth:`set` for more details. Attributes ---------- subm...
Review this code and list any quality issues.
[ { "issue": "I know this automatically gets converted to a classmethod by python, but I'd prefer being explicit about it nonetheless. Also best practice is to forward `**kwargs` on to the parent method, even if `object.__init_subclass__` just errors if it gets keyword arguments.\r\n```suggestion\r\n @classmet...
1
python
description="Seconds from start to end of run", ) duration_cpu: float = Field( default=0, description="CPU sec of duration", ) node_exec_time: float = Field( default=0, description="Seconds of total node runtime", ) node_exe...
Review this code and list any quality issues.
[ { "issue": "Please also add the new fields to `GraphExecutionMeta.stats` here:\r\nhttps://github.com/Significant-Gravitas/AutoGPT/blob/1ad6c76f9ccf9f356eb742f9f9c6d99ab14fb2d4/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts#L272-L288", "severity": "minor", "line": 26 } ]
1
python
BoolVariable("debug_symbols", "Add debugging symbols to release/release_debug builds", True), EnumVariable("windows_subsystem", "Windows subsystem", "gui", ("gui", "console")), BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False), ("msvc_version", ...
Review this code and list any quality issues.
[ { "issue": "I guess it should be simply a single `mingw_prefix` that can be set alongside `arch`.", "severity": "minor", "line": 26 } ]
1
python
# Check that old node can restore from the backup. self.old_node.restorewallet("relative_restored", migrate_res['backup_path']) wallet = self.old_node.get_wallet_rpc("relative_restored") assert wallet.gettransaction(txid) assert_equal(bals, wallet.getbalances()) info = wallet.ge...
Review this code and list any quality issues.
[ { "issue": "Can we add more stricter checks on the transaction received here.\r\n\r\nFor example:\r\n```\r\ntx = wallet.gettransaction(txid)\r\nassert_equal(tx[\"amount\"], 1)\r\nassert_equal(tx[\"confirmations\"], 1)\r\n```\r\nThis gives you tighter guarantees and helps with debugging if the test fails.", ...
1
python
from argcomplete import warn from promptflow._sdk._constants import ListViewType from promptflow.client import PFClient MAX_RESULTS = 20 def run_name_completer(prefix, parsed_args, **kwargs): client = PFClient() runs = client.runs.list(list_view_type=ListViewType.ALL) if len(runs) > MAX_RESULTS: ...
Review this code and list any quality issues.
[ { "issue": "do a max_results=MAX_RESULTS +1 here? So we won't query too much rows from the db in memory.", "severity": "major", "line": 11 } ]
1
python
data_cls: Type[CameraData], manager: "gs.SensorManager", ): super().__init__(options, idx, data_cls, manager) self._options: RasterizerCameraOptions self._camera_node = None self._camera_target = None self._camera_wrapper = None self._camera_registered = False...
Review this code and list any quality issues.
[ { "issue": "`scene.visualizer` is guaranteed to exist. No point to use `getattr` here.", "severity": "minor", "line": 26 } ]
1
python
- deeplake_dataloader: optional parameter. If specified represents the parameters of the deeplake dataloader. Deeplake dataloader parameters are: "shuffle", "batch_size", "num_workers". This parameter exists for train as well as for val. - "shuffle": if True shuffles the dataset. - "batch_size": size of...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n gt_masks is optional parameter and lets say you want to train pure detecter this part is going to exclude. Other mappings are mandatory\r\n```", "severity": "minor", "line": 26 } ]
1
python
assertion = self._call_bamgrid_api( 'accounts/grant', video_id, payload={'id_token': cookie.value.split('|')[1]}, headers={ 'Authorization': token, 'Content-Type': 'application/json; charset=UTF-8' })['assertion'] token ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n resource = self._get_mvpd_resource('ESPN', video_data['name'], video_id, None)\r\n```", "severity": "minor", "line": 26 } ]
1
python
) -> list[dict[str, Any]]: ... ls_mapper: dict[str, str] ls_mapper_r: dict[str, str] def contiguous_regions(mask: ArrayLike) -> list[np.ndarray]: ... def is_math_text(s: str) -> bool: ... def violin_stats( X: ArrayLike, method: tuple[Literal["GaussianKDE"], Literal["scott", "silverman"] | float | Callable] | ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n alias_mapping: type[Artist] | Artist | None = ...,\n```\nI haven't checked but I _think_ this will clear up the stubtest failure. We do not have guidance for removal of a default in the guide, but I think the closest is\n\n> Items decorated with `@_api.delete_parameter` should in...
1
python
os.remove(file_src) return None def hash_proxy_dict(proxy_dict)->str: try: data = dict(proxy_dict) except Exception: data = {} data_str = json.dumps(data, sort_keys=True, default=str) return hashlib.md5(data_str.encode("utf-8")).hexdigest() def compare_checksums(src_path:st...
Review this code and list any quality issues.
[ { "issue": "The return statement at line 379 is indented inside the with block for writing the file. This means the function will return False before the file write operation completes and the context manager closes the file properly. The return statement should be dedented to be at the same level as the else b...
1
python
result = CliRunner().invoke(kedro_cli, [command]) assert ( f"Registered CLI hooks from 1 installed plugin(s): " f"{fake_plugin_distribution.metadata['name']}-{fake_plugin_distribution.version}" in caplog.text ) assert ( f"Before command `{command}`...
Review this code and list any quality issues.
[ { "issue": "This part can be reverted then?", "severity": "minor", "line": 26 } ]
1
python
from sympy.core.function import expand from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.sets.sets import Interval from sympy.simplify.simplify import simplify from sympy.physics.continuum_mechanics.beam import Beam from sympy.fun...
Review this code and list any quality issues.
[ { "issue": "There should be a space after comma here. I don't know why you have deleted it. Please see PEP 8:\nhttps://peps.python.org/pep-0008/", "severity": "minor", "line": 8 } ]
1
python
def dump_port_to_config(port): port_file_path = get_port_file_location() # Set port to ~/.promptflow/pfs/**_pf.port, if already have a port in file , will not write again. with open(port_file_path, "r+", encoding=DEFAULT_ENCODING) as f: service_config = load_yaml(f) or {} service_config["ser...
Review this code and list any quality issues.
[ { "issue": ": ) I think we should add some docs on this constant port in our pf service start help", "severity": "minor", "line": 26 } ]
1
python
chat interface for interacting with the agent. By default, the UI is fetched from a CDN and cached on first use. The returned Starlette application can be mounted into a FastAPI app or run directly with any ASGI server (uvicorn, hypercorn, etc.). Note that the `deps` and `model_setting...
Review this code and list any quality issues.
[ { "issue": "Can we not have this one? No one will really do this, and even if they do, they can create a file and pass it, it's not really an issue.", "severity": "minor", "line": 26 } ]
1
python
# ============================================================ # CUDA # ============================================================ elif has_working_cuda() and has_nvidia_gpu_pci(): version_out = '' if os.name == 'posix': for p in ( '/...
Review this code and list any quality issues.
[ { "issue": "Bare except catches all exceptions including keyboard interrupts and system exit signals. This can mask critical errors and make debugging difficult. Specify explicit exception types like OSError, FileNotFoundError, or at minimum use \"except Exception:\" to avoid catching system-level exceptions.\n...
1
python
cloudtrail_errors = {} cloudtrail_errors_j = red.get( config.get( "celery.cache_cloudtrail_errors_by_arn.redis_key", "CLOUDTRAIL_ERRORS_BY_ARN", ) ) if cloudtrail_errors_j: cloudtrail_errors = json.loads(cloudtrail_errors_j) s3_error_topic = config.get("...
Review this code and list any quality issues.
[ { "issue": "I'm not sure what `role_details.get(\"tags\")` returns 🤔", "severity": "minor", "line": 26 } ]
1
python
e.data += e2.data e.raw += e.raw amount = 10000 raw = self.__read(amount) data = str(raw, self.encoding, "replace") e.data += data e.raw += raw return e def clear(self): """ Clear the console screen. ""...
Review this code and list any quality issues.
[ { "issue": "perhaps use `try`/`except NameError` here, instead of the `None` checks?", "severity": "minor", "line": 26 } ]
1
python
class SubTaskThatFails(luigi.Task): def complete(self): return False def run(self): raise Exception() class CmdlineTest(unittest.TestCase): def setUp(self): MockTarget.fs.clear() @mock.patch("logging.getLogger") def test_cmdline_main_task_cls(self, logger): luigi...
Review this code and list any quality issues.
[ { "issue": "This shouldn't be needed to change right?", "severity": "minor", "line": 26 } ]
1
python
FilePath, ReadBuffer, ) _unix_origin = Timestamp("1970-01-01") _sas_origin = Timestamp("1960-01-01") def _convert_datetimes(sas_datetimes: pd.Series, unit: str) -> pd.Series: """ Convert to Timestamp if possible, otherwise to datetime.datetime. SAS float64 lacks precision for more than ms re...
Review this code and list any quality issues.
[ { "issue": "nit: Not sure if storing the thresholds in a numpy array here is doing much since these values are just iterated over later below e.g just could simplify below to\n\n```python\nfor threshold in [_SAS_MARCH1_4000, _SAS_MARCH1_8000]:\n correction[valid] += (values[valid] >= np.int64(threshold * sca...
1
python
torch_attn_ref_out = torch_attn_ref( q[start_idx:end_idx], k[start_idx:end_idx], v[start_idx:end_idx], end_idx - start_idx, num_heads, head_size ) out_torch.append(torch_attn_ref_out) start_idx = end_idx return torch.cat(out_torch, dim=0) @pytest.mark.skipif(not (HAS_TRITON and...
Review this code and list any quality issues.
[ { "issue": "To be updated in the preceding PR", "severity": "minor", "line": 26 } ]
1
python
{"style": "casual", "topic": "science"}, ] result = synthesizer.synthesize(samples, mock_generated_attribute) assert len(result) == 2 for item in result: assert isinstance(item, dict) assert "generated_content" in item @patch("oumi.core.synthesis.attribute_synthesizer.build_inference...
Review this code and list any quality issues.
[]
0