language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
Textualize__rich
rich/rule.py
{ "start": 276, "end": 4586 }
class ____(JupyterMixin): """A console renderable to draw a horizontal rule (line). Args: title (Union[str, Text], optional): Text to render in the rule. Defaults to "". characters (str, optional): Character(s) used to draw the line. Defaults to "─". style (StyleType, optional): Style of Rule. Defaults to "rule.line". end (str, optional): Character at end of Rule. defaults to "\\\\n" align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". """ def __init__( self, title: Union[str, Text] = "", *, characters: str = "─", style: Union[str, Style] = "rule.line", end: str = "\n", align: AlignMethod = "center", ) -> None: if cell_len(characters) < 1: raise ValueError( "'characters' argument must have a cell width of at least 1" ) if align not in ("left", "center", "right"): raise ValueError( f'invalid value for align, expected "left", "center", "right" (not {align!r})' ) self.title = title self.characters = characters self.style = style self.end = end self.align = align def __repr__(self) -> str: return f"Rule({self.title!r}, {self.characters!r})" def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = options.max_width characters = ( "-" if (options.ascii_only and not self.characters.isascii()) else self.characters ) chars_len = cell_len(characters) if not self.title: yield self._rule_line(chars_len, width) return if isinstance(self.title, Text): title_text = self.title else: title_text = console.render_str(self.title, style="rule.text") title_text.plain = title_text.plain.replace("\n", " ") title_text.expand_tabs() required_space = 4 if self.align == "center" else 2 truncate_width = max(0, width - required_space) if not truncate_width: yield self._rule_line(chars_len, width) return rule_text = Text(end=self.end) if self.align == "center": title_text.truncate(truncate_width, overflow="ellipsis") side_width = (width - cell_len(title_text.plain)) // 2 left = Text(characters * (side_width // chars_len + 1)) left.truncate(side_width - 1) right_length = width - cell_len(left.plain) - cell_len(title_text.plain) right = Text(characters * (side_width // chars_len + 1)) right.truncate(right_length) rule_text.append(left.plain + " ", self.style) rule_text.append(title_text) rule_text.append(" " + right.plain, self.style) elif self.align == "left": title_text.truncate(truncate_width, overflow="ellipsis") rule_text.append(title_text) rule_text.append(" ") rule_text.append(characters * (width - rule_text.cell_len), self.style) elif self.align == "right": title_text.truncate(truncate_width, overflow="ellipsis") rule_text.append(characters * (width - title_text.cell_len - 1), self.style) rule_text.append(" ") rule_text.append(title_text) rule_text.plain = set_cell_size(rule_text.plain, width) yield rule_text def _rule_line(self, chars_len: int, width: int) -> Text: rule_text = Text(self.characters * ((width // chars_len) + 1), self.style) rule_text.truncate(width) rule_text.plain = set_cell_size(rule_text.plain, width) return rule_text def __rich_measure__( self, console: Console, options: ConsoleOptions ) -> Measurement: return Measurement(1, 1) if __name__ == "__main__": # pragma: no cover import sys from rich.console import Console try: text = sys.argv[1] except IndexError: text = "Hello, World" console = Console() console.print(Rule(title=text)) console = Console() console.print(Rule("foo"), width=4)
Rule
python
realpython__materials
python-mixins/mixins.py
{ "start": 468, "end": 818 }
class ____: def __init__(self, key_type, *args, **kwargs): super().__init__(*args, **kwargs) self.__type = key_type def __setitem__(self, key, value): if not isinstance(key, self.__type): raise TypeError(f"key must be {self.__type} but was {type(key)}") super().__setitem__(key, value)
TypedKeyMixin
python
scipy__scipy
scipy/interpolate/tests/test_fitpack.py
{ "start": 6798, "end": 7923 }
class ____: def test_1d_shape(self): x = [1,2,3,4,5] y = [4,5,6,7,8] tck = splrep(x, y) z = splev([1], tck) assert z.shape == (1,) z = splev(1, tck) assert z.shape == () def test_2d_shape(self): x = [1, 2, 3, 4, 5] y = [4, 5, 6, 7, 8] tck = splrep(x, y) t = np.array([[1.0, 1.5, 2.0, 2.5], [3.0, 3.5, 4.0, 4.5]]) z = splev(t, tck) z0 = splev(t[0], tck) z1 = splev(t[1], tck) xp_assert_equal(z, np.vstack((z0, z1))) def test_extrapolation_modes(self): # test extrapolation modes # * if ext=0, return the extrapolated value. # * if ext=1, return 0 # * if ext=2, raise a ValueError # * if ext=3, return the boundary value. x = [1,2,3] y = [0,2,4] tck = splrep(x, y, k=1) rstl = [[-2, 6], [0, 0], None, [0, 4]] for ext in (0, 1, 3): assert_array_almost_equal(splev([0, 4], tck, ext=ext), rstl[ext]) assert_raises(ValueError, splev, [0, 4], tck, ext=2)
TestSplev
python
allegroai__clearml
clearml/backend_interface/task/access.py
{ "start": 146, "end": 4694 }
class ____(object): """A mixin providing task fields access functionality""" session = abstractproperty() data = abstractproperty() cache_dir = abstractproperty() log = abstractproperty() def _get_task_property( self, prop_path: str, raise_on_error: bool = True, log_on_error: bool = True, default: Any = None, ) -> Any: return self._get_data_property( prop_path=prop_path, raise_on_error=raise_on_error, log_on_error=log_on_error, default=default, data=self.data, log=self.log, ) @classmethod def _get_data_property( cls, prop_path: str, raise_on_error: bool = True, log_on_error: bool = True, default: Any = None, data: Any = None, log: Any = None, ) -> Any: obj = data props = prop_path.split(".") for i in range(len(props)): if not hasattr(obj, props[i]) and (not isinstance(obj, dict) or props[i] not in obj): msg = "Task has no %s section defined" % ".".join(props[: i + 1]) if log_on_error and log: log.info(msg) if raise_on_error: raise ValueError(msg) return default if isinstance(obj, dict): obj = obj.get(props[i]) else: obj = getattr(obj, props[i], None) return obj def _set_task_property( self, prop_path: str, value: Any, raise_on_error: bool = True, log_on_error: bool = True, ) -> None: props = prop_path.split(".") if len(props) > 1: obj = self._get_task_property( ".".join(props[:-1]), raise_on_error=raise_on_error, log_on_error=log_on_error, ) else: obj = self.data if not hasattr(obj, props[-1]) and isinstance(obj, dict): obj[props[-1]] = value else: setattr(obj, props[-1], value) def save_exec_model_design_file(self, filename: str = "model_design.txt", use_cache: bool = False) -> str: """Save execution model design to file""" p = Path(self.cache_dir) / filename if use_cache and p.is_file(): return str(p) desc = self._get_task_property("execution.model_desc") try: design = six.next(six.itervalues(desc)) except StopIteration: design = None if not design: raise ValueError("Task has no design in execution.model_desc") p.parent.mkdir(parents=True, exist_ok=True) p.write_text("%s" % design) return str(p) def get_parameters(self) -> Any: return self._get_task_property("execution.parameters") def get_label_num_description(self) -> Dict[int, str]: """Get a dictionary of label number to string pairs representing all labels associated with this number on the model labels. """ model_labels = self._get_task_property("execution.model_labels") label_getter = operator.itemgetter(0) num_getter = operator.itemgetter(1) groups = list(itertools.groupby(sorted(model_labels.items(), key=num_getter), key=num_getter)) if any(len(set(label_getter(x) for x in group)) > 1 for _, group in groups): raise ValueError("Multiple labels mapped to same model index not supported") return {key: ",".join(label_getter(x) for x in group) for key, group in groups} def get_output_destination(self, extra_path: Optional[str] = None, **kwargs: Any) -> str: """Get the task's output destination, with an optional suffix""" return self._get_task_property("output.destination", **kwargs) def get_num_of_classes(self) -> int: """number of classes based on the task's labels""" model_labels = self.data.execution.model_labels expected_num_of_classes = 0 for labels, index in model_labels.items(): expected_num_of_classes += 1 if int(index) > 0 else 0 num_of_classes = int(max(model_labels.values())) if num_of_classes != expected_num_of_classes: self.log.warning( "The highest label index is %d, while there are %d non-bg labels" % (num_of_classes, expected_num_of_classes) ) return num_of_classes + 1 # +1 is meant for bg!
AccessMixin
python
mlflow__mlflow
tests/tensorflow/test_tensorflow2_autolog.py
{ "start": 15247, "end": 17161 }
class ____: def __init__(self, data, target, batch_size): self.data = data self.target = target self.batch_size = batch_size self.ptr = 0 def __next__(self): if self.ptr >= len(self.data): raise StopIteration idx = self.ptr % len(self.data) self.ptr += 1 return self.data[idx : idx + self.batch_size], self.target[idx : idx + self.batch_size] def __iter__(self): return self @pytest.mark.parametrize( "generate_data", [ __example_tf_dataset, __ExampleSequence, functools.partial(__ExampleSequence, with_sample_weights=True), functools.partial(__generator, np.array([[1]] * 10), np.array([[1]] * 10)), pytest.param( functools.partial(__GeneratorClass, np.array([[1]] * 10), np.array([[1]] * 10)), marks=pytest.mark.skipif( Version(tf.__version__).release >= (2, 15) and "TF_USE_LEGACY_KERAS" not in os.environ, reason="does not support", ), ), ], ) @pytest.mark.parametrize("batch_size", [5, 10]) def test_tf_keras_autolog_implicit_batch_size_works(generate_data, batch_size): mlflow.autolog() model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_shape=(1,))) model.compile(loss="mse") # 'x' passed as arg model.fit(generate_data(batch_size), verbose=0) assert mlflow.last_active_run().data.params["batch_size"] == str(batch_size) # 'x' passed as kwarg model.fit(x=generate_data(batch_size), verbose=0) assert mlflow.last_active_run().data.params["batch_size"] == str(batch_size) def __tf_dataset_multi_input(batch_size): a = tf.data.Dataset.range(1) b = tf.data.Dataset.range(1) c = tf.data.Dataset.range(1) ds = tf.data.Dataset.zip(((a, b), c)) return ds.batch(batch_size)
__GeneratorClass
python
pypa__pip
tests/unit/test_req_file.py
{ "start": 6679, "end": 24006 }
class ____: """tests for `process_line`""" def test_parser_error(self, line_processor: LineProcessor) -> None: with pytest.raises(RequirementsFileParseError): line_processor("--bogus", "file", 1) def test_parser_offending_line(self, line_processor: LineProcessor) -> None: line = "pkg==1.0.0 --hash=somehash" with pytest.raises(RequirementsFileParseError) as err: line_processor(line, "file", 1) assert line in str(err.value) def test_parser_non_offending_line(self, line_processor: LineProcessor) -> None: try: line_processor("pkg==1.0.0 --hash=sha256:somehash", "file", 1) except RequirementsFileParseError: pytest.fail("Reported offending line where it should not.") def test_only_one_req_per_line(self, line_processor: LineProcessor) -> None: # pkg_resources raises the ValueError with pytest.raises(InstallationError): line_processor("req1 req2", "file", 1) def test_error_message(self, line_processor: LineProcessor) -> None: """ Test the error message if a parsing error occurs (all of path, line number, and hint). """ with pytest.raises(InstallationError) as exc: line_processor( "my-package=1.0", filename="path/requirements.txt", line_number=3 ) expected = ( "Invalid requirement: 'my-package=1.0': " "Expected end or semicolon (after name and no valid version specifier)\n" " my-package=1.0\n" " ^ (from line 3 of path/requirements.txt)\n" "Hint: = is not a valid operator. Did you mean == ?" ) assert str(exc.value) == expected def test_yield_line_requirement(self, line_processor: LineProcessor) -> None: line = "SomeProject" filename = "filename" comes_from = f"-r {filename} (line 1)" req = install_req_from_line(line, comes_from=comes_from) assert repr(line_processor(line, filename, 1)[0]) == repr(req) def test_yield_pep440_line_requirement(self, line_processor: LineProcessor) -> None: line = "SomeProject @ https://url/SomeProject-py2-py3-none-any.whl" filename = "filename" comes_from = f"-r {filename} (line 1)" req = install_req_from_line(line, comes_from=comes_from) assert repr(line_processor(line, filename, 1)[0]) == repr(req) def test_yield_line_constraint(self, line_processor: LineProcessor) -> None: line = "SomeProject" filename = "filename" comes_from = f"-c {filename} (line {1})" req = install_req_from_line(line, comes_from=comes_from, constraint=True) found_req = line_processor(line, filename, 1, constraint=True)[0] assert repr(found_req) == repr(req) assert found_req.constraint is True def test_yield_line_requirement_with_spaces_in_specifier( self, line_processor: LineProcessor ) -> None: line = "SomeProject >= 2" filename = "filename" comes_from = f"-r {filename} (line 1)" req = install_req_from_line(line, comes_from=comes_from) assert repr(line_processor(line, filename, 1)[0]) == repr(req) assert req.req is not None assert str(req.req.specifier) == ">=2" def test_yield_editable_requirement(self, line_processor: LineProcessor) -> None: url = "git+https://url#egg=SomeProject" line = f"-e {url}" filename = "filename" comes_from = f"-r {filename} (line 1)" req = install_req_from_editable(url, comes_from=comes_from) assert repr(line_processor(line, filename, 1)[0]) == repr(req) def test_yield_editable_constraint(self, line_processor: LineProcessor) -> None: url = "git+https://url#egg=SomeProject" line = f"-e {url}" filename = "filename" comes_from = f"-c {filename} (line {1})" req = install_req_from_editable(url, comes_from=comes_from, constraint=True) found_req = line_processor(line, filename, 1, constraint=True)[0] assert repr(found_req) == repr(req) assert found_req.constraint is True def test_nested_constraints_file( self, monkeypatch: pytest.MonkeyPatch, tmpdir: Path, session: PipSession ) -> None: req_name = "hello" req_file = tmpdir / "parent" / "req_file.txt" req_file.parent.mkdir() req_file.write_text("-c reqs.txt") req_file.parent.joinpath("reqs.txt").write_text(req_name) monkeypatch.chdir(str(tmpdir)) reqs = list(parse_reqfile("./parent/req_file.txt", session=session)) assert len(reqs) == 1 assert reqs[0].name == req_name assert reqs[0].constraint def test_repeated_requirement_files( self, tmp_path: Path, session: PipSession ) -> None: # Test that the same requirements file can be included multiple times # as long as there is no recursion. https://github.com/pypa/pip/issues/13046 tmp_path.joinpath("a.txt").write_text("requests") tmp_path.joinpath("b.txt").write_text("-r a.txt") tmp_path.joinpath("c.txt").write_text("-r a.txt\n-r b.txt") parsed = parse_requirements( filename=os.fspath(tmp_path.joinpath("c.txt")), session=session ) assert [r.requirement for r in parsed] == ["requests", "requests"] def test_recursive_requirements_file( self, tmpdir: Path, session: PipSession ) -> None: req_files: list[Path] = [] req_file_count = 4 for i in range(req_file_count): req_file = tmpdir / f"{i}.txt" req_file.write_text(f"-r {(i+1) % req_file_count}.txt") req_files.append(req_file) # When the passed requirements file recursively references itself with pytest.raises( RequirementsFileParseError, match=( f"{re.escape(str(req_files[0]))} recursively references itself" f" in {re.escape(str(req_files[req_file_count - 1]))}" ), ): list(parse_requirements(filename=str(req_files[0]), session=session)) # When one of other the requirements file recursively references itself req_files[req_file_count - 1].write_text( # Just name since they are in the same folder f"-r {req_files[req_file_count - 2].name}" ) with pytest.raises( RequirementsFileParseError, match=( f"{re.escape(str(req_files[req_file_count - 2]))} recursively" " references itself in" f" {re.escape(str(req_files[req_file_count - 1]))} and again in" f" {re.escape(str(req_files[req_file_count - 3]))}" ), ): list(parse_requirements(filename=str(req_files[0]), session=session)) def test_recursive_relative_requirements_file( self, tmpdir: Path, session: PipSession ) -> None: root_req_file = tmpdir / "root.txt" (tmpdir / "nest" / "nest").mkdir(parents=True) level_1_req_file = tmpdir / "nest" / "level_1.txt" level_2_req_file = tmpdir / "nest" / "nest" / "level_2.txt" root_req_file.write_text("-r nest/level_1.txt") level_1_req_file.write_text("-r nest/level_2.txt") level_2_req_file.write_text("-r ../../root.txt") with pytest.raises( RequirementsFileParseError, match=( f"{re.escape(str(root_req_file))} recursively references itself in" f" {re.escape(str(level_2_req_file))}" ), ): list(parse_requirements(filename=str(root_req_file), session=session)) def test_options_on_a_requirement_line(self, line_processor: LineProcessor) -> None: line = 'SomeProject --config-settings="yo3=yo4" --config-settings "yo1=yo2"' filename = "filename" req = line_processor(line, filename, 1)[0] assert req.config_settings == {"yo3": "yo4", "yo1": "yo2"} def test_hash_options(self, line_processor: LineProcessor) -> None: """Test the --hash option: mostly its value storage. Make sure it reads and preserve multiple hashes. """ line = ( "SomeProject --hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b1" "61e5c1fa7425e73043362938b9824 " "--hash=sha384:59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c" "3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f " "--hash=sha256:486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8" "e5a6c65260e9cb8a7" ) filename = "filename" req = line_processor(line, filename, 1)[0] assert req.hash_options == { "sha256": [ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", "486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7", ], "sha384": [ "59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcd" "b9c666fa90125a3c79f90397bdf5f6a13de828684f" ], } def test_set_isolated( self, line_processor: LineProcessor, options: mock.Mock ) -> None: line = "SomeProject" filename = "filename" options.isolated_mode = True result = line_processor(line, filename, 1, options=options) assert result[0].isolated def test_set_finder_no_index( self, line_processor: LineProcessor, finder: PackageFinder ) -> None: line_processor("--no-index", "file", 1, finder=finder) assert finder.index_urls == [] def test_set_finder_no_index_is_remembered_for_later_invocations( self, line_processor: LineProcessor, finder: PackageFinder ) -> None: line_processor("--no-index", "file", 1, finder=finder) line_processor("--index-url=url", "file", 1, finder=finder) assert finder.index_urls == [] def test_set_finder_index_url( self, line_processor: LineProcessor, finder: PackageFinder, session: PipSession ) -> None: line_processor("--index-url=url", "file", 1, finder=finder, session=session) assert finder.index_urls == ["url"] assert session.auth.index_urls == ["url"] def test_set_finder_find_links( self, line_processor: LineProcessor, finder: PackageFinder ) -> None: line_processor("--find-links=url", "file", 1, finder=finder) assert finder.find_links == ["url"] def test_set_finder_extra_index_urls( self, line_processor: LineProcessor, finder: PackageFinder, session: PipSession ) -> None: line_processor( "--extra-index-url=url", "file", 1, finder=finder, session=session ) assert finder.index_urls == ["url"] assert session.auth.index_urls == ["url"] def test_set_finder_trusted_host( self, line_processor: LineProcessor, caplog: pytest.LogCaptureFixture, session: PipSession, finder: PackageFinder, ) -> None: with caplog.at_level(logging.INFO): line_processor( "--trusted-host=host1 --trusted-host=host2:8080", "file.txt", 1, finder=finder, session=session, ) assert list(finder.trusted_hosts) == ["host1", "host2:8080"] session = finder._link_collector.session assert session.adapters["https://host1/"] is session._trusted_host_adapter assert session.adapters["https://host2:8080/"] is session._trusted_host_adapter # Test the log message. actual = [(r.levelname, r.message) for r in caplog.records] expected = ("INFO", "adding trusted host: 'host1' (from line 1 of file.txt)") assert expected in actual def test_set_finder_allow_all_prereleases( self, line_processor: LineProcessor, finder: PackageFinder ) -> None: line_processor("--pre", "file", 1, finder=finder) assert finder.allow_all_prereleases def test_use_feature( self, line_processor: LineProcessor, options: mock.Mock ) -> None: """--use-feature can be set in requirements files.""" line_processor("--use-feature=fast-deps", "filename", 1, options=options) def test_use_feature_with_error( self, line_processor: LineProcessor, options: mock.Mock ) -> None: """--use-feature triggers error when parsing requirements files.""" with pytest.raises(RequirementsFileParseError): line_processor("--use-feature=resolvelib", "filename", 1, options=options) def test_relative_local_find_links( self, line_processor: LineProcessor, finder: PackageFinder, monkeypatch: pytest.MonkeyPatch, tmpdir: Path, ) -> None: """ Test a relative find_links path is joined with the req file directory """ base_path = tmpdir / "path" def normalize(path: Path) -> str: return os.path.normcase(os.path.abspath(os.path.normpath(str(path)))) # Make sure the test also passes on windows req_file = normalize(base_path / "req_file.txt") nested_link = normalize(base_path / "rel_path") exists_ = os.path.exists def exists(path: str) -> bool: if path == nested_link: return True else: return exists_(path) monkeypatch.setattr(os.path, "exists", exists) line_processor("--find-links=rel_path", req_file, 1, finder=finder) assert finder.find_links == [nested_link] def test_relative_http_nested_req_files( self, finder: PackageFinder, session: PipSession, monkeypatch: pytest.MonkeyPatch, ) -> None: """ Test a relative nested req file path is joined with the req file url """ req_name = "hello" req_file = "http://me.com/me/req_file.txt" def get_file_content( filename: str, *args: Any, **kwargs: Any ) -> tuple[None, str]: if filename == req_file: return None, "-r reqs.txt" elif filename == "http://me.com/me/reqs.txt": return None, req_name pytest.fail(f"Unexpected file requested {filename}") monkeypatch.setattr( pip._internal.req.req_file, "get_file_content", get_file_content ) result = list(parse_reqfile(req_file, session=session)) assert len(result) == 1 assert result[0].name == req_name assert not result[0].constraint def test_relative_local_nested_req_files( self, session: PipSession, monkeypatch: pytest.MonkeyPatch, tmpdir: Path ) -> None: """ Test a relative nested req file path is joined with the req file dir """ req_name = "hello" req_file = tmpdir / "parent" / "req_file.txt" req_file.parent.mkdir() req_file.write_text("-r reqs.txt") req_file.parent.joinpath("reqs.txt").write_text(req_name) monkeypatch.chdir(str(tmpdir)) reqs = list(parse_reqfile("./parent/req_file.txt", session=session)) assert len(reqs) == 1 assert reqs[0].name == req_name assert not reqs[0].constraint def test_absolute_local_nested_req_files( self, session: PipSession, tmpdir: Path ) -> None: """ Test an absolute nested req file path """ req_name = "hello" req_file = tmpdir / "parent" / "req_file.txt" req_file.parent.mkdir() other_req_file = tmpdir / "other" / "reqs.txt" other_req_file.parent.mkdir() # POSIX-ify the path, since Windows backslashes aren't supported. other_req_file_str = str(other_req_file).replace("\\", "/") req_file.write_text(f"-r {other_req_file_str}") other_req_file.write_text(req_name) reqs = list(parse_reqfile(str(req_file), session=session)) assert len(reqs) == 1 assert reqs[0].name == req_name assert not reqs[0].constraint def test_absolute_http_nested_req_file_in_local( self, session: PipSession, monkeypatch: pytest.MonkeyPatch, tmpdir: Path ) -> None: """ Test a nested req file url in a local req file """ req_name = "hello" req_file = tmpdir / "req_file.txt" nested_req_file = "http://me.com/me/req_file.txt" def get_file_content( filename: str, *args: Any, **kwargs: Any ) -> tuple[None, str]: if filename == str(req_file): return None, f"-r {nested_req_file}" elif filename == nested_req_file: return None, req_name pytest.fail(f"Unexpected file requested {filename}") monkeypatch.setattr( pip._internal.req.req_file, "get_file_content", get_file_content ) result = list(parse_reqfile(req_file, session=session)) assert len(result) == 1 assert result[0].name == req_name assert not result[0].constraint
TestProcessLine
python
Textualize__textual
src/textual/widgets/_footer.py
{ "start": 662, "end": 3646 }
class ____(Widget): ALLOW_SELECT = False COMPONENT_CLASSES = { "footer-key--key", "footer-key--description", } DEFAULT_CSS = """ FooterKey { width: auto; height: 1; text-wrap: nowrap; background: $footer-item-background; .footer-key--key { color: $footer-key-foreground; background: $footer-key-background; text-style: bold; padding: 0 1; } .footer-key--description { padding: 0 1 0 0; color: $footer-description-foreground; background: $footer-description-background; } &:hover { color: $footer-key-foreground; background: $block-hover-background; } &.-disabled { text-style: dim; } &.-compact { .footer-key--key { padding: 0; } .footer-key--description { padding: 0 0 0 1; } } } """ compact = reactive(True) """Display compact style.""" def __init__( self, key: str, key_display: str, description: str, action: str, disabled: bool = False, tooltip: str = "", classes="", ) -> None: self.key = key self.key_display = key_display self.description = description self.action = action self._disabled = disabled if disabled: classes += " -disabled" super().__init__(classes=classes) self.shrink = False if tooltip: self.tooltip = tooltip def render(self) -> Text: key_style = self.get_component_rich_style("footer-key--key") description_style = self.get_component_rich_style("footer-key--description") key_display = self.key_display key_padding = self.get_component_styles("footer-key--key").padding description_padding = self.get_component_styles( "footer-key--description" ).padding description = self.description if description: label_text = Text.assemble( ( " " * key_padding.left + key_display + " " * key_padding.right, key_style, ), ( " " * description_padding.left + description + " " * description_padding.right, description_style, ), ) else: label_text = Text.assemble((key_display, key_style)) label_text.stylize_before(self.rich_style) return label_text def on_mouse_down(self) -> None: if self._disabled: self.app.bell() else: self.app.simulate_key(self.key) def _watch_compact(self, compact: bool) -> None: self.set_class(compact, "-compact")
FooterKey
python
numba__numba
numba/core/typing/builtins.py
{ "start": 31724, "end": 31989 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws if all(isinstance(it, types.IterableType) for it in args): zip_type = types.ZipType(args) return signature(zip_type, *args) @infer_global(iter)
Zip
python
django__django
tests/custom_lookups/tests.py
{ "start": 7271, "end": 7328 }
class ____(EndsWith): lookup_name = "ew"
CustomEndsWith
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_shape_base_.py
{ "start": 20940, "end": 21819 }
class ____(TestCase): # Only testing for integer splits. def test_non_iterable(self): assert_raises(ValueError, dsplit, 1, 1) def test_0D_array(self): a = np.array(1) assert_raises(ValueError, dsplit, a, 2) def test_1D_array(self): a = np.array([1, 2, 3, 4]) assert_raises(ValueError, dsplit, a, 2) def test_2D_array(self): a = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) try: dsplit(a, 2) assert_(0) except ValueError: pass def test_3D_array(self): a = np.array([[[1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4], [1, 2, 3, 4]]]) res = dsplit(a, 2) desired = [ np.array([[[1, 2], [1, 2]], [[1, 2], [1, 2]]]), np.array([[[3, 4], [3, 4]], [[3, 4], [3, 4]]]), ] compare_results(res, desired)
TestDsplit
python
Lightning-AI__lightning
tests/tests_pytorch/loops/test_fetchers.py
{ "start": 4053, "end": 9106 }
class ____(Dataset): def __len__(self): return 0 @pytest.mark.parametrize("dataset_cls", [EmptyIterDataset, EmptySizedDataset]) @pytest.mark.parametrize("prefetch_batches", [0, 1]) def test_empty_prefetch_iterator(dataset_cls, prefetch_batches): loader = CombinedLoader(DataLoader(dataset_cls())) fetcher = _PrefetchDataFetcher(prefetch_batches=prefetch_batches) fetcher.setup(loader) iter(fetcher) if dataset_cls is EmptySizedDataset: assert fetcher.done # for 0 length sized datasets we know we're done already else: # if we're prefetching, we can know in advance if the dataset is empty assert fetcher.done == (prefetch_batches > 0) assert not list(fetcher) assert fetcher.done def get_cycles_per_ms() -> float: """Get 10 values and remove the 2 max and 2 min and return the avg. This is to avoid system disturbance that skew the results, e.g. the very first cuda call likely does a bunch of init, which takes much longer than subsequent calls. """ def measure() -> float: """Measure and return approximate number of cycles per millisecond for `torch.cuda._sleep` Copied from: https://github.com/pytorch/pytorch/blob/v1.9.0/test/test_cuda.py#L81. """ start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() torch.cuda._sleep(1000000) end.record() end.synchronize() # cycles_per_ms return 1000000 / start.elapsed_time(end) num = 10 vals = [] for _ in range(num): vals.append(measure()) vals = sorted(vals) stats = vals[2 : num - 2] return sum(stats) / len(stats) BATCH_SIZE = 32 DATASET_LEN = 64 @pytest.mark.parametrize("automatic_optimization", [False, True]) def test_fetching_dataloader_iter_opt(automatic_optimization, tmp_path): class TestModel(BoringModel): def __init__(self, *args, automatic_optimization: bool = False, **kwargs): super().__init__(*args, **kwargs) self.automatic_optimization = automatic_optimization self.count = 0 self.batches = [] def training_step(self, dataloader_iter): assert isinstance(self.trainer.fit_loop._data_fetcher, _DataLoaderIterDataFetcher) # fetch 2 batches batch, batch_idx, _ = next(dataloader_iter) self.batches.append(batch) batch, batch_idx, _ = next(dataloader_iter) self.batches.append(batch) batch = self.batches.pop(0) assert isinstance(batch, Tensor) or batch is None self.count = batch_idx + 1 if self.automatic_optimization: loss = super().training_step(batch, 0) with pytest.raises(MisconfigurationException, match="dataloader_iter"): self.log("train_loss", loss["loss"]) self.log("train_loss", loss["loss"], batch_size=1) else: opt = self.optimizers() loss = self.step(batch) opt.zero_grad() loss.backward() opt.step() def on_train_epoch_end(self): # since the dataset is sized, the loop stops at the limit even though the training_step controls the # consumption of batches assert self.trainer.fit_loop.epoch_loop.batch_progress.current.ready == 32 assert self.trainer.fit_loop._data_fetcher.fetched == 64 assert self.count == 64 model = TestModel(automatic_optimization=automatic_optimization) trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, accelerator="cpu") trainer.fit(model) @pytest.mark.parametrize("fn", ["validate", "test", "predict"]) def test_fetching_dataloader_iter_running_stages(fn, tmp_path): class TestModel(BoringModel): def fetch(self, data_fetcher, dataloader_iter): assert isinstance(data_fetcher, _DataLoaderIterDataFetcher) batch, batch_idx, _ = next(dataloader_iter) assert data_fetcher.fetched == batch_idx + 1 return batch def validation_step(self, dataloader_iter): data_fetcher = self.trainer.validate_loop._data_fetcher batch = self.fetch(data_fetcher, dataloader_iter) return super().validation_step(batch, 0) def test_step(self, dataloader_iter): data_fetcher = self.trainer.test_loop._data_fetcher batch = self.fetch(data_fetcher, dataloader_iter) return super().test_step(batch, 0) def predict_step(self, dataloader_iter): data_fetcher = self.trainer.predict_loop._data_fetcher batch = self.fetch(data_fetcher, dataloader_iter) return super().test_step(batch, 0) model = TestModel() trainer = Trainer(default_root_dir=tmp_path, fast_dev_run=1, accelerator="cpu") trainer_fn = getattr(trainer, fn) trainer_fn(model)
EmptySizedDataset
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 168823, "end": 171306 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 3, 3]"): l_x_ = L_x_ _saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors_hooks_disable = None _grad_increment_nesting = torch._C._functorch._grad_increment_nesting(); _grad_increment_nesting = None diff_args: "f32[3, 3, 3]" = torch._C._functorch._wrap_for_grad(l_x_, 1); l_x_ = None set_inplace_requires_grad_allowed = torch._C._functorch.set_inplace_requires_grad_allowed(True); set_inplace_requires_grad_allowed = None _set_tensor_requires_grad: "f32[3, 3, 3]" = torch._functorch.eager_transforms._set_tensor_requires_grad(diff_args); _set_tensor_requires_grad = None set_inplace_requires_grad_allowed_1 = torch._C._functorch.set_inplace_requires_grad_allowed(False); set_inplace_requires_grad_allowed_1 = None sin: "f32[3, 3, 3]" = diff_args.sin() add: "f32[3, 3, 3]" = sin + 3; sin = None output: "f32[]" = add.sum(); add = None _autograd_grad = torch._functorch.eager_transforms._autograd_grad((output,), [diff_args], create_graph = True); diff_args = None grad_input: "f32[3, 3, 3]" = _autograd_grad[0]; _autograd_grad = None grad_input_1: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(grad_input, 1); grad_input = None output_1: "f32[]" = torch._C._functorch._unwrap_for_grad(output, 1); output = output_1 = None _grad_decrement_nesting = torch._C._functorch._grad_decrement_nesting(); _grad_decrement_nesting = None _saved_tensors_hooks_enable = torch._C._autograd._saved_tensors_hooks_enable(); _saved_tensors_hooks_enable = None return (grad_input_1,) """, ) def test_grad_capture_tensor(self): counters.clear() def wrapper_fn(x): y = torch.randn(3) def fn(x): return (x.sin() + y).sum() return torch.func.grad(fn)(x) x = torch.randn(3, 3, 3) wrapped_gm = self._compile_check(wrapper_fn, (x,)) # Dynamic shapes produce a slightly different graph. if check_dynamic_shape_capture(): return actual = normalize_gm(wrapped_gm.print_readable(print_output=False)) self.assertExpectedInline( actual, """\
GraphModule
python
tensorflow__tensorflow
tensorflow/python/module/module_test.py
{ "start": 14092, "end": 14244 }
class ____(ReturnsNameScopeModule): @property def name_scope(self): return ops.name_scope("yolo/", skip_on_eager=False)
ModuleOverridingNameScope
python
ansible__ansible
lib/ansible/_internal/_templating/_engine.py
{ "start": 2783, "end": 28375 }
class ____: """ The main class for templating, with the main entry-point of template(). """ _sentinel = object() def __init__( self, loader: DataLoader | None = None, variables: dict[str, t.Any] | ChainMap[str, t.Any] | None = None, variables_factory: t.Callable[[], dict[str, t.Any] | ChainMap[str, t.Any]] | None = None, marker_behavior: MarkerBehavior | None = None, ): self._loader = loader self._variables = variables self._variables_factory = variables_factory self._environment: AnsibleEnvironment | None = None # inherit marker behavior from the active template context's templar unless otherwise specified if not marker_behavior: if template_ctx := TemplateContext.current(optional=True): marker_behavior = template_ctx.templar.marker_behavior else: marker_behavior = FAIL_ON_UNDEFINED self._marker_behavior = marker_behavior def copy(self) -> t.Self: new_engine = copy.copy(self) new_engine._environment = None return new_engine def extend(self, marker_behavior: MarkerBehavior | None = None) -> t.Self: new_templar = type(self)( loader=self._loader, variables=self._variables, variables_factory=self._variables_factory, marker_behavior=marker_behavior or self._marker_behavior, ) if self._environment: new_templar._environment = self._environment return new_templar @property def marker_behavior(self) -> MarkerBehavior: return self._marker_behavior @property def basedir(self) -> str: """The basedir from DataLoader.""" return self._loader.get_basedir() if self._loader else '.' @property def environment(self) -> AnsibleEnvironment: if not self._environment: self._environment = AnsibleEnvironment(ansible_basedir=self.basedir) return self._environment def _create_overlay(self, template: str, overrides: TemplateOverrides) -> tuple[str, AnsibleEnvironment]: try: template, overrides = overrides._extract_template_overrides(template) except Exception as ex: raise AnsibleTemplateSyntaxError("Syntax error in template.", obj=template) from ex env = self.environment if overrides is not TemplateOverrides.DEFAULT and (overlay_kwargs := overrides.overlay_kwargs()): env = t.cast(AnsibleEnvironment, env.overlay(**overlay_kwargs)) return template, env @staticmethod def _count_newlines_from_end(in_str): """ Counts the number of newlines at the end of a string. This is used during the jinja2 templating to ensure the count matches the input, since some newlines may be thrown away during the templating. """ i = len(in_str) j = i - 1 try: while in_str[j] == '\n': j -= 1 except IndexError: # Uncommon cases: zero length string and string containing only newlines return i return i - 1 - j @property def available_variables(self) -> dict[str, t.Any] | ChainMap[str, t.Any]: """Available variables this instance will use when templating.""" # DTFIX3: ensure that we're always accessing this as a shallow container-level snapshot, and eliminate uses of anything # that directly mutates this value. _new_context may resolve this for us? if self._variables is None: self._variables = self._variables_factory() if self._variables_factory else {} return self._variables @available_variables.setter def available_variables(self, variables: dict[str, t.Any] | ChainMap[str, t.Any]) -> None: self._variables = variables def resolve_variable_expression( self, expression: str, *, local_variables: dict[str, t.Any] | None = None, ) -> t.Any: """ Resolve a potentially untrusted string variable expression consisting only of valid identifiers, integers, dots, and indexing containing these. Optional local variables may be provided, which can only be referenced directly by the given expression. Valid: x, x.y, x[y].z, x[1], 1, x[y.z] Error: 'x', x['y'], q('env') """ components = re.split(r'[.\[\]]', expression) try: for component in components: if re.fullmatch('[0-9]*', component): continue # allow empty strings and integers validate_variable_name(component) except Exception as ex: raise AnsibleError(f'Invalid variable expression: {expression}', obj=expression) from ex return self.evaluate_expression(TrustedAsTemplate().tag(expression), local_variables=local_variables) @staticmethod def variable_name_as_template(name: str) -> str: """Return a trusted template string that will resolve the provided variable name. Raises an error if `name` is not a valid identifier.""" validate_variable_name(name) return AnsibleTagHelper.tag('{{' + name + '}}', (AnsibleTagHelper.tags(name) | {TrustedAsTemplate()})) def transform(self, variable: t.Any) -> t.Any: """Recursively apply transformations to the given value and return the result.""" return self.template(variable, mode=TemplateMode.ALWAYS_FINALIZE, lazy_options=LazyOptions.SKIP_TEMPLATES_AND_ACCESS) def template( self, variable: t.Any, # DTFIX-FUTURE: once we settle the new/old API boundaries, rename this (here and in other methods) *, options: TemplateOptions = TemplateOptions.DEFAULT, mode: TemplateMode = TemplateMode.DEFAULT, lazy_options: LazyOptions = LazyOptions.DEFAULT, ) -> t.Any: """Templates (possibly recursively) any given data as input.""" original_variable = variable for _attempt in range(TRANSFORM_CHAIN_LIMIT): if variable is None or (value_type := type(variable)) in IGNORE_SCALAR_VAR_TYPES: return variable # quickly ignore supported scalar types which are not be templated value_is_str = isinstance(variable, str) if template_ctx := TemplateContext.current(optional=True): stop_on_template = template_ctx.stop_on_template else: stop_on_template = False if mode is TemplateMode.STOP_ON_TEMPLATE: stop_on_template = True with ( TemplateContext(template_value=variable, templar=self, options=options, stop_on_template=stop_on_template) as ctx, DeprecatedAccessAuditContext.when(ctx.is_top_level), JinjaCallContext(accept_lazy_markers=True), # let default Jinja marker behavior apply, since we're descending into a new template ): try: if not value_is_str: # transforms are currently limited to non-str types as an optimization if (transform := _type_transform_mapping.get(value_type)) and value_type.__name__ not in lazy_options.unmask_type_names: variable = transform(variable) continue template_result = _AnsibleLazyTemplateMixin._try_create(variable, lazy_options) elif not lazy_options.template: template_result = variable elif not is_possibly_template(variable, options.overrides): template_result = variable elif not self._trust_check(variable, skip_handler=stop_on_template): template_result = variable elif stop_on_template: raise TemplateEncountered() else: compiled_template = self._compile_template(variable, options) template_result = compiled_template(self.available_variables) template_result = self._post_render_mutation(variable, template_result, options) except TemplateEncountered: raise except Exception as ex: template_result = defer_template_error(ex, variable, is_expression=False) if ctx.is_top_level or mode is TemplateMode.ALWAYS_FINALIZE: template_result = self._finalize_top_level_template_result( variable, options, template_result, stop_on_container=mode is TemplateMode.STOP_ON_CONTAINER ) return template_result raise AnsibleTemplateTransformLimitError(obj=original_variable) @staticmethod def _finalize_top_level_template_result( variable: t.Any, options: TemplateOptions, template_result: t.Any, is_expression: bool = False, stop_on_container: bool = False, ) -> t.Any: """ This method must be called for expressions and top-level templates to recursively finalize the result. This renders any embedded templates and triggers `Marker` and omit behaviors. """ try: if template_result is Omit: # When the template result is Omit, raise an AnsibleValueOmittedError if value_for_omit is Omit, otherwise return value_for_omit. # Other occurrences of Omit will simply drop out of containers during _finalize_template_result. if options.value_for_omit is Omit: raise AnsibleValueOmittedError() return options.value_for_omit # trust that value_for_omit is an allowed type if stop_on_container and type(template_result) in AnsibleTaggedObject._collection_types: # Use of stop_on_container implies the caller will perform necessary checks on values, # most likely by passing them back into the templating system. try: return template_result._non_lazy_copy() except AttributeError: return template_result # non-lazy containers are returned as-is return _finalize_template_result(template_result, FinalizeMode.TOP_LEVEL) except TemplateEncountered: raise except Exception as ex: raise_from: BaseException if isinstance(ex, MarkerError): exception_to_raise = ex.source._as_exception() # MarkerError is never suitable for use as the cause of another exception, it is merely a raiseable container for the source marker # used for flow control (so its stack trace is rarely useful). However, if the source derives from a ExceptionMarker, its contained # exception (previously raised) should be used as the cause. Other sources do not contain exceptions, so cannot provide a cause. raise_from = exception_to_raise if isinstance(ex.source, ExceptionMarker) else None else: exception_to_raise = ex raise_from = ex exception_to_raise = create_template_error(exception_to_raise, variable, is_expression) if exception_to_raise is ex: raise # when the exception to raise is the active exception, just re-raise it if exception_to_raise is raise_from: raise_from = exception_to_raise.__cause__ # preserve the exception's cause, if any, otherwise no cause will be used raise exception_to_raise from raise_from # always raise from something to avoid the currently active exception becoming __context__ def _compile_template(self, template: str, options: TemplateOptions) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: # NOTE: Creating an overlay that lives only inside _compile_template means that overrides are not applied # when templating nested variables, where Templar.environment is used, not the overlay. They are, however, # applied to includes and imports. try: stripped_template, env = self._create_overlay(template, options.overrides) with _TemplateCompileContext(escape_backslashes=options.escape_backslashes): return t.cast(AnsibleTemplate, env.from_string(stripped_template)) except Exception as ex: return self._defer_jinja_compile_error(ex, template, False) def _compile_expression(self, expression: str, options: TemplateOptions) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: """ Compile a Jinja expression, applying optional compile-time behavior via an environment overlay (if needed). The overlay is necessary to avoid mutating settings on the Templar's shared environment, which could be visible to other code running concurrently. In the specific case of escape_backslashes, the setting only applies to a top-level template at compile-time, not runtime, to ensure that any nested template calls (e.g., include and import) do not inherit the (lack of) escaping behavior. """ try: with _TemplateCompileContext(escape_backslashes=options.escape_backslashes): return AnsibleTemplateExpression(self.environment.compile_expression(expression, False)) except Exception as ex: return self._defer_jinja_compile_error(ex, expression, True) def _defer_jinja_compile_error(self, ex: Exception, variable: str, is_expression: bool) -> t.Callable[[c.Mapping[str, t.Any]], t.Any]: deferred_error = defer_template_error(ex, variable, is_expression=is_expression) def deferred_exception(_jinja_vars: c.Mapping[str, t.Any]) -> t.Any: # a template/expression compile error always results in a single node representing the compile error return self.marker_behavior.handle_marker(deferred_error) return deferred_exception def _post_render_mutation(self, template: str, result: t.Any, options: TemplateOptions) -> t.Any: if options.preserve_trailing_newlines and isinstance(result, str): # The low level calls above do not preserve the newline # characters at the end of the input data, so we # calculate the difference in newlines and append them # to the resulting output for parity # # Using AnsibleEnvironment's keep_trailing_newline instead would # result in change in behavior when trailing newlines # would be kept also for included templates, for example: # "Hello {% include 'world.txt' %}!" would render as # "Hello world\n!\n" instead of "Hello world!\n". data_newlines = self._count_newlines_from_end(template) res_newlines = self._count_newlines_from_end(result) if data_newlines > res_newlines: newlines = options.overrides.newline_sequence * (data_newlines - res_newlines) result = AnsibleTagHelper.tag_copy(result, result + newlines) # If the input string template was source-tagged and the result is not, propagate the source tag to the new value. # This provides further contextual information when a template-derived value/var causes an error. if not Origin.is_tagged_on(result) and (origin := Origin.get_tag(template)): try: result = origin.tag(result) except NotTaggableError: pass # best effort- if we can't, oh well return result def is_template(self, data: t.Any, overrides: TemplateOverrides = TemplateOverrides.DEFAULT) -> bool: """ Evaluate the input data to determine if it contains a template, even if that template is invalid. Containers will be recursively searched. Objects subject to template-time transforms that do not yield a template are not considered templates by this method. Gating a conditional call to `template` with this method is redundant and inefficient -- request templating unconditionally instead. """ options = TemplateOptions(overrides=overrides) if overrides is not TemplateOverrides.DEFAULT else TemplateOptions.DEFAULT try: self.template(data, options=options, mode=TemplateMode.STOP_ON_TEMPLATE) except TemplateEncountered: return True else: return False def resolve_to_container(self, variable: t.Any, options: TemplateOptions = TemplateOptions.DEFAULT) -> t.Any: """ Recursively resolve scalar string template input, stopping at the first container encountered (if any). Used for e.g., partial templating of task arguments, where the plugin needs to handle final resolution of some args internally. """ return self.template(variable, options=options, mode=TemplateMode.STOP_ON_CONTAINER) def evaluate_expression( self, expression: str, *, local_variables: dict[str, t.Any] | None = None, escape_backslashes: bool = True, _render_jinja_const_template: bool = False, ) -> t.Any: """ Evaluate a trusted string expression and return its result. Optional local variables may be provided, which can only be referenced directly by the given expression. """ if not isinstance(expression, str): raise TypeError(f"Expressions must be {str!r}, got {type(expression)!r}.") options = TemplateOptions(escape_backslashes=escape_backslashes, preserve_trailing_newlines=False) with ( TemplateContext(template_value=expression, templar=self, options=options, _render_jinja_const_template=_render_jinja_const_template) as ctx, DeprecatedAccessAuditContext.when(ctx.is_top_level), ): try: if not TrustedAsTemplate.is_tagged_on(expression): raise TemplateTrustCheckFailedError(obj=expression) template_variables = ChainMap(local_variables, self.available_variables) if local_variables else self.available_variables compiled_template = self._compile_expression(expression, options) template_result = compiled_template(template_variables) template_result = self._post_render_mutation(expression, template_result, options) except Exception as ex: template_result = defer_template_error(ex, expression, is_expression=True) return self._finalize_top_level_template_result(expression, options, template_result, is_expression=True) _BROKEN_CONDITIONAL_ALLOWED_FRAGMENT = 'Broken conditionals are currently allowed because the `ALLOW_BROKEN_CONDITIONALS` configuration option is enabled.' _CONDITIONAL_AS_TEMPLATE_MSG = 'Conditionals should not be surrounded by templating delimiters such as {{ }} or {% %}.' def _strip_conditional_handle_empty(self, conditional) -> t.Any: """ Strips leading/trailing whitespace from the input expression. If `ALLOW_BROKEN_CONDITIONALS` is enabled, None/empty is coerced to True (legacy behavior, deprecated). Otherwise, None/empty results in a broken conditional error being raised. """ if isinstance(conditional, str): # Leading/trailing whitespace on conditional expressions is not a problem, except we can't tell if the expression is empty (which *is* a problem). # Always strip conditional input strings. Neither conditional expressions nor all-template conditionals have legit reasons to preserve # surrounding whitespace, and they complicate detection and processing of all-template fallback cases. conditional = AnsibleTagHelper.tag_copy(conditional, conditional.strip()) if conditional in (None, ''): # deprecated backward-compatible behavior; None/empty input conditionals are always True if _TemplateConfig.allow_broken_conditionals: _display.deprecated( msg='Empty conditional expression was evaluated as True.', help_text=self._BROKEN_CONDITIONAL_ALLOWED_FRAGMENT, obj=conditional, version='2.23', ) return True raise AnsibleBrokenConditionalError("Empty conditional expressions are not allowed.", obj=conditional) return conditional def _normalize_and_evaluate_conditional(self, conditional: str | bool) -> t.Any: """Validate and normalize a conditional input value, resolving allowed embedded template cases and evaluating the resulting expression.""" conditional = self._strip_conditional_handle_empty(conditional) # this must follow `_strip_conditional_handle_empty`, since None/empty are coerced to bool (deprecated) if type(conditional) is bool: # pylint: disable=unidiomatic-typecheck return conditional try: if not isinstance(conditional, str): if _TemplateConfig.allow_broken_conditionals: # because the input isn't a string, the result will never be a bool; the broken conditional warning in the caller will apply on the result return self.template(conditional, mode=TemplateMode.ALWAYS_FINALIZE) raise AnsibleBrokenConditionalError(message="Conditional expressions must be strings.", obj=conditional) if is_possibly_all_template(conditional): # Indirection of trusted expressions is always allowed. If the expression appears to be entirely wrapped in template delimiters, # we must resolve it. e.g. `when: "{{ some_var_resolving_to_a_trusted_expression_string }}"`. # Some invalid meta-templating corner cases may sneak through here (e.g., `when: '{{ "foo" }} == {{ "bar" }}'`); these will # result in an untrusted expression error. result = self.template(conditional, mode=TemplateMode.ALWAYS_FINALIZE) result = self._strip_conditional_handle_empty(result) if not isinstance(result, str): _display.deprecated(msg=self._CONDITIONAL_AS_TEMPLATE_MSG, obj=conditional, version='2.23') return result # not an expression # The only allowed use of templates for conditionals is for indirect usage of an expression. # Any other usage should simply be an expression, not an attempt at meta templating. expression = result else: expression = conditional # Disable escape_backslashes when processing conditionals, to maintain backwards compatibility. # This is necessary because conditionals were previously evaluated using {% %}, which was *NOT* affected by escape_backslashes. # Now that conditionals use expressions, they would be affected by escape_backslashes if it was not disabled. return self.evaluate_expression(expression, escape_backslashes=False, _render_jinja_const_template=True) except AnsibleUndefinedVariable as ex: # DTFIX-FUTURE: we're only augmenting the message for context here; once we have proper contextual tracking, we can dump the re-raise raise AnsibleUndefinedVariable("Error while evaluating conditional.", obj=conditional) from ex def evaluate_conditional(self, conditional: str | bool) -> bool: """ Evaluate a trusted string expression or boolean and return its boolean result. A non-boolean result will raise `AnsibleBrokenConditionalError`. The ALLOW_BROKEN_CONDITIONALS configuration option can temporarily relax this requirement, allowing truthy conditionals to succeed. """ result = self._normalize_and_evaluate_conditional(conditional) if isinstance(result, bool): return result bool_result = bool(result) result_origin = Origin.get_tag(result) or Origin.UNKNOWN msg = ( f'Conditional result ({bool_result}) was derived from value of type {native_type_name(result)!r} at {str(result_origin)!r}. ' 'Conditionals must have a boolean result.' ) if _TemplateConfig.allow_broken_conditionals: _display.deprecated( msg=msg, obj=conditional, help_text=self._BROKEN_CONDITIONAL_ALLOWED_FRAGMENT, version='2.23', ) return bool_result raise AnsibleBrokenConditionalError(msg, obj=conditional) @staticmethod def _trust_check(value: str, skip_handler: bool = False) -> bool: """ Return True if the given value is trusted for templating, otherwise return False. When the value is not trusted, a warning or error may be generated, depending on configuration. """ if TrustedAsTemplate.is_tagged_on(value): return True if not skip_handler: with Skippable, _TemplateConfig.untrusted_template_handler.handle(TemplateTrustCheckFailedError, skip_on_ignore=True): raise TemplateTrustCheckFailedError(obj=value) return False
TemplateEngine
python
django__django
tests/syndication_tests/feeds.py
{ "start": 6569, "end": 6659 }
class ____(TestAtomFeed): feed_url = "http://example.com/customfeedurl/"
TestFeedUrlFeed
python
huggingface__transformers
src/transformers/models/perceiver/image_processing_perceiver_fast.py
{ "start": 1109, "end": 5045 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD size = {"height": 224, "width": 224} crop_size = {"height": 256, "width": 256} do_resize = True do_center_crop = True do_rescale = True do_normalize = True def center_crop( self, image: "torch.Tensor", crop_size: dict[str, int], size: dict[str, int], **kwargs, ) -> "torch.Tensor": """ Center crop an image to `(size["height"] / crop_size["height"] * min_dim, size["width"] / crop_size["width"] * min_dim)`. Where `min_dim = min(size["height"], size["width"])`. If the input size is smaller than `crop_size` along any edge, the image will be padded with zeros and then center cropped. Args: image (`"torch.Tensor"`): Image to center crop. crop_size (`dict[str, int]`): Desired output size after applying the center crop. size (`dict[str, int]`): Size of the output image. Returns: `torch.Tensor`: The center cropped image. """ if size.height is None or size.width is None: raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}") height, width = image.shape[-2:] min_dim = min(height, width) cropped_height = int((size.height / crop_size.height) * min_dim) cropped_width = int((size.width / crop_size.width) * min_dim) return super().center_crop(image, SizeDict(height=cropped_height, width=cropped_width)) def _preprocess( self, images: list["torch.Tensor"], do_resize: bool, size: SizeDict, interpolation: Optional["F.InterpolationMode"], do_center_crop: bool, crop_size: SizeDict, do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: Optional[Union[float, list[float]]], image_std: Optional[Union[float, list[float]]], disable_grouping: Optional[bool], return_tensors: Optional[Union[str, TensorType]], **kwargs, ) -> BatchFeature: # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): if do_center_crop: stacked_images = self.center_crop(stacked_images, size=size, crop_size=crop_size) if do_resize: stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation) resized_images_grouped[shape] = stacked_images resized_images = reorder_images(resized_images_grouped, grouped_images_index) # Group images by size for further processing # Needed in case do_resize is False, or resize returns images with different sizes grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} for shape, stacked_images in grouped_images.items(): # Fused rescale and normalize stacked_images = self.rescale_and_normalize( stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) processed_images_grouped[shape] = stacked_images processed_images = reorder_images(processed_images_grouped, grouped_images_index) processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors) __all__ = ["PerceiverImageProcessorFast"]
PerceiverImageProcessorFast
python
scipy__scipy
benchmarks/benchmarks/stats.py
{ "start": 10200, "end": 12215 }
class ____(Benchmark): # Benchmarks that track a value for every distribution can go here param_names = ['dist_name'] params = list(dict(distcont).keys()) dist_data = dict(distcont) def setup(self, dist_name): # Distribution setup follows `DistributionsAll` benchmark. # This focuses on ppf, so the code for handling other functions is # removed for simplicity. self.dist = getattr(stats, dist_name) self.shape_args = self.dist_data[dist_name] def track_distribution_ppf_roundtrip(self, dist_name): # Tracks the worst relative error of a # couple of round-trip ppf -> cdf calculations. vals = [0.001, 0.5, 0.999] ppf = self.dist.ppf(vals, *self.shape_args) round_trip = self.dist.cdf(ppf, *self.shape_args) err_rel = np.abs(vals - round_trip) / vals return np.max(err_rel) def track_distribution_ppf_roundtrip_extrema(self, dist_name): # Tracks the absolute error of an "extreme" round-trip # ppf -> cdf calculation. v = 1e-6 ppf = self.dist.ppf(v, *self.shape_args) round_trip = self.dist.cdf(ppf, *self.shape_args) err_abs = np.abs(v - round_trip) return err_abs def track_distribution_isf_roundtrip(self, dist_name): # Tracks the worst relative error of a # couple of round-trip isf -> sf calculations. vals = [0.001, 0.5, 0.999] isf = self.dist.isf(vals, *self.shape_args) round_trip = self.dist.sf(isf, *self.shape_args) err_rel = np.abs(vals - round_trip) / vals return np.max(err_rel) def track_distribution_isf_roundtrip_extrema(self, dist_name): # Tracks the absolute error of an "extreme" round-trip # isf -> sf calculation. v = 1e-6 ppf = self.dist.isf(v, *self.shape_args) round_trip = self.dist.sf(ppf, *self.shape_args) err_abs = np.abs(v - round_trip) return err_abs
TrackContinuousRoundtrip
python
nryoung__algorithms
tests/test_searching.py
{ "start": 5864, "end": 6369 }
class ____(unittest.TestCase): """ Tests teranry search algorithm on unimodal functions """ def test_terarysearch(self): self.function1 = lambda x: -(x - 2) ** 2 self.function2 = lambda x: math.cos(x) self.eps = 1e-6 rv1 = ternary_search.search(self.function1, -2.0, 2.0, self.eps) rv2 = ternary_search.search(self.function2, -2.0, 2.0, self.eps) self.assertAlmostEqual(rv1, 2.0, 6) self.assertAlmostEqual(rv2, 0.0, 6)
TestTernarySearch
python
xlwings__xlwings
xlwings/constants.py
{ "start": 123344, "end": 123827 }
class ____: xlLast7Days = 2 # from enum XlTimePeriods xlLastMonth = 5 # from enum XlTimePeriods xlLastWeek = 4 # from enum XlTimePeriods xlNextMonth = 8 # from enum XlTimePeriods xlNextWeek = 7 # from enum XlTimePeriods xlThisMonth = 9 # from enum XlTimePeriods xlThisWeek = 3 # from enum XlTimePeriods xlToday = 0 # from enum XlTimePeriods xlTomorrow = 6 # from enum XlTimePeriods xlYesterday = 1 # from enum XlTimePeriods
TimePeriods
python
airbytehq__airbyte
airbyte-integrations/connectors/source-genesys/source_genesys/source.py
{ "start": 5181, "end": 5468 }
class ____(GenesysStream): """ API Docs: https://developer.genesys.cloud/telephony/telephony-apis """ primary_key = "id" cursor_field = "dateModified" def path(self, **kwargs) -> str: return "telephony/providers/edges/trunks"
TelephonyProvidersEdgesTrunks
python
tensorflow__tensorflow
tensorflow/core/function/polymorphism/type_dispatch_test.py
{ "start": 966, "end": 2131 }
class ____(trace.TraceType): def __init__(self, *shape: Optional[int]): self.shape = shape def is_subtype_of(self, other: "MockShape") -> bool: if len(self.shape) != len(other.shape): return False return all(o is None or s == o for s, o in zip(self.shape, other.shape)) def most_specific_common_supertype(self, others): if any(len(other.shape) != len(self.shape) for other in others): return None dims = [ dim if all(dim == other.shape[i] for other in others) else None for i, dim in enumerate(self.shape) ] return MockShape(*dims) def placeholder_value(self, placeholder_context=None): raise NotImplementedError def __str__(self): return str(self.shape) def __repr__(self): return str(self) def __hash__(self) -> int: return hash(self.shape) def __eq__(self, other: "MockShape") -> bool: return self.shape == other.shape def make_shape_function_type(*shape): return function_type.FunctionType([ function_type.Parameter("x", function_type.Parameter.POSITIONAL_ONLY, False, MockShape(*shape)) ])
MockShape
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 5203, "end": 5289 }
class ____(HTTPSuccessful): status_code = 205 empty_body = True
HTTPResetContent
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 1321, "end": 1433 }
class ____(TypedDict): enabled: bool extractionState: str dashboardWidgetQueryId: int
OnDemandResponse
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/base.py
{ "start": 54231, "end": 54412 }
class ____(SchemaEventTarget, visitors.Visitable): """Base class for elements that are targets of a :class:`.SchemaVisitor`. .. versionadded:: 2.0.41 """
SchemaVisitable
python
wireservice__csvkit
csvkit/grep.py
{ "start": 4344, "end": 4501 }
class ____: def __init__(self, pattern): self.pattern = pattern def __call__(self, arg): return self.pattern.search(arg)
regex_callable
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_apps.py
{ "start": 15273, "end": 17493 }
class ____(SentryAppsTest): method = "post" def setUp(self) -> None: super().setUp() self.superuser = self.create_user(is_superuser=True) self.staff_user = self.create_user(is_staff=True) self.login_as(self.superuser, superuser=True) def test_staff_cannot_create_app(self) -> None: """We do not allow staff to create Sentry Apps b/c this cannot be done in _admin.""" self.login_as(self.staff_user, staff=True) response = self.get_error_response(**self.get_data(), status_code=401) assert ( response.data["detail"] == "User must be a part of the Org they're trying to create the app in" ) def test_superuser_cannot_create_app_in_nonexistent_organization(self) -> None: sentry_app = self.create_internal_integration(name="Foo Bar") data = self.get_data(name=sentry_app.name, organization="some-non-existent-org") response = self.get_error_response(**data, status_code=404) assert response.data == { "detail": "Organization 'some-non-existent-org' does not exist.", } def test_superuser_can_create_with_popularity(self) -> None: response = self.get_success_response( **self.get_data(popularity=POPULARITY), status_code=201 ) assert {"popularity": POPULARITY}.items() <= orjson.loads(response.content).items() with self.settings(SENTRY_SELF_HOSTED=False): self.get_success_response( **self.get_data(popularity=25, name="myApp 2"), status_code=201 ) @override_settings(SENTRY_SELF_HOSTED=False) @override_options({"superuser.read-write.ga-rollout": True}) def test_superuser_read_cannot_create(self) -> None: self.get_error_response(**self.get_data(name="POPULARITY")) @override_settings(SENTRY_SELF_HOSTED=False) @override_options({"superuser.read-write.ga-rollout": True}) def test_superuser_read_can_create(self) -> None: self.add_user_permission(self.superuser, "superuser.write") self.get_success_response(**self.get_data(popularity=POPULARITY), status_code=201) @control_silo_test
SuperuserStaffPostSentryAppsTest
python
numpy__numpy
numpy/_core/tests/test_dtype.py
{ "start": 80608, "end": 83084 }
class ____: def test_signature_dtype(self): sig = inspect.signature(np.dtype) assert len(sig.parameters) == 4 assert "dtype" in sig.parameters assert sig.parameters["dtype"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert sig.parameters["dtype"].default is inspect.Parameter.empty assert "align" in sig.parameters assert sig.parameters["align"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert sig.parameters["align"].default is False assert "copy" in sig.parameters assert sig.parameters["copy"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert sig.parameters["copy"].default is False # the optional `metadata` parameter has no default, so `**kwargs` must be used assert "kwargs" in sig.parameters assert sig.parameters["kwargs"].kind is inspect.Parameter.VAR_KEYWORD assert sig.parameters["kwargs"].default is inspect.Parameter.empty def test_signature_dtype_newbyteorder(self): sig = inspect.signature(np.dtype.newbyteorder) assert len(sig.parameters) == 2 assert "self" in sig.parameters assert sig.parameters["self"].kind is inspect.Parameter.POSITIONAL_ONLY assert sig.parameters["self"].default is inspect.Parameter.empty assert "new_order" in sig.parameters assert sig.parameters["new_order"].kind is inspect.Parameter.POSITIONAL_ONLY assert sig.parameters["new_order"].default == "S" @pytest.mark.parametrize("typename", np.dtypes.__all__) def test_signature_dtypes_classes(self, typename: str): dtype_type = getattr(np.dtypes, typename) sig = inspect.signature(dtype_type) match typename.lower().removesuffix("dtype"): case "bytes" | "str": params_expect = {"size"} case "void": params_expect = {"length"} case "datetime64" | "timedelta64": params_expect = {"unit"} case "string": # `na_object` cannot be used in the text signature because of its # `np._NoValue` default, which isn't supported by `inspect.signature`, # so `**kwargs` is used instead. params_expect = {"coerce", "kwargs"} case _: params_expect = set() params_actual = set(sig.parameters) assert params_actual == params_expect
TestDTypeSignatures
python
pandas-dev__pandas
pandas/io/sql.py
{ "start": 88817, "end": 94689 }
class ____(SQLTable): """ Patch the SQLTable for fallback support. Instead of a table variable just use the Create Table statement. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._register_date_adapters() def _register_date_adapters(self) -> None: # GH 8341 # register an adapter callable for datetime.time object import sqlite3 # this will transform time(12,34,56,789) into '12:34:56.000789' # (this is what sqlalchemy does) def _adapt_time(t) -> str: # This is faster than strftime return f"{t.hour:02d}:{t.minute:02d}:{t.second:02d}.{t.microsecond:06d}" # Also register adapters for date/datetime and co # xref https://docs.python.org/3.12/library/sqlite3.html#adapter-and-converter-recipes # Python 3.12+ doesn't auto-register adapters for us anymore adapt_date_iso = lambda val: val.isoformat() adapt_datetime_iso = lambda val: val.isoformat(" ") sqlite3.register_adapter(time, _adapt_time) sqlite3.register_adapter(date, adapt_date_iso) sqlite3.register_adapter(datetime, adapt_datetime_iso) convert_date = lambda val: date.fromisoformat(val.decode()) convert_timestamp = lambda val: datetime.fromisoformat(val.decode()) sqlite3.register_converter("date", convert_date) sqlite3.register_converter("timestamp", convert_timestamp) def sql_schema(self) -> str: return str(";\n".join(self.table)) def _execute_create(self) -> None: with self.pd_sql.run_transaction() as cur: for stmt in self.table: cur.execute(stmt) def insert_statement(self, *, num_rows: int) -> str: names = list(map(str, self.frame.columns)) wld = "?" # wildcard char escape = _get_valid_sqlite_name if self.index is not None: for idx in self.index[::-1]: names.insert(0, idx) bracketed_names = [escape(column) for column in names] col_names = ",".join(bracketed_names) row_wildcards = ",".join([wld] * len(names)) wildcards = ",".join([f"({row_wildcards})" for _ in range(num_rows)]) insert_statement = ( f"INSERT INTO {escape(self.name)} ({col_names}) VALUES {wildcards}" ) return insert_statement def _execute_insert(self, conn, keys, data_iter) -> int: from sqlite3 import Error data_list = list(data_iter) try: conn.executemany(self.insert_statement(num_rows=1), data_list) except Error as exc: raise DatabaseError("Execution failed") from exc return conn.rowcount def _execute_insert_multi(self, conn, keys, data_iter) -> int: data_list = list(data_iter) flattened_data = [x for row in data_list for x in row] conn.execute(self.insert_statement(num_rows=len(data_list)), flattened_data) return conn.rowcount def _create_table_setup(self): """ Return a list of SQL statements that creates a table reflecting the structure of a DataFrame. The first entry will be a CREATE TABLE statement while the rest will be CREATE INDEX statements. """ column_names_and_types = self._get_column_names_and_types(self._sql_type_name) escape = _get_valid_sqlite_name create_tbl_stmts = [ escape(cname) + " " + ctype for cname, ctype, _ in column_names_and_types ] if self.keys is not None and len(self.keys): if not is_list_like(self.keys): keys = [self.keys] else: keys = self.keys cnames_br = ", ".join([escape(c) for c in keys]) create_tbl_stmts.append( f"CONSTRAINT {self.name}_pk PRIMARY KEY ({cnames_br})" ) if self.schema: schema_name = self.schema + "." else: schema_name = "" create_stmts = [ "CREATE TABLE " + schema_name + escape(self.name) + " (\n" + ",\n ".join(create_tbl_stmts) + "\n)" ] ix_cols = [cname for cname, _, is_index in column_names_and_types if is_index] if ix_cols: cnames = "_".join(ix_cols) cnames_br = ",".join([escape(c) for c in ix_cols]) create_stmts.append( "CREATE INDEX " + escape("ix_" + self.name + "_" + cnames) + "ON " + escape(self.name) + " (" + cnames_br + ")" ) return create_stmts def _sql_type_name(self, col): dtype: DtypeArg = self.dtype or {} if is_dict_like(dtype): dtype = cast(dict, dtype) if col.name in dtype: return dtype[col.name] # Infer type of column, while ignoring missing values. # Needed for inserting typed data containing NULLs, GH 8778. col_type = lib.infer_dtype(col, skipna=True) if col_type == "timedelta64": warnings.warn( "the 'timedelta' type is not supported, and will be " "written as integer values (ns frequency) to the database.", UserWarning, stacklevel=find_stack_level(), ) col_type = "integer" elif col_type == "datetime64": col_type = "datetime" elif col_type == "empty": col_type = "string" elif col_type == "complex": raise ValueError("Complex datatypes not supported") if col_type not in _SQL_TYPES: col_type = "string" return _SQL_TYPES[col_type]
SQLiteTable
python
google__jax
jax/_src/ffi.py
{ "start": 2463, "end": 23881 }
class ____(TypedDict): """A dictionary type for registering FFI types. Attributes: type_id: A ``PyCapsule`` object containing a pointer to the ``XLA_FFI_TypeId``. type_info: An optional ``PyCapsule`` object containing a pointer to the type ``XLA_FFI_TypeInfo``. """ type_id: Any type_info: NotRequired[Any] def register_ffi_type_id( name: str, obj: Any, platform: str = "cpu", ) -> None: """Registers a custom type ID for a FFI target. Args: name: the name of the type ID. This name must be unique within the process. obj: a ``PyCapsule`` object encapsulating a pointer to the type ID. platform: the target platform. """ raise ValueError( "register_ffi_type_id is not supported after jaxlib version 381.") def register_ffi_type( name: str, type_registration: TypeRegistration, platform: str = "cpu", ) -> None: """Registers a custom type for a FFI target. Args: name: the name of the type. This name must be unique within the process. type_registration: a ``TypeRegistration`` defining the external type. platform: the target platform. """ return xla_client.register_custom_type( name, type_registration, platform=platform ) def register_ffi_target_as_batch_partitionable(name: str) -> None: """Registers an FFI target as batch partitionable. Args: name: the name of the target. """ xla_client.register_custom_call_as_batch_partitionable(name) xla_bridge.register_plugin_callbacks( functools.partial(xla_client.register_custom_call_as_batch_partitionable, name)) def pycapsule(funcptr): """Wrap a ctypes function pointer in a PyCapsule. The primary use of this function, and the reason why it lives with in the ``jax.ffi`` submodule, is to wrap function calls from external compiled libraries to be registered as XLA custom calls. Example usage:: import ctypes import jax from jax.lib import xla_client libfoo = ctypes.cdll.LoadLibrary('./foo.so') xla_client.register_custom_call_target( name="bar", fn=jax.ffi.pycapsule(libfoo.bar), platform=PLATFORM, api_version=API_VERSION ) Args: funcptr: A function pointer loaded from a dynamic library using ``ctypes``. Returns: An opaque ``PyCapsule`` object wrapping ``funcptr``. """ destructor = ctypes.CFUNCTYPE(None, ctypes.py_object) builder = ctypes.pythonapi.PyCapsule_New builder.restype = ctypes.py_object builder.argtypes = (ctypes.c_void_p, ctypes.c_char_p, destructor) return builder(funcptr, None, destructor(0)) def include_dir() -> str: """Get the path to the directory containing header files bundled with jaxlib""" jaxlib_dir = os.path.dirname(os.path.abspath(jaxlib.__file__)) return os.path.join(jaxlib_dir, "include") def _aval_shape(aval: core.AbstractValue) -> Shape: return () if aval is core.abstract_token else core.physical_aval(aval).shape # pytype: disable=attribute-error def _convert_layout_for_lowering( aval: core.AbstractValue, layout: FfiLayoutOptions = None) -> Sequence[int]: """Convert a layout to the minor-to-major order used by the custom call API.""" if layout is None: return tuple(reversed(range(len(_aval_shape(aval))))) elif isinstance(layout, Layout): if layout.tiling is not None: raise ValueError("The FFI does not support layouts with tiling") return layout.major_to_minor[::-1] else: return tuple(layout) def build_ffi_lowering_function( call_target_name: str, *, operand_layouts: Sequence[FfiLayoutOptions] | None = None, result_layouts: Sequence[FfiLayoutOptions] | None = None, backend_config: Mapping[str, ir.Attribute] | str | None = None, skip_ffi_layout_processing: bool = False, **lowering_args: Any, ) -> Callable[..., ir.Operation]: """Build a lowering op for an foreign function interface (FFI) target. By default, this lowering rule can use the input and output abstract values to compute the input and output types and shapes for the custom call, assuming row-major layouts. Note that layouts passed to this function as tuples should be in minor-to-major order (as expected by XLA) rather than major-to-minor as used by :func:`~jax.ffi.ffi_call` and ``Layout``. If keyword arguments are passed to the lowering rule, these are treated as attributes, and added to `backend_config`. Args: call_target_name: The name of the custom call target. operand_layouts: A sequence of layouts (dimension orders) for each operand. By default, the operands are assumed to be row-major. result_layouts: A sequence of layouts (dimension orders) for each result. By default, the results are assumed to be row-major. backend_config: Configuration data for the custom call. Any keyword arguments passed to the lowering rule will added to this dictionary. lowering_args: Any other arguments to :func:`mlir.custom_call` will also be passed through if provided as extra arguments to this function. skip_ffi_layout_processing: If true, skip processing of operand and result layout arguments passed to the lowering rule. """ def _lowering_op( ctx: mlir.LoweringRuleContext, *operands: ir.Value, **params: Any ) -> ir.Operation: kwargs = dict(lowering_args) kwargs.setdefault("api_version", 4) if kwargs["api_version"] >= 4: if backend_config is not None and not isinstance(backend_config, dict): raise ValueError( "When api_version > 4, backend_config must be a dictionary.") kwargs["backend_config"] = dict( backend_config or {}, **{k: mlir.ir_attribute(v) for k, v in params.items()}) else: if params: raise ValueError( "The use of ffi_call attributes requires a custom call API version " f"of at least 4; got api_version={kwargs['api_version']}.") kwargs["backend_config"] = backend_config if "result_types" not in kwargs: kwargs["result_types"] = [mlir.aval_to_ir_type(aval) for aval in ctx.avals_out] if not skip_ffi_layout_processing: if operand_layouts is None: kwargs["operand_layouts"] = map( _convert_layout_for_lowering, ctx.avals_in ) else: kwargs["operand_layouts"] = [ _convert_layout_for_lowering(*args) for args in zip(ctx.avals_in, operand_layouts) ] if result_layouts is None: kwargs["result_layouts"] = map( _convert_layout_for_lowering, ctx.avals_out ) else: kwargs["result_layouts"] = [ _convert_layout_for_lowering(*args) for args in zip(ctx.avals_out, result_layouts) ] if "result_shapes" not in kwargs and not all( core.is_constant_shape(_aval_shape(aval)) for aval in ctx.avals_out): kwargs["result_shapes"] = [ mlir.shape_tensor(mlir.eval_dynamic_shape_as_ivals(ctx, _aval_shape(aval))) for aval in ctx.avals_out] return mlir.custom_call(call_target_name, operands=operands, **kwargs) return _lowering_op def ffi_lowering( call_target_name: str, *, operand_layouts: Sequence[FfiLayoutOptions] | None = None, result_layouts: Sequence[FfiLayoutOptions] | None = None, backend_config: Mapping[str, ir.Attribute] | str | None = None, skip_ffi_layout_processing: bool = False, **lowering_args: Any ) -> mlir.LoweringRule: """Build a lowering rule for an foreign function interface (FFI) target. By default, this lowering rule can use the input and output abstract values to compute the input and output types and shapes for the custom call, assuming row-major layouts. Note that layouts passed to this function as tuples should be in minor-to-major order (as expected by XLA) rather than major-to-minor as used by :func:`~jax.ffi.ffi_call` and ``Layout``. If keyword arguments are passed to the lowering rule, these are treated as attributes, and added to `backend_config`. Args: call_target_name: The name of the custom call target. operand_layouts: A sequence of layouts (dimension orders) for each operand. By default, the operands are assumed to be row-major. result_layouts: A sequence of layouts (dimension orders) for each result. By default, the results are assumed to be row-major. backend_config: Configuration data for the custom call. Any keyword arguments passed to the lowering rule will added to this dictionary. lowering_args: Any other arguments to :func:`mlir.custom_call` will also be passed through if provided as extra arguments to this function. skip_ffi_layout_processing: If true, skip processing of operand and result layout arguments passed to the lowering rule. """ def _lowering( ctx: mlir.LoweringRuleContext, *operands: ir.Value, **params: Any ) -> Sequence[ir.Value | Sequence[ir.Value]]: result = build_ffi_lowering_function( call_target_name, operand_layouts=operand_layouts, result_layouts=result_layouts, backend_config=backend_config, skip_ffi_layout_processing=skip_ffi_layout_processing, **lowering_args, )(ctx, *operands, **params) return result.results # type: ignore return _lowering ResultMetadata = DuckTypedArray | core.AbstractToken def _result_avals(results: Sequence[ResultMetadata] ) -> tuple[core.AbstractValue, ...]: return tuple(core.shaped_abstractify(r) for r in results) def _check_compatible_avals(a: core.AbstractValue, b: core.AbstractValue) -> bool: if isinstance(a, core.AbstractToken) and isinstance(b, core.AbstractToken): return True if getattr(a, "shape", ()) != getattr(b, "shape", ()): return False if getattr(a, "dtype", ()) != getattr(b, "dtype", ()): return False return True def _convert_layouts_for_ffi_call( avals: Sequence[core.AbstractValue], layouts: Sequence[FfiLayoutOptions]) -> tuple[Sequence[int], ...]: return tuple( _convert_layout_for_lowering( aval, layout if layout is None or isinstance(layout, Layout) else layout[::-1] ) for aval, layout in zip(avals, layouts)) # ffi_call() returns as many results as result_shape_dtypes. @overload def ffi_call( target_name: str, result_shape_dtypes: ResultMetadata, *, has_side_effect: bool = ..., vmap_method: str | None = ..., input_layouts: Sequence[FfiLayoutOptions] | None = ..., output_layouts: FfiLayoutOptions | Sequence[FfiLayoutOptions] | None = ..., input_output_aliases: dict[int, int] | None = ..., custom_call_api_version: int = ..., legacy_backend_config: str | None = ..., vectorized: bool | None | DeprecatedArg = DeprecatedArg(), ) -> Callable[..., Array]: ... @overload def ffi_call( target_name: str, result_shape_dtypes: Sequence[ResultMetadata], *, has_side_effect: bool = ..., vmap_method: str | None = ..., input_layouts: Sequence[FfiLayoutOptions] | None = ..., output_layouts: FfiLayoutOptions | Sequence[FfiLayoutOptions] | None = ..., input_output_aliases: dict[int, int] | None = ..., custom_call_api_version: int = ..., legacy_backend_config: str | None = ..., vectorized: bool | None | DeprecatedArg = DeprecatedArg(), ) -> Callable[..., Sequence[Array]]: ... def ffi_call( target_name: str, result_shape_dtypes: ResultMetadata | Sequence[ResultMetadata], *, has_side_effect: bool = False, vmap_method: str | None = None, input_layouts: Sequence[FfiLayoutOptions] | None = None, output_layouts: FfiLayoutOptions | Sequence[FfiLayoutOptions] | None = None, input_output_aliases: dict[int, int] | None = None, custom_call_api_version: int = 4, legacy_backend_config: str | None = None, vectorized: bool | None | DeprecatedArg = DeprecatedArg(), ) -> Callable[..., Array | Sequence[Array]]: """Call a foreign function interface (FFI) target. See the :ref:`ffi-tutorial` tutorial for more information. Like :func:`~jax.pure_callback`, the behavior of ``ffi_call`` under :func:`~jax.vmap` depends on the value of ``vmap_method``. See the :func:`~jax.pure_callback` documentation for more details about the allowed values and examples of their behavior. The current default behavior is to use ``vmap_method="sequential"`` when not specified, but this behavior is deprecated, and in the future, the default will be to raise a ``NotImplementedError`` unless ``vmap_method`` is explicitly specified. Args: target_name: the name of the XLA FFI custom call target that was registered using :func:`~jax.ffi.register_ffi_target`. result_shape_dtypes: an object, or sequence of objects, with ``shape`` and ``dtype`` attributes which are expected to match the shape and dtype of the custom call output or outputs. :class:`~jax.ShapeDtypeStruct` is often used to define the elements of ``result_shape_dtypes``. ``jax.core.abstract_token`` may be used to represent a token-typed output. has_side_effect: boolean specifying whether the custom call has side effects. When ``True``, the FFI call will be executed even when the outputs are not used. vmap_method: string specifying how the FFI call transforms under :func:`~jax.vmap` as described above. input_layouts: a sequence of layouts for each input argument. In each case, the layout can be (a) ``None`` indicating that this input is in default row-major order, (b) a ``Layout`` specifying the axis order, or (c) a sequence of integers specifying the major-to-minor axis ordering. Users who are familiar with XLA layouts should note that this function expects layouts in major-to-minor order instead of the minor-to-major order that XLA uses. For example, a batch of row-major matrices could be specified using the layout ``[0, 1, 2]``, whereas a batch of column-major matrices would have layout ``[0, 2, 1]``. In both of these examples, the leading/batch dimension is the "slowest" axis. The ``input_layouts`` parameter should be used to request the memory layout expected by the FFI call target, and XLA will ensure that the buffers have the correct layouts before the handler is executed. output_layouts: like ``input_layouts``, but specifying the required layouts for the output arrays. input_output_aliases: a dictionary where the keys are input indices and the values are output indices. This mapping indicates which output arrays alias specific input arrays. custom_call_api_version: the version number of the custom call API implemented by the FFI target ``target_name``. The only formally supported version is the typed FFI API with ``custom_call_api_version=4``, but earlier unsupported custom calls can be executed using this argument. legacy_backend_config: for legacy targets implemented using ``custom_call_api_version<4``, attributes are passed using the opaque string representation provided by this argument. This parameter cannot be used with ``custom_call_api_version>=4``. Returns: A function that can be called with the input arrays as positional arguments to execute the FFI handler. Any keyword arguments are passed as named attributes to the FFI handler using XLA's FFI interface. """ # TODO(danfm): Remove this check 3 months after v0.6.0 is released. if not isinstance(vectorized, DeprecatedArg): raise ValueError( "The 'vectorized' argument of jax.ffi.ffi_call was removed in JAX " "v0.6.0. Use 'vmap_method' instead.") allowed_vmap_methods = ["sequential", "sequential_unrolled", "expand_dims", "broadcast_all", "legacy_vectorized", None] if vmap_method not in allowed_vmap_methods: raise ValueError( f"vmap_method must be on of the allowed methods {allowed_vmap_methods}, " f"but got: {vmap_method}") output_layouts_: Sequence[FfiLayoutOptions] | None if isinstance(result_shape_dtypes, Sequence): output_layouts_ = output_layouts # type: ignore multiple_results = True result_avals = _result_avals(result_shape_dtypes) else: multiple_results = False result_avals = _result_avals([result_shape_dtypes]) output_layouts_ = (output_layouts,) # type: ignore if custom_call_api_version >= 4 and legacy_backend_config is not None: raise ValueError( "The use of the legacy_backend_config parameter requires " f"custom_call_api_version < 4; got {custom_call_api_version}.") def wrapped(*args: ArrayLike, **kwargs: Any): in_avals = [core.get_aval(x) for x in args] if input_layouts is None: static_input_layouts = tuple(map(_convert_layout_for_lowering, in_avals)) else: if len(input_layouts) != len(in_avals): raise ValueError( f"The number of input arguments ({len(in_avals)}) must equal the " f"number of input layouts ({len(input_layouts)}).") static_input_layouts = _convert_layouts_for_ffi_call(in_avals, input_layouts) if output_layouts_ is None: static_output_layouts = tuple(map(_convert_layout_for_lowering, result_avals)) else: if len(output_layouts_) != len(result_avals): raise ValueError( f"The number of outputs ({len(result_avals)}) must equal the " f"number of output layouts ({len(output_layouts_)}).") static_output_layouts = _convert_layouts_for_ffi_call(result_avals, output_layouts_) static_input_output_aliases: tuple[tuple[int, int], ...] = () if input_output_aliases is not None: for i_idx, o_idx in sorted(input_output_aliases.items()): i_idx, o_idx = int(i_idx), int(o_idx) if i_idx >= len(args): raise ValueError( f"input_output_aliases contains the mapping '{i_idx}:{o_idx}' " f"with input index {i_idx} outside the range [0, " f"{len(args)}).") if o_idx >= len(result_avals): raise ValueError( f"input_output_aliases contains the mapping '{i_idx}:{o_idx}' " f"with output index {o_idx} outside the range [0, " f"{len(result_avals)}).") in_aval = in_avals[i_idx] out_aval = result_avals[o_idx] if not _check_compatible_avals(in_aval, out_aval): raise ValueError( f"input_output_aliases contains the mapping '{i_idx}:{o_idx}' " f"referring to an input with abstract value {in_aval} and an " f"output with a different abstract value {out_aval}.") if static_input_layouts[i_idx] != static_output_layouts[o_idx]: raise ValueError( f"input_output_aliases contains the mapping '{i_idx}:{o_idx}' " f"referring to an input with layout {static_input_layouts[i_idx]} " "and an output with a different layout " f"{static_output_layouts[o_idx]}.") static_input_output_aliases += ((i_idx, o_idx),) args = core.standard_insert_pvary(*args) results = ffi_call_p.bind( *args, result_avals=result_avals, vmap_method=vmap_method, target_name=target_name, has_side_effect=has_side_effect, input_layouts=static_input_layouts, output_layouts=static_output_layouts, input_output_aliases=static_input_output_aliases, custom_call_api_version=custom_call_api_version, legacy_backend_config=legacy_backend_config, attributes=_wrap_kwargs_hashable(kwargs), ) if multiple_results: if isinstance(result_shape_dtypes, tuple): return tuple(results) return results else: return results[0] return wrapped # ffi_call must support some small non-hashable input arguments, like np.arrays # and dicts, to support calling FFI targets with array inputs or user defined # structs. Since these arguments will eventually be embedded in the HLO as # dense attributes, we assume that they are small and hash by making an # immutable copy and hashing by value. def _wrap_kwargs_hashable(kwargs: dict[str, Any]) -> Sequence[tuple[str, Any]]: hashable_kwargs: list[tuple[str, Any]] = [] for k, v in sorted(kwargs.items()): if isinstance(v, np.ndarray): hashable_kwargs.append((k, HashableArray(v))) elif isinstance(v, dict): hashable_kwargs.append((k, FrozenDict(v))) else: try: hash(v) except TypeError as e: raise TypeError( f"Non-hashable keyword argument to ffi_call {k}: {v}") from e else: hashable_kwargs.append((k, v)) return tuple(hashable_kwargs) def _unwrap_kwargs_hashable(kwargs: Sequence[tuple[str, Any]]) -> dict[str, Any]: unwrapped_kwargs: dict[str, Any] = {} for k, v in kwargs: if isinstance(v, HashableArray): unwrapped_kwargs[k] = v.val elif isinstance(v, FrozenDict): unwrapped_kwargs[k] = v._d else: unwrapped_kwargs[k] = v return unwrapped_kwargs @dataclasses.dataclass(frozen=True)
TypeRegistration
python
getsentry__sentry
tests/sentry/notifications/platform/slack/test_provider.py
{ "start": 696, "end": 2167 }
class ____(TestCase): def test_default_renderer(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() rendered_template = template.render(data) renderer = SlackNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) rendererable = renderer.render(data=data, rendered_template=rendered_template) rendererable_dict = [block.to_dict() for block in rendererable.get("blocks", [])] assert rendererable_dict == [ {"text": {"text": "Mock Notification", "type": "plain_text"}, "type": "header"}, {"text": {"text": "test", "type": "mrkdwn"}, "type": "section"}, { "elements": [ { "text": {"emoji": True, "text": "Visit Sentry", "type": "plain_text"}, "type": "button", "url": "https://www.sentry.io", } ], "type": "actions", }, { "image_url": "https://raw.githubusercontent.com/knobiknows/all-the-bufo/main/all-the-bufo/bufo-pog.png", "alt_text": "Bufo Pog", "type": "image", }, { "elements": [{"text": "This is a mock footer", "type": "mrkdwn"}], "type": "context", }, ]
SlackRendererTest
python
getsentry__sentry
tests/sentry/grouping/test_enhancer_dart_flutter_javascript.py
{ "start": 314, "end": 744 }
class ____(TestCase): PLATFORM = "javascript" def setUp(self) -> None: super().setUp() self.enhancements = ENHANCEMENT_BASES["all-platforms:2023-01-11"] def apply_rules(self, frame: dict[str, str]) -> dict[str, Any]: frames = [frame] self.enhancements.apply_category_and_updated_in_app_to_frames(frames, self.PLATFORM, {}) return frames[0]
_BaseJavaScriptDartFlutterEnhancerTest
python
google__jax
tests/pallas/tpu_pallas_interpret_test.py
{ "start": 2079, "end": 2964 }
class ____: """Records grid points in the order in which they are procsessed.""" def __init__(self): self._grid_points: list[ProcessedGridPoint] = [] def __enter__(self): return self def __exit__(self, ty, value, traceback): ... def get_recorder(self) -> Callable[[tuple[np.int32, ...], np.int32], None]: def _recorder(grid_point, core_id): processed_grid_point = ProcessedGridPoint( tuple(int(coord) for coord in grid_point), int(core_id) ) self._grid_points.append(processed_grid_point) return _recorder @property def grid_points(self) -> list[ProcessedGridPoint]: return sorted(self._grid_points, key=lambda x: x.core_id) # TODO(jburnim): Figure out how to safely run different instance of TPU # interpret mode in parallel, and then remove this decorator. @jtu.thread_unsafe_test_class()
GridPointRecorderContext
python
great-expectations__great_expectations
great_expectations/metrics/column/values_not_match_regex_values.py
{ "start": 204, "end": 446 }
class ____(ColumnMetric[ColumnValuesNotMatchRegexValuesResult]): """Count of values in a column that do not match a regex""" name = "column_values.not_match_regex_values" regex: str limit: int = 20
ColumnValuesNotMatchRegexValues
python
PyCQA__pylint
tests/functional/s/slots_checks.py
{ "start": 510, "end": 550 }
class ____: __slots__ = ['a']
ThirdGood
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/ecs.py
{ "start": 2353, "end": 4520 }
class ____(AwsGenericHook): """ Interact with Amazon Elastic Container Service (ECS). Provide thin wrapper around :external+boto3:py:class:`boto3.client("ecs") <ECS.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` - `Amazon Elastic Container Service \ <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/Welcome.html>`__ """ def __init__(self, *args, **kwargs) -> None: kwargs["client_type"] = "ecs" super().__init__(*args, **kwargs) def get_cluster_state(self, cluster_name: str) -> str: """ Get ECS Cluster state. .. seealso:: - :external+boto3:py:meth:`ECS.Client.describe_clusters` :param cluster_name: ECS Cluster name or full cluster Amazon Resource Name (ARN) entry. """ return self.conn.describe_clusters(clusters=[cluster_name])["clusters"][0]["status"] def get_task_definition_state(self, task_definition: str) -> str: """ Get ECS Task Definition state. .. seealso:: - :external+boto3:py:meth:`ECS.Client.describe_task_definition` :param task_definition: The family for the latest ACTIVE revision, family and revision ( family:revision ) for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe. """ return self.conn.describe_task_definition(taskDefinition=task_definition)["taskDefinition"]["status"] def get_task_state(self, cluster, task) -> str: """ Get ECS Task state. .. seealso:: - :external+boto3:py:meth:`ECS.Client.describe_tasks` :param cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task or tasks to describe. :param task: Task ID or full ARN entry. """ return self.conn.describe_tasks(cluster=cluster, tasks=[task])["tasks"][0]["lastStatus"] @runtime_checkable
EcsHook
python
pytorch__pytorch
test/distributed/test_store.py
{ "start": 38718, "end": 40003 }
class ____(TestCase): def test_client_connect(self) -> None: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("localhost", 0)) port = sock.getsockname()[1] def listen() -> None: sock.listen() conn, _ = sock.accept() # VALIDATE # 0x3C85F7CE self.assertEqual(conn.recv(5), b"\x00\xce\xf7\x85\x3c") # PING data = conn.recv(5) self.assertEqual(data[0], 13) nonce = struct.unpack("i", data[1:])[0] self.assertEqual(nonce, os.getpid()) # send PING nonce response conn.sendall(data[1:]) conn.close() thread = threading.Thread(target=listen) thread.start() dist.TCPStore( host_name="localhost", port=port, world_size=2, is_master=False, timeout=timedelta(seconds=2), wait_for_workers=False, ) thread.join() if __name__ == "__main__": if device_type != "cpu": assert not torch.get_device_module()._initialized, ( f"test_distributed must not have initialized {device_type} context on main process" ) run_tests()
TestClientProtocol
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 452112, "end": 454885 }
class ____(Request): """ Move tasks to a project :param ids: Tasks to move :type ids: Sequence[str] :param project: Target project ID. If not provided, `project_name` must be provided. Use null for the root project :type project: str :param project_name: Target project name. If provided and a project with this name does not exist, a new project will be created. If not provided, `project` must be provided. :type project_name: str """ _service = "tasks" _action = "move" _version = "2.23" _schema = { "definitions": {}, "properties": { "ids": { "description": "Tasks to move", "items": {"type": "string"}, "type": "array", }, "project": { "description": ( "Target project ID. If not provided, `project_name` must be provided. Use null for the root project" ), "type": "string", }, "project_name": { "description": ( "Target project name. If provided and a project with this name does not exist, a new project will" " be created. If not provided, `project` must be provided." ), "type": "string", }, }, "required": ["ids"], "type": "object", } def __init__(self, ids, project=None, project_name=None, **kwargs): super(MoveRequest, self).__init__(**kwargs) self.ids = ids self.project = project self.project_name = project_name @schema_property("ids") def ids(self): return self._property_ids @ids.setter def ids(self, value): if value is None: self._property_ids = None return self.assert_isinstance(value, "ids", (list, tuple)) self.assert_isinstance(value, "ids", six.string_types, is_array=True) self._property_ids = value @schema_property("project") def project(self): return self._property_project @project.setter def project(self, value): if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("project_name") def project_name(self): return self._property_project_name @project_name.setter def project_name(self, value): if value is None: self._property_project_name = None return self.assert_isinstance(value, "project_name", six.string_types) self._property_project_name = value
MoveRequest
python
scipy__scipy
benchmarks/benchmarks/sparse_linalg_solve.py
{ "start": 842, "end": 1674 }
class ____(Benchmark): params = [ [4, 6, 10, 16, 25, 40, 64, 100], ['dense', 'spsolve', 'cg', 'minres', 'gmres', 'lgmres', 'gcrotmk', 'tfqmr'] ] mapping = {'spsolve': spsolve, 'cg': cg, 'minres': minres, 'gmres': gmres, 'lgmres': lgmres, 'gcrotmk': gcrotmk, 'tfqmr': tfqmr} param_names = ['(n,n)', 'solver'] def setup(self, n, solver): if solver == 'dense' and n >= 25: raise NotImplementedError() self.b = np.ones(n*n) self.P_sparse = _create_sparse_poisson2d(n) if solver == 'dense': self.P_dense = self.P_sparse.toarray() def time_solve(self, n, solver): if solver == 'dense': linalg.solve(self.P_dense, self.b) else: self.mapping[solver](self.P_sparse, self.b)
Bench
python
pypa__setuptools
setuptools/tests/test_egg_info.py
{ "start": 43802, "end": 44941 }
class ____: def test_invalid_entry_point(self, tmpdir_cwd, env): dist = Distribution({"name": "foo", "version": "0.0.1"}) dist.entry_points = {"foo": "foo = invalid-identifier:foo"} cmd = dist.get_command_obj("egg_info") expected_msg = r"(Invalid object reference|Problems to parse)" with pytest.raises((errors.OptionError, ValueError), match=expected_msg) as ex: write_entries(cmd, "entry_points", "entry_points.txt") assert "ensure entry-point follows the spec" in ex.value.args[0] assert "invalid-identifier" in str(ex.value) def test_valid_entry_point(self, tmpdir_cwd, env): dist = Distribution({"name": "foo", "version": "0.0.1"}) dist.entry_points = { "abc": "foo = bar:baz", "def": ["faa = bor:boz"], } cmd = dist.get_command_obj("egg_info") write_entries(cmd, "entry_points", "entry_points.txt") content = Path("entry_points.txt").read_text(encoding="utf-8") assert "[abc]\nfoo = bar:baz\n" in content assert "[def]\nfaa = bor:boz\n" in content
TestWriteEntries
python
sympy__sympy
sympy/functions/special/mathieu_functions.py
{ "start": 551, "end": 2028 }
class ____(MathieuBase): r""" The Mathieu Sine function $S(a,q,z)$. Explanation =========== This function is one solution of the Mathieu differential equation: .. math :: y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0 The other solution is the Mathieu Cosine function. Examples ======== >>> from sympy import diff, mathieus >>> from sympy.abc import a, q, z >>> mathieus(a, q, z) mathieus(a, q, z) >>> mathieus(a, 0, z) sin(sqrt(a)*z) >>> diff(mathieus(a, q, z), z) mathieusprime(a, q, z) See Also ======== mathieuc: Mathieu cosine function. mathieusprime: Derivative of Mathieu sine function. mathieucprime: Derivative of Mathieu cosine function. References ========== .. [1] https://en.wikipedia.org/wiki/Mathieu_function .. [2] https://dlmf.nist.gov/28 .. [3] https://mathworld.wolfram.com/MathieuFunction.html .. [4] https://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuS/ """ def fdiff(self, argindex=1): if argindex == 3: a, q, z = self.args return mathieusprime(a, q, z) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, a, q, z): if q.is_Number and q.is_zero: return sin(sqrt(a)*z) # Try to pull out factors of -1 if z.could_extract_minus_sign(): return -cls(a, q, -z)
mathieus
python
realpython__materials
top-python-game-engines/adventurelib/adventurelib_game_rooms.py
{ "start": 280, "end": 6304 }
class ____(adv.Room): def __init__(self, description: str): super().__init__(description) # All areas can have locked exits self.locked_exits = { "north": False, "south": False, "east": False, "west": False, } # All areas can have items in them self.items = adv.Bag() # All areas can have characters in them self.characters = adv.Bag() # All areas may have been visited already # If so, you can print a shorter description self.visited = False # Which means each area needs a shorter description self.short_desc = "" # Each area also has a very short title for the prompt self.title = "" # Your home home = GameArea( """ You wake as the sun streams in through the single window into your small room. You lie on your feather bed which hugs the north wall, while the remains of last night's fire smolders in the center of the room. Remembering last night's discussion with the council, you throw back your blanket and rise from your comfortable bed. Cold water awaits you as you splash away the night's sleep, grab an apple to eat, and prepare for the day. """ ) home.title = "Home" home.short_desc = "This is your home." # Hamlet hamlet = GameArea( """ From the center of your small hamlet, you can see every other home. It doesn't really even have an official name --- folks around here just call it Home. The council awaits you as you approach. Elder Barron beckons you as you exit your home. """ ) hamlet.title = "Hamlet" hamlet.short_desc = "You are in the hamlet." # Fork in road fork = GameArea( """ As you leave your hamlet, you think about how unprepared you really are. Your lack of experience and pitiful equipment are certainly no match for whatever has been stealing the villages livestock. As you travel, you come across a fork in the path. The path of the livestock thief continues east. However, you know the village of Dunhaven lies to the west, where you may get some additional help. """ ) fork.title = "Fork in road" fork.short_desc = "You are at a fork in the road." # Village of Dunhaven village = GameArea( """ A short trek up the well-worn path brings you the village of Dunhaven. Larger than your humble Home, Dunhaven sits at the end of a supply route from the capitol. As such, it has amenities and capabilities not found in the smaller farming communities. As you approach, you hear the clang-clang of hammer on anvil, and inhale the unmistakable smell of the coal-fed fire of a blacksmith shop to your south. """ ) village.title = "Village of Dunhaven" village.short_desc = "You are in the village of Dunhaven." # Blacksmith shop blacksmith_shop = GameArea( """ As you approach the blacksmith, the sounds of the hammer become clearer and clearer. Passing the front door, you head towards the sound of the blacksmith, and find her busy at the furnace. """ ) blacksmith_shop.title = "Blacksmith Shop" blacksmith_shop.short_desc = "You are in the blacksmith shop." # Side path away from fork side_path = GameArea( """ The path leads away from the fork to Dunhaven. Fresh tracks of something big, dragging something behind it, lead away to the south. """ ) side_path.title = "Side path" side_path.short_desc = "You are standing on a side path." # Wizard's Hut wizard_hut = GameArea( """ The path opens into a shaded glen. A small stream wanders down the hills to the east and past an unassuming hut. In front of the hut, the local wizard Trent sits smoking a long clay pipe. """ ) wizard_hut.title = "Wizard's Hut" wizard_hut.short_desc = "You are at the wizard's hut." # Cave mouth cave_mouth = GameArea( """ The path from Trent's hut follows the stream for a while before turning south away from the water. The trees begin closing overhead, blocking the sun and lending a chill to the air as you continue. The path finally terminates at the opening of a large cave. The tracks you have been following mix and mingle with others, both coming and going, but all the same. Whatever has been stealing your neighbor's livestock lives here, and comes and goes frequently. """ ) cave_mouth.title = "Cave Mouth" cave_mouth.short_desc = "You are at the mouth of large cave." # Cave of the Giant giant_cave = GameArea( """ You take a few tentative steps into the cave. It feels much warmer and more humid than the cold sunless forest air outside. A steady drip of water from the rocks is the only sound for a while. You begin to make out a faint light ahead. You hug the wall and press on, as the light becomes brighter. You finally enter a chamber at least 20 meters across, with a fire blazing in the center. Cages line one wall, some empty, but others containing cows and sheep stolen from you neighbors. Opposite them are piles of the bones of the creatures unlucky enough to have already been devoured. As you look around, you become aware of another presence in the room. """ ) giant_cave.title = "Cave of the Giant" giant_cave.short_desc = "You are in the giant's cave." # Set up the paths between areas home.south = hamlet hamlet.south = fork fork.west = village fork.east = side_path village.south = blacksmith_shop side_path.south = wizard_hut wizard_hut.west = cave_mouth cave_mouth.south = giant_cave # Lock some exits, since you can't leave until something else happens hamlet.locked_exits["south"] = True wizard_hut.locked_exits["west"] = True # Place items in different areas # These are just for flavor home.items.add(adventurelib_game_items.apple) fork.items.add(adventurelib_game_items.cloak) cave_mouth.items.add(adventurelib_game_items.slug) # Place characters where they should be hamlet.characters.add(adventurelib_game_characters.elder_barron) blacksmith_shop.characters.add(adventurelib_game_characters.blacksmith) wizard_hut.characters.add(adventurelib_game_characters.wizard_trent) giant_cave.characters.add(adventurelib_game_characters.giant)
GameArea
python
nedbat__coveragepy
tests/test_coverage.py
{ "start": 371, "end": 2259 }
class ____(CoverageTest): """Make sure our complex self.check_coverage method works.""" def test_successful_coverage(self) -> None: # The simplest run possible. self.check_coverage( """\ a = 1 b = 2 """, lines=[1, 2], ) # You can specify missing lines. self.check_coverage( """\ a = 1 if a == 2: a = 3 """, lines=[1, 2, 3], missing="3", ) def test_failed_coverage(self) -> None: # If the lines are wrong, the message shows right and wrong. with pytest.raises(AssertionError, match=r"\[1, 2] != \[1]"): self.check_coverage( """\ a = 1 b = 2 """, lines=[1], ) # If the missing lines are wrong, the message shows right and wrong. with pytest.raises(AssertionError, match=r"'3' != '37'"): self.check_coverage( """\ a = 1 if a == 2: a = 3 """, lines=[1, 2, 3], missing="37", ) def test_exceptions_really_fail(self) -> None: # An assert in the checked code will really raise up to us. with pytest.raises(AssertionError, match="This is bad"): self.check_coverage( """\ a = 1 assert a == 99, "This is bad" """, ) # Other exceptions too. with pytest.raises(ZeroDivisionError, match="division"): self.check_coverage( """\ a = 1 assert a == 1, "This is good" a/0 """, )
TestCoverageTest
python
PyCQA__pylint
pylint/reporters/text.py
{ "start": 5400, "end": 5767 }
class ____(TextReporter): """Reports messages and layouts in plain text without a module header.""" name = "no-header" def handle_message(self, msg: Message) -> None: """Write message(s) without module header.""" if msg.module not in self._modules: self._modules.add(msg.module) self.write_message(msg)
NoHeaderReporter
python
pymupdf__PyMuPDF
src/table.py
{ "start": 49501, "end": 49539 }
class ____(CellGroup): pass
TableRow
python
huggingface__transformers
src/transformers/models/granitemoe/modular_granitemoe.py
{ "start": 1687, "end": 1754 }
class ____(JetMoeParallelExperts): pass
GraniteMoeParallelExperts
python
walkccc__LeetCode
solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py
{ "start": 220, "end": 2230 }
class ____: # Similar to 2736. Maximum Sum Queries def leftmostBuildingQueries( self, heights: list[int], queries: list[list[int]], ) -> list[int]: ans = [-1] * len(queries) # Store indices (heightsIndex) of heights with heights[heightsIndex] in # descending order. stack = [] # Iterate through queries and heights simultaneously. heightsIndex = len(heights) - 1 for queryIndex, a, b in sorted([IndexedQuery(i, min(a, b), max(a, b)) for i, (a, b) in enumerate(queries)], key=lambda x: -x.b): if a == b or heights[a] < heights[b]: # 1. Alice and Bob are already in the same index (a == b) or # 2. Alice can jump from a -> b (heights[a] < heights[b]). ans[queryIndex] = b else: # Now, a < b and heights[a] >= heights[b]. # Gradually add heights with an index > b to the monotonic stack. while heightsIndex > b: # heights[heightsIndex] is a better candidate, given that # heightsIndex is smaller than the indices in the stack and # heights[heightsIndex] is larger or equal to the heights mapped in # the stack. while stack and heights[stack[-1]] <= heights[heightsIndex]: stack.pop() stack.append(heightsIndex) heightsIndex -= 1 # Binary search to find the smallest index j such that j > b and # heights[j] > heights[a], thereby ensuring heights[j] > heights[b]. j = self._lastGreater(stack, a, heights) if j != -1: ans[queryIndex] = stack[j] return ans def _lastGreater(self, A: list[int], target: int, heights: list[int]): """ Returns the last index i in A s.t. heights[A.get(i)] is > heights[target]. """ l = -1 r = len(A) - 1 while l < r: m = (l + r + 1) // 2 if heights[A[m]] > heights[target]: l = m else: r = m - 1 return l
Solution
python
scipy__scipy
scipy/fftpack/tests/test_basic.py
{ "start": 4825, "end": 7353 }
class ____: def setup_method(self): np.random.seed(1234) def test_definition(self): x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt) y = ifft(x) y1 = direct_idft(x) assert_equal(y.dtype, self.cdt) assert_array_almost_equal(y,y1) x = np.array([1,2,3,4+0j,5], self.cdt) assert_array_almost_equal(ifft(x),direct_idft(x)) def test_definition_real(self): x = np.array([1,2,3,4,1,2,3,4], self.rdt) y = ifft(x) assert_equal(y.dtype, self.cdt) y1 = direct_idft(x) assert_array_almost_equal(y,y1) x = np.array([1,2,3,4,5], dtype=self.rdt) assert_equal(y.dtype, self.cdt) assert_array_almost_equal(ifft(x),direct_idft(x)) def test_random_complex(self): for size in [1,51,111,100,200,64,128,256,1024]: x = random([size]).astype(self.cdt) x = random([size]).astype(self.cdt) + 1j*x y1 = ifft(fft(x)) y2 = fft(ifft(x)) assert_equal(y1.dtype, self.cdt) assert_equal(y2.dtype, self.cdt) assert_array_almost_equal(y1, x) assert_array_almost_equal(y2, x) def test_random_real(self): for size in [1,51,111,100,200,64,128,256,1024]: x = random([size]).astype(self.rdt) y1 = ifft(fft(x)) y2 = fft(ifft(x)) assert_equal(y1.dtype, self.cdt) assert_equal(y2.dtype, self.cdt) assert_array_almost_equal(y1, x) assert_array_almost_equal(y2, x) def test_size_accuracy(self): # Sanity check for the accuracy for prime and non-prime sized inputs if self.rdt == np.float32: rtol = 1e-5 elif self.rdt == np.float64: rtol = 1e-10 for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES: np.random.seed(1234) x = np.random.rand(size).astype(self.rdt) y = ifft(fft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) y = fft(ifft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) x = (x + 1j*np.random.rand(size)).astype(self.cdt) y = ifft(fft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) y = fft(ifft(x)) _assert_close_in_norm(x, y, rtol, size, self.rdt) def test_invalid_sizes(self): assert_raises(ValueError, ifft, []) assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
_TestIFFTBase
python
doocs__leetcode
solution/0200-0299/0287.Find the Duplicate Number/Solution.py
{ "start": 0, "end": 208 }
class ____: def findDuplicate(self, nums: List[int]) -> int: def f(x: int) -> bool: return sum(v <= x for v in nums) > x return bisect_left(range(len(nums)), True, key=f)
Solution
python
openai__openai-python
src/openai/resources/realtime/calls.py
{ "start": 16063, "end": 30690 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCallsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncCallsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncCallsWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncCallsWithStreamingResponse(self) async def create( self, *, sdp: str, session: RealtimeSessionCreateRequestParam | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> _legacy_response.HttpxBinaryResponseContent: """ Create a new Realtime API call over WebRTC and receive the SDP answer needed to complete the peer connection. Args: sdp: WebRTC Session Description Protocol (SDP) offer generated by the caller. session: Realtime session object configuration. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = {"Accept": "application/sdp", **(extra_headers or {})} return await self._post( "/realtime/calls", body=await async_maybe_transform( { "sdp": sdp, "session": session, }, call_create_params.CallCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=_legacy_response.HttpxBinaryResponseContent, ) async def accept( self, call_id: str, *, type: Literal["realtime"], audio: RealtimeAudioConfigParam | Omit = omit, include: List[Literal["item.input_audio_transcription.logprobs"]] | Omit = omit, instructions: str | Omit = omit, max_output_tokens: Union[int, Literal["inf"]] | Omit = omit, model: Union[ str, Literal[ "gpt-realtime", "gpt-realtime-2025-08-28", "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-realtime-preview-2025-06-03", "gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17", "gpt-realtime-mini", "gpt-realtime-mini-2025-10-06", "gpt-audio-mini", "gpt-audio-mini-2025-10-06", ], ] | Omit = omit, output_modalities: List[Literal["text", "audio"]] | Omit = omit, prompt: Optional[ResponsePromptParam] | Omit = omit, tool_choice: RealtimeToolChoiceConfigParam | Omit = omit, tools: RealtimeToolsConfigParam | Omit = omit, tracing: Optional[RealtimeTracingConfigParam] | Omit = omit, truncation: RealtimeTruncationParam | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> None: """ Accept an incoming SIP call and configure the realtime session that will handle it. Args: type: The type of session to create. Always `realtime` for the Realtime API. audio: Configuration for input and output audio. include: Additional fields to include in server outputs. `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription. instructions: The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. "be extremely succinct", "act friendly", "here are examples of good responses") and on audio behavior (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior. Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session. max_output_tokens: Maximum number of output tokens for a single assistant response, inclusive of tool calls. Provide an integer between 1 and 4096 to limit output tokens, or `inf` for the maximum available tokens for a given model. Defaults to `inf`. model: The Realtime model used for this session. output_modalities: The set of modalities the model can respond with. It defaults to `["audio"]`, indicating that the model will respond with audio plus a transcript. `["text"]` can be used to make the model respond with text only. It is not possible to request both `text` and `audio` at the same time. prompt: Reference to a prompt template and its variables. [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts). tool_choice: How the model chooses tools. Provide one of the string modes or force a specific function/MCP tool. tools: Tools available to the model. tracing: Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). Set to null to disable tracing. Once tracing is enabled for a session, the configuration cannot be modified. `auto` will create a trace for the session with default values for the workflow name, group id, and metadata. truncation: When the number of tokens in a conversation exceeds the model's input token limit, the conversation be truncated, meaning messages (starting from the oldest) will not be included in the model's context. A 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before truncation occurs. Clients can configure truncation behavior to truncate with a lower max token limit, which is an effective way to control token usage and cost. Truncation will reduce the number of cached tokens on the next turn (busting the cache), since messages are dropped from the beginning of the context. However, clients can also configure truncation to retain messages up to a fraction of the maximum context size, which will reduce the need for future truncations and thus improve the cache rate. Truncation can be disabled entirely, which means the server will never truncate but would instead return an error if the conversation exceeds the model's input token limit. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_id: raise ValueError(f"Expected a non-empty value for `call_id` but received {call_id!r}") extra_headers = {"Accept": "*/*", **(extra_headers or {})} return await self._post( f"/realtime/calls/{call_id}/accept", body=await async_maybe_transform( { "type": type, "audio": audio, "include": include, "instructions": instructions, "max_output_tokens": max_output_tokens, "model": model, "output_modalities": output_modalities, "prompt": prompt, "tool_choice": tool_choice, "tools": tools, "tracing": tracing, "truncation": truncation, }, call_accept_params.CallAcceptParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=NoneType, ) async def hangup( self, call_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> None: """ End an active Realtime API call, whether it was initiated over SIP or WebRTC. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_id: raise ValueError(f"Expected a non-empty value for `call_id` but received {call_id!r}") extra_headers = {"Accept": "*/*", **(extra_headers or {})} return await self._post( f"/realtime/calls/{call_id}/hangup", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=NoneType, ) async def refer( self, call_id: str, *, target_uri: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> None: """ Transfer an active SIP call to a new destination using the SIP REFER verb. Args: target_uri: URI that should appear in the SIP Refer-To header. Supports values like `tel:+14155550123` or `sip:agent@example.com`. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_id: raise ValueError(f"Expected a non-empty value for `call_id` but received {call_id!r}") extra_headers = {"Accept": "*/*", **(extra_headers or {})} return await self._post( f"/realtime/calls/{call_id}/refer", body=await async_maybe_transform({"target_uri": target_uri}, call_refer_params.CallReferParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=NoneType, ) async def reject( self, call_id: str, *, status_code: int | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> None: """ Decline an incoming SIP call by returning a SIP status code to the caller. Args: status_code: SIP response code to send back to the caller. Defaults to `603` (Decline) when omitted. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not call_id: raise ValueError(f"Expected a non-empty value for `call_id` but received {call_id!r}") extra_headers = {"Accept": "*/*", **(extra_headers or {})} return await self._post( f"/realtime/calls/{call_id}/reject", body=await async_maybe_transform({"status_code": status_code}, call_reject_params.CallRejectParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=NoneType, )
AsyncCalls
python
pypa__pip
src/pip/_vendor/rich/logging.py
{ "start": 497, "end": 12468 }
class ____(Handler): """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns. The level is color coded, and the message is syntax highlighted. Note: Be careful when enabling console markup in log messages if you have configured logging for libraries not under your control. If a dependency writes messages containing square brackets, it may not produce the intended output. Args: level (Union[int, str], optional): Log level. Defaults to logging.NOTSET. console (:class:`~rich.console.Console`, optional): Optional console instance to write logs. Default will use a global console instance writing to stdout. show_time (bool, optional): Show a column for the time. Defaults to True. omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True. show_level (bool, optional): Show a column for the level. Defaults to True. show_path (bool, optional): Show the path to the original log call. Defaults to True. enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True. highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None. markup (bool, optional): Enable console markup in log messages. Defaults to False. rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False. tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None. tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88. tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None. tracebacks_theme (str, optional): Override pygments theme used in traceback. tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False. tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80. log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ". keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``. """ KEYWORDS: ClassVar[Optional[List[str]]] = [ "GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE", "PATCH", ] HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter def __init__( self, level: Union[int, str] = logging.NOTSET, console: Optional[Console] = None, *, show_time: bool = True, omit_repeated_times: bool = True, show_level: bool = True, show_path: bool = True, enable_link_path: bool = True, highlighter: Optional[Highlighter] = None, markup: bool = False, rich_tracebacks: bool = False, tracebacks_width: Optional[int] = None, tracebacks_code_width: Optional[int] = 88, tracebacks_extra_lines: int = 3, tracebacks_theme: Optional[str] = None, tracebacks_word_wrap: bool = True, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[Union[str, ModuleType]] = (), tracebacks_max_frames: int = 100, locals_max_length: int = 10, locals_max_string: int = 80, log_time_format: Union[str, FormatTimeCallable] = "[%x %X]", keywords: Optional[List[str]] = None, ) -> None: super().__init__(level=level) self.console = console or get_console() self.highlighter = highlighter or self.HIGHLIGHTER_CLASS() self._log_render = LogRender( show_time=show_time, show_level=show_level, show_path=show_path, time_format=log_time_format, omit_repeated_times=omit_repeated_times, level_width=None, ) self.enable_link_path = enable_link_path self.markup = markup self.rich_tracebacks = rich_tracebacks self.tracebacks_width = tracebacks_width self.tracebacks_extra_lines = tracebacks_extra_lines self.tracebacks_theme = tracebacks_theme self.tracebacks_word_wrap = tracebacks_word_wrap self.tracebacks_show_locals = tracebacks_show_locals self.tracebacks_suppress = tracebacks_suppress self.tracebacks_max_frames = tracebacks_max_frames self.tracebacks_code_width = tracebacks_code_width self.locals_max_length = locals_max_length self.locals_max_string = locals_max_string self.keywords = keywords def get_level_text(self, record: LogRecord) -> Text: """Get the level name from the record. Args: record (LogRecord): LogRecord instance. Returns: Text: A tuple of the style and level name. """ level_name = record.levelname level_text = Text.styled( level_name.ljust(8), f"logging.level.{level_name.lower()}" ) return level_text def emit(self, record: LogRecord) -> None: """Invoked by logging.""" message = self.format(record) traceback = None if ( self.rich_tracebacks and record.exc_info and record.exc_info != (None, None, None) ): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None traceback = Traceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, code_width=self.tracebacks_code_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, suppress=self.tracebacks_suppress, max_frames=self.tracebacks_max_frames, ) message = record.getMessage() if self.formatter: record.message = record.getMessage() formatter = self.formatter if hasattr(formatter, "usesTime") and formatter.usesTime(): record.asctime = formatter.formatTime(record, formatter.datefmt) message = formatter.formatMessage(record) message_renderable = self.render_message(record, message) log_renderable = self.render( record=record, traceback=traceback, message_renderable=message_renderable ) if isinstance(self.console.file, NullFile): # Handles pythonw, where stdout/stderr are null, and we return NullFile # instance from Console.file. In this case, we still want to make a log record # even though we won't be writing anything to a file. self.handleError(record) else: try: self.console.print(log_renderable) except Exception: self.handleError(record) def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable": """Render message text in to Text. Args: record (LogRecord): logging Record. message (str): String containing log message. Returns: ConsoleRenderable: Renderable to display log message. """ use_markup = getattr(record, "markup", self.markup) message_text = Text.from_markup(message) if use_markup else Text(message) highlighter = getattr(record, "highlighter", self.highlighter) if highlighter: message_text = highlighter(message_text) if self.keywords is None: self.keywords = self.KEYWORDS if self.keywords: message_text.highlight_words(self.keywords, "logging.keyword") return message_text def render( self, *, record: LogRecord, traceback: Optional[Traceback], message_renderable: "ConsoleRenderable", ) -> "ConsoleRenderable": """Render log for display. Args: record (LogRecord): logging Record. traceback (Optional[Traceback]): Traceback instance or None for no Traceback. message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents. Returns: ConsoleRenderable: Renderable to display log. """ path = Path(record.pathname).name level = self.get_level_text(record) time_format = None if self.formatter is None else self.formatter.datefmt log_time = datetime.fromtimestamp(record.created) log_renderable = self._log_render( self.console, [message_renderable] if not traceback else [message_renderable, traceback], log_time=log_time, time_format=time_format, level=level, path=path, line_no=record.lineno, link_path=record.pathname if self.enable_link_path else None, ) return log_renderable if __name__ == "__main__": # pragma: no cover from time import sleep FORMAT = "%(message)s" # FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)], ) log = logging.getLogger("rich") log.info("Server starting...") log.info("Listening on http://127.0.0.1:8080") sleep(1) log.info("GET /index.html 200 1298") log.info("GET /imgs/backgrounds/back1.jpg 200 54386") log.info("GET /css/styles.css 200 54386") log.warning("GET /favicon.ico 404 242") sleep(1) log.debug( "JSONRPC request\n--> %r\n<-- %r", { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", }, {"version": "1.1", "result": True, "error": None, "id": "194521489"}, ) log.debug( "Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer" ) log.error("Unable to find 'pomelo' in database!") log.info("POST /jsonrpc/ 200 65532") log.info("POST /admin/ 401 42234") log.warning("password was rejected for admin site.") def divide() -> None: number = 1 divisor = 0 foos = ["foo"] * 100 log.debug("in divide") try: number / divisor except: log.exception("An error of some kind occurred!") divide() sleep(1) log.critical("Out of memory!") log.info("Server exited with code=-1") log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
RichHandler
python
Textualize__textual
src/textual/css/query.py
{ "start": 1204, "end": 1284 }
class ____(QueryError): """Too many nodes matched the query."""
TooManyMatches
python
kubernetes-client__python
kubernetes/client/api/batch_api.py
{ "start": 543, "end": 5176 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_api_group(self, **kwargs): # noqa: E501 """get_api_group # noqa: E501 get information of a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_group(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1APIGroup If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.get_api_group_with_http_info(**kwargs) # noqa: E501 def get_api_group_with_http_info(self, **kwargs): # noqa: E501 """get_api_group # noqa: E501 get information of a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_group_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIGroup, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_group" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/batch/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIGroup', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
BatchApi
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 5842, "end": 5968 }
class ____(enum.IntEnum): ERROR = 1 WARNING = 2 INFO = 3 LOG = 4 @dataclasses.dataclass(frozen=True)
MessageType
python
spack__spack
lib/spack/spack/test/installer_tui.py
{ "start": 20722, "end": 22214 }
class ____: """Test behavior with different terminal sizes""" def test_small_terminal_truncation(self): """Test that output is truncated for small terminals""" status, _, fake_stdout = create_build_status(total=10, terminal_cols=80, terminal_rows=10) # Add more builds than can fit on screen add_mock_builds(status, 10) status.update() output = fake_stdout.getvalue() # Should contain "more..." message indicating truncation assert "more..." in output def test_large_terminal_no_truncation(self): """Test that all builds shown on large terminal""" status, _, fake_stdout = create_build_status(total=3, terminal_cols=120) add_mock_builds(status, 3) status.update() output = fake_stdout.getvalue() # Should not contain truncation message assert "more..." not in output # Should contain all package names for i in range(3): assert f"pkg{i}" in output def test_narrow_terminal_short_header(self): """Test that narrow terminals get shortened header""" status, _, fake_stdout = create_build_status(total=1, terminal_cols=40) add_mock_builds(status, 1) status.update() output = fake_stdout.getvalue() # Should not contain the full header with hints assert "filter" not in output # But should contain progress assert "Progress:" in output
TestTerminalSizes
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/GraphItem.py
{ "start": 228, "end": 5787 }
class ____(GraphicsObject): """A GraphItem displays graph information as a set of nodes connected by lines (as in 'graph theory', not 'graphics'). Useful for drawing networks, trees, etc. """ def __init__(self, **kwds): GraphicsObject.__init__(self) self.scatter = ScatterPlotItem() self.scatter.setParentItem(self) self.adjacency = None self.pos = None self.picture = None self.pen = 'default' self.setData(**kwds) def setData(self, **kwds): """ Change the data displayed by the graph. ============== ======================================================================= **Arguments:** pos (N,2) array of the positions of each node in the graph. adj (M,2) array of connection data. Each row contains indexes of two nodes that are connected or None to hide lines pen The pen to use when drawing lines between connected nodes. May be one of: * QPen * a single argument to pass to pg.mkPen * a record array of length M with fields (red, green, blue, alpha, width). Note that using this option may have a significant performance cost. * None (to disable connection drawing) * 'default' to use the default foreground color. symbolPen The pen(s) used for drawing nodes. symbolBrush The brush(es) used for drawing nodes. ``**opts`` All other keyword arguments are given to :func:`ScatterPlotItem.setData() <pyqtgraph.ScatterPlotItem.setData>` to affect the appearance of nodes (symbol, size, brush, etc.) ============== ======================================================================= """ if 'adj' in kwds: self.adjacency = kwds.pop('adj') if hasattr(self.adjacency, '__len__') and len(self.adjacency) == 0: self.adjacency = None elif self.adjacency is not None and self.adjacency.dtype.kind not in 'iu': raise Exception("adjacency must be None or an array of either int or unsigned type.") self._update() if 'pos' in kwds: self.pos = kwds['pos'] self._update() if 'pen' in kwds: self.setPen(kwds.pop('pen')) self._update() if 'symbolPen' in kwds: kwds['pen'] = kwds.pop('symbolPen') if 'symbolBrush' in kwds: kwds['brush'] = kwds.pop('symbolBrush') self.scatter.setData(**kwds) self.informViewBoundsChanged() def _update(self): self.picture = None self.prepareGeometryChange() self.update() def setPen(self, *args, **kwargs): """ Set the pen used to draw graph lines. May be: * None to disable line drawing * Record array with fields (red, green, blue, alpha, width) * Any set of arguments and keyword arguments accepted by :func:`mkPen <pyqtgraph.mkPen>`. * 'default' to use the default foreground color. """ if len(args) == 1 and len(kwargs) == 0: self.pen = args[0] else: self.pen = fn.mkPen(*args, **kwargs) self.picture = None self.update() def generatePicture(self): self.picture = QtGui.QPicture() if self.pen is None or self.pos is None or self.adjacency is None: return p = QtGui.QPainter(self.picture) try: pts = self.pos[self.adjacency] pen = self.pen if isinstance(pen, np.ndarray): lastPen = None for i in range(pts.shape[0]): pen = self.pen[i] if lastPen is None or np.any(pen != lastPen): lastPen = pen if pen.dtype.fields is None: p.setPen(fn.mkPen(color=(pen[0], pen[1], pen[2], pen[3]), width=1)) else: p.setPen(fn.mkPen(color=(pen['red'], pen['green'], pen['blue'], pen['alpha']), width=pen['width'])) p.drawLine(QtCore.QPointF(*pts[i][0]), QtCore.QPointF(*pts[i][1])) else: if pen == 'default': pen = getConfigOption('foreground') p.setPen(fn.mkPen(pen)) pts = pts.reshape((pts.shape[0]*pts.shape[1], pts.shape[2])) path = fn.arrayToQPath(x=pts[:,0], y=pts[:,1], connect='pairs') p.drawPath(path) finally: p.end() def paint(self, p, *args): if self.picture is None: self.generatePicture() if getConfigOption('antialias') is True: p.setRenderHint(p.RenderHint.Antialiasing) self.picture.play(p) def boundingRect(self): return self.scatter.boundingRect() def dataBounds(self, *args, **kwds): return self.scatter.dataBounds(*args, **kwds) def pixelPadding(self): return self.scatter.pixelPadding()
GraphItem
python
fluentpython__example-code
attic/operator/dispatch.py
{ "start": 140, "end": 295 }
class ____: def __add__(self, other): return self, other def __repr__(self): return '<{} object>'.format(type(self).__name__)
KnowsAdd
python
PyCQA__pylint
tests/functional/i/invalid/invalid_length/invalid_length_hint_returned.py
{ "start": 1001, "end": 1196 }
class ____: """ __length_hint__ returns node which does not have 'value' in AST """ def __length_hint__(self): # [invalid-length-hint-returned] return lambda: 3
ThirdBadLengthHint
python
altair-viz__altair
altair/datasets/_cache.py
{ "start": 9566, "end": 14438 }
class ____: """Opt-out caching of remote dataset requests.""" _ENV_VAR: ClassVar[LiteralString] = "ALTAIR_DATASETS_DIR" _XDG_CACHE: ClassVar[Path] = ( Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "altair" ).resolve() def __init__(self, reader: _SupportsScanMetadata, /) -> None: self._rd: _SupportsScanMetadata = reader def clear(self) -> None: """Delete all previously cached datasets.""" self._ensure_active() if self.is_empty(): return None ser = ( self._rd._scan_metadata() .select("sha", "suffix") .unique("sha") .select(nw.concat_str("sha", "suffix").alias("sha_suffix")) .collect() .get_column("sha_suffix") ) names = set[str](ser.to_list()) for fp in self: if fp.name in names: fp.unlink() def download_all(self) -> None: """ Download any missing datasets for latest version. Requires **30-50MB** of disk-space. """ stems = tuple(fp.stem for fp in self) predicates = (~(nw.col("sha").is_in(stems)),) if stems else () frame = ( self._rd._scan_metadata(*predicates, is_image=False) .select("sha", "suffix", "url") .unique("sha") .collect() ) if frame.is_empty(): print("Already downloaded all datasets") return None print(f"Downloading {len(frame)} missing datasets...") for meta in _iter_metadata(frame): self._download_one(meta["url"], self.path_meta(meta)) print("Finished downloads") return None def _maybe_download(self, meta: Metadata, /) -> Path: fp = self.path_meta(meta) return ( fp if (fp.exists() and fp.stat().st_size) else self._download_one(meta["url"], fp) ) def _download_one(self, url: str, fp: Path, /) -> Path: with self._rd._opener.open(url) as f: fp.touch() fp.write_bytes(f.read()) return fp @property def path(self) -> Path: """ Returns path to datasets cache. Defaults to (`XDG_CACHE_HOME`_):: "$XDG_CACHE_HOME/altair/" But can be configured using the environment variable:: "$ALTAIR_DATASETS_DIR" You can set this for the current session via:: from pathlib import Path from altair.datasets import load load.cache.path = Path.home() / ".altair_cache" load.cache.path.relative_to(Path.home()).as_posix() ".altair_cache" You can *later* disable caching via:: load.cache.path = None .. _XDG_CACHE_HOME: https://specifications.freedesktop.org/basedir-spec/latest/#variables """ self._ensure_active() fp = Path(usr) if (usr := os.environ.get(self._ENV_VAR)) else self._XDG_CACHE fp.mkdir(parents=True, exist_ok=True) return fp @path.setter def path(self, source: StrPath | None, /) -> None: if source is not None: os.environ[self._ENV_VAR] = str(Path(source).resolve()) else: os.environ[self._ENV_VAR] = "" def path_meta(self, meta: Metadata, /) -> Path: return self.path / (meta["sha"] + meta["suffix"]) def __iter__(self) -> Iterator[Path]: yield from self.path.iterdir() def __repr__(self) -> str: name = type(self).__name__ if self.is_not_active(): return f"{name}<UNSET>" else: return f"{name}<{self.path.as_posix()!r}>" def is_active(self) -> bool: return not self.is_not_active() def is_not_active(self) -> bool: return os.environ.get(self._ENV_VAR) == "" def is_empty(self) -> bool: """Cache is active, but no files are stored in ``self.path``.""" return next(iter(self), None) is None def _ensure_active(self) -> None: if self.is_not_active(): msg = ( f"Cache is unset.\n" f"To enable dataset caching, set the environment variable:\n" f" {self._ENV_VAR!r}\n\n" f"You can set this for the current session via:\n" f" from pathlib import Path\n" f" from altair.datasets import load\n\n" f" load.cache.path = Path.home() / '.altair_cache'" ) raise ValueError(msg) csv_cache: CsvCache def __getattr__(name): if name == "csv_cache": global csv_cache csv_cache = CsvCache() return csv_cache else: msg = f"module {__name__!r} has no attribute {name!r}" raise AttributeError(msg)
DatasetCache
python
tensorflow__tensorflow
tensorflow/tools/common/test_module2.py
{ "start": 743, "end": 851 }
class ____(object): def __init__(self): pass def __model_class1_method__(self): pass
ModuleClass2
python
python__mypy
mypy/traverser.py
{ "start": 28325, "end": 28681 }
class ____(FuncCollectorBase): def __init__(self) -> None: super().__init__() self.found = False def visit_yield_from_expr(self, o: YieldFromExpr) -> None: self.found = True def has_yield_from_expression(fdef: FuncBase) -> bool: seeker = YieldFromSeeker() fdef.accept(seeker) return seeker.found
YieldFromSeeker
python
ray-project__ray
python/ray/data/_internal/execution/operators/hash_shuffle.py
{ "start": 2153, "end": 4062 }
class ____(abc.ABC): """Interface for a stateful aggregation to be used by hash-based shuffling operators (inheriting from `HashShufflingOperatorBase`) and subsequent aggregation of the dataset. Any stateful aggregation has to adhere to the following protocol: - Individual input sequence(s) will be (hash-)partitioned into N partitions each. - Accepting individual partition shards: for any given partition (identified by partition-id) of the input sequence (identified by input-id) aggregation will be receiving corresponding partition shards as the input sequence is being shuffled. - Upon completion of the shuffling (ie once whole sequence is shuffled) aggregation will receive a call to finalize the aggregation at which point it's expected to produce and return resulting block. - After successful finalization aggregation's `clear` method will be invoked to clear any accumulated state to release resources. """ def __init__(self, aggregator_id: int): self._aggregator_id = aggregator_id def accept(self, input_seq_id: int, partition_id: int, partition_shard: Block): """Accepts corresponding partition shard for the partition identified by - Input sequence id - Partition id """ raise NotImplementedError() def finalize(self, partition_id: int) -> Block: """Finalizes aggregation of partitions (identified by partition-id) from all input sequences returning resulting block. """ raise NotImplementedError() def clear(self, partition_id: int): """Clears out any accumulated state for provided partition-id. NOTE: This method is invoked after aggregation is finalized for the given partition.""" raise NotImplementedError()
StatefulShuffleAggregation
python
pytorch__pytorch
test/inductor/test_flex_decoding.py
{ "start": 7643, "end": 68448 }
class ____(InductorTestCase): def setUp(self): super().setUp() self.test_inference_only = False if test_device[0] == "cpu": if LONG_COMPILATION_ON_CPU: self.skipTest( "skip UT for CPU due to long compilation time found in CI" ) self.test_inference_only = True def _check_equal( self, golden_out: torch.Tensor, ref_out: torch.Tensor, compiled_out: torch.Tensor, fudge_factor: float, tensor_name: Optional[str] = None, ): compiled_error = (golden_out - compiled_out).abs().mean() ref_error = (golden_out - ref_out).abs().mean() if torch.isnan(compiled_error).any() and not torch.isnan(ref_error).any(): self.assertTrue(False, "Output/Grad with NaN") if ref_error < (1e-4) * golden_out.abs().mean(): print( "very small ref error of ", (ref_error.to(torch.float64) * (1e5) / golden_out.abs().mean()), ) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close( golden_out.to(dtype=compiled_out.dtype), compiled_out, atol=tolerance.atol, rtol=tolerance.rtol, ) elif compiled_error > ref_error * fudge_factor: name = tensor_name if tensor_name is not None else "" msg = f"{name} Compiled error {compiled_error} is greater than ref error {ref_error} by more than {fudge_factor}X." self.assertTrue(False, msg) def _check_out( self, golden_out: torch.Tensor, ref_out: torch.Tensor, compiled_out: torch.Tensor, ): dtype = ref_out.dtype with torch.no_grad(): # Note, it seems like we really are less accurate than the float32 # computation, likely due to the online softmax if dtype == torch.float32: fudge_factor = 10.0 else: fudge_factor = 1.1 # Checkout output self._check_equal(golden_out, ref_out, compiled_out, fudge_factor, "Out") def run_test( self, score_mod: Optional[Callable] = None, dtype: torch.dtype = torch.float16, Q_B: int = B, Q_H: int = Hq, Q_S: int = 1, Q_D: int = D, KV_B: int = B, KV_H: int = Hkv, KV_S: int = S, V_D: int = D, block_mask: Optional[BlockMask] = None, device="cuda", kernel_options=None, ): assert score_mod is not None or block_mask is not None, ( "Must provide score_mod or block_mask" ) assert Q_H % KV_H == 0 if device == "cpu" and dtype is torch.float16: dtype = torch.float32 q = torch.randn( (Q_B, Q_H, Q_S, Q_D), dtype=dtype, device=device, requires_grad=not self.test_inference_only, ) k = torch.randn( (KV_B, KV_H, KV_S, Q_D), dtype=dtype, device=device, requires_grad=not self.test_inference_only, ) v = torch.randn( (KV_B, KV_H, KV_S, V_D), dtype=dtype, device=device, requires_grad=not self.test_inference_only, ) q_ref, k_ref, v_ref = query_key_value_clones(q, k, v) q_gold, k_gold, v_gold = query_key_value_clones(q, k, v, torch.float64) sdpa_partial = create_attention( score_mod, block_mask, enable_gqa=(Q_H != KV_H), kernel_options=kernel_options, ) compiled_sdpa = torch.compile(sdpa_partial) if not self.test_inference_only: golden_out, gold_lse = sdpa_partial(q_gold, k_gold, v_gold, return_lse=True) ref_out, ref_lse = sdpa_partial(q_ref, k_ref, v_ref, return_lse=True) compiled_out, compiled_lse = compiled_sdpa(q, k, v, return_lse=True) self._check_out( gold_lse, ref_lse, compiled_lse, ) else: golden_out = sdpa_partial(q_gold, k_gold, v_gold, return_lse=False) ref_out = sdpa_partial(q_ref, k_ref, v_ref, return_lse=False) compiled_out = compiled_sdpa(q, k, v, return_lse=False) self._check_out( golden_out, ref_out, compiled_out, ) def run_test_with_call( self, sdpa_call: Callable, golden_call: Optional[Callable] = None, dtype: torch.dtype = torch.float16, Q_B: int = B, Q_H: int = Hq, Q_S: int = 1, Q_D: int = D, KV_B: int = B, KV_H: int = Hkv, KV_S: int = S, V_D: int = D, device="cuda", ): if not golden_call: golden_call = sdpa_call if device == "cpu" and dtype is torch.float16: dtype = torch.float32 q = torch.randn( (Q_B, KV_H, Q_S, Q_D), dtype=dtype, device=device, requires_grad=False, ) k = torch.randn( (KV_B, KV_H, KV_S, Q_D), dtype=dtype, device=device, requires_grad=False, ) v = torch.randn( (KV_B, KV_H, KV_S, V_D), dtype=dtype, device=device, requires_grad=False, ) q_ref, k_ref, v_ref = query_key_value_clones(q, k, v) q_gold, k_gold, v_gold = query_key_value_clones(q, k, v, torch.float64) compiled_sdpa = torch.compile(sdpa_call) golden_out = golden_call(q_gold, k_gold, v_gold) ref_out = golden_call(q_ref, k_ref, v_ref) compiled_out = compiled_sdpa(q, k, v) self._check_out( golden_out, ref_out, compiled_out, ) def preprocess_paged_attention( self, score_mod: Optional[Callable], q: Tensor, k: Tensor, v: Tensor, block_mask, dtype: torch.dtype = torch.float16, page_size: int = 128, device="cuda", ): assert block_mask is not None, "Must provide block_mask" if device == "cpu" and dtype is torch.float16: dtype = torch.float32 Q_B, Q_H, Q_S, _ = q.shape KV_B, KV_H, KV_S, QK_D = k.shape _, _, _, V_D = v.shape # test with different batch size max_batch_size = max(Q_B, KV_B) + 3 n_pages = (KV_S + page_size - 1) // page_size * max_batch_size # allocate cache MAX_CACHED_SEQ_LEN = n_pages * page_size k_cache = torch.zeros( 1, KV_H, MAX_CACHED_SEQ_LEN, QK_D, device=device, dtype=dtype, ) v_cache = torch.zeros( 1, KV_H, MAX_CACHED_SEQ_LEN, V_D, device=device, dtype=dtype, ) # "randomly" initialize the page table paged_attention = PagedAttention( n_pages, page_size, max_batch_size, device=device ) batch_reserve( paged_attention, torch.tensor([KV_S // 4, KV_S // 2, KV_S // 4, KV_S // 3], device=device), ) batch_reserve( paged_attention, torch.tensor([KV_S // 4, KV_S // 2, KV_S // 2, KV_S // 2], device=device), ) batch_reserve( paged_attention, torch.tensor([KV_S // 2, KV_S, KV_S // 2, KV_S], device=device), ) batch_reserve( paged_attention, torch.tensor([KV_S, KV_S, KV_S, KV_S], device=device) ) # update cache with k and v input_pos = ( torch.arange(KV_S, device=device, dtype=torch.int32) .unsqueeze(0) .expand(KV_B, KV_S) ) batch_idx = torch.arange(KV_B, device=device, dtype=torch.int32) paged_attention.assign(batch_idx, input_pos, k, v, k_cache, v_cache) # convert block mask and score mod kv_len_tensor = torch.full((KV_B,), KV_S, device=device, dtype=torch.int64) converted_block_mask = paged_attention.convert_logical_block_mask( block_mask, kv_len=kv_len_tensor ) converted_score_mod = paged_attention.get_score_mod( score_mod, kv_len=kv_len_tensor ) return k_cache, v_cache, converted_block_mask, converted_score_mod def run_paged_attention( self, score_mod: Optional[Callable], q: Tensor, k: Tensor, v: Tensor, dtype: torch.dtype = torch.float16, block_mask: Optional[BlockMask] = None, device="cuda", ): Q_B, Q_H, KV_H = q.shape[0], q.shape[1], k.shape[1] if device == "cpu" and dtype is torch.float16: dtype = torch.float32 if block_mask is None: block_mask = create_block_mask(noop_mask, Q_B, 1, 1, S, device=device) ( k_cache, v_cache, converted_block_mask, converted_score_mod, ) = self.preprocess_paged_attention( score_mod, q, k, v, block_mask, dtype, block_mask.BLOCK_SIZE[1], device ) compiled_sdpa = torch.compile(flex_attention) # compute if not self.test_inference_only: compiled_out, compiled_lse = compiled_sdpa( q, k_cache, v_cache, return_lse=True, block_mask=converted_block_mask, score_mod=converted_score_mod, enable_gqa=(Q_H != KV_H), ) else: compiled_lse = None compiled_out = compiled_sdpa( q, k_cache, v_cache, return_lse=False, block_mask=converted_block_mask, score_mod=converted_score_mod, enable_gqa=(Q_H != KV_H), ) return compiled_out, compiled_lse def run_test_with_paged_attention( self, score_mod: Optional[Callable], dtype: torch.dtype = torch.float16, Q_B: int = B, Q_H: int = Hq, Q_S: int = 1, QK_D: int = D, KV_B: int = B, KV_H: int = Hkv, KV_S: int = S, V_D: int = D, block_mask: Optional[BlockMask] = None, device="cuda", ): assert Q_H % KV_H == 0 if device == "cpu" and dtype is torch.float16: dtype = torch.float32 q = torch.randn( (Q_B, Q_H, Q_S, QK_D), dtype=dtype, device=device, requires_grad=False, ) k = torch.randn( (KV_B, KV_H, KV_S, QK_D), dtype=dtype, device=device, requires_grad=False, ) v = torch.randn( (KV_B, KV_H, KV_S, V_D), dtype=dtype, device=device, requires_grad=False, ) q_ref, k_ref, v_ref = query_key_value_clones(q, k, v) q_gold, k_gold, v_gold = query_key_value_clones(q, k, v, torch.float64) if block_mask is None: block_mask = create_block_mask(noop_mask, Q_B, 1, 1, KV_S, device=device) sdpa_partial = create_attention(score_mod, block_mask, enable_gqa=(Q_H != KV_H)) golden_out, gold_lse = sdpa_partial(q_gold, k_gold, v_gold, return_lse=True) ref_out, ref_lse = sdpa_partial(q_ref, k_ref, v_ref, return_lse=True) compiled_out, compiled_lse = self.run_paged_attention( score_mod, q, k, v, dtype, block_mask, device ) self._check_out( golden_out, ref_out, compiled_out, ) if not self.test_inference_only: self._check_out( gold_lse, ref_lse, compiled_lse, ) def run_test_with_call_paged_attention( self, score_mod: Optional[Callable], mask_mod: Optional[Callable], sdpa_mask: Tensor, dtype: torch.dtype = torch.float16, Q_B: int = B, Q_H: int = Hq, Q_S: int = 1, Q_D: int = D, KV_B: int = B, KV_H: int = Hkv, KV_S: int = S, V_D: int = D, device="cuda", ): if device == "cpu" and dtype is torch.float16: dtype = torch.float32 q = torch.randn( (Q_B, KV_H, Q_S * (Q_H // KV_H), Q_D), dtype=dtype, device=device, requires_grad=False, ) k = torch.randn( (KV_B, KV_H, KV_S, Q_D), dtype=dtype, device=device, requires_grad=False, ) v = torch.randn( (KV_B, KV_H, KV_S, V_D), dtype=dtype, device=device, requires_grad=False, ) q_ref, k_ref, v_ref = query_key_value_clones(q, k, v) q_gold, k_gold, v_gold = query_key_value_clones(q, k, v, torch.float64) golden_call = functools.partial( torch.nn.functional.scaled_dot_product_attention, attn_mask=sdpa_mask ) golden_out = golden_call(q_gold, k_gold, v_gold) ref_out = golden_call(q_ref, k_ref, v_ref) if mask_mod is not None: block_mask = create_block_mask(mask_mod, Q_B, 1, Q_S, KV_S, device=device) else: block_mask = create_block_mask(noop_mask, Q_B, 1, Q_S, KV_S, device=device) compiled_out, _ = self.run_paged_attention( score_mod, q, k, v, dtype, block_mask, device ) self._check_out( golden_out, ref_out, compiled_out, ) @supported_platform @expectedFailure # tl.dot does not support embedding size less than 16 @unittest.skipIf(SKIP_UT_ON_CPU, "Skip on CPU as not supported") @common_utils.parametrize("dtype", test_dtypes_fast) def test_bw_decoding_fails(self, device, dtype): make_kv = functools.partial( torch.randn, (2, 2, 128, 4), dtype=dtype, device=device, requires_grad=True, ) make_q = functools.partial( torch.randn, (2, 2, 8, 4), dtype=dtype, device=device, requires_grad=True, ) q, k, v, backward_grad = make_q(), make_kv(), make_kv(), make_q() block_mask = _create_empty_block_mask(q, k) @torch.compile def sdpa_hop(q, k, v, score_mod, block_mask): return flex_attention(q, k, v, score_mod) output = sdpa_hop(q, k, v, _identity, block_mask) output.backward(backward_grad) @supported_platform @common_utils.parametrize("dtype", test_dtypes) @common_utils.parametrize("score_mod", test_score_mods) @common_utils.parametrize("head_dims", test_Hq_Hkv) @with_tf32_off def test_builtin_score_mods( self, device, dtype: torch.dtype, score_mod: Callable, head_dims ): Hq, Hkv = head_dims assert Hq % Hkv == 0 self.run_test(score_mod, dtype, Q_H=Hq, KV_H=Hkv, device=device) self.run_test_with_paged_attention( score_mod, dtype, Q_H=Hq, KV_H=Hkv, device=device ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.parametrize("score_mod", test_score_mods) @common_utils.parametrize("head_dims", test_Hq_Hkv) @common_utils.parametrize("page_size", test_page_sizes) def test_paged_attention_page_size( self, device, dtype: torch.dtype, score_mod: Callable, head_dims: tuple[int, int], page_size: int, ): Hq, Hkv = head_dims assert Hq % Hkv == 0 def generate_causal_offset(offset: torch.Tensor): def causal_offset_mask(b, h, q_idx, kv_idx): return (offset + q_idx) >= kv_idx return causal_offset_mask mod = generate_causal_offset( torch.tensor(192, device=device, dtype=torch.int32) ) block_mask = create_block_mask( mod, B, 1, 1, S, BLOCK_SIZE=page_size, device=device ) self.run_test_with_paged_attention( score_mod, dtype, Q_B=B, Q_H=Hq, KV_B=B, KV_H=Hkv, KV_S=S, block_mask=block_mask, device=device, ) @supported_platform @common_utils.parametrize("dtype", test_dtypes) @common_utils.parametrize("score_mod", test_score_mods) @common_utils.parametrize("BLOCK_SIZE", test_block_size) def test_builtin_score_mods_different_block_size( self, device, dtype: torch.dtype, score_mod: Callable, BLOCK_SIZE: Union[int, tuple[int, int]], ): block_mask = create_block_mask( noop_mask, B, 1, 1, S, BLOCK_SIZE=BLOCK_SIZE, device=device ) self.run_test(score_mod, dtype, block_mask=block_mask, device=device) @unittest.skipIf(not has_triton_tma_device(), "Skip when TMA is not available") @common_utils.parametrize("dtype", test_dtypes_fast) def test_tma_decoding(self, device, dtype: torch.dtype): n_heads, head_dim, seq_len = 4, 16, 128 score_mod = _generate_alibi_bias(n_heads) kernel_options = {"USE_TMA": True} self.run_test( score_mod=score_mod, dtype=dtype, Q_B=1, Q_H=n_heads, Q_S=1, Q_D=head_dim, KV_B=1, KV_H=n_heads, KV_S=seq_len, V_D=head_dim, device=device, kernel_options=kernel_options, ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.parametrize("k_s", test_input_strides) @common_utils.parametrize("v_s", test_input_strides) @common_utils.parametrize("head_dims", test_Hq_Hkv) def test_strided_inputs(self, device, dtype: torch.dtype, k_s, v_s, head_dims): Hq, Hkv = head_dims assert Hq % Hkv == 0 q1 = torch.randn((B * Hq * D), dtype=dtype, device=device) k1 = torch.randn((B * Hkv * S * D * 4), dtype=dtype, device=device) v1 = torch.randn((B * Hkv * S * D * 4), dtype=dtype, device=device) k_shape = (B, Hkv, S, D) v_shape = (B, Hkv, S, D) q = q1.view(1, Hq, B, D).transpose(0, 2) k_strides, k_offset = k_s(B, Hkv, S, D) k_max = [x * (y - 1) for x, y in zip(k_strides, k_shape)] assert sum(k_max) + k_offset < B * Hkv * S * D * 4 assert k_strides[-1] == 1 k = torch.as_strided(k1, k_shape, k_strides, k_offset) v_strides, v_offset = v_s(B, Hkv, S, D) v_max = [x * (y - 1) for x, y in zip(v_strides, v_shape)] assert sum(v_max) + v_offset < B * Hkv * S * D * 4 assert v_strides[-1] == 1 v = torch.as_strided(v1, v_shape, v_strides, v_offset) score_mod = _generate_alibi_bias(8) sdpa_partial = create_attention( score_mod=score_mod, block_mask=None, enable_gqa=(Hq != Hkv), ) compiled_sdpa = torch.compile(sdpa_partial) ref_out = sdpa_partial(q, k, v) compiled_out = compiled_sdpa(q, k, v) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close( ref_out, compiled_out, atol=tolerance.atol, rtol=tolerance.rtol ) paged_compiled_out, _ = self.run_paged_attention( score_mod, q, k, v, dtype, device=device ) torch.testing.assert_close( ref_out, paged_compiled_out, atol=tolerance.atol, rtol=tolerance.rtol ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.parametrize("head_dims", test_Hq_Hkv) @common_utils.parametrize("batch_dims", test_Bq_Bkv) @common_utils.parametrize("score_mod", test_score_mods) def test_kv_batch_broadcast( self, device, dtype: torch.dtype, head_dims: tuple[int, int], batch_dims: tuple[int, int], score_mod: Callable, ): Hq, Hkv = head_dims assert Hq % Hkv == 0 Bq, Bkv = batch_dims assert Bq > 1 and Bkv == 1 block_mask = create_block_mask(noop_mask, Bq, 1, 1, S, device=device) self.run_test( score_mod, dtype, Bq, Hq, 1, D, Bkv, Hkv, S, D, block_mask, device=device ) @supported_platform @common_utils.parametrize("dtype", test_dtypes) def test_skip_odd_keys(self, device, dtype: torch.dtype): def score_mod(score, b, h, q, kv): return torch.where(kv % 2 == 0, score, float("-inf")) self.run_test(score_mod, dtype, device=device) self.run_test_with_paged_attention(score_mod, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes) def test_function_composition(self, device, dtype: torch.dtype): def score_mod_1(score, b, h, m, n): return score + (m - n) def score_mod_2(score, b, h, m, n): return torch.where(m <= n, score, float("-inf")) def composed_score_mod(score, b, h, m, n): return score_mod_2(score_mod_1(score, b, h, m, n), b, h, m, n) self.run_test(composed_score_mod, dtype, device=device) self.run_test_with_paged_attention(composed_score_mod, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes) def test_captured_buffers(self, device, dtype: torch.dtype): head_offset = torch.rand(Hq, device=device, dtype=dtype) def score_mod(score, b, h, m, n): return score + head_offset[h] self.run_test(score_mod, dtype, device=device) self.run_test_with_paged_attention(score_mod, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes) def test_captured_buffers_all_dims(self, device, dtype: torch.dtype): head_scale = torch.randn(Hq, device=device) batch_scale = torch.randn(B, device=device) kv_scale = torch.randn(S, device=device) q_scale = torch.randn(1, device=device) def all_bias(score, batch, head, token_q, token_kv): score = score + kv_scale[token_kv] score = score + q_scale[token_q] score = score + head_scale[head] score = score + batch_scale[batch] return score self.run_test(all_bias, dtype, device=device) self.run_test_with_paged_attention(all_bias, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_seq_masking(self, device, dtype): seq_idx = torch.zeros(S, device=device, dtype=torch.bool) seq_idx[S // 2 :] = 1 def seq_mask_mod(score, b, h, q, kv): return torch.where(seq_idx[q] == seq_idx[kv], score, float("-inf")) self.run_test(seq_mask_mod, dtype, device=device) self.run_test_with_paged_attention(seq_mask_mod, dtype, device=device) @supported_platform def test_non_divisible_offset_mask(self, device): KV_S = S - 3 offset_tensor = torch.tensor(S // 2 - 3, device=device, dtype=torch.int32) def mask_mod(b, h, q, kv): return kv >= q + offset_tensor block_mask = create_block_mask(mask_mod, B, 1, 1, KV_S, device=device) self.run_test(KV_S=KV_S, block_mask=block_mask, device=device) @supported_platform def test_non_divisible_offset_mask_with_captured_buffer(self, device): KV_S = S - 3 offset_kv = torch.randn(KV_S, device=device, dtype=torch.bfloat16) offset_tensor = torch.tensor(S // 2 - 3, device=device, dtype=torch.int32) def score_mod(score, b, h, q, kv): return score + offset_kv[kv] def mask_mod(b, h, q, kv): return kv >= q + offset_tensor block_mask = create_block_mask(mask_mod, B, 1, 1, KV_S, device=device) self.run_test( KV_S=KV_S, block_mask=block_mask, score_mod=score_mod, device=device ) @supported_platform def test_non_divisible_multi_token_offset_mask(self, device): KV_S = S - 3 Q_S = 3 offset_tensor = torch.tensor(S // 2 - 1, device=device, dtype=torch.int32) def mask_mod(b, h, q, kv): return kv >= q + offset_tensor block_mask = create_block_mask(mask_mod, B, 1, Q_S, KV_S, device=device) self.run_test(Q_S=Q_S, KV_S=KV_S, block_mask=block_mask, device=device) @supported_platform @unittest.skipIf(SKIP_UT_ON_CPU, "Skip on CPU as not supported") def test_non_divisible_multi_token_offset_mask_with_captured_buffer(self, device): KV_S = S - 3 Q_S = 3 offset_kv = torch.randn(KV_S, device=device, dtype=torch.bfloat16) offset_q = torch.randn(Q_S, device=device, dtype=torch.bfloat16) offset_tensor = torch.tensor(S // 2 - 3, device=device, dtype=torch.int32) def score_mod(score, b, h, q, kv): return score + offset_kv[kv] + offset_q[q] def mask_mod(b, h, q, kv): return kv >= q + offset_tensor block_mask = create_block_mask(mask_mod, B, 1, Q_S, KV_S, device=device) self.run_test( Q_S=Q_S, KV_S=KV_S, block_mask=block_mask, score_mod=score_mod, device=device, ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_load_from_bias_seq_only(self, device, dtype): bias = torch.randn(1, S, device=device, dtype=dtype) def bias_mod(score, b, h, q, kv): return score + bias[q, kv] self.run_test(bias_mod, dtype, device=device) self.run_test_with_paged_attention(bias_mod, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_load_from_bias_seq_batch(self, device, dtype): bias = torch.randn(B, 1, S, device=device, dtype=dtype) def bias_mod(score, b, h, q, kv): return score + bias[b, q, kv] self.run_test(bias_mod, dtype, device=device) self.run_test_with_paged_attention(bias_mod, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_load_from_bias_head_seq_batch(self, device, dtype): bias = torch.randn( B, Hq, 1, S, device=device, dtype=dtype, ) def bias_mod(score, b, h, q, kv): return score + bias[b, h, q, kv] self.run_test(bias_mod, dtype, device=device) self.run_test_with_paged_attention(bias_mod, dtype, device=device) @supported_platform @common_utils.parametrize("score_mod", test_score_mods) @common_utils.parametrize("dtype", test_dtypes) @common_utils.parametrize("head_dims", [(D, D // 2), (D // 2, D)]) @with_tf32_off def test_non_equal_head_dims(self, device, dtype, score_mod, head_dims): qk_d, v_d = head_dims self.run_test( score_mod, dtype, B, Hq, 1, qk_d, B, Hkv, S, V_D=v_d, device=device ) self.run_test_with_paged_attention( score_mod, dtype, B, Hq, 1, qk_d, B, Hkv, S, V_D=v_d, device=device ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.parametrize("score_mod", test_score_mods) @common_utils.parametrize("head_dims", test_Hq_Hkv) def test_head_dependent_mask_mod( self, device, dtype: torch.dtype, score_mod, head_dims ): Hq, Hkv = head_dims assert Hq % Hkv == 0 def head_attention_mod(kv_head_num): head_type = torch.tensor( [i % kv_head_num != 0 for i in range(kv_head_num)], dtype=torch.bool, device=device, ) def mask_mod(b, h, q_idx, kv_idx): bi_mask = head_type[h] causal_mask = q_idx >= kv_idx return bi_mask & causal_mask return mask_mod mask_mod = head_attention_mod(Hq) mask = create_block_mask(mask_mod, 1, Hq, 1, S, device=device) self.run_test( score_mod, dtype, Q_H=Hq, KV_H=Hkv, block_mask=mask, device=device ) self.run_test_with_paged_attention( score_mod, dtype, Q_H=Hq, KV_H=Hkv, device=device ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_subgraph_respect_decompostion(self, device, dtype): from torch._decomp import core_aten_decompositions from torch.fx.experimental.proxy_tensor import make_fx def score_mod_func(score, b, h, q, kv): return score - q // (1 + kv) make_kv = functools.partial( torch.randn, (2, 2, 128, 4), dtype=dtype, device=device, requires_grad=True, ) make_q = functools.partial( torch.randn, (2, 2, 8, 4), dtype=dtype, device=device, requires_grad=True, ) query, key, value = make_q(), make_kv(), make_kv() # floor_div is not decomposed in decomposition_table is empty attention = functools.partial(flex_attention, score_mod=score_mod_func) gm = make_fx(attention, decomposition_table={})(query, key, value) self.assertExpectedInline( gm.sdpa_score0.code.strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1, arg3_1, arg4_1): add = torch.ops.aten.add.Tensor(arg4_1, 1); arg4_1 = None floor_divide = torch.ops.aten.floor_divide.default(arg3_1, add); arg3_1 = add = None sub = torch.ops.aten.sub.Tensor(arg0_1, floor_divide); arg0_1 = floor_divide = None return sub""", ) # floor_div is decomposed for core_aten_decompositions gm = make_fx(attention, decomposition_table=core_aten_decompositions())( query, key, value ) self.assertExpectedInline( gm.sdpa_score0.code.strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1, arg3_1, arg4_1): add = torch.ops.aten.add.Tensor(arg4_1, 1); arg4_1 = None div = torch.ops.aten.div.Tensor_mode(arg3_1, add, rounding_mode = 'floor'); arg3_1 = add = None sub = torch.ops.aten.sub.Tensor(arg0_1, div); arg0_1 = div = None return sub""", ) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_silu_on_score(self, device, dtype): def silu_score(score, b, h, q, kv): return torch.nn.functional.silu(score) self.run_test(silu_score, dtype, device=device) self.run_test_with_paged_attention(silu_score, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_padded_dense_causal(self, device, dtype): seq_len = torch.arange(B, device=device, dtype=torch.int32) + 1 def create_padded_dense_wrapper(orig_score_mod): def njt_score_mod(qk, b, h, q, kv): return torch.where( qk <= seq_len[b], orig_score_mod(qk, b, h, q, kv), -float("inf") ) return njt_score_mod causal_njt = create_padded_dense_wrapper(_causal) self.run_test(causal_njt, dtype, device=device) self.run_test_with_paged_attention(causal_njt, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_captured_scale(self, device, dtype): scale = torch.ones((), device=device, dtype=torch.int32) def score_mod_scale(qk, b, h, q, kv): return qk + scale self.run_test(score_mod_scale, dtype, device=device) self.run_test_with_paged_attention(score_mod_scale, dtype, device=device) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_recompile_changed_score_mod(self, device, dtype): scale = torch.ones((), device=device, dtype=torch.int32) ADD = True def score_mod_scale(qk, b, h, q, kv): if ADD: return qk + scale else: return qk * scale self.run_test(score_mod_scale, dtype, device=device) self.run_test_with_paged_attention(score_mod_scale, dtype, device=device) ADD = False self.run_test(score_mod_scale, dtype, device=device) self.run_test_with_paged_attention(score_mod_scale, dtype, device=device) @supported_platform @common_utils.parametrize("head_dim", [17, 24, 94, 121]) @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.serialTest() def test_non_pow_2_headdim(self, device, dtype, head_dim): self.run_test( _rel_bias, dtype, B, Hq, S, head_dim, B, Hkv, S, head_dim, device=device ) @supported_platform @expectedFailure # If we capture a tensor then we can perform a reduction on it, and that shouldn't be allowed @common_utils.parametrize("dtype", test_dtypes_fast) def test_captured_reduction(self, device, dtype): scale = torch.randn((B, 8), device=device) def score_mod_scale(qk, b, h, q, kv): return qk + scale[b].sum(dim=-1) self.run_test(score_mod_scale, dtype, device=device) @supported_platform def test_multiple_score_mod_calls(self, device): query = torch.randn((1, 8, 4, 64), dtype=torch.float32, device=device) keys = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(2) ] values = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(2) ] def scoremod_1(qk, b, h, q, kv): return qk + (q - kv) def scoremod_2(qk, b, h, q, kv): return torch.where(q >= kv, qk, -float("inf")) def f(q, k1, k2, v1, v2): q2 = flex_attention(q, k1, v1, score_mod=scoremod_1) return flex_attention(q2, k2, v2, score_mod=scoremod_2) out = f(query, *keys, *values) out2 = torch.compile(f)(query, *keys, *values) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close(out, out2, atol=tolerance.atol, rtol=tolerance.rtol) @supported_platform def test_multiple_score_mod_calls2(self, device): query = torch.randn((1, 8, 4, 64), dtype=torch.float32, device=device) keys = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(3) ] values = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(3) ] def scoremod_1(qk, b, h, q, kv): return qk + (q - kv) def scoremod_2(qk, b, h, q, kv): return torch.where(q >= kv, qk, -float("inf")) attention1 = functools.partial(flex_attention, score_mod=scoremod_1) def f(q, k1, k2, k3, v1, v2, v3): q2 = attention1(q, k1, v1) q3 = flex_attention(q2, k2, v2, score_mod=scoremod_2) return flex_attention(q3, k3, v3, score_mod=scoremod_1) out = f(query, *keys, *values) out2 = torch.compile(f)(query, *keys, *values) self.assertTrue((out - out2).abs().mean() < 1e-2) @supported_platform def test_multiple_score_mod_calls_paged_attention(self, device): query = torch.randn((1, 8, 4, 64), dtype=torch.float32, device=device) keys = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(2) ] values = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(2) ] def scoremod_1(qk, b, h, q, kv): return qk + (q - kv) def scoremod_2(qk, b, h, q, kv): return torch.where(q >= kv, qk, -float("inf")) block_mask = create_block_mask(noop_mask, 1, 1, 4, 1024, device=device) def f(q, k1, k2, v1, v2): q2 = flex_attention(q, k1, v1, score_mod=scoremod_1, block_mask=block_mask) return flex_attention( q2, k2, v2, score_mod=scoremod_2, block_mask=block_mask ) eager_out = f(query, *keys, *values) ( k_cache1, v_cache1, converted_block_mask1, converted_score_mod1, ) = self.preprocess_paged_attention( scoremod_1, query, keys[0], values[0], block_mask, torch.float32, device=device, ) ( k_cache2, v_cache2, converted_block_mask2, converted_score_mod2, ) = self.preprocess_paged_attention( scoremod_2, query, keys[1], values[1], block_mask, torch.float32, device=device, ) def paged_f(q, k1, k2, v1, v2): q2 = flex_attention( q, k1, v1, score_mod=converted_score_mod1, block_mask=converted_block_mask1, ) return flex_attention( q2, k2, v2, score_mod=converted_score_mod2, block_mask=converted_block_mask2, ) compiled_out = torch.compile(paged_f)( query, k_cache1, k_cache2, v_cache1, v_cache2 ) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close( eager_out, compiled_out, atol=tolerance.atol, rtol=tolerance.rtol ) @supported_platform def test_multiple_score_mod_calls_paged_attention2(self, device): query = torch.randn((1, 8, 4, 64), dtype=torch.float32, device=device) keys = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(3) ] values = [ torch.randn((1, 8, 1024, 64), dtype=torch.float32, device=device) for _ in range(3) ] def scoremod_1(qk, b, h, q, kv): return qk + (q - kv) def scoremod_2(qk, b, h, q, kv): return torch.where(q >= kv, qk, -float("inf")) block_mask = create_block_mask(noop_mask, 1, 1, 4, 1024, device=device) attention1 = functools.partial( flex_attention, score_mod=scoremod_1, block_mask=block_mask ) def f(q, k1, k2, k3, v1, v2, v3): q2 = attention1(q, k1, v1) q3 = flex_attention(q2, k2, v2, score_mod=scoremod_2, block_mask=block_mask) return flex_attention( q3, k3, v3, score_mod=scoremod_1, block_mask=block_mask ) eager_out = f(query, *keys, *values) ( k_cache1, v_cache1, converted_block_mask1, converted_score_mod1, ) = self.preprocess_paged_attention( scoremod_1, query, keys[0], values[0], block_mask, torch.float32, device=device, ) ( k_cache2, v_cache2, converted_block_mask2, converted_score_mod2, ) = self.preprocess_paged_attention( scoremod_2, query, keys[1], values[1], block_mask, torch.float32, device=device, ) ( k_cache3, v_cache3, converted_block_mask3, converted_score_mod3, ) = self.preprocess_paged_attention( scoremod_1, query, keys[2], values[2], block_mask, torch.float32, device=device, ) paged_attention1 = functools.partial( flex_attention, score_mod=converted_score_mod1, block_mask=converted_block_mask1, ) def paged_f(q, k1, k2, k3, v1, v2, v3): q2 = paged_attention1(q, k1, v1) q3 = flex_attention( q2, k2, v2, score_mod=converted_score_mod2, block_mask=converted_block_mask2, ) return flex_attention( q3, k3, v3, score_mod=converted_score_mod3, block_mask=converted_block_mask3, ) compiled_out = torch.compile(paged_f)( query, k_cache1, k_cache2, k_cache3, v_cache1, v_cache2, v_cache3 ) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close( eager_out, compiled_out, atol=tolerance.atol, rtol=tolerance.rtol ) @supported_platform @common_utils.parametrize("dtype", test_dtypes) def test_njt_causal(self, device, dtype): offsets = torch.tensor( [0, 1024, 1024 + 512, S], device=device, dtype=torch.int32 ) seq_idx = torch.zeros(S, device=device, dtype=torch.int32) for idx in range(len(offsets) - 1): seq_idx[offsets[idx] : offsets[idx + 1]] = idx def create_njt_wrapper(orig_score_mod, offsets, seq_idx): def njt_score_mod(qk, b, h, q, kv): q_nested = q - offsets[seq_idx[q]] kv_nested = kv - offsets[seq_idx[kv]] return orig_score_mod(qk, b, h, q_nested, kv_nested) return njt_score_mod causal_njt = create_njt_wrapper(_causal, offsets, seq_idx) self.run_test(causal_njt, dtype, device=device) self.run_test_with_paged_attention(causal_njt, dtype, device=device) @supported_platform def test_mixed_dtypes_fails(self, device): query = torch.randn((1, 1, 8, 64), dtype=torch.float32, device=device) key = torch.randn((1, 1, 1024, 64), dtype=torch.float16, device=device) value = torch.randn((1, 1, 1024, 64), dtype=torch.float16, device=device) with self.assertRaisesRegex( ValueError, "Expected query, key, and value to have the same dtype" ): flex_attention(query, key, value, _identity) @supported_platform @patch.object(torch._inductor.config, "max_autotune", True) def test_max_autotune(self, device): def score_mod(score, b, h, m, n): return score * 2 self.run_test(score_mod, device=device) self.run_test_with_paged_attention(score_mod, device=device) self.run_test_with_paged_attention( score_mod=score_mod, dtype=torch.bfloat16, Q_B=4, Q_H=1, Q_S=1, QK_D=16, KV_B=4, KV_H=1, KV_S=64, V_D=16, device=device, ) @supported_platform @patch.object(torch._inductor.config, "max_autotune", True) def test_max_autotune_with_captured(self, device): head_scale = torch.randn(Hq, device=device) batch_scale = torch.randn(B, device=device) tok_scale = torch.randn(S, device=device) q_scale = torch.randn(1, device=device) def bias_mod(score, batch, head, token_q, token_kv): score = score + tok_scale[token_kv] score = score + q_scale[token_q] score = score + batch_scale[batch] score = score + head_scale[head] return score self.run_test(bias_mod, device=device) self.run_test_with_paged_attention(bias_mod, device=device) @supported_platform def test_fully_masked_out_rows_0_check_gqa(self, device): # Ensure fully masked out rows won't cause NaNs. query = torch.randn( (B, Hq, S, D), dtype=torch.float32, device=device, requires_grad=not self.test_inference_only, ) key = torch.randn( (B, Hkv, S, D), dtype=torch.float32, device=device, requires_grad=not self.test_inference_only, ) value = torch.randn( (B, Hkv, S, D), dtype=torch.float32, device=device, requires_grad=not self.test_inference_only, ) M = S // 2 def mask_mod(b, h, q, kv): return q < M block_mask = create_block_mask(mask_mod, 1, 1, S, S, device=device) flex = torch.compile(flex_attention, dynamic=False) if not self.test_inference_only: out, lse = flex( query, key, value, block_mask=block_mask, enable_gqa=True, return_lse=True, ) self.assertTrue((lse[:, :, M:] == -float("inf")).all()) loss = out.sum() + lse.sum() loss.backward() self.assertEqual(query.grad[:, :, M:, :].sum(), 0) else: out = flex( query, key, value, block_mask=block_mask, enable_gqa=True, return_lse=False, ) self.assertEqual(out[:, :, M:, :].sum(), 0) @supported_platform def test_windowed_no_mask_vs_sdpa(self, device): score_mod = _generate_windowed(1000) attention = functools.partial(flex_attention, score_mod=score_mod) sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) sdpa_attention = functools.partial( torch.nn.functional.scaled_dot_product_attention, attn_mask=sdpa_mask ) self.run_test_with_call( attention, sdpa_attention, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform def test_windowed_full_mask_vs_sdpa(self, device): def mask_mod(b, h, q, kv): return q + 1000 >= kv score_mod = _generate_windowed(1000) block_mask = create_block_mask(mask_mod, 1, 1, 8, S, device=device) attention = functools.partial( flex_attention, block_mask=block_mask, score_mod=score_mod ) sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) sdpa_attention = functools.partial( torch.nn.functional.scaled_dot_product_attention, attn_mask=sdpa_mask ) self.run_test_with_call( attention, sdpa_attention, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform def test_windowed_partial_block_vs_sdpa(self, device): def mask_mod(b, h, q, kv): return q + 1000 >= kv block_mask = create_block_mask(mask_mod, 1, 1, 8, S, device=device) attention = functools.partial(flex_attention, block_mask=block_mask) sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) sdpa_attention = functools.partial( torch.nn.functional.scaled_dot_product_attention, attn_mask=sdpa_mask ) self.run_test_with_call( attention, sdpa_attention, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform def test_windowed_no_mask_vs_sdpa_paged_attention(self, device): score_mod = _generate_windowed(1000) sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) self.run_test_with_call_paged_attention( score_mod, None, sdpa_mask, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform def test_windowed_full_mask_vs_sdpa_paged_attention(self, device): def mask_mod(b, h, q, kv): return q + 1000 >= kv score_mod = _generate_windowed(1000) sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) self.run_test_with_call_paged_attention( score_mod, mask_mod, sdpa_mask, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform def test_windowed_partial_block_vs_sdpa_paged_attention(self, device): def mask_mod(b, h, q, kv): return q + 1000 >= kv sdpa_mask = _get_windowed_sdpa_mask(8, S, 1000) self.run_test_with_call_paged_attention( None, mask_mod, sdpa_mask, Q_H=16, KV_H=16, Q_S=8, device=device ) @supported_platform @unittest.skipIf(SKIP_UT_ON_CPU, "Skip on CPU as not supported") @common_utils.parametrize("dtype", test_dtypes) @common_utils.parametrize("score_mod", [_identity, _causal]) def test_logsumexp_correctness(self, device, dtype, score_mod): make_kv = functools.partial( torch.randn, (B, Hkv, S, D), dtype=dtype, device=device, requires_grad=True, ) make_q = functools.partial( torch.randn, (B, Hkv, Hq // Hkv, D), dtype=dtype, device=device, requires_grad=True, ) q, k, v = make_q(), make_kv(), make_kv() @torch.compile def sdpa_hop(q, k, v, score_mod): return flex_attention(q, k, v, score_mod, return_lse=True) @torch.compile(backend="aot_eager") def eager_sdpa_hop(q, k, v, score_mod): return flex_attention(q, k, v, score_mod, return_lse=True) ref_out, ref_lse = eager_sdpa_hop( q.to(torch.float64), k.to(torch.float64), v.to(torch.float64), score_mod, ) compiled_out, compiled_lse = sdpa_hop(q, k, v, score_mod) self.assertTrue(ref_lse.dtype == torch.float64) self.assertTrue(compiled_lse.dtype == torch.float32) tolerance = Tolerances(atol=2e-2, rtol=2e-2) torch.testing.assert_close( ref_out.to(dtype=torch.float32), compiled_out.to(dtype=torch.float32), atol=tolerance.atol, rtol=tolerance.rtol, ) torch.testing.assert_close( ref_lse.to(dtype=torch.float32), compiled_lse.to(dtype=torch.float32), atol=tolerance.atol, rtol=tolerance.rtol, ) @supported_platform @unittest.skipIf(SKIP_UT_ON_CPU, "Skip on CPU as not supported") def test_not_pw_of_two(self, device): query = torch.randn(1, 12, 1, 16, device=device) key = torch.randn(1, 2, 128, 16, device=device) value = torch.randn(1, 2, 128, 16, device=device) flex_compiled = torch.compile(flex_attention) flex_compiled(query, key, value, enable_gqa=True) @supported_platform @unittest.skipIf(SKIP_UT_ON_CPU, "Skip on CPU as not supported") def test_logsumexp_only_return(self, device): make_q = functools.partial( torch.randn, (B, Hkv, Hq // Hkv, D), dtype=torch.float32, device=device, requires_grad=True, ) make_kv = functools.partial( torch.randn, (B, Hkv, S, D), dtype=torch.float32, device=device, requires_grad=True, ) q, k, v = make_q(), make_kv(), make_kv() @torch.compile def func(q, k, v, score_mod): _, lse = flex_attention(q, k, v, score_mod, return_lse=True) lse_2 = lse * 2 return lse_2 _, code = run_and_get_code(func, q, k, v, _identity) # Ensure that we're still generating the flexattention kernel FileCheck().check_count(".run(primals_1, primals_2, primals_3", 1, True).run( code[0] ) @supported_platform @skip_on_xpu # TODO: SYCL acc issue def test_non_sparse_mulitple_block_size(self, device): def generate_causal_offset(offset: torch.Tensor): def causal_offset_mask(b, h, q_idx, kv_idx): return (offset + q_idx) >= kv_idx return causal_offset_mask def noop(score, b, h, q_idx, kv_idx): # noqa: F841 return score mod = generate_causal_offset( torch.tensor(192, device=device, dtype=torch.int32) ) block_mask = create_block_mask(mod, 1, 1, 1, 65, device=device) self.run_test( score_mod=None, dtype=torch.float32, block_mask=block_mask, Q_B=1, Q_H=1, Q_S=1, Q_D=16, KV_B=1, KV_H=1, KV_S=65, V_D=16, device=device, ) self.run_test_with_paged_attention( score_mod=None, dtype=torch.float32, block_mask=block_mask, Q_B=1, Q_H=1, Q_S=1, QK_D=16, KV_B=1, KV_H=1, KV_S=65, V_D=16, device=device, ) @supported_platform def test_do_not_trigger_dynamic_shapes_on_empty_block_mask(self, device): torch._dynamo.reset() H = Hq q = torch.randn(B, H, 1, D, device=device) for i in range(5): k = torch.randn(B, H, S + i, D, device=device) v = torch.randn(B, H, S + i, D, device=device) compiled_flex_attention = torch.compile(flex_attention) ref = flex_attention(q, k, v) res = compiled_flex_attention(q, k, v) tolerance = Tolerances(atol=2e-1, rtol=2e-1) torch.testing.assert_close( ref, res, atol=tolerance.atol, rtol=tolerance.rtol ) # Ensure no more re-compilation after the second automatic dynamic shape version. if i == 0: self.assertEqual(torch._dynamo.utils.counters["frames"]["ok"], 1) else: self.assertEqual(torch._dynamo.utils.counters["frames"]["ok"], 2) @supported_platform @common_utils.parametrize("dtype", test_dtypes_fast) def test_larger_block_mask_bug(self, device, dtype): def mask_mod(b, h, q_idx, kv_idx): return q_idx >= kv_idx mask_2 = create_block_mask( mask_mod=mask_mod, B=2, H=None, Q_LEN=2, KV_LEN=2, device=device, ) # Compile flex attention flex_attention_compiled = torch.compile(flex_attention, dynamic=False) # Create input tensors shape = (2, 1, 2, 16) q = torch.normal(0.0, 3.0, shape, device=device, dtype=dtype) k = torch.normal(0.0, 3.0, shape, device=device, dtype=dtype) v = torch.normal(0.0, 3.0, shape, device=device, dtype=dtype) eager = flex_attention(q, k, v, block_mask=mask_2) out = flex_attention_compiled(q, k, v, block_mask=mask_2) torch.testing.assert_close(eager, out, atol=5e-3, rtol=5e-3) @common_utils.parametrize("dtype", test_dtypes_fast) @common_utils.parametrize("score_mod", test_score_mods) @supported_platform def test_decode_at_different_input_position( self, device, dtype: torch.dtype, score_mod: Callable ): n_pages, page_size, max_batch_size, max_seq_len = 32, 64, 4, 512 n_heads, head_dim = 4, 16 def causal_mask(b, h, q, kv): return q >= kv block_mask = create_block_mask( causal_mask, max_batch_size, 1, max_seq_len, max_seq_len, device=device, BLOCK_SIZE=page_size, ) # init 4 requests with different prefill length prefill_length = [5, 98, 47, 194] queries, keys, values = [], [], [] for seq_len in prefill_length: q = torch.randn( 1, n_heads, 1, head_dim, device=device, dtype=dtype, requires_grad=False, ) k = torch.randn( 1, n_heads, seq_len, head_dim, device=device, dtype=dtype, requires_grad=False, ) v = torch.randn( 1, n_heads, seq_len, head_dim, device=device, dtype=dtype, requires_grad=False, ) queries.append(q) keys.append(k) values.append(v) # get ground truth output ref_outs, golden_outs = [], [] for q, k, v in zip(queries, keys, values): q_ref, k_ref, v_ref = query_key_value_clones(q, k, v) q_gold, k_gold, v_gold = query_key_value_clones(q, k, v, torch.float64) slice_block_mask = block_mask._adjust(1, k_ref.shape[2]) slice_block_mask.seq_lengths = (1, k_ref.shape[2]) ref_out = flex_attention( q_ref, k_ref, v_ref, score_mod, slice_block_mask, enable_gqa=False ) golden_out = flex_attention( q_gold, k_gold, v_gold, score_mod, slice_block_mask, enable_gqa=False ) ref_outs.append(ref_out) golden_outs.append(golden_out) ref_outs = torch.cat(ref_outs) golden_outs = torch.cat(golden_outs) # init paged attention paged_cache = PagedAttention(n_pages, page_size, max_batch_size, device=device) batch_reserve(paged_cache, torch.tensor([100, 200, 50, 300], device=device)) batch_reserve(paged_cache, torch.tensor([100, 512, 300, 300], device=device)) batch_reserve(paged_cache, torch.tensor([512, 512, 300, 300], device=device)) batch_reserve(paged_cache, torch.tensor([512, 512, 512, 300], device=device)) batch_reserve(paged_cache, torch.tensor([512, 512, 512, 512], device=device)) # allocate paged kv cache MAX_CACHED_SEQ_LEN = n_pages * page_size k_cache = torch.zeros( 1, n_heads, MAX_CACHED_SEQ_LEN, head_dim, device=device, dtype=dtype, ) v_cache = torch.zeros( 1, n_heads, MAX_CACHED_SEQ_LEN, head_dim, device=device, dtype=dtype, ) # prefill paged kv cache for i, seq_len in enumerate(prefill_length): batch_idx = torch.tensor([i], device=device, dtype=torch.int32) input_pos = torch.arange(seq_len, device=device, dtype=torch.int32).view( 1, seq_len ) paged_cache.assign( batch_idx, input_pos, keys[i], values[i], k_cache, v_cache ) # get paged out and check correctness batch_idx = torch.arange(max_batch_size, device=device, dtype=torch.int32) input_pos = torch.tensor(prefill_length, device=device, dtype=torch.int32).view( max_batch_size, 1 ) kv_len_tensor = torch.full( (max_batch_size,), max_seq_len, device=device, dtype=torch.int64 ) new_block_mask = paged_cache.convert_logical_block_mask( block_mask, kv_len=kv_len_tensor ) new_block_mask.seq_lengths = (1, new_block_mask.seq_lengths[1]) compiled_sdpa = torch.compile( create_attention( paged_cache.get_score_mod(score_mod, kv_len=kv_len_tensor), new_block_mask, enable_gqa=False, ) ) paged_out = compiled_sdpa( torch.cat(queries, 0), k_cache, v_cache, block_mask=new_block_mask ) with torch.no_grad(): dtype = paged_out.dtype if dtype == torch.float32: fudge_factor = 10.0 else: fudge_factor = 1.1 # Checkout output self._check_equal(golden_outs, ref_outs, paged_out, fudge_factor, "Out") instantiate_device_type_tests( TestFlexDecoding, globals(), only_for=test_device, allow_xpu=True ) if __name__ == "__main__": from torch._inductor.test_case import run_tests run_tests()
TestFlexDecoding
python
ray-project__ray
python/ray/serve/config.py
{ "start": 16355, "end": 22035 }
class ____(BaseModel): """Config for the Serve Autoscaler.""" # Please keep these options in sync with those in # `src/ray/protobuf/serve.proto`. # Publicly exposed options min_replicas: NonNegativeInt = 1 initial_replicas: Optional[NonNegativeInt] = None max_replicas: PositiveInt = 1 target_ongoing_requests: Optional[PositiveFloat] = DEFAULT_TARGET_ONGOING_REQUESTS metrics_interval_s: PositiveFloat = Field( default=DEFAULT_METRICS_INTERVAL_S, description="[DEPRECATED] How often to scrape for metrics. " "Will be replaced by the environment variables " "`RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PUSH_INTERVAL_S` and " "`RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S` in a future release.", ) look_back_period_s: PositiveFloat = Field( default=30.0, description="Time window to average over for metrics." ) smoothing_factor: PositiveFloat = Field( default=1.0, description="[DEPRECATED] Smoothing factor for autoscaling decisions.", ) # DEPRECATED: replaced by `downscaling_factor` upscale_smoothing_factor: Optional[PositiveFloat] = Field( default=None, description="[DEPRECATED] Please use `upscaling_factor` instead." ) # DEPRECATED: replaced by `upscaling_factor` downscale_smoothing_factor: Optional[PositiveFloat] = Field( default=None, description="[DEPRECATED] Please use `downscaling_factor` instead.", ) upscaling_factor: Optional[PositiveFloat] = Field( default=None, description='Multiplicative "gain" factor to limit upscaling decisions.', ) downscaling_factor: Optional[PositiveFloat] = Field( default=None, description='Multiplicative "gain" factor to limit downscaling decisions.', ) # How frequently to make autoscaling decisions # loop_period_s: float = CONTROL_LOOP_PERIOD_S downscale_delay_s: NonNegativeFloat = Field( default=600.0, description="How long to wait before scaling down replicas to a value greater than 0.", ) # Optionally set for 1->0 transition downscale_to_zero_delay_s: Optional[NonNegativeFloat] = Field( default=None, description="How long to wait before scaling down replicas from 1 to 0. If not set, the value of `downscale_delay_s` will be used.", ) upscale_delay_s: NonNegativeFloat = Field( default=30.0, description="How long to wait before scaling up replicas." ) aggregation_function: Union[str, AggregationFunction] = Field( default=AggregationFunction.MEAN, description="Function used to aggregate metrics across a time window.", ) # Autoscaling policy. This policy is deployment scoped. Defaults to the request-based autoscaler. policy: AutoscalingPolicy = Field( default_factory=AutoscalingPolicy, description="The autoscaling policy for the deployment. This option is experimental.", ) @validator("max_replicas", always=True) def replicas_settings_valid(cls, max_replicas, values): min_replicas = values.get("min_replicas") initial_replicas = values.get("initial_replicas") if min_replicas is not None and max_replicas < min_replicas: raise ValueError( f"max_replicas ({max_replicas}) must be greater than " f"or equal to min_replicas ({min_replicas})!" ) if initial_replicas is not None: if initial_replicas < min_replicas: raise ValueError( f"min_replicas ({min_replicas}) must be less than " f"or equal to initial_replicas ({initial_replicas})!" ) elif initial_replicas > max_replicas: raise ValueError( f"max_replicas ({max_replicas}) must be greater than " f"or equal to initial_replicas ({initial_replicas})!" ) return max_replicas @validator("metrics_interval_s") def metrics_interval_s_deprecation_warning(cls, v: PositiveFloat) -> PositiveFloat: if v != DEFAULT_METRICS_INTERVAL_S: warnings.warn( "The `metrics_interval_s` field in AutoscalingConfig is deprecated and " "will be replaced by the environment variables " "`RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PUSH_INTERVAL_S` and " "`RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S` in a future release.", DeprecationWarning, ) return v @validator("aggregation_function", always=True) def aggregation_function_valid(cls, v: Union[str, AggregationFunction]): if isinstance(v, AggregationFunction): return v return AggregationFunction(str(v).lower()) @classmethod def default(cls): return cls( target_ongoing_requests=DEFAULT_TARGET_ONGOING_REQUESTS, min_replicas=1, max_replicas=100, ) def get_upscaling_factor(self) -> PositiveFloat: if self.upscaling_factor: return self.upscaling_factor return self.upscale_smoothing_factor or self.smoothing_factor def get_downscaling_factor(self) -> PositiveFloat: if self.downscaling_factor: return self.downscaling_factor return self.downscale_smoothing_factor or self.smoothing_factor def get_target_ongoing_requests(self) -> PositiveFloat: return self.target_ongoing_requests # Keep in sync with ServeDeploymentMode in dashboard/client/src/type/serve.ts @Deprecated
AutoscalingConfig
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 7317, "end": 7751 }
class ____(TestCase): def test_basic(self): y1 = [0, 0, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 0, 1, 0] assert_(np.any(y1)) assert_(np.any(y3)) assert_(not np.any(y2)) def test_nd(self): y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]] assert_(np.any(y1)) assert_array_equal(np.any(y1, axis=0), [1, 1, 0]) assert_array_equal(np.any(y1, axis=1), [0, 1, 1])
TestAny
python
falconry__falcon
falcon/bench/queues/queues.py
{ "start": 820, "end": 903 }
class ____: def on_get(self, req, resp, tenant_id): pass
CollectionResource
python
Textualize__textual
tests/test_pilot.py
{ "start": 923, "end": 15507 }
class ____(App): """Auxiliary app with a button following many labels.""" AUTO_FOCUS = None # So that there's no auto-scrolling. def compose(self): for idx in range(100): yield Label(f"label {idx}", id=f"label{idx}") yield Button() async def test_pilot_press_ascii_chars(): """Test that the pilot can press most ASCII characters as keys.""" keys_pressed = [] class TestApp(App[None]): def on_key(self, event: events.Key) -> None: keys_pressed.append(event.character) async with TestApp().run_test() as pilot: for char in KEY_CHARACTERS_TO_TEST: await pilot.press(char) assert keys_pressed[-1] == char async def test_pilot_exception_catching_app_compose(): """Ensuring that test frameworks are aware of exceptions inside compose methods when running via Pilot run_test().""" class FailingApp(App): def compose(self) -> ComposeResult: 1 / 0 yield Label("Beep") with pytest.raises(ZeroDivisionError): async with FailingApp().run_test(): pass async def test_pilot_exception_catching_widget_compose(): class SomeScreen(Screen[None]): def compose(self) -> ComposeResult: 1 / 0 yield Label("Beep") class FailingApp(App[None]): def on_mount(self) -> None: self.push_screen(SomeScreen()) with pytest.raises(ZeroDivisionError): async with FailingApp().run_test(): pass async def test_pilot_exception_catching_action(): """Ensure that exceptions inside action handlers are presented to the test framework when running via Pilot run_test().""" class FailingApp(App): BINDINGS = [Binding("b", "beep", "beep")] def action_beep(self) -> None: 1 / 0 with pytest.raises(ZeroDivisionError): async with FailingApp().run_test() as pilot: await pilot.press("b") async def test_pilot_exception_catching_worker(): class SimpleAppThatCrashes(App[None]): def on_mount(self) -> None: self.crash() @work(name="crash") async def crash(self) -> None: 1 / 0 with pytest.raises(WorkerFailed) as exc: async with SimpleAppThatCrashes().run_test(): pass assert exc.type is ZeroDivisionError async def test_pilot_click_screen(): """Regression test for https://github.com/Textualize/textual/issues/3395. Check we can use `Screen` as a selector for a click.""" async with App().run_test() as pilot: await pilot.click() async def test_pilot_hover_screen(): """Regression test for https://github.com/Textualize/textual/issues/3395. Check we can use `Screen` as a selector for a hover.""" async with App().run_test() as pilot: await pilot.hover() @pytest.mark.parametrize( ["method", "screen_size", "offset"], [ # ("click", (80, 24), (100, 12)), # Right of screen. ("click", (80, 24), (100, 36)), # Bottom-right of screen. ("click", (80, 24), (50, 36)), # Under screen. ("click", (80, 24), (-10, 36)), # Bottom-left of screen. ("click", (80, 24), (-10, 12)), # Left of screen. ("click", (80, 24), (-10, -2)), # Top-left of screen. ("click", (80, 24), (50, -2)), # Above screen. ("click", (80, 24), (100, -2)), # Top-right of screen. # ("click", (5, 5), (7, 3)), # Right of screen. ("click", (5, 5), (7, 7)), # Bottom-right of screen. ("click", (5, 5), (3, 7)), # Under screen. ("click", (5, 5), (-1, 7)), # Bottom-left of screen. ("click", (5, 5), (-1, 3)), # Left of screen. ("click", (5, 5), (-1, -1)), # Top-left of screen. ("click", (5, 5), (3, -1)), # Above screen. ("click", (5, 5), (7, -1)), # Top-right of screen. # ("hover", (80, 24), (100, 12)), # Right of screen. ("hover", (80, 24), (100, 36)), # Bottom-right of screen. ("hover", (80, 24), (50, 36)), # Under screen. ("hover", (80, 24), (-10, 36)), # Bottom-left of screen. ("hover", (80, 24), (-10, 12)), # Left of screen. ("hover", (80, 24), (-10, -2)), # Top-left of screen. ("hover", (80, 24), (50, -2)), # Above screen. ("hover", (80, 24), (100, -2)), # Top-right of screen. # ("hover", (5, 5), (7, 3)), # Right of screen. ("hover", (5, 5), (7, 7)), # Bottom-right of screen. ("hover", (5, 5), (3, 7)), # Under screen. ("hover", (5, 5), (-1, 7)), # Bottom-left of screen. ("hover", (5, 5), (-1, 3)), # Left of screen. ("hover", (5, 5), (-1, -1)), # Top-left of screen. ("hover", (5, 5), (3, -1)), # Above screen. ("hover", (5, 5), (7, -1)), # Top-right of screen. # ("mouse_down", (80, 24), (100, 12)), # Right of screen. ("mouse_down", (80, 24), (100, 36)), # Bottom-right of screen. ("mouse_down", (80, 24), (50, 36)), # Under screen. ("mouse_down", (80, 24), (-10, 36)), # Bottom-left of screen. ("mouse_down", (80, 24), (-10, 12)), # Left of screen. ("mouse_down", (80, 24), (-10, -2)), # Top-left of screen. ("mouse_down", (80, 24), (50, -2)), # Above screen. ("mouse_down", (80, 24), (100, -2)), # Top-right of screen. # ("mouse_down", (5, 5), (7, 3)), # Right of screen. ("mouse_down", (5, 5), (7, 7)), # Bottom-right of screen. ("mouse_down", (5, 5), (3, 7)), # Under screen. ("mouse_down", (5, 5), (-1, 7)), # Bottom-left of screen. ("mouse_down", (5, 5), (-1, 3)), # Left of screen. ("mouse_down", (5, 5), (-1, -1)), # Top-left of screen. ("mouse_down", (5, 5), (3, -1)), # Above screen. ("mouse_down", (5, 5), (7, -1)), # Top-right of screen. # ("mouse_up", (80, 24), (100, 12)), # Right of screen. ("mouse_up", (80, 24), (100, 36)), # Bottom-right of screen. ("mouse_up", (80, 24), (50, 36)), # Under screen. ("mouse_up", (80, 24), (-10, 36)), # Bottom-left of screen. ("mouse_up", (80, 24), (-10, 12)), # Left of screen. ("mouse_up", (80, 24), (-10, -2)), # Top-left of screen. ("mouse_up", (80, 24), (50, -2)), # Above screen. ("mouse_up", (80, 24), (100, -2)), # Top-right of screen. # ("mouse_up", (5, 5), (7, 3)), # Right of screen. ("mouse_up", (5, 5), (7, 7)), # Bottom-right of screen. ("mouse_up", (5, 5), (3, 7)), # Under screen. ("mouse_up", (5, 5), (-1, 7)), # Bottom-left of screen. ("mouse_up", (5, 5), (-1, 3)), # Left of screen. ("mouse_up", (5, 5), (-1, -1)), # Top-left of screen. ("mouse_up", (5, 5), (3, -1)), # Above screen. ("mouse_up", (5, 5), (7, -1)), # Top-right of screen. ], ) async def test_pilot_target_outside_screen_errors(method, screen_size, offset): """Make sure that targeting a click/hover completely outside of the screen errors.""" app = App() async with app.run_test(size=screen_size) as pilot: pilot_method = getattr(pilot, method) with pytest.raises(OutOfBounds): await pilot_method(offset=offset) @pytest.mark.parametrize( ["method", "offset"], [ ("click", (0, 0)), # Top-left corner. ("click", (40, 0)), # Top edge. ("click", (79, 0)), # Top-right corner. ("click", (79, 12)), # Right edge. ("click", (79, 23)), # Bottom-right corner. ("click", (40, 23)), # Bottom edge. ("click", (40, 23)), # Bottom-left corner. ("click", (0, 12)), # Left edge. ("click", (40, 12)), # Right in the middle. # ("hover", (0, 0)), # Top-left corner. ("hover", (40, 0)), # Top edge. ("hover", (79, 0)), # Top-right corner. ("hover", (79, 12)), # Right edge. ("hover", (79, 23)), # Bottom-right corner. ("hover", (40, 23)), # Bottom edge. ("hover", (40, 23)), # Bottom-left corner. ("hover", (0, 12)), # Left edge. ("hover", (40, 12)), # Right in the middle. # ("mouse_down", (0, 0)), # Top-left corner. ("mouse_down", (40, 0)), # Top edge. ("mouse_down", (79, 0)), # Top-right corner. ("mouse_down", (79, 12)), # Right edge. ("mouse_down", (79, 23)), # Bottom-right corner. ("mouse_down", (40, 23)), # Bottom edge. ("mouse_down", (40, 23)), # Bottom-left corner. ("mouse_down", (0, 12)), # Left edge. ("mouse_down", (40, 12)), # Right in the middle. # ("mouse_up", (0, 0)), # Top-left corner. ("mouse_up", (40, 0)), # Top edge. ("mouse_up", (79, 0)), # Top-right corner. ("mouse_up", (79, 12)), # Right edge. ("mouse_up", (79, 23)), # Bottom-right corner. ("mouse_up", (40, 23)), # Bottom edge. ("mouse_up", (40, 23)), # Bottom-left corner. ("mouse_up", (0, 12)), # Left edge. ("mouse_up", (40, 12)), # Right in the middle. ], ) async def test_pilot_target_inside_screen_is_fine_with_correct_coordinate_system( method, offset ): """Make sure that the coordinate system for the click is the correct one. Especially relevant because I kept getting confused about the way it works. """ app = ManyLabelsApp() async with app.run_test(size=(80, 24)) as pilot: app.query_one("#label99").scroll_visible(animate=False) await pilot.pause() pilot_method = getattr(pilot, method) await pilot_method(offset=offset) @pytest.mark.parametrize( ["method", "target"], [ ("click", "#label0"), ("click", "#label90"), ("click", Button), # ("hover", "#label0"), ("hover", "#label90"), ("hover", Button), # ("mouse_down", "#label0"), ("mouse_down", "#label90"), ("mouse_down", Button), # ("mouse_up", "#label0"), ("mouse_up", "#label90"), ("mouse_up", Button), ], ) async def test_pilot_target_on_widget_that_is_not_visible_errors(method, target): """Make sure that clicking a widget that is not scrolled into view raises an error.""" app = ManyLabelsApp() async with app.run_test(size=(80, 5)) as pilot: app.query_one("#label50").scroll_visible(animate=False) await pilot.pause() pilot_method = getattr(pilot, method) with pytest.raises(OutOfBounds): await pilot_method(target) @pytest.mark.parametrize("method", ["click", "hover", "mouse_down", "mouse_up"]) async def test_pilot_target_widget_under_another_widget(method): """The targeting method should return False when the targeted widget is covered.""" class ObscuredButton(App): CSS = """ Label { width: 30; height: 5; } """ def compose(self): yield Button() yield Label() def on_mount(self): self.query_one(Label).styles.offset = (0, -3) app = ObscuredButton() async with app.run_test() as pilot: await pilot.pause() pilot_method = getattr(pilot, method) assert (await pilot_method(Button)) is False @pytest.mark.parametrize("method", ["click", "hover", "mouse_down", "mouse_up"]) async def test_pilot_target_visible_widget(method): """The targeting method should return True when the targeted widget is hit.""" class ObscuredButton(App): def compose(self): yield Button() app = ObscuredButton() async with app.run_test() as pilot: await pilot.pause() pilot_method = getattr(pilot, method) assert (await pilot_method(Button)) is True @pytest.mark.parametrize( ["method", "offset"], [ ("click", (0, 0)), ("click", (2, 0)), ("click", (10, 23)), ("click", (70, 0)), # ("hover", (0, 0)), ("hover", (2, 0)), ("hover", (10, 23)), ("hover", (70, 0)), # ("mouse_down", (0, 0)), ("mouse_down", (2, 0)), ("mouse_down", (10, 23)), ("mouse_down", (70, 0)), # ("mouse_up", (0, 0)), ("mouse_up", (2, 0)), ("mouse_up", (10, 23)), ("mouse_up", (70, 0)), ], ) async def test_pilot_target_screen_always_true(method, offset): app = ManyLabelsApp() async with app.run_test(size=(80, 24)) as pilot: pilot_method = getattr(pilot, method) assert (await pilot_method(offset=offset)) is True async def test_pilot_resize_terminal(): app = App() async with app.run_test(size=(80, 24)) as pilot: # Sanity checks. assert app.size == (80, 24) assert app.screen.size == (80, 24) await pilot.resize_terminal(27, 15) await pilot.pause() assert app.size == (27, 15) assert app.screen.size == (27, 15) async def test_fail_early(): # https://github.com/Textualize/textual/issues/3282 class MyApp(App): CSS_PATH = "foo.tcss" app = MyApp() with pytest.raises(StylesheetError): async with app.run_test() as pilot: await pilot.press("enter") async def test_click_by_widget(): """Test that click accept a Widget instance.""" pressed = False class TestApp(CenteredButtonApp): def on_button_pressed(self): nonlocal pressed pressed = True app = TestApp() async with app.run_test() as pilot: button = app.query_one(Button) assert not pressed await pilot.click(button) assert pressed @pytest.mark.parametrize("times", [1, 2, 3]) async def test_click_times(times: int): """Test that Pilot.click() can be called with a `times` argument.""" events_received: list[Type[events.Event]] = [] class TestApp(App[None]): def compose(self) -> ComposeResult: yield Label("Click counter") @on(events.Click) @on(events.MouseDown) @on(events.MouseUp) def on_label_clicked(self, event: events.Event): events_received.append(event.__class__) app = TestApp() async with app.run_test() as pilot: await pilot.click(Label, times=times) assert ( events_received == [events.MouseDown, events.MouseUp, events.Click] * times )
ManyLabelsApp
python
django__django
tests/model_formsets_regress/models.py
{ "start": 31, "end": 154 }
class ____(models.Model): username = models.CharField(max_length=12, unique=True) serial = models.IntegerField()
User
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/PColorMeshItem.py
{ "start": 594, "end": 1931 }
class ____: def __init__(self): self.nrows = -1 self.ncols = -1 self.pointsarray = Qt.internals.PrimitiveArray(QtCore.QPointF, 2) self.resize(0, 0) def resize(self, nrows, ncols): if nrows == self.nrows and ncols == self.ncols: return self.nrows = nrows self.ncols = ncols # (nrows + 1) * (ncols + 1) vertices, (x, y) self.pointsarray.resize((nrows+1)*(ncols+1)) points = self.pointsarray.instances() # points is a flattened list of a 2d array of # QPointF(s) of shape (nrows+1, ncols+1) # pre-create quads from those instances of QPointF(s). # store the quads as a flattened list of a 2d array # of polygons of shape (nrows, ncols) polys = np.ndarray(nrows*ncols, dtype=object) for r in range(nrows): for c in range(ncols): bl = points[(r+0)*(ncols+1)+(c+0)] tl = points[(r+0)*(ncols+1)+(c+1)] br = points[(r+1)*(ncols+1)+(c+0)] tr = points[(r+1)*(ncols+1)+(c+1)] poly = (bl, br, tr, tl) polys[r*ncols+c] = poly self.polys = polys def ndarray(self): return self.pointsarray.ndarray() def instances(self): return self.polys
QuadInstances
python
pytest-dev__pytest-django
tests/test_fixtures.py
{ "start": 15700, "end": 24855 }
class ____: @pytest.mark.skipif("PYTEST_XDIST_WORKER" in os.environ, reason="xdist in use") def test_settings_before(self) -> None: from django.conf import settings assert ( f"{settings.__class__.__module__}.{settings.__class__.__name__}" == "django.conf.Settings" ) TestLiveServer._test_settings_before_run = True # type: ignore[attr-defined] def test_url(self, live_server: LiveServer) -> None: assert live_server.url == force_str(live_server) def test_change_settings( self, live_server: LiveServer, settings: SettingsWrapper, # noqa: ARG002 ) -> None: assert live_server.url == force_str(live_server) @pytest.mark.skipif("PYTEST_XDIST_WORKER" in os.environ, reason="xdist in use") def test_settings_restored(self) -> None: """Ensure that settings are restored after test_settings_before.""" from django.conf import settings assert TestLiveServer._test_settings_before_run is True # type: ignore[attr-defined] assert ( f"{settings.__class__.__module__}.{settings.__class__.__name__}" == "django.conf.Settings" ) assert settings.ALLOWED_HOSTS == ["testserver"] def test_transactions(self, live_server: LiveServer) -> None: # noqa: ARG002 if not connection.features.supports_transactions: pytest.skip("transactions required for this test") assert not connection.in_atomic_block def test_db_changes_visibility(self, live_server) -> None: response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 0" Item.objects.create(name="foo") response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 1" def test_fixture_db( self, db: None, # noqa: ARG002 live_server: LiveServer, ) -> None: Item.objects.create(name="foo") response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 1" def test_fixture_transactional_db( self, transactional_db: None, # noqa: ARG002 live_server: LiveServer, ) -> None: Item.objects.create(name="foo") response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 1" @pytest.fixture def item(self) -> Item: # This has not requested database access explicitly, but the # live_server fixture auto-uses the transactional_db fixture. item: Item = Item.objects.create(name="foo") return item def test_item(self, item: Item, live_server: LiveServer) -> None: pass @pytest.fixture def item_db(self, db: None) -> Item: # noqa: ARG002 item: Item = Item.objects.create(name="foo") return item def test_item_db( self, item_db: Item, # noqa: ARG002 live_server, ) -> None: response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 1" @pytest.fixture def item_transactional_db(self, transactional_db: None) -> Item: # noqa: ARG002 item: Item = Item.objects.create(name="foo") return item def test_item_transactional_db( self, item_transactional_db: Item, # noqa: ARG002 live_server: LiveServer, ) -> None: response_data = urlopen(live_server + "/item_count/").read() assert force_str(response_data) == "Item count: 1" @pytest.mark.django_project( extra_settings=""" INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'tpkg.app', ] STATIC_URL = '/static/' """ ) def test_serve_static_with_staticfiles_app( self, django_pytester: DjangoPytester, ) -> None: """ LiveServer always serves statics with ``django.contrib.staticfiles`` handler. """ django_pytester.create_test_module( """ from urllib.request import urlopen from django.utils.encoding import force_str class TestLiveServer: def test_a(self, live_server, settings): assert ('django.contrib.staticfiles' in settings.INSTALLED_APPS) response_data = urlopen( live_server + '/static/a_file.txt').read() assert force_str(response_data) == 'bla\\n' """ ) result = django_pytester.runpytest_subprocess("--tb=short", "-v") result.stdout.fnmatch_lines(["*test_a*PASSED*"]) assert result.ret == 0 def test_serve_static_dj17_without_staticfiles_app(self, live_server) -> None: """ Because ``django.contrib.staticfiles`` is not installed LiveServer can not serve statics with django >= 1.7 . """ with pytest.raises(HTTPError): urlopen(live_server + "/static/a_file.txt").read() def test_specified_port_django_111(self, django_pytester: DjangoPytester) -> None: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.bind(("", 0)) __, port = sock.getsockname() finally: sock.close() django_pytester.create_test_module( f""" def test_with_live_server(live_server): assert live_server.port == {port} """ ) django_pytester.runpytest_subprocess(f"--liveserver=localhost:{port}") @pytest.mark.parametrize("username_field", ["email", "identifier"]) @pytest.mark.django_project( extra_settings=""" AUTH_USER_MODEL = 'app.MyCustomUser' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tpkg.app', ] ROOT_URLCONF = 'tpkg.app.urls' """ ) def test_custom_user_model(django_pytester: DjangoPytester, username_field: str) -> None: django_pytester.create_app_file( f""" from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class MyCustomUserManager(BaseUserManager): def create_user(self, {username_field}, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) user = self.model({username_field}={username_field}, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, {username_field}, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user( {username_field}={username_field}, password=password, **extra_fields ) class MyCustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) identifier = models.CharField(unique=True, max_length=100) is_staff = models.BooleanField( 'staff status', default=False, help_text='Designates whether the user can log into this admin site.' ) objects = MyCustomUserManager() USERNAME_FIELD = '{username_field}' """, "models.py", ) django_pytester.create_app_file( """ from django.urls import path from tpkg.app import views urlpatterns = [path('admin-required/', views.admin_required_view)] """, "urls.py", ) django_pytester.create_app_file( """ from django.http import HttpResponse from django.template import Template from django.template.context import Context def admin_required_view(request): assert request.user.is_staff return HttpResponse(Template('You are an admin').render(Context())) """, "views.py", ) django_pytester.makepyfile( """ from django.utils.encoding import force_str from tpkg.app.models import MyCustomUser def test_custom_user_model(admin_client): resp = admin_client.get('/admin-required/') assert force_str(resp.content) == 'You are an admin' """ ) django_pytester.create_app_file("", "migrations/__init__.py") django_pytester.create_app_file( """ from django.db import models, migrations import django.utils.timezone import django.core.validators
TestLiveServer
python
doocs__leetcode
solution/1900-1999/1912.Design Movie Rental System/Solution.py
{ "start": 0, "end": 1283 }
class ____: def __init__(self, n: int, entries: List[List[int]]): self.available = defaultdict(lambda: SortedList()) self.price_map = {} for shop, movie, price in entries: self.available[movie].add((price, shop)) self.price_map[self.f(shop, movie)] = price self.rented = SortedList() def search(self, movie: int) -> List[int]: return [shop for _, shop in self.available[movie][:5]] def rent(self, shop: int, movie: int) -> None: price = self.price_map[self.f(shop, movie)] self.available[movie].remove((price, shop)) self.rented.add((price, shop, movie)) def drop(self, shop: int, movie: int) -> None: price = self.price_map[self.f(shop, movie)] self.rented.remove((price, shop, movie)) self.available[movie].add((price, shop)) def report(self) -> List[List[int]]: return [[shop, movie] for _, shop, movie in self.rented[:5]] def f(self, shop: int, movie: int) -> int: return shop << 30 | movie # Your MovieRentingSystem object will be instantiated and called as such: # obj = MovieRentingSystem(n, entries) # param_1 = obj.search(movie) # obj.rent(shop,movie) # obj.drop(shop,movie) # param_4 = obj.report()
MovieRentingSystem
python
huggingface__transformers
src/transformers/models/lfm2_moe/configuration_lfm2_moe.py
{ "start": 739, "end": 8379 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Lfm2MoeModel`]. It is used to instantiate a LFM2 Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the LFM2-8B-A1B model. e.g. [LiquidAI/LFM2-8B-A1B](https://huggingface.co/LiquidAI/LFM2-8B-A1B) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 65536): Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Lfm2Model`] hidden_size (`int`, *optional*, defaults to 2048): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 7168): Dimension of the MLP representations. moe_intermediate_size (`int`, *optional*, defaults to 1792): Intermediate size of the routed expert. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `True`): Whether to tie weight embeddings rope_parameters (`RopeParameters`, *optional*): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`. max_position_embeddings (`int`, *optional*, defaults to 128000): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`. conv_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in the conv layers. conv_L_cache (`int`, *optional*, defaults to 3): L_cache dim in the conv layers. num_dense_layers (`int`, *optional*, defaults to 2): Number of dense Lfm2MoeMLP layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head). num_experts_per_tok (`int`, *optional*, defaults to 4): Number of selected experts. num_experts (`int`, *optional*, defaults to 32): Number of routed experts. use_expert_bias (`bool`, *optional*, defaults to `True`): Whether to use the expert bias on the routing weights. routed_scaling_factor (`float`, *optional*, defaults to 1.0): Scaling factor for routed experts in MoE models. norm_topk_prob (`bool`, *optional*, defaults to `True`): Whether to normalize the topk probabilities. layer_types (`Optional`, *optional*): Type of each layers. ```python >>> from transformers import Lfm2MoeModel, Lfm2MoeConfig >>> # Initializing a LFM2 Moe model >>> configuration = Lfm2MoeConfig() >>> # Initializing a model from the LFM2-8B-A1B style configuration >>> model = Lfm2MoeModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "lfm2_moe" keys_to_ignore_at_inference = ["past_key_values"] default_theta = 1000000.0 def __init__( self, vocab_size: int = 65536, hidden_size: int = 2048, intermediate_size: int = 7168, moe_intermediate_size: int = 1792, num_hidden_layers: int = 32, pad_token_id: int = 0, bos_token_id: int = 1, eos_token_id: int = 2, tie_word_embeddings: bool = True, rope_parameters: RopeParameters = None, max_position_embeddings: int = 128_000, initializer_range: float = 0.02, use_cache: bool = True, norm_eps: float = 0.00001, num_attention_heads: int = 32, num_key_value_heads: int = 8, conv_bias: bool = False, conv_L_cache: int = 3, num_dense_layers: int = 2, num_experts_per_tok: int = 4, num_experts: int = 32, use_expert_bias: bool = True, routed_scaling_factor: float = 1.0, norm_topk_prob: bool = True, layer_types: Optional[list[str]] = None, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.use_cache = use_cache self.norm_eps = norm_eps # attn operator config self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads # custom operator config self.conv_bias = conv_bias self.conv_L_cache = conv_L_cache # moe config self.num_dense_layers = num_dense_layers self.moe_intermediate_size = moe_intermediate_size self.num_experts_per_tok = num_experts_per_tok self.num_experts = num_experts self.use_expert_bias = use_expert_bias self.routed_scaling_factor = routed_scaling_factor self.norm_topk_prob = norm_topk_prob self.layer_types = layer_types self.rope_parameters = rope_parameters tie_word_embeddings = kwargs.get("tie_embedding", tie_word_embeddings) # to fit original config keys super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) __all__ = ["Lfm2MoeConfig"]
Lfm2MoeConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchSequence1.py
{ "start": 18109, "end": 22374 }
class ____(Enum): A = 1 B = 2 C = 3 def test_tuple_with_subpattern( subj: Literal[MyEnum.A] | tuple[Literal[MyEnum.B], int] | tuple[Literal[MyEnum.C], str], ): match subj: case MyEnum.A: reveal_type(subj, expected_text="Literal[MyEnum.A]") case (MyEnum.B, a): reveal_type(subj, expected_text="tuple[Literal[MyEnum.B], int]") reveal_type(a, expected_text="int") case (MyEnum.C, b): reveal_type(subj, expected_text="tuple[Literal[MyEnum.C], str]") reveal_type(b, expected_text="str") def test_unbounded_tuple1( subj: tuple[int] | tuple[str, str] | tuple[int, Unpack[tuple[str, ...]], complex], ): match subj: case (x,): reveal_type(subj, expected_text="tuple[int]") reveal_type(x, expected_text="int") case (x, y): reveal_type(subj, expected_text="tuple[str, str] | tuple[int, complex]") reveal_type(x, expected_text="str | int") reveal_type(y, expected_text="str | complex") case (x, y, z): reveal_type(subj, expected_text="tuple[int, str, complex]") reveal_type(x, expected_text="int") reveal_type(y, expected_text="str") reveal_type(z, expected_text="complex") def test_unbounded_tuple_2(subj: tuple[int, str, Unpack[tuple[range, ...]]]) -> None: match subj: case [1, *ts1]: reveal_type(ts1, expected_text="list[str | range]") case [1, "", *ts2]: reveal_type(ts2, expected_text="list[range]") def test_unbounded_tuple_3(subj: tuple[int, ...]): match subj: case []: return case x: reveal_type(x, expected_text="tuple[int, ...]") def test_unbounded_tuple_4(subj: tuple[str, ...]): match subj: case x, "": reveal_type(subj, expected_text="tuple[str, Literal['']]") case (x,): reveal_type(subj, expected_text="tuple[str]") case x: reveal_type(subj, expected_text="tuple[str, ...]") def test_unbounded_tuple_5(subj: tuple[int, Unpack[tuple[str, ...]]]): match subj: case x, *rest: reveal_type(subj, expected_text="tuple[int, *tuple[str, ...]]") reveal_type(x, expected_text="int") reveal_type(rest, expected_text="list[str]") case x: reveal_type(x, expected_text="Never") def test_unbounded_tuple_6(subj: tuple[str, ...]): match subj: case ("a", b, _, _): reveal_type(b, expected_text="str") case ("a", b, _, _, _): reveal_type(b, expected_text="str") case (_, b, _, _): reveal_type(b, expected_text="str") case (_, b, _, _, _): reveal_type(b, expected_text="str") case r: reveal_type(r, expected_text="tuple[str, ...]") def test_unbound_tuple_7(subj: tuple[str, Unpack[tuple[object, ...]], int]): match subj: case (*args,): reveal_type(args, expected_text="list[str | object | int]") case a: reveal_type(a, expected_text="Never") match subj: case (*args, last): reveal_type(args, expected_text="list[str | object]") reveal_type(last, expected_text="int") case a: reveal_type(a, expected_text="Never") match subj: case (first, *args, last): reveal_type(first, expected_text="str") reveal_type(args, expected_text="list[object]") reveal_type(last, expected_text="int") case a: reveal_type(a, expected_text="Never") match subj: case (first, second, *args, last): reveal_type(first, expected_text="str") reveal_type(second, expected_text="object") reveal_type(args, expected_text="list[object]") reveal_type(last, expected_text="int") case a: reveal_type(a, expected_text="tuple[str, *tuple[object, ...], int]") def test_variadic_tuple(subj: tuple[int, Unpack[Ts]]) -> tuple[Unpack[Ts]]: match subj: case _, *rest: reveal_type(rest, expected_text="list[Unknown]") return (*rest,)
MyEnum
python
spack__spack
lib/spack/spack/util/parallel.py
{ "start": 257, "end": 1023 }
class ____: """Wrapper class to report an error from a worker process""" def __init__(self, exc_cls, exc, tb): """Create an error object from an exception raised from the worker process. The attributes of the process error objects are all strings as they are easy to send over a pipe. Args: exc: exception raised from the worker process """ self.pid = os.getpid() self.error_message = str(exc) self.stacktrace_message = "".join(traceback.format_exception(exc_cls, exc, tb)) @property def stacktrace(self): msg = "[PID={0.pid}] {0.stacktrace_message}" return msg.format(self) def __str__(self): return self.error_message
ErrorFromWorker
python
pytorch__pytorch
torch/_dynamo/variables/builder.py
{ "start": 169092, "end": 169959 }
class ____: """ SourceLessBuilder does not return a UserDefinedObjectVariable, but in some cases it might be ok to return UserDefinedObjects. In such case, use this builder. """ def __init__(self) -> None: raise AssertionError("Use SourcelessUserDefinedObjectBuilder.create()") @staticmethod def create(tx: "InstructionTranslator", value) -> VariableTracker: value_type = type(value) if issubclass(value_type, MutableMapping): return MutableMappingVariable(value, mutation_type=ValueMutationNew()) elif isinstance(value, torch.nn.Module): return UnspecializedNNModuleVariable( value, mutation_type=ValueMutationNew() ) else: return UserDefinedObjectVariable(value, mutation_type=ValueMutationNew())
SourcelessUserDefinedObjectBuilder
python
getsentry__sentry
src/sentry/users/api/endpoints/userroles_details.py
{ "start": 693, "end": 3783 }
class ____(Endpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } permission_classes = (SuperuserPermission,) @sudo_required def get(self, request: Request, role_name: str) -> Response: # XXX(dcramer): we may decide to relax "view" permission over time, but being more restrictive by default # is preferred if not request.access.has_permission("users.admin"): return self.respond(status=403) try: role = UserRole.objects.get(name=role_name) except UserRole.DoesNotExist: return self.respond({"detail": f"'{role_name}' is not a known role."}, status=404) return self.respond(serialize(role, user=request.user, serializer=UserRoleSerializer())) @sudo_required def put(self, request: Request, role_name: str) -> Response: if not request.access.has_permission("users.admin"): return self.respond(status=403) try: role = UserRole.objects.get(name=role_name) except UserRole.DoesNotExist: return self.respond({"detail": f"'{role_name}' is not a known role."}, status=404) validator = UserRoleValidator(data=request.data, partial=True) if not validator.is_valid(): return self.respond(validator.errors, status=400) result = validator.validated_data try: with transaction.atomic(using=router.db_for_write(UserRole)): if "name" in result: role.name = result["name"] if "permissions" in result: role.permissions = result["permissions"] role.save(update_fields=result.keys()) audit_logger.info( "user-roles.edit", extra={ "actor_id": request.user.id, "role_id": role.id, "form_data": request.data, }, ) except IntegrityError as e: if "already exists" in str(e): return self.respond(status=410) raise return self.respond(serialize(role, user=request.user, serializer=UserRoleSerializer())) @sudo_required def delete(self, request: Request, role_name: str) -> Response: if not request.access.has_permission("users.admin"): return self.respond(status=403) try: role = UserRole.objects.get(name=role_name) except UserRole.DoesNotExist: return self.respond({"detail": f"'{role_name}' is not a known role."}, status=404) with transaction.atomic(using=router.db_for_write(UserRole)): role.delete() audit_logger.info( "user-roles.delete", extra={ "actor_id": request.user.id, "role_id": role.id, }, ) return self.respond(status=204)
UserRoleDetailsEndpoint
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 6421, "end": 6931 }
class ____(BaseModel): class Config: extra = Extra.allow type: Literal["CustomRequester"] class_name: str = Field( ..., description="Fully-qualified name of the class that will be implementing the custom requester strategy. The format is `source_<name>.<package>.<class_name>`.", examples=["source_railz.components.MyCustomRecordExtractor"], title="Class Name", ) parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
CustomRequester
python
fluentpython__example-code-2e
22-dyn-attr-prop/oscon/explore2.py
{ "start": 652, "end": 1496 }
class ____: """A read-only façade for navigating a JSON-like object using attribute notation """ def __new__(cls, arg): # <1> if isinstance(arg, abc.Mapping): return super().__new__(cls) # <2> elif isinstance(arg, abc.MutableSequence): # <3> return [cls(item) for item in arg] else: return arg def __init__(self, mapping): self.__data = {} for key, value in mapping.items(): if keyword.iskeyword(key): key += '_' self.__data[key] = value def __getattr__(self, name): try: return getattr(self.__data, name) except AttributeError: return FrozenJSON(self.__data[name]) # <4> def __dir__(self): return self.__data.keys() # end::EXPLORE2[]
FrozenJSON
python
pandas-dev__pandas
asv_bench/benchmarks/algos/isin.py
{ "start": 4297, "end": 4877 }
class ____: params = [ [np.float64, np.int64, np.uint64, np.object_], [ 1_000, 2_000, 8_000, ], [-2, 0, 2], ] param_names = ["dtype", "M", "offset_factor"] def setup(self, dtype, M, offset_factor): offset = int(M * offset_factor) tmp = Series(np.random.randint(offset, M + offset, 10**6)) self.series = tmp.astype(dtype) self.values = np.arange(M).astype(dtype) def time_isin(self, dtype, M, offset_factor): self.series.isin(self.values)
IsinWithArange
python
dagster-io__dagster
python_modules/dagster/dagster/components/utils/translation.py
{ "start": 829, "end": 4850 }
class ____: asset_attributes: Union[str, BaseModel] resolution_context: ResolutionContext model_key: str = "asset_attributes" def _resolve_asset_attributes(self, context: Mapping[str, Any]) -> Union[AssetSpec, BaseModel]: """Resolves the user-specified asset attributes into an AssetAttributesModel, or an AssetSpec if the UDF returns one. """ if not isinstance(self.asset_attributes, str): return self.asset_attributes resolved_asset_attributes = ( self.resolution_context.at_path(self.model_key) .with_scope(**context) .resolve_value(self.asset_attributes) ) if isinstance(resolved_asset_attributes, AssetSpec): return resolved_asset_attributes elif isinstance(resolved_asset_attributes, AssetAttributesModel): return resolved_asset_attributes elif isinstance(resolved_asset_attributes, dict): return AssetAttributesModel(**(resolved_asset_attributes)) else: check.failed( f"Unexpected return value for asset_attributes UDF: {type(resolved_asset_attributes)}" ) def get_asset_spec(self, base_spec: AssetSpec, context: Mapping[str, Any]) -> AssetSpec: """Returns an AssetSpec that combines the base spec with attributes resolved using the provided context. Usage: ```python class WrappedDagsterXTranslator(DagsterXTranslator): def __init__(self, *, base_translator, resolving_info: TranslatorResolvingInfo): self.base_translator = base_translator self.resolving_info = resolving_info def get_asset_spec(self, base_spec: AssetSpec, x_params: Any) -> AssetSpec: return self.resolving_info.get_asset_spec( base_spec, {"x_params": x_params} ) ``` """ resolved_asset_attributes = self._resolve_asset_attributes(context) if isinstance(resolved_asset_attributes, AssetSpec): return resolved_asset_attributes resolved_attributes = dict( resolve_asset_spec_update_kwargs_to_mapping( model=resolved_asset_attributes, context=self.resolution_context.at_path(self.model_key).with_scope(**context), ) ) if "code_version" in resolved_attributes: resolved_attributes = { **resolved_attributes, "code_version": str(resolved_attributes["code_version"]), } if "key_prefix" in resolved_attributes: prefix = resolved_attributes.pop("key_prefix") if "key" in resolved_attributes: key = resolved_attributes.pop("key") else: key = base_spec.key key = key.with_prefix(prefix) resolved_attributes["key"] = key return base_spec.replace_attributes( **{k: v for k, v in resolved_attributes.items() if k not in TRANSLATOR_MERGE_ATTRIBUTES} ).merge_attributes( **{k: v for k, v in resolved_attributes.items() if k in TRANSLATOR_MERGE_ATTRIBUTES} ) T = TypeVar("T") TranslationFn: TypeAlias = Callable[[AssetSpec, T], AssetSpec] def _build_translation_fn( template_vars_for_translation_fn: Callable[[T], Mapping[str, Any]], ) -> Callable[[ResolutionContext, T], TranslationFn[T]]: def resolve_translation( context: ResolutionContext, model, ) -> TranslationFn[T]: info = TranslatorResolvingInfo( asset_attributes=model, resolution_context=context, model_key="translation", ) return lambda base_asset_spec, data: info.get_asset_spec( base_asset_spec, { **(template_vars_for_translation_fn(data)), "spec": base_asset_spec, }, ) return resolve_translation
TranslatorResolvingInfo
python
ansible__ansible
test/lib/ansible_test/_internal/completion.py
{ "start": 7114, "end": 8078 }
class ____(RemoteCompletionConfig, PythonCompletionConfig): """Configuration for remote POSIX platforms.""" become: t.Optional[str] = None placeholder: bool = False def __post_init__(self): if not self.placeholder: super().__post_init__() if self.become and self.become not in SUPPORTED_BECOME_METHODS: raise Exception(f'POSIX remote completion entry "{self.name}" setting "become" must be omitted or one of: {", ".join(SUPPORTED_BECOME_METHODS)}') if not self.supported_pythons: if self.version and not self.placeholder: raise Exception(f'POSIX remote completion entry "{self.name}" must provide a "python" setting.') else: if not self.version: raise Exception(f'POSIX remote completion entry "{self.name}" is a platform default and cannot provide a "python" setting.') @dataclasses.dataclass(frozen=True)
PosixRemoteCompletionConfig
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/regression.py
{ "start": 684, "end": 1228 }
class ____(): """ Regularization for Elastic Net Regression """ def __init__(self, alpha, l1_ratio=0.5): self.alpha = alpha self.l1_ratio = l1_ratio def __call__(self, w): l1_contr = self.l1_ratio * np.linalg.norm(w) l2_contr = (1 - self.l1_ratio) * 0.5 * w.T.dot(w) return self.alpha * (l1_contr + l2_contr) def grad(self, w): l1_contr = self.l1_ratio * np.sign(w) l2_contr = (1 - self.l1_ratio) * w return self.alpha * (l1_contr + l2_contr)
l1_l2_regularization
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 100831, "end": 101179 }
class ____(InMemoryNetCDF): def test_roundtrip_group_via_memoryview(self) -> None: original = create_test_data() netcdf_bytes = original.to_netcdf(group="sub", engine=self.engine) roundtrip = load_dataset(netcdf_bytes, group="sub", engine=self.engine) assert_identical(roundtrip, original)
InMemoryNetCDFWithGroups
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/sensors.py
{ "start": 2509, "end": 2736 }
class ____(graphene.ObjectType): assetKeys = graphene.List(graphene.NonNull(GrapheneAssetKey)) class Meta: name = "SensorMetadata" GrapheneSensorType = graphene.Enum.from_enum(SensorType)
GrapheneSensorMetadata
python
spulec__freezegun
tests/test_datetimes.py
{ "start": 21795, "end": 29694 }
class ____: def test_direct_method(self) -> None: # Make sure old style classes (not inheriting from object) is supported @freeze_time('2013-04-09') class OldStyleClass: def method(self) -> datetime.date: return datetime.date.today() assert OldStyleClass().method() == datetime.date(2013, 4, 9) def test_inherited_method(self) -> None: class OldStyleBaseClass: def inherited_method(self) -> datetime.date: return datetime.date.today() @freeze_time('2013-04-09') class OldStyleClass(OldStyleBaseClass): pass assert OldStyleClass().inherited_method() == datetime.date(2013, 4, 9) def test_min_and_max() -> None: freezer = freeze_time("2012-01-14") real_datetime = datetime.datetime real_date = datetime.date freezer.start() assert datetime.datetime.min.__class__ == FakeDatetime assert datetime.datetime.max.__class__ == FakeDatetime assert datetime.date.min.__class__ == FakeDate assert datetime.date.max.__class__ == FakeDate assert datetime.datetime.min.__class__ != real_datetime assert datetime.datetime.max.__class__ != real_datetime assert datetime.date.min.__class__ != real_date assert datetime.date.max.__class__ != real_date freezer.stop() assert datetime.datetime.min.__class__ == datetime.datetime assert datetime.datetime.max.__class__ == datetime.datetime assert datetime.date.min.__class__ == datetime.date assert datetime.date.max.__class__ == datetime.date assert datetime.datetime.min.__class__ != FakeDatetime assert datetime.datetime.max.__class__ != FakeDatetime assert datetime.date.min.__class__ != FakeDate assert datetime.date.max.__class__ != FakeDate @freeze_time("2014-07-30T01:00:00Z") def test_freeze_with_timezone_aware_datetime_in_utc() -> None: """ utcnow() should always return a timezone naive datetime """ utc_now = datetime.datetime.utcnow() assert utc_now.tzinfo is None @freeze_time("1970-01-01T00:00:00-04:00") def test_freeze_with_timezone_aware_datetime_in_non_utc() -> None: """ we expect the system to behave like a system with UTC-4 timezone at the beginning of the Epoch (wall clock should be 4 hrs late) """ utc_now = datetime.datetime.utcnow() assert utc_now.tzinfo is None assert utc_now == datetime.datetime(1970, 1, 1, 4) @freeze_time('2015-01-01') def test_time_with_nested() -> None: from time import time first = 1420070400.0 second = 1420070760.0 assert time() == first with freeze_time('2015-01-01T00:06:00'): assert time() == second @pytest.mark.parametrize("func_name", ("monotonic", "perf_counter") ) def test_monotonic_with_nested(func_name: str) -> None: __import__("time", fromlist=[func_name]) invoke_time_func: Callable[[], float] = lambda: getattr(time, func_name)() with freeze_time('2015-01-01') as frozen_datetime_1: initial_t1 = invoke_time_func() with freeze_time('2015-12-25') as frozen_datetime_2: initial_t2 = invoke_time_func() frozen_datetime_2.tick() assert invoke_time_func() == initial_t2 + 1 assert invoke_time_func() == initial_t1 frozen_datetime_1.tick() assert invoke_time_func() == initial_t1 + 1 def test_should_use_real_time() -> None: frozen = datetime.datetime(2015, 3, 5) expected_frozen = 1425513600.0 # TODO: local time seems to leak the local timezone, so this test fails in CI # expected_frozen_local = (2015, 3, 5, 1, 0, 0, 3, 64, -1) expected_frozen_gmt = (2015, 3, 5, 0, 0, 0, 3, 64, -1) expected_clock = 0 from freezegun import api api.call_stack_inspection_limit = 100 # just to increase coverage timestamp_to_convert = 1579602312 time_tuple = time.gmtime(timestamp_to_convert) with freeze_time(frozen): assert time.time() == expected_frozen # assert time.localtime() == expected_frozen_local assert time.gmtime() == expected_frozen_gmt if HAS_CLOCK: assert time.clock() == expected_clock # type: ignore[attr-defined] if HAS_TIME_NS: assert time.time_ns() == expected_frozen * 1e9 assert calendar.timegm(time.gmtime()) == expected_frozen assert calendar.timegm(time_tuple) == timestamp_to_convert with freeze_time(frozen, ignore=['_pytest']): assert time.time() != expected_frozen # assert time.localtime() != expected_frozen_local assert time.gmtime() != expected_frozen_gmt if HAS_CLOCK: assert time.clock() != expected_clock # type: ignore[attr-defined] if HAS_TIME_NS: assert time.time_ns() != expected_frozen * 1e9 assert calendar.timegm(time.gmtime()) != expected_frozen assert calendar.timegm(time_tuple) == timestamp_to_convert @pytest.mark.skipif(not HAS_TIME_NS, reason="time.time_ns is present only on 3.7 and above") def test_time_ns() -> None: freezer = freeze_time("2012-01-14") local_time = datetime.datetime(2012, 1, 14) utc_time = local_time - datetime.timedelta(seconds=time.timezone) expected_timestamp = time.mktime(utc_time.timetuple()) with freezer: assert time.time() == expected_timestamp assert time.time_ns() == expected_timestamp * 1e9 assert time.time() != expected_timestamp assert time.time_ns() != expected_timestamp * 1e9 @pytest.mark.skipif(not HAS_TIME_NS, reason="time.time_ns is present only on 3.7 and above") def test_time_ns_with_microseconds() -> None: freezer = freeze_time("2024-03-20 18:21:10.12345") with freezer: assert time.time_ns() == 1710958870123450112 assert time.time_ns() != 1710958870123450112 def test_compare_datetime_and_time_with_timezone(monkeypatch: pytest.MonkeyPatch) -> None: """ Compare the result of datetime.datetime.now() and time.time() in a non-UTC timezone. These should be consistent. """ try: with monkeypatch.context() as m, freeze_time("1970-01-01 00:00:00"): m.setenv("TZ", "Europe/Berlin") time.tzset() now = datetime.datetime.now() assert now == datetime.datetime.fromtimestamp(time.time()) assert now == datetime.datetime.utcfromtimestamp(time.time()) assert now == datetime.datetime.utcnow() assert now.timestamp() == time.time() finally: time.tzset() # set the timezone back to what is was before def test_timestamp_with_tzoffset() -> None: with freeze_time("2000-01-01", tz_offset=6): utcnow = datetime.datetime(2000, 1, 1, 0) nowtz = datetime.datetime(2000, 1, 1, 0, tzinfo=UTC) now = datetime.datetime(2000, 1, 1, 6) assert now == datetime.datetime.now() assert now == datetime.datetime.fromtimestamp(time.time()) assert now.timestamp() == time.time() assert nowtz.timestamp() == time.time() assert utcnow == datetime.datetime.utcfromtimestamp(time.time()) assert utcnow == datetime.datetime.utcnow() @pytest.mark.skip("timezone handling is currently incorrect") def test_datetime_in_timezone(monkeypatch: pytest.MonkeyPatch) -> None: """ It is assumed that the argument passed to freeze_time is in UTC, unless explicitly indicated otherwise. Therefore datetime.now() should return the frozen time with an offset. """ try: with monkeypatch.context() as m, freeze_time("1970-01-01 00:00:00"): m.setenv("TZ", "Europe/Berlin") time.tzset() assert datetime.datetime.now() == datetime.datetime(1970, 1, 1, 1, 0, 0) finally: time.tzset() # set the timezone back to what is was before
TestOldStyleClasses
python
airbytehq__airbyte
airbyte-integrations/connectors/source-us-census/components.py
{ "start": 4069, "end": 5621 }
class ____(DefaultErrorHandler): """ This Custom Error Handler raises an error when an invalid API key is used. In such cases, the status code is 200, so airbyte doesn't raise an error. """ def interpret_response(self, response_or_exception: Optional[Union[requests.Response, Exception]]) -> ErrorResolution: if self.response_filters: for response_filter in self.response_filters: matched_error_resolution = response_filter.matches(response_or_exception=response_or_exception) if matched_error_resolution: return matched_error_resolution if isinstance(response_or_exception, requests.Response): if response_or_exception.ok: if "Invalid Key" in response_or_exception.text: return ErrorResolution( response_action=ResponseAction.FAIL, failure_type=FailureType.config_error, error_message="Failed to perform request. Error: Valid API Key needed.", ) return SUCCESS_RESOLUTION default_reponse_filter = DefaultHttpResponseFilter(parameters={}, config=self.config) default_response_filter_resolution = default_reponse_filter.matches(response_or_exception) return ( default_response_filter_resolution if default_response_filter_resolution else create_fallback_error_resolution(response_or_exception) ) @dataclass
USCensusErrorHandler
python
pytorch__pytorch
torch/nn/modules/padding.py
{ "start": 12265, "end": 13813 }
class ____(_ConstantPadNd): r"""Pads the input tensor boundaries with a constant value. For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`. Args: padding (int, tuple): the size of the padding. If is `int`, uses the same padding in all boundaries. If a 6-`tuple`, uses (:math:`\text{padding\_left}`, :math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`, :math:`\text{padding\_front}`, :math:`\text{padding\_back}`) Shape: - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where :math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}` :math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}` :math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}` Examples:: >>> m = nn.ConstantPad3d(3, 3.5) >>> input = torch.randn(16, 3, 10, 20, 30) >>> output = m(input) >>> # using different paddings for different sides >>> m = nn.ConstantPad3d((3, 3, 6, 6, 0, 1), 3.5) >>> output = m(input) """ # pyrefly: ignore [bad-override] padding: tuple[int, int, int, int, int, int] def __init__(self, padding: _size_6_t, value: float) -> None: super().__init__(value) self.padding = _ntuple(6)(padding)
ConstantPad3d
python
kamyu104__LeetCode-Solutions
Python/next-closest-time.py
{ "start": 29, "end": 479 }
class ____(object): def nextClosestTime(self, time): """ :type time: str :rtype: str """ h, m = time.split(":") curr = int(h) * 60 + int(m) result = None for i in xrange(curr+1, curr+1441): t = i % 1440 h, m = t // 60, t % 60 result = "%02d:%02d" % (h, m) if set(result) <= set(time): break return result
Solution
python
django__django
tests/m2m_through_regress/models.py
{ "start": 1080, "end": 1296 }
class ____(models.Model): make = models.CharField(max_length=20, unique=True, null=True) drivers = models.ManyToManyField("Driver", through="CarDriver") def __str__(self): return str(self.make)
Car
python
agronholm__apscheduler
src/apscheduler/eventbrokers/psycopg.py
{ "start": 931, "end": 6719 }
class ____(BaseExternalEventBroker): """ An asynchronous, psycopg_ based event broker that uses a PostgreSQL server to broadcast events using its ``NOTIFY`` mechanism. .. _psycopg: https://pypi.org/project/psycopg/ :param conninfo: a libpq connection string (e.g. ``postgres://user:pass@host:port/dbname``) :param options: extra keyword arguments passed to :meth:`psycopg.AsyncConnection.connect` :param channel: the ``NOTIFY`` channel to use :param max_idle_time: maximum time (in seconds) to let the connection go idle, before sending a ``SELECT 1`` query to prevent a connection timeout """ conninfo: str = attrs.field(validator=instance_of(str)) options: Mapping[str, Any] = attrs.field( factory=dict, converter=convert_options, validator=instance_of(Mapping) ) channel: str = attrs.field( kw_only=True, default="apscheduler", validator=instance_of(str) ) max_idle_time: float = attrs.field( kw_only=True, default=10, validator=[instance_of((int, float)), positive_number] ) _send: MemoryObjectSendStream[str] = attrs.field(init=False) @classmethod def from_async_sqla_engine( cls, engine: AsyncEngine, options: Mapping[str, Any] | None = None, **kwargs: Any, ) -> PsycopgEventBroker: """ Create a new psycopg event broker from a SQLAlchemy engine. The engine will only be used to create the appropriate options for :meth:`psycopg.AsyncConnection.connect`. :param engine: an asynchronous SQLAlchemy engine using psycopg as the driver :type engine: ~sqlalchemy.ext.asyncio.AsyncEngine :param options: extra keyword arguments passed to :meth:`psycopg.AsyncConnection.connect` :param kwargs: keyword arguments to pass to the initializer of this class :return: the newly created event broker """ if engine.dialect.driver != "psycopg": raise ValueError( f'The driver in the engine must be "psycopg" (current: ' f"{engine.dialect.driver})" ) conninfo = engine.url.render_as_string(hide_password=False).replace( "+psycopg", "" ) return cls(conninfo, options or {}, **kwargs) def __repr__(self) -> str: return create_repr(self, "conninfo") @property def _temporary_failure_exceptions(self) -> tuple[type[Exception], ...]: return OSError, InterfaceError @asynccontextmanager async def _connect(self) -> AsyncGenerator[AsyncConnection, None]: async for attempt in self._retry(): with attempt: conn = await AsyncConnection.connect(self.conninfo, **self.options) try: yield conn finally: with move_on_after(5, shield=True): await conn.close() async def start(self, exit_stack: AsyncExitStack, logger: Logger) -> None: await super().start(exit_stack, logger) self._send, receive = create_memory_object_stream[str](100) try: await exit_stack.enter_async_context(self._send) await self._task_group.start(self._listen_notifications) exit_stack.callback(self._task_group.cancel_scope.cancel) await self._task_group.start(self._publish_notifications, receive) except BaseException: receive.close() raise async def _listen_notifications(self, *, task_status: TaskStatus[None]) -> None: task_started_sent = False while True: async with self._connect() as conn: try: await conn.execute(f"LISTEN {self.channel}") if not task_started_sent: task_status.started() task_started_sent = True self._logger.debug("Listen connection established") async for notify in conn.notifies(): if event := self.reconstitute_event_str(notify.payload): await self.publish_local(event) except InterfaceError as exc: self._logger.error("Connection error: %s", exc) async def _publish_notifications( self, receive: MemoryObjectReceiveStream[str], *, task_status: TaskStatus[None] ) -> None: task_started_sent = False with receive: while True: async with self._connect() as conn: if not task_started_sent: task_status.started() task_started_sent = True self._logger.debug("Publish connection established") notification: str | None = None while True: with move_on_after(self.max_idle_time): try: notification = await receive.receive() except EndOfStream: return if notification: await conn.execute( "SELECT pg_notify(%t, %t)", [self.channel, notification] ) else: await conn.execute("SELECT 1") async def publish(self, event: Event) -> None: notification = self.generate_notification_str(event) if len(notification) > 7999: raise SerializationError( "Serialized event object exceeds 7999 bytes in size" ) await self._send.send(notification)
PsycopgEventBroker
python
optuna__optuna
optuna/storages/_rdb/alembic/versions/v3.0.0.a.py
{ "start": 2243, "end": 6219 }
class ____(BaseModel): __tablename__ = "trial_params" __table_args__: Any = (UniqueConstraint("trial_id", "param_name"),) param_id = Column(Integer, primary_key=True) trial_id = Column(Integer, ForeignKey("trials.trial_id")) param_name = Column(String(MAX_INDEXED_STRING_LENGTH)) param_value = Column(Float) distribution_json = Column(Text()) def migrate_new_distribution(distribution_json: str) -> str: distribution = json_to_distribution(distribution_json) new_distribution = _convert_old_distribution_to_new_distribution( distribution, suppress_warning=True, ) return distribution_to_json(new_distribution) def restore_old_distribution(distribution_json: str) -> str: distribution = json_to_distribution(distribution_json) old_distribution: BaseDistribution # Float distributions. if isinstance(distribution, FloatDistribution): if distribution.log: old_distribution = LogUniformDistribution( low=distribution.low, high=distribution.high, ) else: if distribution.step is not None: old_distribution = DiscreteUniformDistribution( low=distribution.low, high=distribution.high, q=distribution.step, ) else: old_distribution = UniformDistribution( low=distribution.low, high=distribution.high, ) # Integer distributions. elif isinstance(distribution, IntDistribution): if distribution.log: old_distribution = IntLogUniformDistribution( low=distribution.low, high=distribution.high, step=distribution.step, ) else: old_distribution = IntUniformDistribution( low=distribution.low, high=distribution.high, step=distribution.step, ) # Categorical distribution. else: old_distribution = distribution return distribution_to_json(old_distribution) def persist(session: orm.Session, distributions: list[BaseDistribution]) -> None: if len(distributions) == 0: return session.bulk_save_objects(distributions) session.commit() def upgrade() -> None: bind = op.get_bind() inspector = sa.inspect(bind) tables = inspector.get_table_names() assert "trial_params" in tables session = orm.Session(bind=bind) try: distributions: list[BaseDistribution] = [] for distribution in session.query(TrialParamModel).yield_per(BATCH_SIZE): distribution.distribution_json = migrate_new_distribution( distribution.distribution_json, ) distributions.append(distribution) if len(distributions) == BATCH_SIZE: persist(session, distributions) distributions = [] persist(session, distributions) except SQLAlchemyError as e: session.rollback() raise e finally: session.close() def downgrade() -> None: bind = op.get_bind() inspector = sa.inspect(bind) tables = inspector.get_table_names() assert "trial_params" in tables session = orm.Session(bind=bind) try: distributions = [] for distribution in session.query(TrialParamModel).yield_per(BATCH_SIZE): distribution.distribution_json = restore_old_distribution( distribution.distribution_json, ) distributions.append(distribution) if len(distributions) == BATCH_SIZE: persist(session, distributions) distributions = [] persist(session, distributions) except SQLAlchemyError as e: session.rollback() raise e finally: session.close()
TrialParamModel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor1.py
{ "start": 657, "end": 822 }
class ____(Generic[T]): pass c1: C[bool] | None = C() reveal_type(c1, expected_type="C[bool]") c2: A[int] | C[int] = C() reveal_type(c2, expected_type="C[int]")
C
python
tiangolo__fastapi
scripts/notify_translations.py
{ "start": 1705, "end": 1770 }
class ____(BaseModel): comment: Comment
UpdateDiscussionComment
python
fluentpython__example-code-2e
13-protocol-abc/tombola.py
{ "start": 34, "end": 840 }
class ____(abc.ABC): # <1> @abc.abstractmethod def load(self, iterable): # <2> """Add items from an iterable.""" @abc.abstractmethod def pick(self): # <3> """Remove item at random, returning it. This method should raise `LookupError` when the instance is empty. """ def loaded(self): # <4> """Return `True` if there's at least 1 item, `False` otherwise.""" return bool(self.inspect()) # <5> def inspect(self): """Return a sorted tuple with the items currently inside.""" items = [] while True: # <6> try: items.append(self.pick()) except LookupError: break self.load(items) # <7> return tuple(items) # end::TOMBOLA_ABC[]
Tombola
python
numba__numba
numba/core/datamodel/models.py
{ "start": 43947, "end": 44180 }
class ____(StructModel): """Model for the payload of a mutable struct """ def __init__(self, dmm, fe_typ): members = tuple(fe_typ.field_dict.items()) super().__init__(dmm, fe_typ, members)
StructPayloadModel
python
gevent__gevent
src/greentest/3.14/test_httpservers.py
{ "start": 3646, "end": 12556 }
class ____(BaseTestCase): class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' default_request_version = 'HTTP/1.1' def do_TEST(self): self.send_response(HTTPStatus.NO_CONTENT) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'close') self.end_headers() def do_KEEP(self): self.send_response(HTTPStatus.NO_CONTENT) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'keep-alive') self.end_headers() def do_KEYERROR(self): self.send_error(999) def do_NOTFOUND(self): self.send_error(HTTPStatus.NOT_FOUND) def do_EXPLAINERROR(self): self.send_error(999, "Short Message", "This is a long \n explanation") def do_CUSTOM(self): self.send_response(999) self.send_header('Content-Type', 'text/html') self.send_header('Connection', 'close') self.end_headers() def do_LATINONEHEADER(self): self.send_response(999) self.send_header('X-Special', 'Dängerous Mind') self.send_header('Connection', 'close') self.end_headers() body = self.headers['x-special-incoming'].encode('utf-8') self.wfile.write(body) def do_SEND_ERROR(self): self.send_error(int(self.path[1:])) def do_HEAD(self): self.send_error(int(self.path[1:])) def setUp(self): BaseTestCase.setUp(self) self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() def test_command(self): self.con.request('GET', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_request_line_trimming(self): self.con._http_vsn_str = 'HTTP/1.1\n' self.con.putrequest('XYZBOGUS', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_version_bogus(self): self.con._http_vsn_str = 'FUBAR' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_digits(self): self.con._http_vsn_str = 'HTTP/9.9.9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_signs_and_underscores(self): self.con._http_vsn_str = 'HTTP/-9_9_9.+9_9_9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_major_version_number_too_long(self): self.con._http_vsn_str = 'HTTP/909876543210.0' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_minor_version_number_too_long(self): self.con._http_vsn_str = 'HTTP/1.909876543210' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_none_get(self): self.con._http_vsn_str = '' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_version_none(self): # Test that a valid method is rejected when not HTTP/1.x self.con._http_vsn_str = '' self.con.putrequest('CUSTOM', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_version_invalid(self): self.con._http_vsn = 99 self.con._http_vsn_str = 'HTTP/9.9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED) def test_send_blank(self): self.con._http_vsn_str = '' self.con.putrequest('', '') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) def test_header_close(self): self.con.putrequest('GET', '/') self.con.putheader('Connection', 'close') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_header_keep_alive(self): self.con._http_vsn_str = 'HTTP/1.1' self.con.putrequest('GET', '/') self.con.putheader('Connection', 'keep-alive') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) def test_handler(self): self.con.request('TEST', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NO_CONTENT) def test_return_header_keep_alive(self): self.con.request('KEEP', '/') res = self.con.getresponse() self.assertEqual(res.getheader('Connection'), 'keep-alive') self.con.request('TEST', '/') self.addCleanup(self.con.close) def test_internal_key_error(self): self.con.request('KEYERROR', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) def test_return_custom_status(self): self.con.request('CUSTOM', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) def test_return_explain_error(self): self.con.request('EXPLAINERROR', '/') res = self.con.getresponse() self.assertEqual(res.status, 999) self.assertTrue(int(res.getheader('Content-Length'))) def test_latin1_header(self): self.con.request('LATINONEHEADER', '/', headers={ 'X-Special-Incoming': 'Ärger mit Unicode' }) res = self.con.getresponse() self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind') self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8')) def test_error_content_length(self): # Issue #16088: standard error responses should have a content-length self.con.request('NOTFOUND', '/') res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.NOT_FOUND) data = res.read() self.assertEqual(int(res.getheader('Content-Length')), len(data)) def test_send_error(self): allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT) for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED, HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT, HTTPStatus.SWITCHING_PROTOCOLS): self.con.request('SEND_ERROR', '/{}'.format(code)) res = self.con.getresponse() self.assertEqual(code, res.status) self.assertEqual(None, res.getheader('Content-Length')) self.assertEqual(None, res.getheader('Content-Type')) if code not in allow_transfer_encoding_codes: self.assertEqual(None, res.getheader('Transfer-Encoding')) data = res.read() self.assertEqual(b'', data) def test_head_via_send_error(self): allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT) for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT, HTTPStatus.SWITCHING_PROTOCOLS): self.con.request('HEAD', '/{}'.format(code)) res = self.con.getresponse() self.assertEqual(code, res.status) if code == HTTPStatus.OK: self.assertTrue(int(res.getheader('Content-Length')) > 0) self.assertIn('text/html', res.getheader('Content-Type')) else: self.assertEqual(None, res.getheader('Content-Length')) self.assertEqual(None, res.getheader('Content-Type')) if code not in allow_transfer_encoding_codes: self.assertEqual(None, res.getheader('Transfer-Encoding')) data = res.read() self.assertEqual(b'', data) def certdata_file(*path): return os.path.join(os.path.dirname(__file__), "certdata", *path) @unittest.skipIf(ssl is None, "requires ssl")
BaseHTTPServerTestCase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-analytics-v4-service-account-only/source_google_analytics_v4_service_account_only/source.py
{ "start": 98, "end": 421 }
class ____(source_google_analytics_v4.SourceGoogleAnalyticsV4): """Updating of default source logic This connector shouldn't work with OAuth authentication method. The base logic of this connector is implemented in the "source-source_google_analytics_v4" connector. """
SourceGoogleAnalyticsV4ServiceAccountOnly
python
getsentry__sentry
src/sentry/features/flagpole_context.py
{ "start": 719, "end": 789 }
class ____(Exception): pass @dataclass()
InvalidContextDataException
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 11973, "end": 13148 }
class ____(Widget): """A representation of ``st.checkbox``.""" _value: bool | None proto: CheckboxProto = field(repr=False) label: str help: str form_id: str def __init__(self, proto: CheckboxProto, root: ElementTree) -> None: super().__init__(proto, root) self.type = "checkbox" @property def _widget_state(self) -> WidgetState: ws = WidgetState() ws.id = self.id ws.bool_value = self.value return ws @property def value(self) -> bool: """The value of the widget. (bool)""" # noqa: D400 if self._value is not None: return self._value state = self.root.session_state assert state return cast("bool", state[self.id]) def set_value(self, v: bool) -> Checkbox: """Set the value of the widget.""" self._value = v return self def check(self) -> Checkbox: """Set the value of the widget to True.""" return self.set_value(True) def uncheck(self) -> Checkbox: """Set the value of the widget to False.""" return self.set_value(False) @dataclass(repr=False)
Checkbox
python
python-pillow__Pillow
Tests/test_image_paste.py
{ "start": 131, "end": 11198 }
class ____: size = 128 def assert_9points_image( self, im: Image.Image, expected: list[tuple[int, int, int, int]] ) -> None: px = im.load() assert px is not None actual = [ px[0, 0], px[self.size // 2, 0], px[self.size - 1, 0], px[0, self.size // 2], px[self.size // 2, self.size // 2], px[self.size - 1, self.size // 2], px[0, self.size - 1], px[self.size // 2, self.size - 1], px[self.size - 1, self.size - 1], ] assert actual == [ point[0] if im.mode == "L" else point[: len(im.mode)] for point in expected ] def assert_9points_paste( self, im: Image.Image, im2: Image.Image | str | tuple[int, ...], mask: Image.Image, expected: list[tuple[int, int, int, int]], ) -> None: im3 = im.copy() im3.paste(im2, (0, 0), mask) self.assert_9points_image(im3, expected) # Abbreviated syntax im.paste(im2, mask) self.assert_9points_image(im, expected) @CachedProperty def mask_1(self) -> Image.Image: mask = Image.new("1", (self.size, self.size)) px = mask.load() assert px is not None for y in range(mask.height): for x in range(mask.width): px[y, x] = (x + y) % 2 return mask @CachedProperty def mask_L(self) -> Image.Image: return self.gradient_L.transpose(Image.Transpose.ROTATE_270) @CachedProperty def gradient_L(self) -> Image.Image: gradient = Image.new("L", (self.size, self.size)) px = gradient.load() assert px is not None for y in range(gradient.height): for x in range(gradient.width): px[y, x] = (x + y) % 255 return gradient @CachedProperty def gradient_RGB(self) -> Image.Image: return Image.merge( "RGB", [ self.gradient_L, self.gradient_L.transpose(Image.Transpose.ROTATE_90), self.gradient_L.transpose(Image.Transpose.ROTATE_180), ], ) @CachedProperty def gradient_LA(self) -> Image.Image: return Image.merge( "LA", [ self.gradient_L, self.gradient_L.transpose(Image.Transpose.ROTATE_90), ], ) @CachedProperty def gradient_RGBA(self) -> Image.Image: return Image.merge( "RGBA", [ self.gradient_L, self.gradient_L.transpose(Image.Transpose.ROTATE_90), self.gradient_L.transpose(Image.Transpose.ROTATE_180), self.gradient_L.transpose(Image.Transpose.ROTATE_270), ], ) @CachedProperty def gradient_RGBa(self) -> Image.Image: return Image.merge( "RGBa", [ self.gradient_L, self.gradient_L.transpose(Image.Transpose.ROTATE_90), self.gradient_L.transpose(Image.Transpose.ROTATE_180), self.gradient_L.transpose(Image.Transpose.ROTATE_270), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_solid(self, mode: str) -> None: im = Image.new(mode, (200, 200), "red") im2 = getattr(self, "gradient_" + mode) im.paste(im2, (12, 23)) im = im.crop((12, 23, im2.width + 12, im2.height + 23)) assert_image_equal(im, im2) @pytest.mark.parametrize("y", [10, -10]) @pytest.mark.parametrize("mode", ["L", "RGB"]) @pytest.mark.parametrize("mask_mode", ["", "1", "L", "LA", "RGBa"]) def test_image_self(self, y: int, mode: str, mask_mode: str) -> None: im = getattr(self, "gradient_" + mode) mask = Image.new(mask_mode, im.size, 0xFFFFFFFF) if mask_mode else None im_self = im.copy() im_self.paste(im_self, (0, y), mask) im_copy = im.copy() im_copy.paste(im_copy.copy(), (0, y), mask) assert_image_equal(im_self, im_copy) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_mask_1(self, mode: str) -> None: im = Image.new(mode, (200, 200), "white") im2 = getattr(self, "gradient_" + mode) self.assert_9points_paste( im, im2, self.mask_1, [ (255, 255, 255, 255), (255, 255, 255, 255), (127, 254, 127, 0), (255, 255, 255, 255), (255, 255, 255, 255), (191, 190, 63, 64), (127, 0, 127, 254), (191, 64, 63, 190), (255, 255, 255, 255), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_mask_L(self, mode: str) -> None: im = Image.new(mode, (200, 200), "white") im2 = getattr(self, "gradient_" + mode) self.assert_9points_paste( im, im2, self.mask_L, [ (128, 191, 255, 191), (208, 239, 239, 208), (255, 255, 255, 255), (112, 111, 206, 207), (192, 191, 191, 191), (239, 239, 207, 207), (128, 1, 128, 254), (207, 113, 112, 207), (255, 191, 128, 191), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_mask_LA(self, mode: str) -> None: im = Image.new(mode, (200, 200), "white") im2 = getattr(self, "gradient_" + mode) self.assert_9points_paste( im, im2, self.gradient_LA, [ (128, 191, 255, 191), (112, 207, 206, 111), (128, 254, 128, 1), (208, 208, 239, 239), (192, 191, 191, 191), (207, 207, 112, 113), (255, 255, 255, 255), (239, 207, 207, 239), (255, 191, 128, 191), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_mask_RGBA(self, mode: str) -> None: im = Image.new(mode, (200, 200), "white") im2 = getattr(self, "gradient_" + mode) self.assert_9points_paste( im, im2, self.gradient_RGBA, [ (128, 191, 255, 191), (208, 239, 239, 208), (255, 255, 255, 255), (112, 111, 206, 207), (192, 191, 191, 191), (239, 239, 207, 207), (128, 1, 128, 254), (207, 113, 112, 207), (255, 191, 128, 191), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_image_mask_RGBa(self, mode: str) -> None: im = Image.new(mode, (200, 200), "white") im2 = getattr(self, "gradient_" + mode) self.assert_9points_paste( im, im2, self.gradient_RGBa, [ (128, 255, 126, 255), (0, 127, 126, 255), (126, 253, 126, 255), (128, 127, 254, 255), (0, 255, 254, 255), (126, 125, 254, 255), (128, 1, 128, 255), (0, 129, 128, 255), (126, 255, 128, 255), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_color_solid(self, mode: str) -> None: im = Image.new(mode, (200, 200), "black") rect = (12, 23, 128 + 12, 128 + 23) im.paste("white", rect) hist = im.crop(rect).histogram() while hist: head, hist = hist[:256], hist[256:] assert head[255] == 128 * 128 assert sum(head[:255]) == 0 @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_color_mask_1(self, mode: str) -> None: im = Image.new(mode, (200, 200), (50, 60, 70, 80)[: len(mode)]) color = (10, 20, 30, 40)[: len(mode)] self.assert_9points_paste( im, color, self.mask_1, [ (50, 60, 70, 80), (50, 60, 70, 80), (10, 20, 30, 40), (50, 60, 70, 80), (50, 60, 70, 80), (10, 20, 30, 40), (10, 20, 30, 40), (10, 20, 30, 40), (50, 60, 70, 80), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_color_mask_L(self, mode: str) -> None: im = getattr(self, "gradient_" + mode).copy() color = "white" self.assert_9points_paste( im, color, self.mask_L, [ (127, 191, 254, 191), (111, 207, 206, 110), (127, 254, 127, 0), (207, 207, 239, 239), (191, 191, 190, 191), (207, 206, 111, 112), (254, 254, 254, 255), (239, 206, 206, 238), (254, 191, 127, 191), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_color_mask_RGBA(self, mode: str) -> None: im = getattr(self, "gradient_" + mode).copy() color = "white" self.assert_9points_paste( im, color, self.gradient_RGBA, [ (127, 191, 254, 191), (111, 207, 206, 110), (127, 254, 127, 0), (207, 207, 239, 239), (191, 191, 190, 191), (207, 206, 111, 112), (254, 254, 254, 255), (239, 206, 206, 238), (254, 191, 127, 191), ], ) @pytest.mark.parametrize("mode", ["RGBA", "RGB", "L"]) def test_color_mask_RGBa(self, mode: str) -> None: im = getattr(self, "gradient_" + mode).copy() color = "white" self.assert_9points_paste( im, color, self.gradient_RGBa, [ (255, 63, 126, 63), (47, 143, 142, 46), (126, 253, 126, 255), (15, 15, 47, 47), (63, 63, 62, 63), (142, 141, 46, 47), (255, 255, 255, 0), (48, 15, 15, 47), (126, 63, 255, 63), ], ) def test_different_sizes(self) -> None: im = Image.new("RGB", (100, 100)) im2 = Image.new("RGB", (50, 50)) im.copy().paste(im2) im.copy().paste(im2, (0, 0)) def test_incorrect_abbreviated_form(self) -> None: im = Image.new("L", (1, 1)) with pytest.raises(ValueError): im.paste(im, im, im)
TestImagingPaste
python
google__pytype
pytype/imports/typeshed.py
{ "start": 758, "end": 1719 }
class ____(metaclass=abc.ABCMeta): """Underlying datastore for typeshed.""" @abc.abstractmethod def load_missing(self) -> list[str]: """List of modules that are known to be missing in typeshed.""" raise NotImplementedError() @abc.abstractmethod def load_pytype_blocklist(self) -> list[str]: """List of modules that we maintain our own versions of.""" raise NotImplementedError() @abc.abstractmethod def load_stdlib_versions(self) -> list[str]: raise NotImplementedError() @abc.abstractmethod def filepath(self, relpath) -> str: """Absolute path to a typeshed file.""" raise NotImplementedError() @abc.abstractmethod def file_exists(self, relpath) -> bool: raise NotImplementedError() @abc.abstractmethod def list_files(self, relpath) -> list[str]: raise NotImplementedError() @abc.abstractmethod def load_file(self, relpath) -> tuple[str, str]: raise NotImplementedError()
TypeshedStore