language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
def _dequantize(self, op, quantized_val): """ dequantize quantized value. Because we simulate quantization in training process, all the computations still happen as float point computations, which means we first quantize tensors then dequantize them. For more details, please refer to the...
Review this code and list any quality issues.
[ { "issue": "I am not sure, will this cause some backward issue? And other quantizers also use `copy.deepcopy(wrapper.module.old_weight.data)`, should they also be modified?", "severity": "minor", "line": 26 } ]
1
python
contents = self._call_api( podcast_id, 'contents', f'Downloading page {page + 1}', query={ 'filter': 't:free', 'limit': self._PAGE_SIZE, 'offset': page * self._PAGE_SIZE, }) yield from traverse_obj(c...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://tunein\\.com/podcasts(?:/[^/?#]+){1,2}(?P<series_id>p\\d+)/?\\?(?:[^#]+&)?(?i:topicid)=(?P<id>\\d+)'\r\n```", "severity": "minor", "line": 26 } ]
1
python
" ]\n" " },\n" " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {},\n' ' "outputs": [],\n' ' "source": []\n' " }\n" " ],\n" ' "metadata": {},\n' ' "nbformat": 4,\n' ' "nbformat_mino...
Review this code and list any quality issues.
[]
0
python
from ..utils import ( OnDemandPagedList, traverse_obj, unified_strdate, ) class GronkhIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gronkh\.tv/(?:watch/)?streams?/(?P<id>\d+)' _TESTS = [{ 'url': 'https://gronkh.tv/streams/657', 'info_dict': { 'id': '657', ...
Review this code and list any quality issues.
[ { "issue": "this `only_matching` test case is redundant\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
import threading import time from .common import FileDownloader from . import HlsFD from ..extractor.afreecatv import _cloudfront_auth_request from ..networking.exceptions import network_exceptions class SoopVodFD(FileDownloader): """ Downloads Soop subscription VODs with required cookie refresh requests ...
Review this code and list any quality issues.
[ { "issue": "Could you test what happens if you use `--write-info-json --skip-download` followed by `--load-info-json <filename>.info.json`?\r\n\r\nI ask because if a user does this, then we will lose `_cookie_refresh_params`. The field will be sanitized from the written/loaded info JSON since we're not using `-...
1
python
# coding: utf-8 from .common import InfoExtractor class VimmIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?vimm\.tv/c/(?P<id>[0-9a-z-]+)' _TESTS = [{ 'url': 'https://www.vimm.tv/c/calimeatwagon', 'info_dict': { 'id': 'calimeatwagon', 'ext': 'mp4', 'tit...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n },\r\n 'skip': 'Live',\r\n```", "severity": "minor", "line": 14 } ]
1
python
input_shape_, converter_kwargs_, ) = _pop_args( _args, "config_file", filepath=None, ckpt_file=None, bundle_root=os.getcwd(), net_id=None, meta_file=None, key_in_ckpt="", use_trace=False, input_shape=None, converter_kwar...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n raise FileNotFoundError(f'Checkpoint file \"{ckpt_file_}\" not found, please specify it in argument \"ckpt_file\".')\r\n```", "severity": "minor", "line": 26 } ]
1
python
def linear_to_srgb(lin: np.ndarray) -> np.ndarray: low = lin * SRGB_SLOPE high = (1.0 + SRGB_ALPHA) * np.power(lin, 1.0 / SRGB_EXP, dtype=np.float32) - SRGB_ALPHA return np.where(lin <= LINEAR_THRESHOLD, low, high).astype(np.float32) def correct(bgr8u: np.ndarray, illum_rgb_linear: np.ndarray) -> np.ndarr...
Review this code and list any quality issues.
[ { "issue": "In my opinion, np.clip should be before linearToSrgb call", "severity": "minor", "line": 26 } ]
1
python
class FetchNode(BaseNode): """ A node responsible for fetching the HTML content of a specified URL and updating the graph's state with this content. It uses the AsyncChromiumLoader to fetch the content asynchronously. This node acts as a starting point in many scraping workflows, preparing the stat...
Review this code and list any quality issues.
[ { "issue": "using the beautiful soup by default since it is a lot more comprehensible compared to AsyncChromiumLoader. In future, we can augment this node further to fetch more detailed information when both beautiful soup and AsyncChromiumLoader approach does not work", "severity": "minor", "line": 26 ...
1
python
List of all the partial-movie files. """ force_output_as_scene_name = False def __init__( self, renderer: CairoRenderer | OpenGLRenderer, scene_name: StrPath, **kwargs: Any, ) -> None: self.renderer = renderer self.init_output_directories(str(scene_name...
Review this code and list any quality issues.
[ { "issue": "Similarly to before, `DummySceneFileWriter.init_output_directories()` also types `scene_name` as `StrPath`, so please also change that one to `str`.", "severity": "minor", "line": 26 } ]
1
python
tree_map(require_grad, input_obj) # Also requires_grad_ for micro_batch in stage 0 chunk 0 fwd, # tree_map(torch.Tensor.requires_grad_, micro_batch) # Step2: fwd step output_obj = self.forward_step( model_chunk=model_chunk, model_chunk_id=model_chunk_id, ...
Review this code and list any quality issues.
[ { "issue": "we should clone detached output obj", "severity": "minor", "line": 26 } ]
1
python
Example: ```python import supervision as sv image = ... detections = sv.Detections(...) background_color_annotator = sv.BackgroundColorAnnotator() annotated_frame = background_color_annotator.annotate( scene=image.copy(), ...
Review this code and list any quality issues.
[ { "issue": "`for x1, y1, x2, y2 in detections.xyxy.astype(int)` should work as well and be shorter.", "severity": "minor", "line": 26 } ]
1
python
from colossalai.shardformer.policies.base_policy import Policy from colossalai.zero.low_level import LowLevelZeroOptimizer from .pp_plugin_base import PipelinePluginBase DP_AXIS, PP_AXIS, TP_AXIS = 0, 1, 2 def _convert_floating_point(x, dtype: torch.dtype = torch.float16): if isinstance(x, torch.Tensor) and tor...
Review this code and list any quality issues.
[ { "issue": "`shardformer.optimize` recive attribute `policy` as an object, not a class, if the `custom_policy` is a class, you need to do `custom_policy()` first. So it's better to add assert before using `shardformer.optimize` with `custom_policy`", "severity": "major", "line": 26 } ]
1
python
# # Copyright 2018 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
Review this code and list any quality issues.
[ { "issue": "Is there anyway to mock this for Travis testing?", "severity": "minor", "line": 26 } ]
1
python
'url': 'https://streamff.com/v/55cc94', 'md5': '8745a67bb5e5c570738efe7983826370', 'info_dict': { 'id': '55cc94', 'ext': 'mp4', 'title': '55cc94', 'timestamp': 1634764643, 'upload_date': '20211020' } }] def _real_extract(self, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n json_data = self._download_json(f'https://streamff.com/api/videos/{video_id}', video_id)\r\n```", "severity": "minor", "line": 26 } ]
1
python
"key2": abc "mew_key": 42 "my-key": 3.14 """ def __getattr__(self, key): try: return self[key] except KeyError as exp: raise AttributeError(f'Missing attribute "{key}"') from exp def __setattr__(self, key, val): self[key] = val def __repr__(...
Review this code and list any quality issues.
[ { "issue": "Why do we need a function to get all holders? This wasn't required before", "severity": "minor", "line": 26 } ]
1
python
control_points: typing.Iterable[typing.Iterable[typing.Union[float, int]]], ) -> bool: """Checks if a given point lies on the bezier curves with the given control points. Parameters ---------- point (typing.Iterable[float]) The Cartesian Coordinates of the point to check. control_points (t...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n return len(roots) > 0\r\n```", "severity": "minor", "line": 26 } ]
1
python
on = js_to_json('{ 0: // comment\n1 }') self.assertEqual(json.loads(on), {'0': 1}) on = js_to_json(r'["<p>x<\/p>"]') self.assertEqual(json.loads(on), ['<p>x</p>']) on = js_to_json(r'["\xaa"]') self.assertEqual(json.loads(on), ['\u00aa']) on = js_to_json("['a\\\nb']") ...
Review this code and list any quality issues.
[]
0
python
--uptodate) don't need waste time importing PipSession and friends. """ import logging import os import sys from optparse import Values from typing import TYPE_CHECKING, List, Optional from pip._vendor import certifi from pip._internal.cli.base_command import Command from pip._internal.cli.command_context import Com...
Review this code and list any quality issues.
[ { "issue": "![image](https://github.com/pypa/pip/assets/63936253/107c1fb1-c363-4493-9ad1-79cf20c990b2)\r\n\r\nTo be honest, emitting a warning on every single invocation of pip on Python 3.9 and lower is plain annoying. This can be a debug or verbose log.", "severity": "critical", "line": 26 } ]
1
python
p = X.cdf(x) assert_allclose(X.support(), Y.support()) assert_allclose(X.entropy(), Y.entropy()) assert_allclose(X.median(), Y.median()) assert_allclose(X.logpdf(x), Y.logpdf(x)) assert_allclose(X.pdf(x), Y.pdf(x)) assert_allclose(X.logcdf(x), Y.logcdf(x)) assert...
Review this code and list any quality issues.
[ { "issue": "I didn't check the formulas line by line. I figured the fact that the results agree with the existing implementation (without *using* the existing implementation) is sufficient, but LMK if you want me to look more carefully.", "severity": "minor", "line": 26 } ]
1
python
The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \ such arrays if n_outputs > 1 ...
Review this code and list any quality issues.
[ { "issue": "Please merge the two lines so that “to pass” stays on the same line as the preceding text.", "severity": "minor", "line": 26 } ]
1
python
@mcp.tool() async def get_product_name_link() -> ResourceLink: return ResourceLink( type='resource_link', uri=AnyUrl('resource://product_name.txt'), name='product_name.txt', ) @mcp.resource( 'resource://product_name.txt', mime_type='text/plain', annotations=Annotations(audi...
Review this code and list any quality issues.
[]
0
python
urllib.request.urlopen(f'http://www.google.com') urllib.request.urlopen('file:///foo/bar/baz') urllib.request.urlopen(url) urllib.request.Request(url='http://www.google.com') urllib.request.Request(url=f'http://www.google.com') urllib.request.Request(url='http://' + 'www' + '.google.com') urllib.request.Request(url='h...
Review this code and list any quality issues.
[]
0
python
self.cross_entropy = nn.CrossEntropyLoss() self.distance_type = distance_type self.alpha = alpha self.ks = kernel_size self.svls_layer: Any if kernel_ops == "mean": self.svls_layer = MeanFilter(spatial_dims=dim, size=kernel_size) self.svls_layer.filter = ...
Review this code and list any quality issues.
[ { "issue": "Could you please add more description for the input shape for this function and also for the forward, such as the definition of dimension (we often assume all non-transform components assume input data shape [batch x channel x spatial_dims]) and also need to be one-hot or not. \r\n\r\nHere is an exa...
1
python
'quality': ('name', {preference}), 'height': ('name', {int_or_none}), }, get_all=False) def _real_extract(self, url): video_id = self._match_id(url) username, password = self._get_login_info() if username and password: headers = { 'Aut...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n elif errmsg == 'errors.notFound' and not username:\r\n self.raise_login_required('Video may need login to view')\r\n else:\r\n raise ExtractorError(f'Iwara says: {errmsg}')\r\n```", "severity": "major", "line": 26 } ]
1
python
from hqq.core.quantize import HQQLinear # Since HQQLinear stores some tensors in the 'meta' attribute, we must # explicitly move the parameters to the target device for each HQQLinear layer after `to`. super().to(*args, **kwargs) for module in self.modules(): ...
Review this code and list any quality issues.
[ { "issue": "From what I have seen, only 4 models have this attribute, it might be worthwhile to just overload the `to` method for those models rather than adding `if`s in the code common to all models", "severity": "minor", "line": 26 } ]
1
python
from __future__ import annotations import sys import asyncio import functools import contextvars from typing import Any, Dict, List, TypeVar, Callable, Awaitable from typing_extensions import ParamSpec T_Retval = TypeVar("T_Retval") T_ParamSpec = ParamSpec("T_ParamSpec") if sys.version_info >= (3, 9): to_threa...
Review this code and list any quality issues.
[ { "issue": "nit: I don't think you need the explicit annotation\r\n```suggestion\r\n to_thread = asyncio.to_thread\r\n```", "severity": "minor", "line": 16 } ]
1
python
subtitles.setdefault(sub_data.get('lang') or 'und', []).append({ 'url': update_url_query(self._BLOB_URL % endpoint, {'did': did, 'cid': sub_data['file']['ref']['$link']}), 'ext': traverse_obj(sub_data, ('file', 'mimeType', {mimetype2ext})), }) entries.appe...
Review this code and list any quality issues.
[ { "issue": "After thinking on it, we should drop the language. This is supposed to be a format key specifying the language of the video/audio track. This is also used for `--embed-metadata`. Instead of overwriting the language, possibly incorrectly, I'd rather just not set it at all.\r\n```suggestion\r\n```", ...
1
python
self.imports[api.address] = (module.dll, api.api.name) def _compute_sections(self): assert self.sample_file_static_data is not None if self.sample_file_static_data.pe: for pefile_section in self.sample_file_static_data.pe.sections: self.sections[pefile_section.virtual_ad...
Review this code and list any quality issues.
[ { "issue": "should we perform some sanity checks on the existing data, i.e., that the IDs line up?", "severity": "minor", "line": 26 } ]
1
python
from ..mobject.mobject import * from ..mobject.opengl_mobject import OpenGLMobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..utils.color import * from ..utils.deprecation import deprecated_params from ..utils.iterables import tuplify from ..utils.space_ops import normalize, z_to_vector cl...
Review this code and list any quality issues.
[ { "issue": "This is actually incorrect 😅. Resolution can also be a tuple of `u_res, v_res`. Probably worth mentioning in the description too.", "severity": "critical", "line": 26 } ]
1
python
>>> rnd_custom = RandomColorGenerator(1, sample_colors=custom_palette) >>> rnd_custom.next() in custom_palette True >>> rnd_custom.next() in custom_palette True Without a seed and custom palette (non-deterministic): >>> rnd_nodet = RandomColorGenerator(sample_colors=[RED]) >>> rnd_nodet.nex...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Return the next color from the configured color list.\r\n```", "severity": "minor", "line": 26 } ]
1
python
PartStartEvent, TextPart, TextPartDelta, ThinkingPart, ThinkingPartDelta, ToolCallPart, ToolCallPartDelta, ) from pydantic_ai.models.function import ( AgentInfo, BuiltinToolCallsReturns, DeltaThinkingCalls, DeltaThinkingPart, DeltaToolCall, DeltaToolCalls, FunctionMod...
Review this code and list any quality issues.
[ { "issue": "Why not keep it the way we had it? I like this, for what it's worth, but we haven't used it anywhere else.\n\nDevin pointed out the old code wasn't actually working because `not starlette_import_successful` below needs `()`", "severity": "minor", "line": 26 } ]
1
python
) -> None: """Set up the Tado switch platform.""" tado = entry.runtime_data entities: list[TadoChildLockSwitchEntity] = [] for zone in tado.zones: zone_child_lock_supported = ( len(zone["devices"]) > 0 and "childLockEnabled" in zone["devices"][0] ) if not zone_child...
Review this code and list any quality issues.
[]
0
python
entries = [{ '_type': 'url_transparent', 'url': smuggle_url(episode['webplay_url'], {'no_bangumi_tip': 1}), 'ie_key': BiliBiliIE.ie_key(), 'timestamp': parse_iso8601(episode.get('update_time'), delimiter=' '), 'episode': episode.get('index_title'), ...
Review this code and list any quality issues.
[ { "issue": "Can you put back the Base class and put this there? 😶", "severity": "minor", "line": 26 } ]
1
python
def is_square(n: SupportsIndex, prep: bool = True) -> bool: """Return True if n == a * a for some integer a, else False. If n is suspected of *not* being a square then this is a quick method of confirming that it is not. Examples ======== >>> from sympy.ntheory.primetest import is_square >...
Review this code and list any quality issues.
[ { "issue": "Can you remove the blank line that was added here?", "severity": "minor", "line": 26 } ]
1
python
def _real_extract(self, url): channel_id = self._match_id(url) params = parse_qs(url) media_id = traverse_obj(params, ('wmediaid', 0)) if not self._yes_playlist(channel_id, media_id, playlist_label='channel'): return self.url_result(f'wistia:{media_id}', 'Wistia') tr...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n entries = [\r\n \tself.url_result(f'wistia:{video[\"hashedId\"]}', WistiaIE, title=video.get('name'))\r\n \tfor video in traverse_obj(series, ('sections', ..., 'videos', ...)) or []\r\n \tif video.get('hashedId')\r\n ]\r\n```", "severity": "mi...
1
python
closest_hit = None hit_entity: RigidEntity | None = None ray_hit = self._raycast_against_ground_plane(mouse_ray) if ray_hit.is_hit: closest_hit = ray_hit for entity in self.get_entities(): ray_hit = self.raycast_against_entity_oobb(entity...
Review this code and list any quality issues.
[ { "issue": "Why not just store pre-defined colours in a frozen dict of tuples whose keys would be some `IntEnum` (e.g. `COLOR.RED`) ? That would be more pythonic.", "severity": "minor", "line": 26 } ]
1
python
# ethernet config 'AT$QCPCFG=usbNet,0', 'AT$QCNETDEVCTL=3,1', ] else: # this modem gets upset with too many AT commands if sim_id is None or len(sim_id) == 0: cmds += [ # SIM sleep disable 'AT$QCSIMSLEEP=0', 'AT$QCSIMCFG=SimPowerSave,0', ...
Review this code and list any quality issues.
[ { "issue": "can we just use the stock `lte` connection on the device and get rid of this whole thing? if so, we need to handle deleting this esim connection from existing devices", "severity": "minor", "line": 26 } ]
1
python
num_positions = results.num_positions amounts = results.amounts self.assertTrue(all(num_positions == 0)) self.assertTrue(all(amounts == 0)) def test_zero_trading_days(self): """ Test that when we run a simulation with no trading days (e.g. beginning and ending the sa...
Review this code and list any quality issues.
[ { "issue": "Are we ok to re-use a data portal across algo runs? I thought they were consumed by each run.", "severity": "minor", "line": 26 } ]
1
python
) assert wait_for_event(event_listener, "message_added") requests.post( f"http://localhost:{port}/api/v2/conversations/{conversation_id}/step", json={"session_id": session_id}, ) assert wait_for_event(event_listener, "generation_started") # Wait for config_changed event asser...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n name = chat_config.name.lower()\r\n print(f\"Auto-generated display name: '{chat_config.name}'\")\r\n```", "severity": "minor", "line": 26 } ]
1
python
import argparse import json from evaluator import Evaluator from utils import jload def main(args): # load config config=jload(args.config_file) if config["language"] == "cn": # get metric settings for all categories metrics_per_category = {} for category in config["category"].ke...
Review this code and list any quality issues.
[ { "issue": "You config used to initialize evaluator should consider whether you use `battle` or `evaluate`. You can control this in your config file or determine this based on your `predict_file`. If it has two files, then you should call `battle`, otherwise you should call `evaluate`.", "severity": "minor...
1
python
from collections.abc import Mapping from typing import Any, SupportsIndex, assert_type import numpy as np import numpy.typing as npt def mode_func( ar: npt.NDArray[np.number], width: tuple[int, int], iaxis: SupportsIndex, kwargs: Mapping[str, Any], ) -> None: ... AR_i8: npt.NDArray[np.int64] AR_f8: n...
Review this code and list any quality issues.
[]
0
python
invoke_long_callback( state=state, user_function=update_message_with_image, user_function_args=[ state.get_gui(), get_state_id(state), idx, event.get("text", ""), pages[0]....
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n# Append text to an existing message\r\n```", "severity": "minor", "line": 26 } ]
1
python
def parent_type(node: Optional[LN]) -> Optional[NodeType]: """ Returns: @node.parent.type, if @node is not None and has a parent. OR None, otherwise. """ if node is None or node.parent is None: return None return node.parent.type def child_towards(ancestor: Nod...
Review this code and list any quality issues.
[]
0
python
Compute the energy for each element in the batch. Should only be used in linesearch. """ for i_b, i_e in ti.ndrange(self._B, self.n_elements): if not self.batch_linesearch_active[i_b]: continue J, F = self._compute_ele_J_F(f + 1, i_e, i_b) for mat_id...
Review this code and list any quality issues.
[ { "issue": "Why `ti.Matrix.zero` instead of `ti.Vector.zero` like everywhere else?", "severity": "minor", "line": 26 } ]
1
python
'series': try_get(content, lambda x: x['Media']['Name']), 'tags': tags, 'categories': categories, 'duration': float_or_none(content_package.get('Duration')), 'formats': formats, 'thumbnails': thumbnails, } if content_package.get('HasClosedCapt...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?cp24\\.com/news/(?P<id>[^?#]+)'\r\n```\r\nand use this id for the webpage download message\r\nand maybe also return as `display_id`", "severity": "minor", "line": 26 } ]
1
python
# -*- coding: utf-8 -*- # # Copyright 2017 Open Targets # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
Review this code and list any quality issues.
[ { "issue": "`requests` isn't used for these tests", "severity": "minor", "line": 25 } ]
1
python
""" attention_layer_norm: bool = False """ Apply layer norm to the keys and queries within the attention mechanism. This can help stabilize training. """ residual_dropout: float = 0.1 """ The dropout probability for the MLP and attention output within each block. """ embedding...
Review this code and list any quality issues.
[ { "issue": "How about a clarification like this:\r\n```suggestion\r\n Whether to include bias and weight parameters for the layer norms.\r\n This only affects layer norms that are immediately followed by a linear layer in the forward pass.\r\n Other layer norms, such as those applied to attention keys ...
1
python
@error_logged(swallow=True) def example_function_with_error_swallowed(a: int, b: int, c: int) -> int: raise ValueError("This error should be swallowed") @error_logged(swallow=False) def example_function_with_error_not_swallowed(a: int, b: int, c: int) -> int: raise ValueError("This error should NOT be swallow...
Review this code and list any quality issues.
[]
0
python
self.clearml_task = Task.current_task() else: self.clearml_task = Task.init( project_name=project_name, task_name=task_name, output_uri=output_uri, tags=tags, reuse_last_task_id=reuse_last_task_id, contin...
Review this code and list any quality issues.
[ { "issue": "Should this type hint be `output_uri: str | bool`?\r\n\r\nThanks,\r\nBin", "severity": "minor", "line": 26 } ]
1
python
Args: mode: Name of the mode. Returns: An optionally awaitable object which can be awaited until the screen associated with the mode has been mounted. """ stack = self._screen_stacks.get(mode, []) if stack: await_mount = AwaitMount(stack[...
Review this code and list any quality issues.
[]
0
python
import math import urllib.parse from .common import InfoExtractor from ..utils import ( InAdvancePagedList, determine_ext, format_field, int_or_none, traverse_obj, unified_timestamp, url_or_none, ) class BanByeBaseIE(InfoExtractor): _API_BASE = 'https://api.banbye.com' _CDN_BASE =...
Review this code and list any quality issues.
[ { "issue": "if applying my formats suggestion, we'll need `join_nonempty`:\r\n```suggestion\r\n format_field,\r\n int_or_none,\r\n join_nonempty,\r\n traverse_obj,\r\n```", "severity": "minor", "line": 10 } ]
1
python
def set_gguf_parameters(self): hparams = self.hparams block_count = hparams["num_hidden_layers"] self.gguf_writer.add_vocab_size(hparams["vocab_size"]) self.gguf_writer.add_context_length(hparams["max_position_embeddings"]) self.gguf_writer.add_embedding_length(hparams["hidden_s...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n super().set_gguf_parameters()\r\n\r\n self.gguf_writer.add_vocab_size(self.hparams[\"vocab_size\"])\r\n\r\n if (sliding_window := self.find_hparam([\"window_size\", \"sliding_window\"], optional=True)) is not None:\r\n self.gguf_writer.add_sliding_wi...
1
python
API_RETRY_SLEEP = 10 API_ERROR_OUTPUT = "$ERROR$" TIE_DELTA = 0.1 # Categories that need reference answers NEED_REF_CATS = ["math", "reasoning", "coding"] DEFAULT_MODEL_LIST = { "vicuna_bench": [ "vicuna-13b", "vicuna-7b", "llama-13b", "alpaca-13b", "gpt-3.5-turbo", ...
Review this code and list any quality issues.
[ { "issue": "use glob or other method to automatically detect this list?", "severity": "minor", "line": 26 } ]
1
python
----- Raises ValueError if the given session is the first session in this calendar. """ idx = self.schedule.index.get_loc(session_label) if idx == 0: raise ValueError("There is no previous session as this is the" " beginning of the exchang...
Review this code and list any quality issues.
[]
0
python
Note that Django docs advise _against_ interacting with the database using the ORM models in the ready() path. Specifically, during testing. However, we explicitly use the @bypass_in_test decorator to avoid calling this method during testing. Django also advises against running pattern ...
Review this code and list any quality issues.
[]
0
python
'duration': duration, 'formats': formats, 'id': video_id, 'timestamp': parse_iso8601(upload_date), 'subtitles': subtitles, 'title': title, } class BlackboardCollaborateLaunchIE(InfoExtractor): _VALID_URL = r'https?://[a-z]+\.bbcollab\.com/launch/...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n redirect_url = self._request_webpage(url, video_id).url\r\n if self.suitable(redirect_url):\r\n raise UnsupportedError(redirect_url)\r\n return self.url_result(redirect_url, BlackboardCollaborateIE, video_id)\r\n```", "severity": "minor", "li...
1
python
async def test_partial_replication_on_same_source_master_with_replica_lsn_inc(df_factory): server1 = df_factory.create() server2 = df_factory.create() server3 = df_factory.create() server4 = df_factory.create() df_factory.start_all([server1, server2, server3, server4]) c_s2 = server2.client() ...
Review this code and list any quality issues.
[ { "issue": "TODO for #5580 \r\n\r\nRemove this test all together. It was introduced as part of https://github.com/dragonflydb/dragonfly/pull/5189 but it is no longer needed as we don't do partial sync anymore via the `incremental snapshot`", "severity": "major", "line": 26 } ]
1
python
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import pytest import deepspeed.comm as dist from deepspeed.accelerator import get_accelerator import torch from unit.common import DistributedTest from unit.simple_model import random_dataloader, SimpleModel import deepsp...
Review this code and list any quality issues.
[ { "issue": "Need unit test to verify that \r\n1. tensor.device == cpu after `offload_states()`\r\n2. tensor.device == accelerator after `reload_states()`", "severity": "minor", "line": 3 } ]
1
python
try: config = await syncthing.system.config() version = await syncthing.system.version() except aiosyncthing.exceptions.SyncthingError as exception: raise PlatformNotReady from exception server_id = syncthing.server_id entities = [ FolderSensor( syncthing, ...
Review this code and list any quality issues.
[ { "issue": "Why this change?\nIt's not typing, maybe just remove for now.", "severity": "minor", "line": 26 } ]
1
python
output = str(e.stdout.decode(errors="replace")) errors = str(e.stderr.decode(errors="replace")) raise RuntimeError(f"subprocess call error {e.returncode}: {errors}, {output}.") from e def is_sqrt(num: Sequence[int] | int) -> bool: """ Determine if the input is a square number or a squence of s...
Review this code and list any quality issues.
[ { "issue": "I think there is a potential risk when the input dict has the same key in different dict level. For example:\r\n```\r\ninput_dict = {\"a\":1, \"b\":2, \"c\": {\"a\":3, \"d\":4}}\r\nprint(flatten_dict(input_dict))\r\n```\r\n\r\nThe output will be:\r\n```\r\n{'a': 3, 'b': 2, 'd': 4}\r\n```\r\nI would ...
1
python
from test_framework.p2p import P2PTxInvStore from test_framework.script_util import build_malleated_tx_package from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_not_equal, assert_equal, ) from test_framework.wallet import ( MiniWallet, ) class MempoolW...
Review this code and list any quality issues.
[ { "issue": "30ea904: style nit: here and in p2p_private_broadcast.py\r\n```\r\nparent, child_one, child_two = build_malleated_tx_package(\r\n parent=mini_wallet.create_self_transfer()[\"tx\"],\r\n rebalance_parent_output_amount=int(9.99998 * COIN),\r\n child_amount=int(9.99996 * COIN)\r\n)\r\n```", ...
1
python
from __future__ import absolute_import, division, print_function __metaclass__ = type import io import os import json import datetime import importlib from contextlib import redirect_stdout, suppress from unittest import mock import logging from requests.models import Response, PreparedRequest import pytest from a...
Review this code and list any quality issues.
[ { "issue": "`from awx.main.tests.conftest import load_all_credentials # noqa: F401`", "severity": "critical", "line": 21 } ]
1
python
self._links = self.links self._joints = self.joints self._equalities = self.equalities base_links_idx = {link.idx for link in self.links if link.is_fixed} for joint in tuple(chain.from_iterable(self.joints)): if joint.type == gs.JOINT_TYPE.FREE: base_links_id...
Review this code and list any quality issues.
[ { "issue": "At least, move this on top before the definition of the class, in upper case.", "severity": "major", "line": 26 } ]
1
python
the raw estimates. Returns ------- covariance_corrected : ndarray of shape (n_features, n_features) Corrected robust covariance estimate. References ---------- .. [Croux1999] Influence Function and Efficiency of the Minimum Covariance Determinant...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n consistency_factor = _consistency_factor(\n n_features, n_support / n_samples\n )\n```\nand `n_features = self.raw_covariance_.shape[0]` or maybe `n_samples, n_features = data.shape` (if I understand correctly, this should only be called with `data=X` in `fit...
1
python
if isinstance( e, ( OfflineModeIsEnabled, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError, ), ): raise ConnectionError(f"Couldn'...
Review this code and list any quality issues.
[ { "issue": "I think it would be better to refactor this code and avoid the network call and file read if the variable \"_ignore_default_config\" is True.", "severity": "major", "line": 26 } ]
1
python
if not args.no_sound: import sounddevice as sd print("Running a test of your configuration...\n") if torch.cuda.is_available(): device_id = torch.cuda.current_device() gpu_properties = torch.cuda.get_device_properties(device_id) ## Print some environment information...
Review this code and list any quality issues.
[ { "issue": "- Extract a function so you can reuse instead of duplicating the code\r\n- Use `and`s instead of chaining `if`s\r\n- Break the line above 100 chars", "severity": "major", "line": 26 } ]
1
python
self, crawling_context: TCrawlingContext ) -> AsyncGenerator[TCrawlingContext, None]: """Invoked at the end of the context pipeline to make sure that the `loaded_url` still matches enqueue_strategy. This is done to filter out links that redirect outside of the crawled domain. """ if...
Review this code and list any quality issues.
[ { "issue": "As I said below, please use just `**kwargs: Any` in this case.", "severity": "minor", "line": 26 } ]
1
python
raise ExtractorError(post_data.get('txt'), expected=True) title = description = str_or_none( post_data.get('txt') or self._og_search_description(webpage)) if title: # remove link title = re.sub(r'\s*https?://[^\s]+', '', title) uploader = str_or_none( ...
Review this code and list any quality issues.
[ { "issue": "since these are not used anywhere, move them closer to the return, or even better, remove the variables for them entirely", "severity": "minor", "line": 26 } ]
1
python
@pytest.fixture(scope='session') def celery_session_worker( request, # type: Any celery_session_app, # type: Celery celery_includes, # type: Sequence[str] celery_class_tasks, # type: str celery_worker_pool, # type: Any celery_worker_parameters, # type: Mapping[str, Any] ): # type: (......
Review this code and list any quality issues.
[]
0
python
checkout_version = checkout elif kedro_version_match_starters: checkout_version = version else: checkout_version = "main" if "PySpark" in tools and "Kedro Viz" in tools: # Use the spaceflights-pyspark-viz starter if both PySpark and Kedro Viz are chosen. cookiecutter_args["d...
Review this code and list any quality issues.
[ { "issue": "Shouldn't this just be `cookiecutter_args[\"checkout\"] = checkout_version` as well?", "severity": "minor", "line": 26 } ]
1
python
""" adam_beta1: float = 0.9 """The beta1 parameter for Adam-based optimizers. Exponential decay rate for the first moment estimates. Default is 0.9. """ adam_beta2: float = 0.999 """The beta2 parameter for Adam-based optimizers. Exponential decay rate for the second moment estimates....
Review this code and list any quality issues.
[ { "issue": "OK with the default value -- separate issue, one should be able to use sgd_momentum with more trainer_types.", "severity": "minor", "line": 26 } ]
1
python
def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None): triforce_feed = self._parse_json(self._search_regex( r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage, 'triforce feed', default='{}'), video_id, fatal=False) data_zone = self._search_regex( ...
Review this code and list any quality issues.
[ { "issue": "is this necessary?\r\nI can't think of a genuine case where this change is beneficial 🤔", "severity": "minor", "line": 26 } ]
1
python
'url': 'https://player.glomex.com/integration/1/iframe-player.html?playlistId=cl-bgqaata6aw8x&integrationId=19syy24xjn1oqlpc', 'info_dict': { 'id': 'cl-bgqaata6aw8x', }, 'playlist_mincount': 2, }] @classmethod def build_player_url(cls, video_id, integration, origin_url=N...
Review this code and list any quality issues.
[ { "issue": "I would advise against `re.finditer` as it appears to store a copy of webpage (`mobj.string`).\r\n```suggestion\r\n regex = fr'''(?x)\r\n <iframe[^>]+?src=(?P<q>{quot_re})(?P<url>\r\n (?:https?:)?{cls._BASE_PLAYER_URL_RE}\\?(?:(?!(?P=q)).)+\r\n )(?P=q)'''\...
1
python
_TESTS = [{ 'url': 'https://raisudtirol.rai.it/de/index.php?media=Ttv1656281400', 'info_dict': { 'id': 'Ttv1656281400', 'ext': 'mp4', 'title': 'Tagesschau + Sport am Sonntag - 31-07-2022 20:00', 'date': '20220731', 'thumbnail': r're:https://rai...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'title': 'Tagesschau + Sport am Sonntag - 31-07-2022 20:00',\r\n 'series': 'Tagesschau + Sport am Sonntag',\r\n 'upload_date': '20220731',\r\n 'thumbnail': r're:https://raisudtirol\\.rai\\.it/img/.+?\\.jpg',\r\n 'uploader': 'ra...
1
python
try: vw.saveWorkspace() except IOError: # see #168 for discussion around how to handle non-writable directories logger.info("source directory is not writable, won't save intermediate workspace") else: logger.debug("C...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n with open(sample, \"rb\") as f:\r\n```", "severity": "minor", "line": 26 } ]
1
python
'thumbnail': 'https://img.3speakcontent.co/wjgoxyfy/thumbnails/default.png', 'upload_date': '20211021', 'duration': 2703.867833, 'filesize': 1620054781, }, 'params': {'skip_download': True} }] def _real_extract(self, url): id = self._match_id(url) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if ipfs_m3u8:\r\n ipfs_frmts, ipfs_subs = self._extract_m3u8_formats_and_subtitles(f'https://ipfs.3speak.tv/ipfs/{ipfs_m3u8}',\r\n id, fatal=False, m3u8_id='ipfs')\r\n formats.e...
1
python
# and connect to localhost:1234. Messages should start popping up. The # scan can be finished by pressing Ctrl+C. Then, all of the messages will # show up. # # You can also review the results of a saved scan, and filter by words # or by message range: # # ./devtools_parser.py --use cap.pcap --port 1234 --filter watcher...
Review this code and list any quality issues.
[ { "issue": "It might be nice to use pydoc for this so that your documentation shows up on hover in IDEs.", "severity": "minor", "line": 26 } ]
1
python
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
Review this code and list any quality issues.
[]
0
python
def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ... def dot(self, b, out=..., strict=...): ... def sum(self, axis=..., dtype=..., out=..., keepdims=...): ... def cumsum(self, axis=..., dtype=..., out=...): ... def prod(self, axis=..., dtype=..., out=..., keepdims=...): ... pro...
Review this code and list any quality issues.
[ { "issue": "The docs indicate that `axis` can only be an integer or `None`. And that indeed seems to be the case. So a `SupportsIndex | None` would be more appropriate.", "severity": "minor", "line": 26 } ]
1
python
async def run_task_with_semaphore(self, coroutine): async with self._semaphore: return await coroutine def _create_node_task( self, node: Node, dag_manager: DAGManager, context: FlowExecutionContext, executor: ThreadPoolExecutor, ) -> Task: f ...
Review this code and list any quality issues.
[]
0
python
vod_id = info.get('id') or item_id # id backward compatibility for download archives if vod_id[0] != 'v': vod_id = 'v%s' % vod_id thumbnail = url_or_none(info.get('previewThumbnailURL')) if thumbnail: for p in ('width', 'height'): thumbnail = thumb...
Review this code and list any quality issues.
[ { "issue": "int_or_none has a scale parameter", "severity": "minor", "line": 26 } ]
1
python
from ..notification.event import Event, EventEntityType, EventOperation, _make_event from .job_id import JobId from .status import Status if TYPE_CHECKING: from ..task.task import Task def _run_callbacks(fn): def __run_callbacks(job): fn(job) _TaipyLogger._get_logger().debug(f"{job.id} status...
Review this code and list any quality issues.
[ { "issue": "I believe we want to use * for italic text\r\n\r\n```suggestion\r\n Every time a task is submitted for execution, a new *Job* is created. A job represents a\r\n```", "severity": "minor", "line": 26 } ]
1
python
create_custom_scheduler(self.args, num_training_steps, optimizer) return super().create_scheduler(num_training_steps, optimizer) @override def _get_train_sampler(self, *args, **kwargs) -> Optional["torch.utils.data.Sampler"]: r"""Replace the sequential sampler of KTO Trainer created by trl with...
Review this code and list any quality issues.
[]
0
python
def extract_function_calls_to(fh: FunctionHandle): """extract callers to a function""" func: Function = fh.inner for caller in func.caller_sites: # Everything that is a code reference to the current function is considered a caller, which actually includes # many other references that are NO...
Review this code and list any quality issues.
[]
0
python
merged_settings = merge_model_settings(model_used.settings, self.model_settings) model_settings = merge_model_settings(merged_settings, model_settings) usage_limits = usage_limits or _usage.UsageLimits() async def get_instructions(run_context: RunContext[AgentDepsT]) -> str | None: ...
Review this code and list any quality issues.
[ { "issue": "The existing logic filters out empty strings as well, why do we now only filter `None`s? Note also that if we do want this change, we can just change `parts` instead of having both `parts` and `parts_to_format` :)", "severity": "minor", "line": 26 } ]
1
python
dist_world_size = 0 for node_id in node_list: gids = world_info[node_id] dist_world_size += len(gids) for gid in gids: global_rank_mapping[node_id].append(curr_global_rank) curr_global_rank += 1 logger.info(f"global_rank_mapping={global_rank_mapping}") logger....
Review this code and list any quality issues.
[]
0
python
async def build_index( config: GraphRagConfig, method: IndexingMethod | str = IndexingMethod.Standard, is_update_run: bool = False, memory_profile: bool = False, callbacks: list[WorkflowCallbacks] | None = None, additional_context: dict[str, Any] | None = None, ) -> list[PipelineRunResult]: ...
Review this code and list any quality issues.
[]
0
python
def _get_api_response(self, content_id, postdata, resource_type): response = self._download_json( 'https://www.freetv.com/wordpress/wp-admin/admin-ajax.php', content_id, data=urlencode_postdata(postdata), fatal=True, note=f'Downloading {content_id} {resource_type} JSON') ...
Review this code and list any quality issues.
[ { "issue": "what's the point of this? Did you mean this?\r\n```suggestion\r\n video_url = traverse_obj(api_response, ('data', 'displayMeta', 'streamURLVideo'), expected_type=str)\r\n\r\n formats, subtitles = [], {}\r\n if determine_ext(video_url) != 'm3u8':\r\n self.raise_no_form...
1
python
# issue 4183 async def with_timeout_link_down(client): async with async_timeout.timeout(2): while True: info = await client.info("replication") if info["master_link_status"] == "down": assert info["slave_repl_offset"] > 0 br...
Review this code and list any quality issues.
[ { "issue": "Grammar issue: \"replicas full sync first\" should be \"replicas fully sync first\" or \"replicas perform a full sync first\".\n```suggestion\n # then the assertion below shall fail. In that case, replicas perform a full sync first\n```", "severity": "critical", "line": 26 } ]
1
python
from dataclasses import dataclass, field from functools import partial from typing import TYPE_CHECKING, Generic, Sequence, Type, TypeVar import gstaichi as ti import numpy as np import torch import genesis as gs from genesis.options.sensors.options import SensorOptions from genesis.repr_base import RBC from genesis....
Review this code and list any quality issues.
[ { "issue": "I would advice to add this in TYPE_CHECKING block for consistency.", "severity": "minor", "line": 10 } ]
1
python
import unittest from qlib.data import DatasetProvider from qlib.tests import TestOperatorData from qlib.config import C class TestOperatorDataSetting(TestOperatorData): def test_setting(self): self.assertEqual(len(self.instruments_d), 1) self.assertGreater(len(self.cal), 0) class TestElementOpe...
Review this code and list any quality issues.
[]
0
python
query.update(self._get_checkok_params()) initial_data = self._extract_response( item_id=video_id, ep='next', fatal=False, ytcfg=webpage_ytcfg, query=query, check_get_keys='contents', note='Downloading initial data API JSON', default_client=webpage_client) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n is_premium_subscriber = self._is_premium_subscriber(initial_data)\r\n```", "severity": "minor", "line": 26 } ]
1
python
np.array([ [1.0, 1.0, 1279.0, 719.0] ]), ), ( np.array([ [-1.0, 1.0, 1279.0, 719.0] ]), (1280, 720), np.array([ [0.0, 1.0, 1279.0, 719.0] ]), ), ( np.array(...
Review this code and list any quality issues.
[]
0
python
from __future__ import annotations import contextlib import inspect import re import textwrap from collections.abc import Iterator from pathlib import Path from typing import TYPE_CHECKING, Any, Callable import moderngl import numpy as np import numpy.typing as npt from cloup import Context from moderngl import Attri...
Review this code and list any quality issues.
[ { "issue": "I recently noticed that `typing.Callable` is a deprecated alias of `collections.abc.Callable` and that we should try to use the latter instead:\r\n```suggestion\r\nfrom collections.abc import Callable, Iterator, Sequence\r\nfrom pathlib import Path\r\nfrom typing import TYPE_CHECKING, Any\r\n```", ...
1
python
def test_approx_on_unordered_mapping_with_mismatch( self, pytester: Pytester ) -> None: """https://github.com/pytest-dev/pytest/issues/12444""" pytester.makepyfile( """ import pytest def test_approx_on_unordered_mapping_with_mismatch(): ex...
Review this code and list any quality issues.
[ { "issue": "I wanted to push this change and merge, but did not get permission:\n\n```suggestion\n result = pytester.runpytest()\n result.assert_outcomes(failed=1)\n result.stdout.fnmatch_lines(\n [\n \"*comparison failed.**Mismatched elements: 2 / 4:*\",\n ...
1
python
# coding: utf-8 from __future__ import unicode_literals import base64 import time import uuid from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_str, ) from ..utils import ( ExtractorError, int_or_none, ) class MGTVIE(InfoExtractor): _VALID_URL = r'https?://(?:w(?:...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n info = self._download_json(f'https://pcweb.api.mgtv.com/video/title?videoId={video_id}', video_id, fatal=False) or {}\r\n```", "severity": "minor", "line": 26 } ]
1
python
OHLC_RATIO = 1000 class BcolzMinuteOverlappingData(Exception): pass class BcolzMinuteWriterColumnMismatch(Exception): pass class MinuteBarReader(with_metaclass(ABCMeta)): @abstractproperty def last_available_dt(self): """ Returns ------- dt : pd.Timestamp ...
Review this code and list any quality issues.
[ { "issue": "I agree that name is better/more in line with current standards. I will attempt a patch on top of this one to do the rename.", "severity": "minor", "line": 26 } ]
1
python
# to be cached. if not self._cache.is_cachable(CacheKey(command=args[0], redis_keys=())): self._current_command_cache_key = None self._conn.send_command(*args, **kwargs) return if kwargs.get("keys") is None: raise ValueError("Cannot create...
Review this code and list any quality issues.
[]
0
python
f"Exception during Venstar sensor update: {ex}" ) from ex if not sensor_success: raise update_coordinator.UpdateFailed( "Unable to update Venstar sensor data" ) # older venstars sometimes cannot handle rapid sequential connections await async...
Review this code and list any quality issues.
[ { "issue": "`self.runtimes` either needs to get `list[dict[str, int]] | False` as type, or we store the result temporarily in another variable as this is otherwise a type violation. I would suggest the latter.", "severity": "minor", "line": 26 } ]
1