language string | code-snippit string | instruction string | flaws list | flaw_count int64 |
|---|---|---|---|---|
python | def test_sharding_strategy():
"""Test the different ways the sharding strategy can be set."""
from torch.distributed.fsdp import ShardingStrategy
# default
strategy = FSDPStrategy()
assert strategy.sharding_strategy == ShardingStrategy.FULL_SHARD
# enum
strategy = FSDPStrategy(sharding_str... | Review this code and list any quality issues. | [] | 0 |
python | f"Exception during Venstar sensor update: {ex}"
) from ex
if not sensor_success:
raise update_coordinator.UpdateFailed(
"Unable to update Venstar sensor data"
)
# older venstars sometimes cannot handle rapid sequential connections
await async... | Review this code and list any quality issues. | [
{
"issue": "`self.runtimes` either needs to get `list[dict[str, int]] | False` as type, or we store the result temporarily in another variable as this is otherwise a type violation. I would suggest the latter.",
"severity": "minor",
"line": 26
}
] | 1 |
python | TEST_CASE_DEEP_SUPERVISION.append(test_case)
class TestDynUNet(unittest.TestCase):
@parameterized.expand(TEST_CASE_DYNUNET_3D)
def test_shape(self, input_param, input_shape, expected_shape):
net = DynUNet(**input_param).to(device)
if "alphadropout" in input_param.get("dropout"):
se... | Review this code and list any quality issues. | [
{
"issue": "Since this part is removed, related import can be removed (https://github.com/Project-MONAI/MONAI/pull/6399/files#diff-8f2debbe9c6aa7e8c0b4f65cf36df76bcc5097ce006af6638ae37fb14950ec5eL25)",
"severity": "minor",
"line": 26
}
] | 1 |
python | _OAUTH_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token' # token_endpoint
@staticmethod
def _get_oauth_cache_key(profile):
return f'oauth_refresh_token_{profile}'
def _set_oauth_info(self, token_response, profile):
YoutubeBaseInfoExtractor._OAUTH_ACCESS_TOKEN_CAC... | Review this code and list any quality issues. | [
{
"issue": "for consistency?\r\n```suggestion\r\n YoutubeBaseInfoExtractor._OAUTH_PROFILE = user or 'default'\r\n\r\n if YoutubeBaseInfoExtractor._OAUTH_PROFILE in YoutubeBaseInfoExtractor._OAUTH_ACCESS_TOKEN_CACHE:\r\n```",
"severity": "critical",
"line": 26
}
] | 1 |
python | register_model_info(
[
"AquilaChat-7B",
"AquilaChat2-7B",
"AquilaChat2-34B",
],
"Aquila-Chat",
"https://huggingface.co/BAAI/AquilaChat2-34B",
"Chat models developed by BAAI team",
)
register_model_info(
["xDAN-L1-Chat-RL-v1"],
"xDAN-L1-Chat",
"https://huggingface... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n\r\nregister_model_info(\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | async def test_firefox_headless_headers(httpbin: URL) -> None:
crawler = PlaywrightCrawler(headless=True, browser_type='firefox')
headers = dict[str, str]()
@crawler.router.default_handler
async def request_handler(context: PlaywrightCrawlingContext) -> None:
response = await context.response.t... | Review this code and list any quality issues. | [] | 0 |
python | link_a = torch.tensor([cube1.base_link.idx], dtype=gs.tc_int, device=gs.device)
link_b = torch.tensor([cube2.base_link.idx], dtype=gs.tc_int, device=gs.device)
scene.sim.rigid_solver.add_weld_constraint(link_a, link_b)
scene.step()
welds = scene.sim.rigid_solver.get_weld_constraints(as_tensor=True, to... | Review this code and list any quality issues. | [
{
"issue": "Just keep them both in the same test. An call the test `test_get_weld_constraints_api`",
"severity": "minor",
"line": 26
}
] | 1 |
python | pg_mesh (ProcessGroupMesh): Process group mesh.
pipeline_axis (int): The axis along which the pipeline is constructed.
Attributes:
num_stages (int): Number of stages in the pipeline.
stage (int): The current stage.
"""
def __init__(
self, pg_mesh: ProcessGroupMesh, pipeline... | Review this code and list any quality issues. | [
{
"issue": "Can you keep these attributes in schedule?",
"severity": "minor",
"line": 26
}
] | 1 |
python | view_count_text = self._get_text(renderer, 'viewCountText') or ''
view_count = str_to_int(self._search_regex(
r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
'view count', default=None))
uploader = self._get_text(renderer, 'ownerText', 'shortBylineText')
channel_id = t... | Review this code and list any quality issues. | [
{
"issue": "Don't set timestamp, only upload date. Since the video extractor doesn't return its own timestamp, this will be propagated",
"severity": "major",
"line": 26
}
] | 1 |
python | print(f"Prune all dangling {CI_IMAGE_LABEL} images")
# When detecting podman-docker, `--external` should be added.
run(["docker", "image", "prune", "--force", "--filter", f"label={CI_IMAGE_LABEL}"])
cmd_run = ["docker", "run", "--rm", "--interactive", "--detach", "--tty"]
cmd_run += [
... | Review this code and list any quality issues. | [
{
"issue": "It seems to me we don't usually use this when `text` is set:\r\n```bash\r\n% git grep -r 'text=True' . | wc -l\r\n 37\r\n% git grep -r 'encoding=\"ascii\"' . | wc -l\r\n 3\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | :param allow_generator_output: Whether to allow generator output.
:type allow_generator_output: bool
:param line_timeout_sec: The maximum time to wait for a line of output.
:type line_timeout_sec: Optional[int]
:return: The result of executing the line.
:rtype: ~promptflow.execut... | Review this code and list any quality issues. | [] | 0 |
python | '_cs_followup',
'_cs_namespace',
'_cs_command',
'_channel',
)
def __init__(self, *, data: InteractionPayload, state: ConnectionState[ClientT]):
self._state: ConnectionState[ClientT] = state
self._client: ClientT = state._get_client()
self._session: ClientSession ... | Review this code and list any quality issues. | [
{
"issue": "Storing a random dictionary in an attribute is very rarely a good idea.",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'title': '#138 Nepilnīgā kompensējamo zāļu sistēma pat mēnešiem dzenā pacientus pa aptiekām',
'thumbnail': 'https://pic.latvijasradio.lv/public/assets/media/9/d/large_fd4675ac.jpg',
'upload_date': '20231102',
'timestamp': 1698921060,
'description': 'md5:7bac3b2dd41e443250... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'id': video_id,\r\n **traverse_obj(json, {\r\n 'url': ('playback', 'service', 'url', {url_or_none}),\r\n 'title': ('mediaItem', 'title'),\r\n 'description': ('mediaItem', ('lead', 'body')),\r\n 'durat... | 1 |
python | @pytest.fixture
async def set_time_zone(hass: HomeAssistant) -> None:
"""Set the time zone for the tests."""
# Set our timezone to CST/Regina so we can check calculations
# This keeps UTC-6 all year round
await hass.config.async_set_time_zone("America/Regina")
class MockFlow(ConfigFlow):
"""Test f... | Review this code and list any quality issues. | [
{
"issue": "Don't think we want or need these",
"severity": "minor",
"line": 26
}
] | 1 |
python | model_def,
model_filename,
save_as_external_data=True,
all_tensors_to_one_file=True,
location=data_filename,
size_threshold=0,
convert_attribute=False,
)
# Load the model and verify external data
... | Review this code and list any quality issues. | [
{
"issue": "The key-value pairs are not guaranteed in order. I would build a dictionary from `large_tensor.external_data` then assert the python dict directly.",
"severity": "minor",
"line": 26
}
] | 1 |
python | print(stats_stream.getvalue().rstrip())
green = "\033[92m"
reset = "\033[0m"
print(f"{green}UI window ready in {elapsed_ms:.1f} ms{reset}")
sys.exit(0)
def _ffmpeg_writer_thread(self):
"""Background thread that writes frames to ffmpeg."""
while True:
try:
data = self._ffmpeg_qu... | Review this code and list any quality issues. | [
{
"issue": "The comment in `push_widget()` says the previous widget stays rendered for smooth transitions, but the new-modal render path currently renders only the last widget on `_nav_stack`. Either render the underlying widgets as intended or update this comment to match actual behavior.\n```suggestion\n #... | 1 |
python | }]
}, {
'url': 'https://dvojka.rozhlas.cz/karel-siktanc-cerny-jezdec-bily-kun-napinava-pohadka-o-tajemnem-prizraku-8946969',
'info_dict': {
'id': '8946969',
'title': 'Karel Šiktanc: Černý jezdec, bílý kůň. Napínavá pohádka o tajemném přízraku',
},
'playlist_co... | Review this code and list any quality issues. | [
{
"issue": "inline `formats` in return and change to new method name",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'id': video_id,
'title': title,
'formats': self._extract_png_formats(vidplayer_id),
'is_live': True,
}
class RTVETelevisionIE(InfoExtractor):
IE_NAME = 'rtve.es:television'
_VALID_URL = r'https?://(?:www\.)?rtve\.es/television/[^/]+/[^/]+/(?P<id>\d+).shtml'
_TE... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'series': try_get(info, lambda x: x['programInfo']['title']),\r\n```\r\nor \r\n```py\r\n 'series': traverse_obj(info, ('programInfo', 'title')),\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | func = method.__func__
mobject.add_updater(lambda m: func(m, *args, **kwargs))
return mobject
def f_always(method, *arg_generators, **kwargs):
"""
More functional version of always, where instead
of taking in args, it takes in functions which output
the relevant arguments.
"""
assert_i... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n \"\"\"Redraw the mobject constructed by a function every frame.\r\n\r\n This function returns a mobject with an attached updater that\r\n continuously regenerates the mobject according to the\r\n specified function.\r\n\r\n Parameters\r\n ----------\r\n func\r\... | 1 |
python | sorted_patterns = cls._sort_patterns(dataset_patterns)
missing_keys = [
key
for key in load_versions.keys()
if not (cls._match_pattern(sorted_patterns, key) or key in catalog)
]
if missing_keys:
raise DatasetNotFoundError(
f"'load_v... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n return \"{\" in pattern\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | DB. So it should be a unique and constant across the application run.
Use the UUID format for the ID.
description: The description of the block, explaining what the block does.
contributors: The list of contributors who contributed to the block.
input_schema: The sche... | Review this code and list any quality issues. | [
{
"issue": "Adding this for adding a dynamic persisted stats for blocks. This is persisted in NodeExecutions table",
"severity": "minor",
"line": 26
}
] | 1 |
python | check_array_api_metric(
metric,
array_namespace,
device,
dtype_name,
a_np=X_np,
b_np=Y_np,
**metric_kwargs,
)
array_api_metric_checkers = {
accuracy_score: [
check_array_api_binary_classification_metric,
check_array_api_multiclass_classif... | Review this code and list any quality issues. | [
{
"issue": "@OmarManzoor naive question - why not include `check_array_api_binary_classification_metric` here?",
"severity": "minor",
"line": 26
}
] | 1 |
python | actual_video_id = traverse_obj(nuxt_data, ('item', 'video'))
if not actual_video_id:
raise ExtractorError('Unable to extract actual video ID')
video_data = self._download_json(
f'http://playvideo.qcloud.com/getplayinfo/v2/1253584441/{actual_video_id}',
actual_video_... | Review this code and list any quality issues. | [
{
"issue": "I would write this like so to also extract the source video:\r\n```suggestion\r\n formats = []\r\n for video in traverse_obj(video_data, ('videoInfo', ('sourceVideo', ('transcodeList', ...)), {dict})):\r\n if not url_or_none(video.get('url')):\r\n continue\r\n... | 1 |
python | 'playlist_mincount': 16, # as of 2021/06/20
}, {
'url': 'https://www.nhk.or.jp/school/rika/',
'info_dict': {
'id': 'rika',
'title': '理科',
},
'playlist_mincount': 15, # as of 2021/06/25
}]
@classmethod
def suitable(cls, url):
return super... | Review this code and list any quality issues. | [
{
"issue": "wouldnt `playlist_from_matches` be simpler?",
"severity": "minor",
"line": 26
}
] | 1 |
python | if "like" in funcname:
a = backend_lib.random.randint(0, 10, shape).astype(dtype)
np_r = np_func(a, order=order)
da_r = da_func(a, order=order, chunks=chunks, name=name)
else:
np_r = np_func(shape, order=order, dtype=dtype)
da_r = da_func(shape, order... | Review this code and list any quality issues. | [
{
"issue": "Introduced by 95ef5b753959fd827484e993d399c6a92b01f634 / #6129. I presume this was an unintended typo, wasn't it?",
"severity": "minor",
"line": 26
}
] | 1 |
python | def _wrap_model(self):
"""
Wrap all modules that needed to be compressed.
"""
raise NotImplementedError
def _unwrap_model(self):
"""
Unwrap all modules that needed to be compressed.
"""
raise NotImplementedError
def set_wrappers_attribute(self, n... | Review this code and list any quality issues. | [
{
"issue": "I think you mean `self.get_modules_wrapper().values()`.",
"severity": "minor",
"line": 26
}
] | 1 |
python | if not embedding_model:
raise ValueError("Please provide an embedding model.")
model_kwargs = {"device": device}
encode_kwargs = {"normalize_embeddings": True}
self.model = HuggingFaceEmbeddings(
model_name=embedding_model, model_kwargs=model_kwargs, encode_kwargs=encode... | Review this code and list any quality issues. | [] | 0 |
python | if org_model.__class__.__name__ == 'GPT2Model':
check_output_hidden_state(org_output, sharded_output, stage_manager, atol=atol, rtol=rtol)
check_loss(org_loss, sharded_loss, atol=atol, rtol=rtol)
def unwrap(module):
if isinstance(module, HybridParallelModule):
module = modu... | Review this code and list any quality issues. | [] | 0 |
python | # print(f"\nmaybe_reference_offer = {maker_response['offer']}")
# only check for success
# due to differences in chain progression, the exact offer and trade id may differ from the reference
# assert maker_response == {"success": True, "offer": reference.make_offer_response}
assert maker_response["succ... | Review this code and list any quality issues. | [] | 0 |
python | author_id_field,
book_table,
book_fk_field,
)
self.assertEqual(lhs_expr, Col(author_table, author_id_field))
self.assertEqual(
rhs_expr, Cast(Col(book_table, book_fk_field), author_id_field)
)
def test_bulk_batch_size(self):
objects = rang... | Review this code and list any quality issues. | [
{
"issue": "Then we could just mock `uses_server_side_binding`, which I think would improve the test a little bit.",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'ext': determine_ext(audio_url)
})
return merge_dicts({
'id': display_id,
'formats': formats,
'uploader_id': uploader_id
}, traverse_obj(story_data, {
'title': ('story_content', 'content', 'title') or 'title',
'uploader': ('sharer'... | Review this code and list any quality issues. | [
{
"issue": "same as above\r\n```suggestion\r\n 'title': ((('meta', 'title'), ('ld', 'headline'), ('og', 'og:title'), ('og', 'twitter:title')), {str}),\r\n 'description': ((('meta', 'description'), ('ld', 'description'), ('og', 'og:description'), ('og', 'twitter:description')), {str}),\r\n ... | 1 |
python | gui._bind_var_val(
"scenario_list",
[{"id": "1", "name": "scenario 1"}, {"id": "3", "name": "scenario 3"}, {"id": "2", "name": "scenario 2"}],
)
gui._bind_var_val("selected_obj", {"id": "1", "name": "scenario 1"})
with tgb.Page(frame=None) as page:
tgb.selector( # type: ignore[attr-... | Review this code and list any quality issues. | [
{
"issue": "I would have renamed this test to `test_selector_pandas_series`, which really is the point of it.",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import re
from django.utils.translation import gettext_lazy as _
from django.apps.config import AppConfig
from django.apps.registry import apps
__all__ = [
'CLOUD_PROVIDERS',
'PRIVILEGE_ESCALATION_METHODS',
'ANSI_SGR_PATTERN',
'CAN_CANCEL',
... | Review this code and list any quality issues. | [
{
"issue": "This isn't returned from the function for some reason. Why?",
"severity": "minor",
"line": 25
}
] | 1 |
python | opt_a = torch.optim.Adam(model.parameters(), lr=0.002)
opt_b = torch.optim.SGD(model.parameters(), lr=0.002)
scheduler_a = torch.optim.lr_scheduler.StepLR(opt_a, 10)
scheduler_b = torch.optim.lr_scheduler.StepLR(opt_b, 10)
# single optimizer
model.configure_optimizers = lambda: opt_a
optim, lr_... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n assert len(optim) == len(lr_sched) == 1\r\n assert len(freq) == 0\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | DataContext.get_current().op_resource_reservation_enabled = True
DataContext.get_current().op_resource_reservation_ratio = 0.5
o1 = InputDataBuffer(DataContext.get_current(), [])
# Two GPU operators
o2 = mock_map_op(o1, ray_remote_args={"num_gpus": 1})
o2.min_max_resource_requi... | Review this code and list any quality issues. | [] | 0 |
python | ATTR_LANGUAGE,
ATTR_MEDIA,
ATTR_MEDIA_DESCRIPTION,
ATTR_MEDIA_WARNING,
ATTR_STATUS,
ATTR_VISIBILITY,
DOMAIN,
)
from .coordinator import MastodonConfigEntry
from .utils import get_media_type
class StatusVisibility(StrEnum):
"""StatusVisibility model."""
PUBLIC = "public"
UNLISTED =... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\n vol.Required(ATTR_ACCOUNT_NAME): str,\n```\nuse a const for that",
"severity": "minor",
"line": 26
}
] | 1 |
python | class BoringModel(LightningModule):
def __init__(self, in_features: int = 32, out_features: int = 2):
"""
Testing PL Module
Use as follows:
- subclass
- modify the behavior for what you want
class TestModel(BaseTestModel):
def training_step(...):
... | Review this code and list any quality issues. | [
{
"issue": "let's move these parameters to init args, as now they won't be saved with `save_hyperparameters`",
"severity": "minor",
"line": 26
}
] | 1 |
python | if cancelled:
await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
if sources_to_cache:
write_cache(cache, sources_to_cache, mode)
def format_file_in_place(
src: Path,
fast: bool,
mode: FileMode,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multipro... | Review this code and list any quality issues. | [
{
"issue": "I think you can use `dataclasses.replace(mode, is_pyi=True)`, which is kind of more idiomatic.",
"severity": "minor",
"line": 26
}
] | 1 |
python | except Exception:
pass
raise fastapi.WebSocketException(e.status_code, e.detail)
logger.info(f"handle_worker: {worker_id=}")
worker_info = await worker_utils.receive_worker_info(websocket)
logger.info(f"handle_worker: {worker_info=}")
work_queue = queueing.... | Review this code and list any quality issues. | [
{
"issue": "Moved to `FuturesManager.ensure_listening_for_worker_response()` with similar changes to return the `FutureType` in addition to the response.",
"severity": "minor",
"line": 26
}
] | 1 |
python | """
Text object with 3D position and direction.
Parameters
----------
x, y, z : float
The position of the text.
text : str
The text string to display.
zdir : {'x', 'y', 'z', None, 3-tuple}
The direction of the text. See `.get_dir_vector` for a description of
the ... | Review this code and list any quality issues. | [
{
"issue": "Can we change to\r\n```suggestion\r\n if \"rotation\" in kwargs:\r\n```\r\n? It's not exactly the same in that `Text3D(... roation=None)` is differently handled. But unless we have internal reasons to accept that. We can warn on that case as well.",
"severity": "minor",
"line": 26
}... | 1 |
python | function = f"{__name__}.{sys._getframe().f_code.co_name}"
last_updated = int(time.time())
stats.count(
f"{function}.called",
tags={"redis_key": redis_key, "s3_bucket": s3_bucket, "s3_key": s3_key},
)
if redis_key:
if redis_data_type == "str":
if isinstance(data, str)... | Review this code and list any quality issues. | [] | 0 |
python | def embedding_fn2(text, embedding_dim=EMBEDDING_DIM):
return [] # pragma: no cover
def embedding_fn3(text, embedding_dim=EMBEDDING_DIM):
"""Returns embedding in List[np.ndarray] format"""
return [np.zeros(embedding_dim) for i in range(len(text))]
def embedding_fn4(text, embedding_dim=EMBEDDING_DIM):
... | Review this code and list any quality issues. | [
{
"issue": "this test is for backwards compatibility. Here we are checking the old `ids` tensor's support. We can't change this to `id`",
"severity": "minor",
"line": 26
}
] | 1 |
python | @pytest.mark.parametrize(
'order_by, expected_names',
[
('name', ['alice project', 'bob project', 'shared project']),
('-name', ['shared project', 'bob project', 'alice project']),
],
)
@pytest.mark.django_db
def test_project_list_ordering_by_name(get, order_by, expected_names, organization_... | Review this code and list any quality issues. | [
{
"issue": "does this test even make sense anymore?",
"severity": "minor",
"line": 26
}
] | 1 |
python | # in integer floor division
(np.timedelta64(np.iinfo(np.int64).min),
np.timedelta64(-1)),
])
def test_timedelta_floor_div_warnings(self, op1, op2):
with pytest.warns(RuntimeWarning):
actual = op1 // op2
assert_equal(actual, 0)
assert_equal(actual.... | Review this code and list any quality issues. | [] | 0 |
python | """Multidimensional scaling.
Read more in the :ref:`User Guide <multidimensional_scaling>`.
Parameters
----------
n_components : int, default=2
Number of dimensions in which to immerse the dissimilarities.
metric_mds : bool, default=True
If ``True``, perform metric MDS; otherwise,... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\n init : {'random', 'classical_mds'}, default='random'\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | height: int = None,
width: int = None,
should_center: bool = True,
unpack_groups: bool = True,
disable_ligatures: bool = False,
**kwargs,
):
self.text = text
self.color = color
self.size = size
self.line_spacing = line_spacing
self.font... | Review this code and list any quality issues. | [
{
"issue": "import logger from root don't do this, possibly logger should already be defined.\r\n```suggestion\r\n logger.warning(\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | class P2PNode(P2PDataStore):
def on_inv(self, msg):
pass
class P2PLeakTxTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
def run_test(self):
self.gen_node = self.nodes[0] # The block and tx generating node
self.miniwallet = MiniWallet(self.gen_nod... | Review this code and list any quality issues. | [
{
"issue": "nit: double-checked before and after to check effects of test\r\n\r\n```\r\ndiff --git a/test/functional/p2p_leak_tx.py b/test/functional/p2p_leak_tx.py\r\nindex 42e586fca3..d302a68ebf 100755\r\n--- a/test/functional/p2p_leak_tx.py\r\n+++ b/test/functional/p2p_leak_tx.py\r\n@@ -39,4 +39,9 @@ class P... | 1 |
python | from crawlee.storage_clients.models import ProcessedRequest
logger = getLogger(__name__)
class SitemapRequestLoaderState(BaseModel):
"""State for sitemap request loader persistence."""
model_config = ConfigDict(populate_by_name=True)
# URL queue and processing state
url_queue: Annotated[deque[str]... | Review this code and list any quality issues. | [
{
"issue": "Can we rather use field docstrings, please?",
"severity": "minor",
"line": 26
}
] | 1 |
python | import pytest
import datetime
from django.utils.timezone import now
from awx.main.models.schedules import fast_forward_date
from dateutil.rrule import rrule, HOURLY, MINUTELY, MONTHLY
def test_fast_forward_date_all_hours():
'''
Assert that the resulting fast forwarded date is included in the original rrule
... | Review this code and list any quality issues. | [
{
"issue": "It's best to avoid convoluted logic in tests. Error is always truthy, so the conditional is not really needed. Additionally, the right way of checking the exceptions raised is to narrow the expectation. `pytest.raises()` uses (and `pytest.warns()` or `pytest.deprecated()` for that matter) should alw... | 1 |
python | rest of the app.
If you want to disable scrolling for a fixed-height component,
include an inner ``<div>`` wrapper in your component's HTML to
control the overflow behavior.
You are responsible for ensuring the component's inner HTML content is
responsive to the ``<... | Review this code and list any quality issues. | [] | 0 |
python | # Check that disabled_agent was filtered out
triggered_agents = call_args['triggered_agents']
assert len(triggered_agents) == 2
agent_names = [agent.name for agent in triggered_agents]
assert 'test_agent' in agent_names
assert 'another_agent' in agent_names
assert 'disabled_agent' not in agent_n... | Review this code and list any quality issues. | [] | 0 |
python | def run_fwd_bwd(model, data, label, criterion, optimizer, enable_autocast=False):
model.train()
with torch.cuda.amp.autocast(enabled=enable_autocast):
if criterion:
y = model(data)
loss = criterion(y, label)
else:
loss = model(data, label)
loss = loss.... | Review this code and list any quality issues. | [] | 0 |
python | is_copied = False
orig_df = df
# add index if not chart
if paged:
if _PandasDataAccessor.__INDEX_COL not in df.columns:
is_copied = True
df = df.assign(**{_PandasDataAccessor.__INDEX_COL: df.index})
if columns and _PandasDataAccessor.__IND... | Review this code and list any quality issues. | [
{
"issue": "you're still not dealing with string comparison (not contains) and matchcase",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n<|input|password|>\r\n```",
"severity": "minor",
"line": 19
}
] | 1 |
python | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under t... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\ndef _build_wrong_config_type_reason(config_id: str) -> str:\r\n```",
"severity": "critical",
"line": 26
}
] | 1 |
python | ----------
A
The endpoint of the first angle leg
B
The vertex of the angle
C
The endpoint of the second angle leg
**kwargs
Further keyword arguments are passed to :class:`.Angle`
Returns
-------
The Angle calculate... | Review this code and list any quality issues. | [
{
"issue": "Looking at the rendered output, https://manimce--2684.org.readthedocs.build/en/2684/reference/manim.mobject.geometry.line.Angle.html?highlight=angle#anglefromthreepointsbasicexample, the angle only is a \"right angle\" in *some* sense. Either try changing the order of the legs (`RIGHT, ORIGIN, UP`),... | 1 |
python | )
with patch.object(GraphPickler, "reducer_override", _graph_reducer_override):
state["graph_module"] = GraphPickler.dumps(
state["graph_module"], Options(ops_filter=None)
)
state["example_inputs"] = GraphPickler.dumps(state["example_inputs"])
return p... | Review this code and list any quality issues. | [
{
"issue": "I'm trying to get a high-level overview of what is going on. @zhxchen17 @Lucaskabela.\r\nAre we saying that aot_compile now works on image encoders? And that we were missing serialization of part of the backend?",
"severity": "minor",
"line": 26
}
] | 1 |
python | },
}, {
'url': 'https://mixch.tv/m/61DzpIKE',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
data = self._download_json(
f'https://mixch.tv/api-web/movies/{video_id}', video_id)
return {
'id': video_id,
... | Review this code and list any quality issues. | [
{
"issue": "Let's add the timestamp and inline this\r\n```suggestion\r\n 'timestamp': ('movie', 'published', {int_or_none}),\r\n 'uploader_url': ('ownerInfo', 'id', {lambda x: x and f'https://mixch.tv/u/{x}'}),\r\n }),\r\n```\r\nTests will need to be updated.",
"seve... | 1 |
python | from_inputs: str,
to_outputs: str,
load_versions: dict[str, str] | None,
pipeline: str,
pipelines: list[str],
config: str,
conf_source: str,
params: dict[str, Any],
namespaces: str,
only_missing_outputs: bool,
) -> None:
"""Run the pipeline."""
if pipeline and pipelines:
... | Review this code and list any quality issues. | [
{
"issue": "thanks, @Mohmn , I like the idea to add `pipelines` without revoming `pipeline` tag. But I think it should be one session for all pipeline runs, not one session per one run, wdyt @ankatiyar , @ElenaKhaustova ?",
"severity": "minor",
"line": 26
}
] | 1 |
python | def is_allowlisted(cmd: str) -> bool:
for match in cmd_regex.finditer(cmd):
for group in match.groups():
if group and group not in allowlist_commands:
return False
return True
def execute_shell_impl(
cmd: str, _: Path | None, confirm: ConfirmFunc
) -> Generator[Message,... | Review this code and list any quality issues. | [
{
"issue": "I think \"failed to run\" might be bad prompting. We should be careful to not infer too much from a non-zero exit code I think. I'd just keep the \"Ran\" and not try to infer a success/error status for shell commands, for now.",
"severity": "critical",
"line": 26
}
] | 1 |
python | 'url': capfile,
'ext': determine_ext(capfile, 'dfxp')
}],
} if capfile else None,
})
if len(entries) == 1:
entry = dict(entries[0])
entry['id'] = 'c' + video_id if video_type == 'clip' else video_id
retu... | Review this code and list any quality issues. | [
{
"issue": "i don't like this id tbh.\r\nI personally would have parsed the `chamber` `date` and `t` from the url and maybe hashed them if not just joined them using `_` and used that as the id.",
"severity": "minor",
"line": 26
}
] | 1 |
python | port,
diskann,
hnsw,
):
"""
Initialize the PGVector database.
Args:
dbname (str): Database name
collection_name (str): Collection name
embedding_model_dims (int): Dimension of the embedding vector
user (str): Database user
... | Review this code and list any quality issues. | [
{
"issue": "You can keep this in `create_col` function.",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'skip_download': False,
},
'skip': '404 Not Found',
}, {
# was real live url, but 404 now.
'url': 'https://nicochannel.jp/matsuda_shota/live/sm5VuVsRQSRqkyvLWFZtcou7',
'info_dict': {
'id': 'smpptPykLAjmZQchK4k4p93P',
'ext': 'mp4',
},
'p... | Review this code and list any quality issues. | [
{
"issue": "Again, what' the point of these?",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | Review this code and list any quality issues. | [] | 0 |
python | # Log graph database configuration
graph_config = get_graph_config()
logger.info(f"Graph database: {graph_config.graph_database_provider}")
if graph_config.graph_database_provider == "kuzu":
logger.info(f"Graph database path: {graph_config.graph_file_path}")
else:
... | Review this code and list any quality issues. | [] | 0 |
python | PartDeltaEvent(
index=1, delta=ToolCallPartDelta(args_delta='n Fr', tool_call_id='srvtoolu_01FYcUbzEaqqQh1WBRj1QX3h')
),
PartDeltaEvent(
index=1, delta=ToolCallPartDelta(args_delta='anc', tool_call_id='srvtoolu_01FYcUbzEaqqQh1WBRj1QX3h')
),
... | Review this code and list any quality issues. | [] | 0 |
python | def leave_fstring(self) -> None:
state = self.stack.pop()
assert state == STATE_MIDDLE
def consume_lbrace(self) -> None:
current_state = self.stack[-1]
if current_state == STATE_MIDDLE:
self.stack[-1] = STATE_IN_BRACES
elif current_state == STATE_IN_COLON:
... | Review this code and list any quality issues. | [] | 0 |
python | # connect
sock.connect(socket_address)
# set the socket_timeout now that we're connected
sock.settimeout(self.socket_timeout)
return sock
except OSError as _:
err = _
if sock is not None:
so... | Review this code and list any quality issues. | [] | 0 |
python | tool_call_id=IsStr(),
timestamp=IsNow(tz=timezone.utc),
)
],
timestamp=IsNow(tz=timezone.utc),
run_id=IsStr(),
),
]
)
def test_output_validator_retries():
"""Test that ctx.retry and ctx.max_retries ... | Review this code and list any quality issues. | [
{
"issue": "We should test for output functions as well: https://ai.pydantic.dev/output/#output-functions",
"severity": "minor",
"line": 26
}
] | 1 |
python | _algo_datetime,
_algo_current_data):
"""
Fail if the leverage is greater than the allowed leverage.
"""
if _account.leverage > self.max_leverage:
self.fail()
class MinLeverage(AccountControl):
"""
AccountControl representing a limit on the minimum l... | Review this code and list any quality issues. | [
{
"issue": "You might want to look at using the decorators in `zipline.utils.input_validation` to implement these checks. I think `expect_types(min_leverage=(int, float), deadline=datetime)` and `expect_strictly_bounded(min_leverage=(0, None))` would capture the behavior we want here. If you do end up using th... | 1 |
python | qkv = c_attn(x)
q, k, v = rearrange(qkv, 'b s (n h d) -> n b s h d', n=3, h=H)
mask = [torch.ones(S - i, dtype=dtype, device="cuda") for i in range(B)]
mask = torch.nn.utils.rnn.pad_sequence(mask, batch_first=True)
y = attn(q, k, v, attn_mask=mask, attn_mask_type=AttnMaskType.paddedcausal)
assert... | Review this code and list any quality issues. | [] | 0 |
python | @pytest.mark.skipif(
sys.platform == "win32", reason="adbc_driver_sqlite not available on Windows"
)
def test_read_database_parameterised_adbc(
param: str, param_value: Any, tmp_sqlite_db: Path
) -> None:
# establish parameterised queries and validate usage
query = """
SELECT CAST(STRFTIME('%Y',... | Review this code and list any quality issues. | [] | 0 |
python | # calculate
grad_input = grad_output.matmul(weight)
grad_output = grad_output.contiguous()
# Convert the tensor shapes to 2D for execution compatibility
if len(grad_output.shape) > 2:
grad_output = grad_output.view(-1, grad_output.shape... | Review this code and list any quality issues. | [
{
"issue": "For safety, you'd better wait computation stream here.",
"severity": "minor",
"line": 26
}
] | 1 |
python | if action_type == "template":
action = {"wait_template": "{{ states.switch.test.state == 'off' }}"}
else:
action = {
"wait_for_trigger": {
"platform": "state",
"entity_id": "switch.test",
"to": "off",
}
}
action["tim... | 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 | print_swap = self.swap(builtins, 'print', mock_print)
with print_swap, self.assertRaisesRegex(SystemExit, '1'):
install_dependencies_json_packages.test_dependencies_syntax(
'files',
{
'files': ['MathJax-2.7.5.jar'],
'version': '... | Review this code and list any quality issues. | [
{
"issue": "Maybe you should remove this comment.",
"severity": "major",
"line": 26
}
] | 1 |
python | cache_dir: directory to use for caching rules, or will use the default detected cache directory if None
on_load_rule: callback to invoke before a rule is loaded, use for progress or cancellation
"""
if cache_dir is None:
cache_dir = capa.rules.cache.get_default_cache_directory()
# rule_paths ... | Review this code and list any quality issues. | [
{
"issue": "`1` to `n` instead of `0` to `n-1`",
"severity": "minor",
"line": 26
}
] | 1 |
python | rlevel = right.get_level_values(level)
assert_index_equal(
llevel,
rlevel,
exact=exact,
check_names=check_names,
check_exact=check_exact,
check_categorical=check_categorical,
... | Review this code and list any quality issues. | [
{
"issue": "if we raised TypeError it'll be because the dtypes dont match and arent comparable. in that case, comparing codes doesn't make much sense",
"severity": "minor",
"line": 26
}
] | 1 |
python | assert stats.requests_finished == 2
async def test_crawler_multiple_stops_in_parallel(httpbin: URL) -> None:
"""Test that no new requests are handled after crawler.stop() is called, but ongoing requests can still finish."""
start_urls = [
str(httpbin / '1'),
str(httpbin / '2'),
str(htt... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n crawler.stop(reason=f'Stop called on {context.request.url}')\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | """Returns a JudgeConfig for the Oumi v1 XML DeepSeek R1 judge.
This function creates and returns a JudgeConfig object for the Oumi V1 Judge, which
uses DeepSeek R1 as a judge, with inputs and outputs in XML format.
Returns:
JudgeConfig: A configuration object for the Oumi v1 XML DeepSeek R1 judge... | Review this code and list any quality issues. | [
{
"issue": "@ctseng777 you can use the TogetherInferenceEngine directly, using `InferenceEngineType. TOGETHER`. This way you don't have to manually set api_url and api_key_env_varname !\r\n\r\nSame with SambaNova & DeepSeek",
"severity": "minor",
"line": 26
}
] | 1 |
python | def test_create_api_tool_provider_success(
self, flask_req_ctx_with_containers, db_session_with_containers, mock_external_service_dependencies
):
"""
Test successful creation of API tool provider.
This test verifies:
- Proper provider creation with valid parameters
-... | 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. The controller also passes a string value from the request. This will cause a type mismatch when the service tries to validate the schema... | 1 |
python | if device_info['name'] == 'cuda':
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', '--no-cache-dir', '--use-pep517', 'deepspeed'])
numpy_version = Version(self.get_package_version('numpy'))
if ... | Review this code and list any quality issues. | [
{
"issue": "The error message states \"json.loads() could not decode device_info_str\" but this branch is reached when `device_info_str` is empty or None (the outer `if device_info_str:` check on line 434 fails). The message should be \"device_info_str is empty or None\" to accurately reflect the condition. JSO... | 1 |
python | )
from monai.utils import (
check_parent_dir,
deprecated_arg,
ensure_tuple,
get_equivalent_dtype,
min_version,
optional_import,
pprint_edges,
)
validate, _ = optional_import("jsonschema", name="validate")
ValidationError, _ = optional_import("jsonschema.exceptions", name="ValidationError")
... | Review this code and list any quality issues. | [
{
"issue": "Do we need to support sequence str here and use `load_config_files` in L89?",
"severity": "minor",
"line": 26
}
] | 1 |
python | }
},
{
'url': 'https://zenporn.com/video/15872038/glad-you-came/',
'md5': '296ccab437f5bac6099433768449d8e1',
'info_dict': {
'id': '15872038',
'extr_id': '111585',
'ext': 'mp4',
'title': 'Glad You Came',
... | Review this code and list any quality issues. | [
{
"issue": "This can fatal since `int_or_none` can return `None`, which we cant divide. Let's secure against that:\r\n```suggestion\r\n extr_id = int_or_none(extr_id)\r\n if extr_id is None:\r\n raise ExtractorError('Unable to generate the `gen_info_url`')\r\n dyn_a = extr_id // ... | 1 |
python | if caption:
raise ValueError(
'Caption specified in both content and options.'
' Please remove ambiguity.'
)
# Use caption option
caption = options["caption"]
# If the optional function name is provided, use it
... | Review this code and list any quality issues. | [
{
"issue": "Don't we need a .py extension here like in the else case?",
"severity": "minor",
"line": 26
}
] | 1 |
python | path,
content,
commands,
)
class GraphicsCard:
"""Create a card for displaying vector graphics.
"""
def __init__(
self,
box: str,
view_box: str,
stage: Optional[PackedRecords] = None,
scene: Optional[PackedData] = ... | Review this code and list any quality issues. | [] | 0 |
python | assert isinstance(result.output, str)
assert len(result.output) > 0
async def test_openrouter_file_annotation_validation(openrouter_api_key: str) -> None:
"""Test that file annotations from OpenRouter are correctly validated.
This unit test verifies that responses containing type="file" annotations
a... | Review this code and list any quality issues. | [
{
"issue": "Looking at the cassette, it doesn't actually include file annotations 😄 If we can't force the API to do that, we can just drop this test and only to the one below",
"severity": "minor",
"line": 26
}
] | 1 |
python | NewgroundsPlaylistIE,
NewgroundsUserIE,
)
from .newspicks import NewsPicksIE
from .newstube import NewstubeIE
from .newsy import NewsyIE
from .nextmedia import (
NextMediaIE,
NextMediaActionNewsIE,
AppleDailyIE,
NextTVIE,
)
from .nexx import (
NexxIE,
NexxEmbedIE,
)
from .nfb import NFBIE
fr... | Review this code and list any quality issues. | [] | 0 |
python | Demonstrates how to use vLLM's tokenizer infrastructure for models whose
tokenizers are not natively supported by HuggingFace (e.g. Mistral Tekken,
DeepSeek-V3.2, Grok-2 tiktoken).
This example uses a standard model to demonstrate the pattern. For models
that truly require vLLM's custom tokenizer (e.g. deepseek-ai/Dee... | Review this code and list any quality issues. | [
{
"issue": "should we make these examples use map()? instead of map_batches?",
"severity": "major",
"line": 26
}
] | 1 |
python | translation_placeholders={"media": media_path},
)
media_type = get_media_type(media_path)
media_description = kwargs.get("media_description")
try:
media_data = client.media_post(
media_file=media_path,
mime_type=media_type,
... | Review this code and list any quality issues. | [
{
"issue": "move that out of try, to only have code in there that can fail",
"severity": "critical",
"line": 26
}
] | 1 |
python | }, {
'url': 'https://cooking.nytimes.com/guides/20-how-to-frost-a-cake',
'md5': '64415805fe0b8640fce6b0b9def5989a',
'info_dict': {
'id': '20-how-to-frost-a-cake',
'title': 'How to Frost a Cake',
'description': 'md5:a31fe3b98a8ce7b98aae097730c269cd',
},... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n map(self._extract_video, media_ids), page_id, title, description)\r\n```",
"severity": "major",
"line": 26
}
] | 1 |
python | def bool_or_none(v, default=None):
return v if isinstance(v, bool) else default
def strip_or_none(v, default=None):
return v.strip() if isinstance(v, str) else default
def url_or_none(url):
if not url or not isinstance(url, str):
return None
url = url.strip()
return url if re.match(r'(?:... | Review this code and list any quality issues. | [
{
"issue": "OSError? how? can it be tested?",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'alt_title': 'bratya/season-3/bratq-2021-10-08',
'duration': 1603.0,
'release_date': '2021-10-08T20:15:50+00:00',
'thumbnail': 'https://nbg-img.fite.tv/img/548677_460x260.jpg',
'description': 'Сезон 3 Епизод 25'
},
},
{
... | Review this code and list any quality issues. | [
{
"issue": "use self._parse_json and self._search_regex",
"severity": "minor",
"line": 26
}
] | 1 |
python | return flatten(data)
class TeslemetryEnergySiteLiveCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Class to manage fetching energy site live status from the Teslemetry API."""
config_entry: TeslemetryConfigEntry
updated_once: bool
def __init__(
self,
hass: HomeAssistant,
... | Review this code and list any quality issues. | [] | 0 |
python | assert a.sqr_magnitude() == pytest.approx(1.0 + 4.0 + 9.0)
assert a.magnitude() == pytest.approx(np.sqrt(a.sqr_magnitude()))
na = a.normalized()
assert na.v.dtype == np.float32
assert na.magnitude() == pytest.approx(1.0, rel=1e-6, abs=1e-6)
assert np.allclose(Vec3.zero().normalized().v, [0.0, 0.0, 0... | Review this code and list any quality issues. | [
{
"issue": "This restriction is useless. I would not assert it. It would be better to do `self.v = np.asarray(v, dtype=np.float32)`",
"severity": "minor",
"line": 26
}
] | 1 |
python | DownloadCancelled,
DownloadError,
FormatSorter,
GeoUtils,
PlaylistEntries,
SameFileError,
decodeOption,
download_range_func,
expand_path,
float_or_none,
format_field,
int_or_none,
join_nonempty,
match_filter_func,
parse_bytes,
parse_duration,
preferredenco... | Review this code and list any quality issues. | [
{
"issue": "this needs to be moved up with the classes",
"severity": "minor",
"line": 26
}
] | 1 |
python | LICENSE = """/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
... | Review this code and list any quality issues. | [] | 0 |
python | attrs.update(extra_attributes)
return mark_safe(f"<img{flatatt(attrs)}>")
def __html__(self):
return self.img_tag()
def get_upload_to(self, filename):
"""
Generates a file path within the "images" folder by combining the folder name and the validated filename.
"""
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n # We only include fields to check if they are a UniqueConstraint, and\r\n # they have no condition on them.\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | Parameters
----------
mobject
The Mobject to be transformed. The Mobject will be mutated into the target.
target_mobject
The Mobject that will be transformed into. Will become invisible and replaced by mobject.
path_func
A function defining the path that the mobject will take to ... | Review this code and list any quality issues. | [
{
"issue": "Another minor correction regarding the actual behavior of the animation.\r\n\r\n```suggestion\r\n Controls which mobject is replaced when the transformation is complete.\r\n\r\n If set to True, ``mobject`` will be removed from the scene and ``target_mobject`` will\r\n replace it... | 1 |
python | self._playlist_urls = set()
self.cache = Cache(self)
stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout
self._out_files = Namespace(
out=stdout,
error=sys.stderr,
screen=sys.stderr if self.params.get('quiet') else stdout,
consol... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n stream_name = {sys.stdout: 'stdout', sys.stderr: 'stderr'}[stream]\r\n```\r\nAnything else means code is broken from our side.",
"severity": "critical",
"line": 26
}
] | 1 |
python | }
}, {
'url': 'https://www.harpodeon.com/preview/Behind_the_Screen/421838710',
'md5': '7979df9ca04637282cb7d172ab3a9c3b',
'info_dict': {
'id': '421838710',
'ext': 'mp4',
'title': 'Behind the Screen',
'description': 'A woman tries to break into ... | Review this code and list any quality issues. | [
{
"issue": "clean this up similar to above suggestions",
"severity": "minor",
"line": 26
}
] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.