language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
# We will modify the start date of the rule to last week to prevent a large number of entries if fast_forward: try: # All rules in a ruleset will have the same dtstart value # so lets compare the first event to now to see if its > 30 days old # we choo...
Review this code and list any quality issues.
[ { "issue": "try this\r\n```suggestion\r\n new_rrule = re.sub('(?P<dstart>DTSTART[^:]*):[^T]+T', fr'\\g<dstart>:{new_start_fmt !s}T', rrule)\r\n```", "severity": "minor", "line": 26 } ]
1
python
'only_matching': True, }] _WEBPAGE_TESTS = [{ 'url': 'https://www.pacificblue.biz/noyo-harbor-webcam/', 'info_dict': { 'id': '4fvYdSo8AX', 'ext': 'mp4', 'title': 'startswith:Outside ', 'alt_title': 'Outside', 'description': '<null>', ...
Review this code and list any quality issues.
[ { "issue": "it's fatal in the very next line if `data['items'][0]` isn't a dict, and we don't use any other part of `data`, so we might as well do this above:\r\n\r\n```py\r\n item = self._download_json(\r\n 'https://video.nest.com/api/dropcam/cameras.get_by_public_token',\r\n video_...
1
python
from .adobepass import AdobePassIE from ..utils import ( update_url_query, smuggle_url, ) class SyfyIE(AdobePassIE): _VALID_URL = r'https?://(?:www\.)?syfy\.com/(?:[^/]+/)?videos/(?P<id>[^/?#]+)' _TESTS = [{ 'url': 'http://www.syfy.com/theinternetruinedmylife/videos/the-internet-ruined-my-life...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'skip': 'Redirects to main page',\r\n```", "severity": "minor", "line": 26 } ]
1
python
) def test_early_strategy_with_final_result_in_middle(self): """Test that 'early' strategy stops at first final result, regardless of position.""" tool_called = [] def return_model(_: list[ModelMessage], info: AgentInfo) -> ModelResponse: assert info.output_tools is not None ...
Review this code and list any quality issues.
[]
0
python
tracks = self.update_with_tensors( tensors=detections2boxes(detections=detections), masks=detections.mask ) detections = Detections.empty() if len(tracks) > 0: detections.xyxy = np.array( [track.tlbr for track in tracks], dtype=np.float32 ) ...
Review this code and list any quality issues.
[ { "issue": "Let's use Optional typing here. So: `masks: Optional[np.ndarray] = None`", "severity": "minor", "line": 26 } ]
1
python
It should work as a factory for creating new browser instances. """ AUTOMATION_LIBRARY = 'playwright' def __init__( self, *, browser_type: BrowserType = 'chromium', browser_launch_options: Mapping[str, Any] | None = None, browser_new_context_options: Mapping[str, An...
Review this code and list any quality issues.
[ { "issue": "Little out of scope, but since we're touching it... Couldn't we set this docstring in the `BaseBrowserPlugin.__init__`? Same for the `BaseBrowserController`.", "severity": "minor", "line": 26 } ]
1
python
return AnimationGroup(brace_anim(self.brace), label_anim(self.label)) def shift_brace(self, obj: Mobject, **kwargs: Any) -> Self: if isinstance(obj, list): obj = self.get_group_class()(*obj) self.brace = Brace(obj, self.brace_direction, **kwargs) self.brace.put_at_tip(self.label...
Review this code and list any quality issues.
[ { "issue": "I would argue that the default `label_constructor` should be `Text`.", "severity": "minor", "line": 26 } ]
1
python
async def create_data_points(self, collection_name: str, data_points: List[DataPoint]): data_point_types = get_type_hints(DataPoint) if not await self.has_collection(collection_name): await self.create_collection( collection_name=collection_name, payload_schem...
Review this code and list any quality issues.
[]
0
python
# Testing acl commands client = aioredis.Redis(port=df.port, decode_responses=True) res = await client.execute_command("ACL SETUSER myuser ON >kk +@transaction +set ~*") assert res == "OK" await client.execute_command("AUTH myuser kk") assert "OK" == await client.execute_command("MULTI") await ...
Review this code and list any quality issues.
[ { "issue": "Missing await keyword before asyncio.sleep(0.1). This will cause the code to create a coroutine object without awaiting it, which won't actually sleep and will generate a runtime warning about an unawaited coroutine.", "severity": "minor", "line": 26 } ]
1
python
} test_dict[category]['data'].append(data_sample) return test_dict def process_dev(sample_dict): dev_dict = {} for category in sample_dict.keys(): dev_dict[category] = {'data': [], 'inference_kwargs': default_inference_kwargs} sample_list = sample_dict[category] for sample_i...
Review this code and list any quality issues.
[ { "issue": "Can be merged into one function.", "severity": "minor", "line": 26 } ]
1
python
r"""A rectangle surrounding a :class:`~.Mobject` Examples -------- .. manim:: SurroundingRectExample :save_last_frame: class SurroundingRectExample(Scene): def construct(self): title = Title("A Quote from Newton") quote = Text( ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n *mobjects: Mobject,\n```\nThis way users can get errors in their IDE\nSame with the other case of this happening", "severity": "minor", "line": 26 } ]
1
python
from capa.features.common import Feature, Characteristic from capa.features.address import Address, AbsoluteVirtualAddress from capa.features.extractors import loops from capa.features.extractors.base_extractor import FunctionHandle def interface_extract_function_XXX(fh: FunctionHandle) -> Iterator[Tuple[Feature, Add...
Review this code and list any quality issues.
[ { "issue": "please add error handling here", "severity": "minor", "line": 26 } ]
1
python
), metrics_set=metrics_set, blotter=blotter, benchmark_returns=benchmark_returns, benchmark_sid=benchmark_sid, **{ 'initialize': initialize, 'handle_data': handle_data, 'before_trading_start': before_trading_star...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"Neither '--benchmark-symbol' nor '--benchmark-sid' was\"\r\n \" provided, and ``zipline.api.set_benchmark`` was not called\"\r\n \" in ``initialize``. Did you mean to pass '--no-benchmark'?\"\r\n```", "severity": "minor", "line...
1
python
device_model = "HmIP-MP3P" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=["Kombisignalmelder"] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) # Fixture has playingFileActive=false assert...
Review this code and list any quality issues.
[]
0
python
'thumbnail': r're:https?://\w+\.nyt.com/images/.*\.jpg', 'duration': 1322, } }, { 'url': 'https://www.nytimes.com/2023/11/29/business/dealbook/kamala-harris-biden-voters.html', 'md5': '3eb5ddb1d6f86254fe4f233826778737', 'info_dict': { 'id': '100000009202270', ...
Review this code and list any quality issues.
[ { "issue": "These URLs still work. I know the extractor was broken, and I see that you removed/renamed/rewrote the method it was using to perform most of the extraction, but we still shouldn't remove the extractor or tests. Mark it as `_WORKING = False` and have it just return an `id`-only info dict for now", ...
1
python
more_cookies = httpx.Cookies() more_cookies.set("name", "value", domain="example.com") cookies.update(more_cookies) assert dict(cookies) == {"name": "value"} assert cookies.get("name", domain="example.com") == "value" def test_cookies_with_domain(): cookies = httpx.Cookies() cookies.set("name...
Review this code and list any quality issues.
[]
0
python
traverse_obj, ) class MonstercatIE(InfoExtractor): _VALID_URL = r'https://www\.monstercat\.com/release/(?P<id>\d+)' _TESTS = [{ 'url': 'https://www.monstercat.com/release/742779548009', 'playlist_count': 20, 'info_dict': { 'title': 'The Secret Language of Trees', ...
Review this code and list any quality issues.
[ { "issue": "I think we should check for the IDs needed in the URL and skip instead of yielding a bogus URL\r\n\r\noptionally you could add a warning before continue\r\n```suggestion\r\n ids = extract_attributes(try_call(lambda: get_element_html_by_class('btn-play cursor-pointer mr-small', td)) or '')...
1
python
return fpath def get_all_database_files(self) -> list[File]: """ Get all project files from the database. """ return ( File .select() .where( (File.app_id == self.args['app_id']) & peewee.fn.EXISTS(FileSnapshot.sele...
Review this code and list any quality issues.
[ { "issue": "This is the actual filtering step. The path normalization (`self.relpath`) is there so we can match file path properly with the relevant files set.", "severity": "minor", "line": 26 } ]
1
python
""" returns a list of tagged objects filtered by tag names and object types if no filters applied returns all tagged objects """ results: list[dict[str, Any]] = [] # dashboards if (not obj_types) or ("dashboard" in obj_types): dashboards = ( d...
Review this code and list any quality issues.
[]
0
python
return { 'id': version_id, 'title': title, 'formats': formats, 'alt_title': init_data.get('shortTitle'), 'thumbnail': image_url.replace('$recipe', 'raw') if image_url else None, 'description': smp_dat...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n for lead_media in traverse_obj(morph_payload, (\r\n 'body', 'components', ..., 'props', 'leadMedia', {dict})):\r\n programme_id = traverse_obj(lead_media, ('identifiers', ('vpid', 'playablePid'), {str}, any))\r\n```", "severity": "mi...
1
python
shuffle_group_name = "group-" + self.name if deserializing: # Use CallableLazyImport objects to avoid importing dataframe # module on the scheduler concat_func = CallableLazyImport("dask.dataframe.core._concat") shuffle_group_func = CallableLazyImport( ...
Review this code and list any quality issues.
[]
0
python
"up_proj.weight": None, } # used and delattr in load/shard of gate/up weight self.down_proj = mlp_dproj self.process_group = process_group @staticmethod def from_native_module( module: LlamaMLP, process_group: Union[ProcessGroup, List[ProcessGroup]], *args, **kwargs ) -> Pa...
Review this code and list any quality issues.
[ { "issue": "1. With `self.gate_up_dict` already set in `__init__`, the if block is noneffective and redundant. \r\n2. prevent hard-coding", "severity": "minor", "line": 26 } ]
1
python
# vk serves two same remixlhk cookies in Set-Cookie header and expects # first one to be actually set self._apply_first_set_cookie_header(url_handle, 'remixlhk') login_page = self._download_webpage( 'https://vk.com/login', None, note='Logging in', data=urlenc...
Review this code and list any quality issues.
[ { "issue": "revert unnecessary changes.\r\nfollow our code style", "severity": "minor", "line": 26 } ]
1
python
self._statistics, self._session_pool if self._use_session_pool else None, self._http_client, *self._additional_context_managers, ) if cm and getattr(cm, 'active', False) is False ] async with AsyncExitStack() as exit_stack: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n event_manager.emit(\r\n event=Event.PERSIST_STATE,\r\n event_data=EventPersistStateData(is_migrating=False),\r\n )\r\n```", "severity": "minor", "line": 26 } ]
1
python
Creating the scheduled event failed. Returns -------- :class:`ScheduledEvent` The created scheduled event. """ payload = {} metadata = {} payload['name'] = name if start_time is not MISSING: if start_time.tzinfo is None: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if channel.type is VoiceChannel:\r\n entity_type = EntityType.voice\r\n elif channel.type is StageChannel:\r\n entity_type = EntityType.stage_instance\r\n```", "severity": "minor", "line": 26 } ]
1
python
first_peak = b.get_peak() fork_info2 = None # Create one AugmentedBlockchain instance and reuse it across fork chain validations aug_chain: AugmentedBlockchain | None = AugmentedBlockchain(b) for reorg_block in reorg_blocks: if (reorg_block.height % 100) == 0: ...
Review this code and list any quality issues.
[ { "issue": "it makes me a bit nervous to have this be conditional. If something is changed with the chains, this test may not trigger a reorg anymore, but it will still pass. At least that's what it looks like.\n\nI'm thinking that maybe it would be possible to fix this by adjusting `chain_1_weight` instead, to...
1
python
def round_robin_pick_client(clients, idx): return clients[idx % len(clients)] def round_robin_pick_clients(counter): tokenization_client = round_robin_pick_client(app.state.total_clients, counter) prefill_client = round_robin_pick_client(app.state.prefill_clients, counter) decode_client = round_robin_p...
Review this code and list any quality issues.
[ { "issue": "then why we need client_id_key? we can just do the line 310-315 logic without CLIENT_BOUND_KEY for the original logic. is that correct?", "severity": "minor", "line": 26 } ]
1
python
operands = [] for i in range(insn.getNumOperands()): ops.append(insn.getOpObjects(i)) # Operands stored in a 2D array for j in range(len(ops)): for k in range(len(ops[j])): operands.append(ops[j][k]) return all(n == operands[0] for n in operands) def handle_thunk(addr: gh...
Review this code and list any quality issues.
[ { "issue": "Is there an opportunity to bail early before iterating `THUNK_CHAIN_DEPTH_DELTA` times?", "severity": "minor", "line": 26 } ]
1
python
_attr_has_entity_name = True def __init__( self, coordinator: WaterFurnaceCoordinator, description: SensorEntityDescription ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description # This ensures that the sensors are is...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n device_info[\"model\"] = coordinator.device_metadata.description\n if coordinator.device_metadata.awlabctypedesc:\n```", "severity": "minor", "line": 26 } ]
1
python
token_ids = final_res.outputs[0].token_ids log_probs = None if sampling_params.logprobs is not None: log_probs = [logprobs[token_ids[i]].logprob for i, logprobs in enumerate(final_res.outputs[0].logprobs)] routed_experts = None if self.config.enable_rollout_routing_replay: ...
Review this code and list any quality issues.
[ { "issue": "This is equivalent to `num_preempted=num_preempted`?", "severity": "minor", "line": 26 } ]
1
python
"-ibs", "--inference-batch-size", type=int, default=64, help="Number of prompts to generate per step." ) parser.add_argument( "-imbs", "--inference-microbatch-size", type=int, default=8, help="Number of prompts to send from the producer to the consumer.", ) parser...
Review this code and list any quality issues.
[ { "issue": "When PP is activated, `train-microbatch-size` will not be equal to Number of samples per device. Please rewrite help here to match our implementation.", "severity": "major", "line": 26 } ]
1
python
objects to tokenize ensure_deterministic: bool, optional If True, raise TokenizationError if the objects cannot be deterministically tokenized, e.g. two identical objects will return different tokens. Defaults to the `tokenize.ensure-deterministic` configuration parameter. """ with _...
Review this code and list any quality issues.
[ { "issue": "This seems overly complex. Why isn't a single `ContextVar` sufficient?", "severity": "minor", "line": 26 } ]
1
python
playlist = self._extract_m3u8_formats_and_subtitles( video_info['playlist'][0]['sources'][0]['src'], video_id) base_url = urlparse(video_info['playlist'][0]['sources'][0]['src'])._replace( params='', query='', fragment='') playlist[0][0]['fragment_base_url'] = \ bas...
Review this code and list any quality issues.
[ { "issue": "https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#mandatory-and-optional-metafields", "severity": "minor", "line": 26 } ]
1
python
from __future__ import annotations import pytest from colour import Color from manim.mobject.svg.text_mobject import MarkupText, Text from manim.mobject.types.vectorized_mobject import VMobject from manim.utils.color import RED def test_font_size(): """Test that Text and MarkupText return the correct font_s...
Review this code and list any quality issues.
[ { "issue": "How about you do a frame comparison?", "severity": "minor", "line": 22 } ]
1
python
""" init_fn: InitFnType = InitFnType.normal """ The weight initialization strategy. """ init_std: float = 0.02 """ The standard deviation to use when initializing weights with a "fixed distribution" ``init_fn``, such as "normal". """ init_cutoff_factor: Optional[float] = None ...
Review this code and list any quality issues.
[ { "issue": "When this gets set to true during training this could cause issues later when loading the model for inference since. Instead maybe we have a method on the model like `Olmo.enable_activation_checkpointing()`? The trainer calls that when `TrainConfig.activation_checkpointing` is true`, so we don't nee...
1
python
# Create a PineconeDb instance db = PineconeDb() app_config = AppConfig(collect_metrics=False) App(config=app_config, db=db, embedder=embedder) # Assert that the embedder was set assert db.embedder == embedder pinecone_mock.init.assert_called_once() @patch("embedcha...
Review this code and list any quality issues.
[]
0
python
value = value[1:-1] if value: parts = value.split(',') if len(parts) == 1: parts = value.split(':') if len(parts) == 1: # slice(stop) parts = [parts[0], str(int(parts[0]) + 1)] # else: slice(start, ...
Review this code and list any quality issues.
[ { "issue": "Is it supported to have only some parts as UUID? Should we do this check for every part?", "severity": "minor", "line": 26 } ]
1
python
'responsive_web_graphql_skip_user_profile_image_extensions_enabled': False, 'responsive_web_graphql_timeline_navigation_enabled': True, 'responsive_web_enhance_cards_enabled': False }, 'fieldToggles': { 'withArticleRichContentState': False ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if not self._configuration_arg('legacy_api'):\r\n return self._graphql_to_legacy(\r\n self._call_graphql_api('2ICDjqPd81tulZcYrtpTuQ/TweetResultByRestId', twid), twid)\r\n return traverse_obj(self._call_api(f'statuses/show/{tw...
1
python
payload=payload, **kwargs, ) if label is not None: request.user_data['label'] = label if session_id is not None: request.user_data['session_id'] = session_id return request def get_query_param_from_url(self, param: str, *, default: str | None =...
Review this code and list any quality issues.
[ { "issue": "I see you are following the same pattern as already exists, but I think the cast is not necessary if we redefine model like this:\r\n\r\n```\r\n user_data: Annotated[\r\n UserData,\r\n Field(alias='userData', default_factory=UserData),\r\n PlainValidator(user_data_adapter.val...
1
python
_TESTS = [{ 'url': 'http://www.amadeus.tv/library/65091a87ff85af59d9fc54c3', 'info_dict': { 'id': '5576678021301411311', 'ext': 'mp4', 'title': '02Jieon Park.mp4', 'thumbnail': 'http://1253584441.vod2.myqcloud.com/a0046a27vodtransbj1253584441/7db4af5355766...
Review this code and list any quality issues.
[ { "issue": "Formatting\r\n```suggestion\r\n video_data = self._download_json(\r\n f'http://playvideo.qcloud.com/getplayinfo/v2/1253584441/{video_id}',\r\n video_id, headers={'Referer': 'http://www.amadeus.tv/'})\r\n```", "severity": "minor", "line": 26 } ]
1
python
import asyncio import logging from concurrent.futures import Executor, ProcessPoolExecutor from datetime import datetime from functools import partial from multiprocessing import freeze_support from typing import Set, Tuple try: from aiohttp import web import aiohttp_cors except ImportError as ie: raise Im...
Review this code and list any quality issues.
[ { "issue": "Now we could raise this `from ie`", "severity": "minor", "line": 17 } ]
1
python
if uid: params['uid'] = uid sid = self._search_regex(r'window\.MDSTRMSID\s*=\s*["\']([^"\']+)["\'];', webpage, 'sid', fatal=False, default=None) if sid: params['sid'] = sid pid = self._search_regex(r'window\.MDSTRMPID\s*=\s*["\'](...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n fmts, subs = self._extract_m3u8_formats_and_subtitles(update_url_query(src, params), video_id)\r\n```\r\nImport `update_url_query` from `..utils`", "severity": "major", "line": 26 } ]
1
python
def _extract_formats(self, response, video_id, stream_url): extract_formats = lambda url, video_id: self._extract_m3u8_formats(url, video_id, 'mp4') try: return extract_formats(stream_url, video_id) except ExtractorError: self.report_warning('Failed to parse the m3u8 str...
Review this code and list any quality issues.
[ { "issue": "The key has been the same [since 2018](https://web.archive.org/web/20181204140323/https://player.invintus.com/app.js). Lets hard code it for now and save the additional request. If they start regularly changing the key we can always add this back.", "severity": "minor", "line": 26 } ]
1
python
'channel_id': 'LampaRPG', 'channel_url': 'https://goodgame.ru/channel/LampaRPG', 'description': 'md5:ca5faa69b5d9215afdc65caeca68e1f6', 'thumbnail': r're:^https?://.*\.jpg$', 'live_status': 'is_live', 'view_count': int, }, 'params': {'skip_down...
Review this code and list any quality issues.
[ { "issue": "Doesn't it make more sense to use `response['id']`?", "severity": "minor", "line": 26 } ]
1
python
if not ( parser.has_section(section) and parser.remove_option(section, name) ): # The option was not removed. raise ConfigurationError( "Fatal Internal error [id=1]. Please report as a bug." ) # The section may ...
Review this code and list any quality issues.
[ { "issue": "Why not just use a try...except and raise a custom error if the write fails?", "severity": "critical", "line": 26 } ]
1
python
assert last_executed == "autouse_setup" last_executed = "noautouse_setup" yield assert last_executed == "run_test" last_executed = "noautouse_teardown" def test_autouse_fixture_teardown_order(fixture_1: None, fixture_2: None) -> None: global last_exe...
Review this code and list any quality issues.
[ { "issue": "Perhaps we can submit test_scope_fixture_caching_1 and test_scope_fixture_caching_2 in a separate PR, as they're nice to have anyway and will reduce the size of this PR.", "severity": "minor", "line": 26 } ]
1
python
max_squared_sum=max_squared_sum, sample_weight=sw_train, ) log_reg = LogisticRegression(solver=solver) # The score method of Logistic Regression has a classes_ attribute. log_reg.classes_ = classes scores = list() # Prepare the call the get the score per fold: calc_score scoring ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n # There are 2 routes:\n```", "severity": "minor", "line": 26 } ]
1
python
_, cc_proof = get_vdf_info_and_proof( constants, ClassgroupElement.get_default_element(), cc_vdf.challenge, sub_slot_iters, True, ) # generate sub_epoch_summary, and if the last block was the ...
Review this code and list any quality issues.
[]
0
python
if seg_max.getOffset() < (peoff.getOffset() + 2): continue if getBytes(peoff, 2) == pex: yield off, i def extract_file_embedded_pe() -> Iterator[Tuple[Feature, Address]]: """extract embedded PE features """ for seg in currentProgram.getMemory().getBlocks(): for ea,...
Review this code and list any quality issues.
[ { "issue": "We could possibly skip some indirection here by using `currentProgram.getSymbolTable().getExternalEntryPointIterator()` and `currentProgram.getSymbolTable().getPrimarySymbol(_addr_)`\r\n\r\nhttps://ghidra.re/ghidra_docs/api/ghidra/program/model/symbol/SymbolTable.html#getExternalEntryPointIterator()...
1
python
'title': 'Introducing Understood: Who Broke the Internet?', 'ext': 'mp3', 'description': 'md5:c605117500084e43f08a950adc6a708c', 'duration': 229, 'timestamp': 1745827200000, }, }, { 'url': 'https://www.cbc.ca/listen/live-radio/1-64-the-house/clip/16170...
Review this code and list any quality issues.
[ { "issue": "We can inline this below\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
): output_data = json.convert_pydantic_to_json(output_data) output_size += len(json.dumps(output_data)) log_metadata.debug("Node produced output", **{output_name: output_data}) yield output_name, output_data except Exception as e: error_msg = str(e) y...
Review this code and list any quality issues.
[ { "issue": "As far as I understand this will directly overwrite *all* attributes of `execution_stats` with `node_block.execution_stats`. What's this intended for?\r\n\r\nIf you want to get `execution_stats` out of the function, why not return it?", "severity": "minor", "line": 26 } ]
1
python
i1 -= 1 if i1 - i0 < 3: i0, i1 = 0, len(lev) return lev[i0:i1] def _process_contour_level_args(self, args, z_dtype): """ Determine the contour levels and store in self.levels. """ if self.levels is None: if args: levels_arg =...
Review this code and list any quality issues.
[ { "issue": "AFAICS this is the only usage of `_autolev()`. I find the logic of `using_default` a bit hard to follow (in particular also because whether it takes effect depends on `self.logscale`). I suggest to pull the logic in to have `if self.levels is None` instead of `if using_default` inside `_autolev()`."...
1
python
mapped_messages = await model._map_messages([response], None) # type: ignore[reportPrivateUsage] tool_call_message = mapped_messages[0] assert tool_call_message['role'] == 'assistant' assert tool_call_message.get('content') is None assert tool_call_message.get('tool_calls') == snapshot( [ ...
Review this code and list any quality issues.
[]
0
python
return self.registry.get_worker_ids(instance_id) async def get_instance_id(self, msg: QueryInstMsg) -> QueryInstRetMsg: """ Get the instance id given an ip address. """ ip = msg.ip event_id = msg.event_id instance_node = self.registry.get_instance_by_ip(ip) i...
Review this code and list any quality issues.
[]
0
python
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os # The CUDA compatibility library path must be set before importing # torch, because torch loads CUDA shared libraries at import time and the # dynamic linker only consults LD_LIBRARY_PATH when a librar...
Review this code and list any quality issues.
[ { "issue": "If VLLM_CUDA_COMPATIBILITY_PATH is set to an empty string, it will be treated as falsy and the function will return early (line 18). However, if a user explicitly sets it to an empty string (e.g., to disable a default value), this silent behavior might be confusing. Consider adding explicit handling...
1
python
import configparser from pathlib import Path import click from ... import console from ...constants import CONTEXT_SETTINGS, EPILOG, QUALITIES from ...utils.file_ops import ( add_import_statement, copy_template_files, get_template_names, get_template_path, ) CFG_DEFAULTS = { "frame_rate": 30, ...
Review this code and list any quality issues.
[ { "issue": "We can figure this out ourselves via search if we're curious\r\n```suggestion\r\n```", "severity": "minor", "line": 24 } ]
1
python
def _real_extract(self, url): display_id = self._match_id(url) if display_id.startswith('$/'): display_id = display_id.split('/', 2)[-1].replace('/', ':') else: display_id = display_id.replace(':', '#') display_id = compat_urllib_parse_unquote(display_id) ...
Review this code and list any quality issues.
[ { "issue": "the headers issue is fixed already", "severity": "minor", "line": 26 } ]
1
python
Dict containing the exported data """ response = await self.async_client.get("/v1/exports/", params=self._prepare_params(kwargs)) response.raise_for_status() capture_client_event("async_client.get_memory_export", self.sync_client, {"keys": list(kwargs.keys())}) return response.js...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n async def update_project(self, custom_instructions: Optional[str], custom_categories: Optional[List[str]]) -> Dict[str, Any]:\r\n```", "severity": "minor", "line": 26 } ]
1
python
y_range: Optional[Sequence[float]] = None, min_depth: int = 5, max_quads: int = 1500, use_smoothing: bool = True, **kwargs ): """An implicit function. Parameters ---------- func The implicit function in the form ``f(x, y) = 0``. x_...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n A small ``min_depth`` :math:`d` means that some small details might\r\n```", "severity": "minor", "line": 26 } ]
1
python
format_assistant=StringFormatter(slots=["\n{{content}}"]), format_system=StringFormatter(slots=["<|system|>\n{{content}}"]), format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"), format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]), format_tools...
Review this code and list any quality issues.
[ { "issue": "Question: should we use two templates for the thinking model and non-thinking model separately?", "severity": "minor", "line": 26 } ]
1
python
sym = self.lookup_fully_qualified(fullname) if sym and isinstance(sym.node, TypeInfo): return any(base.fullname == "luigi.parameter.Parameter" for base in sym.node.mro) def _task_class_maker_callback(self, ctx: ClassDefContext) -> None: transformer = TaskTransformer(ctx.cls, ctx.reason,...
Review this code and list any quality issues.
[ { "issue": "Let's remove `print()` statements before merging.", "severity": "minor", "line": 26 } ]
1
python
param.requires_grad = False @staticmethod def _set_cond_input(aux_input: Dict): """Set the speaker conditioning input based on the multi-speaker mode.""" sid, g, lid = None, None, None if "speaker_ids" in aux_input and aux_input["speaker_ids"] is not None: sid = aux_input["s...
Review this code and list any quality issues.
[]
0
python
manufacturer="Hikvision", model=self._data.device_type, ) async def async_camera_image( self, width: int | None = None, height: int | None = None ) -> bytes | None: """Return a still image from the camera.""" try: return await self.hass.async_add_executor...
Review this code and list any quality issues.
[ { "issue": "Given that previously this was just a template string, is this a blocking call?", "severity": "minor", "line": 26 } ]
1
python
async_unsub = run_callback_threadsafe( hass.loop, async_dispatcher_connect, hass, signal, target ).result() def remove_dispatcher() -> None: """Remove signal listener.""" run_callback_threadsafe(hass.loop, async_unsub).result() return remove_dispatcher @callback def _async_remove...
Review this code and list any quality issues.
[ { "issue": "This change converts valid Python 3 syntax to deprecated Python 2 syntax. In Python 3, multiple exceptions must be caught using parentheses: `except (ExceptionA, ExceptionB):`. The Python 2 syntax `except ExceptionA, ExceptionB:` is not valid in Python 3 and will cause a syntax error. This line shou...
1
python
URL_PATH_ARGS_SCHEMAS: Dict[str, str] = {} # Here we use object because the nested schema dictionaries contain mixed # value types (ints, bools, and nested dicts). No narrower type annotation # can represent all possible values without breaking mypy compatibility. HANDLER_ARGS_SCHEMAS: Dict[str, Dict[st...
Review this code and list any quality issues.
[ { "issue": "\"This is a temporary implementation that allows query parameters to override defaults. Schema validation ...\"", "severity": "minor", "line": 26 } ]
1
python
import azure.functions as func from onefuzztypes.enums import NodeState, PoolState from ..onefuzzlib.autoscale import autoscale_pool from ..onefuzzlib.orm import process_state_updates from ..onefuzzlib.workers.nodes import Node from ..onefuzzlib.workers.pools import Pool from ..onefuzzlib.workers.scalesets import Scal...
Review this code and list any quality issues.
[]
0
python
formats, subtitles = [], {} for stream in streams: if stream.get('media_type') == 'hls': fmts, subs = self._extract_m3u8_formats_and_subtitles(stream['url'], content_id, fatal=False) formats.extend(fmts) self._merge_subtitles(subs, target=subtitles) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = TuneInBaseIE._VALID_URL_BASE + r'(?:/radio/[^?#]+-|/embed/player/)(?P<id>s\\d+)'\r\n```", "severity": "minor", "line": 26 } ]
1
python
line_graph = plane.get_line_graph( x_values=[0, 1.5, 2, 2.8, 4, 6.25], y_values=[1, 3, 2.25, 4, 2.5, 1.75], line_color=GOLD_E, vertex_dot_style=dict(stroke_width=3, fill_color=PURPLE), vertex_dot_radius=0.04, stroke_width=4, ) # test that the line and dots can be ...
Review this code and list any quality issues.
[ { "issue": "Could you add a test for the new version too?", "severity": "minor", "line": 26 } ]
1
python
# Generated by Django 4.2.10 on 2024-10-22 15:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0197_remove_sso_app_content'), ] operations = [ migrations.AlterField( model_name='inventorysource', name='...
Review this code and list any quality issues.
[]
0
python
storage_client = gcs.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(key) try: blob.reload() except NotFound: raise FileNotFoundError(f"gs://{bucket_name}/{key}") assert blob.size is not None return blob.size def _gcs_get_bytes_range(bucket_name: str, ke...
Review this code and list any quality issues.
[ { "issue": "I tried to give this a type hint but it looks like the actual client class is created dynamically from botocore. Oh well.", "severity": "minor", "line": 26 } ]
1
python
article = traverse_obj(preload_state, ( 'entities', 'articles', lambda _, v: v['assetVideo'][0] == asset_id, any)) def image_url(image_id): return traverse_obj(preload_state, ( 'entities', 'images', image_id, 'url', ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n f'https://www.bbc.co.uk/programmes/{asset_id}', BBCCoUkIE,\r\n```", "severity": "minor", "line": 26 } ]
1
python
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from torch.nn.parameter import Parameter from vllm.model_executor.custom_op import PluggableLayer from vllm.model_executor.layers.linear import ReplicatedLinear from vllm.platforms import current_pla...
Review this code and list any quality issues.
[ { "issue": "If this is going to run across all batch sizes and CUDA arches, can we validate with some performance sweeps? I don't want this to potentially break some consumer GPUs like sm80 or sm121", "severity": "major", "line": 26 } ]
1
python
) # This should print the help string, including `cl.exe` specifics. self.assertRegex(run.stdout, r"CL.EXE COMPATIBILITY OPTIONS:") def test_clang_cpp(self) -> None: # Note that this is a test of the C-preprocessor mode, not C++ mode. # Create a test file that we'll preprocess. ...
Review this code and list any quality issues.
[ { "issue": "Please call print directly, I don't think we need a helper function for this.", "severity": "major", "line": 26 } ]
1
python
'age_limit': 12, 'alt_title': 'Snow Beast', 'cast': 'count:3', 'categories': 'count:7', 'creators': 'count:2', 'description': 'md5:e604a954a7f827a80e96a3a97d48b269', 'location': 'US', 'release_year': 2011, 'thumbnail': r're:...
Review this code and list any quality issues.
[ { "issue": "Wouldn't it be better to have the traversal return a list?\r\n\r\ne.g. `properties` appears to be a list like `[\"DRM\",\"AVOD\"]`, but if `DRM` is not the first element then the current code will result in a false negative\r\n\r\n```suggestion\r\n if 'DRM' in traverse_obj(query, ('licenses',...
1
python
config_content = response.text # Validate YAML yaml.safe_load(config_content) # Save to destination if local_path.exists(): logger.warning(f"Overwriting existing config at {local_path}") local_path.parent.mkdir(parents=True, exist_ok=True) with open(local_p...
Review this code and list any quality issues.
[ { "issue": "Could you also provide an example of a issue that gets generated? How aligned is it with our template: https://github.com/oumi-ai/oumi/issues/new?template=bug-report.yaml", "severity": "critical", "line": 26 } ]
1
python
expect_markdown(app, "Value 9: 2025-11-19 16:50:00") def test_handles_typing_selection(app: Page): datetime_input_field = get_datetime_input(app, "Datetime input 1 (base)").locator( "input" ) datetime_input_field.type("2026/01/01, 09:30") datetime_input_field.press("Enter") # Click on the...
Review this code and list any quality issues.
[]
0
python
return function = f"{__name__}.{sys._getframe().f_code.co_name}" requester = extended_request.requester_email arn = extended_request.principal.principal_arn stats.count(function, tags={"user": requester, "arn": arn}) log_data: dict = { "function": f"{__name__}.{sys._getframe().f_code.co_na...
Review this code and list any quality issues.
[ { "issue": "Since requests is blocking, can you switch it out for AsyncHttpClient? There's some example usage lying around, IE consoleme/lib/account_indexers/swag.py", "severity": "minor", "line": 26 } ]
1
python
out = flash_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) # out: [bs, seq_len, num_attention_heads, attn_head_size] if attention_mask is not None: seqs = [out[start:end] for start, end in zip(cu_seqlens[:-1], cu_seqlens[1:])] out = pad_sequence(seqs, batch_first=True) # restor...
Review this code and list any quality issues.
[ { "issue": "typo from my side: \r\n```suggestion\r\n - `output_attentions=True` does not work after patching, attention weights will be None\r\n```", "severity": "minor", "line": 26 } ]
1
python
if event_filter[k] is True ] # ======================= Block Helper Functions ======================= # def get_blocks() -> dict[str, Type[Block]]: from backend.blocks import load_all_blocks return load_all_blocks() def is_block_provider_configured(block_cls: type["Block"]) -> bool: """ C...
Review this code and list any quality issues.
[ { "issue": "`create()` is just a wrapper for `__init__`, but with a less well-defined type, causing type checking issues (`block.input_schema` currently resolves to `Unknown` in the code below)\r\n```suggestion\r\n block = block_cls()\r\n```\r\nI have checked that `create()` isn't overridden by any block...
1
python
"""A snapshot of memory usage.""" current_size: ByteSize """Memory usage of the current Python process and its children.""" system_wide_used_size: ByteSize | None """Memory usage of all processes, system-wide.""" max_memory_size: ByteSize """The maximum memory that can be used by `AutoscaledP...
Review this code and list any quality issues.
[ { "issue": "It would be tricky to make this configurable. I guess I could make it a constant though.", "severity": "minor", "line": 26 } ]
1
python
import os from dotenv import load_dotenv from langchain.vectorstores import Chroma from langchain.embeddings import OpenAIEmbeddings from realtime_ai_character.logger import get_logger load_dotenv() logger = get_logger(__name__) embedding = OpenAIEmbeddings(openai_api_key=os.getenv("OPENAI_API_KEY")) if os.getenv('OP...
Review this code and list any quality issues.
[ { "issue": "can you keep the params same? Or is there a reason to change?", "severity": "minor", "line": 12 } ]
1
python
'timestamp': 1701302400, 'upload_date': '20231130', 'creator': 'Sue Li', 'thumbnail': r're:https?://\w+\.nyt.com/images/.*\.jpg', }, }, { 'url': 'https://cooking.nytimes.com/recipes/1019516-overnight-oats', 'md5': '2fe7965a3adc899913b8e25ada360823', ...
Review this code and list any quality issues.
[ { "issue": "it's ok to make this fatal. `_search_nextjs_data` already is, and we have nothing to extract w/o this variable. I'd also use a var name like `next_data`\r\n```suggestion\r\n next_data = self._search_nextjs_data(webpage, page_id)['props']['pageProps']\r\n```", "severity": "major", "lin...
1
python
yield self.url_result(f'https://www.bilibili.com/video/{entry["bvid"]}', BiliBiliIE.ie_key(), entry['bvid']) metadata, paged_list = bilibili_space_extract_playlist(fetch_page, get_metadata, get_entries) return self.playlist_result(paged_list, playlist_id, metadata[...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n def fetch_page(page_idx):\r\n return self._download_json(\r\n 'https://api.bilibili.com/audio/music-service/web/song/upper', playlist_id,\r\n note=f'Downloading page {page_idx}',\r\n query={'uid': playlist_id, 'pn': pag...
1
python
"""extract file features""" for file_handler in FILE_HANDLERS: for feature, addr in file_handler(): yield feature, addr FILE_HANDLERS = ( extract_file_export_names, extract_file_import_names, extract_file_strings, extract_file_section_names, extract_file_embedded_pe, ex...
Review this code and list any quality issues.
[ { "issue": "could be good to compare these against vivisect/IDA extracted features for potential differences", "severity": "major", "line": 26 } ]
1
python
aggregation_inputs = transpose( [result.aggregation_inputs for result in line_results], keys=get_aggregation_inputs_properties(self._flow), ) succeeded_aggregation_inputs = collect_lines(succeeded, aggregation_inputs) return succeeded_inputs, succeeded_aggregation_inputs ...
Review this code and list any quality issues.
[ { "issue": "I guess we don't need to check is_eager_flow? If there is no node runs, node_run_infos would be an empty dict.", "severity": "minor", "line": 26 } ]
1
python
@parameterize("async_op", [True, False]) def check_all2all(shape, dtype, async_op): x = torch.rand(shape, dtype=dtype, device=get_accelerator().get_current_device()) output = torch.empty_like(x) output_fp8 = torch.empty_like(x) origin_hanle = dist.all_to_all_single(output, x, group=_get_default_group(),...
Review this code and list any quality issues.
[]
0
python
new_model = ZeroDDP(new_model, new_gemini_manager) model_ckpt_dir = tempfile.TemporaryDirectory() ckpt_io = GeminiCheckpointIO() model_size = sum(p.numel() * p.element_size() for p in model.parameters()) / 1024**2 ckpt_io.save_model(model, model_ckpt_dir.name, True, True, "epoch", (model_size / 3), u...
Review this code and list any quality issues.
[ { "issue": "Please check whether state dict saved by Gemini is the same as the general state dict.", "severity": "minor", "line": 26 } ]
1
python
import logging from collections.abc import MutableMapping import click from olmo.util import prepare_cli_environment log = logging.getLogger(__name__) def flatten(dictionary, parent_key="", separator="."): items = [] for key, value in dictionary.items(): new_key = parent_key + separator + key if pa...
Review this code and list any quality issues.
[ { "issue": "Just curious, why not use a dictionary and `dict.update(...)` instead of a list with `extend()`?", "severity": "minor", "line": 12 } ]
1
python
if original.is_import or no_commas: for i in range(len(leaves) - 1, -1, -1): if leaves[i].type == STANDALONE_COMMENT: continue if leaves[i].type != token.COMMA: new_comma = Leaf(token.COMMA, ",") ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if component is _BracketSplitComponent.body and should_split_line(\r\n```", "severity": "minor", "line": 26 } ]
1
python
'payment_sid': np.array([5], dtype=np.uint32), 'ratio': np.array([2], dtype=np.float64), 'declared_date': np.array([declared_date], dtype='datetime64[ns]'), 'ex_date': np.array([ex_date], dtype='datetime64[ns]'), 'record_date': np.array([record_date], dtype='datetime64[ns...
Review this code and list any quality issues.
[]
0
python
sts = int_or_none(ytcfg.get('STS')) if not sts: # Attempt to extract from player if player_url is None: error_msg = 'Cannot extract signature timestamp without player_url.' if fatal: raise ExtractorError(error_msg) self...
Review this code and list any quality issues.
[ { "issue": "makes more sense as 2 seperate vars imo. Say, `playback_url` and `watchtime_url`. Most of the code doesn't need to be inside the loop. Unwrapping it only causes a couple lines of repeated code\r\n```py\r\nplayback_url = get_first(...)\r\nif not playback_url:\r\n ...\r\n...\r\nself._download_webpa...
1
python
x = np.atleast_2d(x) counts = rng.integers(10, size=x.shape[-1]) x_rep = [] weights = [] for x_ in x: counts_ = rng.permuted(counts) x_rep.append(np.repeat(x_, counts_)) weights.append(counts_) x_rep, weights = np.stack(x_rep), np.stack(weights...
Review this code and list any quality issues.
[ { "issue": "The purpose of this function is to generate integral weights and use them to produce an `x_rep` array that is `x` with elements repeated `weights` times. The somewhat tricky thing is to ensure that the weights have the same sum along `axis` so we don't have a ragged `x_rep` array. I thought about us...
1
python
] def purge_page_from_cache(page, backend_settings=None, backends=None, *, request=None): urls = _get_page_cached_urls(page, request=request) purge_urls_from_cache(urls, backend_settings, backends) def purge_pages_from_cache( pages, backend_settings=None, backends=None, *, request=None ): batch = Pu...
Review this code and list any quality issues.
[ { "issue": "Question: Because `get_full_url` is used, could using this request result in the wrong site being used to resolve the URLs hostname?", "severity": "critical", "line": 26 } ]
1
python
spany = abs(self._eventpress.ydata - self._eventrelease.ydata) elif self.spancoords == 'pixels': spanx = abs(self._eventpress.x - self._eventrelease.x) spany = abs(self._eventpress.y - self._eventrelease.y) else: _api.check_in_list(['data', 'pixels'], ...
Review this code and list any quality issues.
[ { "issue": "Let's make this an Enum instead. An enum is safer and easier to reason about compared to a bunch of strings.", "severity": "minor", "line": 26 } ]
1
python
# flags: --preview --minimum-version=3.10 match maybe, multiple: case perhaps, 5: pass case perhaps, 6,: pass match more := (than, one), indeed,: case _, (5, 6): pass case [[5], (6)], [7],: pass case _: pass # output match maybe, multiple: case perhap...
Review this code and list any quality issues.
[]
0
python
def _entries(self, query): """Get a specified number of results for a query""" currDate = datetime.datetime.now().date() search_url = "http://www.nicovideo.jp/search/%s" % query spans = self._get_spans_for_range(search_url, query, self._START_DATE, currDate) for (start_date, en...
Review this code and list any quality issues.
[ { "issue": "Maybe we should try make this function a loop rather than use recursion, and from there maybe a generator?", "severity": "minor", "line": 26 } ]
1
python
info.get('title') or '', 'episode metadata', group=('season_no', 'episode_no', 'episode', 'series'), default=(None, None, None, None)) description = traverse_obj(video_data, ('data', 'ongoing_ondemand', 'description', 'fin'), expected_type=str) subtitles = {} for sub in traverse_obj...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n\r\n return {\r\n '_type': 'url_transparent',\r\n 'url': smuggle_url(\r\n f'kaltura:1955031:{video_data[\"data\"][\"ongoing_ondemand\"][\"kaltura\"][\"id\"]}',\r\n {'source_url': url}),\r\n```", "severity": "minor", ...
1
python
console.print_exception() else: for SceneClass in scene_classes_from_file(file): try: scene = SceneClass() scene.render() except Exception: console.print_exception() if nov or args["notify_outdated_version"]: manim = reques...
Review this code and list any quality issues.
[ { "issue": "latest != most recently released\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
self.perspective_uniforms = { "frame_shape": camera.get_shape(), "anti_alias_width": anti_alias_width, "camera_center": tuple(camera.get_center()), "camera_rotation": tuple(np.array(rotation).T.flatten()), "light_source_position": tuple(light_pos), ...
Review this code and list any quality issues.
[ { "issue": "This variable isn't global nor being used in `render_render_group`", "severity": "minor", "line": 26 } ]
1
python
"""Send email notification for task errors using SmtpNotifier.""" try: from airflow.providers.smtp.notifications.smtp import SmtpNotifier except ImportError: log.error( "Failed to send task failure or retry email notification: " "`apache-airflow-providers-smtp` is not ins...
Review this code and list any quality issues.
[ { "issue": "Should we deprecate first? This looks like a breaking change", "severity": "minor", "line": 26 } ]
1