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 | doocs__leetcode | solution/3500-3599/3528.Unit Conversion I/Solution.py | {
"start": 0,
"end": 450
} | class ____:
def baseUnitConversions(self, conversions: List[List[int]]) -> List[int]:
def dfs(s: int, mul: int) -> None:
ans[s] = mul
for t, w in g[s]:
dfs(t, mul * w % mod)
mod = 10**9 + 7
n = len(conversions) + 1
g = [[] for _ in range(n)]
for s, t, w in conversions:
g[s].append((t, w))
ans = [0] * n
dfs(0, 1)
return ans
| Solution |
python | pytorch__pytorch | test/test_sparse.py | {
"start": 195900,
"end": 198194
} | class ____(TestCase):
exact_dtype = True
fp16_low_precision_list = {
'masked.prod',
}
@ops(sparse_masked_reduction_ops)
def test_future_empty_dim(self, device, dtype, op):
"""Currently, `dim=()` in reductions operations means "reduce over
all dimensions" while in future, it will read "no reduce". See
https://github.com/pytorch/pytorch/issues/29137
For sparse masked reductions, we'll implement the current behavior.
For testing, we'll use samples with `dim=0` and map it to
`dim=()` until
torch.testing._internal.common_methods_invocations._generate_reduction_kwargs
is made to generate samples with `dim=()` for non-scalar
inputs. With this and after gh-29137 is resolved, this test
can be deleted. See also `torch.masked._canonical_dim`
implementation about changing the `dim=()` behavior.
"""
samples = op.sample_inputs_func(op, device, dtype, requires_grad=False)
op_name = op.name.replace('masked.', '')
for sample_input in samples:
if sample_input.kwargs.get('dim') != 0:
continue
sample_input_kwargs = dict(sample_input.kwargs)
sample_input_kwargs['dim'] = () # reduce over all dimensions
t = sample_input.input
mask = sample_input_kwargs.get('mask')
if mask is None and op_name in {'prod', 'amax', 'amin'}:
# FIXME: for now reductions with non-zero reduction identity and
# unspecified mask are not supported for sparse COO
# tensors, see torch.masked.prod implementation
# for details.
continue
sparse_op_kwargs = dict(sample_input_kwargs)
actual = op(t.to_sparse(), *sample_input.args, **sample_input_kwargs)
self.assertEqual(actual.layout, torch.sparse_coo)
expected = op(t, *sample_input.args, **sample_input_kwargs).to_sparse()
atol = None
rtol = None
if op.name in self.fp16_low_precision_list and dtype == torch.half:
atol = 1e-5
rtol = 2e-3
self.assertEqual(actual, expected, atol=atol, rtol=rtol)
| TestSparseMaskedReductions |
python | getsentry__sentry | src/sentry/replays/lib/event_linking.py | {
"start": 216,
"end": 566
} | class ____(TypedDict):
type: str
start_time: int
replay_id: str
project_id: int
segment_id: None
payload: (
EventLinkPayloadDebugId
| EventLinkPayloadInfoId
| EventLinkPayloadWarningId
| EventLinkPayloadErrorId
| EventLinkPayloadFatalId
)
retention_days: int
| EventLinkKafkaMessage |
python | neetcode-gh__leetcode | python/1472-design-browser-history.py | {
"start": 793,
"end": 1438
} | class ____:
def __init__(self, homepage: str):
self.i = 0
self.len = 1
self.history = [homepage]
# O(1)
def visit(self, url: str) -> None:
if len(self.history) < self.i + 2:
self.history.append(url)
else:
self.history[self.i + 1] = url
self.i += 1
self.len = self.i + 1
# O(1)
def back(self, steps: int) -> str:
self.i = max(self.i - steps, 0)
return self.history[self.i]
# O(1)
def forward(self, steps: int) -> str:
self.i = min(self.i + steps, self.len - 1)
return self.history[self.i]
| BrowserHistory |
python | jazzband__django-waffle | waffle/migrations/0003_update_strings_for_i18n.py | {
"start": 152,
"end": 6755
} | class ____(migrations.Migration):
dependencies = [
('waffle', '0002_auto_20161201_0958'),
]
operations = [
migrations.AlterModelOptions(
name='flag',
options={'verbose_name': 'Flag', 'verbose_name_plural': 'Flags'},
),
migrations.AlterModelOptions(
name='sample',
options={'verbose_name': 'Sample', 'verbose_name_plural': 'Samples'},
),
migrations.AlterModelOptions(
name='switch',
options={'verbose_name': 'Switch', 'verbose_name_plural': 'Switches'},
),
migrations.AlterField(
model_name='flag',
name='authenticated',
field=models.BooleanField(default=False, help_text='Flag always active for authenticated users?', verbose_name='Authenticated'),
),
migrations.AlterField(
model_name='flag',
name='created',
field=models.DateTimeField(db_index=True, default=django.utils.timezone.now, help_text='Date when this Flag was created.', verbose_name='Created'),
),
migrations.AlterField(
model_name='flag',
name='everyone',
field=models.NullBooleanField(help_text='Flip this flag on (Yes) or off (No) for everyone, overriding all other settings. Leave as Unknown to use normally.', verbose_name='Everyone'),
),
migrations.AlterField(
model_name='flag',
name='groups',
field=models.ManyToManyField(blank=True, help_text='Activate this flag for these user groups.', to='auth.Group', verbose_name='Groups'),
),
migrations.AlterField(
model_name='flag',
name='languages',
field=models.TextField(blank=True, default='', help_text='Activate this flag for users with one of these languages (comma-separated list)', verbose_name='Languages'),
),
migrations.AlterField(
model_name='flag',
name='modified',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date when this Flag was last modified.', verbose_name='Modified'),
),
migrations.AlterField(
model_name='flag',
name='name',
field=models.CharField(help_text='The human/computer readable name.', max_length=100, unique=True, verbose_name='Name'),
),
migrations.AlterField(
model_name='flag',
name='note',
field=models.TextField(blank=True, help_text='Note where this Flag is used.', verbose_name='Note'),
),
migrations.AlterField(
model_name='flag',
name='percent',
field=models.DecimalField(blank=True, decimal_places=1, help_text='A number between 0.0 and 99.9 to indicate a percentage of users for whom this flag will be active.', max_digits=3, null=True, verbose_name='Percent'),
),
migrations.AlterField(
model_name='flag',
name='rollout',
field=models.BooleanField(default=False, help_text='Activate roll-out mode?', verbose_name='Rollout'),
),
migrations.AlterField(
model_name='flag',
name='staff',
field=models.BooleanField(default=False, help_text='Flag always active for staff?', verbose_name='Staff'),
),
migrations.AlterField(
model_name='flag',
name='superusers',
field=models.BooleanField(default=True, help_text='Flag always active for superusers?', verbose_name='Superusers'),
),
migrations.AlterField(
model_name='flag',
name='testing',
field=models.BooleanField(default=False, help_text='Allow this flag to be set for a session for user testing', verbose_name='Testing'),
),
migrations.AlterField(
model_name='flag',
name='users',
field=models.ManyToManyField(blank=True, help_text='Activate this flag for these users.', to=settings.AUTH_USER_MODEL, verbose_name='Users'),
),
migrations.AlterField(
model_name='sample',
name='created',
field=models.DateTimeField(db_index=True, default=django.utils.timezone.now, help_text='Date when this Sample was created.', verbose_name='Created'),
),
migrations.AlterField(
model_name='sample',
name='modified',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date when this Sample was last modified.', verbose_name='Modified'),
),
migrations.AlterField(
model_name='sample',
name='name',
field=models.CharField(help_text='The human/computer readable name.', max_length=100, unique=True, verbose_name='Name'),
),
migrations.AlterField(
model_name='sample',
name='note',
field=models.TextField(blank=True, help_text='Note where this Sample is used.', verbose_name='Note'),
),
migrations.AlterField(
model_name='sample',
name='percent',
field=models.DecimalField(decimal_places=1, help_text='A number between 0.0 and 100.0 to indicate a percentage of the time this sample will be active.', max_digits=4, verbose_name='Percent'),
),
migrations.AlterField(
model_name='switch',
name='active',
field=models.BooleanField(default=False, help_text='Is this switch active?', verbose_name='Active'),
),
migrations.AlterField(
model_name='switch',
name='created',
field=models.DateTimeField(db_index=True, default=django.utils.timezone.now, help_text='Date when this Switch was created.', verbose_name='Created'),
),
migrations.AlterField(
model_name='switch',
name='modified',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date when this Switch was last modified.', verbose_name='Modified'),
),
migrations.AlterField(
model_name='switch',
name='name',
field=models.CharField(help_text='The human/computer readable name.', max_length=100, unique=True, verbose_name='Name'),
),
migrations.AlterField(
model_name='switch',
name='note',
field=models.TextField(blank=True, help_text='Note where this Switch is used.', verbose_name='Note'),
),
]
| Migration |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 42508,
"end": 43258
} | class ____(TestCase):
@override_settings(LANGUAGE_CODE='pl')
def test_to_internal_value(self):
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True)
assert field.to_internal_value('1,1') == Decimal('1.1')
@override_settings(LANGUAGE_CODE='pl')
def test_to_representation(self):
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True)
assert field.to_representation(Decimal('1.1')) == '1,1'
def test_localize_forces_coerce_to_string(self):
field = serializers.DecimalField(max_digits=2, decimal_places=1, coerce_to_string=False, localize=True)
assert isinstance(field.to_representation(Decimal('1.1')), str)
| TestLocalizedDecimalField |
python | google__jax | jax/_src/lib/triton.py | {
"start": 710,
"end": 839
} | class ____(Protocol):
asm: str
smem_bytes: int
cluster_dim_x: int
cluster_dim_y: int
cluster_dim_z: int
| CompilationResult |
python | doocs__leetcode | lcci/16.05.Factorial Zeros/Solution.py | {
"start": 0,
"end": 154
} | class ____:
def trailingZeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
| Solution |
python | pytorch__pytorch | torch/_logging/_internal.py | {
"start": 39025,
"end": 44249
} | class ____(logging.StreamHandler):
"""Like FileHandler, but the file is allocated lazily only upon the first log message"""
def __init__(self, root_dir: Optional[str]) -> None:
# This is implemented in the same way that delay is implemented on
# FileHandler
self.root_dir = root_dir
logging.Handler.__init__(self)
self.stream = None
self._builtin_open = open
# cloned from FileHandler in cpython
def close(self) -> None:
self.acquire()
try:
try:
if self.stream:
try:
self.flush()
finally:
stream = self.stream
self.stream = None
if hasattr(stream, "close"):
stream.close()
finally:
# Issue #19523: call unconditionally to
# prevent a handler leak when delay is set
# Also see Issue #42378: we also rely on
# self._closed being set to True there
logging.StreamHandler.close(self)
finally:
self.release()
def emit(self, record) -> None:
if self.stream is None:
if self.root_dir is None:
TRACE_LOG_DIR = "/logs"
import torch.version as torch_version
if (
hasattr(torch_version, "git_version")
and os.getenv("MAST_HPC_JOB_NAME") is None
):
log.info(
"LazyTraceHandler: disabled because not fbcode or conda on mast"
)
elif not torch._utils_internal.justknobs_check("pytorch/trace:enable"):
log.info(
"LazyTraceHandler: disabled because justknobs_check('pytorch/trace:enable') returned False"
)
elif not os.path.exists(TRACE_LOG_DIR):
log.info(
"LazyTraceHandler: disabled because %s does not exist",
TRACE_LOG_DIR,
)
elif not os.access(TRACE_LOG_DIR, os.W_OK):
log.info(
"LazyTraceHandler: disabled because %s is not writeable",
TRACE_LOG_DIR,
)
else:
self.root_dir = TRACE_LOG_DIR
if self.root_dir is not None:
os.makedirs(self.root_dir, exist_ok=True)
ranksuffix = ""
if dist.is_available() and dist.is_initialized():
ranksuffix = f"rank_{dist.get_rank()}_"
self.stream = tempfile.NamedTemporaryFile(
mode="w+",
suffix=".log",
prefix=f"dedicated_log_torch_trace_{ranksuffix}",
dir=self.root_dir,
delete=False,
)
log.info("LazyTraceHandler: logging to %s", self.stream.name)
else:
# We go poof, remove and no-op
trace_log.removeHandler(self)
return
if self.stream:
super().emit(record)
@functools.cache
def warning_once(logger_obj, *args, **kwargs) -> None:
"""
This function is similar to `logger.warning()`, but will emit the warning with the same message only once
Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
another type of cache that includes the caller frame information in the hashing function.
"""
logger_obj.warning(*args, **kwargs)
def safe_grad_filter(message, category, filename, lineno, file=None, line=None) -> bool:
return "The .grad attribute of a Tensor" not in str(message)
def user_warning_filter(
message, category, filename, lineno, file=None, line=None
) -> bool:
return category is not UserWarning
@contextlib.contextmanager
def hide_warnings(filter_fn=lambda *args, **kwargs: True):
"""
A context manager that temporarily suppresses warnings,
using public API: https://docs.python.org/3/library/warnings.html#warnings.showwarning.
Useful to hide warnings without mutating warnings module state, see:
https://github.com/pytorch/pytorch/issues/128427#issuecomment-2161496162.
NOTE: Warnings issued under this context will still be cached in the __warningregistry__
and count towards the once/default rule. So you should NEVER use this on a user-land function.
Filter must implement the showwarning API:
def filter_fn(message, category, filename, lineno, file=None, line=None) -> bool:
return True # show this warning entry
"""
prior = warnings.showwarning
def _showwarning(*args, **kwargs):
if filter_fn(*args, **kwargs):
prior(*args, **kwargs)
try:
warnings.showwarning = _showwarning
yield
finally:
warnings.showwarning = prior
| LazyTraceHandler |
python | pytest-dev__pytest | testing/test_warnings.py | {
"start": 19151,
"end": 22642
} | class ____:
@staticmethod
def assert_result_warns(result, msg) -> None:
result.stdout.fnmatch_lines([f"*PytestAssertRewriteWarning: {msg}*"])
def test_tuple_warning(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
def test_foo():
assert (1,2)
"""
)
result = pytester.runpytest()
self.assert_result_warns(
result, "assertion is always true, perhaps remove parentheses?"
)
def test_warnings_checker_twice() -> None:
"""Issue #4617"""
expectation = pytest.warns(UserWarning)
with expectation:
warnings.warn("Message A", UserWarning)
with expectation:
warnings.warn("Message B", UserWarning)
@pytest.mark.filterwarnings("always::UserWarning")
def test_group_warnings_by_message(pytester: Pytester) -> None:
pytester.copy_example("warnings/test_group_warnings_by_message.py")
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
f"*== {WARNINGS_SUMMARY_HEADER} ==*",
"test_group_warnings_by_message.py::test_foo[[]0[]]",
"test_group_warnings_by_message.py::test_foo[[]1[]]",
"test_group_warnings_by_message.py::test_foo[[]2[]]",
"test_group_warnings_by_message.py::test_foo[[]3[]]",
"test_group_warnings_by_message.py::test_foo[[]4[]]",
"test_group_warnings_by_message.py::test_foo_1",
" */test_group_warnings_by_message.py:*: UserWarning: foo",
" warnings.warn(UserWarning(msg))",
"",
"test_group_warnings_by_message.py::test_bar[[]0[]]",
"test_group_warnings_by_message.py::test_bar[[]1[]]",
"test_group_warnings_by_message.py::test_bar[[]2[]]",
"test_group_warnings_by_message.py::test_bar[[]3[]]",
"test_group_warnings_by_message.py::test_bar[[]4[]]",
" */test_group_warnings_by_message.py:*: UserWarning: bar",
" warnings.warn(UserWarning(msg))",
"",
"-- Docs: *",
"*= 11 passed, 11 warnings *",
],
consecutive=True,
)
@pytest.mark.filterwarnings("always::UserWarning")
def test_group_warnings_by_message_summary(pytester: Pytester) -> None:
pytester.copy_example("warnings/test_group_warnings_by_message_summary")
pytester.syspathinsert()
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
f"*== {WARNINGS_SUMMARY_HEADER} ==*",
"test_1.py: 21 warnings",
"test_2.py: 1 warning",
" */test_1.py:10: UserWarning: foo",
" warnings.warn(UserWarning(msg))",
"",
"test_1.py: 20 warnings",
" */test_1.py:10: UserWarning: bar",
" warnings.warn(UserWarning(msg))",
"",
"-- Docs: *",
"*= 42 passed, 42 warnings *",
],
consecutive=True,
)
def test_pytest_configure_warning(pytester: Pytester, recwarn) -> None:
"""Issue 5115."""
pytester.makeconftest(
"""
def pytest_configure():
import warnings
warnings.warn("from pytest_configure")
"""
)
result = pytester.runpytest()
assert result.ret == 5
assert "INTERNALERROR" not in result.stderr.str()
warning = recwarn.pop()
assert str(warning.message) == "from pytest_configure"
| TestAssertionWarnings |
python | scikit-learn__scikit-learn | sklearn/datasets/_openml.py | {
"start": 6738,
"end": 41840
} | class ____(ValueError):
"""HTTP 412 is a specific OpenML error code, indicating a generic error"""
pass
def _get_json_content_from_openml_api(
url: str,
error_message: Optional[str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict:
"""
Loads json data from the openml api.
Parameters
----------
url : str
The URL to load from. Should be an official OpenML endpoint.
error_message : str or None
The error message to raise if an acceptable OpenML error is thrown
(acceptable error is, e.g., data id not found. Other errors, like 404's
will throw the native error message).
data_home : str or None
Location to cache the response. None if no cache is required.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
Returns
-------
json_data : json
the json result from the OpenML server if the call was successful.
An exception otherwise.
"""
@_retry_with_clean_cache(url, data_home=data_home)
def _load_json():
with closing(
_open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
) as response:
return json.loads(response.read().decode("utf-8"))
try:
return _load_json()
except HTTPError as error:
# 412 is an OpenML specific error code, indicating a generic error
# (e.g., data not found)
if error.code != 412:
raise error
# 412 error, not in except for nicer traceback
raise OpenMLError(error_message)
def _get_data_info_by_name(
name: str,
version: Union[int, str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
):
"""
Utilizes the openml dataset listing api to find a dataset by
name/version
OpenML api function:
https://www.openml.org/api_docs#!/data/get_data_list_data_name_data_name
Parameters
----------
name : str
name of the dataset
version : int or str
If version is an integer, the exact name/version will be obtained from
OpenML. If version is a string (value: "active") it will take the first
version from OpenML that is annotated as active. Any other string
values except "active" are treated as integer.
data_home : str or None
Location to cache the response. None if no cache is required.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
Returns
-------
first_dataset : json
json representation of the first dataset object that adhired to the
search criteria
"""
if version == "active":
# situation in which we return the oldest active version
url = _SEARCH_NAME.format(name) + "/status/active/"
error_msg = "No active dataset {} found.".format(name)
json_data = _get_json_content_from_openml_api(
url,
error_msg,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
res = json_data["data"]["dataset"]
if len(res) > 1:
first_version = version = res[0]["version"]
warning_msg = (
"Multiple active versions of the dataset matching the name"
f" {name} exist. Versions may be fundamentally different, "
f"returning version {first_version}. "
"Available versions:\n"
)
for r in res:
warning_msg += f"- version {r['version']}, status: {r['status']}\n"
warning_msg += (
f" url: https://www.openml.org/search?type=data&id={r['did']}\n"
)
warn(warning_msg)
return res[0]
# an integer version has been provided
url = (_SEARCH_NAME + "/data_version/{}").format(name, version)
try:
json_data = _get_json_content_from_openml_api(
url,
error_message=None,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
except OpenMLError:
# we can do this in 1 function call if OpenML does not require the
# specification of the dataset status (i.e., return datasets with a
# given name / version regardless of active, deactivated, etc. )
# TODO: feature request OpenML.
url += "/status/deactivated"
error_msg = "Dataset {} with version {} not found.".format(name, version)
json_data = _get_json_content_from_openml_api(
url,
error_msg,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data"]["dataset"][0]
def _get_data_description_by_id(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict[str, Any]:
# OpenML API function: https://www.openml.org/api_docs#!/data/get_data_id
url = _DATA_INFO.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data_set_description"]
def _get_data_features(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> OpenmlFeaturesType:
# OpenML function:
# https://www.openml.org/api_docs#!/data/get_data_features_id
url = _DATA_FEATURES.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data_features"]["feature"]
def _get_data_qualities(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> OpenmlQualitiesType:
# OpenML API function:
# https://www.openml.org/api_docs#!/data/get_data_qualities_id
url = _DATA_QUALITIES.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
# the qualities might not be available, but we still try to process
# the data
return json_data.get("data_qualities", {}).get("quality", [])
def _get_num_samples(data_qualities: OpenmlQualitiesType) -> int:
"""Get the number of samples from data qualities.
Parameters
----------
data_qualities : list of dict
Used to retrieve the number of instances (samples) in the dataset.
Returns
-------
n_samples : int
The number of samples in the dataset or -1 if data qualities are
unavailable.
"""
# If the data qualities are unavailable, we return -1
default_n_samples = -1
qualities = {d["name"]: d["value"] for d in data_qualities}
return int(float(qualities.get("NumberOfInstances", default_n_samples)))
def _load_arff_response(
url: str,
data_home: Optional[str],
parser: str,
output_type: str,
openml_columns_info: dict,
feature_names_to_select: List[str],
target_names_to_select: List[str],
shape: Optional[Tuple[int, int]],
md5_checksum: str,
n_retries: int = 3,
delay: float = 1.0,
read_csv_kwargs: Optional[Dict] = None,
):
"""Load the ARFF data associated with the OpenML URL.
In addition of loading the data, this function will also check the
integrity of the downloaded file from OpenML using MD5 checksum.
Parameters
----------
url : str
The URL of the ARFF file on OpenML.
data_home : str
The location where to cache the data.
parser : {"liac-arff", "pandas"}
The parser used to parse the ARFF file.
output_type : {"numpy", "pandas", "sparse"}
The type of the arrays that will be returned. The possibilities are:
- `"numpy"`: both `X` and `y` will be NumPy arrays;
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
pandas Series or DataFrame.
openml_columns_info : dict
The information provided by OpenML regarding the columns of the ARFF
file.
feature_names_to_select : list of str
The list of the features to be selected.
target_names_to_select : list of str
The list of the target variables to be selected.
shape : tuple or None
With `parser="liac-arff"`, when using a generator to load the data,
one needs to provide the shape of the data beforehand.
md5_checksum : str
The MD5 checksum provided by OpenML to check the data integrity.
n_retries : int, default=3
The number of times to retry downloading the data if it fails.
delay : float, default=1.0
The delay between two consecutive downloads in seconds.
read_csv_kwargs : dict, default=None
Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
It allows to overwrite the default options.
.. versionadded:: 1.3
Returns
-------
X : {ndarray, sparse matrix, dataframe}
The data matrix.
y : {ndarray, dataframe, series}
The target.
frame : dataframe or None
A dataframe containing both `X` and `y`. `None` if
`output_array_type != "pandas"`.
categories : list of str or None
The names of the features that are categorical. `None` if
`output_array_type == "pandas"`.
"""
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
with closing(gzip_file):
md5 = hashlib.md5()
for chunk in iter(lambda: gzip_file.read(4096), b""):
md5.update(chunk)
actual_md5_checksum = md5.hexdigest()
if actual_md5_checksum != md5_checksum:
raise ValueError(
f"md5 checksum of local file for {url} does not match description: "
f"expected: {md5_checksum} but got {actual_md5_checksum}. "
"Downloaded file could have been modified / corrupted, clean cache "
"and retry..."
)
def _open_url_and_load_gzip_file(url, data_home, n_retries, delay, arff_params):
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
with closing(gzip_file):
return load_arff_from_gzip_file(gzip_file, **arff_params)
arff_params: Dict = dict(
parser=parser,
output_type=output_type,
openml_columns_info=openml_columns_info,
feature_names_to_select=feature_names_to_select,
target_names_to_select=target_names_to_select,
shape=shape,
read_csv_kwargs=read_csv_kwargs or {},
)
try:
X, y, frame, categories = _open_url_and_load_gzip_file(
url, data_home, n_retries, delay, arff_params
)
except Exception as exc:
if parser != "pandas":
raise
from pandas.errors import ParserError
if not isinstance(exc, ParserError):
raise
# A parsing error could come from providing the wrong quotechar
# to pandas. By default, we use a double quote. Thus, we retry
# with a single quote before to raise the error.
arff_params["read_csv_kwargs"].update(quotechar="'")
X, y, frame, categories = _open_url_and_load_gzip_file(
url, data_home, n_retries, delay, arff_params
)
return X, y, frame, categories
def _download_data_to_bunch(
url: str,
sparse: bool,
data_home: Optional[str],
*,
as_frame: bool,
openml_columns_info: List[dict],
data_columns: List[str],
target_columns: List[str],
shape: Optional[Tuple[int, int]],
md5_checksum: str,
n_retries: int = 3,
delay: float = 1.0,
parser: str,
read_csv_kwargs: Optional[Dict] = None,
):
"""Download ARFF data, load it to a specific container and create to Bunch.
This function has a mechanism to retry/cache/clean the data.
Parameters
----------
url : str
The URL of the ARFF file on OpenML.
sparse : bool
Whether the dataset is expected to use the sparse ARFF format.
data_home : str
The location where to cache the data.
as_frame : bool
Whether or not to return the data into a pandas DataFrame.
openml_columns_info : list of dict
The information regarding the columns provided by OpenML for the
ARFF dataset. The information is stored as a list of dictionaries.
data_columns : list of str
The list of the features to be selected.
target_columns : list of str
The list of the target variables to be selected.
shape : tuple or None
With `parser="liac-arff"`, when using a generator to load the data,
one needs to provide the shape of the data beforehand.
md5_checksum : str
The MD5 checksum provided by OpenML to check the data integrity.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
parser : {"liac-arff", "pandas"}
The parser used to parse the ARFF file.
read_csv_kwargs : dict, default=None
Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
It allows to overwrite the default options.
.. versionadded:: 1.3
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
X : {ndarray, sparse matrix, dataframe}
The data matrix.
y : {ndarray, dataframe, series}
The target.
frame : dataframe or None
A dataframe containing both `X` and `y`. `None` if
`output_array_type != "pandas"`.
categories : list of str or None
The names of the features that are categorical. `None` if
`output_array_type == "pandas"`.
"""
# Prepare which columns and data types should be returned for the X and y
features_dict = {feature["name"]: feature for feature in openml_columns_info}
if sparse:
output_type = "sparse"
elif as_frame:
output_type = "pandas"
else:
output_type = "numpy"
# XXX: target columns should all be categorical or all numeric
_verify_target_data_type(features_dict, target_columns)
for name in target_columns:
column_info = features_dict[name]
n_missing_values = int(column_info["number_of_missing_values"])
if n_missing_values > 0:
raise ValueError(
f"Target column '{column_info['name']}' has {n_missing_values} missing "
"values. Missing values are not supported for target columns."
)
no_retry_exception = None
if parser == "pandas":
# If we get a ParserError with pandas, then we don't want to retry and we raise
# early.
from pandas.errors import ParserError
no_retry_exception = ParserError
X, y, frame, categories = _retry_with_clean_cache(
url, data_home, no_retry_exception
)(_load_arff_response)(
url,
data_home,
parser=parser,
output_type=output_type,
openml_columns_info=features_dict,
feature_names_to_select=data_columns,
target_names_to_select=target_columns,
shape=shape,
md5_checksum=md5_checksum,
n_retries=n_retries,
delay=delay,
read_csv_kwargs=read_csv_kwargs,
)
return Bunch(
data=X,
target=y,
frame=frame,
categories=categories,
feature_names=data_columns,
target_names=target_columns,
)
def _verify_target_data_type(features_dict, target_columns):
# verifies the data type of the y array in case there are multiple targets
# (throws an error if these targets do not comply with sklearn support)
if not isinstance(target_columns, list):
raise ValueError("target_column should be list, got: %s" % type(target_columns))
found_types = set()
for target_column in target_columns:
if target_column not in features_dict:
raise KeyError(f"Could not find target_column='{target_column}'")
if features_dict[target_column]["data_type"] == "numeric":
found_types.add(np.float64)
else:
found_types.add(object)
# note: we compare to a string, not boolean
if features_dict[target_column]["is_ignore"] == "true":
warn(f"target_column='{target_column}' has flag is_ignore.")
if features_dict[target_column]["is_row_identifier"] == "true":
warn(f"target_column='{target_column}' has flag is_row_identifier.")
if len(found_types) > 1:
raise ValueError(
"Can only handle homogeneous multi-target datasets, "
"i.e., all targets are either numeric or "
"categorical."
)
def _valid_data_column_names(features_list, target_columns):
# logic for determining on which columns can be learned. Note that from the
# OpenML guide follows that columns that have the `is_row_identifier` or
# `is_ignore` flag, these can not be learned on. Also target columns are
# excluded.
valid_data_column_names = []
for feature in features_list:
if (
feature["name"] not in target_columns
and feature["is_ignore"] != "true"
and feature["is_row_identifier"] != "true"
):
valid_data_column_names.append(feature["name"])
return valid_data_column_names
@validate_params(
{
"name": [str, None],
"version": [Interval(Integral, 1, None, closed="left"), StrOptions({"active"})],
"data_id": [Interval(Integral, 1, None, closed="left"), None],
"data_home": [str, os.PathLike, None],
"target_column": [str, list, None],
"cache": [bool],
"return_X_y": [bool],
"as_frame": [bool, StrOptions({"auto"})],
"n_retries": [Interval(Integral, 1, None, closed="left")],
"delay": [Interval(Real, 0.0, None, closed="neither")],
"parser": [
StrOptions({"auto", "pandas", "liac-arff"}),
],
"read_csv_kwargs": [dict, None],
},
prefer_skip_nested_validation=True,
)
def fetch_openml(
name: Optional[str] = None,
*,
version: Union[str, int] = "active",
data_id: Optional[int] = None,
data_home: Optional[Union[str, os.PathLike]] = None,
target_column: Optional[Union[str, List]] = "default-target",
cache: bool = True,
return_X_y: bool = False,
as_frame: Union[str, bool] = "auto",
n_retries: int = 3,
delay: float = 1.0,
parser: str = "auto",
read_csv_kwargs: Optional[Dict] = None,
):
"""Fetch dataset from openml by name or dataset id.
Datasets are uniquely identified by either an integer ID or by a
combination of name and version (i.e. there might be multiple
versions of the 'iris' dataset). Please give either name or data_id
(not both). In case a name is given, a version can also be
provided.
Read more in the :ref:`User Guide <openml>`.
.. versionadded:: 0.20
.. note:: EXPERIMENTAL
The API is experimental (particularly the return value structure),
and might have small backward-incompatible changes without notice
or warning in future releases.
Parameters
----------
name : str, default=None
String identifier of the dataset. Note that OpenML can have multiple
datasets with the same name.
version : int or 'active', default='active'
Version of the dataset. Can only be provided if also ``name`` is given.
If 'active' the oldest version that's still active is used. Since
there may be more than one active version of a dataset, and those
versions may fundamentally be different from one another, setting an
exact version is highly recommended.
data_id : int, default=None
OpenML ID of the dataset. The most specific way of retrieving a
dataset. If data_id is not given, name (and potential version) are
used to obtain a dataset.
data_home : str or path-like, default=None
Specify another download and cache folder for the data sets. By default
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
target_column : str, list or None, default='default-target'
Specify the column name in the data to use as target. If
'default-target', the standard target column a stored on the server
is used. If ``None``, all columns are returned as data and the
target is ``None``. If list (of strings), all columns with these names
are returned as multi-target (Note: not all scikit-learn classifiers
can handle all types of multi-output combinations).
cache : bool, default=True
Whether to cache the downloaded datasets into `data_home`.
return_X_y : bool, default=False
If True, returns ``(data, target)`` instead of a Bunch object. See
below for more information about the `data` and `target` objects.
as_frame : bool or 'auto', default='auto'
If True, the data is a pandas DataFrame including columns with
appropriate dtypes (numeric, string or categorical). The target is
a pandas DataFrame or Series depending on the number of target_columns.
The Bunch will contain a ``frame`` attribute with the target and the
data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas
DataFrames or Series as describe above.
If `as_frame` is 'auto', the data and target will be converted to
DataFrame or Series as if `as_frame` is set to True, unless the dataset
is stored in sparse format.
If `as_frame` is False, the data and target will be NumPy arrays and
the `data` will only contain numerical values when `parser="liac-arff"`
where the categories are provided in the attribute `categories` of the
`Bunch` instance. When `parser="pandas"`, no ordinal encoding is made.
.. versionchanged:: 0.24
The default value of `as_frame` changed from `False` to `'auto'`
in 0.24.
n_retries : int, default=3
Number of retries when HTTP errors or network timeouts are encountered.
Error with status code 412 won't be retried as they represent OpenML
generic errors.
delay : float, default=1.0
Number of seconds between retries.
parser : {"auto", "pandas", "liac-arff"}, default="auto"
Parser used to load the ARFF file. Two parsers are implemented:
- `"pandas"`: this is the most efficient parser. However, it requires
pandas to be installed and can only open dense datasets.
- `"liac-arff"`: this is a pure Python ARFF parser that is much less
memory- and CPU-efficient. It deals with sparse ARFF datasets.
If `"auto"`, the parser is chosen automatically such that `"liac-arff"`
is selected for sparse ARFF datasets, otherwise `"pandas"` is selected.
.. versionadded:: 1.2
.. versionchanged:: 1.4
The default value of `parser` changes from `"liac-arff"` to
`"auto"`.
read_csv_kwargs : dict, default=None
Keyword arguments passed to :func:`pandas.read_csv` when loading the data
from an ARFF file and using the pandas parser. It can allow to
overwrite some default parameters.
.. versionadded:: 1.3
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
data : np.array, scipy.sparse.csr_matrix of floats, or pandas DataFrame
The feature matrix. Categorical features are encoded as ordinals.
target : np.array, pandas Series or DataFrame
The regression target or classification labels, if applicable.
Dtype is float if numeric, and object if categorical. If
``as_frame`` is True, ``target`` is a pandas object.
DESCR : str
The full description of the dataset.
feature_names : list
The names of the dataset columns.
target_names: list
The names of the target columns.
.. versionadded:: 0.22
categories : dict or None
Maps each categorical feature name to a list of values, such
that the value encoded as i is ith in the list. If ``as_frame``
is True, this is None.
details : dict
More metadata from OpenML.
frame : pandas DataFrame
Only present when `as_frame=True`. DataFrame with ``data`` and
``target``.
(data, target) : tuple if ``return_X_y`` is True
.. note:: EXPERIMENTAL
This interface is **experimental** and subsequent releases may
change attributes without notice (although there should only be
minor changes to ``data`` and ``target``).
Missing values in the 'data' are represented as NaN's. Missing values
in 'target' are represented as NaN's (numerical target) or None
(categorical target).
Notes
-----
The `"pandas"` and `"liac-arff"` parsers can lead to different data types
in the output. The notable differences are the following:
- The `"liac-arff"` parser always encodes categorical features as `str` objects.
To the contrary, the `"pandas"` parser instead infers the type while
reading and numerical categories will be casted into integers whenever
possible.
- The `"liac-arff"` parser uses float64 to encode numerical features
tagged as 'REAL' and 'NUMERICAL' in the metadata. The `"pandas"`
parser instead infers if these numerical features corresponds
to integers and uses panda's Integer extension dtype.
- In particular, classification datasets with integer categories are
typically loaded as such `(0, 1, ...)` with the `"pandas"` parser while
`"liac-arff"` will force the use of string encoded class labels such as
`"0"`, `"1"` and so on.
- The `"pandas"` parser will not strip single quotes - i.e. `'` - from
string columns. For instance, a string `'my string'` will be kept as is
while the `"liac-arff"` parser will strip the single quotes. For
categorical columns, the single quotes are stripped from the values.
In addition, when `as_frame=False` is used, the `"liac-arff"` parser
returns ordinally encoded data where the categories are provided in the
attribute `categories` of the `Bunch` instance. Instead, `"pandas"` returns
a NumPy array were the categories are not encoded.
Examples
--------
>>> from sklearn.datasets import fetch_openml
>>> adult = fetch_openml("adult", version=2) # doctest: +SKIP
>>> adult.frame.info() # doctest: +SKIP
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 48842 entries, 0 to 48841
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 age 48842 non-null int64
1 workclass 46043 non-null category
2 fnlwgt 48842 non-null int64
3 education 48842 non-null category
4 education-num 48842 non-null int64
5 marital-status 48842 non-null category
6 occupation 46033 non-null category
7 relationship 48842 non-null category
8 race 48842 non-null category
9 sex 48842 non-null category
10 capital-gain 48842 non-null int64
11 capital-loss 48842 non-null int64
12 hours-per-week 48842 non-null int64
13 native-country 47985 non-null category
14 class 48842 non-null category
dtypes: category(9), int64(6)
memory usage: 2.7 MB
"""
if cache is False:
# no caching will be applied
data_home = None
else:
data_home = get_data_home(data_home=data_home)
data_home = join(str(data_home), "openml")
# check valid function arguments. data_id XOR (name, version) should be
# provided
if name is not None:
# OpenML is case-insensitive, but the caching mechanism is not
# convert all data names (str) to lower case
name = name.lower()
if data_id is not None:
raise ValueError(
"Dataset data_id={} and name={} passed, but you can only "
"specify a numeric data_id or a name, not "
"both.".format(data_id, name)
)
data_info = _get_data_info_by_name(
name, version, data_home, n_retries=n_retries, delay=delay
)
data_id = data_info["did"]
elif data_id is not None:
# from the previous if statement, it is given that name is None
if version != "active":
raise ValueError(
"Dataset data_id={} and version={} passed, but you can only "
"specify a numeric data_id or a version, not "
"both.".format(data_id, version)
)
else:
raise ValueError(
"Neither name nor data_id are provided. Please provide name or data_id."
)
data_description = _get_data_description_by_id(data_id, data_home)
if data_description["status"] != "active":
warn(
"Version {} of dataset {} is inactive, meaning that issues have "
"been found in the dataset. Try using a newer version from "
"this URL: {}".format(
data_description["version"],
data_description["name"],
data_description["url"],
)
)
if "error" in data_description:
warn(
"OpenML registered a problem with the dataset. It might be "
"unusable. Error: {}".format(data_description["error"])
)
if "warning" in data_description:
warn(
"OpenML raised a warning on the dataset. It might be "
"unusable. Warning: {}".format(data_description["warning"])
)
return_sparse = data_description["format"].lower() == "sparse_arff"
as_frame = not return_sparse if as_frame == "auto" else as_frame
if parser == "auto":
parser_ = "liac-arff" if return_sparse else "pandas"
else:
parser_ = parser
if parser_ == "pandas":
try:
check_pandas_support("`fetch_openml`")
except ImportError as exc:
if as_frame:
err_msg = (
"Returning pandas objects requires pandas to be installed. "
"Alternatively, explicitly set `as_frame=False` and "
"`parser='liac-arff'`."
)
else:
err_msg = (
f"Using `parser={parser!r}` with dense data requires pandas to be "
"installed. Alternatively, explicitly set `parser='liac-arff'`."
)
raise ImportError(err_msg) from exc
if return_sparse:
if as_frame:
raise ValueError(
"Sparse ARFF datasets cannot be loaded with as_frame=True. "
"Use as_frame=False or as_frame='auto' instead."
)
if parser_ == "pandas":
raise ValueError(
f"Sparse ARFF datasets cannot be loaded with parser={parser!r}. "
"Use parser='liac-arff' or parser='auto' instead."
)
# download data features, meta-info about column types
features_list = _get_data_features(data_id, data_home)
if not as_frame:
for feature in features_list:
if "true" in (feature["is_ignore"], feature["is_row_identifier"]):
continue
if feature["data_type"] == "string":
raise ValueError(
"STRING attributes are not supported for "
"array representation. Try as_frame=True"
)
if target_column == "default-target":
# determines the default target based on the data feature results
# (which is currently more reliable than the data description;
# see issue: https://github.com/openml/OpenML/issues/768)
target_columns = [
feature["name"]
for feature in features_list
if feature["is_target"] == "true"
]
elif isinstance(target_column, str):
# for code-simplicity, make target_column by default a list
target_columns = [target_column]
elif target_column is None:
target_columns = []
else:
# target_column already is of type list
target_columns = target_column
data_columns = _valid_data_column_names(features_list, target_columns)
shape: Optional[Tuple[int, int]]
# determine arff encoding to return
if not return_sparse:
# The shape must include the ignored features to keep the right indexes
# during the arff data conversion.
data_qualities = _get_data_qualities(data_id, data_home)
shape = _get_num_samples(data_qualities), len(features_list)
else:
shape = None
# obtain the data
url = data_description["url"]
bunch = _download_data_to_bunch(
url,
return_sparse,
data_home,
as_frame=bool(as_frame),
openml_columns_info=features_list,
shape=shape,
target_columns=target_columns,
data_columns=data_columns,
md5_checksum=data_description["md5_checksum"],
n_retries=n_retries,
delay=delay,
parser=parser_,
read_csv_kwargs=read_csv_kwargs,
)
if return_X_y:
return bunch.data, bunch.target
description = "{}\n\nDownloaded from openml.org.".format(
data_description.pop("description")
)
bunch.update(
DESCR=description,
details=data_description,
url="https://www.openml.org/d/{}".format(data_id),
)
return bunch
| OpenMLError |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 56643,
"end": 57297
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BigBird
| BigBirdIntermediate |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 33944,
"end": 34145
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ORGANIZATION", "REPOSITORY", "USER")
| RepositoryInteractionLimitOrigin |
python | walkccc__LeetCode | solutions/63. Unique Paths II/63-2.py | {
"start": 0,
"end": 349
} | class ____:
def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [0] * n
dp[0] = 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]:
dp[j] = 0
elif j > 0:
dp[j] += dp[j - 1]
return dp[n - 1]
| Solution |
python | pyparsing__pyparsing | examples/inv_regex.py | {
"start": 1565,
"end": 2133
} | class ____:
def __init__(self, exprs):
self.exprs = ParseResults(exprs)
def make_generator(self):
def group_gen():
def recurse_list(elist):
if len(elist) == 1:
yield from elist[0].make_generator()()
else:
for s in elist[0].make_generator()():
for s2 in recurse_list(elist[1:]):
yield s + s2
if self.exprs:
yield from recurse_list(self.exprs)
return group_gen
| GroupEmitter |
python | davidhalter__parso | test/normalizer_issue_files/E29.py | {
"start": 40,
"end": 144
} | class ____(object):
bang = 12
#: W291+1:34
'''multiline
string with trailing whitespace'''
| Foo |
python | uqfoundation__dill | dill/_dill.py | {
"start": 36074,
"end": 36237
} | class ____(object):
def __init__(self):
self.items = []
def __getitem__(self, item):
self.items.append(item)
return
| _itemgetter_helper |
python | coleifer__peewee | tests/regressions.py | {
"start": 62526,
"end": 65943
} | class ____(ModelTestCase):
@requires_models(Character, Shape, ShapeDetail)
def test_delete_instance_dfs_nullable(self):
c1, c2 = [Character.create(name=name) for name in ('c1', 'c2')]
for c in (c1, c2):
s = Shape.create(character=c)
ShapeDetail.create(shape=s)
# Update nullables.
with self.assertQueryCount(2):
c1.delete_instance(True)
self.assertHistory(2, [
('UPDATE "shape" SET "character_id" = ? WHERE '
'("shape"."character_id" = ?)', [None, c1.id]),
('DELETE FROM "character" WHERE ("character"."id" = ?)', [c1.id])])
self.assertEqual(Shape.select().count(), 2)
# Delete nullables as well.
with self.assertQueryCount(3):
c2.delete_instance(True, True)
self.assertHistory(3, [
('DELETE FROM "shape_detail" WHERE '
'("shape_detail"."shape_id" IN '
'(SELECT "t1"."id" FROM "shape" AS "t1" WHERE '
'("t1"."character_id" = ?)))', [c2.id]),
('DELETE FROM "shape" WHERE ("shape"."character_id" = ?)', [c2.id]),
('DELETE FROM "character" WHERE ("character"."id" = ?)', [c2.id])])
self.assertEqual(Shape.select().count(), 1)
@requires_models(I, S, P, PS, PP, O, OX)
def test_delete_instance_dfs(self):
i1, i2 = [I.create(name=n) for n in ('i1', 'i2')]
for i in (i1, i2):
s = S.create(i=i)
p = P.create(i=i)
ps = PS.create(p=p, s=s)
pp = PP.create(ps=ps)
o = O.create(ps=ps, s=s)
ox = OX.create(o=o)
with self.assertQueryCount(9):
i1.delete_instance(recursive=True)
self.assertHistory(9, [
('DELETE FROM "pp" WHERE ('
'"pp"."ps_id" IN (SELECT "t1"."id" FROM "ps" AS "t1" WHERE ('
'"t1"."p_id" IN (SELECT "t2"."id" FROM "p" AS "t2" WHERE ('
'"t2"."i_id" = ?)))))', [i1.id]),
('UPDATE "ox" SET "o_id" = ? WHERE ('
'"ox"."o_id" IN (SELECT "t1"."id" FROM "o" AS "t1" WHERE ('
'"t1"."ps_id" IN (SELECT "t2"."id" FROM "ps" AS "t2" WHERE ('
'"t2"."p_id" IN (SELECT "t3"."id" FROM "p" AS "t3" WHERE ('
'"t3"."i_id" = ?)))))))', [None, i1.id]),
('DELETE FROM "o" WHERE ('
'"o"."ps_id" IN (SELECT "t1"."id" FROM "ps" AS "t1" WHERE ('
'"t1"."p_id" IN (SELECT "t2"."id" FROM "p" AS "t2" WHERE ('
'"t2"."i_id" = ?)))))', [i1.id]),
('DELETE FROM "o" WHERE ('
'"o"."s_id" IN (SELECT "t1"."id" FROM "s" AS "t1" WHERE ('
'"t1"."i_id" = ?)))', [i1.id]),
('DELETE FROM "ps" WHERE ('
'"ps"."p_id" IN (SELECT "t1"."id" FROM "p" AS "t1" WHERE ('
'"t1"."i_id" = ?)))', [i1.id]),
('DELETE FROM "ps" WHERE ('
'"ps"."s_id" IN (SELECT "t1"."id" FROM "s" AS "t1" WHERE ('
'"t1"."i_id" = ?)))', [i1.id]),
('DELETE FROM "s" WHERE ("s"."i_id" = ?)', [i1.id]),
('DELETE FROM "p" WHERE ("p"."i_id" = ?)', [i1.id]),
('DELETE FROM "i" WHERE ("i"."id" = ?)', [i1.id]),
])
models = [I, S, P, PS, PP, O, OX]
counts = {OX: 2}
for m in models:
self.assertEqual(m.select().count(), counts.get(m, 1))
| TestDeleteInstanceDFS |
python | milvus-io__pymilvus | tests/test_bulk_writer_buffer.py | {
"start": 14540,
"end": 31347
} | class ____:
"""Extended tests to cover additional edge cases and error paths in buffer.py"""
@pytest.fixture
def schema_with_array(self):
"""Schema with array field for testing array error handling"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="array_field", dtype=DataType.ARRAY, max_capacity=100, element_type=DataType.INT64),
]
return CollectionSchema(fields=fields)
@pytest.fixture
def schema_with_sparse(self):
"""Schema with sparse vector field"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="sparse_vector", dtype=DataType.SPARSE_FLOAT_VECTOR),
]
return CollectionSchema(fields=fields)
def test_persist_npy_with_array_field_error(self, schema_with_array):
"""Test that array field raises error in numpy format"""
buffer = Buffer(schema_with_array, BulkFileType.NUMPY)
buffer.append_row({
"id": 1,
"array_field": [1, 2, 3, 4, 5]
})
with tempfile.TemporaryDirectory() as temp_dir, pytest.raises(MilvusException, match="doesn't support parsing array type"):
buffer.persist(temp_dir)
def test_persist_npy_with_sparse_vector_error(self, schema_with_sparse):
"""Test that sparse vector field raises error in numpy format"""
buffer = Buffer(schema_with_sparse, BulkFileType.NUMPY)
buffer.append_row({
"id": 1,
"sparse_vector": {1: 0.5, 10: 0.3}
})
with tempfile.TemporaryDirectory() as temp_dir, pytest.raises(MilvusException, match="SPARSE_FLOAT_VECTOR"):
# The error happens because SPARSE_FLOAT_VECTOR is not in NUMPY_TYPE_CREATOR
# This causes a KeyError which is caught and re-raised as MilvusException
buffer.persist(temp_dir)
def test_persist_npy_with_json_field(self):
"""Test persisting JSON field as numpy"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="json_field", dtype=DataType.JSON),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.NUMPY)
buffer.append_row({
"id": 1,
"json_field": {"key": "value", "nested": {"data": 123}}
})
with tempfile.TemporaryDirectory() as temp_dir:
files = buffer.persist(temp_dir)
assert len(files) == 2
# Verify JSON field was persisted
json_file = next(f for f in files if "json_field" in f)
assert Path(json_file).exists()
def test_persist_npy_with_float16_vectors(self):
"""Test persisting float16 and bfloat16 vectors as numpy"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="float16_vector", dtype=DataType.FLOAT16_VECTOR, dim=4),
FieldSchema(name="bfloat16_vector", dtype=DataType.BFLOAT16_VECTOR, dim=4),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.NUMPY)
# Add data with bytes for float16/bfloat16 vectors
float16_data = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16).tobytes()
bfloat16_data = bytes([1, 2, 3, 4, 5, 6, 7, 8]) # 4 bfloat16 values = 8 bytes
buffer.append_row({
"id": 1,
"float16_vector": float16_data,
"bfloat16_vector": bfloat16_data,
})
with tempfile.TemporaryDirectory() as temp_dir:
files = buffer.persist(temp_dir)
assert len(files) == 3
for f in files:
assert Path(f).exists()
def test_persist_npy_with_none_values(self):
"""Test persisting None values in numpy format"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="nullable_field", dtype=DataType.INT64),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.NUMPY)
buffer.append_row({"id": 1, "nullable_field": None})
buffer.append_row({"id": 2, "nullable_field": 100})
with tempfile.TemporaryDirectory() as temp_dir:
files = buffer.persist(temp_dir)
assert len(files) == 2
@patch('numpy.save')
def test_persist_npy_exception_handling(self, mock_save):
"""Test exception handling in numpy persist"""
mock_save.side_effect = Exception("Save failed")
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.NUMPY)
buffer.append_row({"id": 1})
with tempfile.TemporaryDirectory() as temp_dir, pytest.raises(MilvusException, match="Failed to persist file"):
buffer.persist(temp_dir)
def test_persist_npy_cleanup_on_partial_failure(self):
"""Test that files are cleaned up if not all fields persist successfully"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=2),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.NUMPY)
buffer.append_row({"id": 1, "vector": [1.0, 2.0]})
with tempfile.TemporaryDirectory() as temp_dir, patch('numpy.save') as mock_save:
# Make the second save fail
mock_save.side_effect = [None, Exception("Second save failed")]
with pytest.raises(MilvusException, match="Failed to persist file"):
buffer.persist(temp_dir)
def test_persist_json_with_float16_vectors(self):
"""Test JSON persist with float16 vectors only"""
# Skip bfloat16 as numpy doesn't have native support
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="float16_vector", dtype=DataType.FLOAT16_VECTOR, dim=4),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.JSON)
float16_data = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16).tobytes()
buffer.append_row({
"id": 1,
"float16_vector": float16_data,
})
with tempfile.TemporaryDirectory() as temp_dir:
files = buffer.persist(temp_dir)
assert len(files) == 1
# Verify the JSON content
with Path(files[0]).open('r') as f:
data = json.load(f)
assert 'rows' in data
assert len(data['rows']) == 1
assert isinstance(data['rows'][0]['float16_vector'], list)
@patch('pathlib.Path.open')
def test_persist_json_exception_handling(self, mock_open):
"""Test exception handling in JSON persist"""
mock_open.side_effect = Exception("Failed to open file")
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.JSON)
buffer.append_row({"id": 1})
with pytest.raises(MilvusException, match="Failed to persist file"):
buffer.persist("/tmp/test")
def test_persist_parquet_with_json_and_sparse(self):
"""Test Parquet persist with JSON and sparse vector fields"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="json_field", dtype=DataType.JSON),
FieldSchema(name="sparse_vector", dtype=DataType.SPARSE_FLOAT_VECTOR),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.PARQUET)
buffer.append_row({
"id": 1,
"json_field": {"key": "value"},
"sparse_vector": {1: 0.5, 10: 0.3}
})
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_parquet') as mock_to_parquet:
# Pass buffer_size and buffer_row_count to avoid UnboundLocalError
files = buffer.persist(temp_dir, buffer_size=1024, buffer_row_count=1)
assert len(files) == 1
mock_to_parquet.assert_called_once()
def test_persist_parquet_with_float16_vectors(self):
"""Test Parquet persist with float16 vectors only"""
# Skip bfloat16 as it has issues with numpy dtype
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="float16_vector", dtype=DataType.FLOAT16_VECTOR, dim=4),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.PARQUET)
float16_data = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16).tobytes()
buffer.append_row({
"id": 1,
"float16_vector": float16_data,
})
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_parquet') as mock_to_parquet:
# Pass buffer_size and buffer_row_count to avoid UnboundLocalError
files = buffer.persist(temp_dir, buffer_size=1024, buffer_row_count=1)
assert len(files) == 1
mock_to_parquet.assert_called_once()
def test_persist_parquet_with_array_field(self):
"""Test Parquet persist with array field"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="array_field", dtype=DataType.ARRAY, max_capacity=100, element_type=DataType.INT64),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.PARQUET)
buffer.append_row({
"id": 1,
"array_field": [1, 2, 3, 4, 5]
})
buffer.append_row({
"id": 2,
"array_field": None # Test None value
})
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_parquet') as mock_to_parquet:
# Pass buffer_size and buffer_row_count to avoid UnboundLocalError
files = buffer.persist(temp_dir, buffer_size=1024, buffer_row_count=2)
assert len(files) == 1
mock_to_parquet.assert_called_once()
def test_persist_parquet_with_unknown_dtype(self):
"""Test Parquet persist with fields having standard dtypes"""
# Using standard field types that work with parquet
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="field1", dtype=DataType.VARCHAR, max_length=100),
FieldSchema(name="field2", dtype=DataType.JSON),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.PARQUET)
buffer.append_row({
"id": 1,
"field1": "test_value",
"field2": {"key": "value"}
})
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_parquet') as mock_to_parquet:
# Pass buffer_size and buffer_row_count to avoid UnboundLocalError
files = buffer.persist(temp_dir, buffer_size=1024, buffer_row_count=1)
assert len(files) == 1
mock_to_parquet.assert_called_once()
def test_persist_csv_with_all_field_types(self):
"""Test CSV persist with common field types"""
# Skip bfloat16 due to numpy dtype issues
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="bool_field", dtype=DataType.BOOL),
FieldSchema(name="int8_field", dtype=DataType.INT8),
FieldSchema(name="int16_field", dtype=DataType.INT16),
FieldSchema(name="int32_field", dtype=DataType.INT32),
FieldSchema(name="float_field", dtype=DataType.FLOAT),
FieldSchema(name="double_field", dtype=DataType.DOUBLE),
FieldSchema(name="varchar_field", dtype=DataType.VARCHAR, max_length=512),
FieldSchema(name="json_field", dtype=DataType.JSON),
FieldSchema(name="array_field", dtype=DataType.ARRAY, max_capacity=100, element_type=DataType.INT64),
FieldSchema(name="float_vector", dtype=DataType.FLOAT_VECTOR, dim=128),
FieldSchema(name="binary_vector", dtype=DataType.BINARY_VECTOR, dim=128),
FieldSchema(name="sparse_vector", dtype=DataType.SPARSE_FLOAT_VECTOR),
FieldSchema(name="float16_vector", dtype=DataType.FLOAT16_VECTOR, dim=128),
FieldSchema(name="int8_vector", dtype=DataType.INT8_VECTOR, dim=128),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.CSV)
row = {
"id": 1,
"bool_field": True,
"int8_field": 127,
"int16_field": 32767,
"int32_field": 2147483647,
"float_field": 3.14,
"double_field": 2.718281828,
"varchar_field": "test string",
"json_field": {"key": "value"},
"array_field": [1, 2, 3],
"float_vector": [1.0] * 128,
"binary_vector": [1] * 128,
"sparse_vector": {1: 0.5},
"float16_vector": np.array([1.0] * 128, dtype=np.float16).tobytes(),
"int8_vector": [1] * 128,
}
buffer.append_row(row)
# Add row with None values
row_with_none = row.copy()
row_with_none["array_field"] = None
buffer.append_row(row_with_none)
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_csv') as mock_to_csv:
files = buffer.persist(temp_dir)
assert len(files) == 1
mock_to_csv.assert_called_once()
@patch('pandas.DataFrame.to_csv')
def test_persist_csv_exception_handling(self, mock_to_csv):
"""Test exception handling in CSV persist"""
mock_to_csv.side_effect = Exception("CSV write failed")
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.CSV)
buffer.append_row({"id": 1})
with pytest.raises(MilvusException, match="Failed to persist file"):
buffer.persist("/tmp/test")
def test_persist_csv_with_custom_config(self):
"""Test CSV persist with custom separator and null key"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="nullable_field", dtype=DataType.INT64),
]
schema = CollectionSchema(fields=fields)
# Create buffer with custom CSV config
config = {"sep": "|", "nullkey": "NULL"}
buffer = Buffer(schema, BulkFileType.CSV, config=config)
buffer.append_row({"id": 1, "nullable_field": None})
buffer.append_row({"id": 2, "nullable_field": 100})
with tempfile.TemporaryDirectory() as temp_dir, patch('pandas.DataFrame.to_csv') as mock_to_csv:
files = buffer.persist(temp_dir)
assert len(files) == 1
# Verify custom config was used
call_kwargs = mock_to_csv.call_args[1]
assert call_kwargs.get('sep') == '|'
assert call_kwargs.get('na_rep') == 'NULL'
def test_get_field_schema(self):
"""Test accessing fields from buffer"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.JSON)
# Test that fields are stored in the buffer
assert "id" in buffer._fields
assert "vector" in buffer._fields
assert buffer._fields["id"].name == "id"
assert buffer._fields["vector"].name == "vector"
# Test that non-existent field is not in buffer
assert "non_existent" not in buffer._fields
def test_throw_method(self):
"""Test the _throw method raises MilvusException"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
]
schema = CollectionSchema(fields=fields)
buffer = Buffer(schema, BulkFileType.JSON)
with pytest.raises(MilvusException, match="Test error message"):
buffer._throw("Test error message")
| TestBufferExtended |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 46166,
"end": 49573
} | class ____(FunnelPreTrainedModel):
def __init__(self, config: FunnelConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.funnel = FunnelBaseModel(config)
self.classifier = FunnelClassificationHead(config, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.funnel(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = outputs[0]
pooled_output = last_hidden_state[:, 0]
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
| FunnelForSequenceClassification |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 8884,
"end": 9231
} | class ____(AtomicRule):
"""integrate(1/sqrt(a+b*x+c*x**2), x) -> log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)"""
a: Expr
b: Expr
c: Expr
def eval(self) -> Expr:
a, b, c, x = self.a, self.b, self.c, self.variable
return log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)
@dataclass
| ReciprocalSqrtQuadraticRule |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 243930,
"end": 244080
} | class ____(Structure):
_fields_ = [
("shortName", c_char_p),
("longName", c_char_p),
("unit", c_char_p),
]
| c_metricInfo_t |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 43189,
"end": 46010
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"entry-points": 9000, "dynamic": ["entry-points"]}}
)
with pytest.raises(
ValueError,
match=(
"Metadata field `entry-points` cannot be both statically defined and listed in field `project.dynamic`"
),
):
_ = metadata.core.entry_points
def test_not_table(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"entry-points": 10}})
with pytest.raises(TypeError, match="Field `project.entry-points` must be a table"):
_ = metadata.core.entry_points
@pytest.mark.parametrize(("field", "expected"), [("console_scripts", "scripts"), ("gui-scripts", "gui-scripts")])
def test_forbidden_fields(self, isolation, field, expected):
metadata = ProjectMetadata(str(isolation), None, {"project": {"entry-points": {field: "foo"}}})
with pytest.raises(
ValueError,
match=(
f"Field `{field}` must be defined as `project.{expected}` instead of "
f"in the `project.entry-points` table"
),
):
_ = metadata.core.entry_points
def test_data_not_table(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"entry-points": {"foo": 7}}})
with pytest.raises(TypeError, match="Field `project.entry-points.foo` must be a table"):
_ = metadata.core.entry_points
def test_data_entry_not_string(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"entry-points": {"foo": {"bar": 4}}}})
with pytest.raises(
TypeError, match="Object reference `bar` of field `project.entry-points.foo` must be a string"
):
_ = metadata.core.entry_points
def test_data_empty(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"entry-points": {"foo": {}}}})
assert metadata.core.entry_points == metadata.core.entry_points == {}
def test_default(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {}})
assert metadata.core.entry_points == metadata.core.entry_points == {}
def test_correct(self, isolation):
metadata = ProjectMetadata(
str(isolation),
None,
{"project": {"entry-points": {"foo": {"bar": "baz", "foo": "baz"}, "bar": {"foo": "baz", "bar": "baz"}}}},
)
assert (
metadata.core.entry_points
== metadata.core.entry_points
== {"bar": {"bar": "baz", "foo": "baz"}, "foo": {"bar": "baz", "foo": "baz"}}
)
| TestEntryPoints |
python | ray-project__ray | python/ray/llm/tests/common/cloud/test_utils.py | {
"start": 9477,
"end": 11059
} | class ____:
"""Tests for the is_remote_path utility function."""
def test_s3_paths(self):
"""Test S3 path detection."""
assert is_remote_path("s3://bucket/path") is True
assert is_remote_path("s3://bucket") is True
assert is_remote_path("s3://anonymous@bucket/path") is True
def test_gcs_paths(self):
"""Test GCS path detection."""
assert is_remote_path("gs://bucket/path") is True
assert is_remote_path("gs://bucket") is True
assert is_remote_path("gs://anonymous@bucket/path") is True
def test_abfss_paths(self):
"""Test ABFSS path detection."""
assert (
is_remote_path("abfss://container@account.dfs.core.windows.net/path")
is True
)
assert is_remote_path("abfss://container@account.dfs.core.windows.net") is True
def test_azure_paths(self):
"""Test Azure path detection."""
assert (
is_remote_path("azure://container@account.blob.core.windows.net/path")
is True
)
assert (
is_remote_path("azure://container@account.dfs.core.windows.net/path")
is True
)
def test_local_paths(self):
"""Test local path detection."""
assert is_remote_path("/local/path") is False
assert is_remote_path("./relative/path") is False
assert is_remote_path("file:///local/path") is False
assert is_remote_path("http://example.com") is False
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
| TestIsRemotePath |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py | {
"start": 718,
"end": 783
} | class ____(abc.ABC):
@abstractmethod
def foo(self): pass
| A6 |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 72327,
"end": 72436
} | class ____(BaseModel, extra="forbid"):
mult: List["Expression"] = Field(..., description="")
| MultExpression |
python | django__django | tests/auth_tests/test_middleware.py | {
"start": 3207,
"end": 8620
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(
"test_user", "test@example.com", "test_password"
)
def setUp(self):
self.middleware = LoginRequiredMiddleware(lambda req: HttpResponse())
self.request = HttpRequest()
def test_public_paths(self):
paths = ["public_view", "public_function_view"]
for path in paths:
response = self.client.get(f"/{path}/")
self.assertEqual(response.status_code, 200)
def test_protected_paths(self):
paths = ["protected_view", "protected_function_view"]
for path in paths:
response = self.client.get(f"/{path}/")
self.assertRedirects(
response,
settings.LOGIN_URL + f"?next=/{path}/",
fetch_redirect_response=False,
)
def test_login_required_paths(self):
paths = ["login_required_cbv_view", "login_required_decorator_view"]
for path in paths:
response = self.client.get(f"/{path}/")
self.assertRedirects(
response,
"/custom_login/" + f"?step=/{path}/",
fetch_redirect_response=False,
)
def test_admin_path(self):
admin_url = reverse("admin:index")
response = self.client.get(admin_url)
self.assertRedirects(
response,
reverse("admin:login") + f"?next={admin_url}",
target_status_code=200,
)
def test_non_existent_path(self):
response = self.client.get("/non_existent/")
self.assertEqual(response.status_code, 404)
def test_paths_with_logged_in_user(self):
paths = [
"public_view",
"public_function_view",
"protected_view",
"protected_function_view",
"login_required_cbv_view",
"login_required_decorator_view",
]
self.client.login(username="test_user", password="test_password")
for path in paths:
response = self.client.get(f"/{path}/")
self.assertEqual(response.status_code, 200)
def test_get_login_url_from_view_func(self):
def view_func(request):
return HttpResponse()
view_func.login_url = "/custom_login/"
login_url = self.middleware.get_login_url(view_func)
self.assertEqual(login_url, "/custom_login/")
@override_settings(LOGIN_URL="/settings_login/")
def test_get_login_url_from_settings(self):
login_url = self.middleware.get_login_url(lambda: None)
self.assertEqual(login_url, "/settings_login/")
@override_settings(LOGIN_URL=None)
def test_get_login_url_no_login_url(self):
with self.assertRaises(ImproperlyConfigured) as e:
self.middleware.get_login_url(lambda: None)
self.assertEqual(
str(e.exception),
"No login URL to redirect to. Define settings.LOGIN_URL or provide "
"a login_url via the 'django.contrib.auth.decorators.login_required' "
"decorator.",
)
def test_get_redirect_field_name_from_view_func(self):
def view_func(request):
return HttpResponse()
view_func.redirect_field_name = "next_page"
redirect_field_name = self.middleware.get_redirect_field_name(view_func)
self.assertEqual(redirect_field_name, "next_page")
@override_settings(
MIDDLEWARE=[
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"auth_tests.test_checks.LoginRequiredMiddlewareSubclass",
],
LOGIN_URL="/settings_login/",
)
def test_login_url_resolve_logic(self):
paths = ["login_required_cbv_view", "login_required_decorator_view"]
for path in paths:
response = self.client.get(f"/{path}/")
self.assertRedirects(
response,
"/custom_login/" + f"?step=/{path}/",
fetch_redirect_response=False,
)
paths = ["protected_view", "protected_function_view"]
for path in paths:
response = self.client.get(f"/{path}/")
self.assertRedirects(
response,
f"/settings_login/?redirect_to=/{path}/",
fetch_redirect_response=False,
)
def test_get_redirect_field_name_default(self):
redirect_field_name = self.middleware.get_redirect_field_name(lambda: None)
self.assertEqual(redirect_field_name, REDIRECT_FIELD_NAME)
def test_public_view_logged_in_performance(self):
"""
Public views don't trigger fetching the user from the database.
"""
self.client.force_login(self.user)
with self.assertNumQueries(0):
response = self.client.get("/public_view/")
self.assertEqual(response.status_code, 200)
def test_protected_view_logged_in_performance(self):
"""
Protected views do trigger fetching the user from the database.
"""
self.client.force_login(self.user)
with self.assertNumQueries(2): # session and user
response = self.client.get("/protected_view/")
self.assertEqual(response.status_code, 200)
| TestLoginRequiredMiddleware |
python | numba__numba | numba/core/types/function_type.py | {
"start": 4028,
"end": 4630
} | class ____(Type):
"""
Represents the prototype of a first-class function type.
Used internally.
"""
cconv = None
def __init__(self, rtype, atypes):
self.rtype = rtype
self.atypes = tuple(atypes)
assert isinstance(rtype, Type), (rtype)
lst = []
for atype in self.atypes:
assert isinstance(atype, Type), (atype)
lst.append(atype.name)
name = '%s(%s)' % (rtype, ', '.join(lst))
super(FunctionPrototype, self).__init__(name)
@property
def key(self):
return self.name
| FunctionPrototype |
python | Lightning-AI__lightning | src/lightning/pytorch/plugins/layer_sync.py | {
"start": 3516,
"end": 3948
} | class ____(torch.nn.modules.batchnorm._BatchNorm):
@override
def _check_input_dim(self, input: Tensor) -> None:
# The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
# is this method that is overwritten by the subclass.
# Here, we are bypassing some tensor sanity checks and trusting that the user
# provides the right input dimensions at inference.
return
| _BatchNormXd |
python | doocs__leetcode | solution/2200-2299/2278.Percentage of Letter in String/Solution.py | {
"start": 0,
"end": 123
} | class ____:
def percentageLetter(self, s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
| Solution |
python | getsentry__sentry | tests/sentry/notifications/models/test_notificationsettingoption.py | {
"start": 570,
"end": 2543
} | class ____(TestCase):
def test_remove_for_user(self) -> None:
NotificationSettingOption.objects.create(
user_id=self.user.id,
scope_type="user",
scope_identifier=self.user.id,
type="alerts",
value="never",
)
# Refresh user for actor
self.user = User.objects.get(id=self.user.id)
# Deletion is deferred and tasks aren't run in tests.
with outbox_runner():
self.user.delete()
assert_no_notification_settings()
def test_remove_for_team(self) -> None:
NotificationSettingOption.objects.create(
team_id=self.team.id,
scope_type="team",
scope_identifier=self.team.id,
type="alerts",
value="never",
)
# Deletion is deferred and tasks aren't run in tests.
with assume_test_silo_mode(SiloMode.REGION), outbox_runner():
self.team.delete()
with self.tasks():
schedule_hybrid_cloud_foreign_key_jobs_control()
assert_no_notification_settings()
def test_remove_for_project(self) -> None:
NotificationSettingOption.objects.create(
user_id=self.user.id,
scope_type="project",
scope_identifier=self.project.id,
type="alerts",
value="never",
)
with assume_test_silo_mode(SiloMode.REGION):
self.project.delete()
assert_no_notification_settings()
def test_remove_for_organization(self) -> None:
NotificationSettingOption.objects.create(
user_id=self.user.id,
scope_type="organization",
scope_identifier=self.organization.id,
type="alerts",
value="never",
)
with assume_test_silo_mode(SiloMode.REGION), outbox_runner():
self.organization.delete()
assert_no_notification_settings()
| NotificationSettingTest |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 124725,
"end": 130218
} | class ____(
fixtures.MappedTest, testing.AssertsCompiledSQL
):
"""test for issue 11449"""
__dialect__ = "default"
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"kind",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
)
Table(
"node",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
Column(
"common_node_id", Integer, ForeignKey("node.id"), nullable=True
),
Column("kind_id", Integer, ForeignKey("kind.id"), nullable=False),
)
Table(
"node_group",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
)
Table(
"node_group_node",
metadata,
Column(
"node_group_id",
Integer,
ForeignKey("node_group.id"),
primary_key=True,
),
Column(
"node_id", Integer, ForeignKey("node.id"), primary_key=True
),
)
@classmethod
def setup_classes(cls):
class Kind(cls.Comparable):
pass
class Node(cls.Comparable):
pass
class NodeGroup(cls.Comparable):
pass
class NodeGroupNode(cls.Comparable):
pass
@classmethod
def insert_data(cls, connection):
kind = cls.tables.kind
connection.execute(
kind.insert(), [{"id": 1, "name": "a"}, {"id": 2, "name": "c"}]
)
node = cls.tables.node
connection.execute(
node.insert(),
{"id": 1, "name": "nc", "kind_id": 2},
)
connection.execute(
node.insert(),
{"id": 2, "name": "na", "kind_id": 1, "common_node_id": 1},
)
node_group = cls.tables.node_group
node_group_node = cls.tables.node_group_node
connection.execute(node_group.insert(), {"id": 1, "name": "group"})
connection.execute(
node_group_node.insert(),
{"id": 1, "node_group_id": 1, "node_id": 2},
)
connection.commit()
@testing.fixture(params=["common_nodes,kind", "kind,common_nodes"])
def node_fixture(self, request):
Kind, Node, NodeGroup, NodeGroupNode = self.classes(
"Kind", "Node", "NodeGroup", "NodeGroupNode"
)
kind, node, node_group, node_group_node = self.tables(
"kind", "node", "node_group", "node_group_node"
)
self.mapper_registry.map_imperatively(Kind, kind)
if request.param == "common_nodes,kind":
self.mapper_registry.map_imperatively(
Node,
node,
properties=dict(
common_node=relationship(
"Node",
remote_side=[node.c.id],
),
kind=relationship(Kind, innerjoin=True, lazy="joined"),
),
)
elif request.param == "kind,common_nodes":
self.mapper_registry.map_imperatively(
Node,
node,
properties=dict(
kind=relationship(Kind, innerjoin=True, lazy="joined"),
common_node=relationship(
"Node",
remote_side=[node.c.id],
),
),
)
self.mapper_registry.map_imperatively(
NodeGroup,
node_group,
properties=dict(
nodes=relationship(Node, secondary="node_group_node")
),
)
self.mapper_registry.map_imperatively(NodeGroupNode, node_group_node)
def test_select(self, node_fixture):
Kind, Node, NodeGroup, NodeGroupNode = self.classes(
"Kind", "Node", "NodeGroup", "NodeGroupNode"
)
session = fixture_session()
with self.sql_execution_asserter(testing.db) as asserter:
group = (
session.scalars(
select(NodeGroup)
.where(NodeGroup.name == "group")
.options(
joinedload(NodeGroup.nodes).joinedload(
Node.common_node
)
)
)
.unique()
.one_or_none()
)
eq_(group.nodes[0].common_node.kind.name, "c")
eq_(group.nodes[0].kind.name, "a")
asserter.assert_(
RegexSQL(
r"SELECT .* FROM node_group "
r"LEFT OUTER JOIN \(node_group_node AS node_group_node_1 "
r"JOIN node AS node_2 "
r"ON node_2.id = node_group_node_1.node_id "
r"JOIN kind AS kind_\d ON kind_\d.id = node_2.kind_id\) "
r"ON node_group.id = node_group_node_1.node_group_id "
r"LEFT OUTER JOIN "
r"\(node AS node_1 JOIN kind AS kind_\d "
r"ON kind_\d.id = node_1.kind_id\) "
r"ON node_1.id = node_2.common_node_id "
r"WHERE node_group.name = :name_5"
)
)
| InnerJoinSplicingWSecondarySelfRefTest |
python | pyinstaller__pyinstaller | bootloader/waflib/Errors.py | {
"start": 757,
"end": 1123
} | class ____(WafError):
def __init__(self, error_tasks=[]):
self.tasks = error_tasks
WafError.__init__(self, self.format_error())
def format_error(self):
lst = ['Build failed']
for tsk in self.tasks:
txt = tsk.format_error()
if txt:
lst.append(txt)
return '\n'.join(lst)
| BuildError |
python | getsentry__sentry | src/sentry/snuba/metrics/naming_layer/public.py | {
"start": 5864,
"end": 6053
} | class ____(Enum):
HTTP_STATUS_CODE = "span.status_code"
# TODO: these tag keys and values below probably don't belong here, and should
# be moved to another more private file.
| SpanTagsKey |
python | tiangolo__fastapi | docs_src/dependencies/tutorial003_py310.py | {
"start": 141,
"end": 603
} | class ____:
def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons=Depends(CommonQueryParams)):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response
| CommonQueryParams |
python | getsentry__sentry | src/sentry/tasks/assemble.py | {
"start": 1765,
"end": 2356
} | class ____:
DIF = "project.dsym" # Debug file upload
RELEASE_BUNDLE = "organization.artifacts" # Release file upload
ARTIFACT_BUNDLE = "organization.artifact_bundle" # Artifact bundle upload
PREPROD_ARTIFACT = "organization.preprod_artifact_bundle" # Preprod artifact upload
PREPROD_ARTIFACT_SIZE_ANALYSIS = (
"organization.preprod_artifact_size_analysis" # Preprod artifact size analysis upload
)
PREPROD_ARTIFACT_INSTALLABLE_APP = (
"organization.preprod_artifact_installable_app" # Preprod artifact installable app upload
)
| AssembleTask |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 78472,
"end": 80404
} | class ____:
"""Test sk_SK address provider methods"""
def test_street_suffix_short(self, faker, num_samples):
for _ in range(num_samples):
street_suffix_short = faker.street_suffix_short()
assert isinstance(street_suffix_short, str)
assert street_suffix_short in SkSkAddressProvider.street_suffixes_short
def test_street_suffix_long(self, faker, num_samples):
for _ in range(num_samples):
street_suffix_long = faker.street_suffix_long()
assert isinstance(street_suffix_long, str)
assert street_suffix_long in SkSkAddressProvider.street_suffixes_long
def test_city_name(self, faker, num_samples):
for _ in range(num_samples):
city = faker.city_name()
assert isinstance(city, str)
assert city in SkSkAddressProvider.cities
def test_street_name(self, faker, num_samples):
for _ in range(num_samples):
street_name = faker.street_name()
assert isinstance(street_name, str)
assert street_name in SkSkAddressProvider.streets
def test_state(self, faker, num_samples):
for _ in range(num_samples):
state = faker.state()
assert isinstance(state, str)
assert state in SkSkAddressProvider.states
def test_postcode(self, faker, num_samples):
for _ in range(num_samples):
postcode = faker.postcode()
assert isinstance(postcode, str)
assert re.fullmatch(r"\d{3} \d{2}", postcode)
def test_city_with_postcode(self, faker, num_samples):
for _ in range(num_samples):
city_with_postcode = faker.city_with_postcode()
assert isinstance(city_with_postcode, str)
match = re.fullmatch(r"\d{3} \d{2} (?P<city>.*)", city_with_postcode)
assert match.group("city") in SkSkAddressProvider.cities
| TestSkSk |
python | numba__numba | numba/tests/test_typeinfer.py | {
"start": 29052,
"end": 30223
} | class ____(numba.core.compiler.CompilerBase):
"""A compiler pipeline that skips passes after typing (provides partial typing info
but not lowering).
"""
def define_pipelines(self):
pm = numba.core.compiler_machinery.PassManager("custom_pipeline")
pm.add_pass(TranslateByteCode, "analyzing bytecode")
pm.add_pass(IRProcessing, "processing IR")
pm.add_pass(PartialTypeInference, "do partial typing")
pm.add_pass_after(DummyCR, PartialTypeInference)
pm.finalize()
return [pm]
def get_func_typing_errs(func, arg_types):
"""
Get typing errors for function 'func'. It creates a pipeline that runs untyped
passes as well as type inference.
"""
typingctx = numba.core.registry.cpu_target.typing_context
targetctx = numba.core.registry.cpu_target.target_context
library = None
return_type = None
_locals = {}
flags = numba.core.compiler.Flags()
flags.nrt = True
pipeline = TyperCompiler(
typingctx, targetctx, library, arg_types, return_type, flags, _locals
)
pipeline.compile_extra(func)
return pipeline.state.typing_errors
| TyperCompiler |
python | numpy__numpy | numpy/f2py/tests/test_character.py | {
"start": 19833,
"end": 20501
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "string", "scalar_string.f90")]
def test_char(self):
for out in (self.module.string_test.string,
self.module.string_test.string77):
expected = ()
assert out.shape == expected
expected = '|S8'
assert out.dtype == expected
def test_char_arr(self):
for out in (self.module.string_test.strarr,
self.module.string_test.strarr77):
expected = (5, 7)
assert out.shape == expected
expected = '|S12'
assert out.dtype == expected
| TestStringScalarArr |
python | kamyu104__LeetCode-Solutions | Python/number-of-subarrays-with-gcd-equal-to-k.py | {
"start": 56,
"end": 690
} | class ____(object):
def subarrayGCD(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
result = 0
dp = collections.Counter()
for x in nums:
new_dp = collections.Counter()
if x%k == 0:
dp[x] += 1
for g, cnt in dp.iteritems():
new_dp[gcd(g, x)] += cnt
dp = new_dp
result += dp[k]
return result
# Time: O(n^2)
# Space: O(1)
# brute force
| Solution |
python | huggingface__transformers | tests/models/mt5/test_modeling_mt5.py | {
"start": 33763,
"end": 35807
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (MT5EncoderModel, MT5ForTokenClassification) if is_torch_available() else ()
test_resize_embeddings = False
pipeline_model_mapping = (
{
"token-classification": MT5ForTokenClassification,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = MT5EncoderOnlyModelTester(self)
self.config_tester = ConfigTester(self, config_class=MT5Config, d_model=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@unittest.skipIf(torch_device == "cpu", "Can't do half precision")
def test_model_fp16_forward(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
def test_with_token_classification_head(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_with_token_classification_head(*config_and_inputs)
def is_pipeline_test_to_skip(
self,
pipeline_test_case_name,
config_class,
model_architecture,
tokenizer_name,
image_processor_name,
feature_extractor_name,
processor_name,
):
if tokenizer_name is None:
return True
# `MT5EncoderOnlyModelTest` is not working well with slow tokenizers (for some models) and we don't want to touch the file
# `src/transformers/data/processors/squad.py` (where this test fails for this model)
if pipeline_test_case_name == "TokenClassificationPipelineTests" and not tokenizer_name.endswith("Fast"):
return True
return False
@require_torch
@require_sentencepiece
@require_tokenizers
| MT5EncoderOnlyModelTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 13585,
"end": 13885
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_JINAAI, frozen=True, exclude=True
)
baseURL: Optional[str]
dimensions: Optional[int]
model: Optional[str]
vectorizeClassName: bool
| _Text2VecJinaConfig |
python | pypa__pipenv | pipenv/patched/pip/_internal/resolution/resolvelib/reporter.py | {
"start": 2201,
"end": 3275
} | class ____(BaseReporter[Requirement, Candidate, str]):
"""A reporter that does an info log for every event it sees."""
def starting(self) -> None:
logger.info("Reporter.starting()")
def starting_round(self, index: int) -> None:
logger.info("Reporter.starting_round(%r)", index)
def ending_round(self, index: int, state: Any) -> None:
logger.info("Reporter.ending_round(%r, state)", index)
logger.debug("Reporter.ending_round(%r, %r)", index, state)
def ending(self, state: Any) -> None:
logger.info("Reporter.ending(%r)", state)
def adding_requirement(
self, requirement: Requirement, parent: Optional[Candidate]
) -> None:
logger.info("Reporter.adding_requirement(%r, %r)", requirement, parent)
def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
logger.info("Reporter.rejecting_candidate(%r, %r)", criterion, candidate)
def pinning(self, candidate: Candidate) -> None:
logger.info("Reporter.pinning(%r)", candidate)
| PipDebuggingReporter |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 1122,
"end": 1334
} | class ____(BaseEvent):
"""Event emitted when a page is skipped due to callback decision."""
page_id: str
@classmethod
def class_name(cls) -> str:
return "PageSkippedEvent"
| PageSkippedEvent |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_view_ops.py | {
"start": 1136,
"end": 1218
} | class ____(DimSpec):
"""Output dimension is a singleton."""
@dataclass
| Singleton |
python | coleifer__peewee | tests/regressions.py | {
"start": 55556,
"end": 55662
} | class ____(TestModel):
dfc = ForeignKeyField(DFC)
name = TextField()
value = IntegerField()
| DFGC |
python | pytest-dev__pytest | testing/test_argcomplete.py | {
"start": 991,
"end": 2239
} | class ____:
"""File completer class, optionally takes a list of allowed extensions."""
def __init__(self, allowednames=(), directories=True):
# Fix if someone passes in a string instead of a list
if type(allowednames) is str:
allowednames = [allowednames]
self.allowednames = [x.lstrip("*").lstrip(".") for x in allowednames]
self.directories = directories
def __call__(self, prefix, **kwargs):
completion = []
if self.allowednames:
if self.directories:
files = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
completion += [f + "/" for f in files]
for x in self.allowednames:
completion += _wrapcall(
["bash", "-c", f"compgen -A file -X '!*.{x}' -- '{prefix}'"]
)
else:
completion += _wrapcall(["bash", "-c", f"compgen -A file -- '{prefix}'"])
anticomp = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
completion = list(set(completion) - set(anticomp))
if self.directories:
completion += [f + "/" for f in anticomp]
return completion
| FilesCompleter |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 19762,
"end": 19996
} | class ____(CellEditor):
''' Calendar-based date cell editor.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| DateEditor |
python | django__django | django/db/models/functions/math.py | {
"start": 2781,
"end": 2875
} | class ____(NumericOutputFieldMixin, Transform):
function = "EXP"
lookup_name = "exp"
| Exp |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict1.py | {
"start": 1114,
"end": 1254
} | class ____(TD3, NotATD):
pass
# This should generate an error because non-TypeDict
# base classes shouldn't be allowed for TD classes.
| TD6 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 884,
"end": 1546
} | class ____(sqltypes.Numeric, sqltypes.Integer):
__visit_name__ = "NUMBER"
def __init__(self, precision=None, scale=None, asdecimal=None):
if asdecimal is None:
asdecimal = bool(scale and scale > 0)
super().__init__(precision=precision, scale=scale, asdecimal=asdecimal)
def adapt(self, impltype):
ret = super().adapt(impltype)
# leave a hint for the DBAPI handler
ret._is_oracle_number = True
return ret
@property
def _type_affinity(self):
if bool(self.scale and self.scale > 0):
return sqltypes.Numeric
else:
return sqltypes.Integer
| NUMBER |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 72436,
"end": 72502
} | class ____(str, Enum):
MAX_SIM = "max_sim"
| MultiVectorComparator |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/tail_log.py | {
"start": 1460,
"end": 5320
} | class ____:
"""
Tail the given log files.
The log files do not have to exist when the ``start()`` method is called. The tail-er will gracefully wait until
the log files are created by the producer and will tail the contents of the
log files until the ``stop()`` method is called.
.. warning:: ``TailLog`` will wait indefinitely for the log file to be created!
Each log file's line will be suffixed with a header of the form: ``[{name}{idx}]:``,
where the ``name`` is user-provided and ``idx`` is the index of the log file
in the ``log_files`` mapping. ``log_line_prefixes`` can be used to override the
header for each log file.
Usage:
::
log_files = {0: "/tmp/0_stdout.log", 1: "/tmp/1_stdout.log"}
tailer = TailLog("trainer", log_files, sys.stdout).start()
# actually run the trainers to produce 0_stdout.log and 1_stdout.log
run_trainers()
tailer.stop()
# once run_trainers() start writing the ##_stdout.log files
# the tailer will print to sys.stdout:
# >>> [trainer0]:log_line1
# >>> [trainer1]:log_line1
# >>> [trainer0]:log_line2
# >>> [trainer0]:log_line3
# >>> [trainer1]:log_line2
.. note:: Due to buffering log lines between files may not necessarily
be printed out in order. You should configure your application's
logger to suffix each log line with a proper timestamp.
"""
def __init__(
self,
name: str,
log_files: dict[int, str],
dst: TextIO,
log_line_prefixes: dict[int, str] | None = None,
interval_sec: float = 0.1,
log_line_filter: Callable[[str], bool] = (lambda _: True),
):
n = len(log_files)
self._threadpool = None
if n > 0:
# pyrefly: ignore [bad-assignment]
self._threadpool = ThreadPoolExecutor(
max_workers=n,
thread_name_prefix=f"{self.__class__.__qualname__}_{name}",
)
self._name = name
self._dst = dst
self._log_files = log_files
self._log_line_prefixes = log_line_prefixes
self._log_line_filter = log_line_filter
self._finished_events: dict[int, Event] = {
local_rank: Event() for local_rank in log_files
}
self._futs: list[Future] = []
self._interval_sec = interval_sec
self._stopped = False
def start(self) -> "TailLog":
if not self._threadpool or not self._dst:
return self
for local_rank, file in self._log_files.items():
header = f"[{self._name}{local_rank}]:"
if self._log_line_prefixes and local_rank in self._log_line_prefixes:
header = self._log_line_prefixes[local_rank]
self._futs.append(
self._threadpool.submit(
tail_logfile,
header=header,
file=file,
dst=self._dst,
finished=self._finished_events[local_rank],
interval_sec=self._interval_sec,
log_line_filter=self._log_line_filter,
)
)
return self
def stop(self) -> None:
for finished in self._finished_events.values():
finished.set()
for local_rank, f in enumerate(self._futs):
try:
f.result()
except Exception as e:
logger.exception(
"error in log tailor for %s%s. %s",
self._name,
local_rank,
e.__class__.__qualname__,
)
if self._threadpool:
self._threadpool.shutdown(wait=True)
self._stopped = True
def stopped(self) -> bool:
return self._stopped
| TailLog |
python | celery__celery | examples/stamping/visitors.py | {
"start": 385,
"end": 649
} | class ____(StampingVisitor):
def on_signature(self, sig: Signature, **headers) -> dict:
mtask_id = str(uuid4())
logger.critical(f"Visitor: Sig '{sig}' is stamped with: {mtask_id}")
return {"mtask_id": mtask_id}
| MonitoringIdStampingVisitor |
python | django__django | tests/m2m_regress/models.py | {
"start": 173,
"end": 391
} | class ____(models.Model):
name = models.CharField(max_length=10)
references = models.ManyToManyField("self")
related = models.ManyToManyField("self")
def __str__(self):
return self.name
| SelfRefer |
python | getsentry__sentry | src/sentry/uptime/endpoints/validators.py | {
"start": 16444,
"end": 21088
} | class ____(BaseDetectorTypeValidator):
enforce_single_datasource = True
data_sources = serializers.ListField(child=UptimeMonitorDataSourceValidator(), required=False)
def validate_config(self, config: dict[str, Any]) -> dict[str, Any]:
"""
Validate that only superusers can change mode to non-MANUAL values.
When a non-superuser updates a monitor that is not in MANUAL mode,
automatically switch to MANUAL.
"""
if "mode" not in config:
return config
mode = config["mode"]
# For updates, if current mode is not MANUAL and user is not a superuser,
# automatically switch to MANUAL mode
if self.instance:
current_mode = self.instance.config.get("mode")
if current_mode != UptimeMonitorMode.MANUAL:
request = self.context["request"]
if not is_active_superuser(request):
config["mode"] = UptimeMonitorMode.MANUAL
return config
# If mode hasn't changed, no further validation needed
if current_mode == mode:
return config
# Only superusers can set/change mode to anything other than MANUAL
if mode != UptimeMonitorMode.MANUAL:
request = self.context["request"]
if not is_active_superuser(request):
raise serializers.ValidationError("Only superusers can modify `mode`")
return config
def validate_enabled(self, value: bool) -> bool:
"""
Validate that enabling a detector is allowed based on seat availability.
This check will ONLY be performed when a detector instance is provided via
context (i.e., during updates). For creation, seat assignment is handled
in the create() method after the detector is created.
"""
detector = self.instance
# Only validate on updates when trying to enable a currently disabled detector
if detector and value and not detector.enabled:
result = quotas.backend.check_assign_seat(DataCategory.UPTIME, detector)
if not result.assignable:
raise serializers.ValidationError(result.reason)
return value
def create(self, validated_data):
detector = super().create(validated_data)
try:
enable_uptime_detector(detector, ensure_assignment=True)
except UptimeMonitorNoSeatAvailable:
# No need to do anything if we failed to handle seat
# assignment. The monitor will be created, but not enabled
pass
return detector
def update(self, instance: Detector, validated_data: dict[str, Any]) -> Detector:
# Handle seat management when enabling/disabling
was_enabled = instance.enabled
enabled = validated_data.get("enabled", was_enabled)
if was_enabled != enabled:
if enabled:
enable_uptime_detector(instance)
else:
disable_uptime_detector(instance)
super().update(instance, validated_data)
data_source = None
if "data_sources" in validated_data:
data_source = validated_data.pop("data_sources")[0]
if data_source is not None:
self.update_data_source(instance, data_source)
return instance
def update_data_source(self, instance: Detector, data_source: dict[str, Any]):
subscription = get_uptime_subscription(instance)
update_uptime_subscription(
subscription=subscription,
url=data_source.get("url", NOT_SET),
interval_seconds=data_source.get("interval_seconds", NOT_SET),
timeout_ms=data_source.get("timeout_ms", NOT_SET),
method=data_source.get("method", NOT_SET),
headers=data_source.get("headers", NOT_SET),
body=data_source.get("body", NOT_SET),
trace_sampling=data_source.get("trace_sampling", NOT_SET),
)
create_audit_entry(
request=self.context["request"],
organization=self.context["organization"],
target_object=instance.id,
event=audit_log.get_event_id("UPTIME_MONITOR_EDIT"),
data=instance.get_audit_log_data(),
)
return instance
def delete(self) -> None:
assert self.instance is not None
remove_uptime_seat(self.instance)
uptime_subscription = get_uptime_subscription(self.instance)
delete_uptime_subscription(uptime_subscription)
super().delete()
| UptimeDomainCheckFailureValidator |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/__init__.py | {
"start": 852,
"end": 5857
} | class ____(AutoSklearnChoice):
@classmethod
def get_components(cls):
components = OrderedDict()
components.update(_classifiers)
components.update(additional_components.components)
return components
def get_available_components(
cls, dataset_properties=None, include=None, exclude=None
):
if dataset_properties is None:
dataset_properties = {}
available_comp = cls.get_components()
components_dict = OrderedDict()
if include is not None and exclude is not None:
raise ValueError(
"The argument include and exclude cannot be used together."
)
if include is not None:
for incl in include:
if incl not in available_comp:
raise ValueError(
"Trying to include unknown component: " "%s" % incl
)
for name in available_comp:
if include is not None and name not in include:
continue
elif exclude is not None and name in exclude:
continue
entry = available_comp[name]
# Avoid infinite loop
if entry == ClassifierChoice:
continue
if entry.get_properties()["handles_classification"] is False:
continue
if (
dataset_properties.get("multiclass") is True
and entry.get_properties()["handles_multiclass"] is False
):
continue
if (
dataset_properties.get("multilabel") is True
and available_comp[name].get_properties()["handles_multilabel"] is False
):
continue
components_dict[name] = entry
return components_dict
def get_hyperparameter_search_space(
self,
feat_type: FEAT_TYPE_TYPE,
dataset_properties=None,
default=None,
include=None,
exclude=None,
):
if dataset_properties is None:
dataset_properties = {}
if include is not None and exclude is not None:
raise ValueError(
"The arguments include and " "exclude cannot be used together."
)
cs = ConfigurationSpace()
# Compile a list of all estimator objects for this problem
available_estimators = self.get_available_components(
dataset_properties=dataset_properties, include=include, exclude=exclude
)
if len(available_estimators) == 0:
raise ValueError("No classifiers found")
if default is None:
defaults = ["random_forest", "liblinear_svc", "sgd", "libsvm_svc"] + list(
available_estimators.keys()
)
for default_ in defaults:
if default_ in available_estimators:
if include is not None and default_ not in include:
continue
if exclude is not None and default_ in exclude:
continue
default = default_
break
estimator = CategoricalHyperparameter(
"__choice__", list(available_estimators.keys()), default_value=default
)
cs.add_hyperparameter(estimator)
for estimator_name in available_estimators.keys():
estimator_configuration_space = available_estimators[
estimator_name
].get_hyperparameter_search_space(
feat_type=feat_type, dataset_properties=dataset_properties
)
parent_hyperparameter = {"parent": estimator, "value": estimator_name}
cs.add_configuration_space(
estimator_name,
estimator_configuration_space,
parent_hyperparameter=parent_hyperparameter,
)
self.configuration_space = cs
self.dataset_properties = dataset_properties
return cs
def predict_proba(self, X):
return self.choice.predict_proba(X)
def estimator_supports_iterative_fit(self):
return hasattr(self.choice, "iterative_fit")
def get_max_iter(self):
if self.estimator_supports_iterative_fit():
return self.choice.get_max_iter()
else:
raise NotImplementedError()
def get_current_iter(self):
if self.estimator_supports_iterative_fit():
return self.choice.get_current_iter()
else:
raise NotImplementedError()
def iterative_fit(self, X, y, n_iter=1, **fit_params):
# Allows to use check_is_fitted on the choice object
self.fitted_ = True
if fit_params is None:
fit_params = {}
return self.choice.iterative_fit(X, y, n_iter=n_iter, **fit_params)
def configuration_fully_fitted(self):
return self.choice.configuration_fully_fitted()
| ClassifierChoice |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 3552,
"end": 4247
} | class ____(enum.Enum):
UNINITIALIZED = 0
ZERO_ON_CALL = 1 # kernel may leave workspace dirty
ZERO_PER_GRAPH = 2 # must be re-zeroed by kernel
@staticmethod
def combine(a: WorkspaceZeroMode, b: WorkspaceZeroMode) -> WorkspaceZeroMode:
if a == b or b == WorkspaceZeroMode.UNINITIALIZED:
return a
if a == WorkspaceZeroMode.UNINITIALIZED:
return b
raise NotImplementedError(f"WorkspaceZeroMode.combine({a!r}, {b!r})")
@staticmethod
def from_bool(zero_fill: bool) -> WorkspaceZeroMode:
if zero_fill:
return WorkspaceZeroMode.ZERO_ON_CALL
return WorkspaceZeroMode.UNINITIALIZED
| WorkspaceZeroMode |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/transfers/oracle_to_azure_data_lake.py | {
"start": 1238,
"end": 4537
} | class ____(BaseOperator):
"""
Runs the query against Oracle and stores the file locally before loading it into Azure Data Lake.
:param filename: file name to be used by the csv file.
:param azure_data_lake_conn_id: destination azure data lake connection.
:param azure_data_lake_path: destination path in azure data lake to put the file.
:param oracle_conn_id: :ref:`Source Oracle connection <howto/connection:oracle>`.
:param sql: SQL query to execute against the Oracle database. (templated)
:param sql_params: Parameters to use in sql query. (templated)
:param delimiter: field delimiter in the file.
:param encoding: encoding type for the file.
:param quotechar: Character to use in quoting.
:param quoting: Quoting strategy. See csv library for more information.
It can take on any of the csv.QUOTE_* constants.
"""
template_fields: Sequence[str] = ("filename", "sql", "sql_params")
template_fields_renderers = {"sql_params": "py"}
ui_color = "#e08c8c"
def __init__(
self,
*,
filename: str,
azure_data_lake_conn_id: str,
azure_data_lake_path: str,
oracle_conn_id: str,
sql: str,
sql_params: dict | None = None,
delimiter: str = ",",
encoding: str = "utf-8",
quotechar: str = '"',
quoting: Literal[0, 1, 2, 3] = csv.QUOTE_MINIMAL,
**kwargs,
) -> None:
super().__init__(**kwargs)
if sql_params is None:
sql_params = {}
self.filename = filename
self.oracle_conn_id = oracle_conn_id
self.sql = sql
self.sql_params = sql_params
self.azure_data_lake_conn_id = azure_data_lake_conn_id
self.azure_data_lake_path = azure_data_lake_path
self.delimiter = delimiter
self.encoding = encoding
self.quotechar = quotechar
self.quoting = quoting
def _write_temp_file(self, cursor: Any, path_to_save: str | bytes | int) -> None:
with open(path_to_save, "w", encoding=self.encoding) as csvfile:
csv_writer = csv.writer(
csvfile,
delimiter=self.delimiter,
quotechar=self.quotechar,
quoting=self.quoting,
)
csv_writer.writerow(field[0] for field in cursor.description)
csv_writer.writerows(cursor)
csvfile.flush()
def execute(self, context: Context) -> None:
oracle_hook = OracleHook(oracle_conn_id=self.oracle_conn_id)
azure_data_lake_hook = AzureDataLakeHook(azure_data_lake_conn_id=self.azure_data_lake_conn_id)
self.log.info("Dumping Oracle query results to local file")
conn = oracle_hook.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql, self.sql_params)
with TemporaryDirectory(prefix="airflow_oracle_to_azure_op_") as temp:
self._write_temp_file(cursor, os.path.join(temp, self.filename))
self.log.info("Uploading local file to Azure Data Lake")
azure_data_lake_hook.upload_file(
os.path.join(temp, self.filename), os.path.join(self.azure_data_lake_path, self.filename)
)
cursor.close()
conn.close()
| OracleToAzureDataLakeOperator |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py | {
"start": 4168,
"end": 4243
} | class ____(object):
ORIGINAL = 0
CALIBRATE = 1
INFERENCE = 2
| GraphState |
python | django__django | django/utils/text.py | {
"start": 2803,
"end": 4531
} | class ____(HTMLParser):
class TruncationCompleted(Exception):
pass
def __init__(self, *, length, replacement, convert_charrefs=True):
super().__init__(convert_charrefs=convert_charrefs)
self.tags = deque()
self.output = []
self.remaining = length
self.replacement = replacement
@cached_property
def void_elements(self):
from django.utils.html import VOID_ELEMENTS
return VOID_ELEMENTS
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
if tag not in self.void_elements:
self.handle_endtag(tag)
def handle_starttag(self, tag, attrs):
self.output.append(self.get_starttag_text())
if tag not in self.void_elements:
self.tags.appendleft(tag)
def handle_endtag(self, tag):
if tag not in self.void_elements:
self.output.append(f"</{tag}>")
try:
self.tags.remove(tag)
except ValueError:
pass
def handle_data(self, data):
data, output = self.process(data)
data_len = len(data)
if self.remaining < data_len:
self.remaining = 0
self.output.append(add_truncation_text(output, self.replacement))
raise self.TruncationCompleted
self.remaining -= data_len
self.output.append(output)
def feed(self, data):
try:
super().feed(data)
except self.TruncationCompleted:
self.output.extend([f"</{tag}>" for tag in self.tags])
self.tags.clear()
self.reset()
else:
# No data was handled.
self.reset()
| TruncateHTMLParser |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_port_status.py | {
"start": 383,
"end": 6010
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'error': 'str',
'port': 'int',
'protocol': 'str'
}
attribute_map = {
'error': 'error',
'port': 'port',
'protocol': 'protocol'
}
def __init__(self, error=None, port=None, protocol=None, local_vars_configuration=None): # noqa: E501
"""V1IngressPortStatus - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._error = None
self._port = None
self._protocol = None
self.discriminator = None
if error is not None:
self.error = error
self.port = port
self.protocol = protocol
@property
def error(self):
"""Gets the error of this V1IngressPortStatus. # noqa: E501
error is to record the problem with the service port The format of the error shall comply with the following rules: - built-in error values shall be specified in this file and those shall use CamelCase names - cloud provider specific error values must have names that comply with the format foo.example.com/CamelCase. # noqa: E501
:return: The error of this V1IngressPortStatus. # noqa: E501
:rtype: str
"""
return self._error
@error.setter
def error(self, error):
"""Sets the error of this V1IngressPortStatus.
error is to record the problem with the service port The format of the error shall comply with the following rules: - built-in error values shall be specified in this file and those shall use CamelCase names - cloud provider specific error values must have names that comply with the format foo.example.com/CamelCase. # noqa: E501
:param error: The error of this V1IngressPortStatus. # noqa: E501
:type: str
"""
self._error = error
@property
def port(self):
"""Gets the port of this V1IngressPortStatus. # noqa: E501
port is the port number of the ingress port. # noqa: E501
:return: The port of this V1IngressPortStatus. # noqa: E501
:rtype: int
"""
return self._port
@port.setter
def port(self, port):
"""Sets the port of this V1IngressPortStatus.
port is the port number of the ingress port. # noqa: E501
:param port: The port of this V1IngressPortStatus. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and port is None: # noqa: E501
raise ValueError("Invalid value for `port`, must not be `None`") # noqa: E501
self._port = port
@property
def protocol(self):
"""Gets the protocol of this V1IngressPortStatus. # noqa: E501
protocol is the protocol of the ingress port. The supported values are: \"TCP\", \"UDP\", \"SCTP\" # noqa: E501
:return: The protocol of this V1IngressPortStatus. # noqa: E501
:rtype: str
"""
return self._protocol
@protocol.setter
def protocol(self, protocol):
"""Sets the protocol of this V1IngressPortStatus.
protocol is the protocol of the ingress port. The supported values are: \"TCP\", \"UDP\", \"SCTP\" # noqa: E501
:param protocol: The protocol of this V1IngressPortStatus. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and protocol is None: # noqa: E501
raise ValueError("Invalid value for `protocol`, must not be `None`") # noqa: E501
self._protocol = protocol
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1IngressPortStatus):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1IngressPortStatus):
return True
return self.to_dict() != other.to_dict()
| V1IngressPortStatus |
python | sqlalchemy__sqlalchemy | test/orm/test_session.py | {
"start": 49843,
"end": 52039
} | class ____(_fixtures.FixtureTest):
__sparse_driver_backend__ = True
def test_autoflush_rollback(self):
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
self.mapper_registry.map_imperatively(Address, addresses)
self.mapper_registry.map_imperatively(
User, users, properties={"addresses": relationship(Address)}
)
sess = fixture_session(autoflush=True)
u = sess.get(User, 8)
newad = Address(email_address="a new address")
u.addresses.append(newad)
u.name = "some new name"
assert u.name == "some new name"
assert len(u.addresses) == 4
assert newad in u.addresses
sess.rollback()
assert u.name == "ed"
assert len(u.addresses) == 3
assert newad not in u.addresses
# pending objects don't get expired
assert newad.email_address == "a new address"
def test_expunge_cascade(self):
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
self.mapper_registry.map_imperatively(Address, addresses)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address,
backref=backref("user", cascade="all"),
cascade="all",
)
},
)
session = fixture_session()
u = session.query(User).filter_by(id=7).one()
# get everything to load in both directions
print([a.user for a in u.addresses])
# then see if expunge fails
session.expunge(u)
assert sa.orm.object_session(u) is None
assert sa.orm.attributes.instance_state(u).session_id is None
for a in u.addresses:
assert sa.orm.object_session(a) is None
assert sa.orm.attributes.instance_state(a).session_id is None
| SessionStateWFixtureTest |
python | huggingface__transformers | src/transformers/models/falcon_h1/modeling_falcon_h1.py | {
"start": 55069,
"end": 57348
} | class ____(PreTrainedModel):
config: FalconH1Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["FalconH1DecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_is_stateful = True
@torch.no_grad()
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, FalconH1Mixer):
init.ones_(module.dt_bias)
init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
init.ones_(module.D)
def compute_mup_vector(config):
"""
Computes the MuP vector based on model configuration.
FalconH1 applies different MuP multiplier for each dimension of the hidden states.
The MuP vector is partitioned into chunks, and each chunk is multiplied with its
corresponding projected dimension.
Args:
config: FalconH1Config object
Returns:
torch.Tensor: The computed MuP vector
"""
# We'll need some values from the config to compute the vector dimensions
intermediate_size = (
config.mamba_d_ssm if config.mamba_d_ssm is not None else int(config.mamba_expand * config.hidden_size)
)
groups_time_state_size = config.mamba_n_groups * config.mamba_d_state
num_heads = config.mamba_n_heads
zxbcdt_multipliers = config.ssm_multipliers
vector_shape = 2 * intermediate_size + 2 * groups_time_state_size + num_heads
mup_vector = torch.ones(1, 1, vector_shape)
# Apply multipliers to different sections of the vector
mup_vector[:, :, :intermediate_size] *= zxbcdt_multipliers[0]
mup_vector[:, :, intermediate_size : 2 * intermediate_size] *= zxbcdt_multipliers[1]
mup_vector[:, :, 2 * intermediate_size : 2 * intermediate_size + groups_time_state_size] *= zxbcdt_multipliers[2]
mup_vector[
:, :, 2 * intermediate_size + groups_time_state_size : 2 * intermediate_size + 2 * groups_time_state_size
] *= zxbcdt_multipliers[3]
mup_vector[:, :, 2 * intermediate_size + 2 * groups_time_state_size :] *= zxbcdt_multipliers[4]
return mup_vector
@auto_docstring
# Adapted from transformers.models.jamba.modeling_jamba.JambaModel
| FalconH1PreTrainedModel |
python | google__python-fire | fire/console/console_attr.py | {
"start": 4225,
"end": 4615
} | class ____(ProgressTrackerSymbols):
"""Characters used by progress trackers."""
@property
def spin_marks(self):
return ['⠏', '⠛', '⠹', '⠼', '⠶', '⠧']
success = text.TypedText(['✓'], text_type=text.TextTypes.PT_SUCCESS)
failed = text.TypedText(['X'], text_type=text.TextTypes.PT_FAILURE)
interrupted = '-'
not_started = '.'
prefix_length = 2
| ProgressTrackerSymbolsUnicode |
python | google__jax | jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py | {
"start": 4086,
"end": 4591
} | class ____(Mask):
left: Mask
right: Mask
def __init__(self, left: Mask, right: Mask):
if left.shape != right.shape:
raise ValueError('Masks must have the same shape')
self.left = left
self.right = right
@property
def shape(self) -> tuple[int, ...]:
return self.left.shape
def __getitem__(self, idx) -> np.ndarray:
return self.left[idx] | self.right[idx]
def __hash__(self):
return hash((type(self),) + (self.left, self.right))
@dataclasses.dataclass
| LogicalOr |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 40632,
"end": 44490
} | class ____(VCSFetchStrategy):
"""Fetch strategy that gets source code from a CVS repository.
Use like this in a package::
version("name", cvs=":pserver:anonymous@www.example.com:/cvsroot%module=modulename")
Optionally, you can provide a branch and/or a date for the URL::
version(
"name",
cvs=":pserver:anonymous@www.example.com:/cvsroot%module=modulename",
branch="branchname", date="date"
)
Repositories are checked out into the standard stage source path directory.
"""
url_attr = "cvs"
optional_attrs = ["branch", "date"]
def __init__(self, **kwargs):
# Discards the keywords in kwargs that may conflict with the next call
# to __init__
forwarded_args = copy.copy(kwargs)
forwarded_args.pop("name", None)
super().__init__(**forwarded_args)
self._cvs = None
if self.branch is not None:
self.branch = str(self.branch)
if self.date is not None:
self.date = str(self.date)
@property
def cvs(self):
if not self._cvs:
self._cvs = which("cvs", required=True)
return self._cvs
@property
def cachable(self):
return self.cache_enabled and (bool(self.branch) or bool(self.date))
def source_id(self):
if not (self.branch or self.date):
# We need a branch or a date to make a checkout reproducible
return None
id = "id"
if self.branch:
id += "-branch=" + self.branch
if self.date:
id += "-date=" + self.date
return id
def mirror_id(self):
if not (self.branch or self.date):
# We need a branch or a date to make a checkout reproducible
return None
# Special-case handling because this is not actually a URL
elements = self.url.split(":")
final = elements[-1]
elements = final.split("/")
# Everything before the first slash is a port number
elements = elements[1:]
result = os.path.sep.join(["cvs"] + elements)
if self.branch:
result += "%branch=" + self.branch
if self.date:
result += "%date=" + self.date
return result
@_needs_stage
def fetch(self):
if self.stage.expanded:
tty.debug("Already fetched {0}".format(self.stage.source_path))
return
tty.debug("Checking out CVS repository: {0}".format(self.url))
with temp_cwd():
url, module = self.url.split("%module=")
# Check out files
args = ["-z9", "-d", url, "checkout"]
if self.branch is not None:
args.extend(["-r", self.branch])
if self.date is not None:
args.extend(["-D", self.date])
args.append(module)
self.cvs(*args)
# Rename repo
repo_name = get_single_file(".")
self.stage.srcdir = repo_name
shutil.move(repo_name, self.stage.source_path)
def _remove_untracked_files(self):
"""Removes untracked files in a CVS repository."""
with working_dir(self.stage.source_path):
status = self.cvs("-qn", "update", output=str)
for line in status.split("\n"):
if re.match(r"^[?]", line):
path = line[2:].strip()
if os.path.isfile(path):
os.unlink(path)
def archive(self, destination):
super().archive(destination, exclude="CVS")
@_needs_stage
def reset(self):
self._remove_untracked_files()
with working_dir(self.stage.source_path):
self.cvs("update", "-C", ".")
def __str__(self):
return "[cvs] %s" % self.url
@fetcher
| CvsFetchStrategy |
python | getsentry__sentry | src/sentry/sentry_metrics/configuration.py | {
"start": 1319,
"end": 6565
} | class ____:
db_backend: IndexerStorage
db_backend_options: Mapping[str, Any]
output_topic: Topic
use_case_id: UseCaseKey
internal_metrics_tag: str | None
writes_limiter_cluster_options: Mapping[str, Any]
writes_limiter_namespace: str
should_index_tag_values: bool
schema_validation_rule_option_name: str | None = None
is_output_sliced: bool | None = False
_METRICS_INGEST_CONFIG_BY_USE_CASE: MutableMapping[
tuple[UseCaseKey, IndexerStorage], MetricsIngestConfiguration
] = dict()
def _register_ingest_config(config: MetricsIngestConfiguration) -> None:
_METRICS_INGEST_CONFIG_BY_USE_CASE[(config.use_case_id, config.db_backend)] = config
def get_ingest_config(
use_case_key: UseCaseKey, db_backend: IndexerStorage
) -> MetricsIngestConfiguration:
if len(_METRICS_INGEST_CONFIG_BY_USE_CASE) == 0:
from django.conf import settings
_register_ingest_config(
MetricsIngestConfiguration(
db_backend=IndexerStorage.POSTGRES,
db_backend_options={},
output_topic=Topic.SNUBA_METRICS,
use_case_id=UseCaseKey.RELEASE_HEALTH,
internal_metrics_tag="release-health",
writes_limiter_cluster_options=settings.SENTRY_METRICS_INDEXER_WRITES_LIMITER_OPTIONS,
writes_limiter_namespace=RELEASE_HEALTH_PG_NAMESPACE,
should_index_tag_values=True,
schema_validation_rule_option_name=RELEASE_HEALTH_SCHEMA_VALIDATION_RULES_OPTION_NAME,
)
)
_register_ingest_config(
MetricsIngestConfiguration(
db_backend=IndexerStorage.POSTGRES,
db_backend_options={},
output_topic=Topic.SNUBA_GENERIC_METRICS,
use_case_id=UseCaseKey.PERFORMANCE,
internal_metrics_tag="perf",
writes_limiter_cluster_options=settings.SENTRY_METRICS_INDEXER_WRITES_LIMITER_OPTIONS_PERFORMANCE,
writes_limiter_namespace=PERFORMANCE_PG_NAMESPACE,
is_output_sliced=settings.SENTRY_METRICS_INDEXER_ENABLE_SLICED_PRODUCER,
should_index_tag_values=False,
schema_validation_rule_option_name=GENERIC_METRICS_SCHEMA_VALIDATION_RULES_OPTION_NAME,
)
)
if (use_case_key, db_backend) == (UseCaseKey.RELEASE_HEALTH, IndexerStorage.MOCK):
_register_ingest_config(
MetricsIngestConfiguration(
db_backend=IndexerStorage.MOCK,
db_backend_options={},
output_topic=Topic.SNUBA_METRICS,
use_case_id=use_case_key,
internal_metrics_tag="release-health",
writes_limiter_cluster_options={},
writes_limiter_namespace="test-namespace-rh",
should_index_tag_values=True,
schema_validation_rule_option_name=RELEASE_HEALTH_SCHEMA_VALIDATION_RULES_OPTION_NAME,
)
)
if (use_case_key, db_backend) == (UseCaseKey.PERFORMANCE, IndexerStorage.MOCK):
_register_ingest_config(
MetricsIngestConfiguration(
db_backend=IndexerStorage.MOCK,
db_backend_options={},
output_topic=Topic.SNUBA_GENERIC_METRICS,
use_case_id=use_case_key,
internal_metrics_tag="perf",
writes_limiter_cluster_options={},
writes_limiter_namespace="test-namespace-perf",
should_index_tag_values=False,
schema_validation_rule_option_name=GENERIC_METRICS_SCHEMA_VALIDATION_RULES_OPTION_NAME,
)
)
return _METRICS_INGEST_CONFIG_BY_USE_CASE[(use_case_key, db_backend)]
def initialize_subprocess_state(config: MetricsIngestConfiguration) -> None:
"""
Initialization function for the subprocesses of the metrics indexer.
`config` is pickleable, and this function lives in a module that can be
imported without any upfront initialization of the Django app. Meaning that
an object like
`functools.partial(initialize_sentry_and_global_consumer_state, config)` is
pickleable as well (which we pass as initialization callback to arroyo).
This function should ideally be kept minimal and not contain too much
logic. Commonly reusable bits should be added to
sentry.utils.arroyo.run_task_with_multiprocessing.
We already rely on sentry.utils.arroyo.run_task_with_multiprocessing to copy
statsd tags into the subprocess, eventually we should do the same for
Sentry tags.
"""
sentry_sdk.set_tag("sentry_metrics.use_case_key", config.use_case_id.value)
def initialize_main_process_state(config: MetricsIngestConfiguration) -> None:
"""
Initialization function for the main process of the metrics indexer.
This primarily sets global tags for instrumentation in both our
statsd/metrics usage and the Sentry SDK.
"""
sentry_sdk.set_tag("sentry_metrics.use_case_key", config.use_case_id.value)
from sentry.utils.metrics import add_global_tags
add_global_tags(all_threads=True, tags={"pipeline": config.internal_metrics_tag or ""})
| MetricsIngestConfiguration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py | {
"start": 40830,
"end": 44865
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a tag template and all tags using the template.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataCatalogDeleteTagTemplateOperator`
:param location: Required. The location of the tag template to delete.
:param tag_template: ID for tag template that is deleted.
:param project_id: The ID of the Google Cloud project that owns the entry group.
If set to ``None`` or missing, the default project_id from the Google Cloud connection is used.
:param force: Required. Currently, this field must always be set to ``true``. This confirms the
deletion of any possible tags using this template. ``force = false`` will be supported in the
future.
:param retry: A retry object used to retry requests. If ``None`` is specified, requests will be
retried using a default configuration.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
``retry`` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud.
Defaults to 'google_cloud_default'.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"location",
"tag_template",
"force",
"project_id",
"retry",
"timeout",
"metadata",
"gcp_conn_id",
"impersonation_chain",
)
def __init__(
self,
*,
location: str,
tag_template: str,
force: bool,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.location = location
self.tag_template = tag_template
self.force = force
self.project_id = project_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> None:
hook = CloudDataCatalogHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
try:
hook.delete_tag_template(
location=self.location,
tag_template=self.tag_template,
force=self.force,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
except NotFound:
self.log.info("Tag Template doesn't exists. skipping")
@deprecated(
planned_removal_date="January 30, 2026",
use_instead="airflow.providers.google.cloud.operators.dataplex.DataplexCatalogUpdateAspectTypeOperator",
reason="The Data Catalog will be discontinued on January 30, 2026 "
"in favor of Dataplex Universal Catalog.",
category=AirflowProviderDeprecationWarning,
)
| CloudDataCatalogDeleteTagTemplateOperator |
python | plotly__plotly.py | plotly/graph_objs/layout/yaxis/_minor.py | {
"start": 235,
"end": 20338
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.yaxis"
_path_str = "layout.yaxis.minor"
_valid_props = {
"dtick",
"gridcolor",
"griddash",
"gridwidth",
"nticks",
"showgrid",
"tick0",
"tickcolor",
"ticklen",
"tickmode",
"ticks",
"tickvals",
"tickvalssrc",
"tickwidth",
}
@property
def dtick(self):
"""
Sets the step in-between ticks on this axis. Use with `tick0`.
Must be a positive number, or special strings available to
"log" and "date" axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick number. For
example, to set a tick mark at 1, 10, 100, 1000, ... set dtick
to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2.
To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special values;
"L<f>", where `f` is a positive number, gives ticks linearly
spaced in value (but not position). For example `tick0` = 0.1,
`dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To
show powers of 10 plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and
"D2". If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval between
ticks to one day, set `dtick` to 86400000.0. "date" also has
special values "M<n>" gives ticks spaced by a number of months.
`n` must be a positive integer. To set ticks on the 15th of
every third month, set `tick0` to "2000-01-15" and `dtick` to
"M3". To set ticks every 4 years, set `dtick` to "M48"
The 'dtick' property accepts values of any type
Returns
-------
Any
"""
return self["dtick"]
@dtick.setter
def dtick(self, val):
self["dtick"] = val
@property
def gridcolor(self):
"""
Sets the color of the grid lines.
The 'gridcolor' 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["gridcolor"]
@gridcolor.setter
def gridcolor(self, val):
self["gridcolor"] = val
@property
def griddash(self):
"""
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
The 'griddash' property is an enumeration that may be specified as:
- One of the following dash styles:
['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot']
- A string containing a dash length list in pixels or percentages
(e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.)
Returns
-------
str
"""
return self["griddash"]
@griddash.setter
def griddash(self, val):
self["griddash"] = val
@property
def gridwidth(self):
"""
Sets the width (in px) of the grid lines.
The 'gridwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["gridwidth"]
@gridwidth.setter
def gridwidth(self, val):
self["gridwidth"] = val
@property
def nticks(self):
"""
Specifies the maximum number of ticks for the particular axis.
The actual number of ticks will be chosen automatically to be
less than or equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
The 'nticks' 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["nticks"]
@nticks.setter
def nticks(self, val):
self["nticks"] = val
@property
def showgrid(self):
"""
Determines whether or not grid lines are drawn. If True, the
grid lines are drawn at every tick mark.
The 'showgrid' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showgrid"]
@showgrid.setter
def showgrid(self, val):
self["showgrid"] = val
@property
def tick0(self):
"""
Sets the placement of the first tick on this axis. Use with
`dtick`. If the axis `type` is "log", then you must take the
log of your starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when `dtick`=*L<f>* (see
`dtick` for more info). If the axis `type` is "date", it should
be a date string, like date data. If the axis `type` is
"category", it should be a number, using the scale where each
category is assigned a serial number from zero in the order it
appears.
The 'tick0' property accepts values of any type
Returns
-------
Any
"""
return self["tick0"]
@tick0.setter
def tick0(self, val):
self["tick0"] = val
@property
def tickcolor(self):
"""
Sets the tick color.
The 'tickcolor' 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["tickcolor"]
@tickcolor.setter
def tickcolor(self, val):
self["tickcolor"] = val
@property
def ticklen(self):
"""
Sets the tick length (in px).
The 'ticklen' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ticklen"]
@ticklen.setter
def ticklen(self, val):
self["ticklen"] = val
@property
def tickmode(self):
"""
Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any
"""
return self["tickmode"]
@tickmode.setter
def tickmode(self, val):
self["tickmode"] = val
@property
def ticks(self):
"""
Determines whether ticks are drawn or not. If "", this axis'
ticks are not drawn. If "outside" ("inside"), this axis' are
drawn outside (inside) the axis lines.
The 'ticks' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', '']
Returns
-------
Any
"""
return self["ticks"]
@ticks.setter
def ticks(self, val):
self["ticks"] = val
@property
def tickvals(self):
"""
Sets the values at which ticks on this axis appear. Only has an
effect if `tickmode` is set to "array". Used with `ticktext`.
The 'tickvals' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["tickvals"]
@tickvals.setter
def tickvals(self, val):
self["tickvals"] = val
@property
def tickvalssrc(self):
"""
Sets the source reference on Chart Studio Cloud for `tickvals`.
The 'tickvalssrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["tickvalssrc"]
@tickvalssrc.setter
def tickvalssrc(self, val):
self["tickvalssrc"] = val
@property
def tickwidth(self):
"""
Sets the tick width (in px).
The 'tickwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["tickwidth"]
@tickwidth.setter
def tickwidth(self, val):
self["tickwidth"] = val
@property
def _prop_descriptions(self):
return """\
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
showgrid
Determines whether or not grid lines are drawn. If
True, the grid lines are drawn at every tick mark.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickcolor
Sets the tick color.
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
"""
def __init__(
self,
arg=None,
dtick=None,
gridcolor=None,
griddash=None,
gridwidth=None,
nticks=None,
showgrid=None,
tick0=None,
tickcolor=None,
ticklen=None,
tickmode=None,
ticks=None,
tickvals=None,
tickvalssrc=None,
tickwidth=None,
**kwargs,
):
"""
Construct a new Minor object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.yaxis.Minor`
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
showgrid
Determines whether or not grid lines are drawn. If
True, the grid lines are drawn at every tick mark.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickcolor
Sets the tick color.
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
Returns
-------
Minor
"""
super().__init__("minor")
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.layout.yaxis.Minor
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.yaxis.Minor`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("dtick", arg, dtick)
self._set_property("gridcolor", arg, gridcolor)
self._set_property("griddash", arg, griddash)
self._set_property("gridwidth", arg, gridwidth)
self._set_property("nticks", arg, nticks)
self._set_property("showgrid", arg, showgrid)
self._set_property("tick0", arg, tick0)
self._set_property("tickcolor", arg, tickcolor)
self._set_property("ticklen", arg, ticklen)
self._set_property("tickmode", arg, tickmode)
self._set_property("ticks", arg, ticks)
self._set_property("tickvals", arg, tickvals)
self._set_property("tickvalssrc", arg, tickvalssrc)
self._set_property("tickwidth", arg, tickwidth)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Minor |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi_list.py | {
"start": 5136,
"end": 8022
} | class ____:
@mock.patch.object(BaseHook, "get_connection", side_effect=get_airflow_connection)
def test_powerbi_operator_async_get_workspace_list_success(self, connection):
"""Assert that get_workspace_list log success message"""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
context["ti"].task_id = TASK_ID
with pytest.raises(TaskDeferred) as exc:
operator.execute(
context=context,
)
assert isinstance(exc.value.trigger, PowerBIWorkspaceListTrigger)
assert exc.value.trigger.workspace_ids is None
def test_powerbi_operator_async_execute_complete_success(self):
"""Assert that execute_complete log success message"""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
operator.execute_complete(
context=context,
event=SUCCESS_LIST_EVENT_WORKSPACES,
)
assert context["ti"].xcom_push.call_count == 1
def test_powerbi_operator_async_execute_complete_fail(self):
"""Assert that execute_complete raise exception on error"""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
with pytest.raises(AirflowException) as exc:
operator.execute_complete(
context=context,
event={
"status": "error",
"message": "error",
"workspace_ids": None,
},
)
assert context["ti"].xcom_push.call_count == 1
assert str(exc.value) == "error"
def test_powerbi_operator_workspace_list_fail(self):
"""Assert that execute_complete raise exception on workspace list fail"""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
with pytest.raises(AirflowException) as exc:
operator.execute_complete(
context=context,
event={
"status": "error",
"message": "error message",
"workspace_ids": None,
},
)
assert context["ti"].xcom_push.call_count == 1
assert str(exc.value) == "error message"
def test_execute_complete_no_event(self):
"""Test execute_complete when event is None or empty."""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
operator.execute_complete(
context=context,
event=None,
)
assert context["ti"].xcom_push.call_count == 0
| TestPowerBIWorkspaceListOperator |
python | mitmproxy__pdoc | test/testdata/demo.py | {
"start": 33,
"end": 360
} | class ____:
"""🐕"""
name: str
"""The name of our dog."""
friends: list["Dog"]
"""The friends of our dog."""
def __init__(self, name: str):
"""Make a Dog without any friends (yet)."""
self.name = name
self.friends = []
def bark(self, loud: bool = True):
"""*woof*"""
| Dog |
python | spyder-ide__spyder | spyder/plugins/updatemanager/workers.py | {
"start": 9508,
"end": 13935
} | class ____(BaseWorker):
"""
Worker that checks for releases using either the Anaconda
default channels or the Github Releases page without
blocking the Spyder user interface, in case of connection
issues.
"""
def __init__(self, stable_only):
super().__init__()
self.stable_only = stable_only
self.asset_info = None
self.error = None
self.checkbox = False
self.channel = None
def _check_update_available(self, release: Version | None = None):
"""
Check if there is an update available.
Releases are obtained from Github and compared to the current Spyder
version to determine if an update is available. The Github release
asset and checksum must be available in order for the release to be
considered.
Parameters
----------
release : packaging.version.Version | (None)
If provided, limit possible releases on Github to this release
or less.
"""
# Get asset info from Github
releases = get_github_releases()
if release is not None:
# Limit Github releases to consider
releases = {k: v for k, v in releases.items() if k <= release}
if self.stable_only:
# Only consider stable releases
releases = {
k: v for k, v in releases.items() if not k.is_prerelease
}
logger.debug(f"Available releases: {sorted(releases)}")
self.asset_info = _check_asset_available(releases, CURRENT_VERSION)
def start(self):
"""Main method of the worker."""
url = None
if not is_conda_based_app():
self.channel = "pypi" # Default channel if not conda
if is_conda_env(sys.prefix):
self.channel, url = get_spyder_conda_channel()
if self.channel == "pypi":
url = "https://pypi.python.org/pypi/spyder/json"
else:
url += '/channeldata.json'
try:
release = None
if url is not None:
# Limit the releases on Github that we consider to those less
# than or equal to what is also available on the conda/pypi
# channel
logger.info(f"Getting release from {url}")
page = requests.get(url)
page.raise_for_status()
data = page.json()
if self.channel == "pypi":
releases = [
parse(k) for k in data["releases"].keys()
if not parse(k).is_prerelease
]
release = max(releases)
else:
# Conda pkgs/main or conda-forge url
spyder_data = data['packages'].get('spyder')
if spyder_data:
release = parse(spyder_data["version"])
self._check_update_available(release)
except SSLError as err:
self.error = SSL_ERROR_MSG
logger.warning(err, exc_info=err)
except ConnectionError as err:
self.error = CONNECT_ERROR_MSG
logger.warning(err, exc_info=err)
except HTTPError as err:
status_code = err.response.status_code
self.error = HTTP_ERROR_MSG.format(status_code=status_code)
logger.warning(err, exc_info=err)
except OSError as err:
self.error = OS_ERROR_MSG.format(error=err)
self.checkbox = True
logger.warning(err, exc_info=err)
except Exception as err:
# Send untracked errors to our error reporter
error_data = dict(
text=traceback.format_exc(),
is_traceback=True,
title="Error when checking for updates",
)
self.sig_exception_occurred.emit(error_data)
logger.error(err, exc_info=err)
finally:
# At this point we **must** emit the signal below so that the
# "Check for updates" action in the Help menu is enabled again
# after the check has finished (it's disabled while the check is
# running).
try:
self.sig_ready.emit(self.error is None)
except RuntimeError:
pass
| WorkerUpdate |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 11597,
"end": 11774
} | class ____(models.Model):
random_char_field = RandomCharField(length=8, include_digits=False)
class Meta:
app_label = "django_extensions"
| RandomCharTestModelAlpha |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecs/tasks.py | {
"start": 906,
"end": 10888
} | class ____(
NamedTuple(
"_DagsterEcsTaskDefinitionConfig",
[
("family", str),
("image", str),
("container_name", str),
("command", Optional[Sequence[str]]),
("log_configuration", Optional[Mapping[str, Any]]),
("secrets", Sequence[Mapping[str, str]]),
("environment", Sequence[Mapping[str, str]]),
("execution_role_arn", Optional[str]),
("task_role_arn", Optional[str]),
("sidecars", Sequence[Mapping[str, Any]]),
("requires_compatibilities", Sequence[str]),
("cpu", str),
("memory", str),
("ephemeral_storage", Optional[int]),
("runtime_platform", Mapping[str, Any]),
("mount_points", Sequence[Mapping[str, Any]]),
("volumes", Sequence[Mapping[str, Any]]),
("repository_credentials", Optional[str]),
("linux_parameters", Optional[Mapping[str, Any]]),
("health_check", Optional[Mapping[str, Any]]),
],
)
):
"""All the information that Dagster needs to create a task definition and compare two task
definitions to see if they should be reused.
"""
def __new__(
cls,
family: str,
image: str,
container_name: str,
command: Optional[Sequence[str]],
log_configuration: Optional[Mapping[str, Any]],
secrets: Optional[Sequence[Mapping[str, str]]],
environment: Optional[Sequence[Mapping[str, str]]],
execution_role_arn: Optional[str],
task_role_arn: Optional[str],
sidecars: Optional[Sequence[Mapping[str, Any]]],
requires_compatibilities: Optional[Sequence[str]],
cpu: Optional[str] = None,
memory: Optional[str] = None,
ephemeral_storage: Optional[int] = None,
runtime_platform: Optional[Mapping[str, Any]] = None,
mount_points: Optional[Sequence[Mapping[str, Any]]] = None,
volumes: Optional[Sequence[Mapping[str, Any]]] = None,
repository_credentials: Optional[str] = None,
linux_parameters: Optional[Mapping[str, Any]] = None,
health_check: Optional[Mapping[str, Any]] = None,
):
return super().__new__(
cls,
check.str_param(family, "family"),
check.str_param(image, "image"),
check.str_param(container_name, "container_name"),
check.opt_sequence_param(command, "command"),
check.opt_mapping_param(log_configuration, "log_configuration"),
sorted(check.opt_sequence_param(secrets, "secrets"), key=lambda s: s["name"]),
sorted(check.opt_sequence_param(environment, "environment"), key=lambda e: e["name"]),
check.opt_str_param(execution_role_arn, "execution_role_arn"),
check.opt_str_param(task_role_arn, "task_role_arn"),
check.opt_sequence_param(sidecars, "sidecars"),
check.opt_sequence_param(requires_compatibilities, "requires_compatibilities"),
check.opt_str_param(cpu, "cpu", default="256"),
check.opt_str_param(memory, "memory", default="512"),
check.opt_int_param(ephemeral_storage, "ephemeral_storage"),
check.opt_mapping_param(runtime_platform, "runtime_platform"),
check.opt_sequence_param(mount_points, "mount_points"),
check.opt_sequence_param(volumes, "volumes"),
check.opt_str_param(repository_credentials, "repository_credentials"),
check.opt_mapping_param(linux_parameters, "linux_parameters"),
check.opt_mapping_param(health_check, "health_check"),
)
def task_definition_dict(self):
kwargs = dict(
family=self.family,
requiresCompatibilities=self.requires_compatibilities,
networkMode="awsvpc",
containerDefinitions=[
merge_dicts(
{
"name": self.container_name,
"image": self.image,
},
(
{"logConfiguration": self.log_configuration}
if self.log_configuration
else {}
),
({"command": self.command} if self.command else {}),
({"secrets": self.secrets} if self.secrets else {}),
({"environment": self.environment} if self.environment else {}),
({"mountPoints": self.mount_points} if self.mount_points else {}),
(
{
"repositoryCredentials": {
"credentialsParameter": self.repository_credentials
}
}
if self.repository_credentials
else {}
),
({"linuxParameters": self.linux_parameters} if self.linux_parameters else {}),
({"healthCheck": self.health_check} if self.health_check else {}),
),
*self.sidecars,
],
cpu=self.cpu,
memory=self.memory,
)
if self.execution_role_arn:
kwargs.update(dict(executionRoleArn=self.execution_role_arn))
if self.task_role_arn:
kwargs.update(dict(taskRoleArn=self.task_role_arn))
if self.runtime_platform:
kwargs.update(dict(runtimePlatform=self.runtime_platform)) # pyright: ignore[reportCallIssue,reportArgumentType]
if self.ephemeral_storage:
kwargs.update(dict(ephemeralStorage={"sizeInGiB": self.ephemeral_storage})) # pyright: ignore[reportCallIssue,reportArgumentType]
if self.volumes:
kwargs.update(dict(volumes=self.volumes)) # pyright: ignore[reportCallIssue,reportArgumentType]
return kwargs
def matches_other_task_definition_config(self, other: "DagsterEcsTaskDefinitionConfig"):
# Proceed with caution when adding additional fields here - if the format of
# DagsterEcsTaskDefinitionConfig.from_task_definition_dict doesn't exactly match what
# is passed in, its possible to create a situation where a new task definition revision
# is being created on every run.
if not (
self.family == other.family
and self.image == other.image
and self.container_name == other.container_name
and self.command == other.command
and self.secrets == other.secrets
and self.environment == other.environment
and self.cpu == other.cpu
and self.memory == other.memory
and _ephemeral_storage_matches(self.ephemeral_storage, other.ephemeral_storage)
and _arns_match(self.execution_role_arn, other.execution_role_arn)
and _arns_match(self.task_role_arn, other.task_role_arn)
):
return False
if not [
(
sidecar["name"],
sidecar["image"],
sidecar.get("environment", []),
sidecar.get("secrets", []),
)
for sidecar in self.sidecars
] == [
(
sidecar["name"],
sidecar["image"],
sidecar.get("environment", []),
sidecar.get("secrets", []),
)
for sidecar in other.sidecars
]:
return False
return True
@staticmethod
def from_task_definition_dict(task_definition_dict, container_name):
matching_container_defs = [
container
for container in task_definition_dict["containerDefinitions"]
if container["name"] == container_name
]
if not matching_container_defs:
raise Exception(f"No container in task definition with expected name {container_name}")
container_definition = matching_container_defs[0]
sidecars = [
container
for container in task_definition_dict["containerDefinitions"]
if container["name"] != container_name
]
return DagsterEcsTaskDefinitionConfig(
family=task_definition_dict["family"],
image=container_definition["image"],
container_name=container_name,
command=container_definition.get("command"),
log_configuration=container_definition.get("logConfiguration"),
secrets=container_definition.get("secrets"),
environment=container_definition.get("environment"),
execution_role_arn=task_definition_dict.get("executionRoleArn"),
task_role_arn=task_definition_dict.get("taskRoleArn"),
sidecars=sidecars,
requires_compatibilities=task_definition_dict.get("requiresCompatibilities"),
cpu=task_definition_dict.get("cpu"),
memory=task_definition_dict.get("memory"),
ephemeral_storage=task_definition_dict.get("ephemeralStorage", {}).get("sizeInGiB"),
runtime_platform=task_definition_dict.get("runtimePlatform"),
mount_points=container_definition.get("mountPoints"),
volumes=task_definition_dict.get("volumes"),
repository_credentials=container_definition.get("repositoryCredentials", {}).get(
"credentialsParameter"
),
linux_parameters=container_definition.get("linuxParameters"),
health_check=container_definition.get("healthCheck"),
)
# 9 retries polls for up to 51.1 seconds with exponential backoff.
BACKOFF_RETRIES = 9
# The ECS API is eventually consistent:
# https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html
# describe_tasks might initially return nothing even if a task exists.
| DagsterEcsTaskDefinitionConfig |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/calibrator/integration_test/custom_aggregator_op_test.py | {
"start": 1351,
"end": 5757
} | class ____(test.TestCase):
def setUp(self):
super(CustomAggregatorTest, self).setUp()
ops.disable_eager_execution()
def testBypassAndMinMax(self):
with self.session():
input_tensor = array_ops.constant(
[1.0, 2.0, 3.0, 4.0, 5.0], dtypes.float32
)
aggregator = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor,
id='1',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_MIN_MAX,
)
aggregator_output = self.evaluate(aggregator)
self.assertAllEqual(aggregator_output.output, [1.0, 2.0, 3.0, 4.0, 5.0])
self.assertEqual(aggregator_output.min, 1.0)
self.assertEqual(aggregator_output.max, 5.0)
self.assertEmpty(aggregator_output.histogram)
def testTwoIdentities(self):
with self.session():
input_tensor1 = array_ops.constant(
[1.0, 2.0, 3.0, 4.0, 5.0], dtypes.float32
)
aggregator1 = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor1,
'2',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_MIN_MAX,
)
aggregator1_output = self.evaluate(aggregator1)
self.assertAllEqual(aggregator1_output.output, [1.0, 2.0, 3.0, 4.0, 5.0])
self.assertEqual(aggregator1_output.min, 1.0)
self.assertEqual(aggregator1_output.max, 5.0)
self.assertEmpty(aggregator1_output.histogram)
input_tensor2 = array_ops.constant(
[-1.0, -2.0, -3.0, -4.0, -5.0], dtypes.float32
)
aggregator2 = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor2,
'3',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_MIN_MAX,
)
aggregator2_output = self.evaluate(aggregator2)
self.assertAllEqual(
aggregator2_output.output, [-1.0, -2.0, -3.0, -4.0, -5.0]
)
self.assertEqual(aggregator2_output.min, -5.0)
self.assertEqual(aggregator2_output.max, -1.0)
self.assertEmpty(aggregator2_output.histogram)
def testBypassAndAverageMinMax(self):
with self.session():
input_tensor1 = array_ops.constant(
[-50.0, -25.0, 0.0, 25.0, 50.0], dtypes.float32
)
aggregator1 = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor1,
'6',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_AVERAGE_MIN_MAX,
)
aggregator1_output = self.evaluate(aggregator1)
self.assertAllEqual(
aggregator1_output.output,
[-50.0, -25.0, 0.0, 25.0, 50.0],
)
self.assertEqual(aggregator1_output.min, -50.0)
self.assertEqual(aggregator1_output.max, 50.0)
self.assertEmpty(aggregator1_output.histogram)
input_tensor2 = array_ops.constant(
[-100.0, -50.0, 0.0, 50.0, 100.0], dtypes.float32
)
aggregator2 = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor2,
'6',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_AVERAGE_MIN_MAX,
)
aggregator2_output = self.evaluate(aggregator2)
self.assertAllEqual(
aggregator2_output.output, [-100.0, -50.0, 0.0, 50.0, 100.0]
)
self.assertEqual(aggregator2_output.min, -100.0)
self.assertEqual(aggregator2_output.max, 100.0)
self.assertEmpty(aggregator2_output.histogram)
def testHistogramCalibration(self):
with self.session():
input_tensor = array_ops.constant(
[1.0, 1.0, 3.0, 4.0, 6.0], dtypes.float32
)
aggregator = custom_aggregator_op_wrapper.custom_aggregator(
input_tensor,
id='7',
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_HISTOGRAM_MSE_BRUTEFORCE,
num_bins=512,
)
aggregator_output = self.evaluate(aggregator)
self.assertAllEqual(aggregator_output.output, [1.0, 1.0, 3.0, 4.0, 6.0])
self.assertEqual(aggregator_output.min, 1.0)
self.assertEqual(aggregator_output.max, 6.0)
self.assertLen(aggregator_output.histogram, 512)
self.assertEqual(sum(aggregator_output.histogram), 5)
self.assertEqual(aggregator_output.histogram[0], 2)
self.assertEqual(aggregator_output.histogram[128], 1)
self.assertEqual(aggregator_output.histogram[192], 1)
self.assertEqual(aggregator_output.histogram[320], 1)
if __name__ == '__main__':
test.main()
| CustomAggregatorTest |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_event_frequency_query_handlers.py | {
"start": 15735,
"end": 18650
} | class ____(BaseEventFrequencyPercentTest, EventFrequencyQueryTestBase):
handler = PercentSessionsQueryHandler
@patch(
"sentry.workflow_engine.handlers.condition.event_frequency_query_handlers.MIN_SESSIONS_TO_FIRE",
1,
)
def test_batch_query_percent(self) -> None:
self._make_sessions(60, self.environment2.name, received=self.end.timestamp())
self._make_sessions(60, self.environment.name, received=self.end.timestamp())
batch_query = self.handler().batch_query(
groups=self.groups,
start=self.start,
end=self.end,
environment_id=self.environment.id,
)
percent_of_sessions = 20
assert batch_query == {
self.event.group_id: percent_of_sessions,
self.event2.group_id: percent_of_sessions,
self.perf_event.group_id: 0,
}
assert self.event3.group_id
batch_query = self.handler().batch_query(
groups=self.group_3,
start=self.start,
end=self.end,
environment_id=self.environment2.id,
)
assert batch_query == {self.event3.group_id: percent_of_sessions}
def test_batch_query_percent_decimal(self) -> None:
self._make_sessions(600, self.environment.name)
assert self.event.group_id
groups = list(
Group.objects.filter(id=self.event.group_id).values(
"id", "type", "project_id", "project__organization_id"
)
)
self.start = before_now(hours=1)
self.end = self.start + timedelta(hours=1)
batch_query = self.handler().batch_query(
groups=groups,
start=self.start,
end=self.end,
environment_id=self.environment.id,
)
assert round(batch_query[self.event.group_id], 4) == 0.17
@patch(
"sentry.workflow_engine.handlers.condition.event_frequency_query_handlers.MIN_SESSIONS_TO_FIRE",
100,
)
def test_batch_query_percent_no_avg_sessions_in_interval(self) -> None:
self._make_sessions(60, self.environment2.name)
self._make_sessions(60, self.environment.name)
batch_query = self.handler().batch_query(
groups=self.groups,
start=self.start,
end=self.end,
environment_id=self.environment.id,
)
percent = 0
assert batch_query == {
self.event.group_id: percent,
self.event2.group_id: percent,
self.perf_event.group_id: percent,
}
assert self.event3.group_id
batch_query = self.handler().batch_query(
groups=self.group_3,
start=self.start,
end=self.end,
environment_id=self.environment2.id,
)
assert batch_query == {self.event3.group_id: percent}
| PercentSessionsQueryTest |
python | automl__auto-sklearn | test/test_metalearning/pyMetaLearn/metalearning/test_kND.py | {
"start": 244,
"end": 4580
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.anneal = pd.Series(
{
"number_of_instances": 898.0,
"number_of_classes": 5.0,
"number_of_features": 38.0,
},
name=232,
)
self.krvskp = pd.Series(
{
"number_of_instances": 3196.0,
"number_of_classes": 2.0,
"number_of_features": 36.0,
},
name=233,
)
self.labor = pd.Series(
{
"number_of_instances": 57.0,
"number_of_classes": 2.0,
"number_of_features": 16.0,
},
name=234,
)
self.runs = {
232: [0.1, 0.5, 0.7],
233: [np.NaN, 0.1, 0.7],
234: [0.5, 0.7, 0.1],
}
self.runs = pd.DataFrame(self.runs)
self.logger = logging.getLogger()
def test_fit_l1_distance(self):
kND = KNearestDatasets(logger=self.logger)
kND.fit(pd.DataFrame([self.anneal, self.krvskp, self.labor]), self.runs)
self.assertEqual(kND.best_configuration_per_dataset[232], 0)
self.assertEqual(kND.best_configuration_per_dataset[233], 1)
self.assertEqual(kND.best_configuration_per_dataset[234], 2)
self.assertTrue(
(kND.metafeatures == pd.DataFrame([self.anneal, self.krvskp, self.labor]))
.all()
.all()
)
# TODO: rename to kNearestTasks or something
def test_kNearestDatasets(self):
kND = KNearestDatasets(logger=self.logger)
kND.fit(pd.DataFrame([self.krvskp, self.labor]), self.runs.loc[:, [233, 234]])
neighbor = kND.kNearestDatasets(self.anneal, 1)
self.assertEqual([233], neighbor)
neighbor, distance = kND.kNearestDatasets(self.anneal, 1, return_distance=True)
self.assertEqual([233], neighbor)
np.testing.assert_array_almost_equal([3.8320802803440586], distance)
neighbors = kND.kNearestDatasets(self.anneal, 2)
self.assertEqual([233, 234], neighbors)
neighbors, distance = kND.kNearestDatasets(self.anneal, 2, return_distance=True)
self.assertEqual([233, 234], neighbors)
np.testing.assert_array_almost_equal(
[3.8320802803440586, 4.367919719655942], distance
)
neighbors = kND.kNearestDatasets(self.anneal, -1)
self.assertEqual([233, 234], neighbors)
neighbors, distance = kND.kNearestDatasets(
self.anneal, -1, return_distance=True
)
self.assertEqual([233, 234], neighbors)
np.testing.assert_array_almost_equal(
[3.8320802803440586, 4.367919719655942], distance
)
self.assertRaises(ValueError, kND.kNearestDatasets, self.anneal, 0)
self.assertRaises(ValueError, kND.kNearestDatasets, self.anneal, -2)
def test_kBestSuggestions(self):
kND = KNearestDatasets(logger=self.logger)
kND.fit(pd.DataFrame([self.krvskp, self.labor]), self.runs.loc[:, [233, 234]])
neighbor = kND.kBestSuggestions(self.anneal, 1)
np.testing.assert_array_almost_equal(
[(233, 3.8320802803440586, 1)],
neighbor,
)
neighbors = kND.kBestSuggestions(self.anneal, 2)
np.testing.assert_array_almost_equal(
[(233, 3.8320802803440586, 1), (234, 4.367919719655942, 2)],
neighbors,
)
neighbors = kND.kBestSuggestions(self.anneal, -1)
np.testing.assert_array_almost_equal(
[(233, 3.8320802803440586, 1), (234, 4.367919719655942, 2)],
neighbors,
)
self.assertRaises(ValueError, kND.kBestSuggestions, self.anneal, 0)
self.assertRaises(ValueError, kND.kBestSuggestions, self.anneal, -2)
def test_random_metric(self):
kND = KNearestDatasets(
logger=self.logger, metric=get_random_metric(random_state=1)
)
kND.fit(pd.DataFrame([self.krvskp, self.labor]), self.runs.loc[:, [233, 234]])
distances = []
for i in range(20):
neighbor = kND.kBestSuggestions(self.anneal, 1)
distances.append(neighbor[0][1])
self.assertEqual(len(np.unique(distances)), 20)
| kNDTest |
python | sympy__sympy | sympy/testing/runtests.py | {
"start": 67264,
"end": 70770
} | class ____(DocTestRunner):
"""
A class used to run DocTest test cases, and accumulate statistics.
The ``run`` method is used to process a single DocTest case. It
returns a tuple ``(f, t)``, where ``t`` is the number of test cases
tried, and ``f`` is the number of test cases that failed.
Modified from the doctest version to not reset the sys.displayhook (see
issue 5140).
See the docstring of the original DocTestRunner for more information.
"""
def run(self, test, compileflags=None, out=None, clear_globs=True):
"""
Run the examples in ``test``, and display the results using the
writer function ``out``.
The examples are run in the namespace ``test.globs``. If
``clear_globs`` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
the test completes, then use ``clear_globs=False``.
``compileflags`` gives the set of flags that should be used by
the Python compiler when running the examples. If not
specified, then it will default to the set of future-import
flags that apply to ``globs``.
The output of each example is checked using
``SymPyDocTestRunner.check_output``, and the results are
formatted by the ``SymPyDocTestRunner.report_*`` methods.
"""
self.test = test
# Remove ``` from the end of example, which may appear in Markdown
# files
for example in test.examples:
example.want = example.want.replace('```\n', '')
example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
if compileflags is None:
compileflags = pdoctest._extract_future_flags(test.globs)
save_stdout = sys.stdout
if out is None:
out = save_stdout.write
sys.stdout = self._fakeout
# Patch pdb.set_trace to restore sys.stdout during interactive
# debugging (so it's not still redirected to self._fakeout).
# Note that the interactive output will go to *our*
# save_stdout, even if that's not the real sys.stdout; this
# allows us to write test cases for the set_trace behavior.
save_set_trace = pdb.set_trace
self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
self.debugger.reset()
pdb.set_trace = self.debugger.set_trace
# Patch linecache.getlines, so we can see the example's source
# when we're inside the debugger.
self.save_linecache_getlines = pdoctest.linecache.getlines
linecache.getlines = self.__patched_linecache_getlines
# Fail for deprecation warnings
with raise_on_deprecated():
try:
return self.__run(test, compileflags, out)
finally:
sys.stdout = save_stdout
pdb.set_trace = save_set_trace
linecache.getlines = self.save_linecache_getlines
if clear_globs:
test.globs.clear()
# We have to override the name mangled methods.
monkeypatched_methods = [
'patched_linecache_getlines',
'run',
'record_outcome'
]
for method in monkeypatched_methods:
oldname = '_DocTestRunner__' + method
newname = '_SymPyDocTestRunner__' + method
setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
| SymPyDocTestRunner |
python | getsentry__sentry | src/sentry/plugins/providers/dummy/repository.py | {
"start": 69,
"end": 1016
} | class ____(RepositoryProvider):
name = "Example"
auth_provider = "dummy"
def get_config(self):
return [
{
"name": "name",
"label": "Repository Name",
"type": "text",
"placeholder": "e.g. getsentry/sentry",
"help": "Enter your repository name.",
"required": True,
}
]
def create_repository(self, organization, data, actor=None):
return {"name": data["name"]}
def compare_commits(self, repo, start_sha, end_sha, actor=None):
return [
{"id": "62de626b7c7cfb8e77efb4273b1a3df4123e6216", "repository": repo.name},
{"id": "58de626b7c7cfb8e77efb4273b1a3df4123e6345", "repository": repo.name},
{"id": end_sha, "repository": repo.name},
]
def repository_external_slug(self, repo):
return repo.external_id
| DummyRepositoryProvider |
python | walkccc__LeetCode | solutions/3003. Maximize the Number of Partitions After Operations/3003.py | {
"start": 0,
"end": 973
} | class ____:
def maxPartitionsAfterOperations(self, s: str, k: int) -> int:
@functools.lru_cache(None)
def dp(i: int, canChange: bool, mask: int) -> int:
"""
Returns the maximum number of partitions of s[i..n), where `canChange` is
True if we can still change a letter, and `mask` is the bitmask of the
letters we've seen.
"""
if i == len(s):
return 0
def getRes(newBit: int, nextCanChange: bool) -> int:
newMask = mask | newBit
if newMask.bit_count() > k:
return 1 + dp(i + 1, nextCanChange, newBit)
return dp(i + 1, nextCanChange, newMask)
# Initialize the result based on the current letter.
res = getRes(1 << (ord(s[i]) - ord('a')), canChange)
# If allowed, explore the option to change the current letter.
if canChange:
for j in range(26):
res = max(res, getRes(1 << j, False))
return res
return dp(0, True, 0) + 1
| Solution |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 16812,
"end": 16872
} | class ____(SingleAggregation):
groupby_chunk = M.last
| Last |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 36883,
"end": 37061
} | class ____(axis_ticks_minor_x, axis_ticks_minor_y):
"""
x & y axis minor tick lines
Parameters
----------
theme_element : element_line
"""
| axis_ticks_minor |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 2388,
"end": 9853
} | class ____(forms.Form):
password = PasswordField(label=_("Password"), autocomplete="current-password")
remember = forms.BooleanField(label=_("Remember Me"), required=False)
user = None
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super().__init__(*args, **kwargs)
adapter = get_adapter()
if app_settings.LOGIN_METHODS == {LoginMethod.EMAIL}:
login_field = EmailField()
elif app_settings.LOGIN_METHODS == {LoginMethod.USERNAME}:
login_widget = forms.TextInput(
attrs={"placeholder": _("Username"), "autocomplete": "username"}
)
login_field = forms.CharField(
label=_("Username"),
widget=login_widget,
max_length=get_username_max_length(),
)
elif app_settings.LOGIN_METHODS == {LoginMethod.PHONE}:
login_field = adapter.phone_form_field(required=True)
else:
login_widget = forms.TextInput(
attrs={
"placeholder": self._get_login_field_placeholder(),
"autocomplete": "email",
}
)
login_field = forms.CharField(
label=pgettext("field label", "Login"), widget=login_widget
)
self.fields["login"] = login_field
set_form_field_order(self, ["login", "password", "remember"])
if app_settings.SESSION_REMEMBER is not None:
del self.fields["remember"]
self._setup_password_field()
def _get_login_field_placeholder(self):
methods = app_settings.LOGIN_METHODS
assert len(methods) > 1 # nosec
assert methods.issubset(
{
LoginMethod.USERNAME,
LoginMethod.EMAIL,
LoginMethod.PHONE,
}
) # nosec
if len(methods) == 3:
placeholder = _("Username, email or phone")
elif methods == {LoginMethod.USERNAME, LoginMethod.EMAIL}:
placeholder = _("Username or email")
elif methods == {LoginMethod.USERNAME, LoginMethod.PHONE}:
placeholder = _("Username or phone")
elif methods == {LoginMethod.EMAIL, LoginMethod.PHONE}:
placeholder = _("Email or phone")
else:
raise ValueError(methods)
return placeholder
def _setup_password_field(self):
password_field = app_settings.SIGNUP_FIELDS.get("password1")
if not password_field:
del self.fields["password"]
return
try:
self.fields["password"].help_text = render_to_string(
"account/password_reset_help_text." + app_settings.TEMPLATE_EXTENSION
)
return
except TemplateDoesNotExist:
pass
try:
reset_url = reverse("account_reset_password")
except NoReverseMatch:
pass
else:
forgot_txt = _("Forgot your password?")
self.fields["password"].help_text = mark_safe(
f'<a href="{reset_url}">{forgot_txt}</a>'
) # nosec
def user_credentials(self) -> dict:
"""
Provides the credentials required to authenticate the user for
login.
"""
login = self.cleaned_data["login"]
method = flows.login.derive_login_method(login)
credentials = {}
credentials[method] = login
# There are projects using usernames that look like email addresses,
# yet, really are usernames. So, if username is a login method, always
# give that a shot.
if (
LoginMethod.USERNAME in app_settings.LOGIN_METHODS
and method != LoginMethod.USERNAME
):
credentials[LoginMethod.USERNAME] = login
password = self.cleaned_data.get("password")
if password:
credentials["password"] = password
return credentials
def clean_login(self):
login = self.cleaned_data["login"]
return login.strip()
def clean(self):
super().clean()
if self._errors:
return
credentials = self.user_credentials()
if "password" in credentials:
return self._clean_with_password(credentials)
return self._clean_without_password(
credentials.get("email"), credentials.get("phone")
)
def _clean_without_password(self, email: Optional[str], phone: Optional[str]):
"""
If we don't have a password field, we need to replicate the request-login-code
behavior.
"""
data = {}
if email:
data["email"] = email
if phone:
data["phone"] = phone
if not data:
self.add_error("login", get_adapter().validation_error("invalid_login"))
else:
form = RequestLoginCodeForm(data)
if not form.is_valid():
for field in ["phone", "email"]:
errors = form.errors.get(field) or [] # type: ignore
for error in errors:
self.add_error("login", error)
else:
self.user = form._user # type: ignore
return self.cleaned_data
def _clean_with_password(self, credentials: dict):
adapter = get_adapter(self.request)
user = adapter.authenticate(self.request, **credentials)
if user:
login = Login(user=user, email=credentials.get("email"))
if flows.login.is_login_rate_limited(context.request, login):
raise adapter.validation_error("too_many_login_attempts")
self._login = login
self.user = user # type: ignore
else:
login_method = flows.login.derive_login_method(
login=self.cleaned_data["login"]
)
raise adapter.validation_error("%s_password_mismatch" % login_method.value)
return self.cleaned_data
def login(self, request, redirect_url=None):
credentials = self.user_credentials()
if "password" in credentials:
return self._login_with_password(request, redirect_url, credentials)
return self._login_by_code(request, redirect_url, credentials)
def _login_by_code(self, request, redirect_url, credentials):
user = getattr(self, "user", None)
phone = credentials.get("phone")
email = credentials.get("email")
flows.login_by_code.LoginCodeVerificationProcess.initiate(
request=request,
user=user,
phone=phone,
email=email,
)
query = None
if redirect_url:
query = {}
query[REDIRECT_FIELD_NAME] = redirect_url
return headed_redirect_response("account_confirm_login_code", query=query)
def _login_with_password(self, request, redirect_url, credentials):
login = self._login
login.redirect_url = redirect_url
ret = flows.login.perform_password_login(request, credentials, login)
remember = app_settings.SESSION_REMEMBER
if remember is None:
remember = self.cleaned_data["remember"]
if remember:
request.session.set_expiry(app_settings.SESSION_COOKIE_AGE)
else:
request.session.set_expiry(0)
return ret
| LoginForm |
python | fastai__fastai | fastai/text/core.py | {
"start": 4602,
"end": 5262
} | class ____():
"Spacy tokenizer for `lang`"
def __init__(self, lang='en', special_toks=None, buf_sz=5000):
import spacy
from spacy.symbols import ORTH
self.special_toks = ifnone(special_toks, defaults.text_spec_tok)
nlp = spacy.blank(lang)
for w in self.special_toks: nlp.tokenizer.add_special_case(w, [{ORTH: w}])
self.pipe,self.buf_sz = nlp.pipe,buf_sz
def __call__(self, items):
return (L(doc).attrgot('text') for doc in self.pipe(map(str,items), batch_size=self.buf_sz))
# %% ../../nbs/30_text.core.ipynb 40
WordTokenizer = SpacyTokenizer
# %% ../../nbs/30_text.core.ipynb 42
| SpacyTokenizer |
python | kamyu104__LeetCode-Solutions | Python/ipo.py | {
"start": 48,
"end": 575
} | class ____(object):
def findMaximizedCapital(self, k, W, Profits, Capital):
"""
:type k: int
:type W: int
:type Profits: List[int]
:type Capital: List[int]
:rtype: int
"""
curr = []
future = sorted(zip(Capital, Profits), reverse=True)
for _ in xrange(k):
while future and future[-1][0] <= W:
heapq.heappush(curr, -future.pop()[1])
if curr:
W -= heapq.heappop(curr)
return W
| Solution |
python | pypa__pip | src/pip/_vendor/pyproject_hooks/_in_process/_in_process.py | {
"start": 1204,
"end": 2201
} | class ____(Exception):
"""Raised if a hook is missing and we are not executing the fallback"""
def __init__(self, hook_name=None):
super().__init__(hook_name)
self.hook_name = hook_name
def _build_backend():
"""Find and load the build backend"""
backend_path = os.environ.get("_PYPROJECT_HOOKS_BACKEND_PATH")
ep = os.environ["_PYPROJECT_HOOKS_BUILD_BACKEND"]
mod_path, _, obj_path = ep.partition(":")
if backend_path:
# Ensure in-tree backend directories have the highest priority when importing.
extra_pathitems = backend_path.split(os.pathsep)
sys.meta_path.insert(0, _BackendPathFinder(extra_pathitems, mod_path))
try:
obj = import_module(mod_path)
except ImportError:
msg = f"Cannot import {mod_path!r}"
raise BackendUnavailable(msg, traceback.format_exc())
if obj_path:
for path_part in obj_path.split("."):
obj = getattr(obj, path_part)
return obj
| HookMissing |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/latest_release_handler.py | {
"start": 1182,
"end": 1637
} | class ____(CacheAccess[Release | Literal[False]]):
"""
If we have a release for a project in an environment, we cache it.
If we don't, we cache False.
"""
def __init__(self, event: GroupEvent, environment: Environment | None):
self._key = latest_release_cache_key(
event.group.project_id, environment.id if environment else None
)
def key(self) -> str:
return self._key
| _LatestReleaseCacheAccess |
python | sympy__sympy | sympy/plotting/pygletplot/plot_curve.py | {
"start": 117,
"end": 2838
} | class ____(PlotModeBase):
style_override = 'wireframe'
def _on_calculate_verts(self):
self.t_interval = self.intervals[0]
self.t_set = list(self.t_interval.frange())
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0]]
evaluate = self._get_evaluator()
self._calculating_verts_pos = 0.0
self._calculating_verts_len = float(self.t_interval.v_len)
self.verts = []
b = self.bounds
for t in self.t_set:
try:
_e = evaluate(t) # calculate vertex
except (NameError, ZeroDivisionError):
_e = None
if _e is not None: # update bounding box
for axis in range(3):
b[axis][0] = min([b[axis][0], _e[axis]])
b[axis][1] = max([b[axis][1], _e[axis]])
self.verts.append(_e)
self._calculating_verts_pos += 1.0
for axis in range(3):
b[axis][2] = b[axis][1] - b[axis][0]
if b[axis][2] == 0.0:
b[axis][2] = 1.0
self.push_wireframe(self.draw_verts(False))
def _on_calculate_cverts(self):
if not self.verts or not self.color:
return
def set_work_len(n):
self._calculating_cverts_len = float(n)
def inc_work_pos():
self._calculating_cverts_pos += 1.0
set_work_len(1)
self._calculating_cverts_pos = 0
self.cverts = self.color.apply_to_curve(self.verts,
self.t_set,
set_len=set_work_len,
inc_pos=inc_work_pos)
self.push_wireframe(self.draw_verts(True))
def calculate_one_cvert(self, t):
vert = self.verts[t]
return self.color(vert[0], vert[1], vert[2],
self.t_set[t], None)
def draw_verts(self, use_cverts):
def f():
pgl.glBegin(pgl.GL_LINE_STRIP)
for t in range(len(self.t_set)):
p = self.verts[t]
if p is None:
pgl.glEnd()
pgl.glBegin(pgl.GL_LINE_STRIP)
continue
if use_cverts:
c = self.cverts[t]
if c is None:
c = (0, 0, 0)
pgl.glColor3f(*c)
else:
pgl.glColor3f(*self.default_wireframe_color)
pgl.glVertex3f(*p)
pgl.glEnd()
return f
| PlotCurve |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 17849,
"end": 20788
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.pos_conv_embed = UniSpeechSatPositionalConvEmbedding(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layers = nn.ModuleList([UniSpeechSatEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states: torch.tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: bool = True,
):
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
if attention_mask is not None:
# make sure padded tokens output 0
expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
hidden_states[~expand_attention_mask] = 0
attention_mask = create_bidirectional_mask(
config=self.config,
input_embeds=hidden_states,
attention_mask=attention_mask,
)
position_embeddings = self.pos_conv_embed(hidden_states)
hidden_states = hidden_states + position_embeddings
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.dropout(hidden_states)
synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
for layer in self.layers:
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
dropout_probability = torch.rand([])
skip_the_layer = self.training and dropout_probability < self.config.layerdrop
if not skip_the_layer or synced_gpus:
# under fsdp or deepspeed zero3 all gpus must run in sync
layer_outputs = layer(
hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
)
hidden_states = layer_outputs[0]
if skip_the_layer:
layer_outputs = (None, None)
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
| UniSpeechSatEncoder |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 17981,
"end": 20200
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
catalog: Optional[str] = Field(
None,
description=(
"Optional name of the catalog to use. The value is the top level in the"
" 3-level namespace of Unity Catalog (catalog / schema / relation). The"
" catalog value can only be specified if a warehouse_id is specified."
" Requires dbt-databricks >= 1.1.1."
),
examples=["main"],
)
commands: List = Field(
...,
description=(
"A list of dbt commands to execute. All commands must start with `dbt`."
" This parameter must not be empty. A maximum of up to 10 commands can be"
" provided."
),
examples=[["dbt deps", "dbt seed", "dbt run --models 123"]],
)
profiles_directory: Optional[str] = Field(
None,
description=(
"Optional (relative) path to the profiles directory. Can only be specified"
" if no warehouse_id is specified. If no warehouse_id is specified and this"
" folder is unset, the root directory is used."
),
)
project_directory: Optional[str] = Field(
None,
description=(
"Optional (relative) path to the project directory, if no value is"
" provided, the root of the git repository is used."
),
)
schema_: Optional[str] = Field(
None,
alias="schema",
description=(
"Optional schema to write to. This parameter is only used when a"
" warehouse_id is also provided. If not provided, the `default` schema is"
" used."
),
)
warehouse_id: Optional[str] = Field(
None,
description=(
"ID of the SQL warehouse to connect to. If provided, we automatically"
" generate and provide the profile and connection details to dbt. It can be"
" overridden on a per-command basis by using the `--profiles-dir` command"
" line argument."
),
examples=["30dade0507d960d1"],
)
| DbtTask |
python | pallets__click | examples/repo/repo.py | {
"start": 54,
"end": 4717
} | class ____:
def __init__(self, home):
self.home = home
self.config = {}
self.verbose = False
def set_config(self, key, value):
self.config[key] = value
if self.verbose:
click.echo(f" config[{key}] = {value}", file=sys.stderr)
def __repr__(self):
return f"<Repo {self.home}>"
pass_repo = click.make_pass_decorator(Repo)
@click.group()
@click.option(
"--repo-home",
envvar="REPO_HOME",
default=".repo",
metavar="PATH",
help="Changes the repository folder location.",
)
@click.option(
"--config",
nargs=2,
multiple=True,
metavar="KEY VALUE",
help="Overrides a config key/value pair.",
)
@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")
@click.version_option("1.0")
@click.pass_context
def cli(ctx, repo_home, config, verbose):
"""Repo is a command line tool that showcases how to build complex
command line interfaces with Click.
This tool is supposed to look like a distributed version control
system to show how something like this can be structured.
"""
# Create a repo object and remember it as as the context object. From
# this point onwards other commands can refer to it by using the
# @pass_repo decorator.
ctx.obj = Repo(os.path.abspath(repo_home))
ctx.obj.verbose = verbose
for key, value in config:
ctx.obj.set_config(key, value)
@cli.command()
@click.argument("src")
@click.argument("dest", required=False)
@click.option(
"--shallow/--deep",
default=False,
help="Makes a checkout shallow or deep. Deep by default.",
)
@click.option(
"--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD."
)
@pass_repo
def clone(repo, src, dest, shallow, rev):
"""Clones a repository.
This will clone the repository at SRC into the folder DEST. If DEST
is not provided this will automatically use the last path component
of SRC and create that folder.
"""
if dest is None:
dest = posixpath.split(src)[-1] or "."
click.echo(f"Cloning repo {src} to {os.path.basename(dest)}")
repo.home = dest
if shallow:
click.echo("Making shallow checkout")
click.echo(f"Checking out revision {rev}")
@cli.command()
@click.confirmation_option()
@pass_repo
def delete(repo):
"""Deletes a repository.
This will throw away the current repository.
"""
click.echo(f"Destroying repo {repo.home}")
click.echo("Deleted!")
@cli.command()
@click.option("--username", prompt=True, help="The developer's shown username.")
@click.option("--email", prompt="E-Mail", help="The developer's email address")
@click.password_option(help="The login password.")
@pass_repo
def setuser(repo, username, email, password):
"""Sets the user credentials.
This will override the current user config.
"""
repo.set_config("username", username)
repo.set_config("email", email)
repo.set_config("password", "*" * len(password))
click.echo("Changed credentials.")
@cli.command()
@click.option(
"--message",
"-m",
multiple=True,
help="The commit message. If provided multiple times each"
" argument gets converted into a new line.",
)
@click.argument("files", nargs=-1, type=click.Path())
@pass_repo
def commit(repo, files, message):
"""Commits outstanding changes.
Commit changes to the given files into the repository. You will need to
"repo push" to push up your changes to other repositories.
If a list of files is omitted, all changes reported by "repo status"
will be committed.
"""
if not message:
marker = "# Files to be committed:"
hint = ["", "", marker, "#"]
for file in files:
hint.append(f"# U {file}")
message = click.edit("\n".join(hint))
if message is None:
click.echo("Aborted!")
return
msg = message.split(marker)[0].rstrip()
if not msg:
click.echo("Aborted! Empty commit message")
return
else:
msg = "\n".join(message)
click.echo(f"Files to be committed: {files}")
click.echo(f"Commit message:\n{msg}")
@cli.command(short_help="Copies files.")
@click.option(
"--force", is_flag=True, help="forcibly copy over an existing managed file"
)
@click.argument("src", nargs=-1, type=click.Path())
@click.argument("dst", type=click.Path())
@pass_repo
def copy(repo, src, dst, force):
"""Copies one or multiple files to a new location. This copies all
files from SRC to DST.
"""
for fn in src:
click.echo(f"Copy from {fn} -> {dst}")
| Repo |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 44345,
"end": 57335
} | class ____(FastSpeech2ConformerPreTrainedModel):
"""
FastSpeech 2 module.
This is a module of FastSpeech 2 described in 'FastSpeech 2: Fast and High-Quality End-to-End Text to Speech'
https://huggingface.co/papers/2006.04558. Instead of quantized pitch and energy, we use token-averaged value introduced in
FastPitch: Parallel Text-to-speech with Pitch Prediction. The encoder and decoder are Conformers instead of regular
Transformers.
"""
def __init__(self, config: FastSpeech2ConformerConfig):
super().__init__(config)
self.config = config
# store hyperparameters
self.vocab_size = config.vocab_size
self.num_mel_bins = config.num_mel_bins
self.hidden_size = config.hidden_size
self.reduction_factor = config.reduction_factor
self.stop_gradient_from_pitch_predictor = config.stop_gradient_from_pitch_predictor
self.stop_gradient_from_energy_predictor = config.stop_gradient_from_energy_predictor
self.multilingual_model = config.num_languages is not None and config.num_languages > 1
if self.multilingual_model:
self.language_id_embedding = torch.nn.Embedding(config.num_languages, self.hidden_size)
self.multispeaker_model = config.num_speakers is not None and config.num_speakers > 1
if self.multispeaker_model:
self.speaker_id_embedding = torch.nn.Embedding(config.num_speakers, config.hidden_size)
self.speaker_embed_dim = config.speaker_embed_dim
if self.speaker_embed_dim:
self.projection = nn.Linear(config.hidden_size + self.speaker_embed_dim, config.hidden_size)
self.encoder = FastSpeech2ConformerEncoder(config, config.encoder_config, use_encoder_input_layer=True)
self.duration_predictor = FastSpeech2ConformerDurationPredictor(config)
self.pitch_predictor = FastSpeech2ConformerVariancePredictor(
config,
num_layers=config.pitch_predictor_layers,
num_chans=config.pitch_predictor_channels,
kernel_size=config.pitch_predictor_kernel_size,
dropout_rate=config.pitch_predictor_dropout,
)
# continuous pitch + FastPitch style avg
self.pitch_embed = FastSpeech2ConformerVarianceEmbedding(
out_channels=self.hidden_size,
kernel_size=config.pitch_embed_kernel_size,
padding=(config.pitch_embed_kernel_size - 1) // 2,
dropout_rate=config.pitch_embed_dropout,
)
self.energy_predictor = FastSpeech2ConformerVariancePredictor(
config,
num_layers=config.energy_predictor_layers,
num_chans=config.energy_predictor_channels,
kernel_size=config.energy_predictor_kernel_size,
dropout_rate=config.energy_predictor_dropout,
)
# continuous energy + FastPitch style avg
self.energy_embed = FastSpeech2ConformerVarianceEmbedding(
out_channels=self.hidden_size,
kernel_size=config.energy_embed_kernel_size,
padding=(config.energy_embed_kernel_size - 1) // 2,
dropout_rate=config.energy_embed_dropout,
)
# The decoder is an encoder
self.decoder = FastSpeech2ConformerEncoder(config, config.decoder_config, use_encoder_input_layer=False)
self.speech_decoder_postnet = FastSpeech2ConformerSpeechDecoderPostnet(config)
self.criterion = FastSpeech2ConformerLoss(config)
self.post_init()
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.LongTensor] = None,
spectrogram_labels: Optional[torch.FloatTensor] = None,
duration_labels: Optional[torch.LongTensor] = None,
pitch_labels: Optional[torch.FloatTensor] = None,
energy_labels: Optional[torch.FloatTensor] = None,
speaker_ids: Optional[torch.LongTensor] = None,
lang_ids: Optional[torch.LongTensor] = None,
speaker_embedding: Optional[torch.FloatTensor] = None,
return_dict: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
) -> Union[tuple, FastSpeech2ConformerModelOutput]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Input sequence of text vectors.
spectrogram_labels (`torch.FloatTensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`, *optional*, defaults to `None`):
Batch of padded target features.
duration_labels (`torch.LongTensor` of shape `(batch_size, sequence_length + 1)`, *optional*, defaults to `None`):
Batch of padded durations.
pitch_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
Batch of padded token-averaged pitch.
energy_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
Batch of padded token-averaged energy.
speaker_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
Speaker ids used to condition features of speech output by the model.
lang_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
Language ids used to condition features of speech output by the model.
speaker_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`, *optional*, defaults to `None`):
Embedding containing conditioning signals for the features of the speech.
Example:
```python
>>> from transformers import (
... FastSpeech2ConformerTokenizer,
... FastSpeech2ConformerModel,
... FastSpeech2ConformerHifiGan,
... )
>>> tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
>>> inputs = tokenizer("some text to convert to speech", return_tensors="pt")
>>> input_ids = inputs["input_ids"]
>>> model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
>>> output_dict = model(input_ids, return_dict=True)
>>> spectrogram = output_dict["spectrogram"]
>>> vocoder = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan")
>>> waveform = vocoder(spectrogram)
>>> print(waveform.shape)
torch.Size([1, 49664])
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
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
)
if attention_mask is None:
attention_mask = torch.ones(input_ids.shape, device=input_ids.device)
has_missing_labels = (
spectrogram_labels is None or duration_labels is None or pitch_labels is None or energy_labels is None
)
if self.training and has_missing_labels:
raise ValueError("All labels must be provided to run in training mode.")
# forward encoder
text_masks = attention_mask.unsqueeze(-2)
encoder_outputs = self.encoder(
input_ids,
text_masks,
output_hidden_states=output_hidden_states,
output_attentions=output_attentions,
return_dict=return_dict,
)
hidden_states = encoder_outputs[0]
# Integrate with language id, speaker id, and speaker embedding
if self.multispeaker_model and speaker_ids is not None:
speaker_id_embeddings = self.speaker_id_embedding(speaker_ids.view(-1))
hidden_states = hidden_states + speaker_id_embeddings.unsqueeze(1)
if self.multilingual_model and lang_ids is not None:
language_id_embbedings = self.language_id_embedding(lang_ids.view(-1))
hidden_states = hidden_states + language_id_embbedings.unsqueeze(1)
if self.speaker_embed_dim is not None and speaker_embedding is not None:
embeddings_expanded = (
nn.functional.normalize(speaker_embedding).unsqueeze(1).expand(-1, hidden_states.size(1), -1)
)
hidden_states = self.projection(torch.cat([hidden_states, embeddings_expanded], dim=-1))
# forward duration predictor and variance predictors
duration_mask = ~attention_mask.bool()
if self.stop_gradient_from_pitch_predictor:
pitch_predictions = self.pitch_predictor(hidden_states.detach(), duration_mask.unsqueeze(-1))
else:
pitch_predictions = self.pitch_predictor(hidden_states, duration_mask.unsqueeze(-1))
if self.stop_gradient_from_energy_predictor:
energy_predictions = self.energy_predictor(hidden_states.detach(), duration_mask.unsqueeze(-1))
else:
energy_predictions = self.energy_predictor(hidden_states, duration_mask.unsqueeze(-1))
duration_predictions = self.duration_predictor(hidden_states)
duration_predictions = duration_predictions.masked_fill(duration_mask, 0.0)
if not self.training:
# use prediction in inference
embedded_pitch_curve = self.pitch_embed(pitch_predictions)
embedded_energy_curve = self.energy_embed(energy_predictions)
hidden_states = hidden_states + embedded_energy_curve + embedded_pitch_curve
hidden_states = length_regulator(hidden_states, duration_predictions, self.config.speaking_speed)
else:
# use groundtruth in training
embedded_pitch_curve = self.pitch_embed(pitch_labels)
embedded_energy_curve = self.energy_embed(energy_labels)
hidden_states = hidden_states + embedded_energy_curve + embedded_pitch_curve
hidden_states = length_regulator(hidden_states, duration_labels)
# forward decoder
if not self.training:
hidden_mask = None
else:
spectrogram_mask = (spectrogram_labels != -100).any(dim=-1)
spectrogram_mask = spectrogram_mask.int()
if self.reduction_factor > 1:
length_dim = spectrogram_mask.shape[1] - spectrogram_mask.shape[1] % self.reduction_factor
spectrogram_mask = spectrogram_mask[:, :, :length_dim]
hidden_mask = spectrogram_mask.unsqueeze(-2)
decoder_outputs = self.decoder(
hidden_states,
hidden_mask,
output_hidden_states=output_hidden_states,
output_attentions=output_attentions,
return_dict=return_dict,
)
outputs_before_postnet, outputs_after_postnet = self.speech_decoder_postnet(decoder_outputs[0])
loss = None
if self.training:
# calculate loss
loss_duration_mask = ~duration_mask
loss_spectrogram_mask = spectrogram_mask.unsqueeze(-1).bool()
loss = self.criterion(
outputs_after_postnet=outputs_after_postnet,
outputs_before_postnet=outputs_before_postnet,
duration_outputs=duration_predictions,
pitch_outputs=pitch_predictions,
energy_outputs=energy_predictions,
spectrogram_labels=spectrogram_labels,
duration_labels=duration_labels,
pitch_labels=pitch_labels,
energy_labels=energy_labels,
duration_mask=loss_duration_mask,
spectrogram_mask=loss_spectrogram_mask,
)
if not return_dict:
postnet_outputs = (outputs_after_postnet,)
audio_feature_predictions = (
duration_predictions,
pitch_predictions,
energy_predictions,
)
outputs = postnet_outputs + encoder_outputs + decoder_outputs[1:] + audio_feature_predictions
return ((loss,) + outputs) if loss is not None else outputs
return FastSpeech2ConformerModelOutput(
loss=loss,
spectrogram=outputs_after_postnet,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
duration_outputs=duration_predictions,
pitch_outputs=pitch_predictions,
energy_outputs=energy_predictions,
)
# Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
| FastSpeech2ConformerModel |
python | bokeh__bokeh | src/bokeh/models/ranges.py | {
"start": 6288,
"end": 10208
} | class ____(DataRange):
''' An auto-fitting range in a continuous scalar dimension.
By default, the ``start`` and ``end`` of the range automatically
assume min and max values of the data for associated renderers.
'''
def __init__(self, *args, **kwargs) -> None:
if kwargs.get('follow') is not None:
kwargs['bounds'] = None
super().__init__(*args, **kwargs)
range_padding = Either(Float, TimeDelta, default=0.1, help="""
How much padding to add around the computed data bounds.
When ``range_padding_units`` is set to ``"percent"``, the span of the
range span is expanded to make the range ``range_padding`` percent larger.
When ``range_padding_units`` is set to ``"absolute"``, the start and end
of the range span are extended by the amount ``range_padding``.
""")
range_padding_units = Enum(PaddingUnits, default="percent", help="""
Whether the ``range_padding`` should be interpreted as a percentage, or
as an absolute quantity. (default: ``"percent"``)
""")
bounds = Nullable(MinMaxBounds(accept_datetime=True), help="""
The bounds that the range is allowed to go to. Typically used to prevent
the user from panning/zooming/etc away from the data.
By default, the bounds will be None, allowing your plot to pan/zoom as far
as you want. If bounds are 'auto' they will be computed to be the same as
the start and end of the ``DataRange1d``.
Bounds are provided as a tuple of ``(min, max)`` so regardless of whether
your range is increasing or decreasing, the first item should be the
minimum value of the range and the second item should be the maximum.
Setting ``min > max`` will result in a ``ValueError``.
If you only want to constrain one end of the plot, you can set ``min`` or
``max`` to ``None`` e.g. ``DataRange1d(bounds=(None, 12))``
""")
min_interval = Either(Null, Float, TimeDelta, help="""
The level that the range is allowed to zoom in, expressed as the
minimum visible interval. If set to ``None`` (default), the minimum
interval is not bound.""")
max_interval = Either(Null, Float, TimeDelta, help="""
The level that the range is allowed to zoom out, expressed as the
maximum visible interval. Note that ``bounds`` can impose an
implicit constraint on the maximum interval as well.""")
flipped = Bool(default=False, help="""
Whether the range should be "flipped" from its normal direction when
auto-ranging.
""")
follow = Nullable(Enum(StartEnd), help="""
Configure the data to follow one or the other data extreme, with a
maximum range size of ``follow_interval``.
If set to ``"start"`` then the range will adjust so that ``start`` always
corresponds to the minimum data value (or maximum, if ``flipped`` is
``True``).
If set to ``"end"`` then the range will adjust so that ``end`` always
corresponds to the maximum data value (or minimum, if ``flipped`` is
``True``).
If set to ``None`` (default), then auto-ranging does not follow, and
the range will encompass both the minimum and maximum data values.
``follow`` cannot be used with bounds, and if set, bounds will be set to
``None``.
""")
follow_interval = Nullable(Either(Float, TimeDelta), help="""
If ``follow`` is set to ``"start"`` or ``"end"`` then the range will
always be constrained to that::
abs(r.start - r.end) <= follow_interval
is maintained.
""")
default_span = Either(Float, TimeDelta, default=2.0, help="""
A default width for the interval, in case ``start`` is equal to ``end``
(if used with a log axis, default_span is in powers of 10).
""")
only_visible = Bool(default=False, help="""
If True, renderers that that are not visible will be excluded from automatic
bounds computations.
""")
| DataRange1d |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 43484,
"end": 43840
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("zh-CN")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in ZhCnProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in ZhCnProvider.MONTH_NAMES.values()
| TestZhCn |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 25409,
"end": 27600
} | class ____:
def test_basic(self, xp):
_, h = freqs(xp.asarray([1.0]), xp.asarray([1.0]), worN=8)
assert_array_almost_equal(h, xp.ones(8))
def test_output(self, xp):
# 1st order low-pass filter: H(s) = 1 / (s + 1)
w = xp.asarray([0.1, 1, 10, 100])
num = xp.asarray([1.])
den = xp.asarray([1, 1.])
w, H = freqs(num, den, worN=w)
s = w * 1j
expected = 1 / (s + 1)
assert_array_almost_equal(xp.real(H), xp.real(expected))
assert_array_almost_equal(xp.imag(H), xp.imag(expected))
def test_freq_range(self, xp):
# Test that freqresp() finds a reasonable frequency range.
# 1st order low-pass filter: H(s) = 1 / (s + 1)
# Expected range is from 0.01 to 10.
num = xp.asarray([1.])
den = xp.asarray([1, 1.])
n = 10
expected_w = _logspace(-2, 1, n, xp=xp)
w, H = freqs(num, den, worN=n)
assert_array_almost_equal(w, expected_w)
def test_plot(self, xp):
def plot(w, h):
assert_array_almost_equal(h, xp.ones(8))
with assert_raises(ZeroDivisionError):
freqs([1.0], [1.0], worN=8, plot=lambda w, h: 1 / 0)
freqs(xp.asarray([1.0]), xp.asarray([1.0]), worN=8, plot=plot)
def test_backward_compat(self, xp):
# For backward compatibility, test if None act as a wrapper for default
w1, h1 = freqs(xp.asarray([1.0]), xp.asarray([1.0]))
w2, h2 = freqs(xp.asarray([1.0]), xp.asarray([1.0]), None)
assert_array_almost_equal(w1, w2)
assert_array_almost_equal(h1, h2)
def test_w_or_N_types(self):
# Measure at 8 equally-spaced points
for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
np.array(8)):
w, h = freqs([1.0], [1.0], worN=N)
assert len(w) == 8
assert_array_almost_equal(h, np.ones(8))
# Measure at frequency 8 rad/sec
for w in (8.0, 8.0+0j):
w_out, h = freqs([1.0], [1.0], worN=w)
assert_array_almost_equal(w_out, [8])
assert_array_almost_equal(h, [1])
@make_xp_test_case(freqs_zpk)
| TestFreqs |
python | fsspec__filesystem_spec | fsspec/json.py | {
"start": 1252,
"end": 3768
} | class ____(json.JSONDecoder):
def __init__(
self,
*,
object_hook: Callable[[dict[str, Any]], Any] | None = None,
parse_float: Callable[[str], Any] | None = None,
parse_int: Callable[[str], Any] | None = None,
parse_constant: Callable[[str], Any] | None = None,
strict: bool = True,
object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
) -> None:
self.original_object_hook = object_hook
super().__init__(
object_hook=self.custom_object_hook,
parse_float=parse_float,
parse_int=parse_int,
parse_constant=parse_constant,
strict=strict,
object_pairs_hook=object_pairs_hook,
)
@classmethod
def try_resolve_path_cls(cls, dct: dict[str, Any]):
with suppress(Exception):
fqp = dct["cls"]
path_cls = _import_class(fqp)
if issubclass(path_cls, PurePath):
return path_cls
return None
@classmethod
def try_resolve_fs_cls(cls, dct: dict[str, Any]):
with suppress(Exception):
if "cls" in dct:
try:
fs_cls = _import_class(dct["cls"])
if issubclass(fs_cls, AbstractFileSystem):
return fs_cls
except Exception:
if "protocol" in dct: # Fallback if cls cannot be imported
return get_filesystem_class(dct["protocol"])
raise
return None
def custom_object_hook(self, dct: dict[str, Any]):
if "cls" in dct:
if (obj_cls := self.try_resolve_fs_cls(dct)) is not None:
return AbstractFileSystem.from_dict(dct)
if (obj_cls := self.try_resolve_path_cls(dct)) is not None:
return obj_cls(dct["str"])
if self.original_object_hook is not None:
return self.original_object_hook(dct)
return dct
def unmake_serializable(self, obj: Any) -> Any:
"""
Inverse function of :meth:`FilesystemJSONEncoder.make_serializable`.
"""
if isinstance(obj, dict):
obj = self.custom_object_hook(obj)
if isinstance(obj, dict):
return {k: self.unmake_serializable(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [self.unmake_serializable(v) for v in obj]
return obj
| FilesystemJSONDecoder |
python | pytorch__pytorch | test/distributed/_shard/sharded_optim/test_sharded_optim.py | {
"start": 1375,
"end": 2520
} | class ____(torch.nn.Module):
def __init__(self, rank=None):
super().__init__()
# Use same seed.
torch.manual_seed(0)
self.linear1 = torch.nn.Linear(17, 12)
self.linear2 = torch.nn.Linear(12, 29)
self.gelu = torch.nn.GELU()
if rank:
self.linear1.cuda(rank)
self.linear2.cuda(rank)
def shard_parameter(self):
rowwise_sharding_spec = ChunkShardingSpec(
dim=0,
placements=[
"rank:0/cuda:0",
"rank:1/cuda:1",
"rank:2/cuda:2",
"rank:3/cuda:3",
],
)
colwise_sharding_spec = ChunkShardingSpec(
dim=1,
placements=[
"rank:0/cuda:0",
"rank:1/cuda:1",
"rank:2/cuda:2",
"rank:3/cuda:3",
],
)
shard_parameter(self.linear1, "weight", rowwise_sharding_spec)
shard_parameter(self.linear2, "weight", colwise_sharding_spec)
def forward(self, inp):
return self.linear2(self.gelu(self.linear1(inp)))
| MyShardedLinear |
python | pytorch__pytorch | torch/_higher_order_ops/out_dtype.py | {
"start": 856,
"end": 5566
} | class ____(HigherOrderOperator):
"""
The out_dtype operator takes an existing ATen functional operator, an
`out_dtype` argument, and arguments to the original operator, and executes
the original operator and returns a Tensor with the `out_dtype` precision.
This operator does not mandate a compute precision so it allows the
representation to not be opinionated about the exact implementation.
The general implementation for all operators will be the following:
1. Promote inputs dtypes based on default PyTorch dtype promotion rules,
using the dtypes of all input Tensors/Scalars and the `out_dtype`
arugument.
2. Execute the operator
3. Cast the output to `out_dtype`
"""
def __init__(self) -> None:
super().__init__("out_dtype")
def __call__(self, op, output_dtype, *args):
if not isinstance(op, torch._ops.OpOverload):
raise ValueError("out_dtype's first argument must be an OpOverload")
if op._schema.is_mutable:
raise ValueError(
"out_dtype's first argument needs to be a functional operator"
)
if not (
len(op._schema.returns) == 1
and isinstance(op._schema.returns[0].type, torch.TensorType)
):
raise ValueError(
"out_dtype's can only apply to ops that return a single tensor"
f"Instead got {[r.type for r in op._schema.returns]}"
)
if op not in ALLOWABLE_OPS:
raise ValueError(
f"out_dtype only allows the following operators: {ALLOWABLE_OPS}."
)
res = super().__call__(op, output_dtype, *args)
return res
out_dtype = OutDtypeOperator()
def trace_out_dtype(proxy_mode, func_overload, op, output_dtype, *args):
# NB: Long-term we should put the decomposition logic into
# ProxyTorchDispatchMode so that people do not need to call maybe_handle_decomp
# in all HigherOrderOp proxy implementations.
r = maybe_handle_decomp(proxy_mode, func_overload, (op, output_dtype, *args), {})
if r is not NotImplemented:
return r
with disable_proxy_modes_tracing():
# This is a simplified implementation of this operator just for tracing.
# Actual implementation may also first promote the arguments
out = op(*args).to(dtype=output_dtype)
node_args = (op, output_dtype, *args)
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
out_proxy = proxy_mode.tracer.create_proxy(
"call_function", func_overload, proxy_args, {}, name="out_dtype"
)
return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
@out_dtype.py_impl(DispatchKey.CompositeExplicitAutograd)
def out_dtype_dense(op: torch._ops.OpOverload, output_dtype: torch.dtype, *args):
if is_int_mm(op, output_dtype, args):
return torch._int_mm(*args)
return out_dtype_fallback(op, output_dtype, *args)
def is_int_mm(op, output_dtype, args):
return (
op is torch.ops.aten.mm.default
and output_dtype == torch.int32
and len(args) == 2
and args[0].dtype == torch.int8
and args[1].dtype == torch.int8
and (args[0].is_cuda or args[0].is_xpu)
and (args[1].is_cuda or args[1].is_xpu)
)
def out_dtype_fallback(op, output_dtype, *args):
flat_inputs = pytree.arg_tree_leaves(*args) + [torch.ones(1, dtype=output_dtype)]
promote_dtype: torch.dtype = elementwise_dtypes(
*flat_inputs,
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)[0]
casted_args = pytree.tree_map_only(
torch.Tensor, lambda arg: arg.to(dtype=promote_dtype), args
)
res = op(*casted_args).to(dtype=output_dtype)
return res
out_dtype.py_autograd_impl(autograd_not_implemented(out_dtype, deferred_error=True))
@out_dtype.py_impl(ProxyTorchDispatchMode)
def out_dtype_proxy(
mode: ProxyTorchDispatchMode,
op: torch._ops.OpOverload,
output_dtype: torch.dtype,
*args,
):
return trace_out_dtype(mode, out_dtype, op, output_dtype, *args)
@out_dtype.py_impl(FakeTensorMode)
def out_dtype_fake_tensor_mode(
mode: FakeTensorMode,
op: torch._ops.OpOverload,
output_dtype: torch.dtype,
*args,
):
with mode:
return out_dtype_dense(op, output_dtype, *args)
@out_dtype.py_functionalize_impl
def out_dtype_func(ctx, op, output_dtype, *args):
unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
with ctx.redispatch_to_next():
res = out_dtype(op, output_dtype, *unwrapped_args)
return ctx.wrap_tensors(res)
| OutDtypeOperator |
python | ray-project__ray | ci/ray_ci/bisect/bisector.py | {
"start": 174,
"end": 2127
} | class ____:
def __init__(
self,
test: Test,
passing_revision: str,
failing_revision: str,
validator: Validator,
git_dir: str,
) -> None:
self.test = test
self.passing_revision = passing_revision
self.failing_revision = failing_revision
self.validator = validator
self.git_dir = git_dir
def run(self) -> Optional[str]:
"""
Find the blame revision for the test given the range of passing and failing
revision. If a blame cannot be found, return None
"""
revisions = self._get_revision_lists()
if len(revisions) < 2:
return None
while len(revisions) > 2:
logger.info(
f"Bisecting between {len(revisions)} revisions: "
f"{revisions[0]} to {revisions[-1]}"
)
mid = len(revisions) // 2
if self._checkout_and_validate(revisions[mid]):
revisions = revisions[mid:]
else:
revisions = revisions[: (mid + 1)]
return revisions[-1]
def _get_revision_lists(self) -> List[str]:
return (
subprocess.check_output(
[
"git",
"rev-list",
"--reverse",
f"^{self.passing_revision}~",
self.failing_revision,
],
cwd=self.git_dir,
)
.decode("utf-8")
.strip()
.split("\n")
)
def _checkout_and_validate(self, revision: str) -> bool:
"""
Validate whether the test is passing or failing on the given revision
"""
subprocess.check_call(["git", "clean", "-df"], cwd=self.git_dir)
subprocess.check_call(["git", "checkout", revision], cwd=self.git_dir)
return self.validator.run(self.test, revision)
| Bisector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.