language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
tags=tags_metadata, ) openapi_schema["info"]["x-logo"] = { "url": "https://lh3.googleusercontent.com/drive-viewer" "/AK7aPaD_iNlMoTquOBsw4boh4tIYxyEuhz6EtEs8nzq3yNkNAK00xGj" "E1KUCmPJSk3TYOjcs6tReG6w_cLu1S7L_gPgT9z52iw=s2560" } app.openapi_schema = openapi_schema return app....
Review this code and list any quality issues.
[ { "issue": "It is indeed too aggressive... maybe exposing it in the configuration would be a good idea, so production setups are not too exposed. I'd actually disable this by default so people consciously turn it on when needed.", "severity": "minor", "line": 26 } ]
1
python
webpage = self._download_webpage(url, video_id, *args, fatal=fatal, note=note, **kwargs) return self._parse_json(webpage, video_id, fatal=fatal) def _extract_formats(self, video_info): media_info = traverse_obj(video_info, ('page_info', 'media_info')) formats = [{ **traverse_obj...
Review this code and list any quality issues.
[ { "issue": "we don't want to add format URLs if they don't contain `label=` ?", "severity": "minor", "line": 26 } ]
1
python
self._move_up() elif direction == "down": self._move_down() elif direction == "left": self._move_left() elif direction == "right": self._move_right() def is_game_over(self) -> bool: for i in range(4): for j in range(4): ...
Review this code and list any quality issues.
[]
0
python
import itertools import hashlib import json import re import time from .common import InfoExtractor from ..compat import ( compat_HTTPError, ) from ..utils import ( ExtractorError, format_field, float_or_none, get_element_by_attribute, int_or_none, lowercase_escape, str_or_none, str...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n_ENCODING_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'\r\n```", "severity": "minor", "line": 26 } ]
1
python
BinarySensorEntityDescription( key="connector.status", translation_key="connector_status", device_class=BinarySensorDeviceClass.PLUG, ), BinarySensorEntityDescription( key="charging.status", translation_key="charging_status", device_class=BinarySensorDeviceClass.B...
Review this code and list any quality issues.
[ { "issue": "why would it be `None`? It looks like it's always set", "severity": "minor", "line": 26 } ]
1
python
logits: torch.Tensor, sequences: torch.LongTensor, num_actions: int, shard_config, vocab_size: int = None, ) -> torch.Tensor: """Calculate action log probs. Args: logits (torch.Tensor): Output tensor of Actor.forward.logits. sequences (torch.LongTensor): Input sequences. ...
Review this code and list any quality issues.
[ { "issue": "`dist_log_prob` and `log_probs_from_logits ` are same level of function but different version, which means that one is for non-tp and one is for tp. \r\n\r\nThus, the input and output should keep as similar as possible.\r\n\r\nFor example, both functions have `log_probs = log_probs.squeeze(-1)`, but...
1
python
assert last_lines[1] == "E ValueError: hello" def test_repr_traceback_and_excinfo(self, importasmod) -> None: mod = importasmod( """ def f(x): raise ValueError(x) def entry(): f(0) """ ) excinfo = pytest.raises(Va...
Review this code and list any quality issues.
[]
0
python
params = self.get_js_init_params(html) self.assertEqual( params, [ "alpha", "/admin/tag-autocomplete/", {"allowSpaces": False, "tagLimit": 3, "autocompleteOnly": False}, ], ) @override_settings(TAG_SPACES_ALLOWED=F...
Review this code and list any quality issues.
[ { "issue": "This can be simplified with `self.assertWarns()`. We also want to assert the warning message – we can use `self.assertWarnsMessage()` for this. And the deprecation is only raised when `render()` is called, so let's minimise the scope of the context manager's block to be more specific. Finally, I thi...
1
python
from .common import InfoExtractor from ..utils import ( NO_DEFAULT, int_or_none, unescapeHTML, ) class TVN24IE(InfoExtractor): _WORKING = False _VALID_URL = r'https?://(?:(?!eurosport)(?:[^/]+)\.)?tvn24(?:bis)?\.pl/(?:[^/]+/)*(?P<id>[^/]+)' _TESTS = [{ 'url': 'http://www.tvn24.pl/wiado...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:(?!eurosport)[^/]+\\.)?tvn24(?:bis)?\\.pl/(?:[^/?#]+/)*(?P<id>[^/?#]+)'\r\n```", "severity": "minor", "line": 11 } ]
1
python
# their prefixes. prefix = text_encoder_name if prefix is None else prefix # Safe prefix to check with. if hotswap and any(text_encoder_name in key for key in state_dict.keys()): raise ValueError("At the moment, hotswapping is not supported for text encoders, please pass `hotswap=False`.") # L...
Review this code and list any quality issues.
[ { "issue": "Not specific to this PR, but would it be better to rename `rank` to `rank_pattern`?", "severity": "minor", "line": 26 } ]
1
python
r"\.lan$", # Local area network r"\.intranet$", # Intranet domains r"\.private$", # Private domains ] for pattern in internal_patterns: if re.search(pattern, host_lower): return True # If none of the internal patterns match, assume it's external return False cl...
Review this code and list any quality issues.
[ { "issue": "The docstring still states 'enabled (bool): Whether to enable maintenance notifications handling. Defaults to False.' but the parameter now accepts Union[bool, Literal[\\\"auto\\\"]] and defaults to \\\"auto\\\". The documentation should be updated to reflect the new parameter type and describe all ...
1
python
) -> ResNet: model: ResNet = ResNet(block, layers, block_inplanes, **kwargs) if pretrained: if isinstance(pretrained, str): if Path(pretrained).exists(): logger.info(f"Loading weights from {pretrained}...") checkpoint = torch.load(pretrained, map_location=devi...
Review this code and list any quality issues.
[ { "issue": "May I know why must have this `state_dict` key here? What if users use their own pre-trained weights?", "severity": "minor", "line": 26 } ]
1
python
class R: def __bool__(self): buf.release() return True max_proto = getattr(self, "proto", pickle.HIGHEST_PROTOCOL) for proto in range(5, max_proto + 1): obj, sub = factory() buf = pickle.PickleBuffer(obj) buffer_callback = ...
Review this code and list any quality issues.
[ { "issue": "Actually, I was probably being silly. Instead of this `n` etc,\njust write\n\n```\nobj = memoryview(b\"a\" * 32)[10:26]\nsub = b\"a\" * len(obj)\nreturn obj, sub\n```", "severity": "major", "line": 26 } ]
1
python
class MPMOptions(Options): """ Options configuring the MPMSolver. Note ---- MPM is a hybrid lagrangian-eulerian method for simulating soft materials. In the eulerian phase, it uses a grid representation. The `upper_bound` and `lower_bound` specify the simulation domain, but a safety padding will be...
Review this code and list any quality issues.
[ { "issue": "I'm not convinced it is relevant to have a flag to disable this feature. What is supposed to be the drawback of enabling this systematically? Flags complexifying the control flow should only be added if necessary because it makes the codebase harder to maintain and comprehend.", "severity": "min...
1
python
# Remove IPv6 addresses because on some CI environments "::1" is not configured # on the system (so our test_ipv6_local() would return False), but it is # possible to bind on "::". This makes it unpredictable whether to expect # that bitcoind has bound on "::1" (for RPC) and "::" (fo...
Review this code and list any quality issues.
[ { "issue": "we could make this manual iteration more pythony with something like:\r\n```python\r\nfrom itertools import combinations_with_replacement\r\naddr = f\"127.0.0.1:11012\"\r\nfor opt1, opt2 in combinations_with_replacement([f\"-bind={addr}\", f\"-bind={addr}=onion\", f\"-whitebind=noban@{addr}\"], 2):\...
1
python
import hashlib import json try: from youtube_transcript_api import YouTubeTranscriptApi except ImportError: raise ImportError( 'YouTube video requires extra dependencies. Install with `pip install youtube-transcript-api "`' ) try: from langchain_community.document_loaders import YoutubeLoader ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nimport json\r\nimport logging\r\n```", "severity": "minor", "line": 2 } ]
1
python
def _real_extract(self, url): video_id = self._match_id(url) formats, subtitles = [], {} airings = self._download_json( f'https://search-api-mlbtv.mlb.com/svc/search/v2/graphql/persisted/query/core/Airings?variables=%7B%22partnerProgramIds%22%3A%5B%22{video_id}%22%5D%2C%22applyEsniMe...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'id': video_id,\r\n 'title': traverse_obj(airings, (..., 'titles', 0, 'episodeName'), get_all=False),\r\n 'formats': formats,\r\n 'subtitles': subtitles,\r\n 'http_headers': {'Authorization': f'Bearer {self._access_token}'},\r\...
1
python
def float(self, *args): # Checks if the model is quantized if getattr(self, "is_quantized", False): raise ValueError( "`.float()` is not supported for quantized model. Please use the model as it is, since the" " model has already been cast to the correct `dtyp...
Review this code and list any quality issues.
[ { "issue": "`_no_split_modules` is for specifying the modules that have residual connections so that we don't split them when using `device_map` on multiple devices. I don't think it's legacy yet.", "severity": "minor", "line": 26 } ]
1
python
f"No to-do list: {list_name}", "list_not_found" ) # Add to list await target_list.async_create_todo_item( TodoItem(summary=item, status=TodoItemStatus.NEEDS_ACTION) ) response: intent.IntentResponse = intent_obj.create_response() response.async_set_resul...
Review this code and list any quality issues.
[ { "issue": "`ListCompleteItem` completes only the first matching item. Here we affect all of them. Is there a reason for not keeping it consistent?", "severity": "minor", "line": 26 } ]
1
python
) self.resource_pool_to_cls[resource_pool][str(Role.RefPolicy)] = ref_policy_cls # create a reward model if reward_fn is None # for legacy discriminative reward model, we create a reward model worker here # for reward loop discriminative reward model, we create a reward loop manager...
Review this code and list any quality issues.
[]
0
python
# Act result = pd.merge_asof(left, right) # Assert expected_duplication_allowance = allow_on_left and allow_on_right assert result.flags.allows_duplicate_labels == expected_duplication_allowance def test_merge_propagates_metadata_from_equal_input_metadata(): """Check that pandas.merge sets the me...
Review this code and list any quality issues.
[ { "issue": "I don't think this will check whether or not a deep copy is made. Recommend doing\n\n assert result.attrs is not left.attrs\n assert result.attrs[\"a\"] is not left.attrs[\"a\"]\n\ninstead. Also I recommend adding in `right` as well for good measure.", "severity": "minor", "line": 26 ...
1
python
CommitOperationAdd, CommitOperationDelete, DatasetCard, DatasetCardData, HfApi, HfFileSystem, ) from datasets import config from datasets.info import DatasetInfosDict from datasets.load import load_dataset_builder from datasets.utils.metadata import MetadataConfigs def delete_from_hub( repo_i...
Review this code and list any quality issues.
[ { "issue": "(nit) maybe add a sanity check to make sure it's a file in the same repo (in case someone defines a dataset with data_files urls from another repo)", "severity": "minor", "line": 26 } ]
1
python
self.seq_data_parallel_group = groups._get_sequence_data_parallel_group() self.seq_parallel_group = groups._get_sequence_parallel_group() self.seq_dp_world_size = groups._get_sequence_data_parallel_world_size() self.mp_world_size = groups._get_model_parallel_world_size() self.expert_para...
Review this code and list any quality issues.
[ { "issue": "Flash attention implementation is not device agnostic and will not run all all platforms.\r\nIt's better to keep the current module forward and not replace it's implementation.", "severity": "minor", "line": 26 } ]
1
python
os.environ['COQUI_TOS_AGREED'] = '1' os.environ['PYTHONIOENCODING'] = 'utf-8' os.environ['CALIBRE_NO_NATIVE_FILEDIALOGS'] = '1' os.environ['CALIBRE_TEMP_DIR'] = tmp_dir os.environ['CALIBRE_CACHE_DIRECTORY'] = tmp_dir os.environ['CALIBRE_CONFIG_DIRECTORY'] = tmp_dir os.environ['TMPDIR'] = tmp_dir os.environ['GRAD...
Review this code and list any quality issues.
[ { "issue": "The LD_PRELOAD environment variable is being set unconditionally with an aarch64-specific library path. This will cause issues on non-aarch64 platforms (x86_64, Windows, macOS) where this library path does not exist. The code should check the platform architecture before setting this environment var...
1
python
import datetime import re import urllib.parse from .common import InfoExtractor from ..utils import ( ExtractorError, OnDemandPagedList, str_to_int, unified_strdate, remove_end, ) class MotherlessIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?motherless\.com/(?:g/[a-z0-9_]+/|G[VIG]?[A-F...
Review this code and list any quality issues.
[ { "issue": "sort\r\n```suggestion\r\n remove_end,\r\n str_to_int,\r\n unified_strdate,\r\n```", "severity": "minor", "line": 11 } ]
1
python
try: # Try to parse as JSON first body = json.loads(body) except json.JSONDecodeError: # If it's not valid JSON and just plain text, # we should send it as plain text instead input_data.json_format = Fals...
Review this code and list any quality issues.
[ { "issue": "can we log more than this? this is no more help than the error message itself :')\r\n\r\nTo debug, the request URL at the very least would be helpful", "severity": "critical", "line": 26 } ]
1
python
first = await response_stream.peek() if isinstance(first, _utils.Unset): raise ValueError('Stream function must return at least one item') yield FunctionStreamedResponse( model_request_parameters=model_request_parameters, _model_name=self._model_name, _it...
Review this code and list any quality issues.
[]
0
python
track_info = tralbum.get('trackinfo') if not track_info: raise ExtractorError('The page doesn\'t contain any tracks') # Only tracks with duration info have songs entries = [ self.url_result( urljoin(url, t['title_link']), BandcampIE.ie_key(), ...
Review this code and list any quality issues.
[ { "issue": "Sorry, I had a missing `=`: what I meant was `r'https?://(?:www\\.)?bandcamp\\.com(?:/radio)?/?\\?.*?(?<=[?&])show=(?P<id>\\d+)'`:\r\n* `https?://(?:www\\.)?bandcamp\\.com(?:/radio)?/?\\?` to match the scheme://domain possibly followed by `/radio` and then possibly by `/`, before `?` that introduces...
1
python
You can use `random_state` for reproducibility. Parameters ---------- n : int, optional Number of items from axis to return. Cannot be used with `frac`. Default = 1 if `frac` = None. frac : float, optional Fraction of axis items to return. Cannot be u...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n When replace = False will not allow ``(n * max(weights) / sum(weights)) > 1``,\r\n to avoid biased results.\r\n```", "severity": "minor", "line": 26 } ]
1
python
If the morph type is unsupported. """ from genesis.engine.materials.FEM.cloth import Cloth as ClothMaterial is_cloth = isinstance(self.material, ClothMaterial) self._uvs = None if is_cloth: # Cloth: load surface mesh directly (no tetrahedralization) if i...
Review this code and list any quality issues.
[ { "issue": "* Everything must fit into 120 chars limit, including comments\n* We prefer explicit check instead of try-except in this context\n```python\n# Load UVs from mesh (1:1 mapping for cloth).\n# UVs are not always available in 3D file, in case they are missing we set the entity UVs to None when UVs are N...
1
python
backend = [TransformBackends.TORCH, TransformBackends.NUMPY] def __init__(self, func: Callable | None = None, inv_func: Callable = no_collation) -> None: if func is not None and not callable(func): raise TypeError(f"func must be None or callable but is {type(func).__name__}.") self.func...
Review this code and list any quality issues.
[]
0
python
body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = cre...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Case 1: Both implementations are the same object.\r\n # Checking against one of them.\r\n is_typealiastype = isinstance(tp, typing.TypeAliasType) # type: ignore [attr-defined]\r\n```", "severity": "minor", "line": 26 } ]
1
python
obj2.value = JSONNull() NullableJSONModel.objects.bulk_update([obj1, obj2], fields=["value"]) self.assertSequenceEqual( NullableJSONModel.objects.filter(value=JSONNull()), [obj1, obj2], ) def test_case_expression_with_jsonnull_then(self): obj = JSONModel.obje...
Review this code and list any quality issues.
[ { "issue": "Playing with this test case (using `In()` rather than `__in`) revealed ticket-36787, but we don't have to block on that here.", "severity": "minor", "line": 26 } ]
1
python
'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None, 'uploader_url': owner_profile_url, 'channel_id': channel_id, 'channel_url': format_field(channel_id, None, 'https://www.youtube.com/channel/%s'), ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n\r\n if get_first(video_details, 'isPostLiveDvr'):\r\n```", "severity": "minor", "line": 26 } ]
1
python
import asyncio import re from unittest import mock from unittest.mock import patch import pytest import pytest_asyncio import redis.asyncio as redis from redis.asyncio.connection import ( BlockingConnectionPool, Connection, ConnectionPool, to_bool, ) from redis.auth.token import TokenInterface from tes...
Review this code and list any quality issues.
[ { "issue": "The imports from unittest.mock are split across two lines (line 4 and line 15). These should be combined into a single import statement for consistency and cleaner code organization.", "severity": "minor", "line": 15 } ]
1
python
:ref_classes: Blink class DeletingTextExample(Scene): def construct(self): text = Text("Deleting", color=PURPLE).scale(1.5).to_edge(LEFT) cursor = Rectangle( color = GREY_A, fill_color = GREY_A, fill_opacity...
Review this code and list any quality issues.
[ { "issue": "Same comment as previous class, these should be passed as kwargs", "severity": "minor", "line": 26 } ]
1
python
Recursively parse the nested data in config source, add every item as `ConfigItem` to the resolver. Args: config: config source to parse. id: id of the ``ConfigItem``, ``"#"`` in id are interpreted as special characters to go one level further into the nested structures....
Review this code and list any quality issues.
[ { "issue": "@wyli Should we put this function in the `utils`? I feel it's not part of `ConfigParser` signature.\r\n\r\nThanks.", "severity": "minor", "line": 26 } ]
1
python
vol.Optional("conversation_command"): cv.string, } async def _validate_conversation_command( self, intent_obj: intent.Intent, conversation_command: str ) -> bool: """Validate that a conversation command can be executed.""" from homeassistant.components.conversation import ( # noqa:...
Review this code and list any quality issues.
[ { "issue": "The supported_features attribute typically contains integer flags, not a list. This check should use bitwise operations to test if the ConversationEntityFeature.CONTROL flag is set.\n```suggestion\n and (\n agent_state.attributes.get(\"supported_features\", 0)\n ...
1
python
"""The Portainer integration.""" from __future__ import annotations from pyportainer import Portainer from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_API_KEY, CONF_API_TOKEN, CONF_HOST, CONF_URL, CONF_VERIFY_SSL, Platform, ) from homeassistant.core ...
Review this code and list any quality issues.
[ { "issue": "The docstring \"Remove a config entry from a device\" is ambiguous and doesn't clearly describe what this function does. It should explain that this function determines whether a device can be removed from a config entry by checking if the device still exists in the coordinator data. A better docstr...
1
python
best_score = algo[AlgoKeys.SCORE] self.algo_ensemble.append(best_model) class AlgoEnsembleBuilder: """ Build ensemble workflow from configs and arguments. Args: history: a collection of trained bundleAlgo algorithms. data_src_cfg_filename: filename of the data source. Exa...
Review this code and list any quality issues.
[]
0
python
auth = self._generate_sapisidhash_header(origin) if auth is not None: headers['Authorization'] = auth headers['X-Origin'] = origin return headers def generate_api_headers( self, *, ytcfg=None, account_syncid=None, session_index=None, visitor_data=Non...
Review this code and list any quality issues.
[ { "issue": "on 2nd thought, better to stick with the existing convention\r\n```suggestion\r\n def _generate_webpage_headers(self):\r\n```", "severity": "minor", "line": 26 } ]
1
python
import tkinter.messagebox from tkinter.simpledialog import SimpleDialog import numpy as np from PIL import Image, ImageTk import matplotlib as mpl from matplotlib import _api, backend_tools, cbook, _c_internal_utils from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationTo...
Review this code and list any quality issues.
[ { "issue": "According to https://github.com/astral-sh/python-build-standalone/issues/382, you might be able to use what `uv` uses: https://github.com/astral-sh/uv/blob/c25c800367a5f43069f1c9d778cfd5de1bcc54a6/crates/uv-python/python/get_interpreter_info.py#L639-L645 (i.e., `sysconfig` values).", "severity":...
1
python
failed = bool(self.status in ('failed', 'error', 'canceled')) if self.failed != failed: self.failed = failed if 'failed' not in update_fields: update_fields.append('failed') # Sanity check: Has the job just started? If so, mark down its start # time. ...
Review this code and list any quality issues.
[ { "issue": "I don't understand why you would want to add elapsed to update fields here. You don't get into this unless `self.elapsed` is None, but why would that happen? If the job isn't finished, I don't want to update the field, even if it's setting it to 0.\r\n\r\nMaybe I could see why you'd want to initiali...
1
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import copy from typing import Dict, Tuple, Any from nni.retiarii.utils import uid from nni.common.device import Device from ...graph import Cell, Edge, Graph, Model, Node from ...operation import Operation, _IOPseudoOperation class CPUDevice...
Review this code and list any quality issues.
[ { "issue": "it is a little strange that why not put `CPUDevice` into device.py? it should also be a `dataclass`?", "severity": "minor", "line": 14 } ]
1
python
Returns: A StarExpr that represents all input columns. """ return StarExpr() @PublicAPI(stability="alpha") def download( uri_column_name: str, filesystem: Optional["pyarrow.fs.FileSystem"] = None, ) -> DownloadExpr: """ Create a download expression that downloads content from URIs. ...
Review this code and list any quality issues.
[ { "issue": "Using * can make calls easier to read, and it also allows us to change the ordering of parameters without worrying about breaking users.\n```suggestion\n uri_column_name: str,\n *,\n filesystem: Optional[\"pyarrow.fs.FileSystem\"] = None,\n```", "severity": "minor", "line": 26 } ]
1
python
subs[s.get('language')] = [] subs[s.get('language')].append({'url': s.get('file'), 'format': s.get('format').lower()}) jwt = meta.get('jwt') if not jwt: raise ExtractorError('Site did not provide an authentication token, cannot proceed.') media = self._download_json(sel...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n formats.extend({\r\n 'bitrate': f.get('bitrate'),\r\n 'url': traverse_obj(f, ('streams', strm)),\r\n 'filesize': f.get('filesize'),\r\n 'width': f.get('width'),\r\n 'height': f.get('height'),\r\n ...
1
python
os.makedirs(tmpdir) logging.debug("Temporary test directory at %s" % tmpdir) results_filepath = None if args.resultsfile: results_filepath = pathlib.Path(args.resultsfile) # Stop early if the parent directory doesn't exist assert results_filepath.parent.exists(), "Results file pare...
Review this code and list any quality issues.
[]
0
python
"RespondCostInfo", "RespondFeeEstimates", "RespondHeaderBlocks", "RespondPuzzleSolution", "RespondPuzzleState", "RespondRemovals", "RespondRemoveCoinSubscriptions", "RespondRemovePuzzleSubscriptions", "RespondSESInfo", "RespondToCoinUpdates", ...
Review this code and list any quality issues.
[]
0
python
if signage_point_index <= min_signage_point: # start farming blocks after min_signage_point continue signage_point: SignagePoint = get_signage_point( constants, BlockCache(blocks), ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n sp_index=signage_point_index,\n```\nI'm pretty sure you need this", "severity": "minor", "line": 26 } ]
1
python
], 'categories': ['人文'], 'duration': 93, 'view_count': int, 'like_count': int, } } ] def _real_extract(self, url): scheme = 'https' if url.startswith('https') else 'http' audio_id = self._match_id(url) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nunnecessary", "severity": "minor", "line": 26 } ]
1
python
rows = await conn.execute_fetchall( "SELECT confirmed_index, spent_index, coinbase, puzzle_hash, " "coin_parent, amount, timestamp, coin_name FROM coin_record WHERE confirmed_index>?", (block_index,), ) for row in rows: coin = self....
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n record = CoinRecord(coin, row[0], uint32(0), row[2] != 0, row[6])\r\n```", "severity": "minor", "line": 26 } ]
1
python
# from: https://www.ardmediathek.de/ard/sammlung/der-krieg-und-ich/68cMkqJdllm639Skj4c7sS/ r'.*(?P<ep_info> \((?:Folge |Teil )?(?P<episode_number>\d+)(?:/\d+)?\)).*', r'.*(?P<ep_info>Folge (?P<episode_number>\d+)(?:\:| -|) )\"(?P<episode>.+)\".*', # E.g.: title="Folge 25/42: Symmetri...
Review this code and list any quality issues.
[ { "issue": "when the cookie is not set, this fails, so I need a parameter here to ignore failures\r\n\r\nERROR: [ARDMediathek] Y3JpZDovL2Rhc2Vyc3RlLmRlL29kZXJicnVjaC8yMDI0LTAxLTIwXzAwLTAwLU1FWg: Unable to download JSON metadata: HTTP Error 400: Bad Request (caused by <HTTPError 400: Bad Request>)", "severit...
1
python
else: if not item_index.values[0].subscriptable() and not self.is_sequence: # we're modifying a single sample, convert it to a list as chunk engine expects multiple samples value = [value] self.chunk_engine.update( self.index[item_index], ...
Review this code and list any quality issues.
[ { "issue": "Why do we compare exactly to the list of length 3? Can't max_shape be 2 dimensional array? Let's say 2d masks", "severity": "minor", "line": 26 } ]
1
python
from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry from .conftest import make_mock_module, make_mock_zone ENTITY_ID = "climate.zone_1" async def test_climate_zone_available( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_touchlinesl_full_client: MagicMo...
Review this code and list any quality issues.
[ { "issue": "Best me to assert is its current state, to represent what it should not, instead of what it should not be. :)", "severity": "minor", "line": 26 } ]
1
python
def render_maec(doc: rd.ResultDocument, ostream: StringIO): """ example:: +--------------------------+-----------------------------------------------------------+ | MAEC Schema | MAEC Value | |--------------------------+-------...
Review this code and list any quality issues.
[ { "issue": "create an inner loop here using `for k,v in maec_schema...`?", "severity": "minor", "line": 26 } ]
1
python
def _recalculate_dagrun_queued_at_deadlines( dagrun: DagRun, new_queued_at: datetime, session: Session ) -> None: """ Recalculate deadline times for deadlines that reference dagrun.queued_at. :param dagrun: The DagRun whose deadlines should be recalculated :param new_queued_at: The new queued_at ti...
Review this code and list any quality issues.
[ { "issue": "I think we should join these 2 tables in the query instead of making one query per deadline?", "severity": "minor", "line": 26 } ]
1
python
""" if profile_level == "level_none": level = torch_npu.profiler.ProfilerLevel.Level_none elif profile_level == "level0": level = torch_npu.profiler.ProfilerLevel.Level0 elif profile_level == "level1": level = torch_npu.profiler.ProfilerLevel.Level1 elif profile_level == "level2"...
Review this code and list any quality issues.
[ { "issue": "When setting level0, the configuration item aic_metrics=torch_npu.profiler.AiCMetrics.PipeUtilization can be omitted. In RL scenarios, aic_metrics is rarely used.", "severity": "minor", "line": 26 } ]
1
python
update_url_query, ) class RadikoBaseIE(InfoExtractor): _GEO_BYPASS = False _FULL_KEY = None _HOSTS_FOR_TIME_FREE_FFMPEG_UNSUPPORTED = ( 'https://c-rpaa.smartstream.ne.jp', 'https://si-c-radiko.smartstream.ne.jp', 'https://tf-f-rpaa-radiko.smartstream.ne.jp', 'https://tf-c-r...
Review this code and list any quality issues.
[ { "issue": "the separator character class is a good idea, but we can inline this in the method\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
from .._utils.flow_utils import resolve_python_entry_file Flow._update_working_dir(working_dir) if name is None: name = flow_dag.get("name", _sanitize_python_variable_name(working_dir.stem)) flow_dag["name"] = name entry = flow_dag.get("entry") entry_file = resolve_...
Review this code and list any quality issues.
[ { "issue": "We can't assume that this environment variable is set when user run `pf flow build` locally, right? cc @D-W- @wangchao1230 \r\n\r\nWith current logic, we will always dump no connections?", "severity": "minor", "line": 26 } ]
1
python
if os.path.exists(temp_file.name): try: os.remove(temp_file.name) except OSError: self.report_warning('Unable to delete temporary file "%s"' % temp_file.name) if success: f['__working'] = True ...
Review this code and list any quality issues.
[ { "issue": "This may cause some unnecessary network calls when `--check-formats` is used without ffmpeg. But ig that's fine", "severity": "minor", "line": 26 } ]
1
python
entity_description: ClimateEntityDescription _attr_current_humidity: float | None = None _attr_current_temperature: float | None = None _attr_fan_mode: str | None _attr_fan_modes: list[str] | None _attr_hvac_action: HVACAction | None = None _attr_hvac_mode: HVACMode | None _attr_hvac_modes: ...
Review this code and list any quality issues.
[ { "issue": "should this be float instead, since the humidity attribute is float?", "severity": "minor", "line": 26 } ]
1
python
save_version: Version string to be used for ``save`` operations by all datasets with enabled versioning. It must: a) be a case-insensitive string that conforms with operating system filename limitations, b) always return the latest version when sorted in l...
Review this code and list any quality issues.
[ { "issue": "Maybe\r\n\r\n```suggestion\r\n warnings.warn(\r\n \"`KedroDataCatalog` is currently an experimental feature and will replace the existing `DataCatalog` \"\r\n \"in Kedro 1.0.0, while adopting the original `DataCatalog` name. Several APIs will be removed \"\r\n ...
1
python
aggregates = ChartDataAggregateConfigField() class ChartDataGeohashDecodeOptionsSchema( ChartDataPostProcessingOperationOptionsSchema ): """ Geohash decode operation config. """ geohash = fields.String( metadata={"description": "Name of source column containing geohash string"}, r...
Review this code and list any quality issues.
[]
0
python
raise def close(self) -> None: """Close backend with audit logging.""" self.logger.debug("[AUDIT_BACKEND] Closing backend") start_time = time.perf_counter() try: self.real_backend.close() self._log_operation("CLOSE", start_time, None, True) except Exc...
Review this code and list any quality issues.
[]
0
python
@Author : alexanderwu @File : memory.py @Modified By: mashenquan, 2023-11-1. According to RFC 116: Updated the type of index key. """ from collections import defaultdict from pathlib import Path from typing import Iterable, Set from pydantic import BaseModel, Field from metagpt.schema import Message from metagpt....
Review this code and list any quality issues.
[ { "issue": "when/where to set ignore_id=True? not just in `tests/metagpt/serialize_deserialize/test_serdeser_base.py`.", "severity": "minor", "line": 26 } ]
1
python
j = i + l * d delta_node = self.delta(i, j, i_b) s = ti.u32(0) t = (l + 1) // 2 while t > 0: if self.delta(i, i + (s + t) * d, i_b) > delta_node: s += t t = ti.select(t > 1, (t + 1) // 2, 0) gamma = i + ti.i...
Review this code and list any quality issues.
[ { "issue": "I wonder if the performance will be slower than the original u64.", "severity": "major", "line": 26 } ]
1
python
if copy: sample = sample.copy() meta = sample.meta meta["modified"] = False metas.append(meta) return metas @link def update_info( new_sample, old_value, sub_index: Index, partial: bool, link_creds=None ): if partial: meta = old_value.data() ...
Review this code and list any quality issues.
[ { "issue": "this will only affect updates right not extends?", "severity": "minor", "line": 26 } ]
1
python
"""Generate answers with GPT-4 Usage: python3 get_api_answer.py --model gpt-3.5-turbo """ import argparse import json import os import time import concurrent.futures import shortuuid import tqdm import openai from fastchat.llm_judge.common import ( load_questions, temperature_config, chat_compeletion_ope...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nimport openai\r\nimport shortuuid\r\nimport tqdm\r\n```", "severity": "minor", "line": 14 } ]
1
python
expect(file_chip).to_have_attribute("title", "Click to retry upload") error_message = uploaded_files.get_by_test_id("stChatInputFileError").first expect(error_message).to_be_visible() # Click to retry - this should succeed since we now allow requests through file_chip.click() ...
Review this code and list any quality issues.
[ { "issue": "[question] Is the viewport size important for this test?", "severity": "minor", "line": 26 } ]
1
python
def test_multilabel_hamming_loss(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) w = np.array([1, 3]) assert hamming_loss(y1, y2) == 1 / 6 assert hamming_loss(y1, y1) == 0 assert hamming_loss(y2, y2) == 0 assert hammin...
Review this code and list any quality issues.
[ { "issue": "This change is a consequence of `present_labels` now being an array, not a list.\nSee [this comment](https://github.com/scikit-learn/scikit-learn/pull/32909/changes#r2623035023).", "severity": "minor", "line": 26 } ]
1
python
error: BaseException | str | None, log: Logger, ) -> None: """Send email notification for task errors using SmtpNotifier.""" try: from airflow.providers.smtp.notifications.smtp import SmtpNotifier except ImportError: log.error("Cannot send email notification: `apache-airflow-providers-sm...
Review this code and list any quality issues.
[ { "issue": "⚠️ This needs to replace more things to make it safe html.", "severity": "minor", "line": 26 } ]
1
python
def is_custom_model(model_name: str) -> bool: """Determines whether the model is a custom model defined in oumi registry.""" result: bool = len(model_name) > 0 and REGISTRY.contains( name=model_name, type=RegistryType.MODEL ) return result def find_internal_model_config_using_model_name( m...
Review this code and list any quality issues.
[ { "issue": "nit:\r\n\r\n```\r\nif hf_config is None:\r\n return None\r\n```", "severity": "minor", "line": 26 } ]
1
python
# No XPU on macOS if sys.platform == "darwin": return False # ---------- Linux ---------- if os.name == "posix": # Must have render node if not os.path.exists("/dev/dri/renderD128"): return False # Pr...
Review this code and list any quality issues.
[]
0
python
def extract_thread(contents, entity_payloads): if not parent: tracker['current_page_thread'] = 0 for content in contents: if not parent and tracker['total_parent_comments'] >= max_parents: yield comment_thread_renderer = try_get...
Review this code and list any quality issues.
[ { "issue": "we don't yet know that `content` is a dict, shouldn't use `get`\r\n```suggestion\r\n view_model = (\r\n traverse_obj(comment_thread_renderer, ('commentViewModel', 'commentViewModel', {dict}))\r\n or traverse_obj(content, ('commentViewM...
1
python
subterrain_parameters : dictionary, optional Lets users pick their own subterrain parameters. """ is_free: bool = False randomize: bool = False # whether to randomize the terrain n_subterrains: Tuple[int, int] = (3, 3) # number of subterrains in x and y directions subterrain_size: Tuple[f...
Review this code and list any quality issues.
[ { "issue": "What is this nightmare? Just do `merged = self.default_params | user`.\r\n\r\nAnd merged is not an appropriate name either.", "severity": "minor", "line": 26 } ]
1
python
'title': 'Atomic Heart (пробуем!) спасибо подписчику EKZO!', 'uploader': 'ZitsmanN', 'uploader_id': '13159830', 'release_timestamp': 1683461378, 'release_date': '20230507', 'thumbnail': r're:https://images.vkplay.live/public_video_stream/record/f5e6e3b5-dc52-4...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n **self._extract_common_meta(record_info),\r\n 'id': video_id,\r\n 'formats': self._extract_formats(record_info, video_id),\r\n```", "severity": "major", "line": 26 } ]
1
python
attrs[subresource.name] = self._create_class_partial( name, subresource, service_name, resource_name, model, resource_defs, service_model) def _load_waiters(self, attrs, model): """ Load resource waiters from the model. Each waiter allows you to wait until a...
Review this code and list any quality issues.
[ { "issue": "Yeah I am fine with that. I do not think that it will happen unless there is a bug. Furthermore, since this is an identifier in general, its value cannot be `None` so it make sense not to default to `None`.", "severity": "critical", "line": 26 } ]
1
python
# Optional dependency required for auth: "auth": [ "Authlib>=1.3.2", ], # Optional charting dependencies: "charts": [ "matplotlib>=3.0.0", "graphviz>=0.19.0", "plotly>=4.0.0", # orjson speeds up large plotly figure processing by 5-10x: "orjson>=3.5.0", ...
Review this code and list any quality issues.
[ { "issue": "The new \"performance\" extra is not included in the \"all\" extra. This means users who install `streamlit[all]` will not get the performance enhancements from uvloop and orjson. Consider adding \"performance\" to the \"all\" extra list on line 115, e.g., `\"streamlit[auth,charts,snowflake,sql,pdf,...
1
python
ModeResult(mode=[[3]], count=[[5]]) >>> stats.mode(a, axis=None, keepdims=False) ModeResult(mode=3, count=5) """ xp = array_namespace(a) # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy` if not xp.isdtype(a.dtype, 'numeric'): message = ("Argument `a` is not recog...
Review this code and list any quality issues.
[ { "issue": "See top post. Thoughts appreciated.", "severity": "minor", "line": 26 } ]
1
python
assert entry.state is ConfigEntryState.NOT_LOADED assert len(hass.config_entries.async_entries(DOMAIN)) == 0 assert "Failed to create a backup of the Z-Wave JS add-on" in caplog.text create_backup.side_effect = None stop_addon.reset_mock() create_backup.reset_mock() uninstall_addon.reset_mock() ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n assert \"Failed to uninstall the Z-Wave JS app\" in caplog.text\n```", "severity": "critical", "line": 26 } ]
1
python
k = KubernetesPodOperator( task_id="task", tolerations=k8s_api_tolerations, ) pod = k.build_pod_request_obj(create_context(k)) sanitized_pod = self.sanitize_for_serialization(pod) assert isinstance(pod.spec.tolerations[0], k8s.V1Toleration) assert sanitiz...
Review this code and list any quality issues.
[]
0
python
"""Transform the sample to the KTO format.""" return self.transform_kto(sample) def _extract_from_chat_format(self, sample) -> str: """Extract the last 'assistant' turn in the chat.""" if not isinstance(sample, list): return sample for turn in sample[::-1]: ...
Review this code and list any quality issues.
[ { "issue": "Why is the param name different than the fn it's overriding in BaseMapDataset (samples_iter)? Is the type of the input param different, and if so, why? This isn't a true override if that's the case IMO", "severity": "minor", "line": 26 } ]
1
python
bf16=self.mixed_precision_dtype == MixedPrecisionDtype.BF16, torch_compile=self.compile, save_steps=self.save_steps, save_strategy=save_strategy, logging_first_step=self.logging_first_step, torch_empty_cache_steps=self.empty_device_cache_steps, res...
Review this code and list any quality issues.
[ { "issue": "Let's keep TODO for data_seed. Ideally, let's file a task to handle data_seed properly, and quote its number here.", "severity": "minor", "line": 26 } ]
1
python
import asyncio import contextvars from concurrent.futures import ThreadPoolExecutor import pytest from promptflow.tracing import ThreadPoolExecutorWithContext @pytest.mark.unittest def test_thread_pool_executor_with_context(): var = contextvars.ContextVar("var", default="default_value") var.set("value_in_pa...
Review this code and list any quality issues.
[]
0
python
from __future__ import annotations import logging import os import sys def get_logger(name: str = "supervision", level: int | None = None) -> logging.Logger: """Creates and configures a logger with stdout and stderr handlers. This function creates a logger that sends INFO and DEBUG level logs to stdout, ...
Review this code and list any quality issues.
[ { "issue": "@copilot lets make it private, so it clear it is just for internal usage", "severity": "minor", "line": 8 } ]
1
python
expect(heading_element).to_be_visible() return heading_element def expect_prefixed_markdown( locator: FrameLocator | Locator | Page, expected_prefix: str, expected_markdown: str | re.Pattern[str], exact_match: bool = False, ) -> None: """Find the markdown with the prefix and then ensure that t...
Review this code and list any quality issues.
[]
0
python
print('warning: unused magic string {str_ref}' .format(str_ref=str_ref)) continue # Calculate the most compact guard, i.e., if a magic string is # referenced under various guards, keep the one that is more generic. # E.g., # guard1 = A and B and C and D and...
Review this code and list any quality issues.
[ { "issue": "This seems a bit over complicated:\r\n* Why do we need the `guard[1:]` (what character are we skipping)?\r\n* The `if guard_j is not None:` and `if neg_guard in guard_j:` can be a single `if`. In addition I'm not sure that we even need `guard_j is not None` check.\r\n* If we are appending sets to th...
1
python
# Then if the test run fails, it will output the missing/incorrect fields. # Properties can be added as: # * A value, e.g. # 'title': 'Video title goes here', # * MD5 checksum; start the string with 'md5:', e.g. # 'description': 'md5:098f6bcd4621d373ca...
Review this code and list any quality issues.
[ { "issue": "Use `urlencode_postdata` from `..utils`", "severity": "minor", "line": 26 } ]
1
python
mocked_pubmaster.send.assert_called_once() mt, md = mocked_pubmaster.send.call_args.args assert mt == msg["type"] assert isinstance(md, capnp._DynamicStructBuilder) assert hasattr(md, msg["type"]) mocked_pubmaster.reset_mock() def test_livestream_track(self, mocker): fake_msg = mes...
Review this code and list any quality issues.
[ { "issue": "Make sure to do something like `for i in $(seq 1 1000); do pytest system/webrtc/tests/test_stream_session.py || break; done` before merging this.", "severity": "minor", "line": 26 } ]
1
python
title = video_data.get('data-emission-title') or video_data.get('data-diffusion-title') or self._og_search_title(webpage) description = self._html_search_regex( r'(?s)<div[^>]+class="intro"[^>]*>.*?<h2>(.+?)</h2>', webpage, 'description', default=None) # page has playlist ...
Review this code and list any quality issues.
[ { "issue": "traverse_obj can be used here aswell", "severity": "minor", "line": 26 } ]
1
python
import imp import unittest import sys sys.path.append('../') import sherlock as sh checksymbols = [] checksymbols = ["_", "-", "."] """Test for mulriple usernames. This test ensures that the function MultipleUsernames works properly. More specific, different scenarios are tested and only usernames th...
Review this code and list any quality issues.
[]
0
python
elif error_code == 'needAdult': self.raise_login_required('Adult verification is required for this stream') elif error_code == 'needLogin': self.raise_login_required('Login is required for this stream') elif error_code == 'needCoinPurchase': raise ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'http_headers': {'Origin': 'https://www.pandalive.co.kr'},\r\n```", "severity": "minor", "line": 26 } ]
1
python
project.get_all_coded_files = lambda: [] project.current_step = 'test' # and a developer who will execute any task except for `ls -al test` developer = Developer(project) developer.execute_task = MagicMock() developer.execute_task.side_effect = [ {'success': F...
Review this code and list any quality issues.
[ { "issue": "same as comment above, here it says list of completed steps: 1 and 2 and then it says right now, we're working on step 2. \r\n\r\nStep 2 is completed and we are working on it at same time.", "severity": "minor", "line": 26 } ]
1
python
}] @classmethod def _extract_embed_urls(cls, url, webpage): for mobj in re.finditer( rf'''(?x)<div\s+\bid=["']Player-Attributes-JWID[^>]+\b data-request-url=["']{cls._VALID_URL_BASE_RE}["'][^>]+\b data-asset-id=["']{cls._VALID_URL_ID_RE}["']''', webpage ): ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n asset, 'palyoutPathAudio', 'playoutpathaudio', expected_type=str)\r\n```\r\n\r\nget_all is not doing anything here:\r\n```\r\ntraverse_obj(obj, A, B) => dict_get(obj, ('A', 'B')) => obj.get('A') or obj.get('B')\r\n```", "severity": "minor", "line": 26 } ]
1
python
def __setattr__(self, key, value): msg = "Operation not allowed! " if key in self.__dict__: msg += "Please change datasets through configuration." else: msg += "Please use DataCatalog.add() instead." raise AttributeError(msg) class DataCatalog: """``DataCata...
Review this code and list any quality issues.
[ { "issue": "These new arguments should also be added to the doc string below.", "severity": "minor", "line": 26 } ]
1
python
import textwrap from deeplake.client.config import HUB_REST_ENDPOINT import click from humbug.report import Report from deeplake.client.client import DeepLakeBackendClient from deeplake.client.utils import remove_username_from_config, write_token, remove_token from deeplake.util.bugout_reporter import ( save_repo...
Review this code and list any quality issues.
[ { "issue": "We aren't validating the token to check if it's a valid one anywhere here", "severity": "minor", "line": 21 } ]
1
python
'playlist_mincount': 20, }, { 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/10yearshayaomiyazaki/', 'only_matching': True, }] @classmethod def suitable(cls, url): return False if NhkVodIE.suitable(url) else super().suitable(url) def _extract_meta_from_class_elements(self...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n for episode in episodes:\r\n if episode_path := episode.get('url'):\r\n yield self._extract_episode_info(urljoin(url, episode_path), episode)\r\n```", "severity": "major", "line": 26 } ]
1
python
self, select_labels: Sequence[int] | int, merge_channels: bool = False ) -> None: # pytype: disable=annotation-type-mismatch self.select_labels = ensure_tuple(select_labels) self.merge_channels = merge_channels def __call__( self, img: NdarrayOrTensor, select_labels: Sequence[int] | in...
Review this code and list any quality issues.
[]
0
python
def mock_up_broadcast_object_fn(a: Any, i: int) -> None: raise NotImplementedError("Calling invalid broadcast object function") #### Python equivalents of CPP CUDA functions #### def alloc_pinned_numa_ptr(size: int) -> torch.Tensor: # Create a 1D uint8 CPU tensor in pinned memory, as uint8 == 1 byte # Re...
Review this code and list any quality issues.
[ { "issue": "I like this idea of having the same set of C functions implemented in Python for non-CUDA platforms.\r\n\r\nCan we separate those to a new source file so that we can import it as:\r\n``` \r\nif torch.cuda.is_available():\r\n import lmcache.c_ops as lmc_ops\r\nelse:\r\n import lmcache.mockup_op...
1
python
import functools import re from .common import InfoExtractor from ..networking import HEADRequest from ..utils import ( ExtractorError, OnDemandPagedList, float_or_none, int_or_none, join_nonempty, parse_age_limit, parse_qs, random_uuidv4, unified_strdate, url_or_none, ) from .....
Review this code and list any quality issues.
[ { "issue": "could you add a test (can be `only_matching`) for a url with the `/en/` path?", "severity": "minor", "line": 22 } ]
1