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 | pypa__pip | src/pip/_internal/commands/lock.py | {
"start": 636,
"end": 5870
} | class ____(RequirementCommand):
"""
EXPERIMENTAL - Lock packages and their dependencies from:
- PyPI (and other indexes) using requirement specifiers.
- VCS project urls.
- Local project directories.
- Local or remote source archives.
pip also supports locking from "requirements files", which provide an easy
way to specify a whole environment to be installed.
The generated lock file is only guaranteed to be valid for the current
python version and platform.
"""
usage = """
%prog [options] [-e] <local project path> ...
%prog [options] <requirement specifier> [package-index-options] ...
%prog [options] -r <requirements file> [package-index-options] ...
%prog [options] <archive url/path> ..."""
def add_options(self) -> None:
self.cmd_opts.add_option(
cmdoptions.PipOption(
"--output",
"-o",
dest="output_file",
metavar="path",
type="path",
default="pylock.toml",
help="Lock file name (default=pylock.toml). Use - for stdout.",
)
)
self.cmd_opts.add_option(cmdoptions.requirements())
self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
self.cmd_opts.add_option(cmdoptions.constraints())
self.cmd_opts.add_option(cmdoptions.build_constraints())
self.cmd_opts.add_option(cmdoptions.no_deps())
self.cmd_opts.add_option(cmdoptions.pre())
self.cmd_opts.add_option(cmdoptions.editable())
self.cmd_opts.add_option(cmdoptions.src())
self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
self.cmd_opts.add_option(cmdoptions.no_build_isolation())
self.cmd_opts.add_option(cmdoptions.use_pep517())
self.cmd_opts.add_option(cmdoptions.check_build_deps())
self.cmd_opts.add_option(cmdoptions.config_settings())
self.cmd_opts.add_option(cmdoptions.no_binary())
self.cmd_opts.add_option(cmdoptions.only_binary())
self.cmd_opts.add_option(cmdoptions.prefer_binary())
self.cmd_opts.add_option(cmdoptions.require_hashes())
self.cmd_opts.add_option(cmdoptions.progress_bar())
index_opts = cmdoptions.make_option_group(
cmdoptions.index_group,
self.parser,
)
self.parser.insert_option_group(0, index_opts)
self.parser.insert_option_group(0, self.cmd_opts)
@with_cleanup
def run(self, options: Values, args: list[str]) -> int:
logger.verbose("Using %s", get_pip_version())
logger.warning(
"pip lock is currently an experimental command. "
"It may be removed/changed in a future release "
"without prior warning."
)
cmdoptions.check_build_constraints(options)
session = self.get_default_session(options)
finder = self._build_package_finder(
options=options,
session=session,
ignore_requires_python=options.ignore_requires_python,
)
build_tracker = self.enter_context(get_build_tracker())
directory = TempDirectory(
delete=not options.no_clean,
kind="install",
globally_managed=True,
)
reqs = self.get_requirements(args, options, finder, session)
wheel_cache = WheelCache(options.cache_dir)
# Only when installing is it permitted to use PEP 660.
# In other circumstances (pip wheel, pip download) we generate
# regular (i.e. non editable) metadata and wheels.
for req in reqs:
req.permit_editable_wheels = True
preparer = self.make_requirement_preparer(
temp_build_dir=directory,
options=options,
build_tracker=build_tracker,
session=session,
finder=finder,
use_user_site=False,
verbosity=self.verbosity,
)
resolver = self.make_resolver(
preparer=preparer,
finder=finder,
options=options,
wheel_cache=wheel_cache,
use_user_site=False,
ignore_installed=True,
ignore_requires_python=options.ignore_requires_python,
upgrade_strategy="to-satisfy-only",
)
self.trace_basic_info(finder)
requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
if options.output_file == "-":
base_dir = Path.cwd()
else:
output_file_path = Path(options.output_file)
if not is_valid_pylock_file_name(output_file_path):
logger.warning(
"%s is not a valid lock file name.",
output_file_path,
)
base_dir = output_file_path.parent
pylock_toml = Pylock.from_install_requirements(
requirement_set.requirements.values(), base_dir=base_dir
).as_toml()
if options.output_file == "-":
sys.stdout.write(pylock_toml)
else:
output_file_path.write_text(pylock_toml, encoding="utf-8")
return SUCCESS
| LockCommand |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 93781,
"end": 94362
} | class ____(sgqlc.types.Enum):
"""The possible states that can be requested when creating a check
run.
Enumeration Choices:
* `COMPLETED`: The check suite or run has been completed.
* `IN_PROGRESS`: The check suite or run is in progress.
* `PENDING`: The check suite or run is in pending state.
* `QUEUED`: The check suite or run has been queued.
* `WAITING`: The check suite or run is in waiting state.
"""
__schema__ = github_schema
__choices__ = ("COMPLETED", "IN_PROGRESS", "PENDING", "QUEUED", "WAITING")
| RequestableCheckStatusState |
python | plotly__plotly.py | plotly/graph_objs/icicle/marker/colorbar/_title.py | {
"start": 233,
"end": 4013
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle.marker.colorbar"
_path_str = "icicle.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.icicle.marker.colorbar.title.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.icicle.marker.colorbar.title.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def side(self):
"""
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h".
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom']
Returns
-------
Any
"""
return self["side"]
@side.setter
def side(self, val):
self["side"] = val
@property
def text(self):
"""
Sets the title of the color bar.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
"""
def __init__(self, arg=None, font=None, side=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.icicle.marker.colorbar.Title`
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
Returns
-------
Title
"""
super().__init__("title")
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.icicle.marker.colorbar.Title
constructor must be a dict or
an instance of :class:`plotly.graph_objs.icicle.marker.colorbar.Title`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("side", arg, side)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Title |
python | ray-project__ray | rllib/algorithms/impala/tests/test_impala.py | {
"start": 247,
"end": 2550
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_impala_minibatch_size_check(self):
config = (
impala.IMPALAConfig()
.environment("CartPole-v1")
.training(minibatch_size=100)
.env_runners(rollout_fragment_length=30)
)
with pytest.raises(
ValueError,
match=r"`minibatch_size` \(100\) must either be None or a multiple of `rollout_fragment_length` \(30\)",
):
config.validate()
def test_impala_lr_schedule(self):
# Test whether we correctly ignore the "lr" setting.
# The first lr should be 0.05.
config = (
impala.IMPALAConfig()
.learners(num_learners=0)
.experimental(_validate_config=False) #
.training(
lr=[
[0, 0.05],
[100000, 0.000001],
],
train_batch_size=100,
)
.env_runners(num_envs_per_env_runner=2)
.environment(env="CartPole-v1")
)
def get_lr(result):
return result[LEARNER_RESULTS][DEFAULT_POLICY_ID][
"default_optimizer_learning_rate"
]
algo = config.build()
optim = algo.learner_group._learner.get_optimizer()
try:
check(optim.param_groups[0]["lr"], 0.05)
for _ in range(1):
r1 = algo.train()
for _ in range(2):
r2 = algo.train()
for _ in range(2):
r3 = algo.train()
# Due to the asynch'ness of IMPALA, learner-stats metrics
# could be delayed by one iteration. Do 3 train() calls here
# and measure guaranteed decrease in lr between 1st and 3rd.
lr1 = get_lr(r1)
lr2 = get_lr(r2)
lr3 = get_lr(r3)
assert lr2 <= lr1, (lr1, lr2)
assert lr3 <= lr2, (lr2, lr3)
assert lr3 < lr1, (lr1, lr3)
finally:
algo.stop()
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestIMPALA |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 10653,
"end": 10862
} | class ____(SubClassBoringModel):
def __init__(self, *args, my_loss=torch.nn.CrossEntropyLoss(), **kwargs):
super().__init__(*args, **kwargs)
self.save_hyperparameters()
| AggSubClassBoringModel |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 1631,
"end": 1889
} | class ____(ComparableEntity):
pass
def _aliased_join_warning(arg):
return testing.expect_warnings(
r"An alias is being generated automatically against joined entity "
r"Mapper\[%s\] due to overlapping tables" % (arg,),
)
| Paperwork |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 15891,
"end": 17053
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreMemcachedHook")
def test_assert_valid_hook_call(self, mock_hook):
mock_hook.return_value.create_instance.return_value = cloud_memcache.Instance()
task = CloudMemorystoreMemcachedCreateInstanceOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
instance_id=TEST_INSTANCE_ID,
instance=TEST_INSTANCE,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
)
task.execute(mock.MagicMock())
mock_hook.assert_called_once_with(gcp_conn_id=TEST_GCP_CONN_ID)
mock_hook.return_value.create_instance.assert_called_once_with(
location=TEST_LOCATION,
instance_id=TEST_INSTANCE_ID,
instance=TEST_INSTANCE,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestCloudMemorystoreMemcachedCreateInstanceOperator |
python | coleifer__peewee | tests/psycopg3_ext.py | {
"start": 14138,
"end": 15926
} | class ____(BaseBinaryJsonFieldTestCase, ModelTestCase):
M = BJson
N = Normal
database = db
requires = [BJson, Normal]
def test_remove_data(self):
BJson.delete().execute() # Clear out db.
BJson.create(data={
'k1': 'v1',
'k2': 'v2',
'k3': {'x1': 'z1', 'x2': 'z2'},
'k4': [0, 1, 2]})
def assertData(exp_list, expected_data):
query = BJson.select(BJson.data.remove(*exp_list)).tuples()
data = query[:][0][0]
self.assertEqual(data, expected_data)
D = BJson.data
assertData(['k3'], {'k1': 'v1', 'k2': 'v2', 'k4': [0, 1, 2]})
assertData(['k1', 'k3'], {'k2': 'v2', 'k4': [0, 1, 2]})
assertData(['k1', 'kx', 'ky', 'k3'], {'k2': 'v2', 'k4': [0, 1, 2]})
assertData(['k4', 'k3'], {'k1': 'v1', 'k2': 'v2'})
def test_json_contains_in_list(self):
m1 = self.M.create(data=[{'k1': 'v1', 'k2': 'v2'}, {'a1': 'b1'}])
m2 = self.M.create(data=[{'k3': 'v3'}, {'k4': 'v4'}])
m3 = self.M.create(data=[{'k5': 'v5', 'k6': 'v6'}, {'k1': 'v1'}])
query = (self.M
.select()
.where(self.M.data.contains([{'k1': 'v1'}]))
.order_by(self.M.id))
self.assertEqual([m.id for m in query], [m1.id, m3.id])
def test_integer_index_weirdness(self):
self._create_test_data()
def fails():
with self.database.atomic():
expr = BJson.data.contains_any(2, 8, 12)
results = list(BJson.select().where(
BJson.data.contains_any(2, 8, 12)))
# Complains of a missing cast/conversion for the data-type?
self.assertRaises(ProgrammingError, fails)
| TestPsycopg3BinaryJsonField |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py | {
"start": 2257,
"end": 2465
} | class ____:
""" __getnewargs_ex__ returns node which does not have 'value' in AST """
def __getnewargs_ex__(self): # [invalid-getnewargs-ex-returned]
return lambda: (1, 2)
| SixthBadGetNewArgsEx |
python | boto__boto3 | boto3/docs/base.py | {
"start": 604,
"end": 1496
} | class ____:
def __init__(self, resource):
self._resource = resource
self._client = self._resource.meta.client
self._resource_model = self._resource.meta.resource_model
self._service_model = self._client.meta.service_model
self._resource_name = self._resource.meta.resource_model.name
self._service_name = self._service_model.service_name
self._service_docs_name = self._client.__class__.__name__
self.member_map = OrderedDict()
self.represents_service_resource = (
self._service_name == self._resource_name
)
self._resource_class_name = self._resource_name
if self._resource_name == self._service_name:
self._resource_class_name = 'ServiceResource'
@property
def class_name(self):
return f'{self._service_docs_name}.{self._resource_name}'
| BaseDocumenter |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 25548,
"end": 26640
} | class ____(RangeMap):
"""
Given parameters suitable for a dict representing keys
and a weighted proportion, return a RangeMap representing
spans of values proportial to the weights:
>>> even = WeightedLookup(a=1, b=1)
[0, 1) -> a
[1, 2) -> b
>>> lk = WeightedLookup(a=1, b=2)
[0, 1) -> a
[1, 3) -> b
>>> lk[.5]
'a'
>>> lk[1.5]
'b'
Adds ``.random()`` to select a random weighted value:
>>> lk.random() in ['a', 'b']
True
>>> choices = [lk.random() for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / choices.count('b')
>>> .4 < ratio < .6
True
"""
def __init__(self, *args, **kwargs):
raw = dict(*args, **kwargs)
# allocate keys by weight
indexes = map(Accumulator(), raw.values())
super().__init__(zip(indexes, raw.keys()), key_match_comparator=operator.lt)
def random(self):
lower, upper = self.bounds()
selector = random.random() * upper
return self[selector]
| WeightedLookup |
python | django__django | tests/db_functions/text/test_sha256.py | {
"start": 228,
"end": 1838
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[
Author(alias="John Smith"),
Author(alias="Jordan Élena"),
Author(alias="皇帝"),
Author(alias=""),
Author(alias=None),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
sha256_alias=SHA256("alias"),
)
.values_list("sha256_alias", flat=True)
.order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a",
"6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e",
"3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
if connection.features.interprets_empty_strings_as_nulls
else None
),
],
)
def test_transform(self):
with register_lookup(CharField, SHA256):
authors = Author.objects.filter(
alias__sha256=(
"ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a"
),
).values_list("alias", flat=True)
self.assertSequenceEqual(authors, ["John Smith"])
| SHA256Tests |
python | kamyu104__LeetCode-Solutions | Python/determine-whether-matrix-can-be-obtained-by-rotation.py | {
"start": 33,
"end": 621
} | class ____(object):
def findRotation(self, mat, target):
"""
:type mat: List[List[int]]
:type target: List[List[int]]
:rtype: bool
"""
checks = [lambda i, j: mat[i][j] == target[i][j],
lambda i, j: mat[i][j] == target[j][-1-i],
lambda i, j: mat[i][j] == target[-1-i][-1-j],
lambda i, j: mat[i][j] == target[-1-j][i]]
traverse = lambda check: all(check(i, j) for i in xrange(len(mat)) for j in xrange(len(mat[0])))
return any(traverse(check) for check in checks)
| Solution |
python | ray-project__ray | python/ray/data/_internal/execution/operators/input_data_buffer.py | {
"start": 250,
"end": 3671
} | class ____(PhysicalOperator):
"""Defines the input data for the operator DAG.
For example, this may hold cached blocks from a previous Dataset execution, or
the arguments for read tasks.
"""
def __init__(
self,
data_context: DataContext,
input_data: Optional[List[RefBundle]] = None,
input_data_factory: Optional[Callable[[int], List[RefBundle]]] = None,
):
"""Create an InputDataBuffer.
Args:
data_context: :class:`~ray.data.context.DataContext`
object to use injestion.
input_data: The list of bundles to output from this operator.
input_data_factory: The factory to get input data, if input_data is None.
"""
super().__init__("Input", [], data_context)
if input_data is not None:
assert input_data_factory is None
# Copy the input data to avoid mutating the original list.
self._input_data = input_data[:]
self._is_input_initialized = True
self._initialize_metadata()
else:
# Initialize input lazily when execution is started.
assert input_data_factory is not None
self._input_data_factory = input_data_factory
self._is_input_initialized = False
self._input_data_index = 0
self.mark_execution_finished()
def start(self, options: ExecutionOptions) -> None:
if not self._is_input_initialized:
self._input_data = self._input_data_factory(
self.target_max_block_size_override
or self.data_context.target_max_block_size
)
self._is_input_initialized = True
self._initialize_metadata()
# InputDataBuffer does not take inputs from other operators,
# so we record input metrics here
for bundle in self._input_data:
self._metrics.on_input_received(bundle)
super().start(options)
def has_next(self) -> bool:
return self._input_data_index < len(self._input_data)
def _get_next_inner(self) -> RefBundle:
# We can't pop the input data. If we do, Ray might garbage collect the block
# references, and Ray won't be able to reconstruct downstream objects.
bundle = self._input_data[self._input_data_index]
self._input_data_index += 1
return bundle
def get_stats(self) -> StatsDict:
return {}
def _add_input_inner(self, refs, input_index) -> None:
raise ValueError("Inputs are not allowed for this operator.")
def _initialize_metadata(self):
assert self._input_data is not None and self._is_input_initialized
self._estimated_num_output_bundles = len(self._input_data)
block_metadata = []
total_rows = 0
for bundle in self._input_data:
block_metadata.extend(bundle.metadata)
bundle_num_rows = bundle.num_rows()
if total_rows is not None and bundle_num_rows is not None:
total_rows += bundle_num_rows
else:
# total row is unknown
total_rows = None
if total_rows:
self._estimated_num_output_rows = total_rows
self._stats = {
"input": block_metadata,
}
def implements_accurate_memory_accounting(self) -> bool:
return True
| InputDataBuffer |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 12338,
"end": 12592
} | class ____(BaseModel):
"""
State of existence of a collection, true = exists, false = does not exist
"""
exists: bool = Field(..., description="State of existence of a collection, true = exists, false = does not exist")
| CollectionExistence |
python | allegroai__clearml | clearml/backend_api/services/v2_9/auth.py | {
"start": 4311,
"end": 4961
} | class ____(Request):
"""
Creates a new set of credentials for the authenticated user.
New key/secret is returned.
Note: Secret will never be returned in any other API call.
If a secret is lost or compromised, the key should be revoked
and a new set of credentials can be created.
"""
_service = "auth"
_action = "create_credentials"
_version = "2.9"
_schema = {
"additionalProperties": False,
"definitions": {},
"properties": {},
"type": "object",
}
| CreateCredentialsRequest |
python | django__django | tests/model_formsets/models.py | {
"start": 2683,
"end": 2913
} | class ____(models.Model):
owner = models.OneToOneField(Owner, models.CASCADE, primary_key=True)
age = models.PositiveIntegerField()
def __str__(self):
return "%s is %d" % (self.owner.name, self.age)
| OwnerProfile |
python | PyCQA__pycodestyle | tests/test_blank_lines.py | {
"start": 3258,
"end": 3663
} | class ____(object):
pass
""")
self.assertEqual([
'E303:6:1', # some_function
'E303:15:1', # SomeFarClass
], result)
def test_method_more_blank_lines(self):
"""
It will trigger an error when more than 1 blank line is found
before method definition
"""
result = errors_from_src("""# First comment line.
| AFarEnoughClass |
python | sympy__sympy | sympy/core/rules.py | {
"start": 28,
"end": 1496
} | class ____:
"""
Immutable mapping that can be used as a generic transformation rule.
Parameters
==========
transform : callable
Computes the value corresponding to any key.
filter : callable, optional
If supplied, specifies which objects are in the mapping.
Examples
========
>>> from sympy.core.rules import Transform
>>> from sympy.abc import x
This Transform will return, as a value, one more than the key:
>>> add1 = Transform(lambda x: x + 1)
>>> add1[1]
2
>>> add1[x]
x + 1
By default, all values are considered to be in the dictionary. If a filter
is supplied, only the objects for which it returns True are considered as
being in the dictionary:
>>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
>>> 2 in add1_odd
False
>>> add1_odd.get(2, 0)
0
>>> 3 in add1_odd
True
>>> add1_odd[3]
4
>>> add1_odd.get(3, 0)
4
"""
def __init__(self, transform, filter=lambda x: True):
self._transform = transform
self._filter = filter
def __contains__(self, item):
return self._filter(item)
def __getitem__(self, key):
if self._filter(key):
return self._transform(key)
else:
raise KeyError(key)
def get(self, item, default=None):
if item in self:
return self[item]
else:
return default
| Transform |
python | ray-project__ray | rllib/examples/evaluation/evaluation_parallel_to_training.py | {
"start": 4478,
"end": 11661
} | class ____(RLlibCallback):
def on_train_result(
self,
*,
algorithm: Algorithm,
metrics_logger: Optional[MetricsLogger] = None,
result: ResultDict,
**kwargs,
):
# The eval results can be found inside the main `result` dict
# (old API stack: "evaluation").
eval_results = result.get(EVALUATION_RESULTS, {})
# In there, there is a sub-key: ENV_RUNNER_RESULTS.
eval_env_runner_results = eval_results.get(ENV_RUNNER_RESULTS)
# Make sure we always run exactly the given evaluation duration,
# no matter what the other settings are (such as
# `evaluation_num_env_runners` or `evaluation_parallel_to_training`).
if eval_env_runner_results and NUM_EPISODES in eval_env_runner_results:
num_episodes_done = eval_env_runner_results[NUM_EPISODES]
if algorithm.config.enable_env_runner_and_connector_v2:
num_timesteps_reported = eval_env_runner_results[NUM_ENV_STEPS_SAMPLED]
else:
num_timesteps_reported = eval_results["timesteps_this_iter"]
# We run for automatic duration (as long as training takes).
if algorithm.config.evaluation_duration == "auto":
# If duration=auto: Expect at least as many timesteps as workers
# (each worker's `sample()` is at least called once).
# UNLESS: All eval workers were completely busy during the auto-time
# with older (async) requests and did NOT return anything from the async
# fetch.
assert (
num_timesteps_reported == 0
or num_timesteps_reported
>= algorithm.config.evaluation_num_env_runners
)
# We count in episodes.
elif algorithm.config.evaluation_duration_unit == "episodes":
# Compare number of entries in episode_lengths (this is the
# number of episodes actually run) with desired number of
# episodes from the config.
assert (
algorithm.iteration + 1 % algorithm.config.evaluation_interval != 0
or num_episodes_done == algorithm.config.evaluation_duration
), (num_episodes_done, algorithm.config.evaluation_duration)
print(
"Number of run evaluation episodes: " f"{num_episodes_done} (ok)!"
)
# We count in timesteps.
else:
# TODO (sven): This assertion works perfectly fine locally, but breaks
# the CI for no reason. The observed collected timesteps is +500 more
# than desired (~2500 instead of 2011 and ~1250 vs 1011).
# num_timesteps_wanted = algorithm.config.evaluation_duration
# delta = num_timesteps_wanted - num_timesteps_reported
# Expect roughly the same (desired // num-eval-workers).
# assert abs(delta) < 20, (
# delta,
# num_timesteps_wanted,
# num_timesteps_reported,
# )
print(
"Number of run evaluation timesteps: "
f"{num_timesteps_reported} (ok?)!"
)
if __name__ == "__main__":
args = parser.parse_args()
# Register our environment with tune.
if args.num_agents > 0:
register_env(
"env",
lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}),
)
base_config = (
get_trainable_cls(args.algo)
.get_default_config()
.environment("env" if args.num_agents > 0 else "CartPole-v1")
.env_runners(create_env_on_local_worker=True)
# Use a custom callback that asserts that we are running the
# configured exact number of episodes per evaluation OR - in auto
# mode - run at least as many episodes as we have eval workers.
.callbacks(AssertEvalCallback)
.evaluation(
# Parallel evaluation+training config.
# Switch on evaluation in parallel with training.
evaluation_parallel_to_training=args.evaluation_parallel_to_training,
# Use two evaluation workers. Must be >0, otherwise,
# evaluation will run on a local worker and block (no parallelism).
evaluation_num_env_runners=args.evaluation_num_env_runners,
# Evaluate every other training iteration (together
# with every other call to Algorithm.train()).
evaluation_interval=args.evaluation_interval,
# Run for n episodes/timesteps (properly distribute load amongst
# all eval workers). The longer it takes to evaluate, the more sense
# it makes to use `evaluation_parallel_to_training=True`.
# Use "auto" to run evaluation for roughly as long as the training
# step takes.
evaluation_duration=args.evaluation_duration,
# "episodes" or "timesteps".
evaluation_duration_unit=args.evaluation_duration_unit,
# Switch off exploratory behavior for better (greedy) results.
evaluation_config={
"explore": False,
# TODO (sven): Add support for window=float(inf) and reduce=mean for
# evaluation episode_return_mean reductions (identical to old stack
# behavior, which does NOT use a window (100 by default) to reduce
# eval episode returns.
"metrics_num_episodes_for_smoothing": 5,
},
)
)
# Set the minimum time for an iteration to 10sec, even for algorithms like PPO
# that naturally limit their iteration times to exactly one `training_step`
# call. This provides enough time for the eval EnvRunners in the
# "evaluation_duration=auto" setting to sample at least one complete episode.
if args.evaluation_duration == "auto":
base_config.reporting(min_time_s_per_iteration=10)
# Add a simple multi-agent setup.
if args.num_agents > 0:
base_config.multi_agent(
policies={f"p{i}" for i in range(args.num_agents)},
policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}",
)
# Set some PPO-specific tuning settings to learn better in the env (assumed to be
# CartPole-v1).
if args.algo == "PPO":
base_config.training(
lr=0.0003,
num_epochs=6,
vf_loss_coeff=0.01,
)
stop = {
TRAINING_ITERATION: args.stop_iters,
f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": (
args.stop_reward
),
NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps,
}
run_rllib_example_script_experiment(
base_config,
args,
stop=stop,
success_metric={
f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": (
args.stop_reward
),
},
)
| AssertEvalCallback |
python | google__pytype | pytype/tests/test_recovery2.py | {
"start": 1329,
"end": 2175
} | class ____(test_base.BaseTest):
"""Tests for recovering after errors(python3 only)."""
def test_bad_call_parameter(self):
ty = self.Infer(
"""
def f():
return "%s" % chr("foo")
""",
report_errors=False,
)
self.assertTypesMatchPytd(
ty,
"""
def f() -> str: ...
""",
)
def test_bad_function(self):
ty = self.Infer(
"""
import time
def f():
return time.unknown_function(3)
def g():
return '%s' % f()
""",
report_errors=False,
)
self.assertTypesMatchPytd(
ty,
"""
import time
from typing import Any
def f() -> Any: ...
def g() -> str: ...
""",
)
if __name__ == "__main__":
test_base.main()
| RecoveryTestsPython3 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 363426,
"end": 364448
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("labels",)
labels = sgqlc.types.Field(
LabelConnection,
graphql_name="labels",
args=sgqlc.types.ArgDict(
(
(
"order_by",
sgqlc.types.Arg(
LabelOrder,
graphql_name="orderBy",
default={"field": "CREATED_AT", "direction": "ASC"},
),
),
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
| Labelable |
python | joke2k__faker | faker/providers/lorem/el_GR/__init__.py | {
"start": 68,
"end": 7458
} | class ____(LoremProvider):
"""Implement lorem provider for ``el_GR`` locale."""
common_words = (
"άρα",
"ένα",
"ένας",
"έξι",
"έτσι",
"έχω",
"ήδη",
"ίδιο",
"αν",
"ανά",
"από",
"ας",
"για",
"δε",
"δεν",
"δύο",
"εγώ",
"εδώ",
"εκτός",
"επί",
"θα",
"κάτι",
"και",
"κι",
"μέχρι",
"μα",
"μας",
"με",
"μη",
"μην",
"μια",
"μιας",
"μου",
"να",
"ναι",
"ο",
"οι",
"πάντα",
"πάντως",
"πιο",
"πλέον",
"ποια",
"πολύ",
"που",
"πως",
"σαν",
"σας",
"σε",
"σου",
"στα",
"στη",
"στις",
"στο",
"τα",
"τη",
"την",
"της",
"τι",
"τις",
"το",
"τον",
"του",
"τους",
"των",
"ως",
"όσο",
"όταν",
"ότι",
"όχι",
)
word_list = common_words * 2 + (
"άλγεβρα",
"άπειρα",
"άρα",
"άρθρων",
"άτομο",
"έγραψες",
"έλεγχος",
"έξι",
"έρθει",
"έστειλε",
"έστελνε",
"έτοιμος",
"έτσι",
"έχω",
"ήδη",
"ίδιο",
"αγοράζοντας",
"αθόρυβες",
"ακούσει",
"αλγόριθμου",
"αναγκάζονται",
"ανακλύψεις",
"αναφέρονται",
"αναφορά",
"ανεπιθύμητη",
"ανταγωνιστής",
"αντιλήφθηκαν",
"ανώδυνη",
"απίστευτα",
"απαράδεκτη",
"απαραίτητο",
"απαρατήρητο",
"απλό",
"αποδείξεις",
"αποθηκευτικού",
"αποκλειστικούς",
"απομόνωση",
"αποστηθίσει",
"αποφάσισε",
"από",
"απόλαυσε",
"αρέσει",
"αρπάζεις",
"αρχεία",
"ατόμου",
"αυτήν",
"αυτός",
"αφήσεις",
"βάζοντας",
"βαθμό",
"βασανίζουν",
"βγήκε",
"βιαστικά",
"βιβλίο",
"βουτήξουν",
"βρίσκονται",
"γέλασαν",
"γεγονός",
"γειτονιάς",
"γεύματος",
"για",
"γιαυτό",
"γνωρίζουμε",
"γνωστή",
"γράψει",
"γραμμές",
"γραμμή",
"γραμμής",
"γραφικά",
"δίνοντας",
"δε",
"δείξει",
"δεδομένων",
"δεν",
"δημιουργήσεις",
"δημιουργείς",
"δημιουργια",
"διάβασε",
"διάσημα",
"διαδίκτυο",
"διακοπή",
"διακοπής",
"διακόψουμε",
"διαπιστώνεις",
"διασφαλίζεται",
"διαφήμιση",
"διαχειριστής",
"διευθυντές",
"διοικητικό",
"διολισθήσεις",
"διορθώσει",
"διορθώσεις",
"δοκιμάσεις",
"δουλεύει",
"δούλευε",
"δυστυχής",
"δυστυχώς",
"δωροδοκηθούν",
"δύο",
"είχαμε",
"εγώ",
"εδώ",
"ειδικά",
"εικόνες",
"εκδόσεις",
"εκείνου",
"εκθέσεις",
"εκτελέσει",
"εκτελέσεις",
"εκτελείται",
"εκτός",
"ελέγχου",
"εντολές",
"εξακολουθεί",
"εξαρτάται",
"εξοργιστικά",
"επί",
"επενδυτής",
"επεξεργασία",
"επιδιορθώσεις",
"επιδιόρθωση",
"επιστρέφουν",
"επιχείριση",
"εργάστηκε",
"εργαζόμενοι",
"εργαζόμενων",
"εργαλείων",
"εργασίας",
"εργοστασίου",
"ερωτήσεις",
"ερώτηση",
"εσωτερικών",
"εταιρείες",
"ευκολότερο",
"εφαμοργής",
"εφαρμογή",
"εφαρμογής",
"ζητήσεις",
"ημέρα",
"θέλεις",
"θέμα",
"θέματα",
"θυμάμαι",
"ιδιαίτερα",
"κάνε",
"κάνεις",
"κάτι",
"και",
"καλύτερο",
"κανένας",
"κανείς",
"κανόνα",
"καταλάθος",
"κειμένων",
"κι",
"κλπ",
"κοιτάζοντας",
"κρατάει",
"κρατήσουν",
"κόλπα",
"κόψεις",
"κύκλο",
"κώδικάς",
"κώδικα",
"λέει",
"λίγο",
"λαμβάνουν",
"λες",
"λετπά",
"λιγότερο",
"λοιπόν",
"μάθε",
"μάλλον",
"μάτσο",
"μέγιστη",
"μέρος",
"μέσης",
"μέχρι",
"μαγικά",
"μερικούς",
"μεταγλωτίσει",
"μεταγλωτιστής",
"μεταφραστής",
"μετράει",
"μετρήσεις",
"μηχανής",
"μπορούσες",
"μπουν",
"νέα",
"νέο",
"νέου",
"νέων",
"νιρβάνα",
"νόμιζες",
"ξέχασε",
"ορίστε",
"πάντα",
"πάντως",
"πάρα",
"πάρεις",
"πήρε",
"παίξουν",
"παίρνει",
"παίρνουν",
"πακέτων",
"παράγοντες",
"παράδειγμα",
"παραγωγικής",
"παραδοτέου",
"παραδώσεις",
"παραπάνω",
"πεδία",
"περίπου",
"περιβάλλον",
"περιβάλλοντος",
"περιεχόμενα",
"περιμένουν",
"περισσότερες",
"περισσότερη",
"πες",
"πετάνε",
"πετάξαμε",
"πετούν",
"πηγαίου",
"πιο",
"πλέον",
"ποια",
"πολύ",
"ποσοστό",
"που",
"προβληματική",
"προγραμματιστές",
"προγραμματιστής",
"προκαλείς",
"προκύπτουν",
"προσεκτικά",
"προσθέσει",
"προσλάμβανες",
"προσοχή",
"προσπαθήσεις",
"προσπαθούν",
"προϊόντα",
"πρόσληψη",
"πρώτης",
"πρώτο",
"πρώτοι",
"πόρτες",
"ροή",
"ρουτίνα",
"ρωτάει",
"ρωτήσει",
"σίγουρος",
"σημαντικό",
"σημαντικός",
"σημεία",
"σκεφτείς",
"σπίτι",
"στέλνοντάς",
"στήλες",
"σταματάς",
"στραβά",
"συγγραφής",
"συγγραφείς",
"συγκεντρωμένοι",
"συγχρόνως",
"συγχωνευτεί",
"συνάδελφος",
"συνέχεια",
"συνεντεύξεις",
"συνεχώς",
"συνηθίζουν",
"σχεδιαστής",
"σωστά",
"τέλειοι",
"τα",
"ταξινομεί",
"τεκμηριώνει",
"τελειώσει",
"τεσσαρών",
"τοπικές",
"τρέξει",
"τρόπο",
"τρόποι",
"τύπου",
"τύπους",
"υπηρεσία",
"υποψήφιο",
"υψηλότερη",
"υόρκη",
"φίλος",
"φαινόμενο",
"φακέλους",
"φράση",
"χάος",
"χαμηλός",
"χαρακτηριστικό",
"χαρακτηριστικών",
"χαρτιού",
"χειρότερα",
"χρειάζονται",
"χρησιμοποίησέ",
"χρησιμοποιούνταν",
"χρησιμοποιούσες",
"χρησιμοποιώντας",
"χρονοδιαγράμματα",
"χρονοδιαγράμματος",
"χρόνου",
"χώρου",
"ωραίο",
"ύψος",
"ώρα",
)
parts_of_speech: Dict[str, tuple] = {}
| Provider |
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 4519,
"end": 10435
} | class ____(serializers.Serializer):
schedule_type = serializers.ChoiceField(
choices=list(zip(SCHEDULE_TYPES.keys(), SCHEDULE_TYPES.keys())),
help_text='Currently supports "crontab" or "interval"',
# The schedule_type IS required when the `type` is not part of the
# `schedule` object field (see self.validate). We cannot mark it as
# required here however since this field may be left out when using the
# alternative schedule format.
required=False,
)
schedule = ObjectField(
help_text="Varies depending on the schedule_type. Is either a crontab string, or a 2 element tuple for intervals (e.g. [1, 'day'])",
)
"""
It is also possible to pass an object with the following formats
>>> { "type": "interval", "value": 5, "unit": "day", }
>>> { "type": "crontab", "value": "0 * * * *", }
When using this format the `schedule_type` is not required
"""
checkin_margin = MissedMarginField(
required=False,
allow_null=True,
default=None,
help_text="How long (in minutes) after the expected checkin time will we wait until we consider the checkin to have been missed.",
min_value=1,
max_value=MAX_MARGIN,
)
max_runtime = EmptyIntegerField(
required=False,
allow_null=True,
default=None,
help_text="How long (in minutes) is the checkin allowed to run for in CheckInStatus.IN_PROGRESS before it is considered failed.",
min_value=1,
max_value=MAX_TIMEOUT,
)
timezone = serializers.ChoiceField(
choices=sorted(AVAILABLE_TIMEZONES),
required=False,
allow_blank=True,
help_text="tz database style timezone string",
)
failure_issue_threshold = EmptyIntegerField(
required=False,
allow_null=True,
default=None,
help_text="How many consecutive missed or failed check-ins in a row before creating a new issue.",
min_value=1,
max_value=MAX_THRESHOLD,
)
recovery_threshold = EmptyIntegerField(
required=False,
allow_null=True,
default=None,
help_text="How many successful check-ins in a row before resolving an issue.",
min_value=1,
max_value=MAX_THRESHOLD,
)
def bind(self, *args, **kwargs):
super().bind(*args, **kwargs)
# Inherit instance data when used as a nested serializer
if self.parent.instance:
self.instance = self.parent.instance.config
self.partial = self.parent.partial
def validate_schedule_type(self, value):
if value:
value = SCHEDULE_TYPES[value]
return value
def validate(self, attrs):
if "schedule_type" in attrs:
schedule_type = attrs["schedule_type"]
elif self.instance:
schedule_type = self.instance.get("schedule_type")
else:
schedule_type = None
# Remove blank timezone values
if attrs.get("timezone") == "":
del attrs["timezone"]
schedule = attrs.get("schedule")
if not schedule:
return attrs
# Translate alternative schedule type key
if isinstance(schedule, dict) and schedule.get("type"):
schedule_type = SCHEDULE_TYPES.get(schedule["type"])
if schedule_type is None:
raise ValidationError({"schedule_type": "Missing or invalid schedule type"})
if schedule_type == ScheduleType.INTERVAL:
# Translate alternative style schedule configuration
if isinstance(schedule, dict):
schedule = [schedule.get("value"), schedule.get("unit")]
if not isinstance(schedule, list):
raise ValidationError({"schedule": "Invalid schedule for for 'interval' type"})
if not isinstance(schedule[0], int):
raise ValidationError({"schedule": "Invalid schedule for schedule unit count"})
if schedule[0] <= 0:
raise ValidationError({"schedule": "Interval must be greater than zero"})
if schedule[1] not in INTERVAL_NAMES:
raise ValidationError({"schedule": "Invalid schedule for schedule unit name"})
elif schedule_type == ScheduleType.CRONTAB:
# Translate alternative style schedule configuration
if isinstance(schedule, dict):
schedule = schedule.get("value")
if not isinstance(schedule, str):
raise ValidationError({"schedule": "Invalid schedule for 'crontab' type"})
# normalize whitespace
schedule = re.sub(CRONTAB_WHITESPACE, " ", schedule).strip()
if schedule.startswith("@"):
try:
schedule = NONSTANDARD_CRONTAB_SCHEDULES[schedule]
except KeyError:
raise ValidationError({"schedule": "Schedule was not parseable"})
# Do not support 6 or 7 field crontabs
if len(schedule.split()) > 5:
raise ValidationError({"schedule": "Only 5 field crontab syntax is supported"})
# Validate the expression and ensure we can traverse forward / back
now = timezone.now()
try:
get_next_schedule(now, CrontabSchedule(schedule))
get_prev_schedule(now, now, CrontabSchedule(schedule))
except CronSimError:
raise ValidationError({"schedule": "Schedule is invalid"})
# Do not support 6 or 7 field crontabs
if len(schedule.split()) > 5:
raise ValidationError({"schedule": "Only 5 field crontab syntax is supported"})
attrs["schedule"] = schedule
attrs["schedule_type"] = schedule_type
return attrs
@extend_schema_serializer(exclude_fields=["alert_rule"])
| ConfigValidator |
python | run-llama__llama_index | llama-index-core/llama_index/core/ingestion/transformations.py | {
"start": 1264,
"end": 1778
} | class ____(BaseModel):
"""A description for a category of transformation within a pipeline."""
name: str = Field(description="Unique name of the type of transformation")
description: str = Field(description="Description for the type of transformation")
input_type: TransformationIOType = Field(
description="Input type for the transformation type"
)
output_type: TransformationIOType = Field(
description="Output type for the transformation type"
)
| TransformationCategory |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/text/langchain.py | {
"start": 482,
"end": 1495
} | class ____(TextSplitter):
"""
Basic wrapper around langchain's text splitter.
TODO: Figure out how to make this metadata aware.
"""
_lc_splitter: "LC_TextSplitter" = PrivateAttr()
def __init__(
self,
lc_splitter: "LC_TextSplitter",
callback_manager: Optional[CallbackManager] = None,
include_metadata: bool = True,
include_prev_next_rel: bool = True,
id_func: Optional[Callable[[int, Document], str]] = None,
):
"""Initialize with parameters."""
id_func = id_func or default_id_func
super().__init__(
callback_manager=callback_manager or CallbackManager(),
include_metadata=include_metadata,
include_prev_next_rel=include_prev_next_rel,
id_func=id_func,
)
self._lc_splitter = lc_splitter
def split_text(self, text: str) -> List[str]:
"""Split text into sentences."""
return self._lc_splitter.split_text(text)
| LangchainNodeParser |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/cascade_delete_relationships/tutorial002.py | {
"start": 338,
"end": 3385
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(
default=None, foreign_key="team.id", ondelete="SET NULL"
)
team: Optional[Team] = Relationship(back_populates="heroes")
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
with Session(engine) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar")
hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team=team_z_force
)
hero_rusty_man = Hero(
name="Rusty-Man", secret_name="Tommy Sharp", age=48, team=team_preventers
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_deadpond)
session.refresh(hero_rusty_man)
session.refresh(hero_spider_boy)
print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)
hero_spider_boy.team = team_preventers
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_spider_boy)
print("Updated hero:", hero_spider_boy)
hero_black_lion = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_sure_e = Hero(name="Princess Sure-E", secret_name="Sure-E")
team_wakaland = Team(
name="Wakaland",
headquarters="Wakaland Capital City",
heroes=[hero_black_lion, hero_sure_e],
)
session.add(team_wakaland)
session.commit()
session.refresh(team_wakaland)
print("Team Wakaland:", team_wakaland)
def delete_team():
with Session(engine) as session:
statement = select(Team).where(Team.name == "Wakaland")
team = session.exec(statement).one()
session.delete(team)
session.commit()
print("Deleted team:", team)
def select_deleted_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.name == "Black Lion")
result = session.exec(statement)
hero = result.first()
print("Black Lion has no team:", hero)
statement = select(Hero).where(Hero.name == "Princess Sure-E")
result = session.exec(statement)
hero = result.first()
print("Princess Sure-E has no team:", hero)
def main():
create_db_and_tables()
create_heroes()
delete_team()
select_deleted_heroes()
if __name__ == "__main__":
main()
| Hero |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 22709,
"end": 25408
} | class ____(MaskedArraySetup):
def check(self, function, *args, method=None, **kwargs):
if method is None:
method = function.__name__
o = function(self.ma, *args, **kwargs)
x = getattr(self.ma, method)(*args, **kwargs)
assert_masked_equal(o, x)
def test_max(self):
self.check(np.max, method="max")
def test_min(self):
self.check(np.min, method="min")
def test_amax(self):
self.check(np.amax, method="max")
def test_amin(self):
self.check(np.amin, method="min")
def test_sum(self):
self.check(np.sum)
def test_cumsum(self):
self.check(np.cumsum)
def test_any(self):
self.check(np.any)
def test_all(self):
self.check(np.all)
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.sometrue is removed in NumPy 2.0")
@pytest.mark.filterwarnings("ignore:`sometrue` is deprecated as of NumPy 1.25.0")
def test_sometrue(self):
self.check(np.sometrue, method="any") # noqa: NPY003, NPY201
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.alltrue is removed in NumPy 2.0")
@pytest.mark.filterwarnings("ignore:`alltrue` is deprecated as of NumPy 1.25.0")
def test_alltrue(self):
self.check(np.alltrue, method="all") # noqa: NPY003, NPY201
def test_prod(self):
self.check(np.prod)
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.product is removed in NumPy 2.0")
@pytest.mark.filterwarnings("ignore:`product` is deprecated as of NumPy 1.25.0")
def test_product(self):
self.check(np.product, method="prod") # noqa: NPY003, NPY201
def test_cumprod(self):
self.check(np.cumprod)
@pytest.mark.skipif(
not NUMPY_LT_2_0, reason="np.cumproduct is removed in NumPy 2.0"
)
@pytest.mark.filterwarnings("ignore:`cumproduct` is deprecated as of NumPy 1.25.0")
def test_cumproduct(self):
self.check(np.cumproduct, method="cumprod") # noqa: NPY003, NPY201
def test_round(self):
self.check(np.round, method="round")
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.round_ is removed in NumPy 2.0")
@pytest.mark.filterwarnings("ignore:`round_` is deprecated as of NumPy 1.25.0")
def test_round_(self):
self.check(np.round_, method="round") # noqa: NPY003, NPY201
def test_around(self):
self.check(np.around, method="round")
def test_clip(self):
self.check(np.clip, 2.0, 4.0)
self.check(np.clip, self.mb, self.mc)
def test_mean(self):
self.check(np.mean)
def test_std(self):
self.check(np.std)
def test_var(self):
self.check(np.var)
| TestMethodLikes |
python | django__django | tests/migrations/test_migrations_manual_porting/0002_second.py | {
"start": 81,
"end": 280
} | class ____(migrations.Migration):
dependencies = [
("migrations", "0001_initial"),
]
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop),
]
| Migration |
python | encode__django-rest-framework | tests/test_metadata.py | {
"start": 12114,
"end": 14951
} | class ____(TestCase):
def test_read_only_primary_key_related_field(self):
"""
On generic views OPTIONS should return an 'actions' key with metadata
on the fields that may be supplied to PUT and POST requests. It should
not fail when a read_only PrimaryKeyRelatedField is present
"""
class Parent(models.Model):
integer_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)])
children = models.ManyToManyField('Child')
name = models.CharField(max_length=100, blank=True, null=True)
class Child(models.Model):
name = models.CharField(max_length=100)
class ExampleSerializer(serializers.ModelSerializer):
children = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
class Meta:
model = Parent
fields = '__all__'
class ExampleView(views.APIView):
"""Example view."""
def post(self, request):
pass
def get_serializer(self):
return ExampleSerializer()
view = ExampleView.as_view()
response = view(request=request)
expected = {
'name': 'Example',
'description': 'Example view.',
'renders': [
'application/json',
'text/html'
],
'parses': [
'application/json',
'application/x-www-form-urlencoded',
'multipart/form-data'
],
'actions': {
'POST': {
'id': {
'type': 'integer',
'required': False,
'read_only': True,
'label': 'ID'
},
'children': {
'type': 'field',
'required': False,
'read_only': True,
'label': 'Children'
},
'integer_field': {
'type': 'integer',
'required': True,
'read_only': False,
'label': 'Integer field',
'min_value': 1,
'max_value': 1000
},
'name': {
'type': 'string',
'required': False,
'read_only': False,
'label': 'Name',
'max_length': 100
}
}
}
}
assert response.status_code == status.HTTP_200_OK
assert response.data == expected
| TestModelSerializerMetadata |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_theme03.py | {
"start": 350,
"end": 2146
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_theme03.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line", "subtype": "stacked"})
chart.axis_ids = [68411392, 68414848]
# Add some test data for the chart(s).
for row_num in range(8):
for col_num in range(6):
worksheet.write_number(row_num, col_num, 1)
chart.add_series(
{
"values": ["Sheet1", 0, 0, 7, 0],
"line": {"color": Color((1, 0))},
}
)
chart.add_series(
{
"values": ["Sheet1", 0, 1, 7, 1],
"line": {"color": Color((1, 1))},
}
)
chart.add_series(
{
"values": ["Sheet1", 0, 2, 7, 2],
"line": {"color": Color((1, 2))},
}
)
chart.add_series(
{
"values": ["Sheet1", 0, 3, 7, 3],
"line": {"color": Color((1, 3))},
}
)
chart.add_series(
{
"values": ["Sheet1", 0, 4, 7, 4],
"line": {"color": Color((1, 4))},
}
)
chart.add_series(
{
"values": ["Sheet1", 0, 5, 7, 5],
"line": {"color": Color((1, 5))},
}
)
worksheet.insert_chart(8, 7, chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | Lightning-AI__lightning | examples/pytorch/basics/backbone_image_classifier.py | {
"start": 1262,
"end": 1751
} | class ____(torch.nn.Module):
"""
>>> Backbone() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Backbone(
(l1): Linear(...)
(l2): Linear(...)
)
"""
def __init__(self, hidden_dim=128):
super().__init__()
self.l1 = torch.nn.Linear(28 * 28, hidden_dim)
self.l2 = torch.nn.Linear(hidden_dim, 10)
def forward(self, x):
x = x.view(x.size(0), -1)
x = torch.relu(self.l1(x))
return torch.relu(self.l2(x))
| Backbone |
python | huggingface__transformers | tests/models/speech_to_text/test_modeling_speech_to_text.py | {
"start": 26274,
"end": 28611
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
model_name = "facebook/s2t-small-librispeech-asr"
cls.model = Speech2TextForConditionalGeneration.from_pretrained(model_name, use_safetensors=False)
cls.processor = Speech2TextProcessor.from_pretrained(model_name)
# loads 4 samples
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
speech_samples = ds.sort("id").select(range(4))[:4]["audio"]
cls.dataset = [x["array"] for x in speech_samples]
def test_generation_librispeech(self):
input_speech = [self.dataset[0]]
input_features = self.processor(input_speech, return_tensors="pt").input_features.to(torch_device)
generated_ids = self.model.generate(input_features)
generated_transcript = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
EXPECTED_TRANSCRIPTIONS = [
"mister quilter is the apostle of the middle classes and we are glad to welcome his gospel"
]
self.assertListEqual(generated_transcript, EXPECTED_TRANSCRIPTIONS)
def test_generation_librispeech_batched(self):
input_speech = self.dataset
inputs = self.processor(input_speech, return_tensors="pt", padding=True)
input_features = inputs.input_features.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
generated_ids = self.model.generate(input_features, attention_mask=attention_mask)
generated_transcripts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
EXPECTED_TRANSCRIPTIONS = [
"mister quilter is the apostle of the middle classes and we are glad to welcome his gospel",
"nor is mister cultar's manner less interesting than his matter",
"he tells us that at this festive season of the year with christmas and roast beef looming before us"
" similes drawn from eating and its results occur most readily to the mind",
"he has grave doubts whether sir frederick leyton's work is really greek after all and can discover in it"
" but little of rocky ithaca",
]
self.assertListEqual(generated_transcripts, EXPECTED_TRANSCRIPTIONS)
| Speech2TextModelIntegrationTests |
python | ray-project__ray | python/ray/dashboard/modules/tests/test_head.py | {
"start": 531,
"end": 3243
} | class ____(dashboard_utils.DashboardHeadModule):
def __init__(self, config: dashboard_utils.DashboardHeadModuleConfig):
super().__init__(config)
@staticmethod
def is_minimal_module():
return False
@routes.get("/test/route_get")
async def route_get(self, req) -> aiohttp.web.Response:
pass
@routes.put("/test/route_put")
async def route_put(self, req) -> aiohttp.web.Response:
pass
@routes.delete("/test/route_delete")
async def route_delete(self, req) -> aiohttp.web.Response:
pass
@routes.view("/test/route_view")
async def route_view(self, req) -> aiohttp.web.Response:
pass
@routes.get("/test/http_get")
async def get_url(self, req) -> aiohttp.web.Response:
url = req.query.get("url")
result = await test_utils.http_get(self.http_session, url)
return aiohttp.web.json_response(result)
@routes.get("/test/aiohttp_cache/{sub_path}")
@dashboard_optional_utils.aiohttp_cache(ttl_seconds=1)
async def test_aiohttp_cache(self, req) -> aiohttp.web.Response:
value = req.query["value"]
return dashboard_optional_utils.rest_response(
status_code=dashboard_utils.HTTPStatusCode.OK,
message="OK",
value=value,
timestamp=time.time(),
)
@routes.get("/test/aiohttp_cache_lru/{sub_path}")
@dashboard_optional_utils.aiohttp_cache(ttl_seconds=60, maxsize=5)
async def test_aiohttp_cache_lru(self, req) -> aiohttp.web.Response:
value = req.query.get("value")
return dashboard_optional_utils.rest_response(
status_code=dashboard_utils.HTTPStatusCode.OK,
message="OK",
value=value,
timestamp=time.time(),
)
@routes.get("/test/file")
async def test_file(self, req) -> aiohttp.web.FileResponse:
file_path = req.query.get("path")
logger.info("test file: %s", file_path)
return aiohttp.web.FileResponse(file_path)
@routes.get("/test/block_event_loop")
async def block_event_loop(self, req) -> aiohttp.web.Response:
"""
Simulates a blocked event loop. To be used for testing purposes only. Creates a
task that blocks the event loop for a specified number of seconds.
"""
seconds = float(req.query.get("seconds", 0.0))
time.sleep(seconds)
return dashboard_optional_utils.rest_response(
status_code=dashboard_utils.HTTPStatusCode.OK,
message=f"Blocked event loop for {seconds} seconds",
timestamp=time.time(),
)
async def run(self):
pass
if __name__ == "__main__":
pass
| TestHead |
python | sphinx-doc__sphinx | sphinx/errors.py | {
"start": 2567,
"end": 2882
} | class ____(SphinxError):
"""Sphinx parallel build error."""
category = 'Sphinx parallel build error'
def __init__(self, message: str, traceback: str) -> None:
self.message = message
self.traceback = traceback
def __str__(self) -> str:
return self.message
| SphinxParallelError |
python | kubernetes-client__python | kubernetes/client/api/internal_apiserver_api.py | {
"start": 543,
"end": 5208
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_api_group(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_group(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1APIGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_api_group_with_http_info(**kwargs) # noqa: E501
def get_api_group_with_http_info(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1APIGroup, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_group" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/internal.apiserver.k8s.io/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIGroup', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
| InternalApiserverApi |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_types.py | {
"start": 17136,
"end": 26913
} | class ____(fixtures.TestBase, AssertsExecutionResults):
__dialect__ = mysql.dialect()
__only_on__ = "mysql", "mariadb"
__backend__ = True
# fixed in mysql-connector as of 2.0.1,
# see https://bugs.mysql.com/bug.php?id=73266
@testing.requires.literal_float_coercion
def test_precision_float_roundtrip(self, metadata, connection):
t = Table(
"t",
metadata,
Column(
"scale_value",
mysql.DOUBLE(precision=15, scale=12, asdecimal=True),
),
Column(
"unscale_value",
mysql.DOUBLE(decimal_return_scale=12, asdecimal=True),
),
)
t.create(connection)
connection.execute(
t.insert(),
dict(
scale_value=45.768392065789,
unscale_value=45.768392065789,
),
)
result = connection.scalar(select(t.c.scale_value))
eq_(result, decimal.Decimal("45.768392065789"))
result = connection.scalar(select(t.c.unscale_value))
eq_(result, decimal.Decimal("45.768392065789"))
@testing.only_if("mysql")
def test_charset_collate_table(self, metadata, connection):
t = Table(
"foo",
metadata,
Column("id", Integer),
Column("data", UnicodeText),
mysql_default_charset="utf8",
mysql_collate="utf8_bin",
)
t.create(connection)
t2 = Table("foo", MetaData(), autoload_with=connection)
assert t2.kwargs["mysql_collate"] in ("utf8_bin", "utf8mb3_bin")
assert t2.kwargs["mysql_default charset"] in ("utf8", "utf8mb3")
# test [ticket:2906]
# in order to test the condition here, need to use
# MySQLdb 1.2.3 and also need to pass either use_unicode=1
# or charset=utf8 to the URL.
connection.execute(t.insert(), dict(id=1, data="some text"))
assert isinstance(connection.scalar(select(t.c.data)), str)
@testing.metadata_fixture(ddl="class")
def bit_table(self, metadata):
bit_table = Table(
"mysql_bits",
metadata,
Column("b1", mysql.MSBit),
Column("b2", mysql.MSBit()),
Column("b3", mysql.MSBit(), nullable=False),
Column("b4", mysql.MSBit(1)),
Column("b5", mysql.MSBit(8)),
Column("b6", mysql.MSBit(32)),
Column("b7", mysql.MSBit(63)),
Column("b8", mysql.MSBit(64)),
)
return bit_table
i, j, k, l = 255, 2**32 - 1, 2**63 - 1, 2**64 - 1
@testing.combinations(
(([0] * 8), None),
([None, None, 0, None, None, None, None, None], None),
(([1] * 8), None),
([sql.text("b'1'")] * 8, [1] * 8),
([0, 0, 0, 0, i, i, i, i], None),
([0, 0, 0, 0, 0, j, j, j], None),
([0, 0, 0, 0, 0, 0, k, k], None),
([0, 0, 0, 0, 0, 0, 0, l], None, testing.fails_if("+asyncmy")),
argnames="store, expected",
)
def test_bit_50_roundtrip(self, connection, bit_table, store, expected):
reflected = Table("mysql_bits", MetaData(), autoload_with=connection)
expected = expected or store
connection.execute(reflected.insert().values(store))
row = connection.execute(reflected.select()).first()
eq_(list(row), expected)
@testing.combinations(
(([0] * 8), None),
([None, None, 0, None, None, None, None, None], None),
(([1] * 8), None),
([sql.text("b'1'")] * 8, [1] * 8),
([0, 0, 0, 0, i, i, i, i], None),
([0, 0, 0, 0, 0, j, j, j], None),
([0, 0, 0, 0, 0, 0, k, k], None),
([0, 0, 0, 0, 0, 0, 0, l], None, testing.fails_if("+asyncmy")),
argnames="store, expected",
)
def test_bit_50_roundtrip_reflected(
self, connection, bit_table, store, expected
):
bit_table = Table("mysql_bits", MetaData(), autoload_with=connection)
expected = expected or store
connection.execute(bit_table.insert().values(store))
row = connection.execute(bit_table.select()).first()
eq_(list(row), expected)
@testing.metadata_fixture(ddl="class")
def boolean_table(self, metadata):
bool_table = Table(
"mysql_bool",
metadata,
Column("b1", BOOLEAN),
Column("b2", Boolean),
Column("b3", mysql.MSTinyInteger(1)),
Column("b4", mysql.MSTinyInteger(1, unsigned=True)),
Column("b5", mysql.MSTinyInteger),
)
return bool_table
@testing.combinations(
([None, None, None, None, None], None),
([True, True, 1, 1, 1], None),
([False, False, 0, 0, 0], None),
([True, True, True, True, True], [True, True, 1, 1, 1]),
([False, False, 0, 0, 0], [False, False, 0, 0, 0]),
argnames="store, expected",
)
def test_boolean_roundtrip(
self, connection, boolean_table, store, expected
):
table = boolean_table
expected = expected or store
connection.execute(table.insert().values(store))
row = connection.execute(table.select()).first()
eq_(list(row), expected)
for i, val in enumerate(expected):
if isinstance(val, bool):
self.assert_(val is row[i])
@testing.combinations(
([None, None, None, None, None], None),
([True, True, 1, 1, 1], [True, True, True, True, 1]),
([False, False, 0, 0, 0], [False, False, False, False, 0]),
([True, True, True, True, True], [True, True, True, True, 1]),
([False, False, 0, 0, 0], [False, False, False, False, 0]),
argnames="store, expected",
)
def test_boolean_roundtrip_reflected(
self, connection, boolean_table, store, expected
):
table = Table("mysql_bool", MetaData(), autoload_with=connection)
eq_(colspec(table.c.b3), "b3 TINYINT(1)")
eq_regex(colspec(table.c.b4), r"b4 TINYINT(?:\(1\))? UNSIGNED")
table = Table(
"mysql_bool",
MetaData(),
Column("b1", BOOLEAN),
Column("b2", Boolean),
Column("b3", BOOLEAN),
Column("b4", BOOLEAN),
autoload_with=connection,
)
eq_(colspec(table.c.b3), "b3 BOOL")
eq_(colspec(table.c.b4), "b4 BOOL")
expected = expected or store
connection.execute(table.insert().values(store))
row = connection.execute(table.select()).first()
eq_(list(row), expected)
for i, val in enumerate(expected):
if isinstance(val, bool):
self.assert_(val is row[i])
class MyTime(TypeDecorator):
impl = TIMESTAMP
cache_ok = True
@testing.combinations(
(TIMESTAMP,),
(MyTime(),),
(String().with_variant(TIMESTAMP, "mysql"),),
argnames="type_",
)
@testing.requires.mysql_zero_date
def test_timestamp_nullable(self, metadata, connection, type_):
ts_table = Table(
"mysql_timestamp",
metadata,
Column("t1", type_),
Column("t2", type_, nullable=False),
mysql_engine="InnoDB",
)
metadata.create_all(connection)
# TIMESTAMP without NULL inserts current time when passed
# NULL. when not passed, generates 0000-00-00 quite
# annoyingly.
# the flag https://dev.mysql.com/doc/refman/5.6/en/\
# server-system-variables.html#sysvar_explicit_defaults_for_timestamp
# changes this for 5.6 if set.
# normalize dates for the amount of time the operation took
def normalize(dt):
if dt is None:
return None
elif now <= dt <= new_now:
return now
else:
return dt
now = connection.exec_driver_sql("select now()").scalar()
connection.execute(ts_table.insert(), {"t1": now, "t2": None})
connection.execute(ts_table.insert(), {"t1": None, "t2": None})
connection.execute(ts_table.insert(), {"t2": None})
new_now = connection.exec_driver_sql("select now()").scalar()
eq_(
[
tuple([normalize(dt) for dt in row])
for row in connection.execute(ts_table.select())
],
[(now, now), (None, now), (None, now)],
)
def test_time_roundtrip(self, metadata, connection):
t = Table("mysql_time", metadata, Column("t1", mysql.TIME()))
t.create(connection)
connection.execute(t.insert().values(t1=datetime.time(8, 37, 35)))
eq_(
connection.execute(select(t.c.t1)).scalar(),
datetime.time(8, 37, 35),
)
def test_year(self, metadata, connection):
"""Exercise YEAR."""
year_table = Table(
"mysql_year",
metadata,
Column("y1", mysql.MSYear),
Column("y2", mysql.MSYear),
Column("y3", mysql.MSYear),
Column("y5", mysql.MSYear(4)),
)
for col in year_table.c:
self.assert_(repr(col))
year_table.create(connection)
reflected = Table("mysql_year", MetaData(), autoload_with=connection)
for table in year_table, reflected:
connection.execute(
table.insert().values(["1950", "50", None, 1950])
)
row = connection.execute(table.select()).first()
eq_(list(row), [1950, 2050, None, 1950])
self.assert_(colspec(table.c.y1).startswith("y1 YEAR"))
eq_regex(colspec(table.c.y5), r"y5 YEAR(?:\(4\))?")
| TypeRoundTripTest |
python | django__django | tests/model_regress/models.py | {
"start": 932,
"end": 1065
} | class ____(models.Model):
id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=200)
| Department |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 26847,
"end": 27661
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_update_job_trigger(self, mock_hook):
mock_hook.return_value.update_job_trigger.return_value = JobTrigger()
operator = CloudDLPUpdateJobTriggerOperator(job_trigger_id=TRIGGER_ID, task_id="id")
operator.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_hook.return_value.update_job_trigger.assert_called_once_with(
job_trigger_id=TRIGGER_ID,
project_id=None,
job_trigger=None,
update_mask=None,
retry=DEFAULT,
timeout=None,
metadata=(),
)
| TestCloudDLPUpdateJobTriggerOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol37.py | {
"start": 129,
"end": 248
} | class ____(type):
def __iter__(cls) -> Iterator[str]:
yield "a"
yield "b"
yield "c"
| StyleMeta |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 11409,
"end": 11478
} | class ____(_NumcodecsChecksumCodec, codec_name="crc32"):
pass
| CRC32 |
python | pytest-dev__pytest | src/_pytest/mark/structures.py | {
"start": 2288,
"end": 8239
} | class ____(NamedTuple):
"""A set of values for a set of parameters along with associated marks and
an optional ID for the set.
Examples::
pytest.param(1, 2, 3)
# ParameterSet(values=(1, 2, 3), marks=(), id=None)
pytest.param("hello", id="greeting")
# ParameterSet(values=("hello",), marks=(), id="greeting")
# Parameter set with marks
pytest.param(42, marks=pytest.mark.xfail)
# ParameterSet(values=(42,), marks=(MarkDecorator(...),), id=None)
# From parametrize mark (parameter names + list of parameter sets)
pytest.mark.parametrize(
("a", "b", "expected"),
[
(1, 2, 3),
pytest.param(40, 2, 42, id="everything"),
],
)
# ParameterSet(values=(1, 2, 3), marks=(), id=None)
# ParameterSet(values=(40, 2, 42), marks=(), id="everything")
"""
values: Sequence[object | NotSetType]
marks: Collection[MarkDecorator | Mark]
id: str | _HiddenParam | None
@classmethod
def param(
cls,
*values: object,
marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
id: str | _HiddenParam | None = None,
) -> ParameterSet:
if isinstance(marks, MarkDecorator):
marks = (marks,)
else:
assert isinstance(marks, collections.abc.Collection)
if any(i.name == "usefixtures" for i in marks):
raise ValueError(
"pytest.param cannot add pytest.mark.usefixtures; see "
"https://docs.pytest.org/en/stable/reference/reference.html#pytest-param"
)
if id is not None:
if not isinstance(id, str) and id is not HIDDEN_PARAM:
raise TypeError(
"Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, "
f"got {type(id)}: {id!r}",
)
return cls(values, marks, id)
@classmethod
def extract_from(
cls,
parameterset: ParameterSet | Sequence[object] | object,
force_tuple: bool = False,
) -> ParameterSet:
"""Extract from an object or objects.
:param parameterset:
A legacy style parameterset that may or may not be a tuple,
and may or may not be wrapped into a mess of mark objects.
:param force_tuple:
Enforce tuple wrapping so single argument tuple values
don't get decomposed and break tests.
"""
if isinstance(parameterset, cls):
return parameterset
if force_tuple:
return cls.param(parameterset)
else:
# TODO: Refactor to fix this type-ignore. Currently the following
# passes type-checking but crashes:
#
# @pytest.mark.parametrize(('x', 'y'), [1, 2])
# def test_foo(x, y): pass
return cls(parameterset, marks=[], id=None) # type: ignore[arg-type]
@staticmethod
def _parse_parametrize_args(
argnames: str | Sequence[str],
argvalues: Iterable[ParameterSet | Sequence[object] | object],
*args,
**kwargs,
) -> tuple[Sequence[str], bool]:
if isinstance(argnames, str):
argnames = [x.strip() for x in argnames.split(",") if x.strip()]
force_tuple = len(argnames) == 1
else:
force_tuple = False
return argnames, force_tuple
@staticmethod
def _parse_parametrize_parameters(
argvalues: Iterable[ParameterSet | Sequence[object] | object],
force_tuple: bool,
) -> list[ParameterSet]:
return [
ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues
]
@classmethod
def _for_parametrize(
cls,
argnames: str | Sequence[str],
argvalues: Iterable[ParameterSet | Sequence[object] | object],
func,
config: Config,
nodeid: str,
) -> tuple[Sequence[str], list[ParameterSet]]:
if not isinstance(argvalues, Collection):
warnings.warn(
PARAMETRIZE_NON_COLLECTION_ITERABLE.format(
nodeid=nodeid,
type_name=type(argvalues).__name__,
),
stacklevel=3,
)
argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
del argvalues
if parameters:
# Check all parameter sets have the correct number of values.
for param in parameters:
if len(param.values) != len(argnames):
msg = (
'{nodeid}: in "parametrize" the number of names ({names_len}):\n'
" {names}\n"
"must be equal to the number of values ({values_len}):\n"
" {values}"
)
fail(
msg.format(
nodeid=nodeid,
values=param.values,
names=argnames,
names_len=len(argnames),
values_len=len(param.values),
),
pytrace=False,
)
else:
# Empty parameter set (likely computed at runtime): create a single
# parameter set with NOTSET values, with the "empty parameter set" mark applied to it.
mark = get_empty_parameterset_mark(config, argnames, func)
parameters.append(
ParameterSet(
values=(NOTSET,) * len(argnames), marks=[mark], id="NOTSET"
)
)
return argnames, parameters
@final
@dataclasses.dataclass(frozen=True)
| ParameterSet |
python | giampaolo__psutil | tests/test_unicode.py | {
"start": 3887,
"end": 4569
} | class ____(PsutilTestCase):
funky_suffix = None
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.skip_tests = False
cls.funky_name = None
if cls.funky_suffix is not None:
if not try_unicode(cls.funky_suffix):
cls.skip_tests = True
else:
cls.funky_name = get_testfn(suffix=cls.funky_suffix)
create_py_exe(cls.funky_name)
def setUp(self):
super().setUp()
if self.skip_tests:
return pytest.skip("can't handle unicode str")
@pytest.mark.xdist_group(name="serial")
@pytest.mark.skipif(ASCII_FS, reason="ASCII fs")
| BaseUnicodeTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 715266,
"end": 725956
} | class ____(sgqlc.types.Type, Node, GitObject, Subscribable, UniformResourceLocatable):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"additions",
"associated_pull_requests",
"author",
"authored_by_committer",
"authored_date",
"authors",
"blame",
"changed_files",
"changed_files_if_available",
"check_suites",
"comments",
"committed_date",
"committed_via_web",
"committer",
"deletions",
"deployments",
"file",
"history",
"message",
"message_body",
"message_body_html",
"message_headline",
"message_headline_html",
"on_behalf_of",
"parents",
"pushed_date",
"signature",
"status",
"status_check_rollup",
"submodules",
"tarball_url",
"tree",
"tree_resource_path",
"tree_url",
"zipball_url",
)
additions = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="additions")
associated_pull_requests = sgqlc.types.Field(
PullRequestConnection,
graphql_name="associatedPullRequests",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(
PullRequestOrder,
graphql_name="orderBy",
default={"field": "CREATED_AT", "direction": "ASC"},
),
),
)
),
)
author = sgqlc.types.Field(GitActor, graphql_name="author")
authored_by_committer = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="authoredByCommitter"
)
authored_date = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="authoredDate"
)
authors = sgqlc.types.Field(
sgqlc.types.non_null(GitActorConnection),
graphql_name="authors",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
blame = sgqlc.types.Field(
sgqlc.types.non_null(Blame),
graphql_name="blame",
args=sgqlc.types.ArgDict(
(
(
"path",
sgqlc.types.Arg(
sgqlc.types.non_null(String), graphql_name="path", default=None
),
),
)
),
)
changed_files = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="changedFiles"
)
changed_files_if_available = sgqlc.types.Field(
Int, graphql_name="changedFilesIfAvailable"
)
check_suites = sgqlc.types.Field(
CheckSuiteConnection,
graphql_name="checkSuites",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"filter_by",
sgqlc.types.Arg(
CheckSuiteFilter, graphql_name="filterBy", default=None
),
),
)
),
)
comments = sgqlc.types.Field(
sgqlc.types.non_null(CommitCommentConnection),
graphql_name="comments",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
committed_date = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="committedDate"
)
committed_via_web = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="committedViaWeb"
)
committer = sgqlc.types.Field(GitActor, graphql_name="committer")
deletions = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="deletions")
deployments = sgqlc.types.Field(
DeploymentConnection,
graphql_name="deployments",
args=sgqlc.types.ArgDict(
(
(
"environments",
sgqlc.types.Arg(
sgqlc.types.list_of(sgqlc.types.non_null(String)),
graphql_name="environments",
default=None,
),
),
(
"order_by",
sgqlc.types.Arg(
DeploymentOrder,
graphql_name="orderBy",
default={"field": "CREATED_AT", "direction": "ASC"},
),
),
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
file = sgqlc.types.Field(
TreeEntry,
graphql_name="file",
args=sgqlc.types.ArgDict(
(
(
"path",
sgqlc.types.Arg(
sgqlc.types.non_null(String), graphql_name="path", default=None
),
),
)
),
)
history = sgqlc.types.Field(
sgqlc.types.non_null(CommitHistoryConnection),
graphql_name="history",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
("path", sgqlc.types.Arg(String, graphql_name="path", default=None)),
(
"author",
sgqlc.types.Arg(CommitAuthor, graphql_name="author", default=None),
),
(
"since",
sgqlc.types.Arg(GitTimestamp, graphql_name="since", default=None),
),
(
"until",
sgqlc.types.Arg(GitTimestamp, graphql_name="until", default=None),
),
)
),
)
message = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="message")
message_body = sgqlc.types.Field(
sgqlc.types.non_null(String), graphql_name="messageBody"
)
message_body_html = sgqlc.types.Field(
sgqlc.types.non_null(HTML), graphql_name="messageBodyHTML"
)
message_headline = sgqlc.types.Field(
sgqlc.types.non_null(String), graphql_name="messageHeadline"
)
message_headline_html = sgqlc.types.Field(
sgqlc.types.non_null(HTML), graphql_name="messageHeadlineHTML"
)
on_behalf_of = sgqlc.types.Field("Organization", graphql_name="onBehalfOf")
parents = sgqlc.types.Field(
sgqlc.types.non_null(CommitConnection),
graphql_name="parents",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
pushed_date = sgqlc.types.Field(DateTime, graphql_name="pushedDate")
signature = sgqlc.types.Field(GitSignature, graphql_name="signature")
status = sgqlc.types.Field("Status", graphql_name="status")
status_check_rollup = sgqlc.types.Field(
"StatusCheckRollup", graphql_name="statusCheckRollup"
)
submodules = sgqlc.types.Field(
sgqlc.types.non_null(SubmoduleConnection),
graphql_name="submodules",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
tarball_url = sgqlc.types.Field(
sgqlc.types.non_null(URI), graphql_name="tarballUrl"
)
tree = sgqlc.types.Field(sgqlc.types.non_null("Tree"), graphql_name="tree")
tree_resource_path = sgqlc.types.Field(
sgqlc.types.non_null(URI), graphql_name="treeResourcePath"
)
tree_url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="treeUrl")
zipball_url = sgqlc.types.Field(
sgqlc.types.non_null(URI), graphql_name="zipballUrl"
)
| Commit |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 148045,
"end": 148908
} | class ____(Response):
"""
Response of tasks.create endpoint.
:param id: ID of the task
:type id: str
"""
_service = "tasks"
_action = "create"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {"id": {"description": "ID of the task", "type": ["string", "null"]}},
"type": "object",
}
def __init__(self, id: Optional[str] = None, **kwargs: Any) -> None:
super(CreateResponse, self).__init__(**kwargs)
self.id = id
@schema_property("id")
def id(self) -> Optional[str]:
return self._property_id
@id.setter
def id(self, value: Optional[str]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
| CreateResponse |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 11272,
"end": 13972
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MBartConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = MBartAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
dropout=config.attention_dropout,
config=config,
)
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
output_attentions: bool = False,
) -> torch.Tensor:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
"""
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states, attn_weights = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
if hidden_states.dtype == torch.float16:
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
return hidden_states, attn_weights
| MBartEncoderLayer |
python | numba__numba | numba/core/target_extension.py | {
"start": 3819,
"end": 3880
} | class ____(Generic):
"""Mark the target as CPU.
"""
| CPU |
python | doocs__leetcode | solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/Solution.py | {
"start": 0,
"end": 587
} | class ____:
def getProbability(self, balls: List[int]) -> float:
@cache
def dfs(i: int, j: int, diff: int) -> float:
if i >= k:
return 1 if j == 0 and diff == 0 else 0
if j < 0:
return 0
ans = 0
for x in range(balls[i] + 1):
y = 1 if x == balls[i] else (-1 if x == 0 else 0)
ans += dfs(i + 1, j - x, diff + y) * comb(balls[i], x)
return ans
n = sum(balls) >> 1
k = len(balls)
return dfs(0, n, 0) / comb(n << 1, n)
| Solution |
python | huggingface__transformers | tests/models/tapas/test_modeling_tapas.py | {
"start": 36118,
"end": 43693
} | class ____(unittest.TestCase):
def _prepare_tables(self):
"""Prepares two tables, both with three distinct rows.
The first table has two columns:
1.0, 2.0 | 3.0
2.0, 0.0 | 1.0
1.0, 3.0 | 4.0
The second table has three columns:
1.0 | 2.0 | 3.0
2.0 | 0.0 | 1.0
1.0 | 3.0 | 4.0
Returns:
SegmentedTensors with the tables.
"""
values = torch.tensor(
[
[[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]],
[[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]],
]
)
row_index = IndexMap(
indices=torch.tensor(
[
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
[[0, 0, 0], [1, 1, 1], [2, 2, 2]],
]
),
num_segments=3,
batch_dims=1,
)
col_index = IndexMap(
indices=torch.tensor(
[
[[0, 0, 1], [0, 0, 1], [0, 0, 1]],
[[0, 1, 2], [0, 1, 2], [0, 1, 2]],
]
),
num_segments=3,
batch_dims=1,
)
return values, row_index, col_index
def test_product_index(self):
_, row_index, col_index = self._prepare_tables()
cell_index = ProductIndexMap(row_index, col_index)
row_index_proj = cell_index.project_outer(cell_index)
col_index_proj = cell_index.project_inner(cell_index)
ind = cell_index.indices
self.assertEqual(cell_index.num_segments, 9)
# Projections should give back the original indices.
np.testing.assert_array_equal(row_index.indices.numpy(), row_index_proj.indices.numpy())
self.assertEqual(row_index.num_segments, row_index_proj.num_segments)
self.assertEqual(row_index.batch_dims, row_index_proj.batch_dims)
np.testing.assert_array_equal(col_index.indices.numpy(), col_index_proj.indices.numpy())
self.assertEqual(col_index.batch_dims, col_index_proj.batch_dims)
# The first and second "column" are identified in the first table.
for i in range(3):
self.assertEqual(ind[0, i, 0], ind[0, i, 1])
self.assertNotEqual(ind[0, i, 0], ind[0, i, 2])
# All rows are distinct in the first table.
for i, i_2 in zip(range(3), range(3)):
for j, j_2 in zip(range(3), range(3)):
if i != i_2 and j != j_2:
self.assertNotEqual(ind[0, i, j], ind[0, i_2, j_2])
# All cells are distinct in the second table.
for i, i_2 in zip(range(3), range(3)):
for j, j_2 in zip(range(3), range(3)):
if i != i_2 or j != j_2:
self.assertNotEqual(ind[1, i, j], ind[1, i_2, j_2])
def test_flatten(self):
_, row_index, col_index = self._prepare_tables()
row_index_flat = flatten(row_index)
col_index_flat = flatten(col_index)
shape = [3, 4, 5]
batched_index = IndexMap(indices=torch.zeros(shape).type(torch.LongTensor), num_segments=1, batch_dims=3)
batched_index_flat = flatten(batched_index)
np.testing.assert_array_equal(
row_index_flat.indices.numpy(), [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5]
)
np.testing.assert_array_equal(
col_index_flat.indices.numpy(), [0, 0, 1, 0, 0, 1, 0, 0, 1, 3, 4, 5, 3, 4, 5, 3, 4, 5]
)
self.assertEqual(batched_index_flat.num_segments.numpy(), np.prod(shape))
np.testing.assert_array_equal(batched_index_flat.indices.numpy(), range(np.prod(shape)))
def test_range_index_map(self):
batch_shape = [3, 4]
num_segments = 5
index = range_index_map(batch_shape, num_segments)
self.assertEqual(num_segments, index.num_segments)
self.assertEqual(2, index.batch_dims)
indices = index.indices
np.testing.assert_array_equal(list(indices.size()), [3, 4, 5])
for i in range(batch_shape[0]):
for j in range(batch_shape[1]):
np.testing.assert_array_equal(indices[i, j, :].numpy(), range(num_segments))
def test_reduce_sum(self):
values, row_index, col_index = self._prepare_tables()
cell_index = ProductIndexMap(row_index, col_index)
row_sum, _ = reduce_sum(values, row_index)
col_sum, _ = reduce_sum(values, col_index)
cell_sum, _ = reduce_sum(values, cell_index)
np.testing.assert_allclose(row_sum.numpy(), [[6.0, 3.0, 8.0], [6.0, 3.0, 8.0]])
np.testing.assert_allclose(col_sum.numpy(), [[9.0, 8.0, 0.0], [4.0, 5.0, 8.0]])
np.testing.assert_allclose(
cell_sum.numpy(),
[[3.0, 3.0, 0.0, 2.0, 1.0, 0.0, 4.0, 4.0, 0.0], [1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0]],
)
def test_reduce_mean(self):
values, row_index, col_index = self._prepare_tables()
cell_index = ProductIndexMap(row_index, col_index)
row_mean, _ = reduce_mean(values, row_index)
col_mean, _ = reduce_mean(values, col_index)
cell_mean, _ = reduce_mean(values, cell_index)
np.testing.assert_allclose(
row_mean.numpy(), [[6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0], [6.0 / 3.0, 3.0 / 3.0, 8.0 / 3.0]]
)
np.testing.assert_allclose(col_mean.numpy(), [[9.0 / 6.0, 8.0 / 3.0, 0.0], [4.0 / 3.0, 5.0 / 3.0, 8.0 / 3.0]])
np.testing.assert_allclose(
cell_mean.numpy(),
[
[3.0 / 2.0, 3.0, 0.0, 2.0 / 2.0, 1.0, 0.0, 4.0 / 2.0, 4.0, 0.0],
[1.0, 2.0, 3.0, 2.0, 0.0, 1.0, 1.0, 3.0, 4.0],
],
)
def test_reduce_max(self):
values = torch.as_tensor([2.0, 1.0, 0.0, 3.0])
index = IndexMap(indices=torch.as_tensor([0, 1, 0, 1]), num_segments=2)
maximum, _ = reduce_max(values, index)
np.testing.assert_array_equal(maximum.numpy(), [2, 3])
def test_reduce_sum_vectorized(self):
values = torch.as_tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0]])
index = IndexMap(indices=torch.as_tensor([[0, 0, 1]]), num_segments=2, batch_dims=0)
sums, new_index = reduce_sum(values, index)
np.testing.assert_allclose(sums.numpy(), [3.0, 3.0])
np.testing.assert_array_equal(new_index.indices.numpy(), [0, 1])
np.testing.assert_array_equal(new_index.num_segments.numpy(), 2)
np.testing.assert_array_equal(new_index.batch_dims, 0)
def test_gather(self):
values, row_index, col_index = self._prepare_tables()
cell_index = ProductIndexMap(row_index, col_index)
# Compute sums and then gather. The result should have the same shape as
# the original table and each element should contain the sum the values in
# its cell.
sums, _ = reduce_sum(values, cell_index)
cell_sum = gather(sums, cell_index)
assert cell_sum.size() == values.size()
np.testing.assert_allclose(
cell_sum.numpy(),
[[[3.0, 3.0, 3.0], [2.0, 2.0, 1.0], [4.0, 4.0, 4.0]], [[1.0, 2.0, 3.0], [2.0, 0.0, 1.0], [1.0, 3.0, 4.0]]],
)
def test_gather_vectorized(self):
values = torch.as_tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
index = IndexMap(indices=torch.as_tensor([[0, 1], [1, 0]]), num_segments=2, batch_dims=1)
result = gather(values, index)
np.testing.assert_array_equal(result.numpy(), [[[1, 2], [3, 4]], [[7, 8], [5, 6]]])
| TapasUtilitiesTest |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/check/decorator.py | {
"start": 326,
"end": 3619
} | class ____(ABC):
"""Output of the @checked decorator, this class holds a reference to the decorated function
and upon first invocation compiles a wrapping function that performs run time type checks on
annotated inputs.
This class is not directly instantiated, but instead dynamic subclasses are created for each
callsite allowing the __call__ method to be replaced[1] with the compiled function to achieve
a single stack frame of over head for this decorator in best cases scenarios.
[1] __call__ can not be replaced on instances, only classes.
"""
def __init__(self, fn):
self._target_fn = fn
self._eval_ctx = EvalContext.capture_from_frame(2)
def __get__(self, instance, _=None):
"""Allow the decorated function to be bound to instances to support class methods."""
if instance:
return MethodType(self, instance)
return self
def __call__(self, *args, **kwargs):
signature = inspect.signature(self._target_fn)
lines = []
param_names = []
defaults = {}
for name, param in signature.parameters.items():
if param.annotation != param.empty:
param_str = build_check_call_str(
ttype=param.annotation,
name=name,
eval_ctx=self._eval_ctx,
)
else:
param_str = param.name
if param.kind in (param.KEYWORD_ONLY, param.POSITIONAL_OR_KEYWORD):
param_str = f"{param.name}={param_str}"
param_names.append(param.name)
if param.default != param.empty:
defaults[param.name] = param.default
lines.append(param_str)
lazy_imports_str = "\n ".join(
f"from {module} import {t}" for t, module in self._eval_ctx.lazy_imports.items()
)
args_str, set_calls_str = build_args_and_assignment_strs(
param_names,
defaults,
kw_only=False,
)
param_block = ",\n ".join(lines)
checked_fn_name = f"__checked_{self._target_fn.__name__}"
fn_str = f"""
def {checked_fn_name}(__checked_wrapper{args_str}):
{lazy_imports_str}
{set_calls_str}
return __checked_wrapper._target_fn(
{param_block}
)
"""
self._eval_ctx.local_ns[INJECTED_DEFAULT_VALS_LOCAL_VAR] = defaults
self._eval_ctx.local_ns[INJECTED_CHECK_VAR] = check
call = self._eval_ctx.compile_fn(
fn_str,
fn_name=checked_fn_name,
)
self.__class__.__call__ = call
return call(self, *args, **kwargs)
def checked(fn):
"""Decorator for adding runtime type checking based on type annotations."""
# if nothing can be checked, return the original fn
annotations = getattr(fn, "__annotations__", None)
if not annotations or (len(annotations) == 1 and set(annotations.keys()) == {"return"}):
return fn
# make a dynamic subclass to be able to hot swap __call__ post compilation
class _DynamicCheckedFnWrapper(CheckedFnWrapper): ...
checked_fn = _DynamicCheckedFnWrapper(fn)
return update_wrapper(
wrapper=checked_fn,
wrapped=fn,
)
| CheckedFnWrapper |
python | getsentry__sentry | src/sentry/codecov/enums.py | {
"start": 284,
"end": 464
} | class ____(Enum):
FLAKY_TESTS = "FLAKY_TESTS"
FAILED_TESTS = "FAILED_TESTS"
SLOWEST_TESTS = "SLOWEST_TESTS"
SKIPPED_TESTS = "SKIPPED_TESTS"
| TestResultsFilterParameter |
python | allegroai__clearml | clearml/backend_api/services/v2_23/auth.py | {
"start": 8914,
"end": 10544
} | class ____(Request):
"""
Updates the label of the existing credentials for the authenticated user.
:param access_key: Existing credentials key
:type access_key: str
:param label: New credentials label
:type label: str
"""
_service = "auth"
_action = "edit_credentials"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"access_key": {"description": "Existing credentials key", "type": "string"},
"label": {"description": "New credentials label", "type": "string"},
},
"required": ["access_key"],
"type": "object",
}
def __init__(self, access_key: str, label: Optional[str] = None, **kwargs: Any) -> None:
super(EditCredentialsRequest, self).__init__(**kwargs)
self.access_key = access_key
self.label = label
@schema_property("access_key")
def access_key(self) -> str:
return self._property_access_key
@access_key.setter
def access_key(self, value: str) -> None:
if value is None:
self._property_access_key = None
return
self.assert_isinstance(value, "access_key", six.string_types)
self._property_access_key = value
@schema_property("label")
def label(self) -> Optional[str]:
return self._property_label
@label.setter
def label(self, value: Optional[str]) -> None:
if value is None:
self._property_label = None
return
self.assert_isinstance(value, "label", six.string_types)
self._property_label = value
| EditCredentialsRequest |
python | plotly__plotly.py | plotly/graph_objs/isosurface/caps/_z.py | {
"start": 233,
"end": 4043
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.caps"
_path_str = "isosurface.caps.z"
_valid_props = {"fill", "show"}
@property
def fill(self):
"""
Sets the fill ratio of the `caps`. The default fill value of
the `caps` is 1 meaning that they are entirely shaded. On the
other hand Applying a `fill` ratio less than one would allow
the creation of openings parallel to the edges.
The 'fill' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["fill"]
@fill.setter
def fill(self, val):
self["fill"] = val
@property
def show(self):
"""
Sets the fill ratio of the `slices`. The default fill value of
the z `slices` is 1 meaning that they are entirely shaded. On
the other hand Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["show"]
@show.setter
def show(self, val):
self["show"] = val
@property
def _prop_descriptions(self):
return """\
fill
Sets the fill ratio of the `caps`. The default fill
value of the `caps` is 1 meaning that they are entirely
shaded. On the other hand Applying a `fill` ratio less
than one would allow the creation of openings parallel
to the edges.
show
Sets the fill ratio of the `slices`. The default fill
value of the z `slices` is 1 meaning that they are
entirely shaded. On the other hand Applying a `fill`
ratio less than one would allow the creation of
openings parallel to the edges.
"""
def __init__(self, arg=None, fill=None, show=None, **kwargs):
"""
Construct a new Z object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.caps.Z`
fill
Sets the fill ratio of the `caps`. The default fill
value of the `caps` is 1 meaning that they are entirely
shaded. On the other hand Applying a `fill` ratio less
than one would allow the creation of openings parallel
to the edges.
show
Sets the fill ratio of the `slices`. The default fill
value of the z `slices` is 1 meaning that they are
entirely shaded. On the other hand Applying a `fill`
ratio less than one would allow the creation of
openings parallel to the edges.
Returns
-------
Z
"""
super().__init__("z")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.isosurface.caps.Z
constructor must be a dict or
an instance of :class:`plotly.graph_objs.isosurface.caps.Z`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("fill", arg, fill)
self._set_property("show", arg, show)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Z |
python | jazzband__prettytable | tests/test_sections.py | {
"start": 86,
"end": 1674
} | class ____:
EXPECTED_RESULT = """
┌──────────┬──────────┬──────────┐
│ Field 1 │ Field 2 │ Field 3 │
├──────────┼──────────┼──────────┤
│ value 4 │ value 5 │ value 6 │
│ value 7 │ value 8 │ value 9 │
├──────────┼──────────┼──────────┤
│ value 10 │ value 11 │ value 12 │
└──────────┴──────────┴──────────┘
""".strip()
TEST_ROWS = [
["value 4", "value 5", "value 6"],
["value 7", "value 8", "value 9"],
["value 10", "value 11", "value 12"],
]
def test_row_end_section_via_argument(self) -> None:
table = PrettyTable()
table.set_style(TableStyle.SINGLE_BORDER)
table.add_row(self.TEST_ROWS[0])
table.add_row(self.TEST_ROWS[1], divider=True)
table.add_row(self.TEST_ROWS[2])
assert table.get_string().strip() == self.EXPECTED_RESULT
def test_row_end_section_via_method(self) -> None:
table = PrettyTable()
table.set_style(TableStyle.SINGLE_BORDER)
table.add_row(self.TEST_ROWS[0])
table.add_row(self.TEST_ROWS[1])
table.add_divider()
table.add_row(self.TEST_ROWS[2])
assert table.get_string().strip() == self.EXPECTED_RESULT
def test_add_rows_divider(self) -> None:
"""A table created with two add_rows calls, one with divider=True has a
divider"""
table = PrettyTable()
table.set_style(TableStyle.SINGLE_BORDER)
table.add_rows(self.TEST_ROWS[0:2], divider=True)
table.add_rows(self.TEST_ROWS[2:])
assert table.get_string().strip() == self.EXPECTED_RESULT
| TestRowEndSection |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 36438,
"end": 38199
} | class ____(BiffRecord):
"""
STYLE record for user-defined cell styles, BIFF3-BIFF8:
Offset Size Contents
0 2 Bit Mask Contents
11-0 0FFFH Index to style XF record
15 8000H Always 0 for user-defined styles
2 var. BIFF2-BIFF7: Non-empty byte string, 8-bit string length
BIFF8: Non-empty Unicode string, 16-bit string length
STYLE record for built-in cell styles, BIFF3-BIFF8:
Offset Size Contents
0 2 Bit Mask Contents
11-0 0FFFH Index to style XF record
15 8000H Always 1 for built-in styles
2 1 Identifier of the built-in cell style:
00H = Normal
01H = RowLevel_lv (see next field)
02H = ColLevel_lv (see next field)
03H = Comma
04H = Currency
05H = Percent
06H = Comma [0] (BIFF4-BIFF8)
07H = Currency [0] (BIFF4-BIFF8)
08H = Hyperlink (BIFF8)
09H = Followed Hyperlink (BIFF8)
3 1 Level for RowLevel or ColLevel style
(zero-based, lv), FFH otherwise
The RowLevel and ColLevel styles specify the formatting of subtotal
cells in a specific outline level. The level is specified by the last
field in the STYLE record. Valid values are 0-6 for the outline levels
1-7.
"""
_REC_ID = 0x0293
def __init__(self):
self._rec_data = pack('<HBB', 0x8000, 0x00, 0xFF)
# TODO: implement user-defined styles???
| StyleRecord |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/generate_erd/pipeline.py | {
"start": 1099,
"end": 4793
} | class ____(Step):
context: ConnectorContext
title = "Generate DBML file"
def __init__(self, context: PipelineContext, skip_relationship_generation: bool) -> None:
super().__init__(context)
self._skip_relationship_generation = skip_relationship_generation
async def _run(self, connector_to_discover: Container) -> StepResult:
if not self._skip_relationship_generation and not self.context.genai_api_key:
raise ValueError("GENAI_API_KEY needs to be provided if the relationship generation is not skipped")
discovered_catalog = await self._get_discovered_catalog(connector_to_discover)
connector_directory = await self.context.get_connector_dir()
command = ["poetry", "run", "erd", "--source-path", "/source", "--source-technical-name", self.context.connector.technical_name]
if self._skip_relationship_generation:
command.append("--skip-llm-relationships")
erd_directory = self._build_erd_container(connector_directory, discovered_catalog).with_exec(command).directory("/source/erd")
await erd_directory.export(str(_get_erd_folder(self.context.connector.code_directory)))
return StepResult(step=self, status=StepStatus.SUCCESS, output=erd_directory)
async def _get_discovered_catalog(self, connector_to_discover: Container) -> str:
source_config_path_in_container = "/data/config.json"
discover_output = (
await connector_to_discover.with_new_file(source_config_path_in_container, contents=self._get_default_config().value)
.with_exec(["discover", "--config", source_config_path_in_container], use_entrypoint=True)
.stdout()
)
return self._get_schema_from_discover_output(discover_output)
def _get_default_config(self) -> Secret:
if not self.context.local_secret_store:
raise ValueError("Expecting local secret store to be set up but couldn't find it")
filtered_secrets = [secret for secret in self.context.local_secret_store.get_all_secrets() if secret.file_name == "config.json"]
if not filtered_secrets:
raise ValueError("Expecting at least one secret to match name `config.json`")
elif len(filtered_secrets) > 1:
self.logger.warning(
f"Expecting only one secret with name `config.json but got {len(filtered_secrets)}. Will take the first one in the list."
)
return filtered_secrets[0]
@staticmethod
def _get_schema_from_discover_output(discover_output: str) -> str:
for line in discover_output.split("\n"):
json_line = json.loads(line)
if json_line.get("type") == "CATALOG":
return json.dumps(json.loads(line).get("catalog"))
raise ValueError("No catalog was found in output")
def _build_erd_container(self, connector_directory: Directory, discovered_catalog: str) -> Container:
"""Create a container to run ERD generation."""
container = with_poetry(self.context)
if self.context.genai_api_key:
container = container.with_secret_variable("GENAI_API_KEY", self.context.genai_api_key.as_dagger_secret(self.dagger_client))
container = (
container.with_mounted_directory("/source", connector_directory)
.with_new_file("/source/erd/discovered_catalog.json", contents=discovered_catalog)
.with_mounted_directory("/app", self.context.erd_package_dir)
.with_workdir("/app")
)
return container.with_exec(["poetry", "lock"], use_entrypoint=True).with_exec(["poetry", "install"], use_entrypoint=True)
| GenerateDbml |
python | walkccc__LeetCode | solutions/3069. Distribute Elements Into Two Arrays I/3069.py | {
"start": 0,
"end": 272
} | class ____:
def resultArray(self, nums: list[int]) -> list[int]:
arr1 = [nums[0]]
arr2 = [nums[1]]
for i in range(2, len(nums)):
if arr1[-1] > arr2[-1]:
arr1.append(nums[i])
else:
arr2.append(nums[i])
return arr1 + arr2
| Solution |
python | crytic__slither | slither/detectors/assembly/shift_parameter_mixup.py | {
"start": 408,
"end": 2858
} | class ____(AbstractDetector):
"""
Check for cases where a return(a,b) is used in an assembly function that also returns two variables
"""
ARGUMENT = "incorrect-shift"
HELP = "The order of parameters in a shift instruction is incorrect."
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-shift-in-assembly"
)
WIKI_TITLE = "Incorrect shift in assembly."
WIKI_DESCRIPTION = "Detect if the values in a shift operation are reversed"
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract C {
function f() internal returns (uint a) {
assembly {
a := shr(a, 8)
}
}
}
```
The shift statement will right-shift the constant 8 by `a` bits"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Swap the order of parameters."
def _check_function(self, f: FunctionContract) -> List[Output]:
results = []
in_assembly = False
for node in f.nodes:
if node.type == NodeType.ASSEMBLY:
in_assembly = True
continue
if node.type == NodeType.ENDASSEMBLY:
in_assembly = False
continue
if not in_assembly:
continue
for ir in node.irs:
if isinstance(ir, Binary) and ir.type in [
BinaryType.LEFT_SHIFT,
BinaryType.RIGHT_SHIFT,
]:
if isinstance(ir.variable_left, Constant) and not isinstance(
ir.variable_right, Constant
):
info: DETECTOR_INFO = [
f,
" contains an incorrect shift operation: ",
node,
"\n",
]
json = self.generate_result(info)
results.append(json)
return results
def _detect(self) -> List[Output]:
results = []
for c in self.contracts:
for f in c.functions:
if f.contract_declarer != c:
continue
if f.contains_assembly:
results += self._check_function(f)
return results
| ShiftParameterMixup |
python | numba__numba | numba/tests/test_extending.py | {
"start": 44012,
"end": 46082
} | class ____(unittest.TestCase):
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
def test_getting_function(self):
addr = get_cython_function_address(
"scipy.special.cython_special", "j0"
)
functype = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
_j0 = functype(addr)
j0 = jit(nopython=True)(lambda x: _j0(x))
self.assertEqual(j0(0), 1)
def test_missing_module(self):
with self.assertRaises(ImportError) as raises:
get_cython_function_address("fakemodule", "fakefunction")
# The quotes are not there in Python 2
msg = "No module named '?fakemodule'?"
match = re.match(msg, str(raises.exception))
self.assertIsNotNone(match)
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
def test_missing_function(self):
with self.assertRaises(ValueError) as raises:
get_cython_function_address(
"scipy.special.cython_special", "foo"
)
msg = (
"No function 'foo' found in __pyx_capi__ of "
"'scipy.special.cython_special'"
)
self.assertEqual(msg, str(raises.exception))
@overload_method(
MyDummyType, "method_jit_option_check_nrt", jit_options={"_nrt": True}
)
def ov_method_jit_option_check_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_method(
MyDummyType, "method_jit_option_check_no_nrt", jit_options={"_nrt": False}
)
def ov_method_jit_option_check_no_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_attribute(
MyDummyType, "attr_jit_option_check_nrt", jit_options={"_nrt": True}
)
def ov_attr_jit_option_check_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_attribute(
MyDummyType, "attr_jit_option_check_no_nrt", jit_options={"_nrt": False}
)
def ov_attr_jit_option_check_no_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
| TestImportCythonFunction |
python | scipy__scipy | scipy/integrate/_ivp/lsoda.py | {
"start": 9752,
"end": 10162
} | class ____(DenseOutput):
def __init__(self, t_old, t, h, order, yh):
super().__init__(t_old, t)
self.h = h
self.yh = yh
self.p = np.arange(order + 1)
def _call_impl(self, t):
if t.ndim == 0:
x = ((t - self.t) / self.h) ** self.p
else:
x = ((t - self.t) / self.h) ** self.p[:, None]
return np.dot(self.yh, x)
| LsodaDenseOutput |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 39023,
"end": 39608
} | class ____(Reduction):
_parameters = ["frame", "b", "split_every"]
_defaults = {"b": 16, "split_every": None}
reduction_chunk = hyperloglog.compute_hll_array
reduction_combine = hyperloglog.reduce_state
reduction_aggregate = hyperloglog.estimate_count
@functools.cached_property
def _meta(self):
return 1.0
@property
def chunk_kwargs(self):
return {"b": self.b}
@property
def combine_kwargs(self):
return self.chunk_kwargs
@property
def aggregate_kwargs(self):
return self.chunk_kwargs
| NuniqueApprox |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/metadata_logging.py | {
"start": 225,
"end": 315
} | class ____:
output_name: str
mapping_key: Optional[str]
@record
| OutputMetadataHandle |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py | {
"start": 485,
"end": 587
} | class ____(type):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args)
| Meta |
python | getsentry__sentry | src/sentry/workflow_engine/utils/scopedstats.py | {
"start": 2526,
"end": 6049
} | class ____:
"""Records statistics during context blocks. Use with record() context manager."""
__slots__ = ("_data", "_has_recorded")
def __init__(self) -> None:
self._data: dict[str, dict[tuple[tuple[str, str | bool], ...], int | float]] = defaultdict(
lambda: defaultdict(int)
)
self._has_recorded = False
@contextmanager
def record(self) -> Generator[None]:
"""Context manager for recording statistics. Automatically adds total_recording_duration."""
collector = _StatsCollector()
parent_collector = _current_collector.get()
context_token = _current_collector.set(collector)
start_time = time.perf_counter()
try:
yield
finally:
end_time = time.perf_counter()
recording_duration = end_time - start_time
collector.set("total_recording_duration", value=recording_duration)
self._merge_collector(collector)
self._has_recorded = True
_current_collector.reset(context_token)
if parent_collector is not None:
collector.merge_into(parent_collector)
def _merge_collector(self, collector: _StatsCollector) -> None:
for key, tags_data in collector._data.items():
final_key_data = self._data[key]
for tags_tuple, amount in tags_data.items():
final_key_data[tags_tuple] += amount
def get_result(
self, tag_filter: Tags | None = None, *, require_recording: bool = False
) -> dict[str, int | float]:
"""Get recorded statistics.
Args:
tag_filter: Only include stats with matching tags
require_recording: Raise ValueError if no recording has occurred
"""
if require_recording and not self._has_recorded:
raise ValueError(
"No recording has occurred. Use recorder.record() context manager first."
)
return _get_filtered_stats(self._data, tag_filter)
def incr(key: str, tags: Tags | None = None, amount: int | float = 1) -> None:
"""Increment a counter if stats are being recorded."""
collector = _current_collector.get()
if collector:
tags_tuple = _generate_tags_key(tags)
collector._data[key][tags_tuple] += amount
def timer(
*,
key: str | None = None,
tags: Tags | None = None,
) -> Callable[[Callable[P, T]], Callable[P, T]]:
"""Decorator to time function execution and record statistics if stats are being recorded.
Records two keys:
- {key}.count: Number of calls
- {key}.total_dur: Total duration in seconds
Default key is "calls.{func.__qualname__}".
"""
def create_wrapper(f: Callable[P, T]) -> Callable[P, T]:
timer_key = key if key is not None else f"calls.{f.__qualname__}"
tags_tuple = _generate_tags_key(tags)
@functools.wraps(f)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
collector = _current_collector.get()
if not collector:
return f(*args, **kwargs)
start_time = time.perf_counter()
try:
return f(*args, **kwargs)
finally:
duration_secs = time.perf_counter() - start_time
collector._data[f"{timer_key}.count"][tags_tuple] += 1
collector._data[f"{timer_key}.total_dur"][tags_tuple] += duration_secs
return wrapper
return create_wrapper
| Recorder |
python | huggingface__transformers | src/transformers/models/evolla/modular_evolla.py | {
"start": 5706,
"end": 5762
} | class ____(EsmSelfOutput):
pass
| EvollaSaProtSelfOutput |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_async/ASYNC230.py | {
"start": 872,
"end": 1069
} | class ____:
def open(self):
pass
async def func():
Foo().open() # OK
async def func():
def open():
pass
open() # OK
def func():
Path("foo").open() # OK
| Foo |
python | huggingface__transformers | src/transformers/models/olmoe/modeling_olmoe.py | {
"start": 20329,
"end": 27085
} | class ____(OlmoePreTrainedModel):
def __init__(self, config: OlmoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[OlmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = OlmoeRotaryEmbedding(config=config)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
@check_model_inputs()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = create_causal_mask( # diff with mixtral: no sliding
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
attention_mask=causal_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
def load_balancing_loss_func(
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
num_experts: Optional[int] = None,
top_k=2,
attention_mask: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, int]:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
gate_logits:
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
shape [batch_size X sequence_length, num_experts].
num_experts:
Number of experts
top_k:
The number of experts to route per-token, can be also interpreted as the `top-k` routing
parameter.
attention_mask (`torch.Tensor`, *optional*):
The attention_mask used in forward function
shape [batch_size X sequence_length] if not None.
Returns:
The auxiliary loss.
"""
if gate_logits is None or not isinstance(gate_logits, tuple):
return 0
if isinstance(gate_logits, tuple):
compute_device = gate_logits[0].device
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
if attention_mask is None:
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.mean(routing_weights, dim=0)
else:
batch_size, sequence_length = attention_mask.shape
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
expert_attention_mask = (
attention_mask[None, :, :, None, None]
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
.reshape(-1, top_k, num_experts)
.to(compute_device)
)
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
expert_attention_mask, dim=0
)
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
router_per_expert_attention_mask = (
attention_mask[None, :, :, None]
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
.reshape(-1, num_experts)
.to(compute_device)
)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
router_per_expert_attention_mask, dim=0
)
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
return overall_loss * num_experts
@auto_docstring
| OlmoeModel |
python | buildout__buildout | src/zc/buildout/buildout.py | {
"start": 2038,
"end": 2383
} | class ____(zc.buildout.UserError, KeyError):
"""A required section is missing.
"""
def __str__(self):
return "The referenced section, %r, was not defined." % self.args[0]
def _annotate_section(section, source):
for key in section:
section[key] = SectionKey(section[key], source)
return section
| MissingSection |
python | kamyu104__LeetCode-Solutions | Python/maximum-alternating-sum-of-squares.py | {
"start": 1505,
"end": 1751
} | class ____(object):
def maxAlternatingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
arr = sorted(x**2 for x in nums)
return sum(arr)-2*sum(arr[i] for i in xrange(len(arr)//2))
| Solution2 |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 4701,
"end": 5137
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def active(self):
raise NotImplementedError()
def __call__(self, name_or_index):
raise NotImplementedError()
def __len__(self):
raise NotImplementedError()
def __iter__(self):
raise NotImplementedError()
def add(self, before=None, after=None):
raise NotImplementedError()
| Sheets |
python | EpistasisLab__tpot | tpot/builtin_modules/arithmetictransformer.py | {
"start": 14710,
"end": 15340
} | class ____(TransformerMixin, BaseEstimator):
def __init__(self, n):
"""
A transformer that returns an array of n.
"""
self.n = n
def fit(self, X, y=None):
return self
def transform(self, X):
transformed_X = np.array(self.transform_helper(np.array(X)))
if transformed_X.dtype != float:
transformed_X = transformed_X.astype(float)
return transformed_X
def transform_helper(self, X):
X = np.array(X)
if len(X.shape) == 1:
X = np.expand_dims(X,0)
return np.ones((X.shape[0],1))*self.n
| NTransformer |
python | dagster-io__dagster | examples/assets_dbt_python/assets_dbt_python/assets/dbt.py | {
"start": 247,
"end": 1073
} | class ____(DagsterDbtTranslator):
def get_asset_key(self, dbt_resource_props: Mapping[str, Any]) -> AssetKey:
asset_key = super().get_asset_key(dbt_resource_props)
if dbt_resource_props["resource_type"] == "model":
asset_key = asset_key.with_prefix(["duckdb", "dbt_schema"])
if dbt_resource_props["resource_type"] == "source":
asset_key = asset_key.with_prefix("duckdb")
return asset_key
@dbt_assets(
manifest=dbt_project.manifest_path,
dagster_dbt_translator=CustomDagsterDbtTranslator(),
)
def dbt_project_assets(context: AssetExecutionContext, dbt: DbtCliResource):
yield from dbt.cli(["build"], context=context).stream()
daily_order_summary_asset_key = get_asset_key_for_model([dbt_project_assets], "daily_order_summary")
| CustomDagsterDbtTranslator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 555174,
"end": 555517
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DeleteIssueComment"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id",)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| DeleteIssueCommentPayload |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 60152,
"end": 62554
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
)
Table("b", metadata, Column("id", Integer, primary_key=True))
Table("c", metadata, Column("id", Integer, primary_key=True))
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(A):
pass
class C(A):
pass
@classmethod
def setup_mappers(cls):
A, B, C = cls.classes.A, cls.classes.B, cls.classes.C
cls.mapper_registry.map_imperatively(A, cls.tables.a)
cls.mapper_registry.map_imperatively(
B,
cls.tables.b,
inherits=A,
inherit_condition=cls.tables.a.c.id == cls.tables.b.c.id,
inherit_foreign_keys=cls.tables.b.c.id,
)
cls.mapper_registry.map_imperatively(
C,
cls.tables.c,
inherits=A,
inherit_condition=cls.tables.a.c.id == cls.tables.c.c.id,
inherit_foreign_keys=cls.tables.c.c.id,
)
def test_ordering(self):
B, C = self.classes.B, self.classes.C
sess = fixture_session()
sess.add_all([B(), C(), B(), C()])
self.assert_sql_execution(
testing.db,
sess.flush,
Conditional(
testing.db.dialect.insert_executemany_returning,
[
CompiledSQL(
"INSERT INTO a (id) VALUES (DEFAULT) RETURNING a.id",
[{}, {}, {}, {}],
),
],
[
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
CompiledSQL("INSERT INTO a () VALUES ()", {}),
],
),
AllOf(
CompiledSQL(
"INSERT INTO b (id) VALUES (:id)", [{"id": 1}, {"id": 3}]
),
CompiledSQL(
"INSERT INTO c (id) VALUES (:id)", [{"id": 2}, {"id": 4}]
),
),
)
| JoinedNoFKSortingTest |
python | astropy__astropy | astropy/modeling/tests/test_constraints.py | {
"start": 720,
"end": 3849
} | class ____:
def setup_class(self):
self.g1 = models.Gaussian1D(10, 14.9, stddev=0.3)
self.g2 = models.Gaussian1D(10, 13, stddev=0.4)
self.x = np.arange(10, 20, 0.1)
self.y1 = self.g1(self.x)
self.y2 = self.g2(self.x)
rsn = default_rng(1234567890)
self.n = rsn.standard_normal(100)
self.ny1 = self.y1 + 2 * self.n
self.ny2 = self.y2 + 2 * self.n
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters)
def test_fixed_par(self, fitter):
fitter = fitter()
g1 = models.Gaussian1D(10, mean=14.9, stddev=0.3, fixed={"amplitude": True})
model = fitter(g1, self.x, self.ny1)
assert model.amplitude.value == 10
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters)
def test_tied_par(self, fitter):
fitter = fitter()
def tied(model):
mean = 50 * model.stddev
return mean
g1 = models.Gaussian1D(10, mean=14.9, stddev=0.3, tied={"mean": tied})
model = fitter(g1, self.x, self.ny1)
assert_allclose(model.mean.value, 50 * model.stddev, rtol=10 ** (-5))
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
def test_joint_fitter(self):
from scipy import optimize
g1 = models.Gaussian1D(10, 14.9, stddev=0.3)
g2 = models.Gaussian1D(10, 13, stddev=0.4)
jf = fitting.JointFitter(
[g1, g2], {g1: ["amplitude"], g2: ["amplitude"]}, [9.8]
)
x = np.arange(10, 20, 0.1)
y1 = g1(x)
y2 = g2(x)
n = np.random.randn(100)
ny1 = y1 + 2 * n
ny2 = y2 + 2 * n
jf(x, ny1, x, ny2)
p1 = [14.9, 0.3]
p2 = [13, 0.4]
A = 9.8
p = np.r_[A, p1, p2]
def compmodel(A, p, x):
return A * np.exp(-0.5 / p[1] ** 2 * (x - p[0]) ** 2)
def errf(p, x1, y1, x2, y2):
return np.ravel(
np.r_[compmodel(p[0], p[1:3], x1) - y1, compmodel(p[0], p[3:], x2) - y2]
)
fitparams, _ = optimize.leastsq(errf, p, args=(x, ny1, x, ny2))
assert_allclose(jf.fitparams, fitparams, rtol=10 ** (-5))
assert_allclose(g1.amplitude.value, g2.amplitude.value)
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters)
def test_no_constraints(self, fitter):
from scipy import optimize
fitter = fitter()
g1 = models.Gaussian1D(9.9, 14.5, stddev=0.3)
def func(p, x):
return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2)
def errf(p, x, y):
return func(p, x) - y
p0 = [9.9, 14.5, 0.3]
y = g1(self.x)
n = np.random.randn(100)
ny = y + n
fitpar, s = optimize.leastsq(errf, p0, args=(self.x, ny))
model = fitter(g1, self.x, ny)
assert_allclose(model.parameters, fitpar, rtol=5 * 10 ** (-3))
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
| TestNonLinearConstraints |
python | huggingface__transformers | examples/pytorch/language-modeling/run_fim.py | {
"start": 6244,
"end": 36187
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
validation_file: Optional[str] = field(
default=None,
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
)
max_train_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
},
)
max_eval_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
},
)
streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"})
block_size: Optional[int] = field(
default=None,
metadata={
"help": (
"Optional input sequence length after tokenization. "
"The training dataset will be truncated in block of this size for training. "
"Default to the model max input length for single sentence inputs (take into account special tokens)."
)
},
)
fim_rate: Optional[float] = field(
default=0.5,
metadata={
"help": (
"Optional probability with which the FIM transformation is applied to the example. "
"Default is 0.5. A rate of 1.0 means every example will undergo FIM transformation, "
"while a rate of 0.0 means no example will."
)
},
)
fim_spm_rate: Optional[float] = field(
default=0.5,
metadata={
"help": (
"Within the examples undergoing FIM transformation, this rate determines the probability "
"of applying the Sentence Permutation Mode (SPM). "
"Default is 0.5. A rate of 1.0 means all FIM transformations will use SPM, "
"while a rate of 0.0 means none will."
)
},
)
truncate_or_pad: Optional[bool] = field(
default=True,
metadata={
"help": (
"Indicates whether the transformed example should be truncated or padded to maintain "
"the same length as the original example. "
"Default is True. If False, the function will not truncate or pad the examples."
)
},
)
fim_prefix_token: Optional[str] = field(
default="<fim_prefix>",
metadata={"help": ("Fill-in-Middle Prefix token. Defaults to '<fim_prefix>'.")},
)
fim_middle_token: Optional[str] = field(
default="<fim_middle>",
metadata={"help": ("Fill-in-Middle Middle token. Defaults to '<fim_middle>'.")},
)
fim_suffix_token: Optional[str] = field(
default="<fim_suffix>",
metadata={"help": ("Fill-in-Middle Suffix token. Defaults to '<fim_suffix>'.")},
)
pad_token: Optional[str] = field(
default="<fim_pad>",
metadata={
"help": (
"Fill-in-Middle Pad token. Used only when 'truncate_or_pad' is set to True. Defaults to '<fim_pad>'."
)
},
)
overwrite_cache: bool = field(
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
)
validation_split_percentage: Optional[int] = field(
default=5,
metadata={
"help": "The percentage of the train set used as validation set in case there's no validation split"
},
)
preprocessing_num_workers: Optional[int] = field(
default=None,
metadata={"help": "The number of processes to use for the preprocessing."},
)
keep_linebreaks: bool = field(
default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
)
def __post_init__(self):
if self.streaming:
require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`")
if self.dataset_name is None and self.train_file is None and self.validation_file is None:
raise ValueError("Need either a dataset name or a training/validation file.")
else:
if self.train_file is not None:
extension = self.train_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
if self.validation_file is not None:
extension = self.validation_file.split(".")[-1]
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
# Set seed before initializing model.
set_seed(training_args.seed)
# Set a numpy random state for FIM transformations
np_rng = np.random.RandomState(seed=training_args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
raw_datasets = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
token=model_args.token,
streaming=data_args.streaming,
trust_remote_code=model_args.trust_remote_code,
)
if "validation" not in raw_datasets:
raw_datasets["validation"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
token=model_args.token,
streaming=data_args.streaming,
trust_remote_code=model_args.trust_remote_code,
)
raw_datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
token=model_args.token,
streaming=data_args.streaming,
trust_remote_code=model_args.trust_remote_code,
)
else:
data_files = {}
dataset_args = {}
if data_args.train_file is not None:
data_files["train"] = data_args.train_file
if data_args.validation_file is not None:
data_files["validation"] = data_args.validation_file
extension = (
data_args.train_file.split(".")[-1]
if data_args.train_file is not None
else data_args.validation_file.split(".")[-1]
)
if extension == "txt":
extension = "text"
dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
raw_datasets = load_dataset(
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
token=model_args.token,
**dataset_args,
)
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
if "validation" not in raw_datasets:
raw_datasets["validation"] = load_dataset(
extension,
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
token=model_args.token,
**dataset_args,
)
raw_datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
token=model_args.token,
**dataset_args,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
"token": model_args.token,
"trust_remote_code": model_args.trust_remote_code,
}
if model_args.config_name:
config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
elif model_args.model_name_or_path:
config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
else:
config = CONFIG_MAPPING[model_args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if model_args.config_overrides is not None:
logger.info(f"Overriding config: {model_args.config_overrides}")
config.update_from_string(model_args.config_overrides)
logger.info(f"New config: {config}")
tokenizer_kwargs = {
"cache_dir": model_args.cache_dir,
"use_fast": model_args.use_fast_tokenizer,
"revision": model_args.model_revision,
"token": model_args.token,
"trust_remote_code": model_args.trust_remote_code,
}
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script. "
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
)
if model_args.model_name_or_path:
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
model = AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
token=model_args.token,
trust_remote_code=model_args.trust_remote_code,
dtype=dtype,
attn_implementation=model_args.attn_implementation,
)
else:
model = AutoModelForCausalLM.from_config(
config,
trust_remote_code=model_args.trust_remote_code,
attn_implementation=model_args.attn_implementation,
)
n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
logger.info(f"Training new model from scratch - Total size={n_params / 2**20:.2f}M params")
# Add the new FIM tokens to the tokenizer and resize model's vocab embeddings
special_tokens = [data_args.fim_prefix_token, data_args.fim_middle_token, data_args.fim_suffix_token]
if data_args.truncate_or_pad:
special_tokens.append(data_args.pad_token)
# Get the factor by which the embedding layer should be padded based on the device
pad_factor = 1
if torch.cuda.is_available():
pad_factor = 8
elif is_torch_xla_available(check_is_tpu=True):
pad_factor = 128
# Add the new tokens to the tokenizer
tokenizer.add_tokens(special_tokens)
original_embeddings = model.get_input_embeddings()
if is_deepspeed_zero3_enabled():
import deepspeed
with deepspeed.zero.GatheredParameters(original_embeddings.weight, modifier_rank=0):
# Get the pre-expansion embeddings of the model and resize the embedding layer
model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=pad_factor)
embeddings = model.get_input_embeddings()
# Sample the embeddings for the new tokens from a multivariate normal distribution
# We do this so that the new embeddings are close to the original embeddings and not necessarily zero
# More on this: https://nlp.stanford.edu/~johnhew/vocab-expansion.html
mean = original_embeddings.mean(dim=0)
n = original_embeddings.size()[0]
sigma = ((original_embeddings - mean).T @ (original_embeddings - mean)) / n
dist = torch.distributions.multivariate_normal.MultivariateNormal(
mean,
covariance_matrix=1e-5 * sigma,
)
new_token_embeddings = torch.stack(
tuple(dist.sample() for _ in range(len(special_tokens))),
dim=0,
)
else:
original_embeddings = model.get_input_embeddings()
# Get the pre-expansion embeddings of the model and resize the embedding layer
model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=pad_factor)
embeddings = model.get_input_embeddings()
# Sample the embeddings for the new tokens from a multivariate normal distribution
# We do this so that the new embeddings are close to the original embeddings and not necessarily zero
# More on this: https://nlp.stanford.edu/~johnhew/vocab-expansion.html
mean = original_embeddings.mean(dim=0)
n = original_embeddings.size()[0]
sigma = ((original_embeddings - mean).T @ (original_embeddings - mean)) / n
dist = torch.distributions.multivariate_normal.MultivariateNormal(
mean,
covariance_matrix=1e-5 * sigma,
)
new_token_embeddings = torch.stack(
tuple(dist.sample() for _ in range(len(special_tokens))),
dim=0,
)
if is_deepspeed_zero3_enabled():
import deepspeed
with deepspeed.zero.GatheredParameters(embeddings.weight, modifier_rank=0):
# Set the new tokens' embeddings to the newly sampled embeddings
embeddings.weight.data[-len(special_tokens) :] = new_token_embeddings
else:
# Set the new tokens' embeddings to the newly sampled embeddings
embeddings.weight.data[-len(special_tokens) :] = new_token_embeddings
# Update the model's embeddings with the new embeddings
model.set_input_embeddings(embeddings)
logger.info("Added special tokens to the tokenizer and resized model's embedding layer")
# Preprocessing the datasets.
# First we tokenize all the texts.
if training_args.do_train:
column_names = list(raw_datasets["train"].features)
else:
column_names = list(raw_datasets["validation"].features)
text_column_name = "text" if "text" in column_names else column_names[0]
# since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
def tokenize_function(examples):
with CaptureLogger(tok_logger) as cl:
output = tokenizer(examples[text_column_name])
# clm-fim input could be much much longer than block_size
if "Token indices sequence length is longer than the" in cl.out:
tok_logger.warning(
"^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits"
" before being passed to the model."
)
return output
with training_args.main_process_first(desc="dataset map tokenization"):
if not data_args.streaming:
tokenized_datasets = raw_datasets.map(
tokenize_function,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on dataset",
)
else:
tokenized_datasets = raw_datasets.map(
tokenize_function,
batched=True,
remove_columns=column_names,
)
if data_args.block_size is None:
block_size = tokenizer.model_max_length
if block_size > config.max_position_embeddings:
logger.warning(
f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
f"Using block_size={min(1024, config.max_position_embeddings)} instead. You can change that default value by passing --block_size xxx."
)
block_size = min(1024, config.max_position_embeddings)
else:
if data_args.block_size > tokenizer.model_max_length:
logger.warning(
f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
)
block_size = min(data_args.block_size, tokenizer.model_max_length)
# Data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
# We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
result["labels"] = result["input_ids"].copy()
return result
# Get the FIM-specific token ids
prefix_tok_id = tokenizer.convert_tokens_to_ids(data_args.fim_prefix_token)
middle_tok_id = tokenizer.convert_tokens_to_ids(data_args.fim_middle_token)
suffix_tok_id = tokenizer.convert_tokens_to_ids(data_args.fim_suffix_token)
pad_tok_id = None
# If truncate_or_pad is on, also get pad token id
if data_args.truncate_or_pad:
pad_tok_id = tokenizer.convert_tokens_to_ids(data_args.pad_token)
# The two functions below perform the FIM transformation on the data (either PSM or SPM or PSM+SPM)
# Don't call fim_transform directly in .map()
# Adapted from https://github.com/loubnabnl/santacoder-finetuning/blob/main/fim.py#L22C13-L83
def fim_transform(example):
"""
This function performs FIM transformation on a single example (list of tokens)
"""
if np_rng.binomial(1, data_args.fim_rate):
boundaries = sorted(np_rng.randint(low=0, high=len(example) + 1, size=2))
prefix = example[: boundaries[0]]
middle = example[boundaries[0] : boundaries[1]]
suffix = example[boundaries[1] :]
if data_args.truncate_or_pad:
total_length = len(prefix) + len(middle) + len(suffix) + 3
diff = total_length - len(example)
if diff > 0:
suffix = suffix[: max(0, len(suffix) - diff)]
elif diff < 0:
suffix.extend([pad_tok_id] * (-diff))
if np_rng.binomial(1, data_args.fim_spm_rate):
# Apply Suffix-Prefix-Middle (SPM) transformation
transformed_example = [prefix_tok_id, suffix_tok_id] + suffix + [middle_tok_id] + prefix + middle
else:
# Apply Prefix-Suffix-Middle (PSM) transformation
transformed_example = [prefix_tok_id] + prefix + [suffix_tok_id] + suffix + [middle_tok_id] + middle
else:
transformed_example = example
return transformed_example
# Below function is the one you are supposed to call in the .map() function
def apply_fim(examples):
"""
Apply FIM transformation to a batch of examples
"""
fim_transform_ids = [fim_transform(ids) for ids in examples["input_ids"]]
examples["input_ids"] = fim_transform_ids
examples["labels"] = fim_transform_ids
# If your application requires custom attention mask, please adjust this function's below line.
# Since FIM transformation increases the number of tokens in input_ids and labels
# but leaves the number of tokens unchanged in attention_masks which would cause problems
examples["attention_mask"] = [[1] * len(mask) for mask in examples["input_ids"]]
return examples
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
# for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
# to preprocess.
#
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
# https://huggingface.co/docs/datasets/process#map
# FIM transformations are only supposed to be applied before group_texts processing otherwise some sentences will
# have 3-4 more tokens than others due to probabilistic addition of FIM-specific tokens which will raise errors
with training_args.main_process_first(desc="processing texts together"):
if not data_args.streaming:
fim_datasets = tokenized_datasets.map(
apply_fim,
batched=True,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
desc="Performing FIM transformation",
)
lm_datasets = fim_datasets.map(
group_texts,
batched=True,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
desc=f"Grouping texts in chunks of {block_size}",
)
else:
fim_datasets = tokenized_datasets.map(
apply_fim,
batched=True,
)
lm_datasets = fim_datasets.map(
group_texts,
batched=True,
)
if training_args.do_train:
if "train" not in tokenized_datasets:
raise ValueError("--do_train requires a train dataset")
train_dataset = lm_datasets["train"]
if data_args.max_train_samples is not None:
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
train_dataset = train_dataset.select(range(max_train_samples))
if training_args.do_eval:
if "validation" not in tokenized_datasets:
raise ValueError("--do_eval requires a validation dataset")
eval_dataset = lm_datasets["validation"]
if data_args.max_eval_samples is not None:
max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
eval_dataset = eval_dataset.select(range(max_eval_samples))
def preprocess_logits_for_metrics(logits, labels):
if isinstance(logits, tuple):
# Depending on the model and config, logits may contain extra tensors,
# like past_key_values, but logits always come first
logits = logits[0]
return logits.argmax(dim=-1)
metric = evaluate.load("accuracy")
def compute_metrics(eval_preds):
preds, labels = eval_preds
# preds have the same shape as the labels, after the argmax(-1) has been calculated
# by preprocess_logits_for_metrics but we need to shift the labels
labels = labels[:, 1:].reshape(-1)
preds = preds[:, :-1].reshape(-1)
return metric.compute(predictions=preds, references=labels)
# Initialize our Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
processing_class=tokenizer,
# Data collator will default to DataCollatorWithPadding, so we change it.
data_collator=default_data_collator,
compute_metrics=compute_metrics
if training_args.do_eval and not is_torch_xla_available(check_is_tpu=True)
else None,
preprocess_logits_for_metrics=(
preprocess_logits_for_metrics
if training_args.do_eval and not is_torch_xla_available(check_is_tpu=True)
else None
),
)
# Training
if training_args.do_train:
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_checkpoint
train_result = trainer.train(resume_from_checkpoint=checkpoint)
trainer.save_model() # Saves the tokenizer too for easy upload
metrics = train_result.metrics
max_train_samples = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
)
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***")
metrics = trainer.evaluate()
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
try:
perplexity = math.exp(metrics["eval_loss"])
except OverflowError:
perplexity = float("inf")
metrics["perplexity"] = perplexity
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)
kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
if data_args.dataset_name is not None:
kwargs["dataset_tags"] = data_args.dataset_name
if data_args.dataset_config_name is not None:
kwargs["dataset_args"] = data_args.dataset_config_name
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
else:
kwargs["dataset"] = data_args.dataset_name
if training_args.push_to_hub:
trainer.push_to_hub(**kwargs)
else:
trainer.create_model_card(**kwargs)
def _mp_fn(index):
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| DataTrainingArguments |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 966355,
"end": 967129
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for SecurityVulnerability."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("SecurityVulnerabilityEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of(SecurityVulnerability), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| SecurityVulnerabilityConnection |
python | jupyterlab__jupyterlab | jupyterlab/extensions/manager.py | {
"start": 6245,
"end": 6518
} | class ____:
"""Extensions cache
Attributes:
cache: Extension list per page
last_page: Last available page result
"""
cache: dict[int, Optional[dict[str, ExtensionPackage]]] = field(default_factory=dict)
last_page: int = 1
| ExtensionsCache |
python | pypa__warehouse | tests/unit/admin/views/test_organizations.py | {
"start": 38873,
"end": 41265
} | class ____:
@freeze_time("2024-01-15")
def test_validate_success(self):
form_data = MultiDict(
{
"seat_limit": "25",
"expires": (date.today() + timedelta(days=365)).isoformat(),
}
)
form = views.ManualActivationForm(formdata=form_data)
assert form.validate(), str(form.errors)
@freeze_time("2024-01-15")
def test_validate_missing_seat_limit(self):
form_data = MultiDict(
{
"expires": (date.today() + timedelta(days=365)).isoformat(),
}
)
form = views.ManualActivationForm(formdata=form_data)
assert not form.validate()
assert "Specify seat limit" in str(form.seat_limit.errors)
def test_validate_missing_expires(self):
form_data = MultiDict(
{
"seat_limit": "25",
}
)
form = views.ManualActivationForm(formdata=form_data)
assert not form.validate()
assert "Specify expiration date" in str(form.expires.errors)
@freeze_time("2024-01-15")
def test_validate_invalid_seat_limit_zero(self):
form_data = MultiDict(
{
"seat_limit": "0",
"expires": (date.today() + timedelta(days=365)).isoformat(),
}
)
form = views.ManualActivationForm(formdata=form_data)
assert not form.validate()
assert "Seat limit must be at least 1" in str(form.seat_limit.errors)
@freeze_time("2024-01-15")
def test_validate_invalid_seat_limit_negative(self):
form_data = MultiDict(
{
"seat_limit": "-1",
"expires": (date.today() + timedelta(days=365)).isoformat(),
}
)
form = views.ManualActivationForm(formdata=form_data)
assert not form.validate()
assert "Seat limit must be at least 1" in str(form.seat_limit.errors)
@freeze_time("2024-01-15")
def test_validate_expires_in_past(self):
form_data = MultiDict(
{
"seat_limit": "25",
"expires": "2020-01-01",
}
)
form = views.ManualActivationForm(formdata=form_data)
assert not form.validate()
assert "Expiration date must be in the future" in str(form.expires.errors)
| TestManualActivationForm |
python | kennethreitz__tablib | src/tablib/formats/_xlsx.py | {
"start": 308,
"end": 4490
} | class ____:
title = 'xlsx'
extensions = ('xlsx',)
@classmethod
def detect(cls, stream):
"""Returns True if given stream is a readable excel file."""
try:
# No need to fully load the file, it should be enough to be able to
# read the manifest.
reader = ExcelReader(stream, read_only=False)
reader.read_manifest()
return True
except Exception:
return False
@classmethod
def export_set(cls, dataset, freeze_panes=True):
"""Returns XLSX representation of Dataset."""
wb = Workbook()
ws = wb.worksheets[0]
ws.title = dataset.title if dataset.title else 'Tablib Dataset'
cls.dset_sheet(dataset, ws, freeze_panes=freeze_panes)
stream = BytesIO()
wb.save(stream)
return stream.getvalue()
@classmethod
def export_book(cls, databook, freeze_panes=True):
"""Returns XLSX representation of DataBook."""
wb = Workbook()
for sheet in wb.worksheets:
wb.remove(sheet)
for i, dset in enumerate(databook._datasets):
ws = wb.create_sheet()
ws.title = dset.title if dset.title else 'Sheet%s' % (i)
cls.dset_sheet(dset, ws, freeze_panes=freeze_panes)
stream = BytesIO()
wb.save(stream)
return stream.getvalue()
@classmethod
def import_set(cls, dset, in_stream, headers=True, read_only=True):
"""Returns databook from XLS stream."""
dset.wipe()
xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
sheet = xls_book.active
dset.title = sheet.title
for i, row in enumerate(sheet.rows):
row_vals = [c.value for c in row]
if (i == 0) and (headers):
dset.headers = row_vals
else:
dset.append(row_vals)
@classmethod
def import_book(cls, dbook, in_stream, headers=True, read_only=True):
"""Returns databook from XLS stream."""
dbook.wipe()
xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
for sheet in xls_book.worksheets:
data = tablib.Dataset()
data.title = sheet.title
for i, row in enumerate(sheet.rows):
row_vals = [c.value for c in row]
if (i == 0) and (headers):
data.headers = row_vals
else:
if i > 0 and len(row_vals) < data.width:
row_vals += [''] * (data.width - len(row_vals))
data.append(row_vals)
dbook.add_sheet(data)
@classmethod
def dset_sheet(cls, dataset, ws, freeze_panes=True):
"""Completes given worksheet from given Dataset."""
_package = dataset._package(dicts=False)
for i, sep in enumerate(dataset._separators):
_offset = i
_package.insert((sep[0] + _offset), (sep[1],))
bold = Font(bold=True)
wrap_text = Alignment(wrap_text=True)
for i, row in enumerate(_package):
row_number = i + 1
for j, col in enumerate(row):
col_idx = get_column_letter(j + 1)
cell = ws[f'{col_idx}{row_number}']
# bold headers
if (row_number == 1) and dataset.headers:
cell.font = bold
if freeze_panes:
# Export Freeze only after first Line
ws.freeze_panes = 'A2'
# bold separators
elif len(row) < dataset.width:
cell.font = bold
# wrap the rest
else:
try:
str_col_value = str(col)
except TypeError:
str_col_value = ''
if '\n' in str_col_value:
cell.alignment = wrap_text
try:
cell.value = col
except (ValueError, TypeError):
cell.value = str(col)
| XLSXFormat |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/texteditor.py | {
"start": 1125,
"end": 1186
} | class ____:
Copy = 'copy_section'
| TextEditorToolbarSections |
python | scrapy__scrapy | scrapy/commands/settings.py | {
"start": 114,
"end": 1986
} | class ____(ScrapyCommand):
requires_crawler_process = False
default_settings = {"LOG_ENABLED": False}
def syntax(self) -> str:
return "[options]"
def short_desc(self) -> str:
return "Get settings values"
def add_options(self, parser: argparse.ArgumentParser) -> None:
super().add_options(parser)
parser.add_argument(
"--get", dest="get", metavar="SETTING", help="print raw setting value"
)
parser.add_argument(
"--getbool",
dest="getbool",
metavar="SETTING",
help="print setting value, interpreted as a boolean",
)
parser.add_argument(
"--getint",
dest="getint",
metavar="SETTING",
help="print setting value, interpreted as an integer",
)
parser.add_argument(
"--getfloat",
dest="getfloat",
metavar="SETTING",
help="print setting value, interpreted as a float",
)
parser.add_argument(
"--getlist",
dest="getlist",
metavar="SETTING",
help="print setting value, interpreted as a list",
)
def run(self, args: list[str], opts: argparse.Namespace) -> None:
assert self.settings is not None
settings = self.settings
if opts.get:
s = settings.get(opts.get)
if isinstance(s, BaseSettings):
print(json.dumps(s.copy_to_dict()))
else:
print(s)
elif opts.getbool:
print(settings.getbool(opts.getbool))
elif opts.getint:
print(settings.getint(opts.getint))
elif opts.getfloat:
print(settings.getfloat(opts.getfloat))
elif opts.getlist:
print(settings.getlist(opts.getlist))
| Command |
python | airbytehq__airbyte | airbyte-ci/connectors/ci_credentials/ci_credentials/models.py | {
"start": 298,
"end": 1715
} | class ____:
connector_name: str
configuration_file_name: str
value: str
@property
def name(self) -> str:
return self.generate_secret_name(self.connector_name, self.configuration_file_name)
@staticmethod
def generate_secret_name(connector_name: str, configuration_file_name: str) -> str:
"""
Generates an unique GSM secret name.
Format of secret name: SECRET_<CAPITAL_CONNECTOR_NAME>_<OPTIONAL_UNIQUE_FILENAME_PART>__CREDS
Examples:
1. connector_name: source-linnworks, filename: dsdssds_a-b---_---_config.json
=> SECRET_SOURCE-LINNWORKS_DSDSSDS_A-B__CREDS
2. connector_name: source-s3, filename: config.json
=> SECRET_SOURCE-LINNWORKS__CREDS
"""
name_parts = ["secret", connector_name]
filename_wo_ext = configuration_file_name.replace(".json", "")
if filename_wo_ext != DEFAULT_SECRET_FILE:
name_parts.append(filename_wo_ext.replace(DEFAULT_SECRET_FILE, "").strip("_-"))
name_parts.append("_creds")
return "_".join(name_parts).upper()
@property
def directory(self) -> str:
if self.connector_name == "base-normalization":
return f"airbyte-integrations/bases/{self.connector_name}/secrets"
else:
return f"airbyte-integrations/connectors/{self.connector_name}/secrets"
@dataclass
| Secret |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 63626,
"end": 63990
} | class ____(_ConfigBase):
distance_metric: VectorDistances
hnsw: Optional[VectorIndexConfigHNSW]
flat: Optional[VectorIndexConfigFlat]
threshold: Optional[int]
@staticmethod
def vector_index_type() -> str:
return VectorIndexType.DYNAMIC.value
VectorIndexConfigDynamic = _VectorIndexConfigDynamic
@dataclass
| _VectorIndexConfigDynamic |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-notion/llama_index/tools/notion/base.py | {
"start": 494,
"end": 754
} | class ____(BaseModel):
"""Notion search data schema."""
query: str
direction: Optional[str] = None
timestamp: Optional[str] = None
value: Optional[str] = None
property: Optional[str] = None
page_size: int = 100
| NotionSearchDataSchema |
python | realpython__materials | python-langgraph/chains/escalation_check.py | {
"start": 134,
"end": 914
} | class ____(BaseModel):
needs_escalation: bool = Field(
description="""Whether the notice requires escalation according
to specified criteria"""
)
escalation_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"""
Determine whether the following notice received from a regulatory
body requires immediate escalation. Immediate escalation is
required when {escalation_criteria}.
Here's the notice message:
{message}
""",
)
]
)
escalation_check_model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
ESCALATION_CHECK_CHAIN = (
escalation_prompt
| escalation_check_model.with_structured_output(EscalationCheck)
)
| EscalationCheck |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 92897,
"end": 93281
} | class ____(sgqlc.types.Enum):
"""The possible scopes of an alert's dependency.
Enumeration Choices:
* `DEVELOPMENT`: A dependency that is only used in development
* `RUNTIME`: A dependency that is leveraged during application
runtime
"""
__schema__ = github_schema
__choices__ = ("DEVELOPMENT", "RUNTIME")
| RepositoryVulnerabilityAlertDependencyScope |
python | spyder-ide__spyder | spyder/plugins/statusbar/widgets/tests/test_status.py | {
"start": 472,
"end": 1045
} | class ____(QMainWindow):
pass
@pytest.fixture
def status_bar(qtbot):
"""Set up StatusBarWidget."""
window = MainWindowMock()
plugin = StatusBar(parent=window, configuration=CONF)
plugin.remove_status_widgets()
plugin.initialize()
qtbot.addWidget(window)
window.resize(640, 480)
window.show()
return (plugin, window)
def test_status_bar_default_widgets(status_bar, qtbot):
"""Run StatusBarWidget."""
plugin, __ = status_bar
# We create three widgets by default
assert len(plugin.STATUS_WIDGETS) == 3
| MainWindowMock |
python | openai__openai-python | src/openai/resources/conversations/items.py | {
"start": 11525,
"end": 21967
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncItemsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
"""
return AsyncItemsWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> AsyncItemsWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/openai/openai-python#with_streaming_response
"""
return AsyncItemsWithStreamingResponse(self)
async def create(
self,
conversation_id: str,
*,
items: Iterable[ResponseInputItemParam],
include: List[ResponseIncludable] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ConversationItemList:
"""
Create items in a conversation with the given ID.
Args:
items: The items to add to the conversation. You may add up to 20 items at a time.
include: Additional fields to include in the response. See the `include` parameter for
[listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
for more information.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not conversation_id:
raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
return await self._post(
f"/conversations/{conversation_id}/items",
body=await async_maybe_transform({"items": items}, item_create_params.ItemCreateParams),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=await async_maybe_transform({"include": include}, item_create_params.ItemCreateParams),
),
cast_to=ConversationItemList,
)
async def retrieve(
self,
item_id: str,
*,
conversation_id: str,
include: List[ResponseIncludable] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> ConversationItem:
"""
Get a single item from a conversation with the given IDs.
Args:
include: Additional fields to include in the response. See the `include` parameter for
[listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include)
for more information.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not conversation_id:
raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
if not item_id:
raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
return cast(
ConversationItem,
await self._get(
f"/conversations/{conversation_id}/items/{item_id}",
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=await async_maybe_transform({"include": include}, item_retrieve_params.ItemRetrieveParams),
),
cast_to=cast(Any, ConversationItem), # Union types cannot be passed in as arguments in the type system
),
)
def list(
self,
conversation_id: str,
*,
after: str | Omit = omit,
include: List[ResponseIncludable] | Omit = omit,
limit: int | Omit = omit,
order: Literal["asc", "desc"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[ConversationItem, AsyncConversationCursorPage[ConversationItem]]:
"""
List all items for a conversation with the given ID.
Args:
after: An item ID to list items after, used in pagination.
include: Specify additional output data to include in the model response. Currently
supported values are:
- `web_search_call.action.sources`: Include the sources of the web search tool
call.
- `code_interpreter_call.outputs`: Includes the outputs of python code execution
in code interpreter tool call items.
- `computer_call_output.output.image_url`: Include image urls from the computer
call output.
- `file_search_call.results`: Include the search results of the file search tool
call.
- `message.input_image.image_url`: Include image urls from the input message.
- `message.output_text.logprobs`: Include logprobs with assistant messages.
- `reasoning.encrypted_content`: Includes an encrypted version of reasoning
tokens in reasoning item outputs. This enables reasoning items to be used in
multi-turn conversations when using the Responses API statelessly (like when
the `store` parameter is set to `false`, or when an organization is enrolled
in the zero data retention program).
limit: A limit on the number of objects to be returned. Limit can range between 1 and
100, and the default is 20.
order: The order to return the input items in. Default is `desc`.
- `asc`: Return the input items in ascending order.
- `desc`: Return the input items in descending order.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not conversation_id:
raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
return self._get_api_list(
f"/conversations/{conversation_id}/items",
page=AsyncConversationCursorPage[ConversationItem],
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform(
{
"after": after,
"include": include,
"limit": limit,
"order": order,
},
item_list_params.ItemListParams,
),
),
model=cast(Any, ConversationItem), # Union types cannot be passed in as arguments in the type system
)
async def delete(
self,
item_id: str,
*,
conversation_id: str,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Conversation:
"""
Delete an item from a conversation with the given IDs.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not conversation_id:
raise ValueError(f"Expected a non-empty value for `conversation_id` but received {conversation_id!r}")
if not item_id:
raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}")
return await self._delete(
f"/conversations/{conversation_id}/items/{item_id}",
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Conversation,
)
| AsyncItems |
python | django__django | tests/admin_views/admin.py | {
"start": 16026,
"end": 16291
} | class ____(forms.ModelForm):
model = FieldOverridePost
class Meta:
help_texts = {
"posted": "Overridden help text for the date",
}
labels = {
"public": "Overridden public label",
}
| FieldOverridePostForm |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/messages/beta_message_batch_individual_response.py | {
"start": 235,
"end": 828
} | class ____(BaseModel):
custom_id: str
"""Developer-provided ID created for each request in a Message Batch.
Useful for matching results to requests, as results may be given out of request
order.
Must be unique for each request within the Message Batch.
"""
result: BetaMessageBatchResult
"""Processing result for this request.
Contains a Message output if processing was successful, an error response if
processing failed, or the reason why processing was not attempted, such as
cancellation or expiration.
"""
| BetaMessageBatchIndividualResponse |
python | getsentry__sentry-python | sentry_sdk/tracing_utils.py | {
"start": 11670,
"end": 18103
} | class ____:
"""
The PropagationContext represents the data of a trace in Sentry.
"""
__slots__ = (
"_trace_id",
"_span_id",
"parent_span_id",
"parent_sampled",
"baggage",
)
def __init__(
self,
trace_id=None, # type: Optional[str]
span_id=None, # type: Optional[str]
parent_span_id=None, # type: Optional[str]
parent_sampled=None, # type: Optional[bool]
dynamic_sampling_context=None, # type: Optional[Dict[str, str]]
baggage=None, # type: Optional[Baggage]
):
# type: (...) -> None
self._trace_id = trace_id
"""The trace id of the Sentry trace."""
self._span_id = span_id
"""The span id of the currently executing span."""
self.parent_span_id = parent_span_id
"""The id of the parent span that started this span.
The parent span could also be a span in an upstream service."""
self.parent_sampled = parent_sampled
"""Boolean indicator if the parent span was sampled.
Important when the parent span originated in an upstream service,
because we want to sample the whole trace, or nothing from the trace."""
self.baggage = baggage
"""Parsed baggage header that is used for dynamic sampling decisions."""
"""DEPRECATED this only exists for backwards compat of constructor."""
if baggage is None and dynamic_sampling_context is not None:
self.baggage = Baggage(dynamic_sampling_context)
@classmethod
def from_incoming_data(cls, incoming_data):
# type: (Dict[str, Any]) -> Optional[PropagationContext]
normalized_data = normalize_incoming_data(incoming_data)
sentry_trace_header = normalized_data.get(SENTRY_TRACE_HEADER_NAME)
sentrytrace_data = extract_sentrytrace_data(sentry_trace_header)
if sentrytrace_data is None:
return None
propagation_context = PropagationContext()
propagation_context.update(sentrytrace_data)
baggage_header = normalized_data.get(BAGGAGE_HEADER_NAME)
if baggage_header:
propagation_context.baggage = Baggage.from_incoming_header(baggage_header)
propagation_context._fill_sample_rand()
return propagation_context
@property
def trace_id(self):
# type: () -> str
"""The trace id of the Sentry trace."""
if not self._trace_id:
# New trace, don't fill in sample_rand
self._trace_id = uuid.uuid4().hex
return self._trace_id
@trace_id.setter
def trace_id(self, value):
# type: (str) -> None
self._trace_id = value
@property
def span_id(self):
# type: () -> str
"""The span id of the currently executed span."""
if not self._span_id:
self._span_id = uuid.uuid4().hex[16:]
return self._span_id
@span_id.setter
def span_id(self, value):
# type: (str) -> None
self._span_id = value
@property
def dynamic_sampling_context(self):
# type: () -> Optional[Dict[str, Any]]
return self.baggage.dynamic_sampling_context() if self.baggage else None
def update(self, other_dict):
# type: (Dict[str, Any]) -> None
"""
Updates the PropagationContext with data from the given dictionary.
"""
for key, value in other_dict.items():
try:
setattr(self, key, value)
except AttributeError:
pass
def __repr__(self):
# type: (...) -> str
return "<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} baggage={}>".format(
self._trace_id,
self._span_id,
self.parent_span_id,
self.parent_sampled,
self.baggage,
)
def _fill_sample_rand(self):
# type: () -> None
"""
Ensure that there is a valid sample_rand value in the baggage.
If there is a valid sample_rand value in the baggage, we keep it.
Otherwise, we generate a sample_rand value according to the following:
- If we have a parent_sampled value and a sample_rate in the DSC, we compute
a sample_rand value randomly in the range:
- [0, sample_rate) if parent_sampled is True,
- or, in the range [sample_rate, 1) if parent_sampled is False.
- If either parent_sampled or sample_rate is missing, we generate a random
value in the range [0, 1).
The sample_rand is deterministically generated from the trace_id, if present.
This function does nothing if there is no baggage.
"""
if self.baggage is None:
return
sample_rand = try_convert(float, self.baggage.sentry_items.get("sample_rand"))
if sample_rand is not None and 0 <= sample_rand < 1:
# sample_rand is present and valid, so don't overwrite it
return
# Get the sample rate and compute the transformation that will map the random value
# to the desired range: [0, 1), [0, sample_rate), or [sample_rate, 1).
sample_rate = try_convert(float, self.baggage.sentry_items.get("sample_rate"))
lower, upper = _sample_rand_range(self.parent_sampled, sample_rate)
try:
sample_rand = _generate_sample_rand(self.trace_id, interval=(lower, upper))
except ValueError:
# ValueError is raised if the interval is invalid, i.e. lower >= upper.
# lower >= upper might happen if the incoming trace's sampled flag
# and sample_rate are inconsistent, e.g. sample_rate=0.0 but sampled=True.
# We cannot generate a sensible sample_rand value in this case.
logger.debug(
f"Could not backfill sample_rand, since parent_sampled={self.parent_sampled} "
f"and sample_rate={sample_rate}."
)
return
self.baggage.sentry_items["sample_rand"] = f"{sample_rand:.6f}" # noqa: E231
def _sample_rand(self):
# type: () -> Optional[str]
"""Convenience method to get the sample_rand value from the baggage."""
if self.baggage is None:
return None
return self.baggage.sentry_items.get("sample_rand")
| PropagationContext |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/utils.py | {
"start": 3280,
"end": 3393
} | class ____(TypedDict):
samplingValue: SamplingValue
type: str
condition: RuleCondition
id: int
| Rule |
python | google__jax | tests/dynamic_api_test.py | {
"start": 36955,
"end": 48836
} | class ____(jtu.JaxTestCase):
def test_jit_basic(self):
@jax.jit
def f(i):
return jnp.sum(jnp.ones(i, dtype='float32'))
self.assertAllClose(f(3), jnp.array(3., dtype='float32'), check_dtypes=True)
def test_jit_basic_2(self):
count = 0
@jax.jit(abstracted_axes=('n',))
def f(x):
nonlocal count
count += 1
return jnp.sum(x)
x = f(np.arange(3))
y = f(np.arange(4))
self.assertAllClose(x, 3., check_dtypes=False)
self.assertAllClose(y, 6., check_dtypes=False)
self.assertEqual(count, 1)
def test_jit_polymorphic_output(self):
# like test_jit_basic, but without the jnp.sum!
count = 0
@jax.jit
def f(i):
nonlocal count
count += 1
return jnp.ones(i, dtype='float32')
self.assertAllClose(f(3), np.ones(3, dtype='float32'), check_dtypes=True)
self.assertAllClose(f(4), np.ones(4, dtype='float32'), check_dtypes=True)
self.assertEqual(count, 1)
@unittest.skip('TODO: need typechecking rule for concatenate')
def test_concatenate(self):
@jax.jit(abstracted_axes=({0: 'n'},))
def f(x): # x: f32[n, 4]
return jnp.concatenate([x, x, x], axis=0)
f(np.ones((5, 4), dtype=np.float32))
# TODO: add assertions
def test_reshape(self):
@jax.jit(abstracted_axes=({0: 'n'},))
def f(x): # x: f32[n, 4]
return jnp.reshape(x, (2, -1))
f(np.ones((5, 4), dtype=np.float32))
# TODO: add assertions
def test_nested(self):
@jax.jit
def nested_f(x): # f32[h, v] -> f32[h, v]
# A nested call that needs shape variables
return jnp.sin(x)
@jax.jit(abstracted_axes=({0: 'h', 1: 'v'},))
def f(x): # f32[h, w] -> f32[h, w]
return jnp.sin(x) + jax.jit(nested_f)(x)
f(np.ones((3, 5), dtype=np.float32))
# TODO: add assertions
def test_nested_arange(self):
def nested_f(x): # f32[h, v] -> f32[h, v]
# A nested call that needs to compute with shapes
return jnp.arange(x.shape[0] * x.shape[1], dtype=x.dtype).reshape(x.shape)
@jax.jit(abstracted_axes=({0: 'h', 1: 'w'},))
def f(x): # f32[h, w] -> f32[h, w]
return x + jax.jit(nested_f)(x)
f(np.ones((3, 5), dtype=np.float32))
# TODO: add assertions
def test_transpose(self):
# see also https://github.com/iree-org/iree-jax/issues/57
@jax.jit(abstracted_axes=({0: 'h', 1: 'w'},))
def f(x): # f32[h, w] -> f32[w, h]
return x.T
f(np.ones((3, 5), dtype=np.float32)) # doesn't crash
# TODO: add assertions
def test_matmul(self):
@jax.jit(abstracted_axes=({0: 'w', 1: 'w'},))
def f(x): # f32[w, w] -> f32[w, w]
return jnp.matmul(x, x)
f(np.ones((5, 5), dtype=np.float32))
# TODO: add assertions
def test_matmul_shape_error(self):
@jax.jit(abstracted_axes=({0: 'h', 1: 'w'},))
def f(x): # f32[h, w] -> error
return jnp.matmul(x, x)
# TODO(necula): improve error message, print actual shapes
with self.assertRaisesRegex(TypeError,
re.escape("dot_general requires contracting dimensions to have the same shape, got")):
f(np.ones((5, 5), dtype=np.float32))
@unittest.skip("TODO: investigate failure")
def test_cond(self):
@jax.jit(abstracted_axes=({0: 'w', 1: 'w'},))
def f(x): # f32[w, w] -> f32[w, w]
return lax.cond(True,
lambda x: jnp.sin(x),
lambda x: jnp.matmul(x, x), x)
f(np.ones((5, 5), dtype=np.float32))
# TODO: add assertions
def test_arange(self):
@jax.jit(abstracted_axes=({0: 'w'},))
def f(x): # f32[w] -> f32[w]
return jnp.arange(x.shape[0], dtype=x.dtype) + x
f(np.ones((5,), dtype=np.float32))
# TODO: add assertions
def test_broadcast(self):
@jax.jit(abstracted_axes=({0: 'w'},))
def f(x): # f32[w] -> f32[w, w]
return jnp.broadcast_to(x, (x.shape[0], x.shape[0]))
f(np.ones((5,), dtype=np.float32))
# TODO: add assertions
def test_zeros(self):
@jax.jit(abstracted_axes=({0: 'w'},))
def f(x): # f32[w] -> f32[w]
return jnp.zeros(x.shape[0], dtype=x.dtype) + x
f(np.ones((5,), dtype=np.float32))
# TODO: add assertions
def test_stack(self):
@jax.jit(abstracted_axes=({0: 'w'},))
def f(x):
return jnp.stack([jnp.sin(x), jnp.cos(x)])
f(np.ones((5,), dtype=np.float32))
# TODO: add assertions
def test_jit_dependent_pair_output(self):
# Like the above 'polymorhpic output' test, but now with a `2 * n`!
count = 0
@jax.jit
def f(n):
nonlocal count
count += 1
return jnp.arange(2 * n)
x = f(3)
y = f(4)
self.assertAllClose(x, jnp.arange(2 * 3), check_dtypes=False)
self.assertAllClose(y, jnp.arange(2 * 4), check_dtypes=False)
self.assertEqual(count, 1)
@unittest.skip("revising slicing logic")
def test_slicing_basic(self):
f = jax.jit(lambda x, n: jnp.sum(x[:n]))
# TODO(mattjj): revise getslice, add typecheck rule for it, enable checks
with jax.enable_checks(False):
ans = f(jnp.arange(10), 3)
expected = jnp.sum(jnp.arange(10)[:3])
self.assertAllClose(ans, expected, check_dtypes=True)
# TODO(mattjj,dougalm,phawkins): debug iree failure, "failed to legalize
# operation 'while' that was explicitly marked illegal"
@unittest.skip("revising slicing logic")
def test_scan_basic(self):
def cumsum(x):
def body(i, _):
return i + 1, jnp.sum(x[:i+1])
_, ans = lax.scan(body, 0, None, length=len(x))
return ans
x = jnp.array([3, 1, 4, 1, 5, 9])
with jax.enable_checks(False):
ans = cumsum(x)
expected = jnp.cumsum(x)
self.assertAllClose(ans, expected, check_dtypes=False)
def test_jit_of_broadcast(self):
x = jax.jit(jnp.ones)(3)
self.assertAllClose(x, jnp.ones(3))
def test_jit_of_broadcast2(self):
x = jax.jit(lambda n: jnp.ones(2 * n))(3)
self.assertAllClose(x, jnp.ones(2 * 3))
def test_mlp_autodiff_dynamic_batch(self):
count = 0
def predict(params, inputs):
for W, b in params:
outputs = jnp.dot(inputs, W) + b
inputs = jnp.maximum(0, outputs)
return outputs
def loss_ref(params, batch):
nonlocal count
count += 1 # count retraces
inputs, targets = batch
predictions = predict(params, inputs)
return jnp.sum((predictions - targets) ** 2)
loss = jax.jit(loss_ref, abstracted_axes=({}, {0: 'n'}))
params = [(jnp.ones((784, 256)), jnp.ones(256)),
(jnp.ones((256, 10)), jnp.ones( 10))]
# two different size batches
batch1 = (inputs, targets) = (jnp.ones((128, 784)), jnp.ones((128, 10)))
batch2 = (inputs, targets) = (jnp.ones((32, 784)), jnp.ones((32, 10)))
_ = loss(params, batch1)
_ = loss(params, batch2)
self.assertEqual(count, 1)
_ = jax.grad(loss)(params, batch1)
_ = jax.grad(loss)(params, batch2)
self.assertEqual(count, 2)
ans = loss( params, batch1)
expected = loss_ref(params, batch1)
self.assertAllClose(ans, expected)
ans = jax.grad(loss )(params, batch1)
expected = jax.grad(loss_ref)(params, batch1)
self.assertAllClose(ans, expected)
@jax.enable_checks(False) # TODO(mattjj): upgrade typecompat to handle bints
def test_mlp_autodiff_dynamic_batch_bint(self):
count = 0
def predict(params, inputs):
for W, b in params:
outputs = jnp.dot(inputs, W) + b
inputs = jnp.maximum(0, outputs)
return outputs
def loss_ref(params, batch):
nonlocal count
count += 1 # count traces
inputs, targets = batch
predictions = predict(params, inputs)
return jnp.sum((predictions - targets) ** 2)
loss = jax.jit(loss_ref, abstracted_axes=({}, {0: 'n'}))
params = [(jnp.ones((784, 256)), jnp.ones(256)),
(jnp.ones((256, 10)), jnp.ones( 10))]
# two different batch sizes *with bints*
bs1 = jax.lax.convert_element_type(128, core.bint(128))
batch1 = (jnp.ones((bs1, 784)), jnp.ones((bs1, 10)))
bs2 = jax.lax.convert_element_type(32, core.bint(128))
batch2 = (jnp.ones((bs2, 784)), jnp.ones((bs2, 10)))
# count retraces (and don't crash)
self.assertEqual(count, 0)
_ = jax.grad(loss)(params, batch1)
self.assertEqual(count, 1)
g2 = jax.grad(loss)(params, batch2)
self.assertEqual(count, 1) # cache hit!
# check the numbers make sense
batch = (jnp.ones((32, 784)), jnp.ones((32, 10)))
g2_expected = jax.grad(loss_ref)(params, batch)
self.assertAllClose(g2, g2_expected, check_dtypes=False,
atol=1e-3, rtol=1e-3)
def test_bint_basic(self):
d = lax.convert_element_type(3, core.bint(5))
self.assertEqual(str(d), '3{≤5}')
@jax.jit
def f(d):
jnp.sin(3.) # don't have an empty jaxpr
return d
f(d) # doesn't crash
def test_bint_iota(self):
def f(d):
return jnp.arange(d, dtype='int32')
y = f(lax.convert_element_type(3, core.bint(5)))
self.assertIsInstance(y, core.DArray)
self.assertAllClose(y._data, np.arange(5), check_dtypes=False)
d = lax.convert_element_type(3, core.bint(5))
y = jax.jit(f)(d)
self.assertIsInstance(y, core.DArray)
self.assertAllClose(y._data, np.arange(5), check_dtypes=False)
def test_bint_compilation_cache(self):
count = 0
@jax.jit
def f(n):
nonlocal count
count += 1
return jnp.zeros(n)
f(lax.convert_element_type(3, core.bint(5)))
f(lax.convert_element_type(4, core.bint(5)))
self.assertEqual(count, 1)
def test_bint_compilation_cache2(self):
count = 0
@jax.jit(abstracted_axes=('n',))
def f(x):
nonlocal count
count += 1
return x.sum()
d = lax.convert_element_type(3, core.bint(5))
x = jnp.arange(d)
y = f(x)
self.assertEqual(y, 3)
self.assertEqual(count, 1)
d = lax.convert_element_type(4, core.bint(5))
x = jnp.arange(d)
y = f(x)
self.assertEqual(y, 6)
self.assertEqual(count, 1)
d = lax.convert_element_type(4, core.bint(6))
x = jnp.arange(d)
y = f(x)
self.assertEqual(y, 6)
self.assertEqual(count, 2)
@unittest.skip('do we want to support this?')
def test_bint_add(self):
d = lax.convert_element_type(4, core.bint(6))
x = jnp.arange(d)
@jax.jit
def f(x):
return x + x
f(x) # doesn't crash
def test_lower_abstracted_axes(self):
@jax.jit(abstracted_axes=('n',))
def f(x):
return x.sum()
f_lowered = f.lower(np.arange(3, dtype='int32'))
mlir_str = f_lowered.compiler_ir()
self.assertIn('tensor<?xi32>', str(mlir_str))
def test_lower_abstracted_axes_shapedtypestruct(self):
@jax.jit(abstracted_axes=('n',))
def f(x):
return x.sum()
f_lowered = f.lower(jax.ShapeDtypeStruct((3,), np.int32))
mlir_str = f_lowered.compiler_ir()
self.assertIn('tensor<?xi32>', str(mlir_str))
def test_slicing_basic_lower(self):
@jax.jit(abstracted_axes=(None, 'n'))
def f(x):
return x[0]
f.lower(jnp.zeros((3, 4))).compiler_ir() # doesn't crash
def test_slicing_basic_execute(self):
@jax.jit(abstracted_axes=(None, 'n'))
def f(x):
return x[0]
y = f(jnp.arange(3 * 4).reshape(3, 4))
self.assertAllClose(y, jnp.array([0, 1, 2, 3]))
def test_gather_basic_bounded(self):
x = jnp.arange(3. * 4.).reshape(3, 4)
def f(i):
return x[i]
sz = jax.lax.convert_element_type(2, core.bint(3))
idx = jnp.arange(sz)
y = jax.jit(jax.vmap(f), abstracted_axes=('n',))(idx)
self.assertIsInstance(y, core.DArray)
self.assertEqual(y.shape, (sz, 4))
self.assertAllClose(y._data, x)
@unittest.skip("currently unmaintained")
@jtu.with_config(jax_dynamic_shapes=True, jax_numpy_rank_promotion="allow",
jax_traceback_filtering='off')
| DynamicShapeExecutionTest |
python | plotly__plotly.py | plotly/graph_objs/scattergl/_line.py | {
"start": 233,
"end": 4250
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergl"
_path_str = "scattergl.line"
_valid_props = {"color", "dash", "shape", "width"}
@property
def color(self):
"""
Sets the line color.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def dash(self):
"""
Sets the style of the lines.
The 'dash' property is an enumeration that may be specified as:
- One of the following enumeration values:
['dash', 'dashdot', 'dot', 'longdash', 'longdashdot',
'solid']
Returns
-------
Any
"""
return self["dash"]
@dash.setter
def dash(self, val):
self["dash"] = val
@property
def shape(self):
"""
Determines the line shape. The values correspond to step-wise
line shapes.
The 'shape' property is an enumeration that may be specified as:
- One of the following enumeration values:
['linear', 'hv', 'vh', 'hvh', 'vhv']
Returns
-------
Any
"""
return self["shape"]
@shape.setter
def shape(self, val):
self["shape"] = val
@property
def width(self):
"""
Sets the line width (in px).
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the line color.
dash
Sets the style of the lines.
shape
Determines the line shape. The values correspond to
step-wise line shapes.
width
Sets the line width (in px).
"""
def __init__(
self, arg=None, color=None, dash=None, shape=None, width=None, **kwargs
):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scattergl.Line`
color
Sets the line color.
dash
Sets the style of the lines.
shape
Determines the line shape. The values correspond to
step-wise line shapes.
width
Sets the line width (in px).
Returns
-------
Line
"""
super().__init__("line")
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.scattergl.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattergl.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("dash", arg, dash)
self._set_property("shape", arg, shape)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | redis__redis-py | redis/_parsers/commands.py | {
"start": 1282,
"end": 3073
} | class ____:
def _get_pubsub_keys(self, *args):
"""
Get the keys from pubsub command.
Although PubSub commands have predetermined key locations, they are not
supported in the 'COMMAND's output, so the key positions are hardcoded
in this method
"""
if len(args) < 2:
# The command has no keys in it
return None
args = [str_if_bytes(arg) for arg in args]
command = args[0].upper()
keys = None
if command == "PUBSUB":
# the second argument is a part of the command name, e.g.
# ['PUBSUB', 'NUMSUB', 'foo'].
pubsub_type = args[1].upper()
if pubsub_type in ["CHANNELS", "NUMSUB", "SHARDCHANNELS", "SHARDNUMSUB"]:
keys = args[2:]
elif command in ["SUBSCRIBE", "PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE"]:
# format example:
# SUBSCRIBE channel [channel ...]
keys = list(args[1:])
elif command in ["PUBLISH", "SPUBLISH"]:
# format example:
# PUBLISH channel message
keys = [args[1]]
return keys
def parse_subcommand(self, command, **options):
cmd_dict = {}
cmd_name = str_if_bytes(command[0])
cmd_dict["name"] = cmd_name
cmd_dict["arity"] = int(command[1])
cmd_dict["flags"] = [str_if_bytes(flag) for flag in command[2]]
cmd_dict["first_key_pos"] = command[3]
cmd_dict["last_key_pos"] = command[4]
cmd_dict["step_count"] = command[5]
if len(command) > 7:
cmd_dict["tips"] = command[7]
cmd_dict["key_specifications"] = command[8]
cmd_dict["subcommands"] = command[9]
return cmd_dict
| AbstractCommandsParser |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_by_id.py | {
"start": 221,
"end": 324
} | class ____(GQLResult):
artifact: Optional[ArtifactFragment]
ArtifactByID.model_rebuild()
| ArtifactByID |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 620,
"end": 1039
} | class ____(
scale_continuous[Literal["legend", "colorbar"] | None],
):
"""
Base class for all continuous color scales
"""
_aesthetics = ["color"]
_: KW_ONLY
guide: Literal["legend", "colorbar"] | None = "colorbar"
na_value: str = "#7F7F7F"
"""
Color of missing values.
"""
# Discrete color scales #
# Note: plotnine operates in the hcl space
@dataclass
| _scale_color_continuous |
python | networkx__networkx | networkx/algorithms/planarity.py | {
"start": 25509,
"end": 49887
} | class ____(nx.DiGraph):
"""Represents a planar graph with its planar embedding.
The planar embedding is given by a `combinatorial embedding
<https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.
.. note:: `check_planarity` is the preferred way to check if a graph is planar.
**Neighbor ordering:**
In comparison to a usual graph structure, the embedding also stores the
order of all neighbors for every vertex.
The order of the neighbors can be given in clockwise (cw) direction or
counterclockwise (ccw) direction. This order is stored as edge attributes
in the underlying directed graph. For the edge (u, v) the edge attribute
'cw' is set to the neighbor of u that follows immediately after v in
clockwise direction.
In order for a PlanarEmbedding to be valid it must fulfill multiple
conditions. It is possible to check if these conditions are fulfilled with
the method :meth:`check_structure`.
The conditions are:
* Edges must go in both directions (because the edge attributes differ)
* Every edge must have a 'cw' and 'ccw' attribute which corresponds to a
correct planar embedding.
As long as a PlanarEmbedding is invalid only the following methods should
be called:
* :meth:`add_half_edge`
* :meth:`connect_components`
Even though the graph is a subclass of nx.DiGraph, it can still be used
for algorithms that require undirected graphs, because the method
:meth:`is_directed` is overridden. This is possible, because a valid
PlanarGraph must have edges in both directions.
**Half edges:**
In methods like `add_half_edge` the term "half-edge" is used, which is
a term that is used in `doubly connected edge lists
<https://en.wikipedia.org/wiki/Doubly_connected_edge_list>`_. It is used
to emphasize that the edge is only in one direction and there exists
another half-edge in the opposite direction.
While conventional edges always have two faces (including outer face) next
to them, it is possible to assign each half-edge *exactly one* face.
For a half-edge (u, v) that is oriented such that u is below v then the
face that belongs to (u, v) is to the right of this half-edge.
See Also
--------
is_planar :
Preferred way to check if an existing graph is planar.
check_planarity :
A convenient way to create a `PlanarEmbedding`. If not planar,
it returns a subgraph that shows this.
Examples
--------
Create an embedding of a star graph (compare `nx.star_graph(3)`):
>>> G = nx.PlanarEmbedding()
>>> G.add_half_edge(0, 1)
>>> G.add_half_edge(0, 2, ccw=1)
>>> G.add_half_edge(0, 3, ccw=2)
>>> G.add_half_edge(1, 0)
>>> G.add_half_edge(2, 0)
>>> G.add_half_edge(3, 0)
Alternatively the same embedding can also be defined in counterclockwise
orientation. The following results in exactly the same PlanarEmbedding:
>>> G = nx.PlanarEmbedding()
>>> G.add_half_edge(0, 1)
>>> G.add_half_edge(0, 3, cw=1)
>>> G.add_half_edge(0, 2, cw=3)
>>> G.add_half_edge(1, 0)
>>> G.add_half_edge(2, 0)
>>> G.add_half_edge(3, 0)
After creating a graph, it is possible to validate that the PlanarEmbedding
object is correct:
>>> G.check_structure()
"""
def __init__(self, incoming_graph_data=None, **attr):
super().__init__(incoming_graph_data=incoming_graph_data, **attr)
self.add_edge = self._forbidden
self.add_edges_from = self._forbidden
self.add_weighted_edges_from = self._forbidden
def _forbidden(self, *args, **kwargs):
"""Forbidden operation
Any edge additions to a PlanarEmbedding should be done using
method `add_half_edge`.
"""
raise NotImplementedError(
"Use `add_half_edge` method to add edges to a PlanarEmbedding."
)
def get_data(self):
"""Converts the adjacency structure into a better readable structure.
Returns
-------
embedding : dict
A dict mapping all nodes to a list of neighbors sorted in
clockwise order.
See Also
--------
set_data
"""
embedding = {}
for v in self:
embedding[v] = list(self.neighbors_cw_order(v))
return embedding
def set_data(self, data):
"""Inserts edges according to given sorted neighbor list.
The input format is the same as the output format of get_data().
Parameters
----------
data : dict
A dict mapping all nodes to a list of neighbors sorted in
clockwise order.
See Also
--------
get_data
"""
for v in data:
ref = None
for w in reversed(data[v]):
self.add_half_edge(v, w, cw=ref)
ref = w
def remove_node(self, n):
"""Remove node n.
Removes the node n and all adjacent edges, updating the
PlanarEmbedding to account for any resulting edge removal.
Attempting to remove a non-existent node will raise an exception.
Parameters
----------
n : node
A node in the graph
Raises
------
NetworkXError
If n is not in the graph.
See Also
--------
remove_nodes_from
"""
try:
for u in self._pred[n]:
succs_u = self._succ[u]
un_cw = succs_u[n]["cw"]
un_ccw = succs_u[n]["ccw"]
del succs_u[n]
del self._pred[u][n]
if n != un_cw:
succs_u[un_cw]["ccw"] = un_ccw
succs_u[un_ccw]["cw"] = un_cw
del self._node[n]
del self._succ[n]
del self._pred[n]
except KeyError as err: # NetworkXError if n not in self
raise nx.NetworkXError(
f"The node {n} is not in the planar embedding."
) from err
nx._clear_cache(self)
def remove_nodes_from(self, nodes):
"""Remove multiple nodes.
Parameters
----------
nodes : iterable container
A container of nodes (list, dict, set, etc.). If a node
in the container is not in the graph it is silently ignored.
See Also
--------
remove_node
Notes
-----
When removing nodes from an iterator over the graph you are changing,
a `RuntimeError` will be raised with message:
`RuntimeError: dictionary changed size during iteration`. This
happens when the graph's underlying dictionary is modified during
iteration. To avoid this error, evaluate the iterator into a separate
object, e.g. by using `list(iterator_of_nodes)`, and pass this
object to `G.remove_nodes_from`.
"""
for n in nodes:
if n in self._node:
self.remove_node(n)
# silently skip non-existing nodes
def neighbors_cw_order(self, v):
"""Generator for the neighbors of v in clockwise order.
Parameters
----------
v : node
Yields
------
node
"""
succs = self._succ[v]
if not succs:
# v has no neighbors
return
start_node = next(reversed(succs))
yield start_node
current_node = succs[start_node]["cw"]
while start_node != current_node:
yield current_node
current_node = succs[current_node]["cw"]
def add_half_edge(self, start_node, end_node, *, cw=None, ccw=None):
"""Adds a half-edge from `start_node` to `end_node`.
If the half-edge is not the first one out of `start_node`, a reference
node must be provided either in the clockwise (parameter `cw`) or in
the counterclockwise (parameter `ccw`) direction. Only one of `cw`/`ccw`
can be specified (or neither in the case of the first edge).
Note that specifying a reference in the clockwise (`cw`) direction means
inserting the new edge in the first counterclockwise position with
respect to the reference (and vice-versa).
Parameters
----------
start_node : node
Start node of inserted edge.
end_node : node
End node of inserted edge.
cw, ccw: node
End node of reference edge.
Omit or pass `None` if adding the first out-half-edge of `start_node`.
Raises
------
NetworkXException
If the `cw` or `ccw` node is not a successor of `start_node`.
If `start_node` has successors, but neither `cw` or `ccw` is provided.
If both `cw` and `ccw` are specified.
See Also
--------
connect_components
"""
succs = self._succ.get(start_node)
if succs:
# there is already some edge out of start_node
leftmost_nbr = next(reversed(self._succ[start_node]))
if cw is not None:
if cw not in succs:
raise nx.NetworkXError("Invalid clockwise reference node.")
if ccw is not None:
raise nx.NetworkXError("Only one of cw/ccw can be specified.")
ref_ccw = succs[cw]["ccw"]
super().add_edge(start_node, end_node, cw=cw, ccw=ref_ccw)
succs[ref_ccw]["cw"] = end_node
succs[cw]["ccw"] = end_node
# when (cw == leftmost_nbr), the newly added neighbor is
# already at the end of dict self._succ[start_node] and
# takes the place of the former leftmost_nbr
move_leftmost_nbr_to_end = cw != leftmost_nbr
elif ccw is not None:
if ccw not in succs:
raise nx.NetworkXError("Invalid counterclockwise reference node.")
ref_cw = succs[ccw]["cw"]
super().add_edge(start_node, end_node, cw=ref_cw, ccw=ccw)
succs[ref_cw]["ccw"] = end_node
succs[ccw]["cw"] = end_node
move_leftmost_nbr_to_end = True
else:
raise nx.NetworkXError(
"Node already has out-half-edge(s), either cw or ccw reference node required."
)
if move_leftmost_nbr_to_end:
# LRPlanarity (via self.add_half_edge_first()) requires that
# we keep track of the leftmost neighbor, which we accomplish
# by keeping it as the last key in dict self._succ[start_node]
succs[leftmost_nbr] = succs.pop(leftmost_nbr)
else:
if cw is not None or ccw is not None:
raise nx.NetworkXError("Invalid reference node.")
# adding the first edge out of start_node
super().add_edge(start_node, end_node, ccw=end_node, cw=end_node)
def check_structure(self):
"""Runs without exceptions if this object is valid.
Checks that the following properties are fulfilled:
* Edges go in both directions (because the edge attributes differ).
* Every edge has a 'cw' and 'ccw' attribute which corresponds to a
correct planar embedding.
Running this method verifies that the underlying Graph must be planar.
Raises
------
NetworkXException
This exception is raised with a short explanation if the
PlanarEmbedding is invalid.
"""
# Check fundamental structure
for v in self:
try:
sorted_nbrs = set(self.neighbors_cw_order(v))
except KeyError as err:
msg = f"Bad embedding. Missing orientation for a neighbor of {v}"
raise nx.NetworkXException(msg) from err
unsorted_nbrs = set(self[v])
if sorted_nbrs != unsorted_nbrs:
msg = "Bad embedding. Edge orientations not set correctly."
raise nx.NetworkXException(msg)
for w in self[v]:
# Check if opposite half-edge exists
if not self.has_edge(w, v):
msg = "Bad embedding. Opposite half-edge is missing."
raise nx.NetworkXException(msg)
# Check planarity
counted_half_edges = set()
for component in nx.connected_components(self):
if len(component) == 1:
# Don't need to check single node component
continue
num_nodes = len(component)
num_half_edges = 0
num_faces = 0
for v in component:
for w in self.neighbors_cw_order(v):
num_half_edges += 1
if (v, w) not in counted_half_edges:
# We encountered a new face
num_faces += 1
# Mark all half-edges belonging to this face
self.traverse_face(v, w, counted_half_edges)
num_edges = num_half_edges // 2 # num_half_edges is even
if num_nodes - num_edges + num_faces != 2:
# The result does not match Euler's formula
msg = "Bad embedding. The graph does not match Euler's formula"
raise nx.NetworkXException(msg)
def add_half_edge_ccw(self, start_node, end_node, reference_neighbor):
"""Adds a half-edge from start_node to end_node.
The half-edge is added counter clockwise next to the existing half-edge
(start_node, reference_neighbor).
Parameters
----------
start_node : node
Start node of inserted edge.
end_node : node
End node of inserted edge.
reference_neighbor: node
End node of reference edge.
Raises
------
NetworkXException
If the reference_neighbor does not exist.
See Also
--------
add_half_edge
add_half_edge_cw
connect_components
"""
self.add_half_edge(start_node, end_node, cw=reference_neighbor)
def add_half_edge_cw(self, start_node, end_node, reference_neighbor):
"""Adds a half-edge from start_node to end_node.
The half-edge is added clockwise next to the existing half-edge
(start_node, reference_neighbor).
Parameters
----------
start_node : node
Start node of inserted edge.
end_node : node
End node of inserted edge.
reference_neighbor: node
End node of reference edge.
Raises
------
NetworkXException
If the reference_neighbor does not exist.
See Also
--------
add_half_edge
add_half_edge_ccw
connect_components
"""
self.add_half_edge(start_node, end_node, ccw=reference_neighbor)
def remove_edge(self, u, v):
"""Remove the edge between u and v.
Parameters
----------
u, v : nodes
Remove the half-edges (u, v) and (v, u) and update the
edge ordering around the removed edge.
Raises
------
NetworkXError
If there is not an edge between u and v.
See Also
--------
remove_edges_from : remove a collection of edges
"""
try:
succs_u = self._succ[u]
succs_v = self._succ[v]
uv_cw = succs_u[v]["cw"]
uv_ccw = succs_u[v]["ccw"]
vu_cw = succs_v[u]["cw"]
vu_ccw = succs_v[u]["ccw"]
del succs_u[v]
del self._pred[v][u]
del succs_v[u]
del self._pred[u][v]
if v != uv_cw:
succs_u[uv_cw]["ccw"] = uv_ccw
succs_u[uv_ccw]["cw"] = uv_cw
if u != vu_cw:
succs_v[vu_cw]["ccw"] = vu_ccw
succs_v[vu_ccw]["cw"] = vu_cw
except KeyError as err:
raise nx.NetworkXError(
f"The edge {u}-{v} is not in the planar embedding."
) from err
nx._clear_cache(self)
def remove_edges_from(self, ebunch):
"""Remove all edges specified in ebunch.
Parameters
----------
ebunch: list or container of edge tuples
Each pair of half-edges between the nodes given in the tuples
will be removed from the graph. The nodes can be passed as:
- 2-tuples (u, v) half-edges (u, v) and (v, u).
- 3-tuples (u, v, k) where k is ignored.
See Also
--------
remove_edge : remove a single edge
Notes
-----
Will fail silently if an edge in ebunch is not in the graph.
Examples
--------
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)
"""
for e in ebunch:
u, v = e[:2] # ignore edge data
# assuming that the PlanarEmbedding is valid, if the half_edge
# (u, v) is in the graph, then so is half_edge (v, u)
if u in self._succ and v in self._succ[u]:
self.remove_edge(u, v)
def connect_components(self, v, w):
"""Adds half-edges for (v, w) and (w, v) at some position.
This method should only be called if v and w are in different
components, or it might break the embedding.
This especially means that if `connect_components(v, w)`
is called it is not allowed to call `connect_components(w, v)`
afterwards. The neighbor orientations in both directions are
all set correctly after the first call.
Parameters
----------
v : node
w : node
See Also
--------
add_half_edge
"""
if v in self._succ and self._succ[v]:
ref = next(reversed(self._succ[v]))
else:
ref = None
self.add_half_edge(v, w, cw=ref)
if w in self._succ and self._succ[w]:
ref = next(reversed(self._succ[w]))
else:
ref = None
self.add_half_edge(w, v, cw=ref)
def add_half_edge_first(self, start_node, end_node):
"""Add a half-edge and set end_node as start_node's leftmost neighbor.
The new edge is inserted counterclockwise with respect to the current
leftmost neighbor, if there is one.
Parameters
----------
start_node : node
end_node : node
See Also
--------
add_half_edge
connect_components
"""
succs = self._succ.get(start_node)
# the leftmost neighbor is the last entry in the
# self._succ[start_node] dict
leftmost_nbr = next(reversed(succs)) if succs else None
self.add_half_edge(start_node, end_node, cw=leftmost_nbr)
def next_face_half_edge(self, v, w):
"""Returns the following half-edge left of a face.
Parameters
----------
v : node
w : node
Returns
-------
half-edge : tuple
"""
new_node = self[w][v]["ccw"]
return w, new_node
def traverse_face(self, v, w, mark_half_edges=None):
"""Returns nodes on the face that belong to the half-edge (v, w).
The face that is traversed lies to the right of the half-edge (in an
orientation where v is below w).
Optionally it is possible to pass a set to which all encountered half
edges are added. Before calling this method, this set must not include
any half-edges that belong to the face.
Parameters
----------
v : node
Start node of half-edge.
w : node
End node of half-edge.
mark_half_edges: set, optional
Set to which all encountered half-edges are added.
Returns
-------
face : list
A list of nodes that lie on this face.
"""
if mark_half_edges is None:
mark_half_edges = set()
face_nodes = [v]
mark_half_edges.add((v, w))
prev_node = v
cur_node = w
# Last half-edge is (incoming_node, v)
incoming_node = self[v][w]["cw"]
while cur_node != v or prev_node != incoming_node:
face_nodes.append(cur_node)
prev_node, cur_node = self.next_face_half_edge(prev_node, cur_node)
if (prev_node, cur_node) in mark_half_edges:
raise nx.NetworkXException("Bad planar embedding. Impossible face.")
mark_half_edges.add((prev_node, cur_node))
return face_nodes
def is_directed(self):
"""A valid PlanarEmbedding is undirected.
All reverse edges are contained, i.e. for every existing
half-edge (v, w) the half-edge in the opposite direction (w, v) is also
contained.
"""
return False
def copy(self, as_view=False):
if as_view is True:
return nx.graphviews.generic_graph_view(self)
G = self.__class__()
G.graph.update(self.graph)
G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
super(self.__class__, G).add_edges_from(
(u, v, datadict.copy())
for u, nbrs in self._adj.items()
for v, datadict in nbrs.items()
)
return G
def to_undirected(self, reciprocal=False, as_view=False):
"""
Returns a non-embedding undirected representation of the graph.
This method strips the planar embedding information and provides
a simple undirected graph representation. While creating the undirected graph,
all edge attributes are retained except the ``"cw"`` and ``"ccw"`` attributes
which are removed from the edge data. Those attributes are specific to
the requirements of planar embeddings.
Parameters
----------
reciprocal : bool (optional)
Not supported for PlanarEmbedding. This parameter raises an exception
if used. All valid embeddings include reciprocal half-edges by definition,
making this parameter unnecessary.
as_view : bool (optional, default=False)
Not supported for PlanarEmbedding. This parameter raises an exception
if used.
Returns
-------
G : Graph
An undirected graph with the same name and nodes as the PlanarEmbedding.
Edges are included with their data, except for the ``"cw"`` and ``"ccw"``
attributes, which are omitted.
Notes
-----
- If edges exist in both directions ``(u, v)`` and ``(v, u)`` in the PlanarEmbedding,
attributes for the resulting undirected edge will be combined, excluding ``"cw"``
and ``"ccw"``.
- A deep copy is made of the other edge attributes as well as the
node and graph attributes, ensuring independence of the resulting graph.
- Subclass-specific data structures used in the original graph may not transfer
to the undirected graph. The resulting graph will be of type ``nx.Graph``.
"""
if reciprocal:
raise ValueError(
"'reciprocal=True' is not supported for PlanarEmbedding.\n"
"All valid embeddings include reciprocal half-edges by definition,\n"
"making this parameter unnecessary."
)
if as_view:
raise ValueError("'as_view=True' is not supported for PlanarEmbedding.")
graph_class = self.to_undirected_class()
G = graph_class()
G.graph.update(deepcopy(self.graph))
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
G.add_edges_from(
(u, v, {k: deepcopy(v) for k, v in d.items() if k not in {"cw", "ccw"}})
for u, nbrs in self._adj.items()
for v, d in nbrs.items()
)
return G
| PlanarEmbedding |
python | pytorch__pytorch | torch/_inductor/codegen/mps_device_op_overrides.py | {
"start": 106,
"end": 671
} | class ____(DeviceOpOverrides):
def device_guard(self, device_idx: int) -> str:
assert device_idx == 0
return "torch._ops.contextlib.nullcontext()"
def set_device(self, device_idx: int) -> str:
assert device_idx == 0
return "pass # MPS set device"
def kernel_driver(self) -> str:
return """
#include <ATen/native/mps/MetalShaderLibrary.h>
"""
def cpp_kernel_type(self) -> str:
return "MTLFunction_t"
register_device_op_overrides("mps", MPSDeviceOpOverrides())
| MPSDeviceOpOverrides |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.