id stringlengths 30 32 | content stringlengths 139 2.8k |
|---|---|
codereview_new_python_data_9371 | def stem(self):
def filename(self):
return pathlib.Path(self.root.filename).joinpath(self.at)
- def read_text(self, encoding=None, *args, **kwargs):
- encoding = io.text_encoding(encoding)
- with self.open('r', *args, encoding=encoding, **kwargs) as strm:
return strm.read(... |
codereview_new_python_data_9372 | class SystemRandom(Random):
"""
def random(self):
- """Return the next random floating point number in the range ``0.0 <= X < 1.0``"""
return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF
def getrandbits(self, k):
No backticks here. This is a docstring and doesn't use markup.
cl... |
codereview_new_python_data_9373 | def handle_alt_loop(self, node: Alt, is_gather: bool, rulename: Optional[str]) -
self.print(
"void **_new_children = PyMem_Realloc(_children, _children_capacity*sizeof(void *));"
)
- self.out_of_memory_return(f"!new_children", cleanup_code="PyMem_Fr... |
codereview_new_python_data_9374 | def _write_atomic(path, data, mode=0o666):
# Python 3.12a1 3513 (Add CALL_INTRINSIC_1 instruction, removed STOPITERATION_ERROR, PRINT_EXPR, IMPORT_STAR)
# Python 3.12a1 3514 (Remove ASYNC_GEN_WRAP, LIST_TO_TUPLE, and UNARY_POSITIVE)
# Python 3.12a1 3515 (Embed jump mask in COMPARE_OP oparg)
-
# Pyt... |
codereview_new_python_data_9375 | def _write_atomic(path, data, mode=0o666):
# Python 3.12a1 3513 (Add CALL_INTRINSIC_1 instruction, removed STOPITERATION_ERROR, PRINT_EXPR, IMPORT_STAR)
# Python 3.12a1 3514 (Remove ASYNC_GEN_WRAP, LIST_TO_TUPLE, and UNARY_POSITIVE)
# Python 3.12a1 3515 (Embed jump mask in COMPARE_OP oparg)
-# Pytho... |
codereview_new_python_data_9376 | def splitroot(p):
empty; the root may be empty, a single slash, or two slashes. The tail
contains anything after the root. For example:
- splitdrive('foo/bar') == ('', '', 'foo/bar')
- splitdrive('/foo/bar') == ('', '/', 'foo/bar')
"""
p = os.fspath(p)
if isinstance(p, bytes):
... |
codereview_new_python_data_9377 | def splitroot(p):
splitroot('//server/share/') == ('//server/share', '/', '')
splitroot('C:/Users/Barney') == ('C:', '/', 'Users/Barney')
- splitroot('Windows') == ('', '', 'Windows')
"""
p = os.fspath(p)
if isinstance(p, bytes):
Perhaps add an example that redundant slashes ... |
codereview_new_python_data_9378 | def commonpath(paths):
drivesplits = [splitroot(p.replace(altsep, sep).lower()) for p in paths]
split_paths = [p.split(sep) for d, r, p in drivesplits]
- if len(set(r for d, r, p in drivesplits)) != 1:
raise ValueError("Can't mix absolute and relative paths")
# Check ... |
codereview_new_python_data_9383 | def cache_effect(self) -> CacheEffect | None:
@contextual
def stack_effect(self) -> StackEffect | None:
- # IDENTIFIER [':' IDENTIFIER]
# TODO: Conditions
if tkn := self.expect(lx.IDENTIFIER):
if self.expect(lx.COLON):
Update this comment?
def cache_effect(self) -> ... |
codereview_new_python_data_9384 | def test_copy(self):
def test_deepcopy(self):
s = slice(1, 10)
c = copy.deepcopy(s)
- self.assertIsNot(s, c)
self.assertEqual(s, c)
s = slice(1, 10, 2)
c = copy.deepcopy(s)
- self.assertIsNot(s, c)
self.assertEqual(s, c)
# Corner cas... |
codereview_new_python_data_9385 | def _next_external_frame(frame, skip_file_prefixes):
# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1, source=None,
- *,
- skip_file_prefixes: tuple[str, ...] = ()):
"""Issue a warning, or maybe ignore it or raise an exception."""
# Check if message is ... |
codereview_new_python_data_9386 | def _next_external_frame(frame, skip_file_prefixes):
# Code typically replaced by _warnings
def warn(message, category=None, stacklevel=1, source=None,
- *,
- skip_file_prefixes: tuple[str, ...] = ()):
"""Issue a warning, or maybe ignore it or raise an exception."""
# Check if message is ... |
codereview_new_python_data_9387 | def absolute(self):
if self.is_absolute():
return self
elif self._drv and _getfullpathname:
- try:
- cwd = _getfullpathname(self._drv)
- except (ValueError, OSError):
- cwd = os.getcwd()
else:
cwd = os.getcwd()
... |
codereview_new_python_data_9388 | def absolute(self):
if self.is_absolute():
return self
elif self._drv and _getfullpathname:
- try:
- cwd = _getfullpathname(self._drv)
- except (ValueError, OSError):
- cwd = os.getcwd()
else:
cwd = os.getcwd()
... |
codereview_new_python_data_9389 | def test_absolute(self):
with os_helper.subst_drive(BASE) as other_drive:
other_cwd = f'{other_drive}\\dirA'
- with os_helper.change_cwd(other_cwd):
- pass
# Relative path on another drive
self.assertEqual(str(P(other_drive).absolute()), oth... |
codereview_new_python_data_9392 | def test_field_recursive_repr(self):
rec_field.type = rec_field
rec_field.name = "id"
repr_output = repr(rec_field)
- expected_output = "Field(name='id',type=...," \
- f"default={MISSING!r},default_factory={MISSING!r}," \
- "init=Tru... |
codereview_new_python_data_9393 | def from_subprocess():
['uname', '-p'],
stderr=subprocess.DEVNULL,
text=True,
- encoding="locale",
).strip()
except (OSError, subprocess.CalledProcessError):
pass
I think `uname` output is not localized.
https://gith... |
codereview_new_python_data_9394 | def from_subprocess():
['uname', '-p'],
stderr=subprocess.DEVNULL,
text=True,
- encoding="locale",
).strip()
except (OSError, subprocess.CalledProcessError):
pass
```suggestion
encoding="utf8",
```
... |
codereview_new_python_data_9396 | def Manager(self):
from .managers import SyncManager
ctx = self.get_context()
m = SyncManager(ctx=ctx)
- proc_class = ctx.Process
m.start()
return m
proc_class isn't used?
def Manager(self):
from .managers import SyncManager
ctx = self.get_cont... |
codereview_new_python_data_9399 | def get_event_loop(self):
except AttributeError:
pass
else:
while f:
module = f.f_globals.get('__name__')
if not (module == 'asyncio' or module.startswith('asyncio.')):
Can you add a comment explaining why this loop ... |
codereview_new_python_data_9400 | def getfqdn(name=''):
hostname from gethostname() is returned.
"""
name = name.strip()
- if not name or name == '0.0.0.0' or name == '::':
name = gethostname()
try:
hostname, aliases, ipaddrs = gethostbyaddr(name)
```suggestion
if not name or name in ('0.0.0.0', '::'):
`... |
codereview_new_python_data_9401 | def test_splitdrive(self):
# gh-96290: support partial/invalid UNC drives
tester('ntpath.splitdrive("//")', ("//", "")) # empty server & missing share
tester('ntpath.splitdrive("///")', ("//", "/")) # empty server & empty share
- tester('ntpath.splitdrive("///y")', ("///y", "")) # ... |
codereview_new_python_data_9402 | def test_normpath(self):
tester("ntpath.normpath('//server/share/../..')", '\\\\server\\share\\')
tester("ntpath.normpath('//server/share/../../')", '\\\\server\\share\\')
- # gh-96290: don't normalize partial/invalid UNC drives
tester("ntpath.normpath('\\\\foo\\bar')", '\\\\foo\\b... |
codereview_new_python_data_9403 | def current_task(loop=None):
loop = events.get_running_loop()
try:
return _current_tasks[loop]
- except:
return None
It _shouldn't_ matter, but I think preferably we would not blanket silence all exceptions here.
```suggestion
except KeyError:
```
def current_task(loo... |
codereview_new_python_data_9405 | def test_default(self):
self.dumps(repr(type)))
def test_ordereddict(self):
- od = collections.OrderedDict(a=1, b=2)
- od.move_to_end('a')
self.assertEqual(
self.dumps(od),
- '{"b": 2, "a": 1}')
self.assertEqual(
self.dumps(od, so... |
codereview_new_python_data_9406 | def test_create_server_trsock(self):
server = self.loop.run_until_complete(f)
self.assertEqual(len(server.sockets), 1)
sock = server.sockets[0]
host, port = sock.getsockname()
self.assertEqual(host, '0.0.0.0')
dup = sock.dup()
I would add a comment here that `sock... |
codereview_new_python_data_9407 | def dummy():
frame = _testcapi.frame_new(dummy.__code__, globals(), locals())
# The following line should not cause a segmentation fault.
- self.assertEqual(frame.f_back, None)
if __name__ == "__main__":
unittest.main()
```suggestion
self.assertIsNone(frame.f_back)
```
d... |
codereview_new_python_data_9408 | async def get_command_stdout(cmd, *args):
async def main():
outputs = [f'foo{i}' for i in range(10)]
res = await asyncio.gather(*[get_command_stdout(sys.executable, '-c',
- f'import sys; print({out!r})') for out in outputs])
self.as... |
codereview_new_python_data_9419 | def get_ci_stage(event_name):
elif event_name == PUSH_EVENT_NAME:
return "postsubmit"
elif event_name == SCHEDULE_EVENT_NAME:
- return "schedule"
elif event_name == WORKFLOW_DISPATCH_EVENT_NAME:
return "unknown"
raise ValueError(f"Unrecognized event name '{event_name}'")
Schedule should proba... |
codereview_new_python_data_9426 | def build_run_flags_for_execution_config(
gpu_id: str = "0") -> List[str]:
"""Returns the IREE run module flags of the execution config."""
- run_flags = list(module_execution_config.extra_flags)
- run_flags.append("--device_allocator=caching")
driver = module_execution_config.driver
if driver == Run... |
codereview_new_python_data_9427 | def generate_rules() -> List[str]:
# TODO(#11136): Currently the DRIVER is a separate field in the CMake rule (
# and has effect on test labels). Generates the flags without the driver.
runner_args += run_module_utils.build_run_flags_for_execution_config(
- test_config.execution_config, without_d... |
codereview_new_python_data_9440 | def get_test_shapes(shapes_id: ShapesId):
# (see get_test_generators).
]
if shapes_id == ShapesId.GPU_LARGE:
- return [TestShape(m=512, k=128, n=256)]
raise ValueError(shapes_id)
why do we need this change?
def get_test_shapes(shapes_id: ShapesId):
# (see get_test_generators).
... |
codereview_new_python_data_9442 | def test_get_previous_comment_on_pr(self):
},
"body": "comment id: 1234"
}]
-
- def _handle_get(endpoint: str, payload: Any):
- if payload["page"] == 1:
- return first_mock_response
- if payload["page"] == 2:
- return second_mock_response
- raise ValueError("Unexp... |
codereview_new_python_data_9443 | def real_path_or_none(
capture_tmp_dir=per_commit_tmp_dir / CAPTURES_REL_PATH)
if args.e2e_test_artifacts_dir is not None:
- if args.run_config is None:
- raise ValueError(
- "--e2e_test_artifacts_dir only supports using with --run_config.")
-
root_benchmark_dir = args.e... |
codereview_new_python_data_9444 | def real_path_or_none(
capture_tmp_dir=per_commit_tmp_dir / CAPTURES_REL_PATH)
if args.e2e_test_artifacts_dir is not None:
- if args.run_config is None:
- raise ValueError(
- "--e2e_test_artifacts_dir only supports using with --run_config.")
-
root_benchmark_dir = args.e... |
codereview_new_python_data_9445 | def real_path_or_none(
capture_tmp_dir=per_commit_tmp_dir / CAPTURES_REL_PATH)
if args.e2e_test_artifacts_dir is not None:
- if args.run_config is None:
- raise ValueError(
- "--e2e_test_artifacts_dir only supports using with --run_config.")
-
root_benchmark_dir = args.e... |
codereview_new_python_data_9446 | def main(args: argparse.Namespace):
)
host_environment = host_environments.pop()
- module_dir_paths = sort_and_dedup_paths([
- iree_artifacts.get_module_dir_path(config.module_generation_config)
for config in run_configs
- ])
output_map[device_name] = {
"host_environ... |
codereview_new_python_data_9447 | def main(args: argparse.Namespace):
)
host_environment = host_environments.pop()
- module_dir_paths = sort_and_dedup_paths([
- iree_artifacts.get_module_dir_path(config.module_generation_config)
for config in run_configs
- ])
output_map[device_name] = {
"host_environ... |
codereview_new_python_data_9448 | def main(args: argparse.Namespace):
)
host_environment = host_environments.pop()
- module_dir_paths = sort_and_dedup_paths([
- iree_artifacts.get_module_dir_path(config.module_generation_config)
for config in run_configs
- ])
output_map[device_name] = {
"host_environ... |
codereview_new_python_data_9450 | def get_table_title() -> str:
class TotalArtifactSizeToTable(MetricsToTableMapper[CompilationMetrics]):
- """Helper to map CompilationMetrics to total dispatch size column."""
def update_base_value(self, compile_metrics: CompilationMetrics,
base_value: Any) -> CompilationMetrics:
n... |
codereview_new_python_data_9465 | def get_ci_stage(event_name):
def get_benchmark_presets(trailers: Mapping[str, str]) -> str:
trailer = trailers.get(BENCHMARK_PRESET_KEY)
if trailer is None:
return ""
I think it's worth a comment why the output here is a string
def get_ci_stage(event_name):
def get_benchmark_presets(trailers: ... |
codereview_new_python_data_9469 | def adb_start_cmd(cmd_args: Sequence[str],
def get_vmfb_full_path_for_benchmark_case(
benchmark_case_dir: pathlib.Path) -> pathlib.Path:
flagfile_path = benchmark_case_dir / MODEL_FLAGFILE_NAME
- with flagfile_path.open("r") as flagfile:
- flagfile_lines = flagfile.readlines()
- for line in flagfile_line... |
codereview_new_python_data_9470 | def adb_start_cmd(cmd_args: Sequence[str],
def get_vmfb_full_path_for_benchmark_case(
benchmark_case_dir: pathlib.Path) -> pathlib.Path:
flagfile_path = benchmark_case_dir / MODEL_FLAGFILE_NAME
- with flagfile_path.open("r") as flagfile:
- flagfile_lines = flagfile.readlines()
- for line in flagfile_line... |
codereview_new_python_data_9471 | def __create_bench(dir_path: pathlib.Path, model_name: str,
if len(model_tags) > 0:
model_name_with_tags += f"-{','.join(model_tags)}"
bench_path = dir_path / model_name_with_tags / case_name
- os.makedirs(bench_path)
(bench_path / "tool").write_text(tool)
return BenchmarkCase(model_nam... |
codereview_new_python_data_9479 | def main(args: argparse.Namespace):
artifacts_root = (
e2e_test_artifacts.artifacts.generate_default_artifacts_root())
- root_path = pathlib.PurePath(f"${{{ROOT_ARTIFACTS_DIR_CMAKE_VARIABLE}}}")
package_name = f"${{{PACKAGE_NAME_CMAKE_VARIABLE}}}"
model_rule_map = model_rule_generator.generate_model... |
codereview_new_python_data_9480 | class BenchmarkCase:
def _find_driver_info_by_execution_config(
module_execution_config: iree_definitions.ModuleExecutionConfig
) -> Optional[DriverInfo]:
- """Finds the matched driver info by the module exeuction config.
Args:
module_execution_config: module execution config to match.
Nit: typo
... |
codereview_new_python_data_9481 |
CUDA_CONFIG = iree_definitions.ModuleExecutionConfig(
id=unique_ids.IREE_MODULE_EXECUTION_CONFIG_CUDA,
tags=["full-inference", "default-flags"],
- loader=iree_definitions.RuntimeLoader.CUDA,
driver=iree_definitions.RuntimeDriver.CUDA)
VULKAN_CONFIG = iree_definitions.ModuleExecutionConfig(
i... |
codereview_new_python_data_9483 | def main():
mlir = torch_mlir.compile(graph,
train_args,
- output_type=torch_mlir.OutputType.LINALG_ON_TENSORS,
- use_tracing=False)
vmfb = iree_torch.compile_to_vmfb(mlir, args.iree_backend)
with open(args.output_file, "wb... |
codereview_new_python_data_9484 | def main():
mlir = torch_mlir.compile(graph,
train_args,
- output_type=torch_mlir.OutputType.LINALG_ON_TENSORS,
- use_tracing=False)
vmfb = iree_torch.compile_to_vmfb(mlir, args.iree_backend)
with open(args.output_file, "wb... |
codereview_new_python_data_9487 | def __build_tool_cmds(self, benchmark_case: BenchmarkCase,
cmds: List[Any] = run_module_utils.build_linux_wrapper_cmds_for_device_spec(
run_config.target_device_spec)
- cmds += [tool_path]
module_path = iree_artifacts.get_module_path(
run_config.module_generation_config,
append?
... |
codereview_new_python_data_9488 | def build_model_import_rule(
model = imported_model.model
if model.source_type == common_definitions.ModelSourceType.EXPORTED_LINALG_MLIR:
- if pathlib.Path(source_model_rule.file_path) != output_file_path:
raise ValueError("Separate path for Linalg model isn't supported ('" +
... |
codereview_new_python_data_9492 | def generate_rules(
artifacts_root=artifacts_root.iree_artifacts_root,
model_rule_map=model_rule_map)
- # Currently the rules are simple so the common rules can be always put at the
# top. Need a topological sort once the dependency gets complicated.
return model_cmake_rules + iree_cmake_rules
... |
codereview_new_python_data_9496 |
-## copyright 2022 the iree authors
#
-# licensed under the apache license v2.0 with llvm exceptions.
-# see https://llvm.org/license.txt for license information.
-# spdx-license-identifier: apache-2.0 with llvm-exception
"""Defines the collections of device specs and provides query methods."""
from typing import... |
codereview_new_python_data_9502 | def generate(
default_run_configs = cls._generate_default_run_configs()
- # Generate compile specs for mobile models.
- mobile_model_compile_specs = [
iree_definitions.CompileSpec(
compile_config=cls.CASCADELAKE_COMPILE_CONFIG, model=model)
- for model in model_groups.MOBILE... |
codereview_new_python_data_9509 | def setUp(self):
return
self.workdir = _setup_artifacts_dir("download")
print(f"TMPDIR = {self.workdir}")
- self.tflite_file = '/'.join([self.workdir, 'model.bc'])
- self.tflite_ir = '/'.join([self.workdir, 'tflite.bc'])
- self.iree_ir = '/'.join([self.workdir, 'tosa.bc'])
if os.path.exi... |
codereview_new_python_data_9511 | def main(args):
print(f"Updating {mig.name} to new versions:"
f" {summarize_versions(new_versions)}")
if not args.dry_run:
- migs_client.patch(
- project=args.project,
- region=region,
- instance_group_manager=mig.name,
- instance_group_manager_resource=c... |
codereview_new_python_data_9585 | def get_addons_stats(hass):
@callback
@bind_hass
def get_core_stats(hass):
- """Return Addons stats.
Async friendly.
"""
```suggestion
"""Return core stats.
```
def get_addons_stats(hass):
@callback
@bind_hass
def get_core_stats(hass):
+ """Return core stats.
Async friendly.
... |
codereview_new_python_data_9586 | async def test_restore_state(mock_heat_meter, hass: HomeAssistant) -> None:
assert state.attributes.get(ATTR_STATE_CLASS) is None
-@patch(API_HEAT_METER_SERVICE)
-async def test_exception_during_setup(mock_heat_meter, hass: HomeAssistant) -> None:
- """Test sensor."""
- entry_data = {
- "device":... |
codereview_new_python_data_9587 | async def _async_shutdown(self, event: Event) -> None:
*(
asyncio.create_task(
entry.async_shutdown(),
- name=f"shutdown config entry {entry.title} {entry.domain} {entry.entry_id}",
)
for entry in self._entries.valu... |
codereview_new_python_data_9588 | def native_value(self) -> float | int | str | None:
"""Return current state."""
descr = self.entity_description
state: float | int | str | None = self.coordinator.data.get(descr.key)
- if state is not None and descr.factor and isinstance(state, float | int):
return state ... |
codereview_new_python_data_9589 | def _rgbx_received(
if self._topic[CONF_BRIGHTNESS_STATE_TOPIC] is None:
rgb = convert_color(*color)
brightness = max(rgb)
- self._attr_brightness = min(round(brightness), 255)
# Normalize the color to 100% brightness
color... |
codereview_new_python_data_9590 | class ReolinkNumberEntityDescription(
value=lambda api, ch: api.get_focus(ch),
method=lambda api, ch, value: api.set_zoom(ch, int(value)),
),
- # "Floodlight turn on brightness" controlles the brightness of the floodlight when
# it is turned on internally by the camera (see "select.flood... |
codereview_new_python_data_9591 | async def async_attach_trigger(
armed_entities = set()
period: dict = {}
attribute = config.get(CONF_ATTRIBUTE)
- job = HassJob(action, f"numeric_state trigger {trigger_info}")
trigger_data = trigger_info["trigger_data"]
_variables = trigger_info["variables"] or {}
```suggestion
job... |
codereview_new_python_data_9592 | def reolink_connect_fixture(mock_get_source_ip):
"homeassistant.components.reolink.host.Host", autospec=True
) as host_mock_class:
host_mock = host_mock_class.return_value
- host_mock.get_host_data = AsyncMock(return_value=None)
- host_mock.get_states = AsyncMock(return_value=None)... |
codereview_new_python_data_9593 | def process_write_state_requests(self, msg: MQTTMessage) -> None:
entity.async_write_ha_state()
except Exception: # pylint: disable=broad-except
_LOGGER.error(
- "Exception on handling write state request to %s for msg on "
"'%s' w... |
codereview_new_python_data_9594 | def __init__(
manufacturer = device["manufacturer"]
device_type = device["type"]
- room_id: str = device.get("location")
room_name: str | None = None
if room_id is not None:
room_name = coordinator.rooms.get(room_id)
```suggestion
room_id: str | None ... |
codereview_new_python_data_9595 | def __init__(
config_entry: ConfigEntry,
coordinator: LivisiDataUpdateCoordinator,
device: dict[str, Any],
- use_room_as_device_name=False,
) -> None:
"""Initialize the common properties of a Livisi device."""
self.config_details: Mapping[str, Any] = device["con... |
codereview_new_python_data_9596 |
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
-from .const import (
- DOMAIN,
- LIVISI_STATE_CHANGE,
- LOGGER,
- PSS_DEVICE_TYPE,
-)
from .coordinator import LivisiDataUpdateCoordinator
from .entity import L... |
codereview_new_python_data_9597 | def _update_state(msg: ReceiveMessage) -> None:
return
try:
if (payload_datetime := dt_util.parse_datetime(new_value)) is None:
- _LOGGER.warning(
- "Invalid state message '%s' from '%s'", msg.payload, msg.topic
- ... |
codereview_new_python_data_9598 | async def test_reauth(
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_PASSWORD: "password"}
)
- assert result["type"] == data_entry_flow.FlowResultType.ABORT
- assert result["reason"] == "reauth_successful"
- assert len(hass.config_entries.async... |
codereview_new_python_data_9599 | async def test_reauth(
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
- assert len(hass.config_entries.async_entries()) == 1
```suggestion
assert len(hass.config_entries.async_entries()) == 1
```
async def test_reauth(
ass... |
codereview_new_python_data_9600 | def _context_id_to_bytes(context_id: str | None) -> bytes | None:
"""Convert a context_id to bytes."""
if context_id is None:
return None
- if len(context_id) == 32:
return UUID(context_id).bytes
if len(context_id) == 26:
return ulid_to_bytes(context_id)
This needs a test ... |
codereview_new_python_data_9601 | def _context_id_to_bytes(context_id: str | None) -> bytes | None:
"""Convert a context_id to bytes."""
if context_id is None:
return None
- if len(context_id) == 32:
return UUID(context_id).bytes
if len(context_id) == 26:
return ulid_to_bytes(context_id)
```suggestion
... |
codereview_new_python_data_9602 | def _context_id_to_bytes(context_id: str | None) -> bytes | None:
"""Convert a context_id to bytes."""
if context_id is None:
return None
- if len(context_id) == 36:
return UUID(context_id).bytes
if len(context_id) == 26:
return ulid_to_bytes(context_id)
```suggestion
... |
codereview_new_python_data_9603 | async def test_camera_fail(hass, init_integration, mock_install, caplog):
return_value=b"ABC", side_effect=ProsegurException()
)
- with caplog.at_level(logging.ERROR, logger="homeassistant.components.prosegur"):
- with pytest.raises(HomeAssistantError) as exc:
- await camera.async_... |
codereview_new_python_data_9604 |
async def async_validate_creds(hass: HomeAssistant, user_input: dict[str, Any]) -> bool:
"""Manage Obihai options."""
- if await hass.async_add_executor_job(
validate_auth,
user_input[CONF_HOST],
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
- ):
- retur... |
codereview_new_python_data_9605 | def __init__(self, pyobihai, serial):
entity_category=EntityCategory.CONFIG,
)
- def press(
- self,
- **kwargs: Any,
- ) -> None:
"""Press button."""
try:
There are no arguments to a button press.
```suggestion
def press(self) -> None:
```
def _... |
codereview_new_python_data_9606 | def __init__(self, pyobihai, serial):
entity_category=EntityCategory.CONFIG,
)
- def press(
- self,
- **kwargs: Any,
- ) -> None:
"""Press button."""
try:
This is a constant. It should be defined outside the `__init__` method.
I suggest that you create ... |
codereview_new_python_data_9607 | async def async_set_temperature(self, **kwargs: Any) -> None:
OverkizCommandParam.FURTHER_NOTICE,
)
- async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
return
A second thing that I don't really like here is that we have a compul... |
codereview_new_python_data_9608 | def async_setup_light_services(hass: HomeAssistant) -> None:
)
-@callback
-def async_setup_lock_services(hass: HomeAssistant) -> None:
- """Create lock-specific services for the ISY Integration."""
- platform = entity_platform.async_get_current_platform()
-
- platform.async_register_entity_service(
-... |
codereview_new_python_data_9609 | async def async_stop(self, exit_code: int = 0, *, force: bool = False) -> None:
def _async_log_running_tasks(self, stage: int) -> None:
"""Log all running tasks."""
for task in self._tasks:
- if not task.done():
- _LOGGER.warning("Shutdown stage %s: still running: %s", ... |
codereview_new_python_data_9610 | def _apply_update( # noqa: C901
# Add name column to StatisticsMeta
_add_columns(session_maker, "statistics_meta", ["name VARCHAR(255)"])
elif new_version == 24:
- # This used to create the unique indices for start and metadata_id
# but we changed the format in schema 34 which w... |
codereview_new_python_data_9611 | def __init__(
self.entity_description = entity_description
self._attr_unique_id = (
- f"{self._host.unique_id}_{self._channel}_{entity_description.key}"
)
async def async_press(self) -> None:
```suggestion
f"{self._host.unique_id}_{channel}_{entity_descripti... |
codereview_new_python_data_9612 | async def async_turn_off(self) -> None:
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set the HVAC Mode and State."""
if hvac_mode == HVACMode.OFF:
- await self.async_turn_on()
- else:
await self.async_turn_off()
async def async_set_te... |
codereview_new_python_data_9613 | def mock_hass_config(
with `hass_config` as parameterized.
"""
if hass_config:
- hass.config_entries = ConfigEntries(
- hass,
- hass_config,
- )
with patch("homeassistant.config.load_yaml_config_file", return_value=hass_config):
yield
Small style sugg... |
codereview_new_python_data_9614 | async def setup_again(*_: Any) -> None:
await self._async_process_on_unload()
return
- except BaseException: # pylint: disable=broad-except
_LOGGER.exception(
"Error setting up entry %s for %s", self.title, integration.domain
)
Should we i... |
codereview_new_python_data_9615 | async def async_attach_trigger(
) -> CALLBACK_TYPE:
"""Listen for events based on configuration."""
trigger_data = trigger_info["trigger_data"]
- number = cast(int, config.get(CONF_NUMBER))
held_more_than = config.get(CONF_HELD_MORE_THAN)
held_less_than = config.get(CONF_HELD_LESS_THAN)
pr... |
codereview_new_python_data_9616 |
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
-from homeassistant.helpers.typing import ConfigType
-from .const import CONF_OBIHAI_HOST, PLATFORMS
-
-__all__ = [
- "CONF_OBIHAI_HOST",
-]
-
-
-def setup(hass: HomeAssistant, config: ConfigType) -> bool:
- "... |
codereview_new_python_data_9617 |
from . import USER_INPUT
-async def test_user_form(hass: HomeAssistant) -> None:
"""Test we get the user initiated form."""
result = await hass.config_entries.flow.async_init(
```suggestion
async def test_user_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
```
from . import USER... |
codereview_new_python_data_9618 |
DATA_SCHEMA = vol.Schema(
{
- vol.Required(CONF_HOST, default=""): str,
vol.Optional(
CONF_USERNAME,
default=DEFAULT_USERNAME,
You don't need empty default
```suggestion
vol.Required(CONF_HOST): str,
```
DATA_SCHEMA = vol.Schema(
{
+ vol.R... |
codereview_new_python_data_9619 | def update(self) -> None:
if self._service_name in call_direction:
self._state = call_direction.get(self._service_name)
-
- self._state = None
I think this line shouldn't be here. Leftover?
def update(self) -> None:
if self._service_name in call_direction:
self... |
codereview_new_python_data_9620 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up from a config entry."""
- await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
-
- return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
```suggestion
... |
codereview_new_python_data_9621 | async def async_setup_platform(
translation_key="manual_migration",
)
- if discovery_info:
- config = PLATFORM_SCHEMA(discovery_info)
-
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
I am a little confused by this line.
When does it get used?... |
codereview_new_python_data_9622 | def __init__(
def update(self) -> bool:
"""Validate connection and retrieve a list of sensors."""
- self.pyobihai = get_pyobihai(self.host, self.username, self.password)
- if not self.pyobihai.check_account():
- return False
self.serial = self.pyobihai.get_device_s... |
codereview_new_python_data_9623 | async def test_yaml_import(hass: HomeAssistant) -> None:
)
await hass.async_block_till_done()
- assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert "errors" not in result
```suggestion
assert result["type"] == FlowResultType.CREATE_ENTRY
```
async def test_y... |
codereview_new_python_data_9624 | def pytest_configure(config: pytest.Config) -> None:
"markers", "no_fail_on_log_exception: mark test to not fail on logged exception"
)
if config.getoption("verbose") > 0:
- logging.getLogger().level = logging.DEBUG
def pytest_runtest_setup() -> None:
```suggestion
logging.getL... |
codereview_new_python_data_9625 | async def async_matching_config_entries(
if not type_filter:
return [entry_json(entry) for entry in entries]
- # Fetch all the integrations so we can check their type
integrations = {}
domains = {entry.domain for entry in entries}
for domain_key, integration_or_exc in (
```suggestion... |
codereview_new_python_data_9626 | async def test_get_config_parameters(
@pytest.mark.parametrize(
- ("include_target"),
- [(True), (False)],
)
async def test_firmware_upload_view(
hass: HomeAssistant,
```suggestion
("firmware_data", "expected_data"),
[({"target": "1"}, {"firmware_target": 1}), ({}, {})],
```
async def t... |
codereview_new_python_data_9627 |
class DeviceAutomationTriggerProtocol(TriggerProtocol, Protocol):
"""Define the format of device_trigger modules.
- Each module must define either TRIGGER_SCHEMA or async_validate_trigger_config.
"""
async def async_get_trigger_capabilities(
Does this need double inheritance?
```suggestion
c... |
codereview_new_python_data_9628 |
class DeviceAutomationTriggerProtocol(TriggerProtocol, Protocol):
"""Define the format of device_trigger modules.
- Each module must define either TRIGGER_SCHEMA or async_validate_trigger_config.
"""
async def async_get_trigger_capabilities(
Should this docstring be adjusted?
class DeviceAut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.