language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
join_nonempty, str_or_none, url_or_none, ) from ..utils.traversal import traverse_obj class TapTapBaseIE(InfoExtractor): _X_UA = 'V=1&PN=WebApp&LANG=zh_CN&VN_CODE=102&LOC=CN&PLT=PC&DS=Android&UID={uuid}&OS=Windows&OSV=10&DT=PC' _VIDEO_API = 'https://www.taptap.cn/webapiv2/video-resource/v1/multi-get' ...
Review this code and list any quality issues.
[ { "issue": "this should be non-fatal or else 1 bad m3u8 url will break playlist extraction\r\n\r\n```suggestion\r\n formats = self._extract_m3u8_formats(video_url, video_id, fatal=False)\r\n```", "severity": "major", "line": 26 } ]
1
python
def _update_references(self, ws: DiscordWebSocket) -> None: for vc in self.voice_clients: vc.main_ws = ws # type: ignore # Silencing the unknown attribute (ok at runtime). def store_user(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> User: # this way is 3...
Review this code and list any quality issues.
[ { "issue": "Please revert this change. The `Guild | GuildPreview` syntax is invalid here for Python 3.8/3.9.\r\nNote, that making `Emoji.guild` will be type of `Union[Guild, GuildPreview]`, would make it a breaking change.", "severity": "minor", "line": 26 } ]
1
python
# Test the IPv6 address. res = self.nodes[0].getnodeaddresses(0, "ipv6") assert_equal(len(res), 1) assert_equal(res[0]["address"], ipv6_addr) assert_equal(res[0]["network"], "ipv6") assert_equal(res[0]["port"], 8333) assert_equal(res[0]["services"], P2P_SERVICES) ...
Review this code and list any quality issues.
[ { "issue": "You might also want to edit/update/remove(?) this comment. I think mentioning that we avoid collisions by adding known-working addresses to the deterministic addrman would be good.", "severity": "minor", "line": 26 } ]
1
python
result.append(arg) return result def visit_BinOp(self, node): if node.op.__class__ in self.operators: sympy_class = self.operators[node.op.__class__] right = self.visit(node.right) left = self.visit(node.left) rev = False if isinstance(no...
Review this code and list any quality issues.
[ { "issue": "Why not put this code in the `else` part of the existing if-else clause?", "severity": "minor", "line": 26 } ]
1
python
if os.path.isfile(os.path.join(datadir, chain, ".cookie")): logger.debug("Deleting leftover cookie file") os.remove(os.path.join(datadir, chain, ".cookie")) def softfork_active(node, key): """Return whether a softfork is active.""" return node.getdeploymentinfo()['deployments'][key]['active'] ...
Review this code and list any quality issues.
[ { "issue": "\"or similarly small\" doesn't really make sense to me. AFAICT this makes just enough transactions to go past the 5MB mempool.", "severity": "minor", "line": 26 } ]
1
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
status_code=200, ).json assert len(response) >= 1 def test_flow_infer_signature(self, pfs_op: PFSOperations) -> None: # prompty response = pfs_op.test_flow_infer_signature( flow_path=(Path(PROMPTY_ROOT) / "prompty_example.prompty").absolute().as_posix(), ...
Review this code and list any quality issues.
[]
0
python
graph: The graph to be executed. graph_credentials_input: A (graph_input_name, credentials_meta) map. Returns: dict[node_id, dict[field_name, CredentialsMetaRaw]]: Node credentials input map. """ result: dict[str, dict[str, JsonValue]] = {} # Get aggregated credentials fields for the g...
Review this code and list any quality issues.
[]
0
python
title: Text | None = getattr(obj, self._internal_name, None) if title is None: return None # If we have a title, convert from Text to console markup return title.markup _WidgetMetaSub = TypeVar("_WidgetMetaSub", bound="_WidgetMeta") class _WidgetMeta(_MessagePumpMeta): """Met...
Review this code and list any quality issues.
[ { "issue": "Not convinced a warning is appropriate.\r\n\r\nGive that a non-capitalized class would be unstyleable by CSS, should this not be an error?", "severity": "minor", "line": 26 } ]
1
python
return self def replace(self, old_mobject: Mobject, new_mobject: Mobject) -> None: """Replace one mobject in the scene with another, preserving draw order. If ``old_mobject`` is a submobject of some other Mobject (e.g. a :class:`.Group`), the new_mobject will replace it inside the group, ...
Review this code and list any quality issues.
[ { "issue": "There is a very subtle bug which is introduced due to an edge case: what if `new_mobject is old_mobject`? This might happen if someone wants to replace Mobject `a` with Mobject `b` and doesn't notice that `a` and `b` are references to the same thing.\r\n```py\r\nsq = Square()\r\nself.add(sq)\r\nself...
1
python
:class:`Mobject` The Mobject itself, after :attr:`z_index` is set. (Returns `self`.) """ z_coord = self.get_center()[-1] self.set_z_index(z_coord) return self class Group(Mobject): """Groups together multiple Mobjects.""" def __init__(self, *mobjects, **kwargs): ...
Review this code and list any quality issues.
[ { "issue": "A more descriptive name and/or a comment would be helpful for this variable.", "severity": "minor", "line": 26 } ]
1
python
Returns ------- class:`bool` ``True`` if the output should be written in a movie format """ if is_png_format(): return False return ( config["write_to_movie"] or is_mp4_format() or is_gif_format() or is_webm_format() or is_mov_format() ) ...
Review this code and list any quality issues.
[ { "issue": "How about running a simple version test to make sure that FFmpeg is actually working? It can be done in another PR though.", "severity": "minor", "line": 26 } ]
1
python
from ._config_comparator._config_comparator import _ConfigComparator from ._serializer._json_serializer import _JsonSerializer from ._serializer._toml_serializer import _TomlSerializer from .checker._checker import _Checker from .checker.issue_collector import IssueCollector from .common._classproperty import _Classpro...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n - `configure_data_node()^`: Configure a data node adding and returning a `DataNodeConfig^`.\r\n```", "severity": "minor", "line": 26 } ]
1
python
from pytorch_lightning.utilities import DeviceType def test_consistency(): assert DeviceType.TPU not in ('GPU', 'CPU') assert DeviceType.TPU in ('TPU', 'CPU') assert DeviceType.TPU in ('tpu', 'CPU') assert DeviceType.TPU not in {'GPU', 'CPU'} assert DeviceType.TPU in {'TPU', 'CPU'} assert Devi...
Review this code and list any quality issues.
[ { "issue": "@tchaton The issue is that 'TPU' is hashed as uppercase but DeviceType.TPU is hashed as lower case, so I think we can just remove this line:\r\n```suggestion\r\n # hash cannot be case invariant\r\n assert DeviceType.TPU not in {'TPU', 'CPU'}\r\n```", "severity": "major", "line": 9 } ...
1
python
''' headers.update( { 'Authorization': f'Bearer {self.token.access_token}', 'Accept': 'application/json', } ) def _make_request(self, method: str, url: str, headers: dict[str, str], **kwargs: Any) -> requests.Response: ''' Actu...
Review this code and list any quality issues.
[ { "issue": "we could combine into `if not self.token or self.token.is_expired()`", "severity": "minor", "line": 26 } ]
1
python
medias = traverse_obj(status, media_path, expected_type=dict, default=[]) for media in medias: if not media or media.get('type') == 'photo': continue data = extract_from_video_info(media) if data: entries.append({**info, **data, 'display_id': ...
Review this code and list any quality issues.
[ { "issue": "why isnt this just:\r\n```suggestion\r\n if not url_or_none(expanded_url) or expanded_url == url:\r\n raise ExtractorError('No video could be found in this tweet', expected=True)\r\n return self.url_result(expanded_url, transparent=True, display_id=twid, **info)\...
1
python
# Form / Picker / Selection # Pre-select choices while displaying a #picker. # #form #selection #choice # --- from h2o_wave import main, app, Q, ui @app('/demo') async def serve(q: Q): if q.args.show_inputs: q.page['example'].items = [ ui.text(f'selected={q.args.picker}'), ui.butto...
Review this code and list any quality issues.
[ { "issue": "I am assuming this is a leftover from development. Please remove as these changes are not relevant to the feature this PR addresses.", "severity": "minor", "line": 24 } ]
1
python
ordered_tile_paths = ( super() .get_basic_sample( global_sample_index, Index(global_sample_index), fetch_chunks, is_tile=True, ) .path_array ) tiles_index, sample_index = translate_slices( ...
Review this code and list any quality issues.
[]
0
python
if args.restrict_to_functions: raise InvalidArgument("Cannot filter functions with dynamic analysis.") return {"processes": {int(pid, 0) for pid in args.restrict_to_processes}} else: raise ShouldExitError(E_INVALID_INPUT_FORMAT) def apply_extractor_filters(extractor: FeatureExtractor, ...
Review this code and list any quality issues.
[ { "issue": "should check to see that `functions` is present and non-empty. ditto with `processes`.", "severity": "minor", "line": 26 } ]
1
python
'https://spankbang.com/api/videos/stream', video_id, 'Downloading stream JSON', data=urlencode_postdata({ 'id': stream_key, 'data': 0, }), headers={ 'Referer': url, 'X-Requested-With': 'XMLHttpRequest', ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n r'<svg[^>]+\\bclass=\"(?:[^\"]*?user[^\"]*?)\">.*?</svg>([^<]+)', webpage, 'uploader', default=None)\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
Review this code and list any quality issues.
[]
0
python
model_request_parameters: ModelRequestParameters, ) -> responses.Response | AsyncStream[responses.ResponseStreamEvent]: tools = ( self._get_builtin_tools(model_request_parameters) + list(model_settings.get('openai_builtin_tools', [])) + self._get_tools(model_request_param...
Review this code and list any quality issues.
[ { "issue": "This can be `==` right? And be merged with the previous `if` statement?", "severity": "minor", "line": 26 } ]
1
python
# The peak value of the 'P99' column is: 1148, mean value of the 'P50' column is: 45.12682926829268 # The peak value of the 'P99' column is: 32000, mean value of the 'P50' column is: 1291.0731707317073 # The peak value of the 'P99' column is: 32000, mean value of the 'P50' column is: 63.951219512195124 # The peak value...
Review this code and list any quality issues.
[]
0
python
Timestamp("2011-01-02"), Timestamp("2011-01-02", tz="US/Eastern"), pd.Timedelta("2 days"), ], name=0.5, index=["A", "B", "C"], ) tm.assert_series_equal(res, exp) res = df.quantile( [0.5], numeric_only=False, interpo...
Review this code and list any quality issues.
[]
0
python
) setattr(right_setting, arg, left if left != default else right) return new_setting def _get_settings_from_t2xs( self, t2xs: Sequence[tuple[dict[str, str], str]], default_args: dict[str, Iterable[str]], ) -> list[TextSetting]: settings = [] t2xwords ...
Review this code and list any quality issues.
[ { "issue": "In the same way you changed `Sequence` to `list` before, it should be possible to do the same here:\r\n```suggestion\r\n ) -> list[TextSetting]:\r\n```", "severity": "minor", "line": 26 } ]
1
python
raise ValueError(error) def _check_xtts_builtin_speakers(self, current_voice:str, speaker:str)->str|bool: new_current_voice = '' proc_current_voice = '' try: import torch import torchaudio import numpy as np from huggingface_hub import hf_hub_...
Review this code and list any quality issues.
[]
0
python
) from zipline.gens.sim_engine import NANOS_IN_MINUTE from zipline.utils.cli import maybe_show_progress from zipline.utils.memoize import lazyval US_EQUITIES_MINUTES_PER_DAY = 390 DEFAULT_EXPECTEDLEN = US_EQUITIES_MINUTES_PER_DAY * 252 * 15 OHLC_RATIO = 1000 class BcolzMinuteOverlappingData(Exception): pass ...
Review this code and list any quality issues.
[ { "issue": "I was also surprised that they were different.\n\nAfter looking at the data portal code which uses `first_trading_day`; `first_trading_day` is used to also get the `first_trading_minute`, as well. Which is then used to determine whether history windows are over valid ranges.\n\nThis code will need t...
1
python
HEADRequest('https://sbs-vod-prod-01.akamaized.net/'), video_id, note='Checking geo-restriction', fatal=False, expected_status=403) if urlh: error_reasons = urlh.headers.get_all('x-error-reason') or [] if 'geo-blocked' in error_reasons: sel...
Review this code and list any quality issues.
[ { "issue": "Isn't this problematic if there are multiple forced subtitles for the same language?", "severity": "minor", "line": 26 } ]
1
python
got = ref.run(None, {"X": x}) self.assertEqual(x.dtype, got[0].dtype) def test_apply_causal(self): m = np.ones((3, 3), dtype=np.float16) _apply_causal(m, 0) self.assertEqual(m.dtype, np.float16) assert_allclose( np.array( [[1, -np.inf, -np.inf], [...
Review this code and list any quality issues.
[ { "issue": "@copilot Remove the overly verbose comments", "severity": "minor", "line": 26 } ]
1
python
if last_date == pd.NaT: # If there is no data, determine how many days to add so that # desired days are written to the correct slots. days_to_zerofill = tds[tds.slice_indexer(end=date)] else: days_to_zerofill = tds[tds.slice_indexer( start=last_da...
Review this code and list any quality issues.
[]
0
python
(maxx, maxy, maxz), (minx, maxy, maxz)] return proj3d._proj_points(xyzs, self.M) def set_aspect(self, aspect, adjustable=None, anchor=None): """ Set the aspect ratios. Parameters ---------- aspect : {'auto', 'equal', 'equalxy', 'equalxz', 'equalyz'} ...
Review this code and list any quality issues.
[ { "issue": "This doesn't seem to be what the title of the PR / the related issue suggests; is it true?", "severity": "minor", "line": 26 } ]
1
python
elif dynamic_type == "int": return _TemplateHandler._to_int(actual_val) elif dynamic_type == "float": return _TemplateHandler._to_float(actual_val) elif dynamic_type == "datetime": return _TemplateHandler._to...
Review this code and list any quality issues.
[ { "issue": "This `if` command handles the case where a dataclass instance is serialized into a dictionary.\r\n\r\nFor example, UserAttribute(\"email\", \"credential_mail\", default=\"example@taipy.org\") will be serialized to\r\n\r\n```\r\n{ \"USER_ATTRIBUTE\": {\"name\": \"email\", \"credentials_name\": \"cred...
1
python
mock_external_service_dependencies["provider_controller"].from_db.assert_called_once() mock_external_service_dependencies["provider_controller"].load_bundled_tools.assert_called_once() def test_create_api_tool_provider_duplicate_name( self, flask_req_ctx_with_containers, db_session_with_containers,...
Review this code and list any quality issues.
[ { "issue": "The service method `create_api_tool_provider` expects `schema_type` to be a string (as defined in line 107 of the service), but this is now passing an enum value. Pass `ApiProviderSchemaType.OPENAPI.value` instead to maintain the string type expected by the service.\n```suggestion\n schema_ty...
1
python
-------- :: >>> Arrow().get_default_tip_length() 0.35 Returns ------- :class:`float` """ max_ratio = self.max_tip_length_to_length_ratio return min(self.tip_length, max_ratio * self.get_length()) def set_stroke_width_from_length(sel...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"A vector specialized for use in graphs.\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Copyright (c) 2024 Microsoft Corporation. # Licensed under the MIT License """System prompts for global search.""" MAP_SYSTEM_PROMPT = """ ---Role--- You are a helpful assistant responding to questions about data in the tables provided. ---Goal--- Generate a response consisting of a list of key points that resp...
Review this code and list any quality issues.
[ { "issue": "Out of curiosity, these and the reduce system prompt are the ones I need to fine tune right?", "severity": "minor", "line": 14 } ]
1
python
for current_chat in video_info.get('chats'): subtitles.setdefault('live_chat', []).append({'url': url_or_none(current_chat['url'])}) return { 'duration': duration, 'formats': formats, 'id': video_id, 'timestamp': parse_iso8601(upload_date), ...
Review this code and list any quality issues.
[ { "issue": "- use `..utils.jwt_decode_hs256`\r\n- it's ok to make this fatal since it's assumed the url isn't valid if the token doesn't decode (or doesn't decode into the expected json structure)\r\n```suggestion\r\n token = self._match_id(url)\r\n video_id = jwt_decode_hs256(token)['resourceAcce...
1
python
def _real_extract(self, url): station = self._match_id(url) area = traverse_obj(self._configuration_arg('area'), 0) or "tokyo" config = self._download_xml('https://www.nhk.or.jp/radio/config/config_web.xml', None, 'Downloading area information') data = config.find(f'.//data//area[.="{ar...
Review this code and list any quality issues.
[ { "issue": "I prefer this formatting/indent, but I guess either is fine\r\n```suggestion\r\n 'url': 'url',\r\n 'width': ('width', {int_or_none}),\r\n 'height': ('height', {int_or_none}),\r\n })),\r\n```", "severity": "minor", "line": 26 } ]
1
python
res += act.get('name') formatted_roles.append(res) return join_nonempty(*formatted_roles, delim=',') def _fetch_artists(self, by_artist): if not by_artist or len(by_artist) == 0: return None artists = [] for artist in by_artist: res = '' ...
Review this code and list any quality issues.
[ { "issue": "Haven't tested this, but I think/hope this should work:\r\n```suggestion\r\n artists = []\r\n for artist in traverse_obj(track, (key, ..., {dict})):\r\n if res := join_nonempty(*traverse_obj(track, (\r\n ...,\r\n ('role', filter, {'{}…'.format})...
1
python
if h.name in hostnames: h.last_job_id = job.id updated_hosts.add(h) if h.id in host_mapping: h.last_job_host_summary_id = host_mapping[h.id] updated_hosts.add(h) Host.objects.bulk_update(list(updated_hosts), ['l...
Review this code and list any quality issues.
[ { "issue": "What if there are _fewer_ than 500 hosts? This \"Hand-rolled\" iterator is hard to read, but that's not a blocker. I tried to test the method in shell:\r\n\r\n```python\r\n>>> my_list = list(range(70))\r\n>>> args = [iter(my_list)]*200\r\n>>> for sublist in zip(*args):\r\n... print([f for f in sub...
1
python
graph_deps = _agent_graph.GraphAgentDeps[AgentDepsT, RunOutputDataT]( user_deps=deps, prompt=user_prompt, new_message_index=len(message_history) if message_history else 0, model=model_used, model_settings=model_settings, usage_limits=usage_limits, ...
Review this code and list any quality issues.
[ { "issue": "Could we move this to some top-level method, like the other override context var usages?", "severity": "major", "line": 26 } ]
1
python
async def async_get_lock_usercode( self, code_slot: int | None = None, refresh: bool = False ) -> ServiceResponse: """Get the usercode at index X on the lock.""" if code_slot is None and refresh: raise ServiceValidationError( "The refresh option is only supported ...
Review this code and list any quality issues.
[ { "issue": "Can we use a translation with translation placeholders for the code slot and error string here?", "severity": "minor", "line": 26 } ]
1
python
self._sort_formats(formats) extra_info.update({ 'id': content_id, 'formats': formats, 'subtitles': subtitles, }) info.update({k: v for k, v in extra_info.items() if v is not None}) return info def _extract_video_info(self, *args, **kwargs): ...
Review this code and list any quality issues.
[]
0
python
self.client.get("/render_no_template/") @override_settings(ROOT_URLCONF="view_tests.default_urls") def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown instead of the technical 404 page, if the user has not altered their URLconf yet. ...
Review this code and list any quality issues.
[ { "issue": "I tried to find if we could make a test a bit closer to the issue but I wasn't successful\r\nHave tested manually that the issue is fixed and that this covered the code changes :+1:", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor from ..networking import HEADRequest from ..utils import ( float_or_none, int_or_none, join_nonempty, parse_qs, traverse_obj, update_url_query, ) from functools import partial class RedCDNLivxIE(InfoExtractor): _VALID_URL = r'https?://[^.]+\.(?:dcs\.redcd...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://[^.]+\\.(?:dcs\\.redcdn|atmcdn)\\.pl/(?:live(?:dash|hls|ss)|nvr)/o2/(?P<tenant>[^/?#]+)/(?P<id>[^?#]+)\\.livx'\r\n```", "severity": "minor", "line": 16 } ]
1
python
# we need to coerce to object dtype to avoid # to allow numpy to take our string as a scalar value dtype = np.dtype("object") if not isna(value): value = ensure_str(value) elif dtype.kind in "mM": value = _maybe_box_and_unbox_datetimelike(value, dtype) subarr = np.em...
Review this code and list any quality issues.
[ { "issue": "What if `value` is `np.int` ? Don't you want to handle that differently?", "severity": "minor", "line": 26 } ]
1
python
) -> None: """ Test unpacking a evil tar with file containing soft links, but no data_filter """ if hasattr(tarfile, "data_filter"): monkeypatch.delattr("tarfile.data_filter") tar_filename = "test_tar_links_no_data_filter.tar" tar_filepath = os.path.join(self...
Review this code and list any quality issues.
[ { "issue": "Since we know the full paths, can we not template to do an exact match of the complete message in both negative cases?", "severity": "minor", "line": 26 } ]
1
python
def find_function_tools(cls_or_obj: Any) -> list[FunctionTool | RawFunctionTool]: methods: list[FunctionTool | RawFunctionTool] = [] for _, member in inspect.getmembers(cls_or_obj): if isinstance(member, (FunctionTool, RawFunctionTool)): methods.append(member) return methods def get_fn...
Review this code and list any quality issues.
[ { "issue": "Maybe this?\n```suggestion\n if (\n hasattr(tool, \"__wrapped__\") # automatically added by functools.wraps\n ):\n resolved_tool = _resolve_wrapped_tool(tool.__wrapped__)\n```", "severity": "minor", "line": 26 } ]
1
python
'Content-Type': 'application/json', 'Accept': 'application/json, text/plain, */*', 'Origin': 'https://www.laxarxames.cat', }, data=json.dumps({ 'Username': username, 'Password': password, 'Device': { 'Platfor...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'https://api.laxarxames.cat/Media/GetMediaPlayInfo', video_id,\r\n```", "severity": "minor", "line": 26 } ]
1
python
if eventData in self.results: self.sf.debug(f"Skipping {eventData} as already mapped.") return None self.results[eventData] = True data = self.query(event.data) if not data: self.sf.error(f"No data received for {event.data}", False) return None ...
Review this code and list any quality issues.
[ { "issue": "Newline missing at end of file.", "severity": "minor", "line": 26 } ]
1
python
"message": "Not Found", } headers = { config.get("auth.user_header_name"): "user@github.com", config.get("auth.groups_header_name"): "groupa,groupb,groupc", } response = self.fetch("/api/v2/route_does_not_exist", method="GET", headers=headers) self.assertE...
Review this code and list any quality issues.
[]
0
python
assert "FILTER" in plan assert plan.index("FILTER") < plan.index("UNNEST") assert_frame_equal( q.collect(), pl.DataFrame({"a": 1, "b": 2}), ) # With `value_counts()` lf = pl.LazyFrame({"a": [1]}).select(pl.col("a").value_counts()).unnest("a") q = lf.filter(pl.col("a") == 1) ...
Review this code and list any quality issues.
[]
0
python
class instance_of(object): """An object that compares equal to any instance of a given type or types. Parameters ---------- types : type or tuple[type] The types to compare equal to. exact : bool, optional Only compare equal to exact instances, not instances of subclasses? """ ...
Review this code and list any quality issues.
[ { "issue": "Is there a reason not to just make this match exactly what the call would look like? `instance_of(str)` seems pretty readable to me.", "severity": "minor", "line": 26 } ]
1
python
branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'llm_log', sa.Column('id', sa.Integer(), nullable=False), sa.Column('company_id', sa.Integer(), nullable=True), sa.Column('api_key', sa.String(),...
Review this code and list any quality issues.
[ { "issue": "I don't think this will work for existing MindsDB databases. \r\n\r\nIIUC, all databases that have run the migration version `2024-02-12_9461892bd889_llm_log.py` will not add these changes, and it might even cause errors because this migration's checksum is different ([ref1](https://github.com/mind...
1
python
return client def _get_or_create_engine(self, configuration: Configuration) -> AsyncEngine: """Get or create the database engine based on configuration.""" if self._engine is not None: return self._engine if self._connection_string is not None: connection_string = s...
Review this code and list any quality issues.
[ { "issue": "This could be something like `not any(dialect in connection_string for dialect in self._supported_dialects)`", "severity": "minor", "line": 26 } ]
1
python
def test_bedrock_provider_model_profile_us_gov_anthropic(env: TestEnv, mocker: MockerFixture): """Test that us-gov. prefixed Anthropic models get the correct profile. This specifically tests the us-gov. prefix which was previously broken because the provider only handled 2-character prefixes. """ e...
Review this code and list any quality issues.
[ { "issue": "we're already testing this above, aren't we?\r\n\r\nlet's add a test to check that we don't have any bedrock shorthand in `KnownModelName` with a geo prefix that we haven't added in the `BEDROCK_GEO_PREFIXES`", "severity": "minor", "line": 26 } ]
1
python
import numpy as np from typing import Optional class DeeplakeRandom(object): def __new__(cls): """Returns a :class:`~deeplake.core.seed.DeeplakeRandom` object singleton instance.""" if not hasattr(cls, "instance"): cls.instance = super(DeeplakeRandom, cls).__new__(cls) cls....
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n seed (int, optional): Integer seed for initializing the computational engines, used for bringing reproducibility to random operations. Set to ``None`` to reset the seed. Defaults to ``None``.\r\n```", "severity": "minor", "line": 18 } ]
1
python
subschema = table.schema for col in table.schema.names: if col in partition_cols: subschema = subschema.remove(subschema.get_field_index(col)) md_list = [] for keys, subgroup in data_df.groupby(partition_keys): if not isinstance(keys, tuple): keys = (keys,) s...
Review this code and list any quality issues.
[ { "issue": "*here*, the path had better be posix...", "severity": "minor", "line": 26 } ]
1
python
}] def _real_extract(self, url): video_id = self._match_id(url) details = self._download_json( f'https://www.s4c.cymru/df/full_prog_details?lang=e&programme_id={video_id}', video_id, fatal=False) playerConfig = self._download_json( 'https://player-api.s4...
Review this code and list any quality issues.
[ { "issue": "extract subs safely\r\n```suggestion\r\n subtitles = {}\r\n for sub in traverse_obj(player_config, ('subtitles', lambda _, v: url_or_none(v['0']))):\r\n subtitles.setdefault(sub.get('3', 'en'), []).append({\r\n 'url': sub['0'],\r\n 'name': sub.g...
1
python
message = "Attribute `tol` of `Test` must be a positive float, if specified." with pytest.raises(ValueError, match=message): Test(tol=np.asarray([])) with pytest.raises(ValueError, match=message): Test(tol=[1, 2, 3]) with pytest.raises(ValueError, match=message): Test(tol=np.nan) ...
Review this code and list any quality issues.
[ { "issue": "Here and throughout.\r\n```suggestion\r\n Test().lmoment(1, standardize=True)\r\n```", "severity": "minor", "line": 26 } ]
1
python
metrics[name] = tensor.norm(p=self.p, dim=across_dim) return metrics class MultiDataNormMetricsCalculator(NormMetricsCalculator): """ The data value format is a two-element list [batch_number, cumulative_data]. Directly use the cumulative_data as new_data to calculate norm metric. TaylorFO pru...
Review this code and list any quality issues.
[]
0
python
expt = self._mlflow_client.get_experiment_by_name(self._experiment_name) if expt is not None: self._experiment_id = expt.experiment_id else: log.warning(f"Experiment with name {self._experiment_name} not found. Creating it.") self._experiment_id = ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n Create the experiment if it does not exist to get the run id.\r\n \r\n Return:\r\n The run id.\r\n```\r\nfor the google docstring style we need spacing here so it gets rendered properly :)", "severity": "minor", "line": 26 } ]
1
python
if input_data.include_serp_info else None ), clickstream_data=( keyword_data.get("clickstream_keyword_info") if input_data.include_clickstream_data else None ), ...
Review this code and list any quality issues.
[ { "issue": "Using a bare `except Exception` is too broad and may catch unexpected exceptions. Consider catching more specific exceptions related to API calls or data processing, or at minimum log the exception for debugging purposes.", "severity": "critical", "line": 26 } ]
1
python
Parameters ---------- graph The graph/curve for which the area needs to be gotten. x_range The range of the minimum and maximum x-values of the area. ``x_range = [x_min, x_max]``. color The color of the area. Creates a gradient if a list of colors is p...
Review this code and list any quality issues.
[ { "issue": "You should use filter here instead of list comps", "severity": "minor", "line": 26 } ]
1
python
return param_id = self.get_param_id(param) assert self.params_already_reduced[param_id] == False, \ f"The parameter {debug_param2name(param)} has already been reduced. \ Gradient computed twice for this partition. \ Multiple gradient reductions are currently not supp...
Review this code and list any quality issues.
[ { "issue": "this comment is now dangling, perhaps move it to before the code you added?", "severity": "minor", "line": 26 } ]
1
python
) onnx.save_model(self.model, model_file_path, self.serialization_format) self.assertTrue(os.path.isfile(model_file_path)) self.assertTrue(os.path.isfile(os.path.join(self.temp_dir, "input_value"))) self.assertTrue(os.path.isfile(os.path.join(self.temp_dir, "attribute_value"))) def...
Review this code and list any quality issues.
[]
0
python
'title': '丘みどり2020配信LIVE Vol.2 ~秋麗~ 【Streaming+(配信チケット)】', 'live_status': 'was_live', 'release_date': '20200920', 'release_timestamp': 1600596000, }, 'params': { 'skip_download': True, 'ignore_no_formats_error': True, }, 'expect...
Review this code and list any quality issues.
[ { "issue": "Is there a cookie we can check for instead?", "severity": "minor", "line": 26 } ]
1
python
name: str resolved: NotRequired[ResolvedData] guild_id: NotRequired[Snowflake] class ChatInputApplicationCommandInteractionData(_BaseApplicationCommandInteractionData, total=False): type: Literal[1] options: List[ApplicationCommandInteractionDataOption] class _BaseNonChatInputApplicationCommandInter...
Review this code and list any quality issues.
[]
0
python
opencast\.hs-osnabrueck\.de| video[0-9]+\.virtuos\.uni-osnabrueck\.de| opencast\.uni-koeln\.de| media\.opencast\.hochschule-rhein-waal\.de| matterhorn\.dce\.harvard\.edu| hs-harz\....
Review this code and list any quality issues.
[ { "issue": "shouldn't be fatal.\r\nuse .get and only append if it exists", "severity": "minor", "line": 26 } ]
1
python
"inner_zero": 0, "inner_false": False, } pool.add(("node1", "obj"), obj_value) segment_none = pool.get(("node1", "obj", "inner_none")) assert segment_none is not None assert isinstance(segment_none, NoneSegment) segment_empty = pool.get(("node1", "obj", "inn...
Review this code and list any quality issues.
[ { "issue": "Corrected spelling of 'Vairabale' to 'Variable' in class name.\n```suggestion\nclass TestVariablePoolGetNotModifyVariableDictionary:\n```", "severity": "minor", "line": 26 } ]
1
python
from __future__ import annotations __all__ = ["DecimalNumber", "Integer", "Variable"] from typing import Sequence import numpy as np from manim import config from manim.constants import * from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.text.tex_mobject import MathTex, Single...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n The numeric value to be displayed. It can later be modified using :meth:`.set_value`.\r\n```", "severity": "minor", "line": 26 } ]
1
python
note=f'Downloading page {page}', query={ 'page': page, 'sort': 'date', 'user': user_id, 'limit': self._PER_PAGE, }) yield from ( self.url_result(f'https://iwara.tv/video/{x}') for x in traverse_obj(vi...
Review this code and list any quality issues.
[ { "issue": "I agree, but it may be useful to have a `UUID_RE` in utils", "severity": "minor", "line": 26 } ]
1
python
Returns ------- heights : (nx, ny) float32 ndarray Highest elevation per coarse cell (NaN if no hit). xs : (nx,) float32 ndarray ys : (ny,) float32 ndarray Coordinates of grid lines (cell centres). Notes ----- • Requires `pyembree` or `rtree` for fast ray‑...
Review this code and list any quality issues.
[ { "issue": "It would be nice to avoid duplicating every lines for x and y:\r\n```python\r\nfrom collections.abc import ValuesView, Sequence\r\n\r\nif np.isscalar(spacing):\r\n spacing = (spacing, spacing)\r\n\r\nn, s, f, f_lin = [None, None], [None, None], [None, None], [None, None]\r\nfor i, (vmin, vmax, de...
1
python
self.assertEqual(len(renderer_classes), 2) self.assertIn(JSONRenderer, renderer_classes) self.assertIn(BrowsableAPIRenderer, renderer_classes) @patch('wagtail.admin.api.views.apps.is_installed') def test_renderer_classes_without_rest_framework(self, mock_is_installed): """Test that only...
Review this code and list any quality issues.
[ { "issue": "Can we have another test that verifies the API can still return HTML with the right `Accept` header?", "severity": "minor", "line": 26 } ]
1
python
def __getitem__(self, indx): ... def __setitem__(self, index, value): ... def __next__(self): ... class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): __array_priority__: Any def __new__(cls, data=..., mask=..., dtype=..., copy=..., subok=..., ndmin=..., fill_value=..., keep_mask=..., hard_mask=..., shr...
Review this code and list any quality issues.
[ { "issue": "These seem related. No need to worry about setting a new personal record <sub>(😏)</sub> for largest diff.", "severity": "minor", "line": 26 } ]
1
python
it was run in a separated thread: the *run_in_thread* parameter to the `(Gui.)run^` method was set to True, or you are running in an IPython notebook context. """ if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running: self._server.stop_...
Review this code and list any quality issues.
[ { "issue": "I don't quite understand this exception.\r\nWhether there are no hooks, then nullcontext is fine.\r\nOr there are, then live and let live...", "severity": "minor", "line": 26 } ]
1
python
class Metadata(Model): timestamp: datetime.datetime version: str argv: Optional[Tuple[str, ...]] = None sample: Sample analysis: Analysis class CompoundStatementType: AND = "and" OR = "or" NOT = "not" OPTIONAL = "optional" class StatementModel(FrozenModel): ... class Compou...
Review this code and list any quality issues.
[ { "issue": "i dont think this is equivalent. is it important that this change be made?\r\n\r\nthe type before the change would be `typing.Literal[\"some\"]` and after the change `str`.", "severity": "minor", "line": 26 } ]
1
python
# but we always get all formats back no matter what settings you send formats.extend(self._extract_mpd_formats( f"{base_media_url}&format=dash", video_id, mpd_id='dash', fatal=False )) formats.extend(self._extract_m3u8_formats( f"{base_media_url}&format=hls", video_id, m3...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n video_id = self._match_id(url)\r\n```", "severity": "minor", "line": 26 } ]
1
python
Compare the key's value of nodes_output and the corresponding requirements one by one. If a key's value that does not match the requirement is found, provide the comment content on how to modify it. No output is required for matching keys. ### nodes_output {nodes_output} ----- ## format example [{tag}] {{ "key1"...
Review this code and list any quality issues.
[ { "issue": "the word \"json\" or \"markdown\" depends on user's choice.", "severity": "minor", "line": 26 } ]
1
python
Args: y_pred: input data to compute, typical segmentation model output. It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values should be binarized. y: ground truth to compute mean dice metric. `y` can be single-channel class indices or in the...
Review this code and list any quality issues.
[ { "issue": "What is the rationale behind putting the dice code into a class? This class doesn't really have much state, whatever is passed to its constructor could be arguments for the function like in the original version. The code using this class creates a new instance each time as well which doesn't let us ...
1
python
def set_default(cls, **kwargs) -> None: """Sets the default values of keyword arguments. If this method is called without any additional keyword arguments, the original default values of the initialization method of this class are restored. Parameters ---------- ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25)\r\n```", "severity": "minor", "line": 26 } ]
1
python
os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk("ray/dashboard/modules/metrics/export") for filename in filenames ] ray_files += [ os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk( "ray/dashboard/modules/metrics/dashboards" ) for fil...
Review this code and list any quality issues.
[ { "issue": "If it works for Pandas >3, we don't need to pin it here", "severity": "minor", "line": 26 } ]
1
python
np.True_ Create a custom distribution with multiple parameterizations. Here we create a custom version of the beta distribution that has an alternative parameterization in terms of the mean ``mu`` and a dispersion parameter ``nu``. >>> class MyBeta: ... @property ... def __make_distrib...
Review this code and list any quality issues.
[ { "issue": "While I'm changing things completely subjectively...\r\n```suggestion\r\n ... return dict(a=a, b=b, mu=mu, nu=nu)\r\n```", "severity": "minor", "line": 26 } ]
1
python
push_data=context.push_data, get_key_value_store=context.get_key_value_store, log=context.log, http_response=result.http_response, ) async def _handle_blocked_request(self, context: HttpCrawlingContext) -> AsyncGenerator[HttpCrawlingContext, None]: """Try to dete...
Review this code and list any quality issues.
[ { "issue": "Wondering whether this part should not look more like this:\r\n\r\n```python\r\nif context.session and context.session.is_blocked_status_code(\r\n status_code=status_code,\r\n additional_blocked_status_codes=self._http_client.additional_blocked_status_codes,\r\n ignore_http_error_status_cod...
1
python
assert pod.num_pods == 3 * 3 + 1 response_texts = set() # replicas are used in a round robin fashion, so sending 3 requests should hit each one time response = GrpcConnectionPool.send_request_sync( _create_test_data_message(), f'{pod.head_args.host}:{pod.head_args.port}',...
Review this code and list any quality issues.
[]
0
python
def _entries(self, nextjs_json, display_id): if isinstance(nextjs_json, dict): yield from self._get_video_data(nextjs_json, display_id) else: for item in nextjs_json: yield from self._get_video_data(item, display_id) def _real_extract(self, url): site...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'categories': traverse_obj(nextjs_json, ('categories', ..., 'label')),\r\n```\r\ntraverse_obj never raises", "severity": "minor", "line": 26 } ]
1
python
Parameters ---------- polyline The parsed SVG polyline. """ points = [_convert_point_to_3d(*point) for point in polyline] vmobject_class = self.get_mobject_type_class() return vmobject_class().set_points_as_corners(points) @staticmethod def text_to_mo...
Review this code and list any quality issues.
[ { "issue": "Can we get rid of this mypy ignore statement?", "severity": "minor", "line": 26 } ]
1
python
torch_dtype=torch.bfloat16, ) ) train_model_config.update( dict( torch_dtype=torch.bfloat16, use_cache=False, ) ) generate_config.update( dict( max_length=1024 + 512, do_sample...
Review this code and list any quality issues.
[ { "issue": "train config should be outside the backend part.", "severity": "minor", "line": 26 } ]
1
python
except FileNotFoundError: checkpoint_type = CheckpointType.sharded # Load config. config_path = resource_path(checkpoint_dir, "config.yaml") model_config = ModelConfig.load(config_path, key="model", validate_paths=False) if checkpoint_type == CheckpointType.unsharded: ...
Review this code and list any quality issues.
[ { "issue": "We still have these lines, but I'm worried this won't work when the model is on the \"meta\" device, and isn't supposed to be initialized until later. Can you try that scenario? Try training a 7B model on 8 GPUs, just for a step or two to see if it still works?", "severity": "minor", "line":...
1
python
# dpo hyperparams self.beta = finetuning_args.pref_beta self.loss_type = finetuning_args.pref_loss self.ftx_gamma = finetuning_args.pref_ftx self.bco_gemma = finetuning_args.pref_bco_weight self.label_smoothing = finetuning_args.dpo_label_smoothing self.simpo_gamma = fine...
Review this code and list any quality issues.
[ { "issue": "`def fsdp2_prepare_model(accelerator, model: torch.nn.Module) -> torch.nn.Module:`\n\nplease change params placements", "severity": "minor", "line": 26 } ]
1
python
---------------- **kwargs : `~matplotlib.axes.Axes.imshow` arguments """ A = np.asanyarray(A) if fignum == 0: ax = gca() else: if fignum is not None and fignum_exists(fignum): # Do not try to set a figure size. figsize = None else: # Extra...
Review this code and list any quality issues.
[ { "issue": "IMHO we could leave data out, because it's not typed anyway, so no advantage of writing it out.", "severity": "minor", "line": 26 } ]
1
python
NetEaseMusicSingerIE, ) from .netverse import ( NetverseIE, NetversePlaylistIE, NetverseSearchIE, ) from .netzkino import NetzkinoIE from .newgrounds import ( NewgroundsIE, NewgroundsPlaylistIE, NewgroundsUserIE, ) from .newspicks import NewsPicksIE from .newsy import NewsyIE from .nextmedia imp...
Review this code and list any quality issues.
[]
0
python
'preference': 1, **traverse_obj(mp4_entry, { 'height': ('height', {int_or_none}), 'width': ('width', {int_or_none}), 'filesize': ('file_size', {int_or_none}), }), }) return { 'formats': formats, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n r'https?://(?:\\w+\\.)?subspla\\.sh/(?P<id>\\w+)',\r\n```", "severity": "minor", "line": 26 } ]
1
python
# A newer version available! ("1.0", "2.0", None, True, True), # A newer version available, and cached value is new too! ("1.0", "2.0", "2.0", True, True), # A newer version available, but was not installed by pip. ("1.0", "2.0", None, False, False), # On the latest versi...
Review this code and list any quality issues.
[]
0
python
) self.update_state(STATE_INIT) self.stepload_greenlet = self.greenlet.spawn(self.stepload_worker, spawn_rate, step_user_count, step_duration) self.stepload_greenlet.link_exception(greenlet_exception_handler) def stepload_worker(self, spawn_rate, step_users_growth, step_duration): c...
Review this code and list any quality issues.
[ { "issue": "Could you not just call `self.environment.shape_class.reset_time()` here and that would be enough?", "severity": "minor", "line": 26 } ]
1
python
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_str, ) from ..utils import ( ExtractorError, lowercase_escape, try_get, ) class StripchatIE(InfoExtractor): _VALID_URL = r'https?://stripchat\.com/(?P<id>[0-9A-Za-z-_]+)' _T...
Review this code and list any quality issues.
[ { "issue": "use `_TESTS = [{...}]`. `_TEST` is legacy interface", "severity": "minor", "line": 17 } ]
1
python
self, device: CyncLight, coordinator: CyncCoordinator, room_name: str | None = None, ) -> None: """Set up base attributes.""" super().__init__(device, coordinator, room_name) supported_color_modes = {ColorMode.ONOFF} if device.supports_capability(CyncCapabili...
Review this code and list any quality issues.
[]
0
python
import functools import math from .streaks import StreaksBaseIE from ..networking import HEADRequest from ..utils import ( InAdvancePagedList, clean_html, js_to_json, parse_iso8601, parse_qs, str_or_none, ) from ..utils.traversal import require, traverse_obj class LocipoBaseIE(StreaksBaseIE):...
Review this code and list any quality issues.
[ { "issue": "Can you explain why we do this?\r\n\r\nIt will make it so passing cookies for this site is ineffective.\r\n\r\nAlso note that both `LocipoPlaylistIE` and `LocipoIE` will clear the cookiejar when they are initialized, so any cookies set during playlist extraction will be cleared again before the firs...
1
python
if error_data.error.innererror: provider_details['content_filter_result'] = ( error_data.error.innererror.content_filter_result.model_dump(exclude_none=True) ) return ModelResponse( parts=[], # Empty parts to trigger c...
Review this code and list any quality issues.
[ { "issue": "It's a bit confusing now that for o series and GPT5, the dropping is handled via the other field, and this is only for 5.1+. Because reading this, it seems like in the case of `if not profile.openai_supports_reasoning_effort_none`, we should be dropping all fields instead of `returning` and not dele...
1
python
-------- >>> len(range(1)) 1 >>> len(range(5)) 5 >>> len(range(1, 5)) 4 >>> len(range(0, 5, 2)) 3 >>> len(range(5, 0, -1)) 5 >>> len(range(5, 0, 1)) 0 """ ...
Review this code and list any quality issues.
[ { "issue": "I should probably comment that the algo was taken from CPython", "severity": "minor", "line": 26 } ]
1
python
self.round = self.num_microbatches // self.stage_manager.num_stages def load_micro_batch(self) -> Any: """Load a micro batch from the current batch. Returns: Any: Micro batch. """ micro_batch = get_micro_batch(self.batch, self.microbatch_offset, self.microbatch_size) ...
Review this code and list any quality issues.
[]
0