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 | pandas-dev__pandas | pandas/tests/series/methods/test_drop_duplicates.py | {
"start": 2201,
"end": 9468
} | class ____:
@pytest.fixture(
params=["int_", "uint", "float64", "str_", "timedelta64[h]", "datetime64[D]"]
)
def dtype(self, request):
"""
Fixture that provides different data types for testing.
"""
return request.param
@pytest.fixture
def cat_series_unused_category(self, dtype, ordered):
"""
Fixture that creates a Categorical Series with some unused categories.
"""
# Test case 1
cat_array = np.array([1, 2, 3, 4, 5], dtype=np.dtype(dtype))
input1 = np.array([1, 2, 3, 3], dtype=np.dtype(dtype))
cat = Categorical(input1, categories=cat_array, ordered=ordered)
tc1 = Series(cat)
return tc1
def test_drop_duplicates_categorical_non_bool(self, cat_series_unused_category):
tc1 = cat_series_unused_category
expected = Series([False, False, False, True])
result = tc1.duplicated()
tm.assert_series_equal(result, expected)
result = tc1.drop_duplicates()
tm.assert_series_equal(result, tc1[~expected])
sc = tc1.copy()
return_value = sc.drop_duplicates(inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc1[~expected])
def test_drop_duplicates_categorical_non_bool_keeplast(
self, cat_series_unused_category
):
tc1 = cat_series_unused_category
expected = Series([False, False, True, False])
result = tc1.duplicated(keep="last")
tm.assert_series_equal(result, expected)
result = tc1.drop_duplicates(keep="last")
tm.assert_series_equal(result, tc1[~expected])
sc = tc1.copy()
return_value = sc.drop_duplicates(keep="last", inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc1[~expected])
def test_drop_duplicates_categorical_non_bool_keepfalse(
self, cat_series_unused_category
):
tc1 = cat_series_unused_category
expected = Series([False, False, True, True])
result = tc1.duplicated(keep=False)
tm.assert_series_equal(result, expected)
result = tc1.drop_duplicates(keep=False)
tm.assert_series_equal(result, tc1[~expected])
sc = tc1.copy()
return_value = sc.drop_duplicates(keep=False, inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc1[~expected])
@pytest.fixture
def cat_series(self, dtype, ordered):
"""
Fixture that creates a Categorical Series with no unused categories.
"""
cat_array = np.array([1, 2, 3, 4, 5], dtype=np.dtype(dtype))
input2 = np.array([1, 2, 3, 5, 3, 2, 4], dtype=np.dtype(dtype))
cat = Categorical(input2, categories=cat_array, ordered=ordered)
tc2 = Series(cat)
return tc2
def test_drop_duplicates_categorical_non_bool2(self, cat_series):
tc2 = cat_series
expected = Series([False, False, False, False, True, True, False])
result = tc2.duplicated()
tm.assert_series_equal(result, expected)
result = tc2.drop_duplicates()
tm.assert_series_equal(result, tc2[~expected])
sc = tc2.copy()
return_value = sc.drop_duplicates(inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc2[~expected])
def test_drop_duplicates_categorical_non_bool2_keeplast(self, cat_series):
tc2 = cat_series
expected = Series([False, True, True, False, False, False, False])
result = tc2.duplicated(keep="last")
tm.assert_series_equal(result, expected)
result = tc2.drop_duplicates(keep="last")
tm.assert_series_equal(result, tc2[~expected])
sc = tc2.copy()
return_value = sc.drop_duplicates(keep="last", inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc2[~expected])
def test_drop_duplicates_categorical_non_bool2_keepfalse(self, cat_series):
tc2 = cat_series
expected = Series([False, True, True, False, True, True, False])
result = tc2.duplicated(keep=False)
tm.assert_series_equal(result, expected)
result = tc2.drop_duplicates(keep=False)
tm.assert_series_equal(result, tc2[~expected])
sc = tc2.copy()
return_value = sc.drop_duplicates(keep=False, inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc2[~expected])
def test_drop_duplicates_categorical_bool(self, ordered):
tc = Series(
Categorical(
[True, False, True, False], categories=[True, False], ordered=ordered
)
)
expected = Series([False, False, True, True])
tm.assert_series_equal(tc.duplicated(), expected)
tm.assert_series_equal(tc.drop_duplicates(), tc[~expected])
sc = tc.copy()
return_value = sc.drop_duplicates(inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc[~expected])
expected = Series([True, True, False, False])
tm.assert_series_equal(tc.duplicated(keep="last"), expected)
tm.assert_series_equal(tc.drop_duplicates(keep="last"), tc[~expected])
sc = tc.copy()
return_value = sc.drop_duplicates(keep="last", inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc[~expected])
expected = Series([True, True, True, True])
tm.assert_series_equal(tc.duplicated(keep=False), expected)
tm.assert_series_equal(tc.drop_duplicates(keep=False), tc[~expected])
sc = tc.copy()
return_value = sc.drop_duplicates(keep=False, inplace=True)
assert return_value is None
tm.assert_series_equal(sc, tc[~expected])
def test_drop_duplicates_categorical_bool_na(self, nulls_fixture):
# GH#44351
ser = Series(
Categorical(
[True, False, True, False, nulls_fixture],
categories=[True, False],
ordered=True,
)
)
result = ser.drop_duplicates()
expected = Series(
Categorical([True, False, np.nan], categories=[True, False], ordered=True),
index=[0, 1, 4],
)
tm.assert_series_equal(result, expected)
def test_drop_duplicates_ignore_index(self):
# GH#48304
ser = Series([1, 2, 2, 3])
result = ser.drop_duplicates(ignore_index=True)
expected = Series([1, 2, 3])
tm.assert_series_equal(result, expected)
def test_duplicated_arrow_dtype(self):
pytest.importorskip("pyarrow")
ser = Series([True, False, None, False], dtype="bool[pyarrow]")
result = ser.drop_duplicates()
expected = Series([True, False, None], dtype="bool[pyarrow]")
tm.assert_series_equal(result, expected)
def test_drop_duplicates_arrow_strings(self):
# GH#54904
pa = pytest.importorskip("pyarrow")
ser = Series(["a", "a"], dtype=pd.ArrowDtype(pa.string()))
result = ser.drop_duplicates()
expecetd = Series(["a"], dtype=pd.ArrowDtype(pa.string()))
tm.assert_series_equal(result, expecetd)
| TestSeriesDropDuplicates |
python | getsentry__sentry | tests/sentry/api/endpoints/test_api_application_details.py | {
"start": 1352,
"end": 1971
} | class ____(APITestCase):
def test_simple(self) -> None:
app = ApiApplication.objects.create(owner=self.user, name="a")
self.login_as(self.user)
url = reverse("sentry-api-0-api-application-details", args=[app.client_id])
response = self.client.delete(url)
assert response.status_code == 204, response.content
app = ApiApplication.objects.get(id=app.id)
assert app.status == ApiApplicationStatus.pending_deletion
assert ScheduledDeletion.objects.filter(
object_id=app.id, model_name="ApiApplication"
).exists()
| ApiApplicationDeleteTest |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 31405,
"end": 35746
} | class ____(httpx.Client):
@lru_cache()
@staticmethod
def _get_ssl_context_cached(ca_file: str, ca_path: str | None = None) -> ssl.SSLContext:
"""Cache SSL context to prevent memory growth from repeated context creation."""
ctx = ssl.create_default_context(cafile=ca_file)
if ca_path:
ctx.load_verify_locations(ca_path)
return ctx
def __init__(self, *, base_url: str | None, dry_run: bool = False, token: str, **kwargs: Any):
if (not base_url) ^ dry_run:
raise ValueError(f"Can only specify one of {base_url=} or {dry_run=}")
auth = BearerAuth(token)
if dry_run:
# If dry run is requested, install a no op handler so that simple tasks can "heartbeat" using a
# real client, but just don't make any HTTP requests
kwargs.setdefault("transport", httpx.MockTransport(noop_handler))
kwargs.setdefault("base_url", "dry-run://server")
else:
kwargs["base_url"] = base_url
kwargs["verify"] = self._get_ssl_context_cached(certifi.where(), API_SSL_CERT_PATH)
# Set timeout if not explicitly provided
kwargs.setdefault("timeout", API_TIMEOUT)
pyver = f"{'.'.join(map(str, sys.version_info[:3]))}"
super().__init__(
auth=auth,
headers={
"user-agent": f"apache-airflow-task-sdk/{__version__} (Python/{pyver})",
"airflow-api-version": API_VERSION,
},
event_hooks={"response": [self._update_auth, raise_on_4xx_5xx], "request": [add_correlation_id]},
**kwargs,
)
def _update_auth(self, response: httpx.Response):
if new_token := response.headers.get("Refreshed-API-Token"):
log.debug("Execution API issued us a refreshed Task token")
self.auth = BearerAuth(new_token)
@retry(
retry=retry_if_exception(_should_retry_api_request),
stop=stop_after_attempt(API_RETRIES),
wait=wait_random_exponential(min=API_RETRY_WAIT_MIN, max=API_RETRY_WAIT_MAX),
before_sleep=before_log(log, logging.WARNING),
reraise=True,
)
def request(self, *args, **kwargs):
"""Implement a convenience for httpx.Client.request with a retry layer."""
# Set content type as convenience if not already set
if "content" in kwargs and "headers" not in kwargs:
kwargs["headers"] = {"content-type": "application/json"}
return super().request(*args, **kwargs)
# We "group" or "namespace" operations by what they operate on, rather than a flat namespace with all
# methods on one object prefixed with the object type (`.task_instances.update` rather than
# `task_instance_update` etc.)
@lru_cache() # type: ignore[misc]
@property
def task_instances(self) -> TaskInstanceOperations:
"""Operations related to TaskInstances."""
return TaskInstanceOperations(self)
@lru_cache() # type: ignore[misc]
@property
def dag_runs(self) -> DagRunOperations:
"""Operations related to DagRuns."""
return DagRunOperations(self)
@lru_cache() # type: ignore[misc]
@property
def connections(self) -> ConnectionOperations:
"""Operations related to Connections."""
return ConnectionOperations(self)
@lru_cache() # type: ignore[misc]
@property
def variables(self) -> VariableOperations:
"""Operations related to Variables."""
return VariableOperations(self)
@lru_cache() # type: ignore[misc]
@property
def xcoms(self) -> XComOperations:
"""Operations related to XComs."""
return XComOperations(self)
@lru_cache() # type: ignore[misc]
@property
def assets(self) -> AssetOperations:
"""Operations related to Assets."""
return AssetOperations(self)
@lru_cache() # type: ignore[misc]
@property
def asset_events(self) -> AssetEventOperations:
"""Operations related to Asset Events."""
return AssetEventOperations(self)
@lru_cache() # type: ignore[misc]
@property
def hitl(self):
"""Operations related to HITL Responses."""
return HITLOperations(self)
# This is only used for parsing. ServerResponseError is raised instead
| Client |
python | pypa__setuptools | setuptools/tests/test_sdist.py | {
"start": 28720,
"end": 32870
} | class ____:
"""
Can be removed/changed if the project decides to change how it handles symlinks
or external files.
"""
@staticmethod
def files_for_symlink_in_extension_depends(tmp_path, dep_path):
return {
"external": {
"dir": {"file.h": ""},
},
"project": {
"setup.py": cleandoc(
f"""
from setuptools import Extension, setup
setup(
name="myproj",
version="42",
ext_modules=[
Extension(
"hello", sources=["hello.pyx"],
depends=[{dep_path!r}]
)
],
)
"""
),
"hello.pyx": "",
"MANIFEST.in": "global-include *.h",
},
}
@pytest.mark.parametrize(
"dep_path", ("myheaders/dir/file.h", "myheaders/dir/../dir/file.h")
)
def test_symlink_in_extension_depends(self, monkeypatch, tmp_path, dep_path):
# Given a project with a symlinked dir and a "depends" targeting that dir
files = self.files_for_symlink_in_extension_depends(tmp_path, dep_path)
jaraco.path.build(files, prefix=str(tmp_path))
symlink_or_skip_test(tmp_path / "external", tmp_path / "project/myheaders")
# When `sdist` runs, there should be no error
members = run_sdist(monkeypatch, tmp_path / "project")
# and the sdist should contain the symlinked files
for expected in (
"myproj-42/hello.pyx",
"myproj-42/myheaders/dir/file.h",
):
assert expected in members
@staticmethod
def files_for_external_path_in_extension_depends(tmp_path, dep_path):
head, _, tail = dep_path.partition("$tmp_path$/")
dep_path = tmp_path / tail if tail else head
return {
"external": {
"dir": {"file.h": ""},
},
"project": {
"setup.py": cleandoc(
f"""
from setuptools import Extension, setup
setup(
name="myproj",
version="42",
ext_modules=[
Extension(
"hello", sources=["hello.pyx"],
depends=[{str(dep_path)!r}]
)
],
)
"""
),
"hello.pyx": "",
"MANIFEST.in": "global-include *.h",
},
}
@pytest.mark.parametrize(
"dep_path", ("$tmp_path$/external/dir/file.h", "../external/dir/file.h")
)
def test_external_path_in_extension_depends(self, monkeypatch, tmp_path, dep_path):
# Given a project with a "depends" targeting an external dir
files = self.files_for_external_path_in_extension_depends(tmp_path, dep_path)
jaraco.path.build(files, prefix=str(tmp_path))
# When `sdist` runs, there should be no error
members = run_sdist(monkeypatch, tmp_path / "project")
# and the sdist should not contain the external file
for name in members:
assert "file.h" not in name
def run_sdist(monkeypatch, project):
"""Given a project directory, run the sdist and return its contents"""
monkeypatch.chdir(project)
with quiet():
run_setup("setup.py", ["sdist"])
archive = next((project / "dist").glob("*.tar.gz"))
with tarfile.open(str(archive)) as tar:
return set(tar.getnames())
def test_sanity_check_setuptools_own_sdist(setuptools_sdist):
with tarfile.open(setuptools_sdist) as tar:
files = tar.getnames()
# setuptools sdist should not include the .tox folder
tox_files = [name for name in files if ".tox" in name]
assert len(tox_files) == 0, f"not empty {tox_files}"
| TestRegressions |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 34248,
"end": 34456
} | class ____(BoringModel):
def validation_step(self, batch, batch_idx):
if not self.trainer.sanity_checking and batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledModelInValidationStep |
python | ray-project__ray | python/ray/llm/_internal/serve/config_generator/inputs.py | {
"start": 1430,
"end": 7190
} | class ____(BaseModel):
id: str
hf_token: Optional[str] = None
type: ModelType
import_model_storage_uri: Optional[str] = None
reference_model_id: Optional[str] = None
def _get_user_input_from_lists(
prompt: str, options: List[str], allow_any_user_input: bool
):
while True:
res = Prompt.ask(prompt)
if allow_any_user_input or res in options:
return res
else:
print("Please enter a valid option.")
def _get_model_id():
model_list = list(DEFAULT_MODEL_ID_TO_GPU.keys())
model_ids = "\n".join(model_list)
prompt_message = f"""[bold]We have provided the defaults for the following models[not bold]:
{model_ids}
[bold]Please enter the model ID you would like to serve, or enter your own custom model ID. For multi-lora serving, enter only the base model ID"""
model_id = _get_user_input_from_lists(
prompt_message, model_list, allow_any_user_input=True
)
return model_id
def _get_validated_model_info():
"""
If the model is supposed to be loaded from huggingface, we make an API call to confirm that
user's credentials work.
"""
while True:
ref_model_id = None
model_id = _get_model_id()
model_type = TEXT_COMPLETION_MODEL_TYPE
if model_id not in DEFAULT_MODEL_ID_TO_GPU:
ref_model_id = "other"
import_model = Confirm.ask(
"Do you have the model weights stored in your cloud buckets? "
"If not, model weights will be downloaded from HuggingFace.",
default=False,
)
if import_model:
# No need to validate since the model is loaded from remote uri
remote_storage_uri = BoldPrompt.ask("Storage uri of your model: ")
return BaseModelInfo(
id=model_id,
hf_token=None,
type=model_type,
import_model_storage_uri=remote_storage_uri,
reference_model_id=ref_model_id,
)
hf_token = get_hf_token()
# Need to validate
try:
repo_info(model_id, token=hf_token)
print(
f"Verified that you can access {model_id} with your HuggingFace token."
)
return BaseModelInfo(
id=model_id,
hf_token=hf_token,
type=model_type,
reference_model_id=ref_model_id,
)
except Exception as e:
print(f"An error occurred: {e}")
# Clear cached tf token in case it was incorrectly entered
clear_hf_token()
print(
"\nUnable to access the HuggingFace repo based on the "
"provided information. Please confirm that you have access "
"to the model and try again."
)
def _get_default_tensor_parallelism(model_id: str, gpu_type: GPUType) -> int:
if model_id in DEFAULT_MODEL_ID_TO_GPU:
llm_config = get_default_llm_config(model_id=model_id, gpu_type=gpu_type)
return llm_config.engine_kwargs.setdefault("tensor_parallel_size", 1)
return 1
_DEFAULT_NUM_LORA_PER_REPLICA = 16
def get_input_model_via_args(
model_id: str,
hf_token: Optional[str],
gpu_type: GPUType,
tensor_parallelism: int,
enable_lora: Optional[bool],
num_loras_per_replica: Optional[int],
) -> TextCompletionModelConfig:
if enable_lora:
max_num_lora_per_replica = (
num_loras_per_replica or _DEFAULT_NUM_LORA_PER_REPLICA
)
default_lora_uri = get_lora_storage_uri()
lora_config = TextCompletionLoraModelConfig(
max_num_lora_per_replica=max_num_lora_per_replica,
uri=default_lora_uri,
)
else:
lora_config = None
return convert_inputs_to_text_completion_model(
model_id=model_id,
hf_token=hf_token,
gpu_type=gpu_type,
tensor_parallelism=tensor_parallelism,
lora_config=lora_config,
)
def get_input_model_via_interactive_inputs() -> TextCompletionModelConfig:
"""
This method constructs a corresponding model object based on user inputs.
This model object should be used to construct the final serve config.
"""
base_model_info = _get_validated_model_info()
available_gpu_types = get_available_gpu_types(base_model_info.id)
gpu_type = _get_user_input_from_list("GPU type", available_gpu_types)
default_tensor_parallelism = _get_default_tensor_parallelism(
base_model_info.id, gpu_type=gpu_type
)
tensor_parallelism = BoldIntPrompt.ask(
"Tensor parallelism", default=default_tensor_parallelism
)
is_lora_enabled = Confirm.ask("[bold]Enable LoRA serving", default=False)
if is_lora_enabled:
default_lora_uri = get_lora_storage_uri()
max_num_lora_per_replica = BoldIntPrompt.ask(
"Maximum number of LoRA models per replica",
default=_DEFAULT_NUM_LORA_PER_REPLICA,
)
lora_uri = BoldPrompt.ask("LoRA storage uri", default=default_lora_uri)
lora_config = TextCompletionLoraModelConfig(
max_num_lora_per_replica=max_num_lora_per_replica,
uri=lora_uri,
)
else:
lora_config = None
return convert_inputs_to_text_completion_model(
model_id=base_model_info.id,
hf_token=base_model_info.hf_token,
remote_storage_uri=base_model_info.import_model_storage_uri,
gpu_type=gpu_type,
tensor_parallelism=tensor_parallelism,
lora_config=lora_config,
reference_model_id=base_model_info.reference_model_id,
)
| BaseModelInfo |
python | sphinx-doc__sphinx | tests/roots/test-api-set-translator/conf.py | {
"start": 1002,
"end": 1679
} | class ____(XMLTranslator):
pass
def setup(app):
app.set_translator('html', ConfHTMLTranslator)
app.set_translator('dirhtml', ConfDirHTMLTranslator)
app.set_translator('singlehtml', ConfSingleHTMLTranslator)
app.set_translator('pickle', ConfPickleTranslator)
app.set_translator('json', ConfJsonTranslator)
app.set_translator('latex', ConfLaTeXTranslator)
app.set_translator('man', ConfManualPageTranslator)
app.set_translator('texinfo', ConfTexinfoTranslator)
app.set_translator('text', ConfTextTranslator)
app.set_translator('xml', ConfXMLTranslator)
app.set_translator('pseudoxml', ConfPseudoXMLTranslator)
| ConfPseudoXMLTranslator |
python | psf__requests | src/requests/models.py | {
"start": 2127,
"end": 6052
} | class ____:
@property
def path_url(self):
"""Build the path URL to use."""
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = "/"
url.append(path)
query = p.query
if query:
url.append("?")
url.append(query)
return "".join(url)
@staticmethod
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, "read"):
return data
elif hasattr(data, "__iter__"):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(
k.encode("utf-8") if isinstance(k, str) else k,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
return urlencode(result, doseq=True)
else:
return data
@staticmethod
def _encode_files(files, data):
"""Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
"""
if not files:
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, "__iter__"):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(
field.decode("utf-8")
if isinstance(field, bytes)
else field,
v.encode("utf-8") if isinstance(v, str) else v,
)
)
for k, v in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
elif hasattr(fp, "read"):
fdata = fp.read()
elif fp is None:
continue
else:
fdata = fp
rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
| RequestEncodingMixin |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 214523,
"end": 215524
} | class ____(TestCase):
def test_basic(self):
for i, iterable, expected_min, expected_max in (
(1, [10, 2, 20, 5, 17, 4], 1, 2),
(2, [10, -2, -20, 5, 17, 4], 2, 4),
(3, [10, 10, 20, 10], 0, 2),
(4, [30, 30, 20, 30], 2, 0),
):
with self.subTest(i=i):
self.assertEqual(mi.argmin(iterable), expected_min)
self.assertEqual(mi.argmax(iterable), expected_max)
def test_key(self):
for i, iterable, key, expected_min, expected_max in (
(1, [10, -2, -20, 5, 17, 4], abs, 1, 2),
(
2,
[[0] * 10, [0] * 5, [0] * 3, [0] * 12, [0] * 2, [0] * 3],
len,
4,
3,
),
):
with self.subTest(i=i):
self.assertEqual(mi.argmin(iterable, key=key), expected_min)
self.assertEqual(mi.argmax(iterable, key=key), expected_max)
| ArgMinArgMaxTests |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-raptor/llama_index/packs/raptor/base.py | {
"start": 3134,
"end": 12243
} | class ____(BaseRetriever):
"""Raptor indexing retriever."""
def __init__(
self,
documents: List[BaseNode],
tree_depth: int = 3,
similarity_top_k: int = 2,
llm: Optional[LLM] = None,
embed_model: Optional[BaseEmbedding] = None,
vector_store: Optional[BasePydanticVectorStore] = None,
transformations: Optional[List[TransformComponent]] = None,
summary_module: Optional[SummaryModule] = None,
existing_index: Optional[VectorStoreIndex] = None,
mode: QueryModes = "collapsed",
**kwargs: Any,
) -> None:
"""Init params."""
super().__init__(
**kwargs,
)
self.mode = mode
self.summary_module = summary_module or SummaryModule(llm=llm)
self.index = existing_index or VectorStoreIndex(
nodes=[],
storage_context=StorageContext.from_defaults(vector_store=vector_store),
embed_model=embed_model,
transformations=transformations,
)
self.tree_depth = tree_depth
self.similarity_top_k = similarity_top_k
if len(documents) > 0:
asyncio.run(self.insert(documents))
def _get_embeddings_per_level(self, level: int = 0) -> List[float]:
"""
Retrieve embeddings per level in the abstraction tree.
Args:
level (int, optional): Target level. Defaults to 0 which stands for leaf nodes.
Returns:
List[float]: List of embeddings
"""
filters = MetadataFilters(filters=[MetadataFilter("level", level)])
# kind of janky, but should work with any vector index
source_nodes = self.index.as_retriever(
similarity_top_k=10000, filters=filters
).retrieve("retrieve")
return [x.node for x in source_nodes]
async def insert(self, documents: List[BaseNode]) -> None:
"""
Given a set of documents, this function inserts higher level of abstractions within the index.
For later retrieval
Args:
documents (List[BaseNode]): List of Documents
"""
embed_model = self.index._embed_model
transformations = self.index._transformations
cur_nodes = run_transformations(documents, transformations, in_place=False)
for level in range(self.tree_depth):
# get the embeddings for the current documents
if self._verbose:
print(f"Generating embeddings for level {level}.")
embeddings = await embed_model.aget_text_embedding_batch(
[node.get_content(metadata_mode="embed") for node in cur_nodes]
)
assert len(embeddings) == len(cur_nodes)
id_to_embedding = {
node.id_: embedding for node, embedding in zip(cur_nodes, embeddings)
}
if self._verbose:
print(f"Performing clustering for level {level}.")
# cluster the documents
nodes_per_cluster = get_clusters(cur_nodes, id_to_embedding)
if self._verbose:
print(
f"Generating summaries for level {level} with {len(nodes_per_cluster)} clusters."
)
summaries_per_cluster = await self.summary_module.generate_summaries(
nodes_per_cluster
)
if self._verbose:
print(
f"Level {level} created summaries/clusters: {len(nodes_per_cluster)}"
)
# replace the current nodes with their summaries
new_nodes = [
TextNode(
text=summary,
metadata={"level": level},
excluded_embed_metadata_keys=["level"],
excluded_llm_metadata_keys=["level"],
)
for summary in summaries_per_cluster
]
# insert the nodes with their embeddings and parent_id
nodes_with_embeddings = []
for cluster, summary_doc in zip(nodes_per_cluster, new_nodes):
for node in cluster:
node.metadata["parent_id"] = summary_doc.id_
node.excluded_embed_metadata_keys.append("parent_id")
node.excluded_llm_metadata_keys.append("parent_id")
node.embedding = id_to_embedding[node.id_]
nodes_with_embeddings.append(node)
self.index.insert_nodes(nodes_with_embeddings)
# set the current nodes to the new nodes
cur_nodes = new_nodes
self.index.insert_nodes(cur_nodes)
async def collapsed_retrieval(self, query_str: str) -> Response:
"""Query the index as a collapsed tree -- i.e. a single pool of nodes."""
return await self.index.as_retriever(
similarity_top_k=self.similarity_top_k
).aretrieve(query_str)
async def tree_traversal_retrieval(self, query_str: str) -> Response:
"""Query the index as a tree, traversing the tree from the top down."""
# get top k nodes for each level, starting with the top
parent_ids = None
selected_node_ids = set()
selected_nodes = []
level = self.tree_depth - 1
while level >= 0:
# retrieve nodes at the current level
if parent_ids is None:
nodes = await self.index.as_retriever(
similarity_top_k=self.similarity_top_k,
filters=MetadataFilters(
filters=[MetadataFilter(key="level", value=level)]
),
).aretrieve(query_str)
for node in nodes:
if node.id_ not in selected_node_ids:
selected_nodes.append(node)
selected_node_ids.add(node.id_)
parent_ids = [node.id_ for node in nodes]
if self._verbose:
print(f"Retrieved parent IDs from level {level}: {parent_ids!s}")
# retrieve nodes that are children of the nodes at the previous level
elif parent_ids is not None and len(parent_ids) > 0:
nested_nodes = await asyncio.gather(
*[
self.index.as_retriever(
similarity_top_k=self.similarity_top_k,
filters=MetadataFilters(
filters=[MetadataFilter(key="parent_id", value=id_)]
),
).aretrieve(query_str)
for id_ in parent_ids
]
)
nodes = [node for nested in nested_nodes for node in nested]
for node in nodes:
if node.id_ not in selected_node_ids:
selected_nodes.append(node)
selected_node_ids.add(node.id_)
if self._verbose:
print(f"Retrieved {len(nodes)} from parents at level {level}.")
level -= 1
parent_ids = None
return selected_nodes
def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]:
"""Retrieve nodes given query and mode."""
# not used, needed for type checking
def retrieve(
self, query_str_or_bundle: QueryType, mode: Optional[QueryModes] = None
) -> List[NodeWithScore]:
"""Retrieve nodes given query and mode."""
if isinstance(query_str_or_bundle, QueryBundle):
query_str = query_str_or_bundle.query_str
else:
query_str = query_str_or_bundle
return asyncio.run(self.aretrieve(query_str, mode or self.mode))
async def aretrieve(
self, query_str_or_bundle: QueryType, mode: Optional[QueryModes] = None
) -> List[NodeWithScore]:
"""Retrieve nodes given query and mode."""
if isinstance(query_str_or_bundle, QueryBundle):
query_str = query_str_or_bundle.query_str
else:
query_str = query_str_or_bundle
mode = mode or self.mode
if mode == "tree_traversal":
return await self.tree_traversal_retrieval(query_str)
elif mode == "collapsed":
return await self.collapsed_retrieval(query_str)
else:
raise ValueError(f"Invalid mode: {mode}")
def persist(self, persist_dir: str) -> None:
self.index.storage_context.persist(persist_dir=persist_dir)
@classmethod
def from_persist_dir(
cls: "RaptorRetriever",
persist_dir: str,
embed_model: Optional[BaseEmbedding] = None,
**kwargs: Any,
) -> "RaptorRetriever":
storage_context = StorageContext.from_defaults(persist_dir=persist_dir)
return cls(
[],
existing_index=load_index_from_storage(
storage_context, embed_model=embed_model
),
**kwargs,
)
| RaptorRetriever |
python | django__django | django/db/utils.py | {
"start": 619,
"end": 662
} | class ____(DatabaseError):
pass
| DataError |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_error_z.py | {
"start": 233,
"end": 14397
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.error_z"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"symmetric",
"thickness",
"traceref",
"tracerefminus",
"type",
"value",
"valueminus",
"visible",
"width",
}
@property
def array(self):
"""
Sets the data corresponding the length of each error bar.
Values are plotted relative to the underlying data.
The 'array' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["array"]
@array.setter
def array(self, val):
self["array"] = val
@property
def arrayminus(self):
"""
Sets the data corresponding the length of each error bar in the
bottom (left) direction for vertical (horizontal) bars Values
are plotted relative to the underlying data.
The 'arrayminus' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["arrayminus"]
@arrayminus.setter
def arrayminus(self, val):
self["arrayminus"] = val
@property
def arrayminussrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
The 'arrayminussrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["arrayminussrc"]
@arrayminussrc.setter
def arrayminussrc(self, val):
self["arrayminussrc"] = val
@property
def arraysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `array`.
The 'arraysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["arraysrc"]
@arraysrc.setter
def arraysrc(self, val):
self["arraysrc"] = val
@property
def color(self):
"""
Sets the stroke color of the error bars.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def symmetric(self):
"""
Determines whether or not the error bars have the same length
in both direction (top/bottom for vertical bars, left/right for
horizontal bars.
The 'symmetric' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["symmetric"]
@symmetric.setter
def symmetric(self, val):
self["symmetric"] = val
@property
def thickness(self):
"""
Sets the thickness (in px) of the error bars.
The 'thickness' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["thickness"]
@thickness.setter
def thickness(self, val):
self["thickness"] = val
@property
def traceref(self):
"""
The 'traceref' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["traceref"]
@traceref.setter
def traceref(self, val):
self["traceref"] = val
@property
def tracerefminus(self):
"""
The 'tracerefminus' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["tracerefminus"]
@tracerefminus.setter
def tracerefminus(self, val):
self["tracerefminus"] = val
@property
def type(self):
"""
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value. Set this
constant in `value`. If "percent", the bar lengths correspond
to a percentage of underlying data. Set this percentage in
`value`. If "sqrt", the bar lengths correspond to the square of
the underlying data. If "data", the bar lengths are set with
data set `array`.
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['percent', 'constant', 'sqrt', 'data']
Returns
-------
Any
"""
return self["type"]
@type.setter
def type(self, val):
self["type"] = val
@property
def value(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars.
The 'value' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
@property
def valueminus(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
The 'valueminus' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["valueminus"]
@valueminus.setter
def valueminus(self, val):
self["valueminus"] = val
@property
def visible(self):
"""
Determines whether or not this set of error bars is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["visible"]
@visible.setter
def visible(self, val):
self["visible"] = val
@property
def width(self):
"""
Sets the width (in px) of the cross-bar at both ends of the
error bars.
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud for
`array`.
color
Sets the stroke color of the error bars.
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
"""
def __init__(
self,
arg=None,
array=None,
arrayminus=None,
arrayminussrc=None,
arraysrc=None,
color=None,
symmetric=None,
thickness=None,
traceref=None,
tracerefminus=None,
type=None,
value=None,
valueminus=None,
visible=None,
width=None,
**kwargs,
):
"""
Construct a new ErrorZ object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.ErrorZ`
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
`arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud for
`array`.
color
Sets the stroke color of the error bars.
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
"constant", the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
Returns
-------
ErrorZ
"""
super().__init__("error_z")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatter3d.ErrorZ
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter3d.ErrorZ`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("array", arg, array)
self._set_property("arrayminus", arg, arrayminus)
self._set_property("arrayminussrc", arg, arrayminussrc)
self._set_property("arraysrc", arg, arraysrc)
self._set_property("color", arg, color)
self._set_property("symmetric", arg, symmetric)
self._set_property("thickness", arg, thickness)
self._set_property("traceref", arg, traceref)
self._set_property("tracerefminus", arg, tracerefminus)
self._set_property("type", arg, type)
self._set_property("value", arg, value)
self._set_property("valueminus", arg, valueminus)
self._set_property("visible", arg, visible)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| ErrorZ |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_fmin.py | {
"start": 3671,
"end": 5816
} | class ____(unittest.TestCase):
class SomeError(Exception):
# XXX also test domain.exceptions mechanism that actually catches this
pass
def eval_fn(self, space):
raise TestFmin.SomeError()
def setUp(self):
self.trials = Trials()
def test_catch_eval_exceptions_True(self):
# -- should go to max_evals, catching all exceptions, so all jobs
# should have JOB_STATE_ERROR
fmin(
self.eval_fn,
space=hp.uniform("x", 0, 1),
algo=rand.suggest,
trials=self.trials,
max_evals=2,
catch_eval_exceptions=True,
return_argmin=False,
)
trials = self.trials
assert len(trials) == 0
assert len(trials._dynamic_trials) == 2
assert trials._dynamic_trials[0]["state"] == JOB_STATE_ERROR
assert trials._dynamic_trials[0]["misc"]["error"] != None
assert trials._dynamic_trials[1]["state"] == JOB_STATE_ERROR
assert trials._dynamic_trials[1]["misc"]["error"] != None
def test_catch_eval_exceptions_False(self):
with self.assertRaises(TestFmin.SomeError):
fmin(
self.eval_fn,
space=hp.uniform("x", 0, 1),
algo=rand.suggest,
trials=self.trials,
max_evals=2,
catch_eval_exceptions=False,
)
print(len(self.trials))
assert len(self.trials) == 0
assert len(self.trials._dynamic_trials) == 1
def test_status_fail_tpe():
trials = Trials()
argmin = fmin(
fn=lambda x: (
{"loss": (x - 3) ** 2, "status": STATUS_OK}
if (x < 0)
else {"status": STATUS_FAIL}
),
space=hp.uniform("x", -5, 5),
algo=tpe.suggest,
max_evals=50,
trials=trials,
)
assert len(trials) == 50, len(trials)
assert argmin["x"] < 0, argmin
assert "loss" in trials.best_trial["result"], "loss" in trials.best_trial["result"]
assert trials.best_trial["result"]["loss"] >= 9, trials.best_trial["result"]["loss"]
| TestFmin |
python | readthedocs__readthedocs.org | readthedocs/core/middleware.py | {
"start": 1676,
"end": 3180
} | class ____:
"""
Middleware to update the CSP headers for specific views given its URL name.
This is useful for views that we don't have much control over,
like views from third-party packages. For views that we have control over,
we should update the CSP headers directly in the view.
Use the `RTD_CSP_UPDATE_HEADERS` setting to define the views that need to
update the CSP headers. The setting should be a dictionary where the key is
the URL name of the view and the value is a dictionary with the CSP headers,
for example:
.. code-block:: python
RTD_CSP_UPDATE_HEADERS = {
"login": {"form-action": ["https:"]},
}
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# Views that raised an exception don't have a resolver_match object.
resolver_match = request.resolver_match
if not resolver_match:
return response
url_name = resolver_match.url_name
update_csp_headers = settings.RTD_CSP_UPDATE_HEADERS
if url_name in update_csp_headers:
if hasattr(response, "_csp_update"):
raise ValueError(
"Can't update CSP headers at the view and middleware at the same time, use one or the other."
)
response._csp_update = update_csp_headers[url_name]
return response
| UpdateCSPMiddleware |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/databricks.py | {
"start": 837,
"end": 1649
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "databricks"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.databricks
@override
def create_batch_setup(
self,
request: pytest.FixtureRequest,
data: pd.DataFrame,
extra_data: Mapping[str, pd.DataFrame],
context: AbstractDataContext,
engine_manager: Optional[SessionSQLEngineManager] = None,
) -> BatchTestSetup:
return DatabricksBatchTestSetup(
data=data,
config=self,
extra_data=extra_data,
table_name=self.table_name,
context=context,
engine_manager=engine_manager,
)
| DatabricksDatasourceTestConfig |
python | joke2k__faker | faker/providers/bank/de_CH/__init__.py | {
"start": 42,
"end": 191
} | class ____(BankProvider):
"""Implement bank provider for ``de_CH`` locale."""
bban_format = "#################"
country_code = "CH"
| Provider |
python | Netflix__metaflow | metaflow/plugins/env_escape/override_decorators.py | {
"start": 2992,
"end": 3605
} | class ____(object):
def __init__(self, class_path, serializer):
self._class_path = class_path
self._serializer = serializer
@property
def class_path(self):
return self._class_path
@property
def serializer(self):
return self._serializer
def local_exception_deserialize(class_path):
def _wrapped(func):
return LocalExceptionDeserializer(class_path, func)
return _wrapped
def remote_exception_serialize(class_path):
def _wrapped(func):
return RemoteExceptionSerializer(class_path, func)
return _wrapped
| RemoteExceptionSerializer |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 49361,
"end": 51030
} | class ____(Request):
"""
Delete metadata from model
:param model: ID of the model
:type model: str
:param keys: The list of metadata keys to delete
:type keys: Sequence[str]
"""
_service = "models"
_action = "delete_metadata"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"keys": {
"description": "The list of metadata keys to delete",
"items": {"type": "string"},
"type": "array",
},
"model": {"description": "ID of the model", "type": "string"},
},
"required": ["model", "keys"],
"type": "object",
}
def __init__(self, model: str, keys: List[str], **kwargs: Any) -> None:
super(DeleteMetadataRequest, self).__init__(**kwargs)
self.model = model
self.keys = keys
@schema_property("model")
def model(self) -> str:
return self._property_model
@model.setter
def model(self, value: str) -> None:
if value is None:
self._property_model = None
return
self.assert_isinstance(value, "model", six.string_types)
self._property_model = value
@schema_property("keys")
def keys(self) -> List[str]:
return self._property_keys
@keys.setter
def keys(self, value: List[str]) -> None:
if value is None:
self._property_keys = None
return
self.assert_isinstance(value, "keys", (list, tuple))
self.assert_isinstance(value, "keys", six.string_types, is_array=True)
self._property_keys = value
| DeleteMetadataRequest |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py | {
"start": 4634,
"end": 25595
} | class ____(object): # pylint: disable=missing-docstring
def setUp(self, num_workers, num_ps, use_cs=False):
super(BaseFaultToleranceTest, self).setUp()
self._cluster = multi_worker_test_base.create_multi_process_cluster(
num_workers=num_workers,
num_ps=num_ps,
rpc_layer="grpc",
stream_output=True,
)
self._cluster_def = self._cluster.cluster_resolver.cluster_spec().as_dict()
self._cluster_def["chief"] = [
"localhost:%d" % multi_worker_test_base.pick_unused_port()
]
cluster_resolver = SimpleClusterResolver(
server_lib.ClusterSpec(self._cluster_def), rpc_layer="grpc"
)
if use_cs:
os.environ["TF_PSS_ENABLE_COORDINATION_SERVICE"] = "1"
# The strategy's constructor would connect to the cluster.
self.strategy = parameter_server_strategy_v2.ParameterServerStrategyV2(
cluster_resolver
)
self.cluster_coord = cluster_coordinator.ClusterCoordinator(self.strategy)
self.thread_coord = thread_coordinator.Coordinator(
clean_stop_exception_types=[]
)
self.num_workers = num_workers
self.num_ps = num_ps
def tearDown(self):
super(BaseFaultToleranceTest, self).tearDown()
self._cluster.stop()
self._cluster = None
def _restart(self, downtime_secs, job):
"""Kills `job` (index: 0) and restarts it after `downtime_secs`.
Args:
downtime_secs: secs before restarting the job.
job: a string specifying the job to restart.
"""
self._cluster.kill_task(job, 0)
time.sleep(downtime_secs)
self.assertFalse(context.check_alive("/job:%s/replica:0/task:0" % job))
self._cluster.start_task(job, 0)
while not context.check_alive("/job:%s/replica:0/task:0" % job):
time.sleep(1)
def _restart_in_thread(self, downtime_secs, restart_job):
def _restart_fn():
with self.thread_coord.stop_on_exception():
self._restart(downtime_secs, restart_job)
restart_thread = threading.Thread(target=_restart_fn)
restart_thread.start()
return restart_thread
def _ensure_threads_closed(self):
"""Ensures worker and preemption threads are closed."""
# Worker and preemption threads should exist before releasing
# ClusterCoordinator.
running_threads = test_util.get_running_threads()
self.assertTrue(
test_util.has_thread(_WORKER_THREAD_PREFIX, running_threads))
self.assertIn(_WORKER_PREEMPTION_THREAD_NAME, running_threads)
# Print object graph if ClusterCoordinator may leak.
if sys.getrefcount(self.cluster_coord) > 2:
try:
test_util.show_backref(self.cluster_coord)
except: # pylint: disable=bare-except
pass
# Wait for threads to close.
self.cluster_coord = None
self.strategy = None
gc.collect()
time.sleep(1)
# Verify thread names.
running_threads = test_util.get_running_threads()
self.assertNotIn(_WORKER_PREEMPTION_THREAD_NAME, running_threads)
self.assertFalse(
test_util.has_thread(_WORKER_THREAD_PREFIX, running_threads),
"Worker thread is not stopped properly.")
def _create_model_and_run_indefinitely(self):
model = Model(self.cluster_coord)
model.do_infinite_step.assign(True)
model.schedule_training_functions(10)
# Model does infinite training step, so at this moment, we expect to have
# `self.num_workers` infinite closures inflight, and `10-self.num_workers`
# closures in the queue.
while (self.cluster_coord._cluster.closure_queue._inflight_closure_count <
self.num_workers):
time.sleep(0.1)
return model
def testClusterCoordinatorDestroyed(self):
self._ensure_threads_closed()
def testWorkerPreemptionBetweenFunctions(self):
model = Model(self.cluster_coord)
model.schedule_training_functions(2)
model.join_training_functions()
self.assertEqual(model.iterations.numpy(), 2)
self._restart(downtime_secs=2, job="worker")
model.schedule_training_functions(2)
model.join_training_functions()
self.assertEqual(model.iterations.numpy(), 4)
def testWorkerPreemptionMidstFunction(self):
model = Model(self.cluster_coord)
model.do_infinite_step.assign(True)
model.schedule_training_functions(4)
# Model does infinite training step, so at this moment, we expect to have
# `self.num_workers` infinite closures inflight, and `4-self.num_workers`
# closures in the queue.
while (self.cluster_coord._cluster.closure_queue._inflight_closure_count <
self.num_workers):
time.sleep(0.1)
self.assertFalse(self.cluster_coord.done())
self._restart(downtime_secs=2, job="worker")
model.join_training_functions()
self.assertGreaterEqual(model.iterations.numpy(), 4)
def testOneWorkerPreemptionWithCancellation(self):
@def_function.function
def normal_function():
x = random_ops.random_uniform((2, 10))
y = random_ops.random_uniform((10, 2))
return math_ops.reduce_mean(math_ops.matmul(x, y))
@def_function.function
def error_function():
x = random_ops.random_uniform((2, 10))
y = random_ops.random_uniform((10, 2))
check_ops.assert_non_positive_v2(
math_ops.reduce_sum(math_ops.matmul(x, y)))
return x
@def_function.function
def long_function():
x = random_ops.random_uniform((1000, 1000))
for _ in math_ops.range(10000):
a = random_ops.random_uniform((1000, 1000))
b = random_ops.random_uniform((1000, 1000))
x += math_ops.matmul(a, b)
return x
for _ in range(3):
self.cluster_coord.schedule(normal_function)
long_function_result = self.cluster_coord.schedule(long_function)
self.cluster_coord.schedule(error_function)
time.sleep(1) # Let it run a couple steps.
self._restart(2, "worker")
# InvalidArgumentError thrown from the error_function.
with self.assertRaises(errors.InvalidArgumentError):
self.cluster_coord.join()
# CancelledError thrown by ClusterCoordinator after cancelling due to user
# error.
with self.assertRaises(errors.CancelledError):
long_function_result.fetch()
for _ in range(3):
self.cluster_coord.schedule(normal_function)
self.cluster_coord.join()
# The cluster is likely still being recovered since `join` returned early
# due to the error_function.
failure_handler = self.cluster_coord._cluster.failure_handler
failure_handler.stop()
failure_handler._preemption_handler_thread.join()
def testHandleDatasetCreationFailureWithDatasetFn(self):
model = Model(self.cluster_coord)
restart_thread = self._restart_in_thread(5, "worker")
model.schedule_training_functions(3)
model.rebuild_iterators()
model.schedule_training_functions(3)
model.rebuild_iterators()
model.schedule_training_functions(3)
model.join_training_functions()
self.thread_coord.join([restart_thread])
self.assertGreaterEqual(model.iterations.numpy(), 3)
# TODO(yuefengz): consider using combinations when there is more code
# duplication.
def testHandleDatasetCreationFailureWithDataset(self):
model = Model(self.cluster_coord)
restart_thread = self._restart_in_thread(5, "worker")
model.schedule_training_functions(3)
model.rebuild_iterators(use_dataset_fn=False)
model.schedule_training_functions(3)
model.rebuild_iterators(use_dataset_fn=False)
model.schedule_training_functions(3)
model.join_training_functions()
self.thread_coord.join([restart_thread])
self.assertGreaterEqual(model.iterations.numpy(), 3)
def testWorkerPreemptionErrorType(self):
@def_function.function
def worker_train_fn():
x = random_ops.random_uniform((2, 10))
y = random_ops.random_uniform((10, 2))
return math_ops.reduce_mean(math_ops.matmul(x, y))
def run_fn():
with self.thread_coord.stop_on_exception():
with ops.device("/job:worker/replica:0/task:0"):
for _ in range(3):
for _ in range(3):
worker_train_fn()
time.sleep(5)
run_thread = threading.Thread(target=run_fn)
run_thread.start()
time.sleep(1) # Let it run a couple steps.
self._restart(2, "worker")
try:
self.thread_coord.join([run_thread])
except (errors.UnavailableError, errors.AbortedError) as e:
logging.info("Got exception %r, error message is %s", e, e)
self.assertIn(_RPC_ERROR_FROM_WORKER, str(e)) # pylint: disable=g-assert-in-except
self.assertNotIn(_RPC_ERROR_FROM_PS, str(e))
self.assertTrue("failed to connect to all addresses" in str(e) or
"Unable to find a context_id" in str(e) or
"Socket closed" in str(e) or
"Connection reset by peer" in str(e) or
"Transport closed" in str(e))
def testWorkerPreemptionErrorTypeWithPythonFunction(self):
def worker_train_fn():
x = random_ops.random_uniform((2, 10))
y = random_ops.random_uniform((10, 2))
return math_ops.reduce_mean(math_ops.matmul(x, y))
def run_fn():
with self.thread_coord.stop_on_exception():
with ops.device("/job:worker/replica:0/task:0"):
for _ in range(3):
for _ in range(3):
worker_train_fn()
time.sleep(5)
run_thread = threading.Thread(target=run_fn)
run_thread.start()
time.sleep(1) # Let it run a couple steps.
self._restart(2, "worker")
try:
self.thread_coord.join([run_thread])
except (errors.UnavailableError, errors.AbortedError) as e:
logging.info("Got exception %r, error message is %s", e, e)
self.assertIn(_RPC_ERROR_FROM_WORKER, str(e)) # pylint: disable=g-assert-in-except
self.assertNotIn(_RPC_ERROR_FROM_PS, str(e))
self.assertTrue("failed to connect to all addresses" in str(e) or
"Unable to find a context_id" in str(e) or
"Socket closed" in str(e) or
"Connection reset by peer" in str(e) or
"Transport closed" in str(e))
def testPSPreemptionErrorType(self):
with ops.device("/job:ps/replica:0/task:0"):
v = variables.Variable(
initial_value=random_ops.random_uniform((2, 10)),
dtype=dtypes.float32)
@def_function.function
def worker_train_fn():
y = random_ops.random_uniform((10, 2))
return math_ops.reduce_mean(math_ops.matmul(v, y))
def run_fn():
with self.thread_coord.stop_on_exception():
with ops.device("/job:worker/replica:0/task:0"):
for _ in range(3):
for _ in range(3):
worker_train_fn()
time.sleep(5)
run_thread = threading.Thread(target=run_fn)
run_thread.start()
time.sleep(1) # Let it run a couple steps.
# Use a short restart delay to cover the case that RPC channel is reused
self._restart(1, "ps")
try:
self.thread_coord.join([run_thread])
except (errors.UnavailableError, errors.AbortedError) as e:
logging.info("Got exception %r, error message is %s", e, e)
self.assertIn(_RPC_ERROR_FROM_PS, str(e)) # pylint: disable=g-assert-in-except
if isinstance(e, errors.UnavailableError):
self.assertTrue("failed to connect to all addresses" in str(e) or
"Socket closed" in str(e) or
"Connection reset by peer" in str(e) or
"Transport closed" in str(e))
if isinstance(e, errors.AbortedError):
self.assertTrue(
"RecvTensor expects a different device incarnation" in str(e) or
"Unable to find a context_id" in str(e))
self._ensure_threads_closed()
def testTwoWorkersPreempted(self):
if self.num_workers < 2:
self.skipTest("Worker number is less than 2.")
model = self._create_model_and_run_indefinitely()
self.assertFalse(self.cluster_coord.done())
self._cluster.kill_task("worker", 0)
self._cluster.kill_task("worker", 1)
time.sleep(2)
self.assertFalse(context.check_alive("/job:worker/replica:0/task:0"))
self.assertFalse(context.check_alive("/job:worker/replica:0/task:1"))
self._cluster.start_task("worker", 0)
self._cluster.start_task("worker", 1)
time.sleep(2)
self.assertTrue(context.check_alive("/job:worker/replica:0/task:0"))
self.assertTrue(context.check_alive("/job:worker/replica:0/task:1"))
model.join_training_functions()
self.assertGreaterEqual(model.iterations.numpy(), 10)
def testWorkerContinuousFailure(self):
model = self._create_model_and_run_indefinitely()
self.assertFalse(self.cluster_coord.done())
self._cluster.kill_task("worker", 0)
time.sleep(2)
self.assertFalse(context.check_alive("/job:worker/replica:0/task:0"))
self._cluster.start_task("worker", 0)
time.sleep(2)
self.assertTrue(context.check_alive("/job:worker/replica:0/task:0"))
self._cluster.kill_task("worker", 0)
time.sleep(2)
self.assertFalse(context.check_alive("/job:worker/replica:0/task:0"))
self._cluster.start_task("worker", 0)
time.sleep(2)
self.assertTrue(context.check_alive("/job:worker/replica:0/task:0"))
model.join_training_functions()
self.assertGreaterEqual(model.iterations.numpy(), 10)
def testPSFailureWhileRecoveryFromWokerFailure(self):
model = self._create_model_and_run_indefinitely()
time.sleep(1)
self.assertFalse(self.cluster_coord.done())
def kill(task):
self._cluster.kill_task(task, 0)
self.sleep(1)
self._cluster.start_task(task, 0)
kill_thread_1 = threading.Thread(target=kill, args=("worker",))
kill_thread_2 = threading.Thread(target=kill, args=("ps",))
kill_thread_1.start()
kill_thread_2.start()
kill_thread_1.join()
kill_thread_2.join()
with self.assertRaises(
(errors.UnavailableError, errors.InvalidArgumentError)):
model.join_training_functions()
def testNumpyFetchedAfterWorkerFailure(self):
with self.strategy.scope():
v = variables.Variable(initial_value=0, dtype=dtypes.int32)
@def_function.function
def worker_fn():
return v + 1, v - 1
remote_value = self.cluster_coord.schedule(worker_fn)
# Attempt to fetch before killing worker task should succeed.
self.assertEqual((1, -1), remote_value.fetch())
self._cluster.kill_task("worker", 0)
# So should attempt to fetch after killing worker task.
self.assertEqual((1, -1), remote_value.fetch())
def testTensorGotAfterWorkerFailure(self):
with self.strategy.scope():
v = variables.Variable(initial_value=0, dtype=dtypes.int32)
@def_function.function
def worker_fn():
return v + 1, v - 1
remote_value = self.cluster_coord.schedule(worker_fn)
# Attempt to fetch before killing worker task should succeed.
fetched = remote_value.get()[0]
self.assertIsInstance(fetched, tensor.Tensor)
self.assertEqual(fetched.device, "/job:chief/replica:0/task:0/device:CPU:0")
self.assertEqual((1, -1), remote_value.get())
remote_value.get()[0].numpy()
# As well as the remote tensors that point to worker0 or worker1.
values = remote_value._values[0]
self.assertIsInstance(values, tensor.Tensor)
self.assertRegex(values.device,
"/job:worker/replica:0/task:[0-1]/device:CPU:0")
self.assertEqual((1, -1), remote_value._values)
remote_value._values[0].numpy()
# Terminate the workers and wait a little so that they are indeed killed.
for i in range(self.num_workers):
self._cluster.kill_task("worker", i)
time.sleep(5)
# Attempt to fetch after killing worker tasks should succeed as well.
remote_value.get()[0].numpy()
self.assertEqual((1, -1), remote_value.get())
# Attempting to copy the tensor from worker now should fail.
with self.assertRaises(errors.UnavailableError) as cm:
remote_value._values[0].numpy()
self.assertIn("failed to connect to all addresses", cm.exception.message)
self.assertIn("/job:worker/replica:0/task:", cm.exception.message)
def testFetchFromPSAfterWorkerFailure(self):
# Test for flaky failures when reading from a parameter server while a
# worker is recovering.
# Place some variables on PSes, kill a worker, and continuously poll one of
# those variables.
model = Model(self.cluster_coord)
# kill the worker after a delay to make sure variable reading runs while
# worker is up, while it's down, and while it restarts
def kill_after_delay():
time.sleep(3)
logging.info("Killing worker 0")
self._cluster.kill_task("worker", 0)
time.sleep(1)
logging.info("Restarting worker 0")
self._cluster.start_task("worker", 0)
kill_thread = threading.Thread(target=kill_after_delay)
kill_thread.start()
model.do_infinite_step.assign(True)
model.schedule_training_functions(1)
num_reads = 0
num_reads_after_restart = 0
read_interval_secs = 0.1
worker_has_stopped = False
# limit runtime of the test: stop after doing a few reads after worker
# is back up, or after a fixed maximum number of reads
while num_reads_after_restart <= 5 and num_reads < 200:
worker_up = context.check_alive("/job:worker/replica:0/task:0")
if not worker_up:
worker_has_stopped = True
if worker_up and worker_has_stopped:
num_reads_after_restart += 1
model.join_training_functions()
start = time.time()
while time.time() < start + read_interval_secs:
model.iterations.read_value()
num_reads += 1
# run another epoch
model.do_infinite_step.assign(True)
model.schedule_training_functions(1)
def testClusterStateNotDisrupted(self):
# This test has side effects and can disrupt other tests, even if the
# resource created by it will not be used in following tests.
# TODO(b/155209534): enable this test.
# self.testPSPreemptionErrorType()
self.thread_coord = thread_coordinator.Coordinator(
clean_stop_exception_types=[])
self.testWorkerPreemptionMidstFunction()
self.thread_coord = thread_coordinator.Coordinator(
clean_stop_exception_types=[])
self.testWorkerPreemptionErrorType()
# In previous tests, workers may fail after training is done. But the
# following tests start with creating resources where failure is not
# handled.
# TODO(b/153888707): enable the following two tests.
# self.testTwoWorkersPreempted()
# self.testWorkerContinuousFailure()
def _run_and_kill_ps_task(self):
self._create_model_and_run_indefinitely()
self._cluster.kill_task("ps", 0)
while self.cluster_coord._cluster.closure_queue._error is None:
time.sleep(1)
logging.info("Trying to join, expecting error")
def testJoinRaisesUnavailableErrorAtPsFailure(self):
self._run_and_kill_ps_task()
with self.assertRaises((errors.UnavailableError, errors.NotFoundError,
errors.FailedPreconditionError)):
self.cluster_coord.join()
def testScheduleRaisesUnavailableErrorAtPsFailure(self):
self._run_and_kill_ps_task()
with self.assertRaises((errors.UnavailableError, errors.NotFoundError,
errors.FailedPreconditionError)):
self.cluster_coord.schedule(def_function.function(lambda: None))
def testWorkerExecutionAfterPsFailureRaisesExpectedError(self):
model = self._create_model_and_run_indefinitely()
for i in range(self.num_ps):
self._cluster.kill_task("ps", i)
while self.cluster_coord._cluster.closure_queue._error is None:
time.sleep(1)
@def_function.function
def trivial_function():
return model.iterations + 1
for i in range(self.num_workers):
try:
with ops.device("/job:worker/replica:0/task:{}".format(i)):
trivial_function()
except Exception as e: # pylint: disable=broad-except
if cluster_coordinator._is_ps_failure(e): # pylint: disable=protected-access
if i < self.num_workers - 1:
continue
return
raise AssertionError("Executing a function after PS fails, should "
"result in a PS failure.")
def testAsyncWaitIsNoOp(self):
if self.num_workers < 2:
self.skipTest("Worker number is less than 2.")
model = self._create_model_and_run_indefinitely()
self.assertFalse(self.cluster_coord.done())
self._cluster.kill_task("worker", 0)
time.sleep(2)
self.assertFalse(context.check_alive("/job:worker/replica:0/task:0"))
# Should pass without exception even with failed remote workers
context.async_wait()
model.join_training_functions()
self.assertGreaterEqual(model.iterations.numpy(), 10)
self._cluster.start_task("worker", 0)
| BaseFaultToleranceTest |
python | aimacode__aima-python | utils.py | {
"start": 21732,
"end": 21937
} | class ____(int):
"""Just like `bool`, except values display as 'T' and 'F' instead of 'True' and 'False'."""
__str__ = __repr__ = lambda self: 'T' if self else 'F'
T = Bool(True)
F = Bool(False)
| Bool |
python | catalyst-team__catalyst | catalyst/contrib/data/dataset.py | {
"start": 2845,
"end": 4149
} | class ____(Dataset):
"""General purpose dataset class to use with `numpy_data`."""
def __init__(
self,
numpy_data: np.ndarray,
numpy_key: str = "features",
dict_transform: Optional[Callable] = None,
):
"""
General purpose dataset class to use with `numpy_data`.
Args:
numpy_data: numpy data
(for example path to embeddings, features, etc.)
numpy_key: key to use for output dictionary
dict_transform: transforms to use on dict.
(for example normalize vector, etc)
"""
super().__init__()
self.data = numpy_data
self.key = numpy_key
self.dict_transform = (
dict_transform if dict_transform is not None else lambda x: x
)
def __getitem__(self, index: int) -> Any:
"""Gets element of the dataset.
Args:
index: index of the element in the dataset
Returns:
Single element by index
"""
dict_ = {self.key: np.copy(self.data[index])}
dict_ = self.dict_transform(dict_)
return dict_
def __len__(self) -> int:
"""
Returns:
int: length of the dataset
"""
return len(self.data)
| NumpyDataset |
python | astropy__astropy | astropy/cosmology/_src/tests/io/base.py | {
"start": 1873,
"end": 2913
} | class ____(IOTestBase):
"""Tests for a Cosmology[Read/Write].
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass. Subclasses must define a :func:`pytest.fixture`
``cosmo`` that returns/yields an instance of a |Cosmology|.
See ``TestCosmology`` for an example.
"""
@pytest.fixture(scope="class")
def read(self):
"""Read Cosmology instance using ``Cosmology.read()``."""
return Cosmology.read
@pytest.fixture(scope="class")
def write(self, cosmo):
"""Write Cosmology using ``.write()``."""
return cosmo.write
@pytest.fixture
def add_cu(self):
"""Add :mod:`astropy.cosmology.units` to the enabled units."""
# TODO! autoenable 'cu' if cosmology is imported?
with u.add_enabled_units(cu):
yield
##############################################################################
| ReadWriteTestMixinBase |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 113674,
"end": 117901
} | class ____(Fittable1DModel):
"""
Projected (surface density) analytic King Model.
Parameters
----------
amplitude : float
Amplitude or scaling factor.
r_core : float
Core radius (f(r_c) ~ 0.5 f_0)
r_tide : float
Tidal radius.
Notes
-----
This model approximates a King model with an analytic function. The derivation of this
equation can be found in King '62 (equation 14). This is just an approximation of the
full model and the parameters derived from this model should be taken with caution.
It usually works for models with a concentration (c = log10(r_t/r_c) parameter < 2.
Model formula:
.. math::
f(x) = A r_c^2 \\left(\\frac{1}{\\sqrt{(x^2 + r_c^2)}} -
\\frac{1}{\\sqrt{(r_t^2 + r_c^2)}}\\right)^2
Examples
--------
.. plot::
:include-source:
import numpy as np
from astropy.modeling.models import KingProjectedAnalytic1D
import matplotlib.pyplot as plt
plt.figure()
rt_list = [1, 2, 5, 10, 20]
for rt in rt_list:
r = np.linspace(0.1, rt, 100)
mod = KingProjectedAnalytic1D(amplitude = 1, r_core = 1., r_tide = rt)
sig = mod(r)
plt.loglog(r, sig/sig[0], label=f"c ~ {mod.concentration:0.2f}")
plt.xlabel("r")
plt.ylabel(r"$\\sigma/\\sigma_0$")
plt.legend()
plt.show()
References
----------
.. [1] https://ui.adsabs.harvard.edu/abs/1962AJ.....67..471K
"""
amplitude = Parameter(
default=1,
bounds=(FLOAT_EPSILON, None),
description="Amplitude or scaling factor",
)
r_core = Parameter(
default=1, bounds=(FLOAT_EPSILON, None), description="Core Radius"
)
r_tide = Parameter(
default=2, bounds=(FLOAT_EPSILON, None), description="Tidal Radius"
)
@property
def concentration(self):
"""Concentration parameter of the king model."""
return np.log10(np.abs(self.r_tide / self.r_core))
@staticmethod
def _core_func(x, r_core, r_tide, power=1):
return (
1.0 / np.sqrt(x**2 + r_core**2) ** power
- 1.0 / np.sqrt(r_tide**2 + r_core**2) ** power
)
@staticmethod
def _filter(x, r_tide, result):
"""Set invalid r values to 0"""
bounds = (x >= r_tide) | (x < 0)
result[bounds] = result[bounds] * 0.0
def evaluate(self, x, amplitude, r_core, r_tide):
"""
Analytic King model function.
"""
result = amplitude * r_core**2 * self._core_func(x, r_core, r_tide) ** 2
self._filter(x, r_tide, result)
return result
def fit_deriv(self, x, amplitude, r_core, r_tide):
"""
Analytic King model function derivatives.
"""
d_amplitude = r_core**2 * self._core_func(x, r_core, r_tide) ** 2
self._filter(x, r_tide, d_amplitude)
d_r_core = (
-2.0
* amplitude
* r_core**3
* self._core_func(x, r_core, r_tide, power=3)
* self._core_func(x, r_core, r_tide)
+ 2 * amplitude * r_core * self._core_func(x, r_core, r_tide) ** 2
)
self._filter(x, r_tide, d_r_core)
d_r_tide = (
2 * amplitude * r_core**2 * r_tide * self._core_func(x, r_core, r_tide)
) / (r_core**2 + r_tide**2) ** (3 / 2)
self._filter(x, r_tide, d_r_tide)
return [d_amplitude, d_r_core, d_r_tide]
@property
def bounding_box(self):
"""
Tuple defining the default ``bounding_box`` limits.
The model is not defined for r > r_tide.
``(r_low, r_high)``
"""
return (0 * self.r_tide, 1 * self.r_tide)
@property
def input_units(self):
if self.r_core.input_unit is None:
return None
return {self.inputs[0]: self.r_core.input_unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {
"r_core": inputs_unit[self.inputs[0]],
"r_tide": inputs_unit[self.inputs[0]],
"amplitude": outputs_unit[self.outputs[0]],
}
| KingProjectedAnalytic1D |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/relationship.py | {
"start": 2671,
"end": 3233
} | class ____(Base):
"""test for #9150"""
__tablename__ = "MyTable"
idx: Mapped[int] = mapped_column(Integer, primary_key=True)
mytable_id: Mapped[int] = mapped_column(ForeignKey("MyTable.idx"))
not_anno = mapped_column(Integer)
selfref_1: Mapped[Optional[SelfReferential]] = relationship(
remote_side=idx
)
selfref_2: Mapped[Optional[SelfReferential]] = relationship(
foreign_keys=mytable_id
)
selfref_3: Mapped[Optional[SelfReferential]] = relationship(
remote_side=not_anno
)
| SelfReferential |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/transfers/mssql_to_hive.py | {
"start": 1309,
"end": 5791
} | class ____(BaseOperator):
"""
Moves data from Microsoft SQL Server to Hive.
The operator runs your query against Microsoft SQL Server, stores
the file locally before loading it into a Hive table. If the
``create`` or ``recreate`` arguments are set to ``True``, a
``CREATE TABLE`` and ``DROP TABLE`` statements are generated.
Hive data types are inferred from the cursor's metadata.
Note that the table generated in Hive uses ``STORED AS textfile``
which isn't the most efficient serialization format. If a
large amount of data is loaded and/or if the table gets
queried considerably, you may want to use this operator only to
stage the data into a temporary table before loading it into its
final destination using a ``HiveOperator``.
:param sql: SQL query to execute against the Microsoft SQL Server
database. (templated)
:param hive_table: target Hive table, use dot notation to target a specific
database. (templated)
:param create: whether to create the table if it doesn't exist
:param recreate: whether to drop and recreate the table at every execution
:param partition: target partition as a dict of partition columns and
values. (templated)
:param delimiter: field delimiter in the file
:param mssql_conn_id: source Microsoft SQL Server connection
:param hive_cli_conn_id: Reference to the
:ref:`Hive CLI connection id <howto/connection:hive_cli>`.
:param hive_auth: optional authentication option passed for the Hive connection
:param tblproperties: TBLPROPERTIES of the hive table being created
"""
template_fields: Sequence[str] = ("sql", "partition", "hive_table")
template_ext: Sequence[str] = (".sql",)
template_fields_renderers = {"sql": "tsql"}
ui_color = "#a0e08c"
def __init__(
self,
*,
sql: str,
hive_table: str,
create: bool = True,
recreate: bool = False,
partition: dict | None = None,
delimiter: str = chr(1),
mssql_conn_id: str = "mssql_default",
hive_cli_conn_id: str = "hive_cli_default",
hive_auth: str | None = None,
tblproperties: dict | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.sql = sql
self.hive_table = hive_table
self.partition = partition
self.create = create
self.recreate = recreate
self.delimiter = delimiter
self.mssql_conn_id = mssql_conn_id
self.hive_cli_conn_id = hive_cli_conn_id
self.partition = partition or {}
self.tblproperties = tblproperties
self.hive_auth = hive_auth
@classmethod
def type_map(cls, mssql_type: int) -> str:
"""Map MsSQL type to Hive type."""
map_dict = {
pymssql.BINARY.value: "INT", # type:ignore[attr-defined]
pymssql.DECIMAL.value: "FLOAT", # type:ignore[attr-defined]
pymssql.NUMBER.value: "INT", # type:ignore[attr-defined]
}
return map_dict.get(mssql_type, "STRING")
def execute(self, context: Context):
mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id)
self.log.info("Dumping Microsoft SQL Server query results to local file")
with mssql.get_conn() as conn:
with conn.cursor() as cursor:
cursor.execute(self.sql)
with NamedTemporaryFile(mode="w", encoding="utf-8") as tmp_file:
csv_writer = csv.writer(tmp_file, delimiter=self.delimiter)
field_dict = {}
for col_count, field in enumerate(cursor.description, start=1):
col_position = f"Column{col_count}"
field_dict[col_position if field[0] == "" else field[0]] = self.type_map(field[1])
csv_writer.writerows(cursor) # type:ignore[arg-type]
tmp_file.flush()
hive = HiveCliHook(hive_cli_conn_id=self.hive_cli_conn_id, auth=self.hive_auth)
self.log.info("Loading file into Hive")
hive.load_file(
tmp_file.name,
self.hive_table,
field_dict=field_dict,
create=self.create,
partition=self.partition,
delimiter=self.delimiter,
recreate=self.recreate,
tblproperties=self.tblproperties,
)
| MsSqlToHiveOperator |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/api.py | {
"start": 2630,
"end": 2753
} | class ____:
Consoles = 'tabs_consoles_section'
Edit = 'tabs_edit_section'
| IPythonConsoleWidgetTabsContextMenuSections |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_iter.py | {
"start": 2326,
"end": 2605
} | class ____:
def __init__(self, n):
self.n = n
self.i = 0
def __next__(self):
res = self.i
if res >= self.n:
raise StopIteration
self.i = res + 1
return res
def __iter__(self):
return self
| BasicIterClass |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 35122,
"end": 35777
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
MSE loss.
regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
Regression outputs of the time series modeling heads.
"""
loss: Optional[torch.FloatTensor] = None
regression_outputs: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`PatchTSTForPrediction`].
"""
)
| PatchTSTForRegressionOutput |
python | PyCQA__pylint | pylint/reporters/base_reporter.py | {
"start": 575,
"end": 3087
} | class ____:
"""Base class for reporters.
symbols: show short symbolic names for messages.
"""
extension = ""
name = "base"
"""Name of the reporter."""
def __init__(self, output: TextIO | None = None) -> None:
self.linter: PyLinter
self.section = 0
self.out: TextIO = output or sys.stdout
self.messages: list[Message] = []
# Build the path prefix to strip to get relative paths
self.path_strip_prefix = os.getcwd() + os.sep
def handle_message(self, msg: Message) -> None:
"""Handle a new message triggered on the current file."""
self.messages.append(msg)
def writeln(self, string: str = "") -> None:
"""Write a line in the output buffer."""
try:
print(string, file=self.out)
except UnicodeEncodeError:
print(self.reencode_output_after_unicode_error(string), file=self.out)
@staticmethod
def reencode_output_after_unicode_error(string: str) -> str:
return string.encode(encoding="utf-8", errors="replace").decode("utf8")
def display_reports(self, layout: Section) -> None:
"""Display results encapsulated in the layout tree."""
self.section = 0
if layout.report_id:
if isinstance(layout.children[0].children[0], Text):
layout.children[0].children[0].data += f" ({layout.report_id})"
else:
raise ValueError(f"Incorrect child for {layout.children[0].children}")
self._display(layout)
def _display(self, layout: Section) -> None:
"""Display the layout."""
raise NotImplementedError()
def display_messages(self, layout: Section | None) -> None:
"""Hook for displaying the messages of the reporter.
This will be called whenever the underlying messages
needs to be displayed. For some reporters, it probably
doesn't make sense to display messages as soon as they
are available, so some mechanism of storing them could be used.
This method can be implemented to display them after they've
been aggregated.
"""
# Event callbacks
def on_set_current_module(self, module: str, filepath: str | None) -> None:
"""Hook called when a module starts to be analysed."""
def on_close(
self,
stats: LinterStats,
previous_stats: LinterStats | None,
) -> None:
"""Hook called when a module finished analyzing."""
| BaseReporter |
python | streamlit__streamlit | lib/tests/streamlit/commands/page_config_test.py | {
"start": 1151,
"end": 7737
} | class ____(DeltaGeneratorTestCase):
def test_set_page_config_title(self):
st.set_page_config(page_title="Hello")
c = self.get_message_from_queue().page_config_changed
assert c.title == "Hello"
@parameterized.expand([":shark:", "https://foo.com/image.png"])
def test_set_page_config_icon_strings(self, icon_string: str):
"""page_config icons can be emoji shortcodes, and image URLs."""
st.set_page_config(page_icon=icon_string)
c = self.get_message_from_queue().page_config_changed
assert c.favicon == icon_string
def test_set_page_config_emoji_icon_strings(self):
"""page_config icons can be emojis."""
st.set_page_config(page_icon="🦈")
c = self.get_message_from_queue().page_config_changed
assert c.favicon == "emoji:🦈"
def test_set_page_config_icon_random(self):
"""If page_icon == "random", we choose a random emoji."""
st.set_page_config(page_icon="random")
c = self.get_message_from_queue().page_config_changed
assert c.favicon in set(RANDOM_EMOJIS)
assert is_emoji(c.favicon)
def test_set_page_config_icon_invalid_string(self):
"""If set_page_config is passed a garbage icon string, we just pass it
through without an error (even though nothing will be displayed).
"""
st.set_page_config(page_icon="st.balloons")
c = self.get_message_from_queue().page_config_changed
assert c.favicon == "st.balloons"
@parameterized.expand([param(b"123"), param("file/on/disk.png")])
def test_set_page_config_icon_calls_image_to_url(self, icon: PageIcon):
"""For all other page_config icon inputs, we just call image_to_url."""
with mock.patch(
"streamlit.commands.page_config.image_to_url",
return_value="https://mock.url",
):
st.set_page_config(page_icon=icon)
c = self.get_message_from_queue().page_config_changed
assert c.favicon == "https://mock.url"
def test_set_page_config_layout_wide(self):
st.set_page_config(layout="wide")
c = self.get_message_from_queue().page_config_changed
assert c.layout == PageConfigProto.WIDE
def test_set_page_config_layout_centered(self):
st.set_page_config(layout="centered")
c = self.get_message_from_queue().page_config_changed
assert c.layout == PageConfigProto.CENTERED
def test_set_page_config_layout_none(self):
st.set_page_config(layout=None)
c = self.get_message_from_queue().page_config_changed
assert c.layout == PageConfigProto.LAYOUT_UNSET
def test_set_page_config_layout_invalid(self):
with pytest.raises(StreamlitAPIException):
st.set_page_config(layout="invalid")
def test_set_page_config_sidebar_auto(self):
st.set_page_config(initial_sidebar_state="auto")
c = self.get_message_from_queue().page_config_changed
assert c.initial_sidebar_state == PageConfigProto.AUTO
def test_set_page_config_sidebar_expanded(self):
st.set_page_config(initial_sidebar_state="expanded")
c = self.get_message_from_queue().page_config_changed
assert c.initial_sidebar_state == PageConfigProto.EXPANDED
def test_set_page_config_sidebar_collapsed(self):
st.set_page_config(initial_sidebar_state="collapsed")
c = self.get_message_from_queue().page_config_changed
assert c.initial_sidebar_state == PageConfigProto.COLLAPSED
def test_set_page_config_sidebar_none(self):
st.set_page_config(initial_sidebar_state=None)
c = self.get_message_from_queue().page_config_changed
assert c.initial_sidebar_state == PageConfigProto.SIDEBAR_UNSET
def test_set_page_config_sidebar_invalid(self):
with pytest.raises(StreamlitInvalidSidebarStateError):
st.set_page_config(initial_sidebar_state="INVALID")
def test_set_page_config_menu_items_about(self):
menu_items = {" about": "*This is an about. This accepts markdown.*"}
st.set_page_config(menu_items=menu_items)
c = self.get_message_from_queue().page_config_changed.menu_items
assert c.about_section_md == "*This is an about. This accepts markdown.*"
def test_set_page_config_menu_items_bug_and_help(self):
menu_items = {
"report a bug": "https://report_a_bug.com",
"GET HELP": "https://get_help.com",
}
st.set_page_config(menu_items=menu_items)
c = self.get_message_from_queue().page_config_changed.menu_items
assert not c.hide_report_a_bug
assert not c.hide_get_help
assert c.about_section_md == ""
assert c.report_a_bug_url == "https://report_a_bug.com"
assert c.get_help_url == "https://get_help.com"
def test_set_page_config_menu_items_empty_string(self):
with pytest.raises(StreamlitInvalidURLError):
menu_items = {"report a bug": "", "GET HELP": "", "about": ""}
st.set_page_config(menu_items=menu_items)
def test_set_page_config_menu_items_none(self):
menu_items = {"report a bug": None, "GET HELP": None, "about": None}
st.set_page_config(menu_items=menu_items)
c = self.get_message_from_queue().page_config_changed.menu_items
assert c.hide_report_a_bug
assert c.hide_get_help
assert c.about_section_md == ""
def test_set_page_config_menu_items_invalid(self):
with pytest.raises(StreamlitAPIException) as e:
menu_items = {"invalid": "fdsa"}
st.set_page_config(menu_items=menu_items)
assert str(e.value) == (
'We only accept the keys: `"Get help"`, `"Report a bug"`, and `"About"` '
'(`"invalid"` is not a valid key.)'
)
def test_set_page_config_menu_items_empty_dict(self):
st.set_page_config(menu_items={})
c = self.get_message_from_queue().page_config_changed.menu_items
assert c.about_section_md == ""
@parameterized.expand(
[
({}, {}),
(
{
"HELLO_1": 4,
"Hello_2": "world",
"hElLo_3": 5.5,
"": "",
},
{"hello_1": 4, "hello_2": "world", "hello_3": 5.5, "": ""},
),
]
)
def test_lower_clean_dict_keys(self, input_dict, answer_dict):
return_dict = _lower_clean_dict_keys(input_dict)
assert return_dict == answer_dict
| PageConfigTest |
python | pypa__pip | tests/unit/test_locations.py | {
"start": 525,
"end": 3261
} | class ____:
def setup_method(self) -> None:
self.tempdir = tempfile.mkdtemp()
self.st_uid = 9999
self.username = "example"
self.patch()
def teardown_method(self) -> None:
self.revert_patch()
shutil.rmtree(self.tempdir, ignore_errors=True)
def patch(self) -> None:
"""first store and then patch python methods pythons"""
self.tempfile_gettempdir = tempfile.gettempdir
self.old_os_fstat = os.fstat
if sys.platform != "win32":
# os.geteuid and pwd.getpwuid are not implemented on windows
self.old_os_geteuid = os.geteuid
self.old_pwd_getpwuid = pwd.getpwuid
self.old_getpass_getuser = getpass.getuser
# now patch
tempfile.gettempdir = lambda: self.tempdir
getpass.getuser = lambda: self.username
os.fstat = lambda fd: self.get_mock_fstat(fd)
if sys.platform != "win32":
os.geteuid = lambda: self.st_uid
pwd.getpwuid = self.get_mock_getpwuid
def revert_patch(self) -> None:
"""revert the patches to python methods"""
tempfile.gettempdir = self.tempfile_gettempdir
getpass.getuser = self.old_getpass_getuser
if sys.platform != "win32":
# os.geteuid and pwd.getpwuid are not implemented on windows
os.geteuid = self.old_os_geteuid
pwd.getpwuid = self.old_pwd_getpwuid
os.fstat = self.old_os_fstat
def get_mock_fstat(self, fd: int) -> os.stat_result:
"""returns a basic mock fstat call result.
Currently only the st_uid attribute has been set.
"""
result = Mock()
result.st_uid = self.st_uid
return result
def get_mock_getpwuid(self, uid: int) -> Any:
"""returns a basic mock pwd.getpwuid call result.
Currently only the pw_name attribute has been set.
"""
result = Mock()
result.pw_name = self.username
return result
def test_default_should_use_sysconfig(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.delattr(sysconfig, "_PIP_USE_SYSCONFIG", raising=False)
if sys.version_info[:2] >= (3, 10):
assert _should_use_sysconfig() is True
else:
assert _should_use_sysconfig() is False
@pytest.mark.parametrize("vendor_value", [True, False, None, "", 0, 1])
def test_vendor_overriden_should_use_sysconfig(
self, monkeypatch: pytest.MonkeyPatch, vendor_value: Any
) -> None:
monkeypatch.setattr(
sysconfig, "_PIP_USE_SYSCONFIG", vendor_value, raising=False
)
assert _should_use_sysconfig() is bool(vendor_value)
| TestLocations |
python | chardet__chardet | chardet/macromanprober.py | {
"start": 4377,
"end": 6077
} | class ____(CharSetProber):
def __init__(self) -> None:
super().__init__()
self._last_char_class = OTH
self._freq_counter: List[int] = []
self.reset()
def reset(self) -> None:
self._last_char_class = OTH
self._freq_counter = [0] * FREQ_CAT_NUM
# express the prior that MacRoman is a somewhat rare encoding;
# this can be done by starting out in a slightly improbable state
# that must be overcome
self._freq_counter[2] = 10
super().reset()
@property
def charset_name(self) -> str:
return "MacRoman"
@property
def language(self) -> str:
return ""
def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
byte_str = self.remove_xml_tags(byte_str)
for c in byte_str:
char_class = MacRoman_CharToClass[c]
freq = MacRomanClassModel[(self._last_char_class * CLASS_NUM) + char_class]
if freq == 0:
self._state = ProbingState.NOT_ME
break
self._freq_counter[freq] += 1
self._last_char_class = char_class
return self.state
def get_confidence(self) -> float:
if self.state == ProbingState.NOT_ME:
return 0.01
total = sum(self._freq_counter)
confidence = (
0.0
if total < 0.01
else (self._freq_counter[3] - self._freq_counter[1] * 20.0) / total
)
confidence = max(confidence, 0.0)
# lower the confidence of MacRoman so that other more accurate
# detector can take priority.
confidence *= 0.73
return confidence
| MacRomanProber |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 6509,
"end": 6718
} | class ____(ReprForm):
def __init__(self, subfield_count=12, **kwargs):
super().__init__(**kwargs)
self.fields["mv_field"] = MultiBooleanField(subfield_count=subfield_count)
| ManyMultiValueForm |
python | dask__distributed | distributed/tests/test_core.py | {
"start": 1271,
"end": 4348
} | class ____:
"""
A class which counts the number of live instances.
"""
n_instances = 0
# Use __new__, as __init__ can be bypassed by pickle.
def __new__(cls):
cls.n_instances += 1
obj = object.__new__(cls)
weakref.finalize(obj, cls._finalize)
return obj
@classmethod
def _finalize(cls, *args):
cls.n_instances -= 1
def echo_serialize(comm, x):
return {"result": to_serialize(x)}
def echo_no_serialize(comm, x):
return {"result": x}
@gen_test()
async def test_server_status_is_always_enum():
"""Assignments with strings is forbidden"""
server = Server({})
assert isinstance(server.status, Status)
assert server.status != Status.stopped
server.status = Status.stopped
assert server.status == Status.stopped
with pytest.raises(TypeError):
server.status = "running"
@gen_test()
async def test_server_assign_assign_enum_is_quiet():
"""That would be the default in user code"""
server = Server({})
server.status = Status.running
@gen_test()
async def test_server_status_compare_enum_is_quiet():
"""That would be the default in user code"""
server = Server({})
# Note: We only want to assert that this comparison does not
# raise an error/warning. We do not want to assert its result.
server.status == Status.running # noqa: B015
@gen_test(config={"distributed.admin.system-monitor.gil.enabled": True})
async def test_server_close_stops_gil_monitoring():
pytest.importorskip("gilknocker")
server = Server({})
assert server.monitor._gilknocker.is_running
await server.close()
assert not server.monitor._gilknocker.is_running
@gen_test()
async def test_server():
"""
Simple Server test.
"""
async with Server({"ping": pingpong}) as server:
with pytest.raises(ValueError):
server.port
await server.listen(8881)
assert server.port == 8881
assert server.address == ("tcp://%s:8881" % get_ip())
await server
for addr in ("127.0.0.1:8881", "tcp://127.0.0.1:8881", server.address):
comm = await connect(addr)
n = await comm.write({"op": "ping"})
assert isinstance(n, int)
assert 4 <= n <= 1000
response = await comm.read()
assert response == b"pong"
await comm.write({"op": "ping", "close": True})
response = await comm.read()
assert response == b"pong"
await comm.close()
@gen_test()
async def test_server_raises_on_blocked_handlers():
async with Server({"ping": pingpong}, blocked_handlers=["ping"]) as server:
await server.listen(8881)
comm = await connect(server.address)
await comm.write({"op": "ping"})
msg = await comm.read()
_, exception, _ = clean_exception(msg["exception"])
assert isinstance(exception, ValueError)
assert "'ping' handler has been explicitly disallowed" in repr(exception)
await comm.close()
| CountedObject |
python | fastai__fastai | fastai/optimizer.py | {
"start": 15942,
"end": 19160
} | class ____(Optimizer, GetAttr):
"Wrap `opt` in a lookahead optimizer"
_default='opt'
def __init__(self,
opt:Optimizer, # `Optimizer` to wrap with Lookahead
k:int=6, # How often to conduct Lookahead step
alpha:float=0.5, # Slow weight moving average coefficient
):
store_attr('opt,k,alpha')
self._init_state()
def step(self, closure=None):
if closure is not None: raise NotImplementedError("fastai optimizers currently do not support closure")
if self.slow_weights is None: self._copy_weights()
self.opt.step()
self.count += 1
if self.count%self.k != 0: return
for slow_pg,fast_pg in zip(self.slow_weights,self.param_lists):
for slow_p,fast_p in zip(slow_pg,fast_pg):
slow_p.data.add_(fast_p.data-slow_p.data, alpha=self.alpha)
fast_p.data.copy_(slow_p.data)
def clear_state(self):
self.opt.clear_state()
self._init_state()
def state_dict(self):
state = self.opt.state_dict()
state.update({'count': self.count, 'slow_weights': self.slow_weights})
return state
def load_state_dict(self, sd):
self.count = sd.pop('count')
self.slow_weights = sd.pop('slow_weights')
self.opt.load_state_dict(sd)
def _init_state(self): self.count,self.slow_weights = 0,None
def _copy_weights(self): self.slow_weights = L(L(p.clone().detach() for p in pg) for pg in self.param_lists)
@property
def param_lists(self): return self.opt.param_lists
@param_lists.setter
def param_lists(self, v): self.opt.param_lists = v
# %% ../nbs/12_optimizer.ipynb 111
@delegates(RAdam)
def ranger(
params:Tensor|Iterable, # Model parameters
lr:float|slice, # Default learning rate
mom:float=0.95, # Gradient moving average (β1) coefficient
wd:Real=0.01, # Optional weight decay (true or L2)
eps:float=1e-6, # Added for numerical stability
k:int=6, # How often to conduct Lookahead step
alpha:float=0.5, # Slow weight moving average coefficient
**kwargs
) -> Lookahead:
"Convenience method for `Lookahead` with `RAdam`"
return Lookahead(RAdam(params, lr=lr, mom=mom, wd=wd, eps=eps, **kwargs), k=k, alpha=alpha)
# %% ../nbs/12_optimizer.ipynb 114
def detuplify_pg(d):
res = {}
for k,v in d.items():
if k == 'params': continue
if is_listy(v): res.update(**{f'{k}__{i}': v_ for i,v_ in enumerate(v)})
else: res[k] = v
return res
# %% ../nbs/12_optimizer.ipynb 116
def set_item_pg(pg, k, v):
if '__' not in k: pg[k] = v
else:
name,idx = k.split('__')
pg[name] = tuple(v if i==int(idx) else pg[name][i] for i in range_of(pg[name]))
return pg
# %% ../nbs/12_optimizer.ipynb 118
pytorch_hp_map = {'momentum': 'mom', 'weight_decay': 'wd', 'alpha': 'sqr_mom', 'betas__0': 'mom',
'betas__1': 'sqr_mom'}
# %% ../nbs/12_optimizer.ipynb 119
def _convert_params(o:list) -> list:
splitter = []
for group in o:
if isinstance(group, dict): splitter.append(group)
else: splitter.append({'params':group})
return splitter
# %% ../nbs/12_optimizer.ipynb 120
| Lookahead |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 7451,
"end": 7597
} | class ____(ASTBase):
pass
# Primary expressions
################################################################################
| ASTExpression |
python | huggingface__transformers | src/transformers/models/gemma2/modeling_gemma2.py | {
"start": 20794,
"end": 24037
} | class ____(Gemma2PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Gemma2Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""
Example:
```python
>>> from transformers import AutoTokenizer, Gemma2ForCausalLM
>>> model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-9b")
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is your favorite condiment?"
```"""
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
if self.config.final_logit_softcapping is not None:
logits = logits / self.config.final_logit_softcapping
logits = torch.tanh(logits)
logits = logits * self.config.final_logit_softcapping
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| Gemma2ForCausalLM |
python | doocs__leetcode | solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py | {
"start": 0,
"end": 310
} | class ____:
def minDeletion(self, nums: List[int]) -> int:
n = len(nums)
i = ans = 0
while i < n - 1:
if nums[i] == nums[i + 1]:
ans += 1
i += 1
else:
i += 2
ans += (n - ans) % 2
return ans
| Solution |
python | pydantic__pydantic | tests/benchmarks/shared.py | {
"start": 4798,
"end": 5035
} | class ____(BaseModel):
model_config = {'defer_build': True}
def rebuild_model(model: type[BaseModel], raise_errors: bool = True) -> None:
model.model_rebuild(force=True, _types_namespace={}, raise_errors=raise_errors)
| DeferredModel |
python | jazzband__prettytable | tests/test_style.py | {
"start": 229,
"end": 6648
} | class ____:
"""Verify different cases for positional-junction characters"""
def test_default(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
assert (
city_data.get_string().strip()
== """
╔═══════════╦══════╦════════════╦═════════════════╗
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Adelaide ║ 1295 ║ 1158259 ║ 600.5 ║
║ Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║ Darwin ║ 112 ║ 120900 ║ 1714.7 ║
║ Hobart ║ 1357 ║ 205556 ║ 619.5 ║
║ Sydney ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9 ║
║ Perth ║ 5386 ║ 1554769 ║ 869.4 ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
)
def test_no_header(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.header = False
assert (
city_data.get_string().strip()
== """
╔═══════════╦══════╦═════════╦════════╗
║ Adelaide ║ 1295 ║ 1158259 ║ 600.5 ║
║ Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║ Darwin ║ 112 ║ 120900 ║ 1714.7 ║
║ Hobart ║ 1357 ║ 205556 ║ 619.5 ║
║ Sydney ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9 ║
║ Perth ║ 5386 ║ 1554769 ║ 869.4 ║
╚═══════════╩══════╩═════════╩════════╝""".strip()
)
def test_with_title(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.title = "Title"
assert (
city_data.get_string().strip()
== """
╔═════════════════════════════════════════════════╗
║ Title ║
╠═══════════╦══════╦════════════╦═════════════════╣
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Adelaide ║ 1295 ║ 1158259 ║ 600.5 ║
║ Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║ Darwin ║ 112 ║ 120900 ║ 1714.7 ║
║ Hobart ║ 1357 ║ 205556 ║ 619.5 ║
║ Sydney ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9 ║
║ Perth ║ 5386 ║ 1554769 ║ 869.4 ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
)
def test_with_title_no_header(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.title = "Title"
city_data.header = False
assert (
city_data.get_string().strip()
== """
╔═════════════════════════════════════╗
║ Title ║
╠═══════════╦══════╦═════════╦════════╣
║ Adelaide ║ 1295 ║ 1158259 ║ 600.5 ║
║ Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║ Darwin ║ 112 ║ 120900 ║ 1714.7 ║
║ Hobart ║ 1357 ║ 205556 ║ 619.5 ║
║ Sydney ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9 ║
║ Perth ║ 5386 ║ 1554769 ║ 869.4 ║
╚═══════════╩══════╩═════════╩════════╝""".strip()
)
def test_hrule_all(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.title = "Title"
city_data.hrules = HRuleStyle.ALL
assert (
city_data.get_string().strip()
== """
╔═════════════════════════════════════════════════╗
║ Title ║
╠═══════════╦══════╦════════════╦═════════════════╣
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Adelaide ║ 1295 ║ 1158259 ║ 600.5 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Darwin ║ 112 ║ 120900 ║ 1714.7 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Hobart ║ 1357 ║ 205556 ║ 619.5 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Sydney ║ 2058 ║ 4336374 ║ 1214.8 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9 ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Perth ║ 5386 ║ 1554769 ║ 869.4 ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
)
def test_vrules_none(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.vrules = VRuleStyle.NONE
assert (
city_data.get_string().strip()
== "═══════════════════════════════════════════════════\n"
" City name Area Population Annual Rainfall \n"
"═══════════════════════════════════════════════════\n"
" Adelaide 1295 1158259 600.5 \n"
" Brisbane 5905 1857594 1146.4 \n"
" Darwin 112 120900 1714.7 \n"
" Hobart 1357 205556 619.5 \n"
" Sydney 2058 4336374 1214.8 \n"
" Melbourne 1566 3806092 646.9 \n"
" Perth 5386 1554769 869.4 \n"
"═══════════════════════════════════════════════════".strip()
)
def test_vrules_frame_with_title(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
city_data.vrules = VRuleStyle.FRAME
city_data.title = "Title"
assert (
city_data.get_string().strip()
== """
╔═════════════════════════════════════════════════╗
║ Title ║
╠═════════════════════════════════════════════════╣
║ City name Area Population Annual Rainfall ║
╠═════════════════════════════════════════════════╣
║ Adelaide 1295 1158259 600.5 ║
║ Brisbane 5905 1857594 1146.4 ║
║ Darwin 112 120900 1714.7 ║
║ Hobart 1357 205556 619.5 ║
║ Sydney 2058 4336374 1214.8 ║
║ Melbourne 1566 3806092 646.9 ║
║ Perth 5386 1554769 869.4 ║
╚═════════════════════════════════════════════════╝""".strip()
)
| TestPositionalJunctions |
python | Farama-Foundation__Gymnasium | gymnasium/vector/vector_env.py | {
"start": 22857,
"end": 23645
} | class ____(VectorWrapper):
"""Wraps the vectorized environment to allow a modular transformation of the actions.
Equivalent of :class:`gymnasium.ActionWrapper` for vectorized environments.
"""
def step(
self, actions: ActType
) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, Any]]:
"""Steps through the environment using a modified action by :meth:`action`."""
return self.env.step(self.actions(actions))
def actions(self, actions: ActType) -> ActType:
"""Transform the actions before sending them to the environment.
Args:
actions (ActType): the actions to transform
Returns:
ActType: the transformed actions
"""
raise NotImplementedError
| VectorActionWrapper |
python | protocolbuffers__protobuf | python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py | {
"start": 512,
"end": 4714
} | class ____(Command):
"""Generates Python sources for .proto files."""
description = 'Generate Python sources for .proto files'
user_options = [
('extra-proto-paths=', None,
'Additional paths to resolve imports in .proto files.'),
('protoc=', None,
'Path to a specific `protoc` command to use.'),
]
boolean_options = ['recurse']
def initialize_options(self):
"""Sets the defaults for the command options."""
self.source_dir = None
self.proto_root_path = None
self.extra_proto_paths = []
self.output_dir = '.'
self.proto_files = None
self.recurse = True
self.protoc = None
def finalize_options(self):
"""Sets the final values for the command options.
Defaults were set in `initialize_options`, but could have been changed
by command-line options or by other commands.
"""
self.ensure_dirname('source_dir')
self.ensure_string_list('extra_proto_paths')
if self.output_dir is None:
self.output_dir = '.'
self.ensure_dirname('output_dir')
# SUBTLE: if 'source_dir' is a subdirectory of any entry in
# 'extra_proto_paths', then in general, the shortest --proto_path prefix
# (and the longest relative .proto filenames) must be used for
# correctness. For example, consider:
#
# source_dir = 'a/b/c'
# extra_proto_paths = ['a/b', 'x/y']
#
# In this case, we must ensure that a/b/c/d/foo.proto resolves
# canonically as c/d/foo.proto, not just d/foo.proto. Otherwise, this
# import:
#
# import "c/d/foo.proto";
#
# would result in different FileDescriptor.name keys from "d/foo.proto".
# That will cause all the definitions in the file to be flagged as
# duplicates, with an error similar to:
#
# c/d/foo.proto: "packagename.MessageName" is already defined in file "d/foo.proto"
#
# For paths in self.proto_files, we transform them to be relative to
# self.proto_root_path, which may be different from self.source_dir.
#
# Although the order of --proto_paths is significant, shadowed filenames
# are errors: if 'a/b/c.proto' resolves to different files under two
# different --proto_path arguments, then the path is rejected as an
# error. (Implementation note: this is enforced in protoc's
# DiskSourceTree class.)
if self.proto_root_path is None:
self.proto_root_path = os.path.normpath(self.source_dir)
for root_candidate in self.extra_proto_paths:
root_candidate = os.path.normpath(root_candidate)
if self.proto_root_path.startswith(root_candidate):
self.proto_root_path = root_candidate
if self.proto_root_path != self.source_dir:
self.announce('using computed proto_root_path: ' + self.proto_root_path, level=2)
if not self.source_dir.startswith(self.proto_root_path):
raise OptionError(
'source_dir '
+ self.source_dir
+ ' is not under proto_root_path '
+ self.proto_root_path
)
if self.proto_files is None:
files = glob.glob(os.path.join(self.source_dir, '*.proto'))
if self.recurse:
files.extend(
glob.glob(
os.path.join(self.source_dir, '**', '*.proto'), recursive=True
)
)
self.proto_files = [
f.partition(self.proto_root_path + os.path.sep)[-1] for f in files
]
if not self.proto_files:
raise OptionError('no .proto files were found under ' + self.source_dir)
self.ensure_string_list('proto_files')
if self.protoc is None:
self.protoc = os.getenv('PROTOC')
if self.protoc is None:
self.protoc = shutil.which('protoc')
def run(self):
# All proto file paths were adjusted in finalize_options to be relative
# to self.proto_root_path.
proto_paths = ['--proto_path=' + self.proto_root_path]
proto_paths.extend(['--proto_path=' + x for x in self.extra_proto_paths])
# Run protoc.
subprocess.run(
[
self.protoc,
'--python_out=' + self.output_dir,
]
+ proto_paths
+ self.proto_files
)
| generate_py_protobufs |
python | gabrielfalcao__HTTPretty | tests/functional/test_fakesocket.py | {
"start": 1271,
"end": 2540
} | class ____(socket.socket):
"""
Just an editable socket factory
It allows mock to patch readonly functions
"""
connect = sendall = lambda *args, **kw: None
fake_socket_interupter_flag = {}
def recv(flag, size):
"""
Two pass recv implementation
This implementation will for the first time send something that is smaller than
the asked size passed in argument.
Any further call will just raise RuntimeError
"""
if 'was_here' in flag:
raise RuntimeError('Already sent everything')
else:
flag['was_here'] = None
return 'a' * (size - 1)
recv = functools.partial(recv, fake_socket_interupter_flag)
@mock.patch('httpretty.old_socket', new=FakeSocket)
def _test_shorten_response():
u"HTTPretty shouldn't try to read from server when communication is over"
from sure import expect
import httpretty
fakesocket = httpretty.fakesock.socket(socket.AF_INET,
socket.SOCK_STREAM)
with mock.patch.object(fakesocket.truesock, 'recv', recv):
fakesocket.connect(('localhost', 80))
fakesocket._true_sendall('WHATEVER')
expect(fakesocket.fd.read()).to.equal(
'a' * (httpretty.socket_buffer_size - 1))
| FakeSocket |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/list.py | {
"start": 945,
"end": 4058
} | class ____(BaseTransformOutputParser[list[str]]):
"""Parse the output of a model to a list."""
@property
def _type(self) -> str:
return "list"
@abstractmethod
def parse(self, text: str) -> list[str]:
"""Parse the output of an LLM call.
Args:
text: The output of an LLM call.
Returns:
A list of strings.
"""
def parse_iter(self, text: str) -> Iterator[re.Match]:
"""Parse the output of an LLM call.
Args:
text: The output of an LLM call.
Yields:
A match object for each part of the output.
"""
raise NotImplementedError
@override
def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[list[str]]:
buffer = ""
for chunk in input:
if isinstance(chunk, BaseMessage):
# Extract text
chunk_content = chunk.content
if not isinstance(chunk_content, str):
continue
buffer += chunk_content
else:
# Add current chunk to buffer
buffer += chunk
# Parse buffer into a list of parts
try:
done_idx = 0
# Yield only complete parts
for m in droplastn(self.parse_iter(buffer), 1):
done_idx = m.end()
yield [m.group(1)]
buffer = buffer[done_idx:]
except NotImplementedError:
parts = self.parse(buffer)
# Yield only complete parts
if len(parts) > 1:
for part in parts[:-1]:
yield [part]
buffer = parts[-1]
# Yield the last part
for part in self.parse(buffer):
yield [part]
@override
async def _atransform(
self, input: AsyncIterator[str | BaseMessage]
) -> AsyncIterator[list[str]]:
buffer = ""
async for chunk in input:
if isinstance(chunk, BaseMessage):
# Extract text
chunk_content = chunk.content
if not isinstance(chunk_content, str):
continue
buffer += chunk_content
else:
# Add current chunk to buffer
buffer += chunk
# Parse buffer into a list of parts
try:
done_idx = 0
# Yield only complete parts
for m in droplastn(self.parse_iter(buffer), 1):
done_idx = m.end()
yield [m.group(1)]
buffer = buffer[done_idx:]
except NotImplementedError:
parts = self.parse(buffer)
# Yield only complete parts
if len(parts) > 1:
for part in parts[:-1]:
yield [part]
buffer = parts[-1]
# Yield the last part
for part in self.parse(buffer):
yield [part]
| ListOutputParser |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 34547,
"end": 37548
} | class ____(base_classes.Table):
@property
def show_autofilter(self):
return self.api["show_autofilter"]
@show_autofilter.setter
def show_autofilter(self, value):
self.append_json_action(
func="showAutofilterTable", args=[self.index - 1, value]
)
def __init__(self, parent, key):
self._parent = parent
self._api = self.parent.api["tables"][key - 1]
self.key = key
def append_json_action(self, **kwargs):
self.parent.book.append_json_action(
**{
**kwargs,
**{
"sheet_position": self.parent.index - 1,
},
}
)
@property
def api(self):
return self._api
@property
def parent(self):
return self._parent
@property
def name(self):
return self.api["name"]
@name.setter
def name(self, value):
self.api["name"] = value
self.append_json_action(func="setTableName", args=[self.index - 1, value])
@property
def range(self):
if self.api["range_address"]:
return self.parent.range(self.api["range_address"])
else:
return None
@property
def header_row_range(self):
if self.api["header_row_range_address"]:
return self.parent.range(self.api["header_row_range_address"])
else:
return None
@property
def data_body_range(self):
if self.api["data_body_range_address"]:
return self.parent.range(self.api["data_body_range_address"])
else:
return None
@property
def totals_row_range(self):
if self.api["total_row_range_address"]:
return self.parent.range(self.api["total_row_range_address"])
else:
return None
@property
def show_headers(self):
return self.api["show_headers"]
@show_headers.setter
def show_headers(self, value):
self.append_json_action(func="showHeadersTable", args=[self.index - 1, value])
@property
def show_totals(self):
return self.api["show_totals"]
@show_totals.setter
def show_totals(self, value):
self.append_json_action(func="showTotalsTable", args=[self.index - 1, value])
@property
def table_style(self):
return self.api["table_style"]
@table_style.setter
def table_style(self, value):
self.append_json_action(func="setTableStyle", args=[self.index - 1, value])
@property
def index(self):
# TODO: make available in public API
if isinstance(self.key, numbers.Number):
return self.key
else:
for ix, obj in self.api:
if obj["name"] == self.key:
return ix + 1
raise KeyError(self.key)
def resize(self, range):
self.append_json_action(
func="resizeTable", args=[self.index - 1, range.address]
)
| Table |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/workspace.py | {
"start": 1210,
"end": 5149
} | class ____(IHaveNew, LegacyNamedTupleMixin):
image: Optional[str]
python_file: Optional[str]
package_name: Optional[str]
module_name: Optional[str]
working_directory: Optional[str]
executable_path: Optional[str]
attribute: Optional[str]
git_metadata: Optional[GitMetadata]
container_context: Mapping[str, Any]
cloud_context_env: Mapping[str, Any]
pex_metadata: Optional[PexMetadata]
agent_queue: Optional[AgentQueue]
autoload_defs_module_name: Optional[str]
defs_state_info: Optional[DefsStateInfo]
def __new__(
cls,
image: Optional[str] = None,
python_file: Optional[str] = None,
package_name: Optional[str] = None,
module_name: Optional[str] = None,
working_directory: Optional[str] = None,
executable_path: Optional[str] = None,
attribute: Optional[str] = None,
git_metadata: Optional[GitMetadata] = None,
container_context: Optional[Mapping[str, Any]] = None,
cloud_context_env: Optional[Mapping[str, Any]] = None,
pex_metadata: Optional[PexMetadata] = None,
agent_queue: Optional[AgentQueue] = None,
autoload_defs_module_name: Optional[str] = None,
defs_state_info: Optional[DefsStateInfo] = None,
):
check.invariant(
len(
[
val
for val in [
python_file,
package_name,
module_name,
autoload_defs_module_name,
]
if val
]
)
== 1,
"Must supply exactly one of python_file, package_name, module_name, or autoload_defs_module_name.",
)
return super().__new__(
cls,
image=image,
python_file=python_file,
package_name=package_name,
module_name=module_name,
working_directory=working_directory,
executable_path=executable_path,
attribute=attribute,
git_metadata=git_metadata,
container_context=container_context or {},
cloud_context_env=cloud_context_env or {},
pex_metadata=pex_metadata,
agent_queue=agent_queue,
autoload_defs_module_name=autoload_defs_module_name,
defs_state_info=defs_state_info,
)
def with_cloud_context_env(
self,
cloud_context_env: Mapping[str, Any],
) -> "CodeLocationDeployData":
return copy(self, cloud_context_env=cloud_context_env)
def get_multipex_server_command(
self,
port: Optional[int],
socket: Optional[str] = None,
metrics_enabled: bool = False,
) -> list[str]:
return (
["dagster-cloud", "pex", "grpc", "--host", "0.0.0.0"]
+ (["--port", str(port)] if port else [])
+ (["--socket", str(socket)] if socket else [])
+ (["--enable-metrics"] if metrics_enabled else [])
+ (
["--defs-state-info", serialize_value(self.defs_state_info)]
if self.defs_state_info
else []
)
)
def get_multipex_server_env(self) -> dict[str, str]:
return {"DAGSTER_CURRENT_IMAGE": self.image} if self.image else {}
def get_grpc_server_command(self, metrics_enabled: bool = False) -> list[str]:
return (
([self.executable_path, "-m"] if self.executable_path else [])
+ [
"dagster",
"api",
"grpc",
]
+ (["--enable-metrics"] if metrics_enabled else [])
+ (
["--defs-state-info", serialize_value(self.defs_state_info)]
if self.defs_state_info
else []
)
)
| CodeLocationDeployData |
python | sympy__sympy | sympy/stats/random_matrix_models.py | {
"start": 9682,
"end": 9846
} | class ____(CircularEnsembleModel):
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S.One)
| CircularOrthogonalEnsembleModel |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-everlyai/llama_index/llms/everlyai/base.py | {
"start": 635,
"end": 2880
} | class ____(OpenAI):
"""
EverlyAI LLM.
Examples:
`pip install llama-index-llms-everlyai`
```python
from llama_index.llms.everlyai import EverlyAI
llm = EverlyAI(api_key="your-api-key")
response = llm.complete("Hello World!")
print(response)
```
"""
def __init__(
self,
model: str = DEFAULT_MODEL,
temperature: float = DEFAULT_TEMPERATURE,
max_tokens: int = DEFAULT_NUM_OUTPUTS,
additional_kwargs: Optional[Dict[str, Any]] = None,
max_retries: int = 10,
api_key: Optional[str] = None,
callback_manager: Optional[CallbackManager] = None,
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
completion_to_prompt: Optional[Callable[[str], str]] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
output_parser: Optional[BaseOutputParser] = None,
) -> None:
additional_kwargs = additional_kwargs or {}
callback_manager = callback_manager or CallbackManager([])
api_key = get_from_param_or_env("api_key", api_key, "EverlyAI_API_KEY")
super().__init__(
model=model,
temperature=temperature,
max_tokens=max_tokens,
api_base=EVERLYAI_API_BASE,
api_key=api_key,
additional_kwargs=additional_kwargs,
max_retries=max_retries,
callback_manager=callback_manager,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
output_parser=output_parser,
)
@classmethod
def class_name(cls) -> str:
return "EverlyAI_LLM"
@property
def metadata(self) -> LLMMetadata:
return LLMMetadata(
context_window=everlyai_modelname_to_contextsize(self.model),
num_output=self.max_tokens,
is_chat_model=True,
model_name=self.model,
)
@property
def _is_chat_model(self) -> bool:
return True
| EverlyAI |
python | django__django | tests/staticfiles_tests/test_storage.py | {
"start": 25106,
"end": 26022
} | class ____(CollectionTestCase):
run_collectstatic_in_setUp = False
hashed_file_path = hashed_file_path
def test_protocol_relative_url_ignored(self):
with override_settings(
STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "static_url_slash")],
STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"],
):
self.run_collectstatic()
relpath = self.hashed_file_path("ignored.css")
self.assertEqual(relpath, "ignored.61707f5f4942.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b"//foobar", content)
@override_settings(
STORAGES={
**settings.STORAGES,
STATICFILES_STORAGE_ALIAS: {
"BACKEND": "staticfiles_tests.storage.NoneHashStorage",
},
}
)
| TestCollectionManifestStorageStaticUrlSlash |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 1408,
"end": 1709
} | class ____:
def setup(self):
N = 10**5
B = N + 20000
self.datetime_left = DatetimeIndex(range(N))
self.datetime_right = DatetimeIndex(range(N, B))
def time_datetime_difference_disjoint(self):
self.datetime_left.difference(self.datetime_right)
| SetDisjoint |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 210894,
"end": 213456
} | class ____(ParseElementEnhance):
"""Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` is set to ``True``, the matching tokens are
returned as a single token string, with the delimiters included;
otherwise, the matching tokens are returned as a list of tokens,
with the delimiters suppressed.
If ``allow_trailing_delim`` is set to True, then the list may end with
a delimiter.
Example:
.. doctest::
>>> DelimitedList(Word(alphas)).parse_string("aa,bb,cc")
ParseResults(['aa', 'bb', 'cc'], {})
>>> DelimitedList(Word(hexnums), delim=':', combine=True
... ).parse_string("AA:BB:CC:DD:EE")
ParseResults(['AA:BB:CC:DD:EE'], {})
.. versionadded:: 3.1.0
"""
def __init__(
self,
expr: Union[str, ParserElement],
delim: Union[str, ParserElement] = ",",
combine: bool = False,
min: typing.Optional[int] = None,
max: typing.Optional[int] = None,
*,
allow_trailing_delim: bool = False,
) -> None:
if isinstance(expr, str_type):
expr = ParserElement._literalStringClass(expr)
expr = typing.cast(ParserElement, expr)
if min is not None and min < 1:
raise ValueError("min must be greater than 0")
if max is not None and min is not None and max < min:
raise ValueError("max must be greater than, or equal to min")
self.content = expr
self.raw_delim = str(delim)
self.delim = delim
self.combine = combine
if not combine:
self.delim = Suppress(delim) if not isinstance(delim, Suppress) else delim
self.min = min or 1
self.max = max
self.allow_trailing_delim = allow_trailing_delim
delim_list_expr = self.content + (self.delim + self.content) * (
self.min - 1,
None if self.max is None else self.max - 1,
)
if self.allow_trailing_delim:
delim_list_expr += Opt(self.delim)
if self.combine:
delim_list_expr = Combine(delim_list_expr)
super().__init__(delim_list_expr, savelist=True)
def _generateDefaultName(self) -> str:
content_expr = self.content.streamline()
return f"{content_expr} [{self.raw_delim} {content_expr}]..."
| DelimitedList |
python | django__django | tests/admin_ordering/models.py | {
"start": 698,
"end": 889
} | class ____(admin.ModelAdmin):
def get_ordering(self, request):
if request.user.is_superuser:
return ["rank"]
else:
return ["name"]
| DynOrderingBandAdmin |
python | kamyu104__LeetCode-Solutions | Python/minimum-knight-moves.py | {
"start": 1806,
"end": 2403
} | class ____(object):
def __init__(self):
self.__lookup = {(0, 0):0, (1, 1):2, (1, 0):3} # special cases
def minKnightMoves(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
def dp(x, y):
x, y = abs(x), abs(y)
if x < y:
x, y = y, x
if (x, y) not in self.__lookup: # greedy, smaller x, y is always better if not special cases
self.__lookup[(x, y)] = min(dp(x-1, y-2), dp(x-2, y-1)) + 1
return self.__lookup[(x, y)]
return dp(x, y)
| Solution2 |
python | keras-team__keras | keras/src/ops/linalg_test.py | {
"start": 21097,
"end": 24762
} | class ____(testing.TestCase):
def test_qr_init_mode_reduced(self):
qr_op = linalg.Qr(mode="reduced")
self.assertIsNotNone(qr_op)
def test_qr_init_mode_complete(self):
qr_op = linalg.Qr(mode="complete")
self.assertIsNotNone(qr_op)
def test_qr_init_invalid_mode(self):
invalid_mode = "invalid_mode"
expected_error = (
r"`mode` argument value not supported. "
r"Expected one of \{'reduced', 'complete'\}. "
f"Received: mode={invalid_mode}"
)
with self.assertRaisesRegex(ValueError, expected_error):
linalg.Qr(mode=invalid_mode)
def test_compute_output_spec_low_rank(self):
qr_op = linalg.Qr(mode="reduced")
low_rank_input = np.random.rand(3)
with self.assertRaisesRegex(
ValueError, r"Input should have rank >= 2. Received: .*"
):
qr_op.compute_output_spec(low_rank_input)
def test_compute_output_spec_undefined_dimensions(self):
qr_op = linalg.Qr(mode="reduced")
undefined_dim_input = KerasTensor(shape=(None, 4), dtype="float32")
with self.assertRaisesRegex(
ValueError,
r"Input should have its last 2 dimensions "
r"fully-defined. Received: .*",
):
qr_op.compute_output_spec(undefined_dim_input)
def test_qr_call_mode_reduced(self):
qr_op = linalg.Qr(mode="reduced")
test_input = np.random.rand(10, 10)
q, r = qr_op.call(test_input)
self.assertEqual(q.shape, (10, 10))
self.assertEqual(r.shape, (10, 10))
def test_qr_call_mode_complete(self):
qr_op = linalg.Qr(mode="complete")
test_input = np.random.rand(10, 10)
q, r = qr_op.call(test_input)
self.assertEqual(q.shape, (10, 10))
self.assertEqual(r.shape, (10, 10))
def test_jvp(self):
if backend.backend() in ["openvino", "numpy"]:
pytest.skip("Backend does not support jvp operation")
a1, a2 = ops.convert_to_tensor(0.1), ops.convert_to_tensor(0.2)
primals, tangents = linalg.jvp(backend.numpy.sin, (a1,), (a2,))
self.assertAllClose(primals, 0.0998, atol=1e-4)
self.assertAllClose(tangents, 0.1990, atol=1e-4)
def f(x):
return backend.numpy.sin(x), x**2
primals_out, tangents_out, aux = linalg.jvp(
f, (a1,), (a2,), has_aux=True
)
self.assertAllClose(primals_out, 0.0998, atol=1e-4)
self.assertAllClose(tangents_out, 0.1990, atol=1e-4)
self.assertAllClose(aux, 0.01, atol=1e-4)
def test_jvp_symbolic_has_aux_false(self):
primals = KerasTensor((None, 7))
tangents = KerasTensor((None, 7))
def fun(x):
# simple non-linear transformation
return ops.sin(x) + ops.cos(x)
primals_out, tangents_out = linalg.jvp(fun, (primals,), (tangents,))
# output shapes must match input shapes
self.assertEqual(primals_out.shape, primals.shape)
self.assertEqual(tangents_out.shape, tangents.shape)
"""Symbolic JVP test – has_aux=True."""
def fun(x):
y = ops.exp(x)
aux = ops.mean(y, axis=-1, keepdims=True) # auxiliary output
return y, aux
primals_out, tangents_out, aux = linalg.jvp(
fun, (primals,), (tangents,), has_aux=True
)
# main output shapes
self.assertEqual(primals_out.shape, primals.shape)
self.assertEqual(tangents_out.shape, tangents.shape)
# auxiliary shape: (batch, 1)
self.assertEqual(aux.shape, (None, 1))
| QrOpTest |
python | getsentry__sentry-python | sentry_sdk/crons/consts.py | {
"start": 0,
"end": 87
} | class ____:
IN_PROGRESS = "in_progress"
OK = "ok"
ERROR = "error"
| MonitorStatus |
python | Textualize__textual | tests/text_area/test_setting_themes.py | {
"start": 205,
"end": 1561
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield TextArea("print('hello')", language="python")
async def test_default_theme():
app = TextAreaApp()
async with app.run_test():
text_area = app.query_one(TextArea)
assert text_area.theme is "css"
async def test_setting_builtin_themes():
class MyTextAreaApp(App[None]):
def compose(self) -> ComposeResult:
yield TextArea("print('hello')", language="python", theme="vscode_dark")
app = MyTextAreaApp()
async with app.run_test():
text_area = app.query_one(TextArea)
assert text_area.theme == "vscode_dark"
text_area.theme = "monokai"
assert text_area.theme == "monokai"
async def test_setting_unknown_theme_raises_exception():
app = TextAreaApp()
async with app.run_test():
text_area = app.query_one(TextArea)
with pytest.raises(ThemeDoesNotExist):
text_area.theme = "this-theme-doesnt-exist"
async def test_registering_and_setting_theme():
app = TextAreaApp()
async with app.run_test():
text_area = app.query_one(TextArea)
text_area.register_theme(TextAreaTheme("my-theme"))
assert "my-theme" in text_area.available_themes
text_area.theme = "my-theme"
assert text_area.theme == "my-theme"
| TextAreaApp |
python | tiangolo__fastapi | scripts/sponsors.py | {
"start": 1396,
"end": 1460
} | class ____(BaseModel):
user: SponsorsUser
| SponsorsResponseData |
python | astropy__astropy | astropy/table/tests/test_masked.py | {
"start": 14656,
"end": 15111
} | class ____:
def test_rename_masked_column(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name="a", data=[1, 2, 3], mask=[0, 1, 0]))
t["a"].fill_value = 42
t.rename_column("a", "b")
assert t.masked
assert np.all(t["b"] == np.array([1, 2, 3]))
assert np.all(t["b"].mask == np.array([0, 1, 0], bool))
assert t["b"].fill_value == 42
assert t.colnames == ["b"]
| TestRenameColumn |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 12460,
"end": 12618
} | class ____(Module):
def extra_repr(self) -> str:
return f"kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}"
| _MaxUnpoolNd |
python | pytorch__pytorch | torch/_subclasses/functional_tensor.py | {
"start": 14285,
"end": 31991
} | class ____(TorchDispatchMode):
def __init__(self, pre_dispatch=False, export=False, _allow_token_discovery=False):
super().__init__()
self.export = export
self.is_on_stack = False
self.enter_stack = []
# Indicates to our torch_dispatch dispatching infra that
# this is an "infra" mode with lower dispatching precedence.
self._mode_key = torch._C._TorchDispatchModeKey.FUNCTIONAL
self.pre_dispatch = pre_dispatch
# This will be turned off later for pre-dispatch functionalization
self._dispatch_key = torch._C.DispatchKey.PreDispatch if pre_dispatch else None # type: ignore[attr-defined]
# Map of effect type (ex. _EffectType.ORDERED) to a token. The tokens help keep
# track of the ordering between side effectful operations.
self._tokens: dict[Any, torch.Tensor] = {}
# Filled after forward tracing.
self._tokens_forward_output: dict[Any, torch.Tensor] = {}
# Functionalization runs twice in AOTAutograd, once in
# `run_functionalized_fw_and_collect_metadata` to collect metadata to
# see which tensors need to be functionalized and discover how many
# tokens we need, and another time in `make_fx` which does the actual
# tracing to replace ops with their functional variants and handling
# side-effectful ops. In the second stage there should be no token
# discovery. This flag distinguishes between the two stages.
self._allow_token_discovery = _allow_token_discovery
self._storage_to_base: weakref.WeakKeyDictionary[
torch.storage.UntypedStorage, Optional[FunctionalTensor]
] = weakref.WeakKeyDictionary()
# No-op if FunctionalTensorMode is already in use
def __enter__(self):
def _get_prev_mode():
if self._dispatch_key == torch._C.DispatchKey.PreDispatch:
return _get_dispatch_mode_pre_dispatch(
torch._C._TorchDispatchModeKey.FUNCTIONAL
)
return torch._C._get_dispatch_mode(
torch._C._TorchDispatchModeKey.FUNCTIONAL
)
if _get_prev_mode() is None:
self.enter_stack.append(True)
return super().__enter__()
else:
self.enter_stack.append(False)
return self
def __exit__(self, a, b, c):
is_on_stack = self.enter_stack.pop()
if is_on_stack:
super().__exit__(a, b, c)
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
unrecognized_types = [
t
for t in types
if not issubclass(t, torch._subclasses.FakeTensor)
and t not in [torch.Tensor, FunctionalTensor]
]
if unrecognized_types:
not_implemented_log.debug(
"FunctionalTensor unrecognized subclass(es): %s", unrecognized_types
)
return NotImplemented
def _can_decompose(func):
# See https://github.com/pytorch/pytorch/pull/115258#issuecomment-1900755832
# Never decompose dropout in export
if self.export and func is torch.ops.aten.dropout.default:
return False
# We unconditionally decompose ops that are maybe aliasing or mutating ops
from torch._decomp import _should_decompose_because_unsafe_op
if _should_decompose_because_unsafe_op(func):
return True
# (1) we unconditionally decompose maybe-aliasing or maybe-mutating ops,
# because we must know statically of an op mutates or aliasing in order to functionalize it properly
# (2) for mutating ops that have CompositeImplicit decomps, we choose to decompose them today.
# In theory, we could walk this back and avoid decomposing them later if we need to.
alias_info_present = any(arg.alias_info for arg in func._schema.arguments)
if alias_info_present or func._schema.is_mutable:
return True
# If we are here, it means we are seeing functional composite op.
# For pre-dispatch IR, we don't want to decompose this op
# For post-dispatch IR, we do want to decompose this op. it is fine
# to decompose here even if you want to preserve a CIA in post-dispatch export
# because we already override decompose behaviour so it will do the
# right thing.
if self.export:
if self.pre_dispatch:
# If it is CIA custom op, we warn that we are assuming this op is indeed functional.
if func.namespace not in ["aten", "prim"] and func._can_decompose():
warnings.warn(
f"At pre-dispatch tracing, we assume that any custom op marked with "
f"CompositeImplicitAutograd and have functional schema are safe to not decompose. "
f"Found {func} to be one such op.",
stacklevel=2,
)
return False
return True
# in normal torch.compile IR, we only decompose an op if autograd
# would have decomposed it (NB: autograd may have been skipped if
# we are in inference mode)
# TODO: the flatten here can potentially be deduped with the
# unwrapping pytree_map later
flat_args_kwargs, _ = pytree.tree_flatten((args, kwargs))
return autograd_would_have_decomposed(func, flat_args_kwargs)
if (
func not in FunctionalTensor.metadata_fns
and _can_decompose(func)
# Not all funcs from __torch_dispatch__ are actual dispatcher ops,
# e.g. prim.device
and torch._C._dispatch_has_kernel(func.name())
):
with self:
r = func.decompose(*args, **kwargs)
if r is not NotImplemented:
return r
def wrap(x):
# Only wrap our outputs in subclasses if the inner functionalization call
# also wrapped outputs into FunctionalTensorWrappers.
# When can this happen? e.g. `torch.div(2, 2)`
assert not isinstance(x, FunctionalTensor)
if isinstance(x, torch.Tensor) and torch._is_functional_tensor(x):
return FunctionalTensor(x, self)
return x
def unwrap(x):
return x.elem
from torch._higher_order_ops.auto_functionalize import (
can_auto_functionalize,
do_auto_functionalize,
do_auto_functionalize_v2,
)
if can_auto_functionalize(
func
) and not torch._C._dispatch_has_kernel_for_dispatch_key(
func.name(), torch._C.DispatchKey.Functionalize
):
import torch._export.config as export_config
import torch._inductor.config as inductor_config
if torch.compiler.is_exporting():
if export_config.enable_auto_functionalized_v2_for_export:
return do_auto_functionalize_v2(self, func, args, kwargs)
return do_auto_functionalize(self, func, args, kwargs)
if inductor_config.enable_auto_functionalized_v2:
return do_auto_functionalize_v2(self, func, args, kwargs)
return do_auto_functionalize(self, func, args, kwargs)
from torch._higher_order_ops.effects import handle_effects, has_effects
if has_effects(func):
assert not torch._C._dispatch_has_kernel_for_dispatch_key(
func.name(), torch._C.DispatchKey.Functionalize
)
return handle_effects(
self._allow_token_discovery, self._tokens, func, args, kwargs
)
args_unwrapped, kwargs_unwrapped = pytree.tree_map_only(
FunctionalTensor, unwrap, (args, kwargs)
)
# Expectation: functionalization should not **already** be enabled above our mode.
# Why would that be bad? when we return a FunctionalTensor here, we don't want functionalization
# to run above this mode and further wrap that output in **another** C++ FunctionalTensorWrapper.
is_included = torch._C._dispatch_tls_is_dispatch_key_included(
torch._C.DispatchKey.Functionalize
)
is_excluded = torch._C._dispatch_tls_is_dispatch_key_excluded(
torch._C.DispatchKey.Functionalize
)
assert is_excluded or not is_included
include_to_set = (
torch._C._dispatch_tls_local_include_set()
| torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
)
exclude_to_set = (
torch._C._dispatch_tls_local_exclude_set().remove(
torch._C.DispatchKey.Functionalize
)
- FunctionalTensor._extra_dispatch_keys
)
if isinstance(func, TorchBindOpOverload):
# When the function is a TorchBindOpOverload, meaning some of the
# inputs are FakeScriptObjects, we need to skip c++ dispatcher and
# dispatch in python because C++ dispatcher will check the schema
# and cannot recognize FakeScriptObject.
ctx = PythonFunctionalizeAPI()
fully_unwrapped_args = ctx.unwrap_tensors(args)
fully_unwrapped_kwargs = ctx.unwrap_tensors(
kwargs # pyrefly: ignore[bad-argument-type]
)
outs_unwrapped = func(
*fully_unwrapped_args,
**fully_unwrapped_kwargs,
)
outs_wrapped = ctx.wrap_tensors(outs_unwrapped)
else:
# All we want to do here is reuse the existing C++ functionalization logic.
# This requires swizzling our TLS dispatch keys so that the Functionalize key is active.
with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set):
try:
# By default for python functionalization (for AOTAutograd), we reapply views.
old_apply_views = torch._functionalize_enable_reapply_views(True) # type: ignore[attr-defined]
# Sometimes these functions cannot be directly dispatched to functionalize key
# because args are sometimes not functional tensors for some reason?
if func in FunctionalTensor.metadata_fns:
outs_unwrapped = func(*args_unwrapped, **kwargs_unwrapped)
outs_wrapped = pytree.tree_map_only(
torch.Tensor, wrap, outs_unwrapped
)
else:
# Note: [Functionalization View Replay Annotation]
# When functionalization encounters a mutation, it handles aliases by lazily regenerating the aliases
# at the first time they are next used.
# This is a problem when plumbing user annotations during tracing. We want the view ops from view replay
# to have the same annotation that the user specified on the original views. But view replay in
# functionalization happens the next time the alias is used (e.g. second_op(alias_with_pending_mutation)),
# so when we regenerate views before calling into second_op, those views will end up getting the metadata
# for second_op!
#
# Instead, we need to remember the node metadata from the original views, and ensure that this node metadata
# is globally set when we lazily perform view replay.
# The globally set metadata will be used to populate the fx node created for the replayed operation.
if m := torch._C._get_dispatch_mode(
torch._C._TorchDispatchModeKey.PROXY
):
for a in pytree.tree_leaves([args, kwargs]):
if not isinstance(a, FunctionalTensor):
continue
curr_node = m.tracer.tensor_tracker[
torch._from_functional_tensor(a.elem)
].proxy.node
with fx_traceback.set_current_replay_node(curr_node):
torch._sync(a)
# When we dispatch to the C++ functionalization kernel, we might need to jump back to the
# PreDispatch mode stack afterwards, to handle any other PreDispatch modes underneath
# FunctionalTensorMode. If we call func() directly, we would need to exclude PreDispatch
# from the TLS in order to avoid infinite looping, but this would prevent us from coming
# back to PreDispatch later
outs_unwrapped = func._op_dk(
torch._C.DispatchKey.Functionalize,
*args_unwrapped,
**kwargs_unwrapped,
)
if self.export:
if func is torch.ops.aten.dropout.default:
torch._freeze_functional_tensor(outs_unwrapped) # type: ignore[attr-defined]
outs_wrapped = pytree.tree_map_only(
torch.Tensor, wrap, outs_unwrapped
)
finally:
torch._disable_functionalization()
torch._functionalize_enable_reapply_views(old_apply_views) # type: ignore[attr-defined]
is_included = torch._C._dispatch_tls_is_dispatch_key_included(
torch._C.DispatchKey.Functionalize
)
is_excluded = torch._C._dispatch_tls_is_dispatch_key_excluded(
torch._C.DispatchKey.Functionalize
)
assert is_excluded or not is_included
if (
# If no outputs are our functional subclass, then don't try to fix up aliasing
not any(
isinstance(x, FunctionalTensor)
for x in pytree.tree_leaves(outs_wrapped)
)
# Since lift_fresh lifts its argument into a functional tensor, we can skip the
# aliasing correction step. Otherwise, we would be setting the storage of a
# lifted tensor to that of an unlifted tensor.
# Ref: https://github.com/pytorch/pytorch/issues/111506
or func is torch.ops.aten.lift_fresh.default
):
return outs_wrapped
# for metadata mutations, need to manually mutate the metadata of the FunctionalTensor wrapper
if (
torch.Tag.inplace_view in func.tags
and func is not torch.ops.aten.set_.source_Tensor
):
with torch.utils._mode_utils.no_dispatch():
func(*args, **kwargs)
# Wrapper tensor subclasses do not have correct aliasing info! Use this util to manually correct the output aliasing.
# inplace ops like `aten.add_()` are expected to return inputs **directly**, instead of creating fresh tensor objects.
# Use this util to figure out the right thing to return.
# If none of our inputs were wrapped, then we have no FunctionalTensor outputs that we need to fix up storages for.
return return_and_correct_aliasing(func, args, kwargs, outs_wrapped)
@classmethod
def is_infra_mode(cls) -> bool:
return True
@contextlib.contextmanager
def disable_functional_mode():
return _disable_infra_mode(torch._C._TorchDispatchModeKey.FUNCTIONAL)
# This is similar to torch.func.functionalize, but:
# - It uses FunctionalTensorMode, and FunctionalTensor (a python subclass).
# One important advantage to using this mode is that it will let us
# run functionalization underneath __torch_dispatch__,
# which we need in AOTAutograd.
# - Doing so means that it does not automatically compose with other
# functorch transforms, since these transforms always run above __torch_dispatch__.
# That's why this util lives here, and not in functorch.
def dispatch_functionalize(func, mode: FunctionalTensorMode = FunctionalTensorMode()):
# TODO: pull these from aot autograd
def to_fun(t):
if isinstance(t, torch.Tensor):
return FunctionalTensor.to_functional(t)
return t
def from_fun(t):
if not isinstance(t, FunctionalTensor):
# quick sanity assert
if isinstance(t, torch.Tensor):
assert not torch._is_functional_tensor(t)
return t
torch._sync(t)
return torch._from_functional_tensor(t.elem)
def inner(*args, **kwargs):
disable_above = torch._C._ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
)
with disable_above, mode:
func_args = pytree.tree_map_only(torch.Tensor, to_fun, args)
func_kwargs = pytree.tree_map_only(torch.Tensor, to_fun, kwargs)
func_outputs = func(*func_args, **func_kwargs)
outputs = pytree.tree_map_only(FunctionalTensor, from_fun, func_outputs)
return outputs
return inner
| FunctionalTensorMode |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/attributes/duplicates_9267.py | {
"start": 123,
"end": 260
} | class ____:
def __init__(self) -> None:
self.a_obj = A()
def func(self):
self.a_obj = A()
self.a_obj = A()
| B |
python | django-extensions__django-extensions | django_extensions/mongodb/fields/__init__.py | {
"start": 434,
"end": 1022
} | class ____(StringField):
description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
kwargs["max_length"] = kwargs.get("max_length", 50)
# Set db_index=True unless it's been set manually.
if "db_index" not in kwargs:
kwargs["db_index"] = True
super().__init__(*args, **kwargs)
def get_internal_type(self):
return "SlugField"
def formfield(self, **kwargs):
defaults = {"form_class": forms.SlugField}
defaults.update(kwargs)
return super().formfield(**defaults)
| SlugField |
python | sympy__sympy | sympy/polys/agca/modules.py | {
"start": 42821,
"end": 47240
} | class ____(Module):
"""
Class for quotient modules.
Do not instantiate this directly. For subquotients, see the
SubQuotientModule class.
Attributes:
- base - the base module we are a quotient of
- killed_module - the submodule used to form the quotient
- rank of the base
"""
dtype = QuotientModuleElement
def __init__(self, ring, base, submodule):
Module.__init__(self, ring)
if not base.is_submodule(submodule):
raise ValueError('%s is not a submodule of %s' % (submodule, base))
self.base = base
self.killed_module = submodule
self.rank = base.rank
def __repr__(self):
return repr(self.base) + "/" + repr(self.killed_module)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
This happens if and only if the base module is the same as the
submodule being killed.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> (F/[(1, 0)]).is_zero()
False
>>> (F/[(1, 0), (0, 1)]).is_zero()
True
"""
return self.base == self.killed_module
def is_submodule(self, other):
"""
Return True if ``other`` is a submodule of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False
"""
if isinstance(other, QuotientModule):
return self.killed_module == other.killed_module and \
self.base.is_submodule(other.base)
if isinstance(other, SubQuotientModule):
return other.container == self
return False
def submodule(self, *gens, **opts):
"""
Generate a submodule.
This is the same as taking a quotient of a submodule of the base
module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> Q.submodule([x, 0])
<[x, 0] + <[x, x]>>
"""
return SubQuotientModule(gens, self, **opts)
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> F.convert([1, 0])
[1, 0] + <[1, 2], [1, x]>
"""
if isinstance(elem, QuotientModuleElement):
if elem.module is self:
return elem
if self.killed_module.is_submodule(elem.module.killed_module):
return QuotientModuleElement(self, self.base.convert(elem.data))
raise CoercionFailed
return QuotientModuleElement(self, self.base.convert(elem))
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.identity_hom()
Matrix([
[1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module).quotient_domain(self.killed_module)
def quotient_hom(self):
"""
Return the quotient homomorphism to ``self``.
That is, return a homomorphism representing the natural map from
``self.base`` to ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.quotient_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module)
| QuotientModule |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/inset_locator.py | {
"start": 6311,
"end": 17874
} | class ____(BboxConnector):
@_docstring.interpd
def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs):
"""
Connect two bboxes with a quadrilateral.
The quadrilateral is specified by two lines that start and end at
corners of the bboxes. The four sides of the quadrilateral are defined
by the two lines given, the line between the two corners specified in
*bbox1* and the line between the two corners specified in *bbox2*.
Parameters
----------
bbox1, bbox2 : `~matplotlib.transforms.Bbox`
Bounding boxes to connect.
loc1a, loc2a, loc1b, loc2b : {1, 2, 3, 4}
The first line connects corners *loc1a* of *bbox1* and *loc2a* of
*bbox2*; the second line connects corners *loc1b* of *bbox1* and
*loc2b* of *bbox2*. Valid values are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4
**kwargs
Patch properties for the line drawn:
%(Patch:kwdoc)s
"""
if "transform" in kwargs:
raise ValueError("transform should not be set")
super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs)
self.loc1b = loc1b
self.loc2b = loc2b
def get_path(self):
# docstring inherited
path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2)
path2 = self.connect_bbox(self.bbox2, self.bbox1,
self.loc2b, self.loc1b)
path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]]
return Path(path_merged)
def _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator):
"""Helper function to add an inset axes and disable navigation in it."""
if axes_class is None:
axes_class = HostAxes
if axes_kwargs is None:
axes_kwargs = {}
fig = parent_axes.get_figure(root=False)
inset_axes = axes_class(
fig, parent_axes.get_position(),
**{"navigate": False, **axes_kwargs, "axes_locator": axes_locator})
return fig.add_axes(inset_axes)
@_docstring.interpd
def inset_axes(parent_axes, width, height, loc='upper right',
bbox_to_anchor=None, bbox_transform=None,
axes_class=None, axes_kwargs=None,
borderpad=0.5):
"""
Create an inset axes with a given width and height.
Both sizes used can be specified either in inches or percentage.
For example,::
inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left')
creates in inset axes in the lower left corner of *parent_axes* which spans
over 30%% in height and 40%% in width of the *parent_axes*. Since the usage
of `.inset_axes` may become slightly tricky when exceeding such standard
cases, it is recommended to read :doc:`the examples
</gallery/axes_grid1/inset_locator_demo>`.
Notes
-----
The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted
differently from that of legend. The value of bbox_to_anchor
(or the return value of its get_points method; the default is
*parent_axes.bbox*) is transformed by the bbox_transform (the default
is Identity transform) and then interpreted as points in the pixel
coordinate (which is dpi dependent).
Thus, following three calls are identical and creates an inset axes
with respect to the *parent_axes*::
axins = inset_axes(parent_axes, "30%%", "40%%")
axins = inset_axes(parent_axes, "30%%", "40%%",
bbox_to_anchor=parent_axes.bbox)
axins = inset_axes(parent_axes, "30%%", "40%%",
bbox_to_anchor=(0, 0, 1, 1),
bbox_transform=parent_axes.transAxes)
Parameters
----------
parent_axes : `matplotlib.axes.Axes`
Axes to place the inset axes.
width, height : float or str
Size of the inset axes to create. If a float is provided, it is
the size in inches, e.g. *width=1.3*. If a string is provided, it is
the size in relative units, e.g. *width='40%%'*. By default, i.e. if
neither *bbox_to_anchor* nor *bbox_transform* are specified, those
are relative to the parent_axes. Otherwise, they are to be understood
relative to the bounding box provided via *bbox_to_anchor*.
loc : str, default: 'upper right'
Location to place the inset axes. Valid locations are
'upper left', 'upper center', 'upper right',
'center left', 'center', 'center right',
'lower left', 'lower center', 'lower right'.
For backward compatibility, numeric values are accepted as well.
See the parameter *loc* of `.Legend` for details.
bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
Bbox that the inset axes will be anchored to. If None,
a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set
to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.
Otherwise, *parent_axes.bbox* is used. If a tuple, can be either
[left, bottom, width, height], or [left, bottom].
If the kwargs *width* and/or *height* are specified in relative units,
the 2-tuple [left, bottom] cannot be used. Note that,
unless *bbox_transform* is set, the units of the bounding box
are interpreted in the pixel coordinate. When using *bbox_to_anchor*
with tuple, it almost always makes sense to also specify
a *bbox_transform*. This might often be the axes transform
*parent_axes.transAxes*.
bbox_transform : `~matplotlib.transforms.Transform`, optional
Transformation for the bbox that contains the inset axes.
If None, a `.transforms.IdentityTransform` is used. The value
of *bbox_to_anchor* (or the return value of its get_points method)
is transformed by the *bbox_transform* and then interpreted
as points in the pixel coordinate (which is dpi dependent).
You may provide *bbox_to_anchor* in some normalized coordinate,
and give an appropriate transform (e.g., *parent_axes.transAxes*).
axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
The type of the newly created inset axes.
axes_kwargs : dict, optional
Keyword arguments to pass to the constructor of the inset axes.
Valid arguments include:
%(Axes:kwdoc)s
borderpad : float or (float, float), default: 0.5
Padding between inset axes and the bbox_to_anchor.
If a float, the same padding is used for both x and y.
If a tuple of two floats, it specifies the (x, y) padding.
The units are axes font size, i.e. for a default font size of 10 points
*borderpad = 0.5* is equivalent to a padding of 5 points.
.. versionadded:: 3.11
The *borderpad* parameter now accepts a tuple of (x, y) paddings.
Returns
-------
inset_axes : *axes_class*
Inset axes object created.
"""
if (bbox_transform in [parent_axes.transAxes,
parent_axes.get_figure(root=False).transFigure]
and bbox_to_anchor is None):
_api.warn_external("Using the axes or figure transform requires a "
"bounding box in the respective coordinates. "
"Using bbox_to_anchor=(0, 0, 1, 1) now.")
bbox_to_anchor = (0, 0, 1, 1)
if bbox_to_anchor is None:
bbox_to_anchor = parent_axes.bbox
if (isinstance(bbox_to_anchor, tuple) and
(isinstance(width, str) or isinstance(height, str))):
if len(bbox_to_anchor) != 4:
raise ValueError("Using relative units for width or height "
"requires to provide a 4-tuple or a "
"`Bbox` instance to `bbox_to_anchor.")
return _add_inset_axes(
parent_axes, axes_class, axes_kwargs,
AnchoredSizeLocator(
bbox_to_anchor, width, height, loc=loc,
bbox_transform=bbox_transform, borderpad=borderpad))
@_docstring.interpd
def zoomed_inset_axes(parent_axes, zoom, loc='upper right',
bbox_to_anchor=None, bbox_transform=None,
axes_class=None, axes_kwargs=None,
borderpad=0.5):
"""
Create an anchored inset axes by scaling a parent axes. For usage, also see
:doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`.
Parameters
----------
parent_axes : `~matplotlib.axes.Axes`
Axes to place the inset axes.
zoom : float
Scaling factor of the data axes. *zoom* > 1 will enlarge the
coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the
coordinates (i.e., "zoomed out").
loc : str, default: 'upper right'
Location to place the inset axes. Valid locations are
'upper left', 'upper center', 'upper right',
'center left', 'center', 'center right',
'lower left', 'lower center', 'lower right'.
For backward compatibility, numeric values are accepted as well.
See the parameter *loc* of `.Legend` for details.
bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
Bbox that the inset axes will be anchored to. If None,
*parent_axes.bbox* is used. If a tuple, can be either
[left, bottom, width, height], or [left, bottom].
If the kwargs *width* and/or *height* are specified in relative units,
the 2-tuple [left, bottom] cannot be used. Note that
the units of the bounding box are determined through the transform
in use. When using *bbox_to_anchor* it almost always makes sense to
also specify a *bbox_transform*. This might often be the axes transform
*parent_axes.transAxes*.
bbox_transform : `~matplotlib.transforms.Transform`, optional
Transformation for the bbox that contains the inset axes.
If None, a `.transforms.IdentityTransform` is used (i.e. pixel
coordinates). This is useful when not providing any argument to
*bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes
sense to also specify a *bbox_transform*. This might often be the
axes transform *parent_axes.transAxes*. Inversely, when specifying
the axes- or figure-transform here, be aware that not specifying
*bbox_to_anchor* will use *parent_axes.bbox*, the units of which are
in display (pixel) coordinates.
axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
The type of the newly created inset axes.
axes_kwargs : dict, optional
Keyword arguments to pass to the constructor of the inset axes.
Valid arguments include:
%(Axes:kwdoc)s
borderpad : float, default: 0.5
Padding between inset axes and the bbox_to_anchor.
The units are axes font size, i.e. for a default font size of 10 points
*borderpad = 0.5* is equivalent to a padding of 5 points.
Returns
-------
inset_axes : *axes_class*
Inset axes object created.
"""
return _add_inset_axes(
parent_axes, axes_class, axes_kwargs,
AnchoredZoomLocator(
parent_axes, zoom=zoom, loc=loc,
bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform,
borderpad=borderpad))
| BboxConnectorPatch |
python | doocs__leetcode | solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def minInsertions(self, s: str) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= j:
return 0
if s[i] == s[j]:
return dfs(i + 1, j - 1)
return 1 + min(dfs(i + 1, j), dfs(i, j - 1))
return dfs(0, len(s) - 1)
| Solution |
python | simonw__datasette | tests/test_api.py | {
"start": 41798,
"end": 41960
} | class ____:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return other == self.a or other == self.b
| Either |
python | readthedocs__readthedocs.org | readthedocs/api/v3/tests/test_remoterepositories.py | {
"start": 422,
"end": 3899
} | class ____(APIEndpointMixin):
def setUp(self):
super().setUp()
self.remote_organization = fixture.get(
RemoteOrganization,
created=self.created,
modified=self.modified,
avatar_url="https://avatars.githubusercontent.com/u/366329?v=4",
name="Read the Docs",
slug="readthedocs",
url="https://github.com/readthedocs",
vcs_provider=GITHUB,
)
self.remote_repository = fixture.get(
RemoteRepository,
organization=self.remote_organization,
created=self.created,
modified=self.modified,
avatar_url="https://avatars3.githubusercontent.com/u/test-rtd?v=4",
clone_url="https://github.com/rtd/project.git",
description="This is a test project.",
full_name="rtd/project",
html_url="https://github.com/rtd/project",
name="project",
ssh_url="git@github.com:rtd/project.git",
vcs=REPO_TYPE_GIT,
vcs_provider=GITHUB,
default_branch="master",
private=False,
)
self.remote_repository.projects.add(self.project)
social_account = fixture.get(SocialAccount, user=self.me, provider=GITHUB)
fixture.get(
RemoteRepositoryRelation,
remote_repository=self.remote_repository,
user=self.me,
account=social_account,
admin=True,
)
fixture.get(
RemoteOrganizationRelation,
remote_organization=self.remote_organization,
user=self.me,
account=social_account,
)
def test_remote_repository_list(self):
url = reverse("remoterepositories-list")
data = {"expand": ["remote_organization"]}
self.client.logout()
response = self.client.get(url, data)
self.assertEqual(response.status_code, 401)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.get(url, data)
self.assertEqual(response.status_code, 200)
self.assertDictEqual(
response.json(),
self._get_response_dict("remoterepositories-list"),
)
def test_remote_repository_list_name_filter(self):
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.get(
reverse("remoterepositories-list"),
{"expand": ["remote_organization"], "name": "proj"},
)
self.assertEqual(response.status_code, 200)
response_data = response.json()
self.assertEqual(len(response_data["results"]), 1)
self.assertDictEqual(
response_data,
self._get_response_dict("remoterepositories-list"),
)
def test_remote_repository_list_full_name_filter(self):
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
response = self.client.get(
reverse("remoterepositories-list"),
{"expand": ["remote_organization"], "full_name": "proj"},
)
self.assertEqual(response.status_code, 200)
response_data = response.json()
self.assertEqual(len(response_data["results"]), 1)
self.assertDictEqual(
response_data,
self._get_response_dict("remoterepositories-list"),
)
| RemoteRepositoryEndpointTests |
python | matplotlib__matplotlib | lib/matplotlib/container.py | {
"start": 6919,
"end": 8132
} | class ____(Container):
"""
Container for the artists created in a :meth:`.Axes.stem` plot.
The container can be treated like a namedtuple ``(markerline, stemlines,
baseline)``.
Attributes
----------
markerline : `~matplotlib.lines.Line2D`
The artist of the markers at the stem heads.
stemlines : `~matplotlib.collections.LineCollection`
The artists of the vertical lines for all stems.
baseline : `~matplotlib.lines.Line2D`
The artist of the horizontal baseline.
"""
def __init__(self, markerline_stemlines_baseline, **kwargs):
"""
Parameters
----------
markerline_stemlines_baseline : tuple
Tuple of ``(markerline, stemlines, baseline)``.
``markerline`` contains the `.Line2D` of the markers,
``stemlines`` is a `.LineCollection` of the main lines,
``baseline`` is the `.Line2D` of the baseline.
"""
markerline, stemlines, baseline = markerline_stemlines_baseline
self.markerline = markerline
self.stemlines = stemlines
self.baseline = baseline
super().__init__(markerline_stemlines_baseline, **kwargs)
| StemContainer |
python | joke2k__faker | faker/providers/job/fa_IR/__init__.py | {
"start": 42,
"end": 1821
} | class ____(BaseProvider):
jobs = [
"هنرپیشه",
"ناخدا",
"بخشدار",
"خیاط",
"گلهدار",
"باغدار",
"مؤذن",
"ساربان",
"آشپز",
"دندانپزشک",
"نجار",
"چوپان",
"خانهدار",
"شورا",
"نویسنده",
"گارسون",
"استاد",
"فروشنده",
"شیشهساز",
"مدیر",
"نقاش ساختمان",
"قایقران",
"رفتگر",
"وزیر",
"خلبان",
"آرایشگر",
"روحانی",
"متخصص",
"فوتبالیست",
"قصاب",
"ساعتساز",
"بقال",
"تلفنچی",
"تاجر",
"عینکساز",
"خوشنویس",
"جنگلبان",
"معلم",
"مهندس",
"راننده",
"آذین گر",
"نظامی",
"نانوا",
"فرماندار",
"دانشآموز",
"دانشجو",
"تعمیرکار",
"کشاورز",
"هنرمند",
"معاون",
"بانکدار",
"آهنگر",
"رئیس",
"سرتیپ",
"سرایدار",
"کارمند",
"مربی",
"سرهنگ",
"غواص",
"پزشک",
"دربان",
"آتشنشان",
"ماهیگیر",
"میوهفروش",
"نگهبان",
"پاسدار",
"قاضی",
"وکیل",
"کارگر",
"شهردار",
"معدنچی",
"پرستار",
"افسر",
"عکاس",
"لولهکش",
"بازیگر",
"باربر",
"رئیسجمهور",
"نخستوزیر",
"روانشناس",
"خبرنگار",
"بازنشسته",
"مجسمهساز",
"گروهبان",
"مغازهدار",
"خواننده",
"سرباز",
"سخنران",
"جراح",
"سفالگر",
"جهانگرد",
"جوشکار",
"چشمپزشک",
"گزارشگر",
"خطاط",
]
| Provider |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_integrations.py | {
"start": 6198,
"end": 7626
} | class ____(TestCase):
def test_subclass_is_replaced_on_get(self):
project = fixture.get(Project, main_language_project=None)
integration = Integration.objects.create(
project=project,
integration_type=Integration.GITHUB_WEBHOOK,
)
integration = Integration.objects.get(pk=integration.pk)
self.assertIsInstance(integration, GitHubWebhook)
def test_subclass_is_replaced_on_subclass(self):
project = fixture.get(Project, main_language_project=None)
integration = Integration.objects.create(
project=project,
integration_type=Integration.GITHUB_WEBHOOK,
)
integration = Integration.objects.subclass(integration)
self.assertIsInstance(integration, GitHubWebhook)
def test_subclass_is_replaced_on_create(self):
project = fixture.get(Project, main_language_project=None)
integration = Integration.objects.create(
integration_type=Integration.GITHUB_WEBHOOK,
project=project,
)
self.assertIsInstance(integration, GitHubWebhook)
def test_generic_token(self):
project = fixture.get(Project, main_language_project=None)
integration = Integration.objects.create(
integration_type=Integration.API_WEBHOOK,
project=project,
)
self.assertIsNotNone(integration.token)
| IntegrationModelTests |
python | walkccc__LeetCode | solutions/1464. Maximum Product of Two Elements in an Array/1464.py | {
"start": 0,
"end": 242
} | class ____:
def maxProduct(self, nums: list[int]) -> int:
max1 = 0
max2 = 0
for num in nums:
if num > max1:
max2, max1 = max1, num
elif num > max2:
max2 = num
return (max1 - 1) * (max2 - 1)
| Solution |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 4912,
"end": 8414
} | class ____(BaseAsyncClient):
async def create_artifact(self, artifact: "ArtifactCreate") -> "Artifact":
response = await self.request(
"POST",
"/artifacts/",
json=artifact.model_dump(mode="json", exclude_unset=True),
)
from prefect.client.schemas.objects import Artifact
from prefect.events.utilities import emit_event
created = Artifact.model_validate(response.json())
# Emit an event for artifact creation
resource = {
"prefect.resource.id": f"prefect.artifact.{created.id}",
}
if created.key:
resource["prefect.resource.name"] = created.key
payload = {
k: v
for k, v in {
"key": created.key,
"type": created.type,
"description": created.description,
}.items()
if v is not None
}
emit_event(
event="prefect.artifact.created",
resource=resource,
payload=payload,
)
return created
async def update_artifact(
self, artifact_id: "UUID", artifact: "ArtifactUpdate"
) -> None:
from prefect.events.utilities import emit_event
await self.request(
"PATCH",
"/artifacts/{id}",
path_params={"id": artifact_id},
json=artifact.model_dump(mode="json", exclude_unset=True),
)
# Emit an event for artifact update
resource = {
"prefect.resource.id": f"prefect.artifact.{artifact_id}",
}
payload = artifact.model_dump(mode="json", exclude_unset=True)
emit_event(
event="prefect.artifact.updated",
resource=resource,
payload=payload or None,
)
return None
async def read_artifacts(
self, **kwargs: Unpack["ArtifactReadParams"]
) -> list["Artifact"]:
response = await self.request(
"POST",
"/artifacts/filter",
json={
"artifacts": (
artifact_filter.model_dump(mode="json", exclude_unset=True)
if (artifact_filter := kwargs.get("artifact_filter"))
else None
),
"flow_runs": (
flow_run_filter.model_dump(mode="json", exclude_unset=True)
if (flow_run_filter := kwargs.get("flow_run_filter"))
else None
),
"task_runs": (
task_run_filter.model_dump(mode="json", exclude_unset=True)
if (task_run_filter := kwargs.get("task_run_filter"))
else None
),
"limit": kwargs.get("limit", None),
"offset": kwargs.get("offset", 0),
"sort": kwargs.get("sort", None),
},
)
from prefect.client.schemas.objects import Artifact
return Artifact.model_validate_list(response.json())
async def delete_artifact(self, artifact_id: "UUID") -> None:
try:
await self.request(
"DELETE",
"/artifacts/{id}",
path_params={"id": artifact_id},
)
except HTTPStatusError as e:
if e.response.status_code == 404:
raise ObjectNotFound(http_exc=e) from e
else:
raise
| ArtifactAsyncClient |
python | huggingface__transformers | src/transformers/models/janus/modular_janus.py | {
"start": 24722,
"end": 24796
} | class ____(ChameleonVQVAEEncoderResnetBlock):
pass
| JanusVQVAEResnetBlock |
python | joke2k__faker | faker/providers/person/en_IE/__init__.py | {
"start": 267,
"end": 58684
} | class ____(PersonProvider):
formats = (
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}-{{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}-{{last_name}}",
"{{prefix_male}} {{first_name_male}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
"{{prefix_male}} {{first_name_male}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
)
first_names_male = (
"Aaron",
"Adam",
"Adrian",
"Aedan",
"Aidan",
"Aiden",
"Alan",
"Alastair",
"Albert",
"Alex",
"Alexander",
"Alistair",
"Alister",
"Andrew",
"Angus",
"Anthony",
"Antoin",
"Anton",
"Aodhan",
"Arran",
"Arron",
"Ashley",
"Bailey",
"Bailie",
"Barry",
"Ben",
"Benjamin",
"Benn",
"Bernard",
"Blaine",
"Blake",
"Brad",
"Bradley",
"Brandon",
"Breandan",
"Brendan",
"Brett",
"Brian",
"Bryan",
"Cahal",
"Cahir",
"Cailum",
"Cal",
"Caleb",
"Callan",
"Callum",
"Calum",
"Calvin",
"Cameron",
"Caoimhin",
"Caolain",
"Caolan",
"Caomhan",
"Carl",
"Carter",
"Cathal",
"Charles",
"Charlie",
"Che",
"Chris",
"Christian",
"Christie",
"Christopher",
"Christy",
"Cianan",
"Ciaran",
"Cillian",
"Clark",
"Clifford",
"Cody",
"Colin",
"Colm",
"Colum",
"Conal",
"Conall",
"Conan",
"Conchur",
"Conn",
"Connor",
"Conor",
"Conrad",
"Corey",
"Cormac",
"Cory",
"Craig",
"Curtis",
"Daire",
"Dale",
"Damian",
"Damien",
"Daniel",
"Danny",
"Dara",
"Darragh",
"Darrell",
"Darren",
"Darryl",
"Daryl",
"David",
"Deaglan",
"Dean",
"Deane",
"Declan",
"Dennis",
"Dermot",
"Desmond",
"Diarmuid",
"Dillon",
"Domhnall",
"Dominic",
"Don",
"Donal",
"Duncan",
"Dylan",
"Eamon",
"Eamonn",
"Edward",
"Elliot",
"Emmet",
"Emmett",
"Enda",
"Eoghan",
"Eoin",
"Eric",
"Ethan",
"Euan",
"Eugene",
"Eunan",
"Evan",
"Ewan",
"Feargal",
"Fearghal",
"Fergal",
"Fergus",
"Finbar",
"Finn",
"Fintan",
"Fionntan",
"Francis",
"Frazer",
"Gabriel",
"Gareth",
"Garrett",
"Gary",
"Gavin",
"Geoffrey",
"George",
"Gerald",
"Gerard",
"Giles",
"Glen",
"Glenn",
"Gordon",
"Graeme",
"Graham",
"Grant",
"Gregory",
"Hamish",
"Harry",
"Harvey",
"Hayden",
"Henry",
"Hugh",
"Iain",
"Ian",
"Isaac",
"Jack",
"Jackson",
"Jacob",
"Jaime",
"Jake",
"James",
"Jamie",
"Jared",
"Jarlath",
"Jason",
"Jay",
"Jeffrey",
"Jesse",
"Joe",
"Joel",
"John",
"Johnathan",
"Johnny",
"Jon",
"Jonathan",
"Jonathon",
"Jordan",
"Jordon",
"Joseph",
"Josh",
"Joshua",
"Jude",
"Justin",
"Kane",
"Karl",
"Kealan",
"Keelan",
"Keith",
"Kelvin",
"Kenneth",
"Kevin",
"Kieran",
"Killian",
"Kirk",
"Kristian",
"Kristopher",
"Kurt",
"Kurtis",
"Kyle",
"Lee",
"Leo",
"Leon",
"Lewis",
"Liam",
"Lloyd",
"Logan",
"Lorcan",
"Louis",
"Lucas",
"Luke",
"Lyndon",
"Macauley",
"Mairtin",
"Malachy",
"Malcolm",
"Manus",
"Marc",
"Marco",
"Marcus",
"Mark",
"Martin",
"Matthew",
"Max",
"Michael",
"Micheal",
"Mitchel",
"Mitchell",
"Morgan",
"Myles",
"Naoise",
"Nathan",
"Nathaniel",
"Neil",
"Niall",
"Nicholas",
"Nigel",
"Noel",
"Odhran",
"Oisin",
"Oliver",
"Omar",
"Oran",
"Owen",
"Padraic",
"Padraig",
"Patrick",
"Paul",
"Pauric",
"Peadar",
"Pearce",
"Pearse",
"Peter",
"Philip",
"Phillip",
"Piaras",
"Pierce",
"Raymond",
"Reece",
"Reuben",
"Rhys",
"Rian",
"Richard",
"Robbie",
"Robert",
"Robin",
"Rohan",
"Ronan",
"Rory",
"Ross",
"Rowan",
"Roy",
"Ruairi",
"Ruari",
"Russell",
"Ryan",
"Sam",
"Samuel",
"Saul",
"Scot",
"Scott",
"Seamus",
"Sean",
"Sean-Paul",
"Shane",
"Shaun",
"Shay",
"Shea",
"Simon",
"Stefan",
"Stephen",
"Steven",
"Stewart",
"Stuart",
"Taylor",
"Terence",
"Thomas",
"Tiarnan",
"Tiernan",
"Timothy",
"Tobias",
"Toby",
"Tom",
"Tomas",
"Tony",
"Travis",
"Trevor",
"Tristan",
"Troy",
"Tyler",
"Tyrone",
"Vincent",
"Warren",
"Wayne",
"William",
"Zac",
"Zach",
"Zachary",
"Zak",
)
first_names_female = (
"Abbi",
"Abbie",
"Abby",
"Abigail",
"Adele",
"Aideen",
"Aileen",
"Ailis",
"Aimee",
"Aine",
"Aisling",
"Aislinn",
"Alana",
"Alanis",
"Alanna",
"Alannah",
"Alex",
"Alexandra",
"Alexandria",
"Alice",
"Alicia",
"Alisha",
"Alison",
"Alix",
"Amanda",
"Amber",
"Amelia",
"Amie",
"Amy",
"Amy-Lee",
"Amy-Leigh",
"Anastasia",
"Andrea",
"Angela",
"Anna",
"Annalise",
"Anne-Marie",
"Annie",
"Antoinette",
"Aoibheann",
"Aoibhin",
"Aoibhinn",
"Aoife",
"April",
"Arianne",
"Ashleigh",
"Ashlene",
"Ashley",
"Ashling",
"Ashton",
"Ayesha",
"Bernadette",
"Beth",
"Bethan",
"Bethany",
"Billie-Jo",
"Blanaid",
"Brigid",
"Brittany",
"Brogan",
"Bronach",
"Bronagh",
"Brooke",
"Brooklyn",
"Bryony",
"Cailin",
"Caitlin",
"Caitlyn",
"Caitriona",
"Caoilfhionn",
"Caoimhe",
"Cara",
"Caragh",
"Carla",
"Carly",
"Carmel",
"Carol",
"Caroline",
"Carolyn",
"Carrie",
"Casey",
"Cassandra",
"Cassie",
"Catherine",
"Cathy",
"Catriona",
"Ceara",
"Celine",
"Chantel",
"Chantelle",
"Charis",
"Charlene",
"Charlie",
"Charlotte",
"Chelsea",
"Chelsey",
"Cherie",
"Cherith",
"Chloe",
"Christina",
"Christine",
"Ciara",
"Ciarrai",
"Claire",
"Clara",
"Clare",
"Clarissa",
"Claudia",
"Cliodhna",
"Cliona",
"Clodagh",
"Codie",
"Colleen",
"Collette",
"Connie",
"Constance",
"Cora",
"Corinne",
"Corrie",
"Cortney",
"Courteney",
"Courtney",
"Daire",
"Dairine",
"Dana",
"Danielle",
"Dara",
"Darcy",
"Darragh",
"Dawn",
"Dayna",
"Dearbhail",
"Dearbhaile",
"Dearbhla",
"Deborah",
"Deirbhile",
"Demi",
"Demi-Lee",
"Demi-Leigh",
"Denise",
"Dervla",
"Diane",
"Dionne",
"Donna",
"Eadaoin",
"Ebony",
"Edel",
"Eden",
"Eileen",
"Eilis",
"Eilish",
"Eimear",
"Eimer",
"Eimhear",
"Elaine",
"Eleanor",
"Elise",
"Elisha",
"Elizabeth",
"Ella",
"Ellen",
"Ellie",
"Eloise",
"Emer",
"Emilie",
"Emily",
"Emma",
"Emma-Louise",
"Enya",
"Erica",
"Erika",
"Erin",
"Eryn",
"Esther",
"Eva",
"Eve",
"Evelyn",
"Evie",
"Fainche",
"Faith",
"Faye",
"Fiona",
"Fionnuala",
"Frances",
"Francesca",
"Freya",
"Gabrielle",
"Gemma",
"Georgia",
"Georgina",
"Geraldine",
"Gillian",
"Gina",
"Grace",
"Grainne",
"Haley",
"Hannah",
"Harriet",
"Hayleigh",
"Hayley",
"Heather",
"Heidi",
"Helen",
"Helena",
"Hollie",
"Holly",
"India",
"Iona",
"Jacqueline",
"Jade",
"Jamie",
"Jamie-Lee",
"Jamie-Leigh",
"Jana",
"Jane",
"Janet",
"Janice",
"Janine",
"Jasmin",
"Jasmine",
"Jayde",
"Jayne",
"Jemma",
"Jena",
"Jenna",
"Jenni",
"Jennifer",
"Jenny",
"Jessica",
"Jill",
"Joanna",
"Joanne",
"Jodie",
"Jody",
"Johanna",
"Jolene",
"Jordan",
"Josephine",
"Joy",
"Judith",
"Julia",
"Julie",
"Julie-Anne",
"Justine",
"Kaitlin",
"Kaitlyn",
"Kara",
"Karen",
"Karla",
"Karley",
"Kate",
"Katelyn",
"Katharine",
"Katherine",
"Kathleen",
"Kathryn",
"Kathy",
"Katie",
"Katie-Louise",
"Katrina",
"Katy",
"Kayleigh",
"Keely",
"Keeva",
"Kellie",
"Kelly",
"Kelly-Anne",
"Kelly-Marie",
"Kelsey",
"Keri",
"Kerri",
"Kerrie",
"Kerry",
"Kiera",
"Kimberly",
"Kira",
"Kirby",
"Kirsten",
"Kirstie",
"Kirstin",
"Kirsty",
"Kori",
"Kristin",
"Kristina",
"Lana",
"Laoise",
"Lara",
"Laura",
"Lauren",
"Laurie",
"Leah",
"Leanne",
"Leigh",
"Leona",
"Leonie",
"Lesley",
"Lindsay",
"Lisa",
"Lisa-Marie",
"Lois",
"Lorna",
"Louise",
"Lucia",
"Lucinda",
"Lucy",
"Lydia",
"Lynda",
"Lyndsay",
"Lyndsey",
"Lynsey",
"Madison",
"Maeve",
"Mairead",
"Margaret",
"Maria",
"Marie",
"Marie-Claire",
"Martha",
"Martina",
"Mary",
"Maura",
"Maureen",
"Meabh",
"Meaghan",
"Meg",
"Megan",
"Meghan",
"Meibh",
"Melanie",
"Melissa",
"Mia",
"Michaela",
"Micheala",
"Michelle",
"Miriam",
"Mollie",
"Molly",
"Morgan",
"Nadia",
"Nadine",
"Naoimh",
"Naoise",
"Naomh",
"Naomi",
"Natalie",
"Natasha",
"Niamh",
"Nichola",
"Nichole",
"Nicola",
"Nicole",
"Nikita",
"Nikki",
"Nina",
"Nora",
"Nuala",
"Olivia",
"Oonagh",
"Orfhlaith",
"Orla",
"Orlagh",
"Orlaigh",
"Orlaith",
"Padraigin",
"Paige",
"Patrice",
"Patricia",
"Paula",
"Phoebe",
"Polly",
"Rachael",
"Rachel",
"Rachelle",
"Rebecca",
"Rebekah",
"Regan",
"Rhian",
"Rhianna",
"Rhianne",
"Rhiannon",
"Roberta",
"Robyn",
"Roise",
"Roisin",
"Rose",
"Roseanna",
"Rosemary",
"Rosie",
"Ruth",
"Sabrina",
"Sacha",
"Samantha",
"Sandra",
"Saoirse",
"Sara",
"Sarah",
"Sarah-Jane",
"Sarah-Louise",
"Sasha",
"Saskia",
"Savannah",
"Seana",
"Seanan",
"Seaneen",
"Seanna",
"Selina",
"Seona",
"Serena",
"Shania",
"Shanice",
"Shanna",
"Shannan",
"Shannen",
"Shannon",
"Sharon",
"Shauna",
"Shauneen",
"Shelby",
"Shelley",
"Sheree",
"Shona",
"Sian",
"Simone",
"Sinead",
"Siobhan",
"Siofra",
"Sophia",
"Sophie",
"Sophie-Louise",
"Sorcha",
"Stacey",
"Stephanie",
"Susan",
"Susanna",
"Susannah",
"Suzanne",
"Tamara",
"Tammy",
"Tanya",
"Tara",
"Taylor",
"Teresa",
"Terri",
"Tess",
"Tessa",
"Theresa",
"Therese",
"Tia",
"Tiarna",
"Tiegan",
"Tiffany",
"Toni",
"Tonicha",
"Tori",
"Tory",
"Tracey",
"Tyler",
"Una",
"Ursula",
"Vanessa",
"Victoria",
"Whitney",
"Yasmin",
"Yasmine",
"Zara",
"Zoe",
)
first_names = first_names_male + first_names_female
last_names = (
"Achison",
"Adams",
"Agnew",
"Ahearn",
"Ahearne",
"Ahern",
"Aherne",
"Ainsboro",
"Allen",
"Allis",
"Anderson",
"Andrews",
"Angus",
"Annsboro",
"Ansboro",
"Arthurs",
"Ashe",
"Ashman",
"Atchison",
"Atkins",
"Atkinson",
"Aylward",
"Baker",
"Baldwin",
"Bale",
"Bandeville",
"Banks",
"Bann",
"Bannon",
"Banville",
"Barnes",
"Barnett",
"Barneville",
"Barrett",
"Barrnette",
"Barron",
"Barry",
"Bartley",
"Bates",
"Baxter",
"Beakey",
"Beal",
"Beale",
"Beasty",
"Beattie",
"Beatty",
"Beggan",
"Beggs",
"Begley",
"Behan",
"Beirn",
"Beirne",
"Bell",
"Belton",
"Bennet",
"Bennett",
"Beresford",
"Bergin",
"Bermingham",
"Berminghim",
"Bernard",
"Berney",
"Bernie",
"Berry",
"Biesty",
"Bird",
"Birmingham",
"Bishop",
"Black",
"Blake",
"Blanch",
"Blanche",
"Bodkin",
"Bogan",
"Bohan",
"Boland",
"Boles",
"Bolger",
"Bonar",
"Boner",
"Bones",
"Bonner",
"Boreland",
"Borland",
"Bourke",
"Bowe",
"Bowen",
"Bowler",
"Bowles",
"Boyce",
"Boylan",
"Boyle",
"Boyse",
"Bradden",
"Bradley",
"Brady",
"Branaola",
"Brannelly",
"Brassil",
"Bray",
"Bree",
"Breen",
"Breheny",
"Brennan",
"Breslin",
"Bresnehan",
"Brett",
"Brick",
"Bridge",
"Bridson",
"Brien",
"Briody",
"Brislane",
"Broderick",
"Brody",
"Brogan",
"Brophy",
"Brosnan",
"Brown",
"Browne",
"Broy",
"Bruen",
"Bruton",
"Bryan",
"Bryson",
"Buckley",
"Burchill",
"Burke",
"Burns",
"Burton",
"Butler",
"Buttimer",
"Buttimore",
"Byrne",
"Byrnes",
"Cadden",
"Caddow",
"Cadogan",
"Cafferkey",
"Cafferky",
"Cafferty",
"Caffrey",
"Cagney",
"Cahalane",
"Cahill",
"Cahillane",
"Cahir",
"Caine",
"Cairn",
"Cairns",
"Caldwell",
"Callaghan",
"Callan",
"Callanan",
"Calligan",
"Callinan",
"Cally",
"Calvey",
"Campbell",
"Canavan",
"Cannan",
"Canniffe",
"Canning",
"Cannon",
"Canny",
"Cantwell",
"Caplis",
"Capples",
"Capua",
"Carbery",
"Carey",
"Carleton",
"Carley",
"Carlin",
"Carmody",
"Carney",
"Carolan",
"Carr",
"Carragher",
"Carrig",
"Carrigan",
"Carrigy",
"Carroll",
"Carry",
"Carter",
"Carthy",
"Carton",
"Carty",
"Carville",
"Casey",
"Cashen",
"Cashman",
"Cassen",
"Casserley",
"Casserly",
"Cassidy",
"Cassin",
"Cattigan",
"Cauley",
"Caulfield",
"Cavanagh",
"Cawley",
"Charles",
"Christopher",
"Clafferty",
"Claffey",
"Clair",
"Clancy",
"Clare",
"Clarke",
"Classon",
"Clavin",
"Clear",
"Cleary",
"Clements",
"Clenaghan",
"Clerkin",
"Clery",
"Clifford",
"Clinten",
"Clinton",
"Clogherty",
"Cloherty",
"Clohessey",
"Clohessy",
"Cloney",
"Cloonan",
"Cloone",
"Clooney",
"Clune",
"Coady",
"Coakley",
"Cody",
"Coen",
"Coffey",
"Cogan",
"Cogley",
"Cohalan",
"Cohen",
"Coholan",
"Cole",
"Coleman",
"Colfer",
"Colgan",
"Colhoun",
"Coll",
"Collen",
"Colleneler",
"Colleran",
"Colley",
"Collier",
"Colligan",
"Collinder",
"Collins",
"Colly",
"Colreavy",
"Colum",
"Comber",
"Combre",
"Comer",
"Comerford",
"Comisky",
"Commins",
"Comyn",
"Conaty",
"Conboy",
"Concannon",
"Condon",
"Condren",
"Condron",
"Conefrey",
"Conlan",
"Conlon",
"Conmee",
"Conmy",
"Connachton",
"Connaghy",
"Connaughton",
"Conneeley",
"Conneely",
"Connell",
"Connellan",
"Connelly",
"Connery",
"Connole",
"Connolly",
"Connor",
"Connors",
"Conole",
"Conree",
"Conroy",
"Conry",
"Considine",
"Convey",
"Conway",
"Conwell",
"Coogan",
"Cook",
"Cooke",
"Coolahan",
"Coonan",
"Cooney",
"Corbett",
"Corcoran",
"Corduff",
"Corish",
"Corkery",
"Corless",
"Corley",
"Cormack",
"Cormican",
"Cormick",
"Cormy",
"Corr",
"Corridan",
"Corrigan",
"Corry",
"Cosgrave",
"Cosgrove",
"Costello",
"Costelloe",
"Costigan",
"Cotter",
"Coughlan",
"Counihan",
"Courcey",
"Cournane",
"Courtenay",
"Courtney",
"Cousins",
"Cowan",
"Cowely",
"Cowen",
"Cowley",
"Cox",
"Coyle",
"Coyne",
"Crahan",
"Craig",
"Craine",
"Crampsey",
"Crampsie",
"Crane",
"Crangle",
"Cranley",
"Cranly",
"Craven",
"Crawley",
"Crean",
"Creed",
"Creedon",
"Cregan",
"Crehan",
"Cremin",
"Cribbons",
"Crilly",
"Crimmins",
"Crinion",
"Croal",
"Crohan",
"Crolly",
"Cronelly",
"Cronin",
"Cronly",
"Crosbie",
"Crosby",
"Cross",
"Crossan",
"Crota",
"Crotty",
"Crowe",
"Crowley",
"Crudden",
"Cruise",
"Cryan",
"Cuddihy",
"Cuffe",
"Culhane",
"Cullen",
"Culligan",
"Cullinan",
"Cullinane",
"Culloty",
"Cully",
"Cumiskey",
"Cumisky",
"Cummins",
"Cummiskey",
"Cummisky",
"Cunnane",
"Cunneen",
"Cunningham",
"Cunny",
"Curley",
"Curnane",
"Curneen",
"Curnyn",
"Curran",
"Currie",
"Curry",
"Curtin",
"Curtis",
"Cusack",
"D'Arcy",
"Daiken",
"Dalton",
"Daly",
"Danaher",
"Dane",
"Daniel",
"Daniels",
"Darcy",
"Dargan",
"Darmody",
"Dasey",
"Davenport",
"Davern",
"Davey",
"Davin",
"Davis",
"Davitt",
"Davoren",
"Davy",
"Daw",
"Dawson",
"Day",
"Deacon",
"Deacy",
"Deady",
"Dean",
"Deane",
"Dease",
"Deasy",
"Dee",
"Deegadan",
"Deegan",
"Deehan",
"Deeley",
"Deely",
"Deeney",
"Deeny",
"Deere",
"Deery",
"Deigan",
"Deignan",
"Delahunty",
"Delaney",
"Delap",
"Delargy",
"Deloughrey",
"Deloughry",
"Dempsey",
"Denihan",
"Denis",
"Denison",
"Dennehy",
"Denning",
"Denny",
"Dermody",
"Dermott",
"Derrig",
"Desmond",
"Devally",
"Devane",
"Devaney",
"Devanney",
"Devenney",
"Dever",
"Devereaux Deaueroux",
"Devereux",
"Devery",
"Devilly",
"Devin",
"Devine",
"Devitt",
"Devlin",
"Devoy",
"Dickey",
"Dickie",
"Dickson",
"Diffin",
"Diffley",
"Diggin",
"Diggins",
"Dignan",
"Dillane",
"Dillon",
"Dinan",
"Dineen",
"Dinneen",
"Dirrane",
"Diskin",
"Divenney",
"Diver",
"Divine",
"Diviney",
"Dixon",
"Dobbin",
"Dobbins",
"Dogherty",
"Doherty",
"Dolan",
"Donagher",
"Donaldson",
"Donegan",
"Donlon",
"Donnan",
"Donnell",
"Donnellan",
"Donnelly",
"Donoghue",
"Donohoe",
"Donohue",
"Donovan",
"Doody",
"Dooey",
"Doogan",
"Doohan",
"Doolan",
"Dooley",
"Doorty",
"Doran",
"Dordan",
"Dore",
"Dorgan",
"Dornan",
"Dorrian",
"Doudigan",
"Dowd",
"Dower",
"Dowey",
"Dowley",
"Dowling",
"Downes",
"Downey",
"Downing",
"Doyle",
"Drennan",
"Drian",
"Driscoll",
"Drohan",
"Droney",
"Drum",
"Drumm",
"Drummond",
"Drummy",
"Duane",
"Duff",
"Duffin",
"Duffy",
"Duggan",
"Duhig",
"Duhy",
"Duignan",
"Dulohery",
"Duncan",
"Dunford",
"Dungan",
"Dunleavey",
"Dunleavy",
"Dunne",
"Dunning",
"Dunny",
"Dunphy",
"Dunworth",
"Durkan",
"Durkin",
"Durnan",
"Durnin",
"Durning",
"Durrihy",
"Dwane",
"Dwyer",
"Dyer",
"Earl",
"Earle",
"Early",
"Egan",
"Eivers",
"Elliot",
"Elliott",
"Ellis",
"Elwood",
"English",
"Ennis",
"Enright",
"Ervin",
"Ervine",
"Eustace",
"Evans",
"Evoy",
"Fadden",
"Fadian",
"Fagan",
"Faherty",
"Fahey",
"Fahy",
"Fair",
"Fall",
"Fallon",
"Falvey",
"Fannin",
"Fanning",
"Fannon",
"Farell",
"Farnan",
"Farnon",
"Farragher",
"Farrell",
"Farrelly",
"Farren",
"Farrissey",
"Farrissy",
"Farry",
"Faulkner",
"Faull",
"Fay",
"Fealy",
"Fearon",
"Fee",
"Feehan",
"Feeley",
"Feely",
"Feeney",
"Feeny",
"Fegan",
"Fehan",
"Fehilly",
"Feighery",
"Felban",
"Fenelon",
"Fenighty",
"Fenlon",
"Fennell",
"Fennelly",
"Fennessey",
"Fenning",
"Fenton",
"Fergus",
"Ferguson",
"Ferris",
"Ferriter",
"Ferry",
"Field",
"Fielding",
"Filban",
"Filbin",
"Finan",
"Finegan",
"Finlay",
"Finn",
"Finnegan",
"Finneran",
"Finnerty",
"Finnucane",
"Finucane",
"Fisher",
"Fitzgerald",
"Fitzgibbon",
"Fitzgibbons",
"Fitzmartin",
"Fitzmaurice",
"Fitzpatrick",
"Fitzsimmons",
"Fitzsimons",
"Flaherty",
"Flahive",
"Flanagan",
"Flannagan",
"Flannelly",
"Flannery",
"Flatley",
"Flavin",
"Fleming",
"Flinn",
"Flood",
"Flynn",
"Fogarty",
"Folan",
"Foley",
"Foody",
"Foran",
"Forbes",
"Ford",
"Forde",
"Forkin",
"Fox",
"Foy",
"Foyle",
"Fraher",
"Frances",
"Francis",
"Franklin",
"Frawley",
"Freaney",
"Freeley",
"Freely",
"Freeney",
"Freil",
"Fresh",
"Friel",
"Furey",
"Fyfe",
"Gaffney",
"Gahan",
"Gaine",
"Gainey",
"Gallagher",
"Gallaher",
"Gallen",
"Galligan",
"Gallivan",
"Gallogly",
"Galvin",
"Ganley",
"Ganly",
"Gannon",
"Garavan",
"Garde",
"Garety",
"Gargan",
"Garland",
"Garraghy",
"Garrahy",
"Garrihy",
"Garry",
"Gartlan",
"Gartland",
"Garvey",
"Garvin",
"Gately",
"Gaughan",
"Gavaghan",
"Gavican",
"Gavigan",
"Gavin",
"Gay",
"Gaynard",
"Gaynor",
"Geany",
"Gearty",
"Geary",
"Geherty",
"Geoghegan",
"Geraghty",
"Gerarghty",
"Gibbon",
"Gibbons",
"Giblin",
"Gibney",
"Gibson",
"Gilbane",
"Gilbride",
"Gildea",
"Gilduff",
"Giles",
"Gilgunn",
"Gilhooly",
"Gill",
"Gillan",
"Gillen",
"Gillespie",
"Gillic",
"Gillick",
"Gilligan",
"Gilliland",
"Gillis",
"Gillooly",
"Gilmartin",
"Gilmore",
"Gilroy",
"Gilsenan",
"Ginevan",
"Ging",
"Ginnitty",
"Ginnity",
"Ginty",
"Girvan",
"Givern",
"Glavin",
"Glazier",
"Gleasure",
"Gleeson",
"Glennon",
"Gloster",
"Glynn",
"Godfrey",
"Goff",
"Gogan",
"Gogarty",
"Goggin",
"Golden",
"Golding",
"Goldrick",
"Gollan",
"Goodwin",
"Gorevan",
"Gorey",
"Gorham",
"Gorman",
"Gough",
"Goulden",
"Goulding",
"Grace",
"Grady",
"Graham",
"Grahams",
"Grattan",
"Gray",
"Grealish",
"Greally",
"Greaney",
"Greehy",
"Greelish",
"Greely",
"Green",
"Greene",
"Grennan",
"Grey",
"Griffen",
"Griffin",
"Griffith",
"Griffiths",
"Groarke",
"Grogan",
"Groogan",
"Growney",
"Gubain",
"Gubben",
"Guerin",
"Guihan",
"Guilfoyle",
"Guinan",
"Guinane",
"Guinevan",
"Guiney",
"Guinnane",
"Guinness",
"Guiry",
"Gunn",
"Gunning",
"Gwynn",
"Hackett",
"Hagan",
"Haggerty",
"Hahessy",
"Haire",
"Hallahan",
"Hallanan",
"Halley",
"Hallinan",
"Hallissey",
"Halloran",
"Halpen",
"Halpin",
"Hamilton",
"Hanafin",
"Hanbury",
"Hankard",
"Hanley",
"Hanlon",
"Hanly",
"Hanna",
"Hannah",
"Hanncard",
"Hannigan",
"Hannon",
"Hanrahan",
"Hanratty",
"Hara",
"Harahoe",
"Haran",
"Hardiman",
"Hardy",
"Hare",
"Haren",
"Hargadon",
"Hargan",
"Harkin",
"Harkins",
"Harley",
"Harmon",
"Harnett",
"Harrihy",
"Harrington",
"Harris",
"Harrison",
"Harry",
"Harte",
"Hartigan",
"Hartnett",
"Harty",
"Hassett",
"Hastey",
"Hastie",
"Hastings",
"Hasty",
"Hatton",
"Haugh",
"Haughey",
"Haverty",
"Hawe",
"Hawthorn",
"Hayden",
"Hayes",
"Heaffy",
"Healy",
"Heaney",
"Heaphy",
"Hearn",
"Hearne",
"Hearty",
"Heavey",
"Heckett",
"Hedderman",
"Hedigan",
"Heelan",
"Heenan",
"Heeney",
"Heffernan",
"Hefferon",
"Heffron",
"Hegarty",
"Heggarty",
"Hehir",
"Helen",
"Helery",
"Hely",
"Hempenstall",
"Hendry",
"Henebry",
"Heneghan",
"Henery",
"Heney",
"Hennebry",
"Hennelley",
"Hennelly",
"Hennessey",
"Hennessy",
"Hennigan",
"Henry",
"Hepenstall",
"Heraghty",
"Heraty",
"Herbert",
"Hereward",
"Herity",
"Herlihy",
"Hernon",
"Heron",
"Heskin",
"Heslin",
"Hession",
"Hever",
"Hewson",
"Hickey",
"Higgins",
"Hilary",
"Hillen",
"Hillery",
"Hilliard",
"Hinney",
"Hishon",
"Histon",
"Hoare",
"Hoban",
"Hodnett",
"Hoey",
"Hogan",
"Holden",
"Holland",
"Hollins",
"Hollywood",
"Holmes",
"Holohan",
"Honan",
"Hopkins",
"Horan",
"Hore",
"Horgan",
"Hosae",
"Hosey",
"Hoskins",
"Hough",
"Houlihan",
"Hourican",
"Hourigan",
"Hourihane",
"Howard",
"Howe",
"Howley",
"Hughes",
"Humphreys",
"Hunt",
"Hunter",
"Hurd",
"Hurley",
"Hussey",
"Hutchinson",
"Hutchison",
"Hutton",
"Hyde",
"Hyland",
"Hyman",
"Hynes",
"Iago",
"Igoe",
"Inglis",
"Ingoldsby",
"Irvine",
"Irwin",
"Ivers",
"Ivory",
"Jackman",
"Jackson",
"Jameson",
"Jennings",
"Jiles",
"Johnson",
"Johnston",
"Johnstone",
"Jones",
"Jordan",
"Joyce",
"Judge",
"Kane",
"Kangley",
"Kavanagh",
"Keady",
"Kealey",
"Keally",
"Kealty",
"Kealy",
"Keane",
"Keaney",
"Keany",
"Keapock",
"Kearney",
"Kearns",
"Keary",
"Keating",
"Keaveney",
"Keaveny",
"Keeffe",
"Keegan",
"Keehan",
"Keelan",
"Keeley",
"Keely",
"Keenaghan",
"Keenahan",
"Keenan",
"Keeney",
"Keery",
"Keevers",
"Kehoe",
"Keightley",
"Kelleher",
"Keller",
"Kelly",
"Kelvey",
"Kenlan",
"Kenlon",
"Kenna",
"Kenneally",
"Kennedy",
"Kennellan",
"Kennelly",
"Kenny",
"Keogan",
"Keogh",
"Keoghan",
"Keoghane",
"Keohan",
"Keohane",
"Keown",
"Kerin",
"Kerins",
"Kerley",
"Kerlin",
"Kermody",
"Kernan",
"Kerney",
"Kerr",
"Kerrigan",
"Kerrisk",
"Kerville",
"Kerwick",
"Kevane",
"Keville",
"Keyes",
"Kidney",
"Kiely",
"Kieran",
"Kierane",
"Kierans",
"Kiernan",
"Kilawee",
"Kilbane",
"Kilbride",
"Kilcoyne",
"Kilday",
"Kildea",
"Kilduff",
"Kilfoyle",
"Kilgallen",
"Kilgallon",
"Kilhooly",
"Kilkenny",
"Killeen",
"Killilea",
"Killooly",
"Killoran",
"Killoughry",
"Kilmartin",
"Kilmore",
"Kilroe",
"Kilroy",
"Kinaghan",
"Kinahan",
"King",
"Kingston",
"Kiniry",
"Kinlan",
"Kinlen",
"Kinnane",
"Kinnear",
"Kinnegan",
"Kinner",
"Kinnerk",
"Kinney",
"Kinnon",
"Kinny",
"Kinsella",
"Kirby",
"Kirke",
"Kirwan",
"Kissane",
"Kitson",
"Kneafsey",
"Knight",
"Kyne",
"Lacey",
"Lacy",
"Lafferty",
"Laffey",
"Lahey",
"Lahiffe",
"Lahy",
"Laing",
"Lally",
"Lalor",
"Lambe",
"Lamont",
"Landa",
"Lande",
"Landers",
"Landy",
"Lane",
"Lang",
"Langan",
"Lanigan",
"Lappin",
"Lardner",
"Largan",
"Largey",
"Larkin",
"Lavan",
"Lavell",
"Lavelle",
"Laverty",
"Lavery",
"Lavin",
"Lawless",
"Lawlor",
"Leacy",
"Leahy",
"Leary",
"Leavey",
"Leddin",
"Leddon",
"Leddy",
"Ledwich",
"Ledwith",
"Lee",
"Leech",
"Leen",
"Leeney",
"Lehane",
"Leland",
"Lenaghan",
"Leneghan",
"Lenehan",
"Lenihan",
"Lennane",
"Lennon",
"Leonard",
"Lester",
"Levan",
"Leyden",
"Leydon",
"Liddane",
"Liddy",
"Lillis",
"Lincoln",
"Lindsay",
"Linehan",
"Linnane",
"Linny",
"Linskey",
"Liston",
"Little",
"Loftus",
"Logan",
"Loghan",
"Logue",
"London",
"Lonergan",
"Long",
"Longan",
"Looney",
"Lord",
"Lordan",
"Loughlin",
"Loughnane",
"Loughran",
"Loughrey",
"Loughry",
"Lovett",
"Lowe",
"Lowney",
"Lowry",
"Lucey",
"Lucid",
"Lucitt",
"Luddy",
"Lundon",
"Lunham",
"Lunney",
"Lunny",
"Lyden",
"Lydon",
"Lynch",
"Lynchechaun",
"Lynchehaun",
"Lyne",
"Lyng",
"Lynn",
"Lynskey",
"Lyons",
"Lysaght",
"Mac Breen",
"MacAdoo",
"MacAleavy",
"MacAllen",
"MacAloon",
"MacAnally",
"MacArt",
"MacArthur",
"MacBreen",
"MacBride",
"MacCaffrey",
"MacCann",
"MacCartan",
"MacCarthy",
"MacCarville",
"MacClenaghan",
"MacCole",
"MacComisky",
"MacConachy",
"MacConnaghy",
"MacCool",
"MacCormack",
"MacCurtin",
"MacDermott",
"MacDevitt",
"MacDonagh",
"MacDonald",
"MacDonnell",
"MacDougall",
"MacDowell",
"MacDwyer",
"MacDyer",
"MacEgan",
"MacElgunn",
"MacEver",
"MacEvoy",
"MacFadden",
"MacFall",
"MacFaull",
"MacGee",
"MacGeehan",
"MacGill",
"MacGilligan",
"MacGing",
"MacGinley",
"MacGinnitty",
"MacGinnity",
"MacGinty",
"MacGloin",
"MacGlynn",
"MacGovern",
"MacGreal",
"MacGroarty",
"MacGuinness",
"MacGurk",
"MacHale",
"MacHenry",
"MacHugh",
"MacInerney",
"MacInnes",
"MacKenna",
"MacKeown",
"MacKevitt",
"MacLysaght",
"MacMahon",
"MacMonagle",
"MacMorrow",
"MacMullan",
"MacMullen",
"MacNabb",
"MacNaboe",
"MacNaboola",
"MacNally",
"MacNamara",
"MacNamee",
"MacNeela",
"MacNeill",
"MacNelis",
"MacNulty",
"MacPhilbin",
"MacShea",
"MacSweeney",
"MacTiernan",
"MacVeagh",
"MacVeigh",
"MacWilliams",
"Macauley",
"Macken",
"Mackesey",
"Mackey",
"Mackle",
"Maclean",
"Macmillan",
"Macrea",
"Madden",
"Maddock",
"Maddy",
"Madigan",
"Magan",
"Magann",
"Magauran",
"Magee",
"Mageean",
"Magennis",
"Magennity",
"Magill",
"Maginn",
"Magrath",
"Maguire",
"Mahedy",
"Maher",
"Mahon",
"Mahoney",
"Mahony",
"Malley",
"Mallon",
"Malone",
"Maloney",
"Malowney",
"Manahan",
"Mangan",
"Manley",
"Mann",
"Manning",
"Mannion",
"Mannix",
"Mansell",
"Mansfield",
"Mara",
"Markey",
"Markham",
"Marley",
"Marnan",
"Marren",
"Marrinan",
"Marron",
"Marry",
"Martin",
"Martyn",
"Masterson",
"Matthews",
"Maughan",
"Maxwell",
"May",
"Maye",
"McAdams",
"McAleavy",
"McAleenan",
"McAleer",
"McAlinney",
"McAlister",
"McAloon",
"McAlunny",
"McAnally",
"McAndrew",
"McAnulty",
"McArdle",
"McAreavey",
"McAtee",
"McAteer",
"McAuley",
"McAuliffe",
"McAveigh",
"McBreen",
"McBride",
"McBrien",
"McCabe",
"McCadam",
"McCadden",
"McCafferky",
"McCafferty",
"McCaffrey",
"McCaffry",
"McCahill",
"McCall",
"McCallion",
"McCann",
"McCardle",
"McCarney",
"McCarra",
"McCarron",
"McCartan",
"McCarte",
"McCarthy",
"McCarville",
"McCaughan",
"McCaughey",
"McCaul",
"McCauley",
"McCausland",
"McCay",
"McClean",
"McClelland",
"McCloskey",
"McCluskey",
"McColgan",
"McColl",
"McCollam",
"McComiskey",
"McConaghey",
"McConaghy",
"McConnell",
"McConnon",
"McCooey",
"McCool",
"McCorkill",
"McCorley",
"McCormick",
"McCorry",
"McCourt",
"McCoy",
"McCracken",
"McCrann",
"McCrea",
"McCready",
"McCreanor",
"McCrory",
"McCrossan",
"McCrudden",
"McCullagh",
"McCullough",
"McCumiskey",
"McCumisky",
"McCurdy",
"McCurley",
"McCurtin",
"McCusker",
"McDade",
"McDaeid",
"McDaid",
"McDermod",
"McDermott",
"McDevitt",
"McDonagh",
"McDonald",
"McDougald",
"McDowell",
"McDunphy",
"McDwyer",
"McDyer",
"McElduff",
"McElgunn",
"McElhattin",
"McEllistrim",
"McElnay",
"McElnea",
"McElroe",
"McElroy",
"McElwaine",
"McElwee",
"McEnaney",
"McEneaney",
"McEnry",
"McEntaggart",
"McEntee",
"McEvaddy",
"McEvilly",
"McEvoy",
"McFadden",
"McFall",
"McFarland",
"McFaull",
"McGahey",
"McGalligly",
"McGann",
"McGarraghy",
"McGarrigle",
"McGarry",
"McGarvey",
"McGauran",
"McGaw",
"McGeady",
"McGee",
"McGeehan",
"McGeoghegan",
"McGeown",
"McGerr",
"McGettigan",
"McGettrick",
"McGill",
"McGillicuddy",
"McGilligan",
"McGilly",
"McGilroy",
"McGinley",
"McGinnitty",
"McGinty",
"McGirl",
"McGirr",
"McGivern",
"McGlinchey",
"McGlinchy",
"McGloin",
"McGlynn",
"McGoff",
"McGoldrick",
"McGonagle",
"McGough",
"McGourty",
"McGovern",
"McGowan",
"McGowern",
"McGrane",
"McGrath",
"McGreal",
"McGrenehan",
"McGroarty",
"McGrory",
"McGruddie",
"McGruddy",
"McGuigan",
"McGuill",
"McGuinn",
"McGuinness",
"McGuire",
"McGuirk",
"McGuirl",
"McGurk",
"McHale",
"McHarry",
"McHenry",
"McHugh",
"McIldownie",
"McIlroe",
"McIlroy",
"McIlwee",
"McIneely",
"McInerney",
"McInnes",
"McIntyre",
"McIvor",
"McKaigue",
"McKay",
"McKee",
"McKeegan",
"McKeever",
"McKelvey",
"McKendry",
"McKeniry",
"McKenna",
"McKenny",
"McKeogh",
"McKeon",
"McKeown",
"McKernon",
"McKevitt",
"McKie",
"McKiernan",
"McKillop",
"McKing",
"McKinley",
"McKinney",
"McKinnon",
"McKnight",
"McLaughlin",
"McLaverty",
"McLean",
"McLeer",
"McLeese",
"McLeigh",
"McLeod",
"McLoon",
"McLoone",
"McLoughlin",
"McMacken",
"McMahon",
"McManus",
"McMaster",
"McMenamin",
"McMonagle",
"McMorrow",
"McMullen",
"McMurrough",
"McNaboe",
"McNally",
"McNamara",
"McNamee",
"McNaughton",
"McNea",
"McNealy",
"McNee",
"McNeely",
"McNeill",
"McNelis",
"McNevin",
"McNicholas",
"McNicholl",
"McNill",
"McNulty",
"McPartland",
"McPartlin",
"McPartlon",
"McPherson",
"McPhilbin",
"McPhillips",
"McPolin",
"McQuade",
"McQuaid",
"McQueen",
"McQuilkan",
"McQuillan",
"McQuillen",
"McQuin",
"McQuinn",
"McRann",
"McReady",
"McRoarty",
"McRory",
"McShane",
"McSharry",
"McSheehy",
"McTeague",
"McTernan",
"McTiernan",
"McTigue",
"McVeagh",
"McVeigh",
"McVicker",
"McVitty",
"McWalter",
"Meaghan",
"Meagher",
"Meaney",
"Meany",
"Meara",
"Mee",
"Meehan",
"Meenaghan",
"Meenan",
"Megaw",
"Mehigan",
"Melady",
"Meldon",
"Melia",
"Melican",
"Mellet",
"Mellon",
"Melody",
"Melville",
"Melvin",
"Menton",
"Mernagh",
"Merrigan",
"Merry",
"Mescall",
"Meskill",
"Miley",
"Millar",
"Millea",
"Miller",
"Millet",
"Millican",
"Milligan",
"Milmo",
"Milne",
"Milroy",
"Minihan",
"Minihane",
"Minogue",
"Miscell",
"Miskell",
"Mitchell",
"Moan",
"Moffatt",
"Moffit",
"Mohan",
"Moher",
"Molloy",
"Moloney",
"Molyneux",
"Monaghan",
"Monagle",
"Monahan",
"Mongan",
"Monk",
"Monks",
"Monroe",
"Montague",
"Montgomery",
"Moody",
"Moone",
"Mooney",
"Moore",
"Morahan",
"Moran",
"Morgan",
"Moriarty",
"Morley",
"Mornane",
"Moroney",
"Morrin",
"Morris",
"Morrison",
"Morrissey",
"Morrow",
"Mountain",
"Moy",
"Moylan",
"Moynihan",
"Mulcahy",
"Mulcair",
"Muldoon",
"Muldowney",
"Mulgrave",
"Mulgrew",
"Mulhare",
"Mulhern",
"Mulkerrin",
"Mullaghan",
"Mullaly",
"Mullan",
"Mullane",
"Mullaney",
"Mullany",
"Mullarkey",
"Mullen",
"Mullery",
"Mulligan",
"Mullin",
"Mullins",
"Mullooly",
"Mullooney",
"Mulloughney",
"Mulloy",
"Mulqueen",
"Mulqueeny",
"Mulrain",
"Mulrooney",
"Mulroy",
"Mulry",
"Mulryan",
"Mulvany",
"Mulvenna",
"Mulvey",
"Mulvihill",
"Mulvin",
"Mulvy",
"Munnelly",
"Munroe",
"Murae",
"Murnane",
"Murnin",
"Murphy",
"Murray",
"Murrihy",
"Murtagh",
"Myers",
"Myles",
"Nagle",
"Nallon",
"Nally",
"Nalty",
"Nangle",
"Nary",
"Nash",
"Naughton",
"Nea",
"Nealon",
"Neary",
"Nee",
"Needham",
"Neehan",
"Neelan",
"Neelin",
"Neenan",
"Neilan",
"Neilian",
"Neill",
"Neligan",
"Nelis",
"Nelson",
"Nestor",
"Neville",
"Nevin",
"Neylon",
"Nicholas",
"Nicholls",
"Nicholson",
"Niland",
"Nixon",
"Nolan",
"Nolty",
"Noonan",
"Noone",
"Norris",
"Norry",
"Norton",
"Nugent",
"Nulty",
"Nunne",
"Nyhan",
"O'Beirn",
"O'Beirne",
"O'Boyle",
"O'Brassil",
"O'Brazil",
"O'Brennan",
"O'Brien",
"O'Brown",
"O'Bryan",
"O'Bryen",
"O'Byrne",
"O'Cadden",
"O'Cafferky",
"O'Callaghan",
"O'Carolan",
"O'Carroll",
"O'Casey",
"O'Cassidy",
"O'Cleary",
"O'Clery",
"O'Connell",
"O'Connor",
"O'Crohan",
"O'Crowley",
"O'Curry",
"O'Daly",
"O'Dea",
"O'Devanney",
"O'Devenny",
"O'Doherty",
"O'Donnell",
"O'Donoghue",
"O'Donohoe",
"O'Donovan",
"O'Dowd",
"O'Driscoll",
"O'Duffy",
"O'Dwyer",
"O'Farrell",
"O'Farrelly",
"O'Flaherty",
"O'Flynn",
"O'Freil",
"O'Friel",
"O'Gallagher",
"O'Gara",
"O'Goldrick",
"O'Gorman",
"O'Gowan",
"O'Grady",
"O'Growney",
"O'Hagan",
"O'Haire",
"O'Halloran",
"O'Hanlon",
"O'Hanrahan",
"O'Hara",
"O'Hare",
"O'Haughey",
"O'Hea",
"O'Hegarty",
"O'Hehir",
"O'Herlihy",
"O'Hickey",
"O'Higgins",
"O'Hora",
"O'Houlihan",
"O'Hurley",
"O'Hussey",
"O'Kane",
"O'Kearney",
"O'Keefe",
"O'Keeffe",
"O'Kelly",
"O'Kennedy",
"O'Kieve",
"O'Leary",
"O'Loan",
"O'Looney",
"O'Loughlin",
"O'Loughlinn",
"O'Mahoney",
"O'Mahony",
"O'Malley",
"O'Mara",
"O'Meara",
"O'Mooney",
"O'Moore",
"O'Mullan",
"O'Murnaghan",
"O'Neill",
"O'Nolan",
"O'Rafferty",
"O'Rahilly",
"O'Reardon",
"O'Regan",
"O'Reilly",
"O'Riordan",
"O'Rooney",
"O'Rourke",
"O'Ruane",
"O'Ryan",
"O'Scannell",
"O'Shannon",
"O'Sharkey",
"O'Shaughnessy",
"O'Shea",
"O'Sheehan",
"O'Sheil",
"O'Shiel",
"O'Sullivan",
"O'Sweeney",
"O'Tierney",
"O'Togher",
"O'Toole",
"Ormsby",
"Owens",
"Padden",
"Parker",
"Parsons",
"Paten",
"Patterson",
"Patton",
"Paul",
"Pender",
"Perkins",
"Perri",
"Perry",
"Peyton",
"Phayre",
"Phelan",
"Philban",
"Philbin",
"Phillips",
"Piggott",
"Pigott",
"Pinder",
"Plover",
"Poland",
"Powell",
"Power",
"Prendergast",
"Prial",
"Price",
"Pringle",
"Pryal",
"Purcell",
"Quaide",
"Qualter",
"Queally",
"Queenane",
"Quigley",
"Quigney",
"Quill",
"Quillinan",
"Quilty",
"Quin",
"Quinlan",
"Quinlivan",
"Quinn",
"Quinney",
"Quinny",
"Quirke",
"Rabbitte",
"Rafferty",
"Rafter",
"Raftery",
"Raftis",
"Rahilly",
"Raight",
"Rails",
"Raleigh",
"Randles",
"Raney",
"Raol",
"Rattigan",
"Rawley",
"Rayel",
"Rea",
"Reade",
"Reardon",
"Reavy",
"Reddin",
"Reddy",
"Redican",
"Redmond",
"Reen",
"Regan",
"Reid",
"Reidy",
"Reilly",
"Renehan",
"Reynell",
"Reynolds",
"Reynoldson",
"Rhatigan",
"Rhattigan",
"Rice",
"Richard",
"Richards",
"Richardson",
"Richey",
"Richie",
"Ridge",
"Rigney",
"Riney",
"Ring",
"Rinn",
"Riordan",
"Roach",
"Roache",
"Roarke",
"Roarty",
"Roberts",
"Robertson",
"Robeson",
"Robinson",
"Roche",
"Rock",
"Rodden",
"Roddy",
"Roden",
"Rodgers",
"Roe",
"Rogers",
"Rogerson",
"Rohan",
"Roland",
"Ronan",
"Ronayne",
"Rooney",
"Rose",
"Ross",
"Rourke",
"Rowan",
"Rowe",
"Rowley",
"Ruane",
"Rudden",
"Ruddy",
"Rudkins",
"Rush",
"Russell",
"Ryan",
"Ryder",
"Ryle",
"Rynn",
"Rynne",
"Salmon",
"Sammon",
"Saors",
"Sarsfield",
"Sayers",
"Scallan",
"Scallon",
"Scally",
"Scanlan",
"Scanlon",
"Scannell",
"Scollan",
"Scriven",
"Scullion",
"Scully",
"Seally",
"Sealy",
"Sears",
"Seery",
"Segerson",
"Segersun",
"Setrick",
"Sexton",
"Shaffrey",
"Shanahan",
"Shanley",
"Shannon",
"Shanny",
"Sharkey",
"Sharpe",
"Sharry",
"Shaughnessy",
"Shea",
"Sheahan",
"Sheane",
"Sheedy",
"Sheehan",
"Sheehy",
"Sheeran",
"Sheerin",
"Sheil",
"Sheilds",
"Sheridan",
"Sherlock",
"Sherry",
"Shevlin",
"Shiel",
"Shields",
"Shiels",
"Shine",
"Short",
"Shortt",
"Sigerson",
"Silk",
"Silke",
"Simmon",
"Simmonds",
"Simmons",
"Sinan",
"Sinnott",
"Skally",
"Skeahan",
"Skeffington",
"Skehan",
"Skelly",
"Skivington",
"Slamon",
"Slattery",
"Slevin",
"Sloan",
"Sloane",
"Slowey",
"Slyne",
"Small",
"Smith",
"Smullen",
"Smyth",
"Smythe",
"Somers",
"Soolaghan",
"Spain",
"Spencer",
"Spenser",
"Spillane",
"Stack",
"Stanton",
"Stapleton",
"Staunton",
"Steed",
"Stenson",
"Stephens",
"Stephenson",
"Steward",
"Stewart",
"Stoices",
"Stokes",
"Stone",
"Storey",
"Story",
"Stuart",
"Sugrue",
"Sullivan",
"Summerville",
"Supple",
"Sweeney",
"Sweeny",
"Swift",
"Swords",
"Synnott",
"Taggart",
"Tangney",
"Tansey",
"Tarpey",
"Taylor",
"Teahan",
"Tehan",
"Ternan",
"Terry",
"Thom",
"Thomas",
"Thompson",
"Thornton",
"Tiernan",
"Tierney",
"Timlin",
"Timoney",
"Timony",
"Tinney",
"Toal",
"Tobin",
"Togher",
"Tohall",
"Tolan",
"Tolin",
"Toms",
"Toner",
"Toolan",
"Toole",
"Toolin",
"Toolis",
"Tooman",
"Toomey",
"Tormay",
"Tormey",
"Torpey",
"Torrence",
"Torrens",
"Tracey",
"Tracy",
"Trainor",
"Travers",
"Traynor",
"Treacy",
"Treanor",
"Trenor",
"Troy",
"Tubridy",
"Tully",
"Tuohey",
"Tuohy",
"Turley",
"Tutty",
"Twohey",
"Twohig",
"Twomey",
"Tynan",
"Tyrrell",
"Uniacke",
"Uniaque",
"Vaughan",
"Veale",
"Victory",
"Wade",
"Waldron",
"Wall",
"Wallace",
"Walls",
"Walsh",
"Walshe",
"Walter",
"Walters",
"Ward",
"Warren",
"Waters",
"Watters",
"Watts",
"Weaver",
"Weever",
"Weir",
"Weldon",
"Whalen",
"Whelan",
"Whelehan",
"White",
"Whitty",
"Whyte",
"Wilkins",
"Wilkinson",
"Williams",
"Wilson",
"Winters",
"Wolfe",
"Woods",
"Woolley",
"Woulfe",
"Wren",
"Wrenn",
"Wright",
"Wrynn",
"Wynne",
"Young",
"de Courcey",
"de Lacy",
"Ó Corra",
)
prefixes_female = ("Mrs.", "Ms.", "Miss", "Dr.")
prefixes_male = ("Mr.", "Dr.")
| Provider |
python | ray-project__ray | python/ray/serve/_private/usage.py | {
"start": 130,
"end": 2580
} | class ____(Enum):
API_VERSION = TagKey.SERVE_API_VERSION
NUM_DEPLOYMENTS = TagKey.SERVE_NUM_DEPLOYMENTS
GCS_STORAGE = TagKey.GCS_STORAGE
NUM_GPU_DEPLOYMENTS = TagKey.SERVE_NUM_GPU_DEPLOYMENTS
FASTAPI_USED = TagKey.SERVE_FASTAPI_USED
DAG_DRIVER_USED = TagKey.SERVE_DAG_DRIVER_USED
HTTP_ADAPTER_USED = TagKey.SERVE_HTTP_ADAPTER_USED
GRPC_INGRESS_USED = TagKey.SERVE_GRPC_INGRESS_USED
REST_API_VERSION = TagKey.SERVE_REST_API_VERSION
NUM_APPS = TagKey.SERVE_NUM_APPS
NUM_REPLICAS_LIGHTWEIGHT_UPDATED = TagKey.SERVE_NUM_REPLICAS_LIGHTWEIGHT_UPDATED
USER_CONFIG_LIGHTWEIGHT_UPDATED = TagKey.SERVE_USER_CONFIG_LIGHTWEIGHT_UPDATED
AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED = (
TagKey.SERVE_AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED
)
DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_DEPLOYMENT_HANDLE_API_USED
DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED = (
TagKey.SERVE_DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED
)
MULTIPLEXED_API_USED = TagKey.SERVE_MULTIPLEXED_API_USED
HTTP_PROXY_USED = TagKey.SERVE_HTTP_PROXY_USED
GRPC_PROXY_USED = TagKey.SERVE_GRPC_PROXY_USED
SERVE_STATUS_API_USED = TagKey.SERVE_STATUS_API_USED
SERVE_GET_APP_HANDLE_API_USED = TagKey.SERVE_GET_APP_HANDLE_API_USED
SERVE_GET_DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_GET_DEPLOYMENT_HANDLE_API_USED
APP_CONTAINER_RUNTIME_ENV_USED = TagKey.SERVE_APP_CONTAINER_RUNTIME_ENV_USED
DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED = (
TagKey.SERVE_DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED
)
NUM_NODE_COMPACTIONS = TagKey.SERVE_NUM_NODE_COMPACTIONS
AUTO_NUM_REPLICAS_USED = TagKey.SERVE_AUTO_NUM_REPLICAS_USED
CUSTOM_REQUEST_ROUTER_USED = TagKey.SERVE_CUSTOM_REQUEST_ROUTER_USED
NUM_REPLICAS_VIA_API_CALL_UPDATED = TagKey.SERVE_NUM_REPLICAS_VIA_API_CALL_UPDATED
NUM_REPLICAS_USING_ASYNCHRONOUS_INFERENCE = (
TagKey.SERVE_NUM_REPLICAS_USING_ASYNCHRONOUS_INFERENCE
)
CUSTOM_AUTOSCALING_POLICY_USED = TagKey.SERVE_CUSTOM_AUTOSCALING_POLICY_USED
def record(self, value: str):
"""Record telemetry value."""
record_extra_usage_tag(self.value, value)
def get_value_from_report(self, report: Dict) -> Optional[str]:
"""Returns `None` if the tag isn't in the report."""
if "extra_usage_tags" not in report:
return None
return report["extra_usage_tags"].get(TagKey.Name(self.value).lower(), None)
| ServeUsageTag |
python | tensorflow__tensorflow | tensorflow/python/distribute/integration_test/mwms_peer_failure_test.py | {
"start": 1955,
"end": 5682
} | class ____(test.TestCase):
# Note that all the tests use auto_restart=True. Currently we rely on the
# assumption that an external system restarts failed tasks. If the assumption
# is not true, the remaining tasks may still hang instead of fail.
#
# In these tests we leverage the auto restart feature of MultiProcessRunner.
# Failed workers are restarted automatically. In reality there needs to be
# some job management system that does the restart, e.g. Kubernetes.
#
# Worker failures may cause problems if there're more than one collective, and
# the failure happens after the first collective. In this case the recovered
# worker will be running a different collective with the rest, which causes a
# deadlock. Note that collectives are common, e.g. when creating variables the
# initial values are broadcasted from the first worker.
#
# We use a multiprocessing.Manager().dict() object to track the attempts of
# each worker. We take different actions in different attempts to simuate the
# events in real world. E.g. some tests make a worker fail on the first
# attempt only, and asserts that it should recovery.
def test_creating_variable(self):
# This test simulates the case when a worker fails before or during creating
# a variable. Creating variables involve broadcasting the initial value from
# the first replica to all replicas.
def worker_fn():
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
with strategy.scope():
tf.Variable(1.)
# worker-1 dies here.
if strategy.cluster_resolver.task_id == 1:
quick_exit(1)
v = tf.Variable(tf.random.uniform(()))
return v.read_value().numpy()
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
mpr = multi_process_runner.MultiProcessRunner(
worker_fn, cluster_spec, rpc_layer=RPC_PROTOCOL)
mpr.start()
# TODO(b/151232436): Always raise UnavailableError when a peer fails.
with self.assertRaises(
(tf.errors.UnavailableError, tf.errors.DeadlineExceededError)):
mpr.join(timeout=60)
def test_reduce_small_tensor(self):
# This test simulates the case when a worker fails before or during reducing
# a small tensors, e.g. reading a metric.
#
# Note that this is written for a specific corner case that used to happen
# only when all of the following conditions are met:
# - There're two workers.
# - They're reducing a small tensor. The definition of small varies
# per platform.
# - They're reducing a single tensor. Batched all-reduce are not affected.
# - It must be worker-1 that fails.
# Under this case, the all-reduce is effectively two send/recv operation,
# the first one from worker-0 to worker-1, and the second one vice versa.
# The first one blocks the second one. In send/recv, the sending party is
# not aware of the failures of the receiving party.
def worker_fn():
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
value = tf.identity([1.])
strategy.reduce("sum", value, axis=None)
# worker-1 dies here.
if strategy.cluster_resolver.task_id == 1:
quick_exit(1)
strategy.reduce("sum", value, axis=None)
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
mpr = multi_process_runner.MultiProcessRunner(
worker_fn, cluster_spec, rpc_layer=RPC_PROTOCOL)
mpr.start()
# TODO(b/151232436): Always raise UnavailableError when a peer fails.
with self.assertRaises(
(tf.errors.UnavailableError, tf.errors.DeadlineExceededError)):
mpr.join(timeout=60)
| PeerFailureTest |
python | mlflow__mlflow | tests/dev/test_remove_experimental_decorators.py | {
"start": 1743,
"end": 2131
} | class ____:
@experimental(version="1.2.0")
def method(self):
pass
def regular_func():
pass
""")
output = subprocess.check_output([sys.executable, SCRIPT_PATH, test_file], text=True)
assert output.count("Removed") == 3 # Should remove all 3 decorators
content = test_file.read_text()
assert (
content
== """
def func1():
pass
| MyClass |
python | geekcomputers__Python | Checker_game_by_dz/modules/checker_board.py | {
"start": 128,
"end": 5492
} | class ____:
def __init__(self):
self.board = []
self.selected = None
self.black_l = self.white_l = 12
self.black_k = self.white_k = 0
self.create_board()
# to design the board
def draw_cubes(self, window):
window.fill(green)
for row in range(rows):
for col in range(row % 2, cols, 2):
pg.draw.rect(
window, yellow, (row * sq_size, col * sq_size, sq_size, sq_size)
)
def move(self, piece, row, col):
self.board[piece.row][piece.col], self.board[row][col] = (
self.board[row][col],
self.board[piece.row][piece.col],
)
piece.move(row, col)
if row == rows - 1 or row == 0:
piece.make_king()
if piece.color == white:
self.white_k += 1
else:
self.black_k += 1
# to get piece whatever they want
def get_piece(self, row, col):
return self.board[row][col]
def create_board(self):
for row in range(rows):
self.board.append([])
for col in range(cols):
if col % 2 == ((row + 1) % 2):
if row < 3:
self.board[row].append(pieces(row, col, white))
elif row > 4:
self.board[row].append(pieces(row, col, black))
else:
self.board[row].append(0)
else:
self.board[row].append(0)
def draw(self, window):
self.draw_cubes(window)
for row in range(rows):
for col in range(cols):
piece = self.board[row][col]
if piece != 0:
piece.draw(window)
def get_valid_moves(self, piece):
moves = {}
l = piece.col - 1
r = piece.col + 1
row = piece.row
if piece.color == black or piece.king:
moves.update(
self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l)
)
moves.update(
self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r)
)
if piece.color == white or piece.king:
moves.update(
self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l)
)
moves.update(
self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r)
)
return moves
def remove(self, pieces):
for piece in pieces:
self.board[piece.row][piece.col] = 0
if piece != 0:
if piece.color == black:
self.black_l -= 1
else:
self.white_l -= 1
def winner(self):
if self.black_l <= 0:
return white
elif self.white_l <= 0:
return black
return None
# Traversal Left
def _traverse_l(self, start, stop, step, color, l, skip=[]):
moves = {}
last = []
for r in range(start, stop, step):
if l < 0:
break
current = self.board[r][l]
if current == 0:
if skip and not last:
break
elif skip:
moves[(r, l)] = last + skip
else:
moves[(r, l)] = last
if last:
if step == -1:
row = max(r - 3, 0)
else:
row = min(r + 3, rows)
moves.update(
self._traverse_l(r + step, row, step, color, l - 1, skip=last)
)
moves.update(
self._traverse_r(r + step, row, step, color, l + 1, skip=last)
)
break
elif current.color == color:
break
else:
last = [current]
l -= 1
return moves
# Traversal Right
def _traverse_r(self, start, stop, step, color, right, skip=[]):
moves = {}
last = []
for r in range(start, stop, step):
if right >= cols:
break
current = self.board[r][right]
if current == 0:
if skip and not last:
break
elif skip:
moves[(r, right)] = last + skip
else:
moves[(r, right)] = last
if last:
if step == -1:
row = max(r - 3, 0)
else:
row = min(r + 3, rows)
moves.update(
self._traverse_l(
r + step, row, step, color, right - 1, skip=last
)
)
moves.update(
self._traverse_r(
r + step, row, step, color, right + 1, skip=last
)
)
break
elif current.color == color:
break
else:
last = [current]
right += 1
return moves
| checker_board |
python | pyqtgraph__pyqtgraph | pyqtgraph/exporters/HDF5Exporter.py | {
"start": 293,
"end": 2570
} | class ____(Exporter):
Name = "HDF5 Export: plot (x,y)"
windows = []
allowCopy = False
def __init__(self, item):
Exporter.__init__(self, item)
self.params = Parameter.create(name='params', type='group', children=[
{'name': 'Name', 'title': translate("Exporter", 'Name'), 'type': 'str', 'value': 'Export', },
{'name': 'columnMode', 'title': translate("Exporter", 'columnMode'), 'type': 'list',
'limits': ['(x,y) per plot', '(x,y,y,y) for all plots'], 'value': '(x,y) per plot'},
])
def parameters(self):
return self.params
def export(self, fileName=None):
if not HAVE_HDF5:
raise RuntimeError("This exporter requires the h5py package, "
"but it was not importable.")
import h5py
if not isinstance(self.item, PlotItem):
raise Exception("Must have a PlotItem selected for HDF5 export.")
if fileName is None:
self.fileSaveDialog(filter=["*.h5", "*.hdf", "*.hd5"])
return
dsname = self.params['Name']
fd = h5py.File(fileName, 'a') # forces append to file... 'w' doesn't seem to "delete/overwrite"
data = []
appendAllX = self.params['columnMode'] == '(x,y) per plot'
# Check if the arrays are ragged
len_first = len(self.item.curves[0].getData()[0]) if self.item.curves[0] else None
ragged = any(len(i.getData()[0]) != len_first for i in self.item.curves)
if ragged:
dgroup = fd.create_group(dsname)
for i, c in enumerate(self.item.curves):
d = c.getData()
fdata = numpy.array([d[0], d[1]]).astype('double')
cname = c.name() if c.name() is not None else str(i)
dgroup.create_dataset(cname, data=fdata)
else:
for i, c in enumerate(self.item.curves):
d = c.getData()
if appendAllX or i == 0:
data.append(d[0])
data.append(d[1])
fdata = numpy.array(data).astype('double')
fd.create_dataset(dsname, data=fdata)
fd.close()
if HAVE_HDF5:
HDF5Exporter.register()
| HDF5Exporter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/loop18.py | {
"start": 203,
"end": 542
} | class ____: ...
def foo(v: A | B | None) -> Generator[A, None, None]:
reveal_type(v)
if not isinstance(v, B):
reveal_type(v, expected_text="A | None")
while v is not None:
reveal_type(v, expected_text="A")
yield v
v = v.parent
reveal_type(v, expected_text="A | None")
| B |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 1974,
"end": 2499
} | class ____(
mixins.NodeDetailMixin, mixins.NodeUndoMixin, mixins.NodeReviveMixin, nodes.End
):
"""
The ``End`` node in a flow.
This node serves as the terminal point of a flow
.. code-block:: python
class MyFlow(flow.Flow):
...
approved = this.End()
rejected = this.End()
"""
index_view_class = views.IndexTaskView
detail_view_class = views.DetailTaskView
undo_view_class = views.UndoTaskView
revive_view_class = views.ReviveTaskView
| End |
python | walkccc__LeetCode | solutions/2229. Check if an Array Is Consecutive/2229.py | {
"start": 0,
"end": 136
} | class ____:
def isConsecutive(self, nums: list[int]) -> bool:
return max(nums) - min(nums) + 1 == len(set(nums)) == len(nums)
| Solution |
python | gawel__pyquery | tests/test_pyquery.py | {
"start": 13541,
"end": 21867
} | class ____(TestCase):
html = '''
<div class="portlet">
<a href="/toto">Test<img src ="myimage" />My link text</a>
<a href="/toto2"><img src ="myimage2" />My link text 2</a>
</div>
'''
html2 = '''
<input name="spam" value="Spam">
<input name="eggs" value="Eggs">
<input type="checkbox" value="Bacon">
<input type="radio" value="Ham">
'''
html2_newline = '''
<input id="newline-text" type="text" name="order" value="S
pam">
<input id="newline-radio" type="radio" name="order" value="S
pam">
'''
html3 = '''
<textarea id="textarea-single">Spam</textarea>
<textarea id="textarea-multi">Spam
<b>Eggs</b>
Bacon</textarea>
'''
html4 = '''
<select id="first">
<option value="spam">Spam</option>
<option value="eggs">Eggs</option>
</select>
<select id="second">
<option value="spam">Spam</option>
<option value="eggs" selected>Eggs</option>
<option value="bacon">Bacon</option>
</select>
<select id="third">
</select>
<select id="fourth">
<option value="spam">Spam</option>
<option value="spam">Eggs</option>
<option value="spam">Bacon</option>
</select>
'''
html6 = '''
<select id="first" multiple>
<option value="spam" selected>Spam</option>
<option value="eggs" selected>Eggs</option>
<option value="bacon">Bacon</option>
</select>
<select id="second" multiple>
<option value="spam">Spam</option>
<option value="eggs">Eggs</option>
<option value="bacon">Bacon</option>
</select>
<select id="third" multiple>
<option value="spam">Spam</option>
<option value="spam">Eggs</option>
<option value="spam">Bacon</option>
</select>
'''
html5 = '''
<div>
<input id="first" value="spam">
<input id="second" value="eggs">
<textarea id="third">bacon</textarea>
</div>
'''
def test_attr_empty_string(self):
d = pq('<div>')
d.attr('value', '')
self.assertEqual(d.outer_html(), '<div value=""></div>')
self.assertEqual(d.outer_html(method="xml"), '<div value=""/>')
def test_remove(self):
d = pq(self.html)
d('img').remove()
val = d('a:first').html()
assert val == 'TestMy link text', repr(val)
val = d('a:last').html()
assert val == 'My link text 2', repr(val)
def test_class(self):
d = pq('<div></div>')
d.removeClass('xx')
assert 'class' not in str(d), str(d)
def test_val_for_inputs(self):
d = pq(self.html2)
self.assertIsNone(d('input[name="none"]').val())
self.assertEqual(d('input[name="spam"]').val(), 'Spam')
self.assertEqual(d('input[name="eggs"]').val(), 'Eggs')
self.assertEqual(d('input:checkbox').val(), 'Bacon')
self.assertEqual(d('input:radio').val(), 'Ham')
d('input[name="spam"]').val('42')
d('input[name="eggs"]').val('43')
d('input:checkbox').val('44')
d('input:radio').val('45')
self.assertEqual(d('input[name="spam"]').val(), '42')
self.assertEqual(d('input[name="eggs"]').val(), '43')
self.assertEqual(d('input:checkbox').val(), '44')
self.assertEqual(d('input:radio').val(), '45')
def test_val_for_inputs_with_newline(self):
d = pq(self.html2_newline)
self.assertEqual(d('#newline-text').val(), 'Spam')
self.assertEqual(d('#newline-radio').val(), 'S\npam')
def test_val_for_textarea(self):
d = pq(self.html3)
self.assertEqual(d('#textarea-single').val(), 'Spam')
self.assertEqual(d('#textarea-single').text(), 'Spam')
d('#textarea-single').val('42')
self.assertEqual(d('#textarea-single').val(), '42')
# Note: jQuery still returns 'Spam' here.
self.assertEqual(d('#textarea-single').text(), '42')
multi_expected = '''Spam\n<b>Eggs</b>\nBacon'''
self.assertEqual(d('#textarea-multi').val(), multi_expected)
self.assertEqual(d('#textarea-multi').text(), multi_expected)
multi_new = '''Bacon\n<b>Eggs</b>\nSpam'''
multi_new_expected = '''Bacon\n<b>Eggs</b>\nSpam'''
d('#textarea-multi').val(multi_new)
self.assertEqual(d('#textarea-multi').val(), multi_new_expected)
self.assertEqual(d('#textarea-multi').text(), multi_new_expected)
def test_val_for_select(self):
d = pq(self.html4)
self.assertEqual(d('#first').val(), 'spam')
self.assertEqual(d('#second').val(), 'eggs')
self.assertIsNone(d('#third').val())
d('#first').val('eggs')
d('#second').val('bacon')
d('#third').val('eggs') # Selecting non-existing option.
self.assertEqual(d('#first').val(), 'eggs')
self.assertEqual(d('#second').val(), 'bacon')
self.assertIsNone(d('#third').val())
d('#first').val('bacon') # Selecting non-existing option.
self.assertEqual(d('#first').val(), 'spam')
# Value set based on option order, not value order
d('#second').val(['bacon', 'eggs'])
self.assertEqual(d('#second').val(), 'eggs')
d('#fourth').val(['spam'])
self.assertEqual(d('#fourth').val(), 'spam')
# Sets first option with matching value
self.assertEqual(d('#fourth option[selected]').length, 1)
self.assertEqual(d('#fourth option[selected]').text(), 'Spam')
def test_val_for_select_multiple(self):
d = pq(self.html6)
self.assertEqual(d('#first').val(), ['spam', 'eggs'])
# Selecting non-existing option.
d('#first').val(['eggs', 'sausage', 'bacon'])
self.assertEqual(d('#first').val(), ['eggs', 'bacon'])
self.assertEqual(d('#second').val(), [])
d('#second').val('eggs')
self.assertEqual(d('#second').val(), ['eggs'])
d('#second').val(['not spam', 'not eggs'])
self.assertEqual(d('#second').val(), [])
d('#third').val(['spam'])
self.assertEqual(d('#third').val(), ['spam', 'spam', 'spam'])
def test_val_for_input_and_textarea_given_array_value(self):
d = pq('<input type="text">')
d('input').val(['spam', 'eggs'])
self.assertEqual(d('input').val(), 'spam,eggs')
d = pq('<textarea></textarea>')
d('textarea').val(['spam', 'eggs'])
self.assertEqual(d('textarea').val(), 'spam,eggs')
def test_val_for_multiple_elements(self):
d = pq(self.html5)
# "Get" returns *first* value.
self.assertEqual(d('div > *').val(), 'spam')
# "Set" updates *every* value.
d('div > *').val('42')
self.assertEqual(d('#first').val(), '42')
self.assertEqual(d('#second').val(), '42')
self.assertEqual(d('#third').val(), '42')
def test_val_checkbox_no_value_attribute(self):
d = pq('<input type="checkbox">')
self.assertEqual(d.val(), 'on')
d = pq('<input type="checkbox" value="">')
self.assertEqual(d.val(), '')
def test_val_radio_no_value_attribute(self):
d = pq('<input type="radio">')
self.assertEqual(d.val(), 'on')
def test_val_value_is_empty_string(self):
d = pq('<input value="">')
self.assertEqual(d.val(), '')
def test_val_input_has_no_value_attr(self):
d = pq('<input>')
self.assertEqual(d.val(), '')
def test_html_replacement(self):
html = '<div>Not Me<span>Replace Me</span>Not Me</div>'
replacement = 'New <em>Contents</em> New'
expected = html.replace('Replace Me', replacement)
d = pq(html)
d.find('span').html(replacement)
new_html = d.outerHtml()
self.assertEqual(new_html, expected)
self.assertIn(replacement, new_html)
def test_html_escape(self):
inner_html = 'encoded <script> tag with "quotes".' \
'<span>nested <tag></span>'
html = '<div>' + inner_html + '</div>'
d = pq(html)
self.assertEqual(d.html(), inner_html)
| TestManipulating |
python | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 108962,
"end": 111358
} | class ____(Locator):
"""
Place evenly spaced minor ticks, with the step size and maximum number of ticks
chosen automatically.
The Axis must use a linear scale and have evenly spaced major ticks.
"""
def __init__(self, n=None):
"""
Parameters
----------
n : int or 'auto', default: :rc:`xtick.minor.ndivs` or :rc:`ytick.minor.ndivs`
The number of subdivisions of the interval between major ticks;
e.g., n=2 will place a single minor tick midway between major ticks.
If *n* is 'auto', it will be set to 4 or 5: if the distance
between the major ticks equals 1, 2.5, 5 or 10 it can be perfectly
divided in 5 equidistant sub-intervals with a length multiple of
0.05; otherwise, it is divided in 4 sub-intervals.
"""
self.ndivs = n
def __call__(self):
# docstring inherited
if self.axis.get_scale() == 'log':
_api.warn_external('AutoMinorLocator does not work on logarithmic scales')
return []
majorlocs = np.unique(self.axis.get_majorticklocs())
if len(majorlocs) < 2:
# Need at least two major ticks to find minor tick locations.
# TODO: Figure out a way to still be able to display minor ticks with less
# than two major ticks visible. For now, just display no ticks at all.
return []
majorstep = majorlocs[1] - majorlocs[0]
if self.ndivs is None:
self.ndivs = mpl.rcParams[
'ytick.minor.ndivs' if self.axis.axis_name == 'y'
else 'xtick.minor.ndivs'] # for x and z axis
if self.ndivs == 'auto':
majorstep_mantissa = 10 ** (np.log10(majorstep) % 1)
ndivs = 5 if np.isclose(majorstep_mantissa, [1, 2.5, 5, 10]).any() else 4
else:
ndivs = self.ndivs
minorstep = majorstep / ndivs
vmin, vmax = sorted(self.axis.get_view_interval())
t0 = majorlocs[0]
tmin = round((vmin - t0) / minorstep)
tmax = round((vmax - t0) / minorstep) + 1
locs = (np.arange(tmin, tmax) * minorstep) + t0
return self.raise_if_exceeds(locs)
def tick_values(self, vmin, vmax):
raise NotImplementedError(
f"Cannot get tick locations for a {type(self).__name__}")
| AutoMinorLocator |
python | doocs__leetcode | solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/Solution.py | {
"start": 0,
"end": 422
} | class ____:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [1] * n
f = [-1] * 32
for i in range(n - 1, -1, -1):
t = 1
for j in range(32):
if (nums[i] >> j) & 1:
f[j] = i
elif f[j] != -1:
t = max(t, f[j] - i + 1)
ans[i] = t
return ans
| Solution |
python | ansible__ansible | lib/ansible/module_utils/_internal/_messages.py | {
"start": 2120,
"end": 2929
} | class ____(_datatag.AnsibleSerializableDataclass):
"""Base class for an error/warning/deprecation event with optional chain (from an exception __cause__ chain) and an optional traceback."""
_validation_auto_enabled = False
def __post_init__(self): ... # required for deferred dataclass validation
msg: str
formatted_source_context: _t.Optional[str] = None
formatted_traceback: _t.Optional[str] = None
help_text: _t.Optional[str] = None
chain: _t.Optional[EventChain] = None
events: _t.Optional[_t.Tuple[Event, ...]] = None
_dataclass_validation.inject_post_init_validation(EventChain, EventChain._validation_allow_subclasses)
_dataclass_validation.inject_post_init_validation(Event, Event._validation_allow_subclasses)
@_dataclasses.dataclass(**_dataclass_kwargs)
| Event |
python | wandb__wandb | wandb/sync/sync.py | {
"start": 1036,
"end": 12499
} | class ____(threading.Thread):
def __init__(
self,
sync_list,
project=None,
entity=None,
run_id=None,
job_type=None,
view=None,
verbose=None,
mark_synced=None,
app_url=None,
sync_tensorboard=None,
log_path=None,
append=None,
skip_console=None,
replace_tags=None,
):
threading.Thread.__init__(self)
self._sync_list = sync_list
self._project = project
self._entity = entity
self._run_id = run_id
self._job_type = job_type
self._view = view
self._verbose = verbose
self._mark_synced = mark_synced
self._app_url = app_url
self._sync_tensorboard = sync_tensorboard
self._log_path = log_path
self._append = append
self._skip_console = skip_console
self._replace_tags = replace_tags or {}
self._tmp_dir = tempfile.TemporaryDirectory()
atexit.register(self._tmp_dir.cleanup)
def _parse_pb(self, data, exit_pb=None):
pb = wandb_internal_pb2.Record()
pb.ParseFromString(data)
record_type = pb.WhichOneof("record_type")
if self._view:
if self._verbose:
print("Record:", pb) # noqa: T201
else:
print("Record:", record_type) # noqa: T201
return pb, exit_pb, True
if record_type == "run":
if self._run_id:
pb.run.run_id = self._run_id
if self._project:
pb.run.project = self._project
if self._entity:
pb.run.entity = self._entity
if self._job_type:
pb.run.job_type = self._job_type
# Replace tags if specified
if self._replace_tags:
new_tags = [self._replace_tags.get(tag, tag) for tag in pb.run.tags]
pb.run.ClearField("tags")
pb.run.tags.extend(new_tags)
pb.control.req_resp = True
elif record_type in ("output", "output_raw") and self._skip_console:
return pb, exit_pb, True
elif record_type == "exit":
exit_pb = pb
return pb, exit_pb, True
elif record_type == "final":
assert exit_pb, "final seen without exit"
pb = exit_pb
exit_pb = None
return pb, exit_pb, False
def _find_tfevent_files(self, sync_item):
tb_event_files = 0
tb_logdirs = []
tb_root = None
if self._sync_tensorboard:
if os.path.isdir(sync_item):
files = []
for dirpath, _, _files in os.walk(sync_item):
for f in _files:
if TFEVENT_SUBSTRING in f:
files.append(os.path.join(dirpath, f))
for tfevent in files:
tb_event_files += 1
tb_dir = os.path.dirname(os.path.abspath(tfevent))
if tb_dir not in tb_logdirs:
tb_logdirs.append(tb_dir)
if len(tb_logdirs) > 0:
tb_root = os.path.dirname(os.path.commonprefix(tb_logdirs))
elif TFEVENT_SUBSTRING in sync_item:
tb_root = os.path.dirname(os.path.abspath(sync_item))
tb_logdirs.append(tb_root)
tb_event_files = 1
return tb_event_files, tb_logdirs, tb_root
def _setup_tensorboard(self, tb_root, tb_logdirs, tb_event_files, sync_item):
"""Return true if this sync item can be synced as tensorboard."""
if tb_root is not None:
if tb_event_files > 0 and sync_item.endswith(WANDB_SUFFIX):
wandb.termwarn("Found .wandb file, not streaming tensorboard metrics.")
else:
print(f"Found {tb_event_files} tfevent files in {tb_root}") # noqa: T201
if len(tb_logdirs) > 3:
wandb.termwarn(
f"Found {len(tb_logdirs)} directories containing tfevent files. "
"If these represent multiple experiments, sync them "
"individually or pass a list of paths."
)
return True
return False
def _send_tensorboard(self, tb_root, tb_logdirs, send_manager):
if self._entity is None:
viewer, _ = send_manager._api.viewer_server_info()
self._entity = viewer.get("entity")
proto_run = wandb_internal_pb2.RunRecord()
proto_run.run_id = self._run_id or wandb.util.generate_id()
proto_run.project = self._project or wandb.util.auto_project_name(None)
proto_run.entity = self._entity
proto_run.telemetry.feature.sync_tfevents = True
url = (
f"{self._app_url}"
f"/{url_quote(proto_run.entity)}"
f"/{url_quote(proto_run.project)}"
f"/runs/{url_quote(proto_run.run_id)}"
)
print(f"Syncing: {url} ...") # noqa: T201
sys.stdout.flush()
# using a handler here automatically handles the step
# logic, adds summaries to the run, and handles different
# file types (like images)... but we need to remake the send_manager
record_q = queue.Queue()
sender_record_q = queue.Queue()
new_interface = InterfaceQueue(record_q)
context_keeper = context.ContextKeeper()
send_manager = sender.SendManager(
settings=send_manager._settings,
record_q=sender_record_q,
result_q=queue.Queue(),
interface=new_interface,
context_keeper=context_keeper,
)
record = send_manager._interface._make_record(run=proto_run)
settings = wandb.Settings(
root_dir=self._tmp_dir.name,
run_id=proto_run.run_id,
x_start_time=time.time(),
)
settings_static = SettingsStatic(dict(settings))
handle_manager = handler.HandleManager(
settings=settings_static,
record_q=record_q,
result_q=None,
stopped=False,
writer_q=sender_record_q,
interface=new_interface,
context_keeper=context_keeper,
)
filesystem.mkdir_exists_ok(settings.files_dir)
send_manager.send_run(record, file_dir=settings.files_dir)
watcher = tb_watcher.TBWatcher(
settings_static,
proto_run,
new_interface,
True,
)
for tb in tb_logdirs:
watcher.add(tb, True, tb_root)
sys.stdout.flush()
watcher.finish()
# send all of our records like a boss
progress_step = 0
spinner_states = ["-", "\\", "|", "/"]
line = " Uploading data to wandb\r"
while len(handle_manager) > 0:
data = next(handle_manager)
handle_manager.handle(data)
while len(send_manager) > 0:
data = next(send_manager)
send_manager.send(data)
print_line = spinner_states[progress_step % 4] + line
wandb.termlog(print_line, newline=False, prefix=True)
progress_step += 1
# finish sending any data
while len(send_manager) > 0:
data = next(send_manager)
send_manager.send(data)
sys.stdout.flush()
handle_manager.finish()
send_manager.finish()
def _robust_scan(self, ds):
"""Attempt to scan data, handling incomplete files."""
try:
return ds.scan_data()
except AssertionError as e:
if ds.in_last_block():
wandb.termwarn(
f".wandb file is incomplete ({e}), be sure to sync this run again once it's finished"
)
return None
else:
raise
def run(self):
if self._log_path is not None:
print(f"Find logs at: {self._log_path}") # noqa: T201
for sync_item in self._sync_list:
tb_event_files, tb_logdirs, tb_root = self._find_tfevent_files(sync_item)
if os.path.isdir(sync_item):
files = os.listdir(sync_item)
filtered_files = list(filter(lambda f: f.endswith(WANDB_SUFFIX), files))
if tb_root is None and (
check_and_warn_old(files) or len(filtered_files) != 1
):
print(f"Skipping directory: {sync_item}") # noqa: T201
continue
if len(filtered_files) > 0:
sync_item = os.path.join(sync_item, filtered_files[0])
sync_tb = self._setup_tensorboard(
tb_root, tb_logdirs, tb_event_files, sync_item
)
# If we're syncing tensorboard, let's use a tmp dir for images etc.
root_dir = self._tmp_dir.name if sync_tb else os.path.dirname(sync_item)
# When appending we are allowing a possible resume, ie the run
# does not have to exist already
resume = "allow" if self._append else None
sm = sender.SendManager.setup(root_dir, resume=resume)
if sync_tb:
self._send_tensorboard(tb_root, tb_logdirs, sm)
continue
ds = datastore.DataStore()
try:
ds.open_for_scan(sync_item)
except AssertionError as e:
print(f".wandb file is empty ({e}), skipping: {sync_item}") # noqa: T201
continue
# save exit for final send
exit_pb = None
finished = False
shown = False
while True:
data = self._robust_scan(ds)
if data is None:
break
pb, exit_pb, cont = self._parse_pb(data, exit_pb)
if exit_pb is not None:
finished = True
if cont:
continue
sm.send(pb)
# send any records that were added in previous send
while not sm._record_q.empty():
data = sm._record_q.get(block=True)
sm.send(data)
if pb.control.req_resp:
result = sm._result_q.get(block=True)
result_type = result.WhichOneof("result_type")
if not shown and result_type == "run_result":
r = result.run_result.run
# TODO(jhr): hardcode until we have settings in sync
url = (
f"{self._app_url}"
f"/{url_quote(r.entity)}"
f"/{url_quote(r.project)}"
f"/runs/{url_quote(r.run_id)}"
)
print(f"Syncing: {url} ... ", end="") # noqa: T201
sys.stdout.flush()
shown = True
sm.finish()
# Only mark synced if the run actually finished
if self._mark_synced and not self._view and finished:
synced_file = f"{sync_item}{SYNCED_SUFFIX}"
with open(synced_file, "w"):
pass
print("done.") # noqa: T201
| SyncThread |
python | google__flatbuffers | python/flatbuffers/reflection/RPCCall.py | {
"start": 179,
"end": 5074
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = RPCCall()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsRPCCall(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
@classmethod
def RPCCallBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x42\x46\x42\x53", size_prefixed=size_prefixed)
# RPCCall
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# RPCCall
def Name(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.String(o + self._tab.Pos)
return None
# RPCCall
def Request(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from reflection.Object import Object
obj = Object()
obj.Init(self._tab.Bytes, x)
return obj
return None
# RPCCall
def Response(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from reflection.Object import Object
obj = Object()
obj.Init(self._tab.Bytes, x)
return obj
return None
# RPCCall
def Attributes(self, j):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
if o != 0:
x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x)
from reflection.KeyValue import KeyValue
obj = KeyValue()
obj.Init(self._tab.Bytes, x)
return obj
return None
# RPCCall
def AttributesLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
if o != 0:
return self._tab.VectorLen(o)
return 0
# RPCCall
def AttributesIsNone(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
return o == 0
# RPCCall
def Documentation(self, j):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
if o != 0:
a = self._tab.Vector(o)
return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
return ""
# RPCCall
def DocumentationLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
if o != 0:
return self._tab.VectorLen(o)
return 0
# RPCCall
def DocumentationIsNone(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
return o == 0
def RPCCallStart(builder):
builder.StartObject(5)
def Start(builder):
RPCCallStart(builder)
def RPCCallAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder, name):
RPCCallAddName(builder, name)
def RPCCallAddRequest(builder, request):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(request), 0)
def AddRequest(builder, request):
RPCCallAddRequest(builder, request)
def RPCCallAddResponse(builder, response):
builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(response), 0)
def AddResponse(builder, response):
RPCCallAddResponse(builder, response)
def RPCCallAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder, attributes):
RPCCallAddAttributes(builder, attributes)
def RPCCallStartAttributesVector(builder, numElems):
return builder.StartVector(4, numElems, 4)
def StartAttributesVector(builder, numElems):
return RPCCallStartAttributesVector(builder, numElems)
def RPCCallAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder, documentation):
RPCCallAddDocumentation(builder, documentation)
def RPCCallStartDocumentationVector(builder, numElems):
return builder.StartVector(4, numElems, 4)
def StartDocumentationVector(builder, numElems):
return RPCCallStartDocumentationVector(builder, numElems)
def RPCCallEnd(builder):
return builder.EndObject()
def End(builder):
return RPCCallEnd(builder)
| RPCCall |
python | pyodide__pyodide | src/py/pyodide/http/_pyfetch.py | {
"start": 2174,
"end": 12105
} | class ____:
"""A wrapper for a Javascript fetch :js:data:`Response`.
Parameters
----------
url
URL that was fetched
js_response
A :py:class:`~pyodide.ffi.JsProxy` of the fetch :js:class:`Response`.
abort_controller
The abort controller that may be used to cancel the fetch request.
abort_signal
The abort signal that was used for the fetch request.
"""
js_request: "Request"
js_response: JsFetchResponse
_url: str
abort_controller: "AbortController | None"
abort_signal: "AbortSignal | None"
def __init__(
self,
request: "str | Request",
js_response: JsFetchResponse,
abort_controller: "AbortController | None" = None,
abort_signal: "AbortSignal | None" = None,
):
if isinstance(request, str):
request = Request.new(request)
self.js_request = request
self._url = self.js_request.url
self.js_response = js_response
self.abort_controller = abort_controller
self.abort_signal = abort_signal
@property
def body_used(self) -> bool:
"""Has the response been used yet?
If so, attempting to retrieve the body again will raise an
:py:exc:`OSError`. Use :py:meth:`~FetchResponse.clone` first to avoid this.
See :js:attr:`Response.bodyUsed`.
"""
return self.js_response.bodyUsed
@property
def headers(self) -> dict[str, str]:
"""Response headers as dictionary."""
return Object.fromEntries(self.js_response.headers.entries()).to_py()
@property
def ok(self) -> bool:
"""Was the request successful?
See :js:attr:`Response.ok`.
"""
return self.js_response.ok
@property
def redirected(self) -> bool:
"""Was the request redirected?
See :js:attr:`Response.redirected`.
"""
return self.js_response.redirected
@property
def status(self) -> int:
"""Response status code
See :js:attr:`Response.status`.
"""
return self.js_response.status
@property
def status_text(self) -> str:
"""Response status text
See :js:attr:`Response.statusText`.
"""
return self.js_response.statusText
@property
def type(self) -> str:
"""The type of the response.
See :js:attr:`Response.type`.
"""
return self.js_response.type
@property
def url(self) -> str:
"""The url of the response.
The value may be different than the url passed to fetch.
See :js:attr:`Response.url`.
"""
return self.js_response.url
def _raise_if_failed(self) -> None:
if (signal := self.abort_signal) and signal.aborted:
raise AbortError(signal.reason)
if self.js_response.bodyUsed:
raise BodyUsedError
def raise_for_status(self) -> None:
"""Raise an :py:exc:`~pyodide.http.HttpStatusError` if the status of the response is an error (4xx or 5xx)"""
if 400 <= self.status < 600:
raise HttpStatusError(self.status, self.status_text, self.url)
def clone(self) -> "FetchResponse":
"""Return an identical copy of the :py:class:`FetchResponse`.
This method exists to allow multiple uses of :py:class:`FetchResponse`
objects. See :js:meth:`Response.clone`.
"""
if self.js_response.bodyUsed:
raise BodyUsedError
return FetchResponse(
self.js_request,
self.js_response.clone(),
self.abort_controller,
self.abort_signal,
)
@_abort_on_cancel
async def buffer(self) -> JsBuffer:
"""Return the response body as a Javascript :js:class:`ArrayBuffer`.
See :js:meth:`Response.arrayBuffer`.
"""
self._raise_if_failed()
return await self.js_response.arrayBuffer()
@_abort_on_cancel
async def text(self) -> str:
"""Return the response body as a string"""
self._raise_if_failed()
return await self.js_response.text()
@_abort_on_cancel
async def string(self) -> str:
"""Return the response body as a string
Does the same thing as :py:meth:`FetchResponse.text`.
.. deprecated:: 0.24.0
Use :py:meth:`FetchResponse.text` instead.
"""
return await self.text()
@_abort_on_cancel
async def json(self, **kwargs: Any) -> Any:
"""Treat the response body as a JSON string and use
:py:func:`json.loads` to parse it into a Python object.
Any keyword arguments are passed to :py:func:`json.loads`.
"""
self._raise_if_failed()
return json.loads(await self.string(), **kwargs)
@_abort_on_cancel
async def memoryview(self) -> memoryview:
"""Return the response body as a :py:class:`memoryview` object"""
self._raise_if_failed()
return (await self.buffer()).to_memoryview()
@_abort_on_cancel
async def _into_file(self, f: IO[bytes] | IO[str]) -> None:
"""Write the data into an empty file with no copy.
Warning: should only be used when f is an empty file, otherwise it may
overwrite the data of f.
"""
buf = await self.buffer()
buf._into_file(f)
@_abort_on_cancel
async def _create_file(self, path: str) -> None:
"""Uses the data to back a new file without copying it.
This method avoids copying the data when creating a new file. If you
want to write the data into an existing file, use
.. code-block:: python
buf = await resp.buffer()
buf.to_file(file)
Parameters
----------
path : str
The path to the file to create. The file should not exist but
it should be in a directory that exists. Otherwise, will raise
an ``OSError``
"""
with open(path, "x") as f:
await self._into_file(f)
@_abort_on_cancel
async def bytes(self) -> bytes:
"""Return the response body as a bytes object"""
self._raise_if_failed()
return (await self.buffer()).to_bytes()
@_abort_on_cancel
async def unpack_archive(
self, *, extract_dir: str | None = None, format: str | None = None
) -> None:
"""Treat the data as an archive and unpack it into target directory.
Assumes that the file is an archive in a format that :py:mod:`shutil` has
an unpacker for. The arguments ``extract_dir`` and ``format`` are passed
directly on to :py:func:`shutil.unpack_archive`.
Parameters
----------
extract_dir :
Directory to extract the archive into. If not provided, the current
working directory is used.
format :
The archive format: one of ``"zip"``, ``"tar"``, ``"gztar"``,
``"bztar"``. Or any other format registered with
:py:func:`shutil.register_unpack_format`. If not provided,
:py:meth:`unpack_archive` will use the archive file name extension and
see if an unpacker was registered for that extension. In case none
is found, a :py:exc:`ValueError` is raised.
"""
buf = await self.buffer()
filename = self._url.rsplit("/", -1)[-1]
unpack_buffer(buf, filename=filename, format=format, extract_dir=extract_dir)
def abort(self, reason: Any = None) -> None:
"""Abort the fetch request.
In case ``abort_controller`` is not set, a :py:exc:`ValueError` is raised.
"""
if self.abort_controller is None:
raise ValueError("abort_controller is not set")
self.abort_controller.abort(_construct_abort_reason(reason))
async def pyfetch(
request: "str | Request",
/,
*,
signal: Any = None,
fetcher: Any = None,
**kwargs: Any,
) -> FetchResponse:
r"""Fetch the url and return the response.
This functions provides a similar API to :js:func:`fetch` however it is
designed to be convenient to use from Python. The
:class:`~pyodide.http.FetchResponse` has methods with the output types
already converted to Python objects.
Parameters
----------
request :
Either a string URL or a JavaScript Request object to fetch.
signal :
Abort signal to use for the fetch request.
fetcher :
Fetcher to use for the fetch request.
\*\*kwargs :
keyword arguments are passed along as `optional parameters to the fetch API
<https://developer.mozilla.org/en-US/docs/Web/API/fetch#options>`_.
Examples
--------
>>> import pytest; pytest.skip("Can't use top level await in doctests")
>>> res = await pyfetch("https://cdn.jsdelivr.net/pyodide/v0.23.4/full/repodata.json")
>>> res.ok
True
>>> res.status
200
>>> data = await res.json()
>>> data
{'info': {'arch': 'wasm32', 'platform': 'emscripten_3_1_32',
'version': '0.23.4', 'python': '3.11.2'}, ... # long output truncated
"""
controller = AbortController.new()
if signal:
signal = abortSignalAny(to_js([signal, controller.signal]))
else:
signal = controller.signal
kwargs["signal"] = signal
fetcher = fetcher or _jsfetch
args = to_js(kwargs, dict_converter=Object.fromEntries)
if isinstance(request, str):
request = Request.new(request, args)
try:
return FetchResponse(
request,
await fetcher(request, args),
controller,
signal,
)
except CancelledError as e:
controller.abort(
_construct_abort_reason("\n".join(map(str, e.args))) if e.args else None
)
raise
except JsException as e:
raise AbortError(e) from None
| FetchResponse |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 61376,
"end": 65513
} | class ____(ClapPreTrainedModel):
config: ClapTextConfig
input_modalities = ("text",)
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self.embeddings = ClapTextEmbeddings(config)
self.encoder = ClapTextEncoder(config)
self.pooler = ClapTextPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
batch_size, seq_length = input_shape
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(((batch_size, seq_length)), device=device)
if token_type_ids is None:
if hasattr(self.embeddings, "token_type_ids"):
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
token_type_ids = buffered_token_type_ids_expanded
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
token_type_ids=token_type_ids,
inputs_embeds=inputs_embeds,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@auto_docstring
| ClapTextModel |
python | keras-team__keras | keras/src/metrics/hinge_metrics.py | {
"start": 279,
"end": 1293
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Computes the hinge metric between `y_true` and `y_pred`.
`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.
Examples:
>>> m = keras.metrics.Hinge()
>>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
>>> m.result()
1.3
>>> m.reset_state()
>>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
... sample_weight=[1, 0])
>>> m.result()
1.1
"""
def __init__(self, name="hinge", dtype=None):
super().__init__(fn=hinge, name=name, dtype=dtype)
# Metric should be minimized during optimization.
self._direction = "down"
def get_config(self):
return {"name": self.name, "dtype": self.dtype}
@keras_export("keras.metrics.SquaredHinge")
| Hinge |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py | {
"start": 11,
"end": 159
} | class ____:
foo: List[str] = field(default_factory=lambda: []) # PIE807
bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807
| Foo |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 93184,
"end": 97597
} | class ____(_AutoModelForVision2Seq):
@classmethod
def from_config(cls, config, **kwargs):
warnings.warn(
"The class `AutoModelForVision2Seq` is deprecated and will be removed in v5.0. Please use "
"`AutoModelForImageTextToText` instead.",
FutureWarning,
)
return super().from_config(config, **kwargs)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
warnings.warn(
"The class `AutoModelForVision2Seq` is deprecated and will be removed in v5.0. Please use "
"`AutoModelForImageTextToText` instead.",
FutureWarning,
)
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
__all__ = [
"MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
"MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING",
"MODEL_FOR_AUDIO_TOKENIZATION_MAPPING",
"MODEL_FOR_AUDIO_XVECTOR_MAPPING",
"MODEL_FOR_BACKBONE_MAPPING",
"MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING",
"MODEL_FOR_CAUSAL_LM_MAPPING",
"MODEL_FOR_CTC_MAPPING",
"MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
"MODEL_FOR_DEPTH_ESTIMATION_MAPPING",
"MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
"MODEL_FOR_IMAGE_MAPPING",
"MODEL_FOR_IMAGE_SEGMENTATION_MAPPING",
"MODEL_FOR_IMAGE_TO_IMAGE_MAPPING",
"MODEL_FOR_KEYPOINT_DETECTION_MAPPING",
"MODEL_FOR_KEYPOINT_MATCHING_MAPPING",
"MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING",
"MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
"MODEL_FOR_MASKED_LM_MAPPING",
"MODEL_FOR_MASK_GENERATION_MAPPING",
"MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
"MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
"MODEL_FOR_OBJECT_DETECTION_MAPPING",
"MODEL_FOR_PRETRAINING_MAPPING",
"MODEL_FOR_QUESTION_ANSWERING_MAPPING",
"MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
"MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
"MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
"MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
"MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
"MODEL_FOR_TEXT_ENCODING_MAPPING",
"MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING",
"MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING",
"MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING",
"MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
"MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING",
"MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING",
"MODEL_FOR_VISION_2_SEQ_MAPPING",
"MODEL_FOR_RETRIEVAL_MAPPING",
"MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING",
"MODEL_FOR_MULTIMODAL_LM_MAPPING",
"MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING",
"MODEL_MAPPING",
"MODEL_WITH_LM_HEAD_MAPPING",
"MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
"MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING",
"MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING",
"MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING",
"AutoModel",
"AutoBackbone",
"AutoModelForAudioClassification",
"AutoModelForAudioFrameClassification",
"AutoModelForAudioTokenization",
"AutoModelForAudioXVector",
"AutoModelForCausalLM",
"AutoModelForCTC",
"AutoModelForDepthEstimation",
"AutoModelForImageClassification",
"AutoModelForImageSegmentation",
"AutoModelForImageToImage",
"AutoModelForInstanceSegmentation",
"AutoModelForKeypointDetection",
"AutoModelForKeypointMatching",
"AutoModelForMaskGeneration",
"AutoModelForTextEncoding",
"AutoModelForMaskedImageModeling",
"AutoModelForMaskedLM",
"AutoModelForMultipleChoice",
"AutoModelForMultimodalLM",
"AutoModelForNextSentencePrediction",
"AutoModelForObjectDetection",
"AutoModelForPreTraining",
"AutoModelForQuestionAnswering",
"AutoModelForSemanticSegmentation",
"AutoModelForSeq2SeqLM",
"AutoModelForSequenceClassification",
"AutoModelForSpeechSeq2Seq",
"AutoModelForTableQuestionAnswering",
"AutoModelForTextToSpectrogram",
"AutoModelForTextToWaveform",
"AutoModelForTimeSeriesPrediction",
"AutoModelForTokenClassification",
"AutoModelForUniversalSegmentation",
"AutoModelForVideoClassification",
"AutoModelForVision2Seq",
"AutoModelForVisualQuestionAnswering",
"AutoModelForDocumentQuestionAnswering",
"AutoModelWithLMHead",
"AutoModelForZeroShotImageClassification",
"AutoModelForZeroShotObjectDetection",
"AutoModelForImageTextToText",
]
| AutoModelForVision2Seq |
python | walkccc__LeetCode | solutions/3336. Find the Number of Subsequences With Equal GCD/3336-3.py | {
"start": 0,
"end": 967
} | class ____:
def subsequencePairCount(self, nums: list[int]) -> int:
MOD = 1_000_000_007
maxNum = max(nums)
# dp[x][y] := number of disjoint pairs `seq1` and `seq2` of
# nums so far, where GCD(seq1) == x and GCD(seq2) == y
dp = [[0] * (maxNum + 1) for _ in range(maxNum + 1)]
dp[0][0] = 1
for num in nums:
newDp = [[0] * (maxNum + 1) for _ in range(maxNum + 1)]
for x in range(maxNum + 1):
for y in range(maxNum + 1):
# 1. Skip `num`.
newDp[x][y] += dp[x][y]
newDp[x][y] %= MOD
# 2. Pick `num` in the first subsequence.
newX = math.gcd(x, num)
newDp[newX][y] += dp[x][y]
newDp[newX][y] %= MOD
# 3. Pick `num` in the second subsequence.
newY = math.gcd(y, num)
newDp[x][newY] += dp[x][y]
newDp[x][newY] %= MOD
dp = newDp
return sum(dp[g][g]
for g in range(1, maxNum + 1)) % MOD
| Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/helpers/execution/run_steps.py | {
"start": 740,
"end": 2340
} | class ____(Exception):
pass
def _get_dependency_graph(steps: STEP_TREE) -> Dict[str, List[str]]:
"""
Get the dependency graph of a step tree.
"""
dependency_graph: Dict[str, List[str]] = {}
for step in steps:
if isinstance(step, StepToRun):
dependency_graph[step.id] = step.depends_on
elif isinstance(step, list):
nested_dependency_graph = _get_dependency_graph(list(step))
dependency_graph = {**dependency_graph, **nested_dependency_graph}
else:
raise Exception(f"Unexpected step type: {type(step)}")
return dependency_graph
def _get_transitive_dependencies_for_step_id(
dependency_graph: Dict[str, List[str]], step_id: str, visited: Optional[Set[str]] = None
) -> List[str]:
"""Get the transitive dependencies for a step id.
Args:
dependency_graph (Dict[str, str]): The dependency graph to use.
step_id (str): The step id to get the transitive dependencies for.
visited (Optional[Set[str]], optional): The set of visited step ids. Defaults to None.
Returns:
List[str]: List of transitive dependencies as step ids.
"""
if visited is None:
visited = set()
if step_id not in visited:
visited.add(step_id)
dependencies: List[str] = dependency_graph.get(step_id, [])
for dependency in dependencies:
dependencies.extend(_get_transitive_dependencies_for_step_id(dependency_graph, dependency, visited))
return dependencies
else:
return []
@dataclass
| InvalidStepConfiguration |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 96389,
"end": 97393
} | class ____(Response):
"""
Response of events.get_scalar_metrics_and_variants endpoint.
:param metrics:
:type metrics: dict
"""
_service = "events"
_action = "get_scalar_metrics_and_variants"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"metrics": {"additionalProperties": True, "type": ["object", "null"]}},
"type": "object",
}
def __init__(self, metrics: Optional[dict] = None, **kwargs: Any) -> None:
super(GetScalarMetricsAndVariantsResponse, self).__init__(**kwargs)
self.metrics = metrics
@schema_property("metrics")
def metrics(self) -> Optional[dict]:
return self._property_metrics
@metrics.setter
def metrics(self, value: Optional[dict]) -> None:
if value is None:
self._property_metrics = None
return
self.assert_isinstance(value, "metrics", (dict,))
self._property_metrics = value
| GetScalarMetricsAndVariantsResponse |
python | Textualize__textual | docs/examples/how-to/containers01.py | {
"start": 272,
"end": 567
} | class ____(App):
"""Simple app to play with containers."""
def compose(self) -> ComposeResult:
with Horizontal(): # (1)!
yield Box() # (2)!
yield Box()
yield Box()
if __name__ == "__main__":
app = ContainerApp()
app.run()
| ContainerApp |
python | lepture__authlib | authlib/oauth1/rfc5849/errors.py | {
"start": 1010,
"end": 1082
} | class ____(OAuth1Error):
error = "invalid_request"
| InvalidRequestError |
python | ray-project__ray | python/ray/llm/tests/serve/gpu/integration/test_openai_compatibility_no_accelerator_type.py | {
"start": 28,
"end": 1733
} | class ____:
"""Test that rayllm is compatible with OpenAI API without specifying accelerator_type"""
def test_models_no_accelerator_type(
self, testing_model_no_accelerator
): # noqa: F811
"""Check model listing without accelerator_type"""
client, model = testing_model_no_accelerator
models = client.models.list()
assert len(models.data) == 1, "Only the test model should be returned"
assert models.data[0].id == model, "The test model id should match"
def test_completions_no_accelerator_type(
self, testing_model_no_accelerator
): # noqa: F811
"""Check completions without accelerator_type"""
client, model = testing_model_no_accelerator
completion = client.completions.create(
model=model,
prompt="Hello world",
max_tokens=2,
)
assert completion.model == model
assert completion.model
assert completion.choices[0].text == "test_0 test_1"
def test_chat_no_accelerator_type(self, testing_model_no_accelerator): # noqa: F811
"""Check chat completions without accelerator_type"""
client, model = testing_model_no_accelerator
chat_completion = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Hello world"}],
)
assert chat_completion
assert chat_completion.usage
assert chat_completion.id
assert isinstance(chat_completion.choices, list)
assert chat_completion.choices[0].message.content
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
| TestOpenAICompatibilityNoAcceleratorType |
python | jazzband__django-pipeline | tests/tests/test_compiler.py | {
"start": 4691,
"end": 5516
} | class ____(TestCase):
def setUp(self):
default_collector.collect()
self.compiler = Compiler()
def test_output_path(self):
compiler_class = self.compiler.compilers[0]
compiler = compiler_class(
verbose=self.compiler.verbose,
storage=self.compiler.storage,
)
output_path = compiler.output_path("js/helpers.coffee", "js")
self.assertEqual(output_path, "js/helpers.js")
def test_compile(self):
paths = self.compiler.compile([_("pipeline/js/dummy.coffee")])
default_collector.collect()
self.assertEqual([_("pipeline/js/dummy.junk")], list(paths))
def tearDown(self):
default_collector.clear()
@pipeline_settings(COMPILERS=["tests.tests.test_compiler.CompilerWithEmptyFirstArg"])
| CompilerSelfWriterTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.