language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
upload_file = UploadFile( tenant_id=self._tenant_id, storage_type=dify_config.STORAGE_TYPE, key=file_key, name=file_key, size=len(img_bytes), extension=image_ext, ...
Review this code and list any quality issues.
[ { "issue": "The URL is constructed using `upload_file.id` before the `upload_file` object is committed to the database. While the `UploadFile` model does generate an ID in its `__init__` method, this creates a potential race condition where the image markdown link is added to the content before the database tra...
1
python
current_token = torch.tensor(batch_token_ids[batch_id], dtype=torch.long, device=logits.device) curretn_socre = torch.gather(current_logit, 0, current_token) curretn_socre = torch.where(curretn_socre < 0, curretn_socre * penalty, curretn_socre / penalty) logits_list.append(current_l...
Review this code and list any quality issues.
[]
0
python
} for key, url in (get_video_info('thumbnail') or {}).items() if url], 'description': clean_html(get_video_info('description')), 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')), 'uploader_id': str_or_none(traverse_obj(api_data, ('...
Review this code and list any quality issues.
[ { "issue": "could do this\r\n```suggestion\r\n if not comments_info.get('server'):\r\n return\r\n\r\n danmaku = traverse_obj(self._download_json(\r\n f'{comments_info[\"server\"]}/v1/threads', video_id, data=json.dumps({\r\n```", "severity": "minor", "line": 26 } ]
1
python
def test_recursive_dict_subclass_in_key(self): self._test_recursive_collection_in_key(MyDict) def test_recursive_frozendict_in_key(self): self._test_recursive_collection_in_key(frozendict, minprotocol=2) def test_recursive_frozendict_subclass_in_key(self): self._test_recursive_collecti...
Review this code and list any quality issues.
[ { "issue": "This does not add anything in comparison with `test_recursive_dict` and `test_recursive_dict_subclass`. The new tests are only needed for immutable frozendict (like there are special tests for tuple and frozenset).", "severity": "minor", "line": 26 } ]
1
python
'id': 'uskn-news', }, 'playlist_mincount': 755, }, { 'url': 'https://www.ondemandkorea.com/en/player/vod/the-land', 'info_dict': { 'id': 'the-land', }, 'playlist_count': 52, }] _PAGE_SIZE = 100 def _fetch_page(self, display_id, page): ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n ie=OnDemandKoreaIE, video_title=episode.get('title'))\r\n```", "severity": "minor", "line": 26 } ]
1
python
}, ) raw_metadata = self._extract_data_attr( self._download_webpage( url, show_id, 'Downloading Show Metadata.', ), show_id, 'blob', ) metadata = traverse_obj(raw_metadata, ( 'appData', 'shows', lambda _,...
Review this code and list any quality issues.
[ { "issue": "don't add `timestamp` if you're just duplicating `release_date`\r\n\r\nI would change `release_date` to `release_timestamp` and add a fallback to the value given in `audio_data`", "severity": "minor", "line": 26 } ]
1
python
# NOTE: if test_baseline == test_contender and # filter_baseline == filter_contender, you are analyzing the stdev description = 'Comparing %s (from %s) to %s (from %s)' % ( filter_baseline, test_baseline, filter_contender, test_contender) else: # should never happen prin...
Review this code and list any quality issues.
[ { "issue": "should `run_or_load_benchmark` also be prefixed with `gbench.util` here?", "severity": "minor", "line": 26 } ]
1
python
def __init__(self, module: Module, precision: str, shard_config: ShardConfig, dp_group: ProcessGroup, use_ddp: bool) -> None: self.stage_manager = shard_config.pipeline_stage_manager self.dp_group = dp_group shardformer = ShardFormer(shard_config) module, self.shared_par...
Review this code and list any quality issues.
[ { "issue": "`find_unused_parameters=False` and `static_graph=False` may lead to correctness issue when there are unused params. This is commonly observed when layer drop is used.", "severity": "minor", "line": 26 } ]
1
python
"""Data needed to create a new crawling request.""" model_config = ConfigDict(populate_by_name=True) url: Annotated[str, BeforeValidator(validate_http_url), Field()] """URL of the web page to crawl""" unique_key: Annotated[str, Field(alias='uniqueKey')] """A unique key identifying the request. Tw...
Review this code and list any quality issues.
[ { "issue": "Are these query string parameters? Not a fan of how httpx decided to name it.", "severity": "minor", "line": 26 } ]
1
python
ret_value = self.__get_content_accessor().get_info( t.cast(str, front_var), newvalue.get(), isinstance(newvalue, _TaipyContentImage) ) if isinstance(ret_value, tuple): newvalue = f"/{Gui._CONTENT_ROOT}/{ret_value[0]}" ...
Review this code and list any quality issues.
[ { "issue": "We'll make that generic at one point hu?", "severity": "minor", "line": 26 } ]
1
python
ranges = [] intervals = itree[start_idx:end_idx] for interval in intervals: ranges.append(interval.data) return sorted(ranges) else: return None def _get_carray_path(self, sid, field): sid_subdir = _sid_subdir_path(sid) # carra...
Review this code and list any quality issues.
[ { "issue": "Though technically there is no data for that date, this error really occurs when there is no data at all for the sid.\r\nShould we have a different exception indicating that there is no data for any date, instead of `NoDataOnDate` which is just for the date requested?", "severity": "minor", ...
1
python
datastudio, deviantart, dipdive, dipity, dotsub, etsy, five_hundred_px, five_min, flickr, funny_or_die, geograph_gg, geograph_uk, github_gist, gmep, hlipp, huffduffer, hulu, ifixit, ifttt, iheart, issuu, justin_tv, kickstarter, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n loom,\nmajor_league_gaming,\n```", "severity": "minor", "line": 26 } ]
1
python
) model = AutoModel.from_pretrained( model_path, trust_remote_code=True, **from_pretrained_kwargs ) return model, tokenizer def get_default_conv_template(self, model_path: str) -> Conversation: model_path = model_path.lower() if "chatglm2" in model_path: ...
Review this code and list any quality issues.
[]
0
python
#!/usr/bin/env python3 import argparse import os import openai import pinecone import time import sys from collections import deque from typing import Dict, List from dotenv import load_dotenv import os # Parse arguments for optional extensions parser = argparse.ArgumentParser() parser.add_argument('-e', '--env', narg...
Review this code and list any quality issues.
[ { "issue": "Being a bit nitpicky here, but the logic as structured will load the extension .env first and then the main, which means the extension can't overwrite anything in the main. We should reverse the order - first load the core .env, then load optional extension(s), which can add more env variables or ov...
1
python
except Exception as e: if isinstance(e, TimeoutError): logger.warning("get blocking timeout, trigger cancel the future task") future.cancel() logger.warning("Error occurred in get_blocking: %s, return None", e) memory_obj = None t2 = time.perf...
Review this code and list any quality issues.
[ { "issue": "Can we make them as `@property` so we don't need to have the `get_` at the beginning? `get_get_xxx` and `get_put_xxx` sound a bit weird.", "severity": "minor", "line": 26 } ]
1
python
while True: try: part = await socket.recv() # Parse message based on format if part.startswith(b"{"): # JSON format - typically from external systems like Mooncake msg_dict = json.loads(part) msg = m...
Review this code and list any quality issues.
[ { "issue": "should this be asyncio.sleep? this is a seaparte thread right?", "severity": "minor", "line": 26 } ]
1
python
Boolean True if ``predicate`` is true for all the derivatives when ``symbol`` is varied in ``range``, False otherwise. """ from sympy.solvers.solveset import solveset expression = sympify(expression) free = expression.free_symbols if symbol is None: if len(free) > 1: ...
Review this code and list any quality issues.
[ { "issue": "Don't catch AttributeError. It is always the wrong approach because it masks bugs and makes it difficult for anyone reading the code to understand which attribute is missing and why it is missing.\r\n\r\nInstead this should be checking the type of something.\r\n\r\nLikewise `except NotImplementedErr...
1
python
formats_ = [] for media in json_data: media_data = json_data.get(media) if not isinstance(media_data, dict): continue if media.startswith('dash'): video_format = self._get_media_format('dash_video', media_data) audio_format = se...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n json_data = self._get_json_data(webpage, video_id)['anyVideo']['gidInformation']['packerData']['video']\r\n\r\n formats = self._media_selector(video_resource.get('videoResource'))\r\n self._sort_formats(formats)\r\n```", "severity": "minor", "line": 26 ...
1
python
# in the form Y/X (UR) if custom_position in ["LEFT", "RIGHT"]: custom_position = "O" + custom_position[0] elif custom_position in ["UP", "DOWN"]: custom_position = custom_position[0] + "O" elif custom_position == "ORIGIN": custom_position = "O" * 2 el...
Review this code and list any quality issues.
[ { "issue": "I don't believe `on_mouse_press` is used anywhere. `button` is an integer in `Scene`, so there is no need for the map unless there are plans to change this in `Scene`.", "severity": "minor", "line": 26 } ]
1
python
optimizer.zero_grad() criterion(outputs).backward() optimizer.step() with shared_tempdir() as tempdir: model_ckpt_path = f"{tempdir}/model" optim_ckpt_path = f"{tempdir}/optimizer" run_model() booster.save_model(fsdp_model, model_ckpt_path, shard=False) boo...
Review this code and list any quality issues.
[ { "issue": "`assert not xxx` is simpler and easy to read", "severity": "minor", "line": 26 } ]
1
python
half = (size[0] * 0.5, size[1] * 0.5) verts = np.array( [ [-half[0], -half[1], 0.0], [half[0], -half[1], 0.0], [half[0], half[1], 0.0], [-half[0], -half[1], 0.0], [half[0], half[1], 0.0], [-half[0], half[1], 0.0], ], dty...
Review this code and list any quality issues.
[ { "issue": "Same. I would rather export `x` and `y` components. More readable I think.", "severity": "minor", "line": 26 } ]
1
python
po_token=player_po_token) except ExtractorError as e: self.report_warning(e) continue if pr_id := self._invalid_player_response(pr, video_id): skipped_clients[client] = pr_id elif pr: # Save client details for introspec...
Review this code and list any quality issues.
[ { "issue": "the name should indicate it is in millseconds", "severity": "minor", "line": 26 } ]
1
python
if row is None: raise Exception("Internal error") if use_file: path = self.get_key_value_path(store_id=store_id, blob_hash=blob_hash) path.parent.mkdir(parents=True, exist_ok=True) # TODO: consider file-system based locking of either the file or the store director...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n d = {}\r\n if self.unconfirmed_keys_values.setdefault(store_id, d) is not d:\r\n```\r\n\r\nor, a bit less fancy pants...\r\n\r\n```suggestion\r\n if store_id not in self.unconfirmed_keys_values:\r\n self.unconfirmed_keys_values[store_id] = {}\r\n ...
1
python
blocks_reorg_chain = bt.get_consecutive_blocks( 4, blocks_reorg_chain, seed=b"2", block_refs=[uint32(5), uint32(11)], transaction_data=spend_bundle2 ) blocks_reorg_chain = bt.get_consecutive_blocks(4, blocks_reorg_chain, seed=b"2") fork_info = ForkInfo(-1, -1, b.constants.GENESIS_CHALLENGE) for...
Review this code and list any quality issues.
[ { "issue": "the reason this check is here is to make sure the test actually triggers a reorg. As far as I can tell, with this change, we wouldn't ensure that happens.\n\nWould it not be possible to make the check against `19` above instead depend on which chain we're using, but still with a hard coded height.",...
1
python
"catalog": [ "catalog*", "catalog*/**", "../**/user1/catalog2*", "../**/catalog2*", ] } catalog = OmegaConfigLoader( conf_source=str(tmp_path), base_env=_BASE_ENV, env="dev", conf...
Review this code and list any quality issues.
[ { "issue": "See https://github.com/python/cpython/issues/100690\r\n\r\nThis assert was trivially passing, the test was not doing anything (and it's broken at least in 3.11 and 3.12)", "severity": "critical", "line": 26 } ]
1
python
ti.loop_config(serialize=static_rigid_sim_config.para_level < gs.PARA_LEVEL.ALL) for i_b in range(_B): # temp variables res = ti.Vector.zero(gs.ti_float, 5) old_force = ti.Vector.zero(gs.ti_float, 5) bc = ti.Vector.zero(gs.ti_float, 5) Ac = ti.Vector.zero(gs.ti_float, 9) ...
Review this code and list any quality issues.
[ { "issue": "just use `constraint_state.efc_force[i_c, i_b] ** 2`, it will be fine.\r\n\r\nYou may use `* constraint_state.diag[i_c, i_b]` in place of `/ constraint_state.efc_D[i_c, i_b]` to avoid division, which is much slower than multiplication.", "severity": "major", "line": 26 } ]
1
python
results = processor.post_process_object_detection( outputs=outputs, target_sizes=target_size)[0] detections = sv.Detections.from_transformers(results) ``` """ # noqa: E501 // docs if "boxes" in transformers_results: class_ids = ( tran...
Review this code and list any quality issues.
[ { "issue": "It looks like you forgot to add a data field in this line.", "severity": "minor", "line": 26 } ]
1
python
"type": Optional[list[int]], "default": None, "env_converter": _to_int_list, }, "internal_api_server_socket_path_prefix": { "type": Optional[str], "default": None, "env_converter": str, }, "plugin_locations": { "type": Optional[list[str]], "default...
Review this code and list any quality issues.
[]
0
python
elif mode != 'sc': file_qs['indexMode'] = 'true' return update_url_query(f'https://r.dcs.redcdn.pl/{mode}/o2/{tenant}/{path}.livx{suffix}', file_qs) # no id or title for a transmission. making ones up. title = path \ .replace('/live/', '/').replace('/live', '').r...
Review this code and list any quality issues.
[ { "issue": "`getcode()` is deprecated\r\n```suggestion\r\n if nvr_urlh and nvr_urlh.status == 200:\r\n```\r\nAlso, any thoughts on my DST suggestion from above?", "severity": "minor", "line": 26 } ]
1
python
'description': description, 'uploader_id': uploader_id, 'uploader_url': f'https://{uploader_id}.tumblr.com/' if uploader_id else None, 'like_count': post_json.get('like_count'), 'repost_count': post_json.get('reblog_count'), 'age_limit': {True: 18, False: 0}.g...
Review this code and list any quality issues.
[ { "issue": "This can be removed if applying the above suggestion about folding `_ambiguous_providers` into `_providers`\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
torchscript_module = torch.jit.script(self.eval(), **kwargs) elif method == 'trace': # if no example inputs are provided, try to see if model has example_input_array set if example_inputs is None: example_inputs = self.example_input_array #...
Review this code and list any quality issues.
[ { "issue": "I do not think that data shall overwrite model protected attributes...", "severity": "minor", "line": 26 } ]
1
python
'info_dict': { 'id': '1131431769', 'title': '\u201dPOTOP\u201d, r. Kristijan Krajn\u010dan , (EN + HRsub)', 'uploader': 'croatian.film', 'uploader_id': 'user94192658', 'uploader_url': 'https://vimeo.com/user94192658', 'duration': 937, }, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n self.raise_geo_restricted(countries=self._GEO_COUNTRIES)\r\n```", "severity": "minor", "line": 26 } ]
1
python
msg = state.messages[idx] state.messages[idx] = (msg[0], message, msg[2]) else: idx = len(state.messages) state.messages.append((f"{len(state.messages)}", message, users[0][0])) state.refresh("messages") return idx # append to an existing message def append_to_message(state: State,...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n [\"Fetching information from Wikipedia ...\"],\r\n```", "severity": "minor", "line": 26 } ]
1
python
# compute dice (BxC) for each channel for each batch return self.dice_helper(y_pred=y_pred, y=y) # type: ignore def aggregate( self, reduction: MetricReduction | str | None = None ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: """ Execute reduction and aggregation logic...
Review this code and list any quality issues.
[ { "issue": "it seems setting `include_background` to `True` or `False` will make the output key `label_0` correspond to the first or second channel? I think this could be explained in the docstring or changed to have a consistent `label_0`.", "severity": "minor", "line": 26 } ]
1
python
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ] # K constants for the left path. KL = [0, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] # K constants for the right path. KR = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0] def fi(x, y, z, i): """The f1, f2, f3, f4, and f5 functions from the speci...
Review this code and list any quality issues.
[]
0
python
row: Optional[:class:`int`] The relative row this select menu belongs to. A Discord component can only have 5 rows. By default, items are arranged automatically into those 5 rows. If you'd like to control the relative positioning of the row then passing an index is advised. For example, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n .. versionadded:: 2.4\r\n```", "severity": "minor", "line": 26 } ]
1
python
) def test_sg_coeffs_large(xp): # Test that for large values of window_length and polyorder the array of # coefficients returned is symmetric. The aim is to ensure that # no potential numeric overflow occurs. coeffs0 = savgol_coeffs(31, 9, xp=xp) xp_assert_close( coeffs0, xp.flip(coeffs0), a...
Review this code and list any quality issues.
[]
0
python
@abstractmethod def setup_template( self, option: str, attribute: str, validator: Callable[[Any], Any] | None = None, on_update: Callable[[Any], None] | None = None, on_cancel: Callable[[], None] | None = None, ) -> None: """Set up a template that manages ...
Review this code and list any quality issues.
[ { "issue": "Why is the parameter named `on_cancel`, I think that rather reflects how it's used in the binary sensor, not when it's called.\r\nAlso, it seems only `TriggerEntity` calls it, it's ignored by `TemplateEntity`.\r\nFinally, it seems it's not called when \"the tempalte entity renders unknown or unavail...
1
python
from ..utils.traversal import traverse_obj class NuumBaseIE(InfoExtractor): def _call_api(self, path, video_id, description, query={}): response = self._download_json( f'https://nuum.ru/api/v2/{path}', video_id, query=query, note=f'Downloading {description} metadata', ...
Review this code and list any quality issues.
[ { "issue": "if the idea is to make this non-fatal we should do this, yeah?\r\n```suggestion\r\n stream = traverse_obj(container, ('media_container_streams', 0, {dict})) or {}\r\n media = traverse_obj(stream, ('stream_media', 0, {dict})) or {}\r\n```", "severity": "minor", "line": 26 } ]
1
python
from ..utils import ( HEADRequest, UserNotLive, float_or_none, merge_dicts, str_or_none, traverse_obj, unified_timestamp, url_or_none, ) class KickBaseIE(InfoExtractor): _API_HEADERS = {} def _call_api(self, path, display_id, note='Downloading API JSON', headers={}, **kwargs):...
Review this code and list any quality issues.
[ { "issue": "put this in `_real_initialize`", "severity": "minor", "line": 26 } ]
1
python
class FieldEncryption: """Handle decoding of sensitive fields during transmission""" @classmethod def decrypt_field(cls, encoded_text: str) -> str | None: """ Decode Base64 encoded field from frontend. Args: encoded_text: Base64 encoded text from frontend Retur...
Review this code and list any quality issues.
[ { "issue": "We do not need this fallback; if the decoding fails, it should throw an error directly.", "severity": "critical", "line": 26 } ]
1
python
assert result["type"] is FlowResultType.FORM with patch( "pyvesync.vesync.VeSync.login", side_effect=VeSyncLoginError("Mock login failed"), ): result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass...
Review this code and list any quality issues.
[ { "issue": "Also assert the unique id\r\n```py\r\nassert result[\"result\"].unique_id == \"...\"\r\n```", "severity": "minor", "line": 26 } ]
1
python
def joystick_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int, personality) -> Alert: gb = sm['carControl'].actuators.accel / 4. steer = sm['carControl'].actuators.torque vals = f"Gas: {round(gb * 100.)}%, Steer: {round(steer * 100.)}%" return NormalPerman...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n text = \"Switch to Traffic-Aware Cruise Control to engage\"\r\n```", "severity": "minor", "line": 26 } ]
1
python
def normalize_string_prefix(s: str, remove_u_prefix: bool = False) -> str: """Make all string prefixes lowercase. If remove_u_prefix is given, also removes any u prefix from the string. """ match = re.match(r"^([" + STRING_PREFIX_CHARS + r"]*)(.*)$", s, re.DOTALL) assert match is not None, f"failed...
Review this code and list any quality issues.
[ { "issue": "Just double checking - There is never a chance of > 2 here right?\r\n\r\n- Also, lets set a const for 2 to explain it's value\r\n\r\nFeel free to pick a better name etc.\r\n```suggestion\r\n TWO_CHAR_PREFIX_LEN = 2\r\n if len(new_prefix) == TWO_CHAR_PREFIX_LEN and \"r\" != new_prefix[0].lower(...
1
python
util.run(cmd_unicode) cmd_check_test_name = cmd_prefix + [ os.path.join('tools', 'check_test_name.py') ] util.run(cmd_check_test_name) @click.command() @click.option( '--xp-markers', default=False, is_flag=True, help='For each function using `xp_capabilities`, ensure non-numpy backends ar...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n \"\"\"🔧 Run checks which require building or importing SciPy.\n```", "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 _info(self): return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files...
Review this code and list any quality issues.
[ { "issue": "Same here, we can't use read_schema_from_file. But using `open()` and pyarrow:\r\n```suggestion\r\n with open(file, \"rb\") as f:\r\n self.info.features = datasets.Features.from_arrow_schema(pa.ipc.open_stream(f).schema)\r\n```", "severity": "minor", ...
1
python
label : str A string to use as the header for the expander. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font heig...
Review this code and list any quality issues.
[ { "issue": "The docstring is internally contradictory: it says `key` is required when `on_change` is a callback, but immediately says a key will be generated if omitted. Reword to clarify that auto-generated keys apply only when `on_change` is not a callback (and a callback requires an explicit `key`).\n```sugg...
1
python
title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, ...
Review this code and list any quality issues.
[]
0
python
'ie_key': BiliBiliIE.ie_key(), 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '), 'episode': episode.get('index_title'), 'episode_number': int_or_none(episode.get('index')), } for episode in season_info['episodes']] entries = sorted(entries, key=l...
Review this code and list any quality issues.
[ { "issue": "You can remove `**kwargs` from all `_get_entries` functions", "severity": "minor", "line": 26 } ]
1
python
for f in sorted(files_gen): path = "/".join([base, f]) if base else f full = os.path.join(current, f) if f.endswith("js"): self.scripts.append_script(self._add_assets_resource(path, full)) elif f.endswith("css"): s...
Review this code and list any quality issues.
[ { "issue": "@anders-kiaer this looks great, and fantastic tests - I love `does_not_raise`, hadn't seen that trick before but I can see it coming in handy elsewhere.\r\n\r\nThe name is a little long, would it be ambiguous if we just call it `csp_hashes` or `script_hashes`?\r\n\r\nCan you add a bit of usage examp...
1
python
_ARGUMENTS = ["--template"] @classmethod def create_parser(cls): create_parser = _TaipyParser._add_subparser( cls._COMMAND_NAME, help="Create a new Taipy application using pre-defined templates.", ) create_parser.add_argument( "--template", ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n sys.exit(1)\r\n```", "severity": "minor", "line": 26 } ]
1
python
angle The rotation angle. axis The rotation axis as a numpy vector. about_point The rotation center. about_edge If ``about_point``is ``None``, this argument specifies the direction of the bounding box point to be taken as the rotation center. Examples ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n )\r\n```", "severity": "minor", "line": 26 } ]
1
python
'vcodec': media.get('codec_type'), 'format_id': str_or_none(media.get('quality_type')), 'filesize': int_or_none(media.get('size')), 'ext': 'mp4', **media_specific_format } for media in media_json] return _single_video_format def _media_selector(self,...
Review this code and list any quality issues.
[ { "issue": "```py\r\n def _media_selector(self, json_data):\r\n for path, override in (\r\n (('video_list',), {}),\r\n (('dynamic_video', 'dynamic_video_list'), {'acodec': 'none'}),\r\n (('dynamic_video', 'dynamic_audio_list'), {'vcodec': 'none', 'ext': 'm4a'}),\r\n ...
1
python
("1_foo", False), ("1.foo", False), ("1-foo", False), ("foo bar", False), ("foo.bar", False), ("foo&bar", False), ("", False), ("a 😃bc", True), ("X😃", True), ("%", True), ("😃", True), (...
Review this code and list any quality issues.
[]
0
python
self.entities_analytical[entity_idx].set_qpos((*pos, *quat)) self.entities_analytical[entity_idx].zero_all_dofs_velocity() def update_pos_quat_gjk(self, entity_idx: int, pos, euler) -> None: quat = gs.utils.geom.xyz_to_quat(xyz=np.array(euler, dtype=gs.np_float), degrees=True) self.entities...
Review this code and list any quality issues.
[]
0
python
QA_SPECIAL_TOKENS = { "Question": "<|prompter|>", "Answer": "<|assistant|>", "System": "<|system|>", "StartPrefix": "<|prefix_begin|>", "EndPrefix": "<|prefix_end|>", } class Mode(Enum): sft = "sft" rm = "rm" rl = "rl" def format_system_prefix(prefix, eos_token): return "{}{}{}"....
Review this code and list any quality issues.
[ { "issue": "worth considering extracting this class into a separate file. not necessary, i'll leave it up to you", "severity": "major", "line": 26 } ]
1
python
) _, y_true, y_pred, sample_weight, multioutput = ( _check_reg_targets_with_floating_dtype( y_true, y_pred, sample_weight, multioutput, xp=xp ) ) if _num_samples(y_pred) < 2: msg = "D^2 score is not well-defined with less than two samples." warnings.warn(msg, Und...
Review this code and list any quality issues.
[ { "issue": "Let's sync this branch with `main` and pass `average=True` to this call to ensure symmetric quantile computation. This might fix discrepancies between the weighted and unweighted cases.", "severity": "minor", "line": 26 } ]
1
python
except StopIteration: log_path = None try: qlog_path = next(path for path, filename in files if filename in QLOG_FILENAMES) except StopIteration: qlog_path = None try: camera_path = next(path for path, filename in files if filename in CAMERA_FILENAMES) except St...
Review this code and list any quality issues.
[]
0
python
df2 = flavor_read_html(StringIO(data), match="Unit") assert_framelist_equal(df1, df2) def test_file_like(self, spam_data, flavor_read_html): with open(spam_data, encoding="UTF-8") as f: df1 = flavor_read_html(f, match=".*Water.*") with open(spam_data, encoding="UTF-8") as f: ...
Review this code and list any quality issues.
[ { "issue": "The test above also has a `with pytest.raises(URLError, ..`, do you know why that does not need an update?", "severity": "minor", "line": 26 } ]
1
python
import re from .common import InfoExtractor class NZZIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?nzz\.ch/(?:[^/]+/)*[^/?#]+-ld\.(?P<id>\d+)' _TESTS = [{ 'url': 'http://www.nzz.ch/zuerich/gymizyte/gymizyte-schreiben-schueler-heute-noch-diktate-ld.9153', 'info_dict': { 'id'...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n for script in re.findall(r'(?s)<script[^>]* data-hid=\"jw-video-jw[^>]+>(.+?)</script>', webpage):\r\n```", "severity": "minor", "line": 23 } ]
1
python
language: str | None = Field(default=None, description="Admin language") @field_validator("password") @classmethod def validate_password(cls, value: str) -> str: return valid_password(value) class SetupStatusResponse(BaseModel): step: Literal["not_started", "finished"] = Field(description="Se...
Review this code and list any quality issues.
[]
0
python
video_id = self._match_id(url) self._download_webpage('https://globo-ab.globo.com/v2/selected-alternatives?experiments=player-isolated-experiment-02&skipImpressions=true', video_id, 'Getting cookies') video = self._download_json( 'http://api.globovideos.com/videos/%s/playlist' % video_id, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n self._request_webpage(HeadRequest(security['sources'][0]['url_template']), video_id, 'Getting locksession cookie')\r\n```", "severity": "critical", "line": 26 } ]
1
python
with pytest.raises(ValueError) as excinfo: deprecation_warning("old_feature", error=True) assert "`old_feature` has been deprecated." in str(excinfo.value) def test_deprecated_decorator_function(): with patch("ray._common.deprecation.logger.warning") as mock_warning, patch( "ray._common.deprec...
Review this code and list any quality issues.
[]
0
python
'id': info['_id'], 'title': info.get('title') or 'Untitled Broadcast', 'description': info.get('description'), 'duration': int_or_none(info.get('length')), 'thumbnails': thumbnails, 'uploader': info.get('channel', {}).get('display_name'), 'uploader...
Review this code and list any quality issues.
[ { "issue": "1. `chapters` should be `None` (not `[]`) if chapter data extraction fails\r\n2. It is bad practice to clear a nonlocal variable like this, especially in the middle of assigning it", "severity": "critical", "line": 26 } ]
1
python
def _prepare_model_for_training( model: "PreTrainedModel", model_args: "ModelArguments", output_layer_name: str = "lm_head" ) -> None: r""" Includes: (1) cast the layernorm in fp32 (2) make output embedding layer require grads (3) add the upcasting of the lm_head in fp32 Inspired...
Review this code and list any quality issues.
[ { "issue": "must we use this implementation for all the methods?", "severity": "minor", "line": 26 } ]
1
python
placeholder="The top 5 most interesting news stories in the data.", default=None, advanced=False, ) source_data: str | None = SchemaField( description="The data to generate the list from.", placeholder="News Today: Humans land on Mars: Today humans landed ...
Review this code and list any quality issues.
[ { "issue": "1. `list[str]`\n2. Please also add an itemized output (which outputs the generated entries individually)", "severity": "minor", "line": 26 } ]
1
python
'id': '5534601', }, 'playlist_mincount': 323, }] def _real_extract(self, url): self.scheme = scheme = 'https' if url.startswith('https') else 'http' mobj = self._match_valid_url(url) uid, playlist_id = mobj.group('uid'), mobj.group('id') webpage = self._downloa...
Review this code and list any quality issues.
[ { "issue": "The point of paged list is that it is lazy! Don't unpack it...", "severity": "minor", "line": 26 } ]
1
python
TVCIE, TVCArticleIE, ) from .tver import TVerIE from .tvigle import TvigleIE from .tviplayer import TVIPlayerIE from .tvland import TVLandIE from .tvn24 import TVN24IE from .tvnoe import TVNoeIE from .tvopengr import ( TVOpenGrEmbedIE, TVOpenGrWatchIE, ) from .tvp import ( TVPIE, TVPEmbedIE, TVP...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nfrom .tvw import (\r\n TvwIE,\r\n TvwTvChannelsIE,\r\n)\r\n```", "severity": "minor", "line": 26 } ]
1
python
https?:// (?:(?:www|static3)\.)?mediasetplay\.mediaset\.it/ (?: (?:fiction|programmi-tv|serie-tv)/(?:.+?/)? (?:[a-z]+)_SE(?P<id>\d{12}) (?:,ST(?P<st>\d{12}))? ...
Review this code and list any quality issues.
[ { "issue": "It's `playlist_mincount` (as I remembered when a test unexpectedly succeeded with `playlist_min_count`).", "severity": "minor", "line": 26 } ]
1
python
videos_ids_and_titles = {} media_webpage = self._download_webpage(self._MEDIA_PAGE_URL, 'media', fatal=False) if media_webpage: clips_json = traverse_obj( self._search_json(self._MEDIA_START_PATTERN, media_webpage, 'clips json', 'media'), ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nNot needed", "severity": "minor", "line": 26 } ]
1
python
import logging import sentry_sdk from sentry_sdk.integrations.anthropic import AnthropicIntegration from sentry_sdk.integrations.logging import LoggingIntegration from backend.util.settings import Settings def sentry_init(): sentry_dsn = Settings().secrets.sentry_dsn sentry_sdk.init( dsn=sentry_dsn,...
Review this code and list any quality issues.
[]
0
python
scene = SceneClass(renderer) scene.render() except Exception: console.print_exception() elif config.renderer == "webgl": try: from manim.grpc.impl import frame_server_impl server = frame_server_impl.get(file) server.start() ...
Review this code and list any quality issues.
[ { "issue": "still, `args[\"notify_outdated_version\"]` isn't actually necessary here if the config is doing it's job properly", "severity": "minor", "line": 26 } ]
1
python
own context that is destroyed once the page is closed or crashes. fingerprint_generator: An optional instance of implementation of `FingerprintGenerator` that is used to generate browser fingerprints together with consistent headers. """ config = service_locator.get_configura...
Review this code and list any quality issues.
[ { "issue": "The debug log checks `default_launch_browser_options['executable_path']` before merging in `browser_launch_options`, so it can (a) miss cases where the caller provides `browser_launch_options={'executable_path': ...}` and (b) log an executable path that later gets overridden by `browser_launch_optio...
1
python
cls.__calendar = date_range('2014', '2015', freq=cls.trading_calendar.day) cls.__assets = assets = Int64Index(arange(1, 20)) cls.__tmp_finder_ctx = tmp_asset_finder( equities=make_simple_equity_info( assets, cls.__calendar[0...
Review this code and list any quality issues.
[]
0
python
def load_view( self, id: str, optimize: Optional[bool] = False, tensors: Optional[List[str]] = None, num_workers: int = 0, scheduler: str = "threaded", progressbar: Optional[bool] = True, ): """Loads the view and returns the :class:`~deeplake.core.data...
Review this code and list any quality issues.
[ { "issue": "@farizrahman4u I tested the code and it works, but why is this function not running infinitely, since it's running recursively with no offramp?", "severity": "minor", "line": 26 } ]
1
python
config=TextSelectorConfig(type=TextSelectorType.URL) ), vol.Optional(CONF_PREFIX, default=""): cv.string, } ) class S3ConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowRes...
Review this code and list any quality issues.
[ { "issue": "The duplicate-check uses `_async_abort_entries_match` with `CONF_PREFIX: normalized_prefix`. Existing config entries created before this change won’t have `prefix` in `entry.data`, so an empty `normalized_prefix` will not match and the flow can allow duplicate entries for the same bucket/endpoint (r...
1
python
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5) model.to(self.device) for epoch in range(1): print('# Epoch {} #'.format(epoch)) self._train(model, optimizer) self._test(model) batch_size = 32 input_shape = (batch_size, 1, 28, ...
Review this code and list any quality issues.
[ { "issue": "just curious, why changing 'output' to 'input'?", "severity": "minor", "line": 26 } ]
1
python
is_pp_last_stage = use_pipeline and booster.plugin.stage_manager.is_last_stage() total_step = len(train_dataloader) model.train() optimizer.zero_grad() train_dataloader_iter = iter(train_dataloader) with tqdm(range(total_step), desc=f'Epoch [{epoch + 1}/{NUM_EPOCHS}]', d...
Review this code and list any quality issues.
[]
0
python
app.command( context_settings=CONTEXT_ALLOW_EXTRA_ARGS, help="Evaluate a model.", )(evaluate) app.command()(env) app.command( # Alias for evaluate name="eval", hidden=True, context_settings=CONTEXT_ALLOW_EXTRA_ARGS, help="Evaluate a model.", )(evaluate) ...
Review this code and list any quality issues.
[]
0
python
if is_transposed: # (batch_size, 1, input_dim) @ (batch_size, input_dim, output_dim) -> (batch_size, 1, output_dim) -> (batch_size, output_dim) out = torch.bmm(input.unsqueeze(1), weight).squeeze(1) else: # (batch_size, output_dim, input_dim) @ (batch_size, input_dim, 1) -> (batch_size, outp...
Review this code and list any quality issues.
[ { "issue": "clarification taken from #43439", "severity": "minor", "line": 26 } ]
1
python
This is a safety net for tests that don't run Trainer's teardown. """ valid_signals = _SignalConnector._valid_signals() if not _IS_WINDOWS: # SIGKILL and SIGSTOP are not allowed to be modified by the user valid_signals -= {signal.SIGKILL, signal.SIGSTOP} handlers = {signum: signal.getsi...
Review this code and list any quality issues.
[ { "issue": "shouldn't this code be after `yield` statement?", "severity": "minor", "line": 26 } ]
1
python
# Configuration for tests # TODO: Change to llamafactory/tiny-random-Llama-3 MODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct" # Basic inference args INFER_ARGS = { "model_name_or_path": MODEL_NAME, "finetuning_type": "lora", "template": "llama3", "infer_dtype": "float16", "infer_backend": "sglang",...
Review this code and list any quality issues.
[ { "issue": "can we instantiate chat_model in functions rather than in global", "severity": "minor", "line": 26 } ]
1
python
f"WebSocket error: {content.get('error_code')}" f" - {content.get('error_message')}" ) if content.get("finished"): logger.debug("Transcription finished") except Exception as e: ...
Review this code and list any quality issues.
[ { "issue": "SpeechStream added a new field `_start_time_offset` to make sure the timestamps are aligned with our recordings, so we need to pass it here in construction and add them in SpeechData.\n\nNice abstraction BTW. Maybe we should add this to the core lib.", "severity": "major", "line": 26 } ]
1
python
html_content = f""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{rule.name}</title> <link rel="icon" href="../img/favicon.ico" type="image/x-icon"> <link rel="styles...
Review this code and list any quality issues.
[]
0
python
from re import findall from .common import InfoExtractor from ..utils import traverse_obj class HytaleIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?hytale\.com/news/20\d\d/(?:0?[1-9]|1[0-2])/(?P<id>[a-z0-9-]+)' _TESTS = [{ 'url': 'https://hytale.com/news/2021/07/summer-2021-development-update'...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?hytale\\.com/news/\\d+/\\d+/(?P<id>[a-z0-9-]+)'\r\n```\r\nThere is no need for it to be so strict", "severity": "minor", "line": 8 } ]
1
python
array([datetime.time(10, 0, tzinfo=datetime.timezone.utc), datetime.time(11, 0, tzinfo=datetime.timezone.utc)], dtype=object) """ return ints_to_pydatetime(self.asi8, self.tz, box="time", reso=self._creso) @property def date(self) -> npt.NDArray[np.object_]: """ Returns ...
Review this code and list any quality issues.
[]
0
python
"""Testing timeout execution for a page.""" books, _ = build_resources path_page = pages.joinpath("loop_unrun.ipynb") path_c = books.joinpath("config", "_config_timeout.yml") path_html = pages.joinpath("_build", "_page", "loop_unrun", "html") result = cli.invoke( commands.build, [ ...
Review this code and list any quality issues.
[ { "issue": "@choldgraf @chrisjsewell while writing a test for this PR (adding custom builder passthrough) I am not sure where to specify the `jupyter-book` command line options. The test seems to fail when adding them as keyword arguments to `commands.build`. Any ideas on how to specify this using `cli.invoke`?...
1
python
"""Shared utilities for chat tools.""" import logging from typing import Any from backend.api.features.library import db as library_db from backend.api.features.library import model as library_model from backend.api.features.store import db as store_db from backend.data import graph as graph_db from backend.data.grap...
Review this code and list any quality issues.
[ { "issue": "nit: helper functions not defined in top-down order", "severity": "major", "line": 1 } ]
1
python
return if request.session_id: session = await self._get_session_by_id(request.session_id) else: session = await self._get_session() proxy_info = await self._get_proxy_info(request, session) result = RequestHandlerRunResult(key_value_store_getter=self.get_key_valu...
Review this code and list any quality issues.
[ { "issue": "The name is somewhat confusing. It sets the original Request object to the readonly property `context.request`. It is kind of breaking our own constraint.", "severity": "minor", "line": 26 } ]
1
python
# Name "npt._ArrayLikeInt_co" is not defined [name-defined] NumpySorter: TypeAlias = npt._ArrayLikeInt_co | None # type: ignore[name-defined] from typing import ( ParamSpec, SupportsIndex, ) from typing import Concatenate # pyright: ignore[reportUnusedImport] from typing import T...
Review this code and list any quality issues.
[ { "issue": "Should test always importing `Self` and `Unpack` from `typing` whether or not we are doing `TYPE_CHECKING` and then other modules that import those symbols from `_typing` will have access to them, as they should work at runtime.\r\n\r\nI don't think it's a good idea to change `Self` and `Unpack` to ...
1
python
def coin_record_dict_backwards_compat(coin_record: dict[str, Any]) -> dict[str, Any]: del coin_record["spent"] return coin_record class FullNodeRpcClient(RpcClient): """ Client to Chia RPC, connects to a local full node. Uses HTTP/JSON, and converts back from JSON into native python objects before...
Review this code and list any quality issues.
[ { "issue": "this looks suspicious. what if you make a request to a node by hostname and you get \"host not found\". Is there a good reason to not pass through the `ResponseFailureError`?\r\nThis applies to the other places here too.", "severity": "critical", "line": 26 } ]
1
python
def get_center(self): """Center coordinates the mobject""" return self.get_critical_point(np.zeros(self.dim)) def get_center_of_mass(self): return np.apply_along_axis(np.mean, 0, self.get_all_points()) def get_boundary_point(self, direction): all_points = self.get_points_defini...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Left center coordinate of the :class:`~.Mobject`.\"\"\"\r\n```", "severity": "minor", "line": 26 } ]
1
python
'uploader_id': ('upData', 'mid', {str_or_none}), 'like_count': ('videoData', 'stat', 'like', {int_or_none}), 'tags': ('tags', ..., 'tag_name'), 'thumbnail': ('videoData', 'pic', {url_or_none}), }), **festival_info, **traverse_obj(video_...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?bilibili\\.com/bangumi/play/(?P<id>ep\\d+)'\r\n```\r\nas far as I can tell, it's just unnecessary complexity, unless you have an example (w/log) where this is needed", "severity": "major", "line": 26 } ]
1
python
from .common import InfoExtractor class BibelTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?bibeltv\.de/mediathek/videos/(?:crn/)?(?P<id>\d+)' _TESTS = [{ 'url': 'https://www.bibeltv.de/mediathek/videos/329703-sprachkurs-in-malaiisch', 'md5': '252f908192d611de038b8504b08bf97f', ...
Review this code and list any quality issues.
[ { "issue": "Since we dont use `media` this should be traversed instead\r\n```suggestion\r\n for media_url in traverse_obj(data, (..., 'src', {url_or_none})):\r\n```", "severity": "minor", "line": 26 } ]
1
python
check_allclose(expected, out) def test_rsi_edge_cases(self): """ Test against example RSI calculation found online. Test cases where close prices are always increasing and where close prices are always decreasing. Scaling price series by a factor should not affect the result...
Review this code and list any quality issues.
[ { "issue": "What do you think of breaking this into 3 separate tests? One for `always_increasing`, one for `always_decreasing`, and one for `same_returns`?\r\n\r\nEach of those cases may independently fail, and it would be useful to isolate which one fails if they do.", "severity": "critical", "line": 2...
1
python
assert len(initialized_flags_after) == 0, ( f"All _initialized flags should be cleared, but found: {initialized_flags_after}" ) @pytest.mark.asyncio async def test_indexes_awaited_properly(self): """Test that index creation is properly awaited. The second part of the fix en...
Review this code and list any quality issues.
[]
0
python
# TODO: Uncomment these once https://github.com/actions/runner/issues/664 is resolved, # right now these cause more confusion than clarity :( # print("::group:: Setup & Install Black") run([sys.executable, "-m", "venv", str(ENV_PATH)], check=True) # print(f"Created virtual environment at `{ENV_PATH!s}`.") req = "blac...
Review this code and list any quality issues.
[ { "issue": "Want to cleanup or maybe comment that this is good for debugging or future use?", "severity": "critical", "line": 26 } ]
1
python
def get_capabilities(): rules_dir: str = "" try: selected_dir = askDirectory("Choose capa rules directory", "Ok") # type: ignore [name-defined] # noqa: F821 if selected_dir: rules_dir = selected_dir.getPath() except RuntimeError: # RuntimeError thrown when user selects "...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n popup(\"capa explorer encountered warnings during analysis. Please check the console output for more information.\") # type: ignore [name-defined] # noqa: F821\r\n```", "severity": "minor", "line": 26 } ]
1
python
def load_dataset_from_config(config: DatasetAnalyzeConfig) -> BaseMapDataset: """Load dataset based on configuration. This function loads datasets directly from the registry for analysis purposes, avoiding the need for tokenizers and other training infrastructure. """ from oumi.core.registry import...
Review this code and list any quality issues.
[ { "issue": "Mostly curious here: any reason to not support subsets?", "severity": "minor", "line": 26 } ]
1