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 | facebook__pyre-check | tools/upgrade/commands/tests/consolidate_nested_configurations_test.py | {
"start": 618,
"end": 6902
} | class ____(unittest.TestCase):
def test_gather_nested_configuration_mapping(self) -> None:
arguments = MagicMock()
configurations = []
expected_mapping = {}
mapping = ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).gather_nested_configuration_mapping(configurations)
self.assertEqual(expected_mapping, mapping)
configurations = [
"a/.pyre_configuration.local",
"b/.pyre_configuration.local",
"a/b/.pyre_configuration.local",
"aa/.pyre_configuration.local",
]
expected_mapping = {
"a/.pyre_configuration.local": ["a/b/.pyre_configuration.local"],
"aa/.pyre_configuration.local": [],
"b/.pyre_configuration.local": [],
}
mapping = ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).gather_nested_configuration_mapping(configurations)
self.assertEqual(expected_mapping, mapping)
@patch.object(Repository, "remove_paths")
@patch.object(Configuration, "get_errors")
def test_consolidate(self, get_errors, remove_paths) -> None:
get_errors.return_value = errors.Errors([])
with tempfile.TemporaryDirectory() as root:
configuration_path = os.path.join(root, ".pyre_configuration.local")
nested_a = tempfile.mkdtemp("a", dir=root)
nested_b = tempfile.mkdtemp("b", dir=root)
nested_a_configuration = os.path.join(nested_a, ".pyre_configuration.local")
nested_b_configuration = os.path.join(nested_b, ".pyre_configuration.local")
with open(configuration_path, "w+") as configuration_file, open(
nested_a_configuration, "w+"
) as nested_configuration_a, open(
nested_b_configuration, "w+"
) as nested_configuration_b:
json.dump({"targets": ["//x/..."]}, configuration_file)
json.dump({"targets": ["//a/..."]}, nested_configuration_a)
json.dump({"targets": ["//b/..."]}, nested_configuration_b)
configuration_file.seek(0)
nested_configuration_a.seek(0)
nested_configuration_b.seek(0)
consolidate_nested(
repository,
Path(configuration_path),
[Path(nested_a_configuration), Path(nested_b_configuration)],
)
remove_paths.assert_has_calls(
[
call([Path(nested_a_configuration)]),
call([Path(nested_b_configuration)]),
]
)
self.assertEqual(
json.load(configuration_file),
{"targets": ["//x/...", "//a/...", "//b/..."]},
)
@patch.object(Repository, "commit_changes")
@patch.object(consolidate_nested_configurations, "consolidate_nested")
def test_run_skip(self, consolidate, commit_changes) -> None:
with tempfile.TemporaryDirectory() as root:
arguments = MagicMock()
arguments.subdirectory = root
arguments.lint = False
arguments.no_commit = False
# Skip if no configurations found
ConsolidateNestedConfigurations.from_arguments(arguments, repository).run()
consolidate.assert_not_called()
# Skip if only one configuration found
with open(os.path.join(root, ".pyre_configuration.local"), "w+"):
ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).run()
consolidate.assert_not_called()
@patch.object(Repository, "commit_changes")
@patch.object(consolidate_nested_configurations, "consolidate_nested")
@patch.object(Configuration, "get_errors")
def test_run_topmost(self, get_errors, consolidate, commit_changes) -> None:
with tempfile.TemporaryDirectory() as root:
arguments = MagicMock()
arguments.subdirectory = root
arguments.lint = False
arguments.no_commit = False
# Consolidate with existing topmost configuration
subdirectory_a = tempfile.mkdtemp("a", dir=root)
subdirectory_b = tempfile.mkdtemp("b", dir=root)
with open(
os.path.join(root, ".pyre_configuration.local"), "w+"
) as configuration, open(
os.path.join(subdirectory_a, ".pyre_configuration.local"), "w+"
) as nested_a, open(
os.path.join(subdirectory_b, ".pyre_configuration.local"), "w+"
) as nested_b:
json.dump({"targets": ["//x/..."]}, configuration)
configuration.seek(0)
ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).run()
consolidate.assert_called_once_with(
repository,
Path(configuration.name),
sorted([Path(nested_a.name), Path(nested_b.name)]),
)
@patch.object(Repository, "commit_changes")
@patch.object(consolidate_nested_configurations, "consolidate_nested")
@patch.object(Configuration, "get_errors")
def test_run_no_topmost(self, get_errors, consolidate, commit_changes) -> None:
with tempfile.TemporaryDirectory() as root:
arguments = MagicMock()
arguments.subdirectory = root
arguments.lint = False
arguments.no_commit = False
# Consolidate with no existing topmost configuration
subdirectory_a = tempfile.mkdtemp("a", dir=root)
subdirectory_b = tempfile.mkdtemp("b", dir=root)
with open(
os.path.join(subdirectory_a, ".pyre_configuration.local"), "w+"
), open(os.path.join(subdirectory_b, ".pyre_configuration.local"), "w+"):
ConsolidateNestedConfigurations.from_arguments(
arguments, repository
).run()
consolidate.assert_not_called()
| ConsolidateNestedConfigurationsTest |
python | django__django | django/contrib/postgres/fields/array.py | {
"start": 11559,
"end": 12047
} | class ____(Transform):
def __init__(self, index, base_field, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = index
self.base_field = base_field
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
if not lhs.endswith("]"):
lhs = "(%s)" % lhs
return "%s[%%s]" % lhs, (*params, self.index)
@property
def output_field(self):
return self.base_field
| IndexTransform |
python | oauthlib__oauthlib | tests/openid/connect/core/grant_types/test_refresh_token.py | {
"start": 417,
"end": 677
} | class ____(RefreshTokenGrantTest):
"""Test that OpenID don't interfere with normal OAuth 2 flows."""
def setUp(self):
super().setUp()
self.auth = RefreshTokenGrant(request_validator=self.mock_validator)
| OpenIDRefreshTokenInterferenceTest |
python | pypa__warehouse | warehouse/accounts/interfaces.py | {
"start": 760,
"end": 6837
} | class ____(Interface):
def get_user(user_id):
"""
Return the user object that represents the given userid, or None if
there is no user for that ID.
"""
def get_user_by_username(username):
"""
Return the user object corresponding with the given username, or None
if there is no user with that username.
"""
def get_user_by_email(email):
"""
Return the user object corresponding with the given email, or None
if there is no user with that email.
"""
def get_users_by_prefix(prefix: str) -> list:
"""
Return a list of user objects that match the given prefix.
"""
def get_admin_user():
"""
Returns the `admin` user object.
"""
def find_userid(username):
"""
Find the unique user identifier for the given username or None if there
is no user with the given username.
"""
def check_password(user_id, password, *, tags=None):
"""
Returns a boolean representing whether the given password is valid for
the given userid.
May have an optional list of tags, which allows identifying the purpose of
checking the password.
"""
def create_user(username, name, password):
"""
Accepts a user object, and attempts to create a user with those
attributes.
A UserAlreadyExists Exception is raised if the user already exists.
"""
def add_email(user_id, email_address, primary=False, verified=False, public=False):
"""
Adds an email for the provided user_id
"""
def update_user(user_id, **changes):
"""
Updates the user object
"""
def disable_password(user_id, request, reason=None):
"""
Disables the given user's password, preventing further login until the user
resets their password. If a reason was given, this will be persisted and reset
when the user is re-enabled.
"""
def is_disabled(user_id):
"""
Checks if a user has been disabled, and returns a tuple of
(IsDisabled: bool, Reason: Optional[DisableReason])
"""
def has_two_factor(user_id):
"""
Returns True if the user has any form of two factor
authentication and is allowed to use it.
"""
def has_totp(user_id):
"""
Returns True if the user has a TOTP device provisioned.
"""
def has_webauthn(user_id):
"""
Returns True if the user has a security key provisioned.
"""
def has_recovery_codes(user_id):
"""
Returns True if the user has at least one valid recovery code.
"""
def get_recovery_codes(user_id):
"""
Returns RecoveryCode objects associated with the user.
"""
def get_recovery_code(user_id, code):
"""
Returns a specific RecoveryCode object associated with the user and the
provided code.
"""
def get_totp_secret(user_id):
"""
Returns the user's TOTP secret as bytes.
If the user doesn't have a TOTP secret or is not
allowed to use a second factor, returns None.
"""
def check_totp_value(user_id, totp_value, *, tags=None):
"""
Returns True if the given TOTP code is valid.
"""
def add_webauthn(user_id, **kwargs):
"""
Adds a WebAuthn credential to the given user.
Returns None if the user already has this credential.
"""
def get_webauthn_credential_options(user_id, *, challenge, rp_name, rp_id):
"""
Returns a dictionary of credential options suitable for beginning the WebAuthn
provisioning process for the given user.
"""
def get_webauthn_assertion_options(user_id, *, challenge, rp_id):
"""
Returns a dictionary of assertion options suitable for beginning the WebAuthn
authentication process for the given user.
"""
def verify_webauthn_credential(credential, *, challenge, rp_id, origin):
"""
Checks whether the given credential is valid, i.e. suitable for generating
assertions during authentication.
Returns the validated credential on success, raises
webauthn.RegistrationRejectedError on failure.
"""
def verify_webauthn_assertion(user_id, assertion, *, challenge, origin, rp_id):
"""
Checks whether the given assertion was produced by the given user's WebAuthn
device.
Returns the updated signage count on success, raises
webauthn.AuthenticationRejectedError on failure.
"""
def get_webauthn_by_label(user_id, label):
"""
Returns a WebAuthn credential for the given user by its label,
or None if no credential for the user has this label.
"""
def get_webauthn_by_credential_id(user_id, credential_id):
"""
Returns a WebAuthn credential for the given user by its credential ID,
or None of the user doesn't have a credential with this ID.
"""
def generate_recovery_codes(user_id):
"""
Generates RecoveryCode objects for the given user.
Returns a list of plain-text codes.
"""
def check_recovery_code(user_id, code):
"""
Checks if supplied code matches a valid hashed recovery code for the given user.
Returns True if supplied recovery code is valid, and marks the stored code as
burned.
"""
def get_password_timestamp(user_id):
"""
Returns POSIX timestamp corresponding to the datetime that the users password
was most recently updated
"""
def record_tos_engagement(
user_id,
revision,
engagement,
):
"""
Add a record of end user being flashed about, notified of, viewing, or agreeing
to a terms of service change.
"""
| IUserService |
python | langchain-ai__langchain | libs/partners/prompty/tests/unit_tests/fake_chat_model.py | {
"start": 389,
"end": 1381
} | class ____(SimpleChatModel):
"""Fake Chat Model wrapper for testing purposes."""
def _call(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> str:
return json.dumps([message.model_dump() for message in messages])
async def _agenerate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: AsyncCallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
output_str = "fake response 2"
message = AIMessage(content=output_str)
generation = ChatGeneration(message=message)
return ChatResult(generations=[generation])
@property
def _llm_type(self) -> str:
return "fake-echo-prompt-chat-model"
@property
def _identifying_params(self) -> dict[str, Any]:
return {"key": "fake"}
| FakeEchoPromptChatModel |
python | run-llama__llama_index | llama-index-integrations/graph_rag/llama-index-graph-rag-cognee/llama_index/graph_rag/cognee/base.py | {
"start": 343,
"end": 3100
} | class ____(Protocol):
"""
Abstract graph RAG protocol.
This protocol defines the interface for a graphRAG, which is responsible
for adding, storing, processing and retrieving information from knowledge graphs.
Attributes:
llm_api_key: str: Api key for desired llm.
graph_db_provider: str: The graph database provider.
vector_db_provider: str: The vector database provider.
relational_db_provider: str: The relational database provider.
db_name: str: The name of the databases.
"""
@abstractmethod
async def add(
self, data: Union[Document, List[Document]], dataset_name: str = "main_dataset"
) -> None:
"""
Add data to the specified dataset.
This data will later be processed and made into a knowledge graph.
Args:
data (Union[Document, List[Document]]): The document(s) to be added to the graph.
dataset_name (str): Name of the dataset or node set where the data will be added.
"""
@abstractmethod
async def process_data(self, dataset_name: str = "main_dataset") -> None:
"""
Process and structure data in the dataset and make a knowledge graph out of it.
Args:
dataset_name (str): The dataset name to process.
"""
@abstractmethod
async def search(self, query: str) -> list:
"""
Search the knowledge graph for relevant information using graph-based retrieval.
Args:
query (str): The query string to match against entities and relationships in the graph.
Returns:
list: Search results containing graph-based insights and related information.
"""
@abstractmethod
async def get_related_nodes(self, node_id: str) -> list:
"""
Find nodes and relationships connected to a specific node in the knowledge graph.
Args:
node_id (str): The identifier or name of the node to find connections for.
Returns:
list: Related nodes, relationships, and insights connected to the specified node.
"""
@abstractmethod
async def visualize_graph(
self, open_browser: bool = False, output_file_path: str | None = None
) -> str:
"""
Generate HTML visualization of the knowledge graph.
Args:
open_browser (bool): Whether to automatically open the visualization in the default browser.
output_file_path (str | None): Directory path where the HTML file will be saved.
If None, saves to user's home directory.
Returns:
str: Full path to the generated HTML visualization file.
"""
| GraphRAG |
python | matplotlib__matplotlib | lib/matplotlib/patheffects.py | {
"start": 389,
"end": 2161
} | class ____:
"""
A base class for path effects.
Subclasses should override the ``draw_path`` method to add effect
functionality.
"""
def __init__(self, offset=(0., 0.)):
"""
Parameters
----------
offset : (float, float), default: (0, 0)
The (x, y) offset to apply to the path, measured in points.
"""
self._offset = offset
def _offset_transform(self, renderer):
"""Apply the offset to the given transform."""
return mtransforms.Affine2D().translate(
*map(renderer.points_to_pixels, self._offset))
def _update_gc(self, gc, new_gc_dict):
"""
Update the given GraphicsContext with the given dict of properties.
The keys in the dictionary are used to identify the appropriate
``set_`` method on the *gc*.
"""
new_gc_dict = new_gc_dict.copy()
dashes = new_gc_dict.pop("dashes", None)
if dashes:
gc.set_dashes(**dashes)
for k, v in new_gc_dict.items():
set_method = getattr(gc, 'set_' + k, None)
if not callable(set_method):
raise AttributeError(f'Unknown property {k}')
set_method(v)
return gc
def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):
"""
Derived should override this method. The arguments are the same
as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
except the first argument is a renderer.
"""
# Get the real renderer, not a PathEffectRenderer.
if isinstance(renderer, PathEffectRenderer):
renderer = renderer._renderer
return renderer.draw_path(gc, tpath, affine, rgbFace)
| AbstractPathEffect |
python | django__django | tests/staticfiles_tests/test_views.py | {
"start": 721,
"end": 954
} | class ____(TestServeStatic):
"""
Test serving static files disabled when DEBUG is False.
"""
def test_disabled_serving(self):
self.assertFileNotFound("test.txt")
@override_settings(DEBUG=True)
| TestServeDisabled |
python | apache__airflow | providers/pgvector/src/airflow/providers/pgvector/operators/pgvector.py | {
"start": 951,
"end": 1876
} | class ____(SQLExecuteQueryOperator):
"""
This operator is designed for ingesting data into a PostgreSQL database with pgvector support.
It inherits from the SQLExecuteQueryOperator and extends its functionality by registering
the pgvector data type with the database connection before executing queries.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:PgVectorIngestOperator`
"""
def __init__(self, *args, **kwargs) -> None:
"""Initialize a new PgVectorIngestOperator."""
super().__init__(*args, **kwargs)
def _register_vector(self) -> None:
"""Register the vector type with your connection."""
conn = self.get_db_hook().get_conn()
register_vector(conn)
def execute(self, context):
self._register_vector()
super().execute(context)
| PgVectorIngestOperator |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/runner.py | {
"start": 351,
"end": 1126
} | class ____(VirtualEnv, PythonRun):
"""local file system python virtual environment via the virtualenv package."""
@staticmethod
def id() -> str:
return "virtualenv"
@property
def _package_tox_env_type(self) -> str:
return "virtualenv-pep-517"
@property
def _external_pkg_tox_env_type(self) -> str:
return "virtualenv-cmd-builder"
@property
def default_pkg_type(self) -> str:
tox_root: Path = self.core["tox_root"]
if not (any((tox_root / i).exists() for i in ("pyproject.toml", "setup.py", "setup.cfg"))):
return "skip"
return super().default_pkg_type
@impl
def tox_register_tox_env(register: ToxEnvRegister) -> None:
register.add_run_env(VirtualEnvRunner)
| VirtualEnvRunner |
python | doocs__leetcode | solution/3700-3799/3737.Count Subarrays With Majority Element I/Solution.py | {
"start": 0,
"end": 371
} | class ____:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
n = len(nums)
ans = 0
for i in range(n):
cnt = Counter()
for j in range(i, n):
k = j - i + 1
cnt[nums[j]] += 1
if cnt[target] > k // 2:
ans += 1
return ans
| Solution |
python | kamyu104__LeetCode-Solutions | Python/find-the-sum-of-the-power-of-all-subsequences.py | {
"start": 53,
"end": 431
} | class ____(object):
def sumOfPower(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(k+1)
dp[0] = 1
for x in nums:
for i in reversed(xrange(k+1)):
dp[i] = (dp[i]+(dp[i]+(dp[i-x] if i-x >= 0 else 0)))%MOD
return dp[k]
| Solution |
python | ray-project__ray | python/ray/actor.py | {
"start": 5463,
"end": 6203
} | class ____(Generic[_Ret, _T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]):
def remote(
self,
__arg0: "Union[_T0, ObjectRef[_T0]]",
__arg1: "Union[_T1, ObjectRef[_T1]]",
__arg2: "Union[_T2, ObjectRef[_T2]]",
__arg3: "Union[_T3, ObjectRef[_T3]]",
__arg4: "Union[_T4, ObjectRef[_T4]]",
__arg5: "Union[_T5, ObjectRef[_T5]]",
__arg6: "Union[_T6, ObjectRef[_T6]]",
__arg7: "Union[_T7, ObjectRef[_T7]]",
) -> "ObjectRef[_Ret]":
...
def bind(
self,
__arg0: _T0,
__arg1: _T1,
__arg2: _T2,
__arg3: _T3,
__arg4: _T4,
__arg5: _T5,
__arg6: _T6,
__arg7: _T7,
) -> Any:
...
| _RemoteMethod7 |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 95687,
"end": 97126
} | class ____:
def test_inprocess_supervisor_comms_roundtrip(self):
"""
Test that InProcessSupervisorComms correctly sends a message to the supervisor,
and that the supervisor's response is received via the message queue.
This verifies the end-to-end communication flow:
- send_request() dispatches a message to the supervisor
- the supervisor handles the request and appends a response via send_msg()
- get_message() returns the enqueued response
This test mocks the supervisor's `_handle_request()` method to simulate
a simple echo-style response, avoiding full task execution.
"""
class MinimalSupervisor(InProcessTestSupervisor):
def _handle_request(self, msg, log, req_id):
resp = VariableResult(key=msg.key, value="value")
self.send_msg(resp, req_id)
supervisor = MinimalSupervisor(
id="test",
pid=123,
process=MagicMock(),
process_log=MagicMock(),
client=MagicMock(),
)
comms = InProcessSupervisorComms(supervisor=supervisor)
supervisor.comms = comms
test_msg = GetVariable(key="test_key")
response = comms.send(test_msg)
# Ensure we got back what we expect
assert isinstance(response, VariableResult)
assert response.value == "value"
| TestInProcessTestSupervisor |
python | django-haystack__django-haystack | haystack/admin.py | {
"start": 584,
"end": 2293
} | class ____(ChangeList):
def __init__(self, **kwargs):
self.haystack_connection = kwargs.pop("haystack_connection", DEFAULT_ALIAS)
super_kwargs = kwargs
if django_version[0] >= 4:
super_kwargs["search_help_text"] = "Search..."
super().__init__(**super_kwargs)
def get_results(self, request):
if SEARCH_VAR not in request.GET:
return super().get_results(request)
# Note that pagination is 0-based, not 1-based.
sqs = (
SearchQuerySet(self.haystack_connection)
.models(self.model)
.auto_query(request.GET[SEARCH_VAR])
.load_all()
)
paginator = Paginator(sqs, self.list_per_page)
# Get the number of objects, with admin filters applied.
result_count = paginator.count
full_result_count = (
SearchQuerySet(self.haystack_connection).models(self.model).all().count()
)
can_show_all = result_count <= self.list_max_show_all
multi_page = result_count > self.list_per_page
# Get the list of objects to display on this page.
try:
result_list = paginator.page(self.page_num).object_list
# Grab just the Django models, since that's what everything else is
# expecting.
result_list = [result.object for result in result_list]
except InvalidPage:
result_list = ()
self.result_count = result_count
self.full_result_count = full_result_count
self.result_list = result_list
self.can_show_all = can_show_all
self.multi_page = multi_page
self.paginator = paginator
| SearchChangeList |
python | bokeh__bokeh | tests/test_bokehjs.py | {
"start": 1129,
"end": 1989
} | class ____:
def test_bokehjs(self) -> None:
os.chdir('bokehjs')
proc = subprocess.Popen(["node", "make", "test"], stdout=subprocess.PIPE)
out, _ = proc.communicate()
msg = out.decode('utf-8', errors='ignore')
os.chdir('..')
print(msg)
if proc.returncode != 0:
assert False
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| TestBokehJS |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/splice_z/package.py | {
"start": 217,
"end": 917
} | class ____(Package):
"""Simple package with one optional dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/splice-z-1.0.tar.gz"
version("1.0.2")
version("1.0.1")
version("1.0.0")
variant("foo", default=False, description="nope")
variant("bar", default=False, description="nope")
variant("compat", default=True, description="nope")
can_splice("splice-z@1.0.0 +compat", when="@1.0.1 +compat")
can_splice("splice-z@1.0.0:1.0.1 +compat", when="@1.0.2 +compat")
def install(self, spec, prefix):
with open(prefix.join("splice-z"), "w", encoding="utf-8") as f:
f.write("splice-z: {0}".format(prefix))
| SpliceZ |
python | django__django | tests/db_functions/text/test_chr.py | {
"start": 209,
"end": 1861
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="John Smith", alias="smithj")
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
cls.rhonda = Author.objects.create(name="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(first_initial=Left("name", 1))
self.assertCountEqual(authors.filter(first_initial=Chr(ord("J"))), [self.john])
self.assertCountEqual(
authors.exclude(first_initial=Chr(ord("J"))), [self.elena, self.rhonda]
)
def test_non_ascii(self):
authors = Author.objects.annotate(first_initial=Left("name", 1))
self.assertCountEqual(authors.filter(first_initial=Chr(ord("É"))), [self.elena])
self.assertCountEqual(
authors.exclude(first_initial=Chr(ord("É"))), [self.john, self.rhonda]
)
def test_transform(self):
with register_lookup(IntegerField, Chr):
authors = Author.objects.annotate(name_code_point=Ord("name"))
self.assertCountEqual(
authors.filter(name_code_point__chr=Chr(ord("J"))), [self.john]
)
self.assertCountEqual(
authors.exclude(name_code_point__chr=Chr(ord("J"))),
[self.elena, self.rhonda],
)
def test_annotate(self):
authors = Author.objects.annotate(
first_initial=Left("name", 1),
initial_chr=Chr(ord("J")),
)
self.assertSequenceEqual(
authors.filter(first_initial=F("initial_chr")),
[self.john],
)
| ChrTests |
python | huggingface__transformers | tests/utils/import_structures/import_structure_register_with_duplicates.py | {
"start": 1290,
"end": 1446
} | class ____:
def __init__(self):
pass
@requires(
backends=(
"torch",
"torch"
)
)
# That's a statement
def c3():
pass
| C3 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 360159,
"end": 360806
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("IssueTimelineItemEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(
sgqlc.types.list_of("IssueTimelineItem"), graphql_name="nodes"
)
page_info = sgqlc.types.Field(
sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| IssueTimelineConnection |
python | astropy__astropy | astropy/convolution/kernels.py | {
"start": 5552,
"end": 7741
} | class ____(Kernel1D):
"""
1D Box filter kernel.
The Box filter or running mean is a smoothing filter. It is not isotropic
and can produce artifacts when applied repeatedly to the same data.
The generated kernel is normalized so that it integrates to 1.
By default, the Box kernel uses the ``linear_interp`` discretization mode,
which allows non-shifting, even-sized kernels. This is achieved by
weighting the edge pixels with 1/2. E.g a Box kernel with an effective
smoothing of 4 pixels would have the following array: [0.5, 1, 1, 1, 0.5].
Parameters
----------
width : number
Width of the filter kernel.
mode : {'linear_interp', 'center', 'oversample', 'integrate'}, optional
One of the following discretization modes:
* 'linear_interp' (default)
Discretize model by linearly interpolating
between the values at the corners of the bin.
* 'center'
Discretize model by taking the value
at the center of the bin.
* 'oversample'
Discretize model by taking the average
on an oversampled grid.
* 'integrate'
Discretize model by integrating the
model over the bin.
factor : number, optional
Factor of oversampling. Default factor = 10.
See Also
--------
Gaussian1DKernel, Trapezoid1DKernel, RickerWavelet1DKernel
Examples
--------
Kernel response function:
.. plot::
:include-source:
import matplotlib.pyplot as plt
from astropy.convolution import Box1DKernel
box_1D_kernel = Box1DKernel(9)
plt.plot(box_1D_kernel, drawstyle='steps')
plt.xlim(-1, 9)
plt.xlabel('x [pixels]')
plt.ylabel('value')
plt.show()
"""
_separable = True
_is_bool = True
def __init__(self, width, **kwargs):
self._model = models.Box1D(1.0 / width, 0, width)
self._default_size = _round_up_to_odd_integer(width)
kwargs["mode"] = "linear_interp"
super().__init__(**kwargs)
self.normalize()
| Box1DKernel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_natural_language.py | {
"start": 1683,
"end": 2120
} | class ____:
@patch("airflow.providers.google.cloud.operators.natural_language.CloudNaturalLanguageHook")
def test_minimal_green_path(self, hook_mock):
hook_mock.return_value.analyze_entities.return_value = ANALYZE_ENTITIES_RESPONSE
op = CloudNaturalLanguageAnalyzeEntitiesOperator(task_id="task-id", document=DOCUMENT)
resp = op.execute({})
assert resp == {}
| TestCloudLanguageAnalyzeEntitiesOperator |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 10603,
"end": 11627
} | class ____(BaseExtensionApp):
description = "Update labextension(s)"
flags = update_flags
all = Bool(False, config=True, help="Whether to update all extensions")
def run_task(self):
self.deprecation_warning(
"Updating extensions with the jupyter labextension update command is now deprecated and will be removed in a future major version of JupyterLab."
)
if not self.all and not self.extra_args:
self.log.warning(
"Specify an extension to update, or use --all to update all extensions"
)
return False
app_options = AppOptions(
app_dir=self.app_dir,
logger=self.log,
core_config=self.core_config,
labextensions_path=self.labextensions_path,
)
if self.all:
return update_extension(all_=True, app_options=app_options)
return any(update_extension(name=arg, app_options=app_options) for arg in self.extra_args)
| UpdateLabExtensionApp |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 21499,
"end": 23783
} | class ____(StateMachineEvent):
key: Key
run_id: int
who_has: dict[Key, Collection[str]]
nbytes: dict[Key, int]
priority: tuple[int, ...]
run_spec: T_runspec | None
resource_restrictions: dict[str, float]
actor: bool
annotations: dict
span_id: str | None
__slots__ = tuple(__annotations__)
def __post_init__(self) -> None:
# Fixes after msgpack decode
if isinstance(self.priority, list): # type: ignore[unreachable]
self.priority = tuple(self.priority) # type: ignore[unreachable]
def _to_dict(self, *, exclude: Container[str] = ()) -> dict:
return StateMachineEvent._to_dict(self._clean(), exclude=exclude)
def _clean(self) -> StateMachineEvent:
out = copy(self)
out.run_spec = None
return out
def to_loggable(self, *, handled: float) -> StateMachineEvent:
out = self._clean()
out.handled = handled
return out
def _after_from_dict(self) -> None:
self.run_spec = None
@classmethod
def _f(cls) -> None:
return # pragma: nocover
@classmethod
def dummy_runspec(cls, key: Key) -> Task:
return Task(key, cls._f)
@staticmethod
def dummy(
key: Key,
*,
run_id: int = 0,
who_has: dict[Key, Collection[str]] | None = None,
nbytes: dict[Key, int] | None = None,
priority: tuple[int, ...] = (0,),
resource_restrictions: dict[str, float] | None = None,
actor: bool = False,
annotations: dict | None = None,
stimulus_id: str,
) -> ComputeTaskEvent:
"""Build a dummy event, with most attributes set to a reasonable default.
This is a convenience method to be used in unit testing only.
"""
return ComputeTaskEvent(
key=key,
run_id=run_id,
who_has=who_has or {},
nbytes=nbytes or {k: 1 for k in who_has or ()},
priority=priority,
run_spec=ComputeTaskEvent.dummy_runspec(key),
resource_restrictions=resource_restrictions or {},
actor=actor,
annotations=annotations or {},
span_id=None,
stimulus_id=stimulus_id,
)
@dataclass
| ComputeTaskEvent |
python | ansible__ansible | lib/ansible/module_utils/facts/network/nvme.py | {
"start": 910,
"end": 1967
} | class ____(NetworkCollector):
name = 'nvme'
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
"""
Currently NVMe is only supported in some Linux distributions.
If NVMe is configured on the host then a file will have been created
during the NVMe driver installation. This file holds the unique NQN
of the host.
Example of contents of /etc/nvme/hostnqn:
# cat /etc/nvme/hostnqn
nqn.2014-08.org.nvmexpress:fc_lif:uuid:2cd61a74-17f9-4c22-b350-3020020c458d
"""
nvme_facts = {}
nvme_facts['hostnqn'] = ""
if sys.platform.startswith('linux'):
for line in get_file_content('/etc/nvme/hostnqn', '').splitlines():
if line.startswith('#') or line.startswith(';') or line.strip() == '':
continue
if line.startswith('nqn.'):
nvme_facts['hostnqn'] = line
break
return nvme_facts
| NvmeInitiatorNetworkCollector |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/timers.py | {
"start": 2721,
"end": 4002
} | class ____:
"""
Tracks the most recent value of a metric. This is analogous to gauges in statsd.
"""
__slots__ = ["value", "min_value", "max_value", "count", "_timestamp"]
def __init__(self, value: float):
self.value = value
self.min_value = value
self.max_value = value
self.count = 1
# Internal timestamp so we can determine priority.
self._timestamp = time.time()
def update(self, new_value: float) -> None:
self.min_value = min(self.min_value, new_value)
self.max_value = max(self.max_value, new_value)
self.value = new_value
self.count += 1
self._timestamp = time.time()
def merge(self, other: "GaugeNode") -> None:
if self._timestamp < other._timestamp:
# Keep the "later" value
self.value = other.value
self._timestamp = other._timestamp
self.min_value = min(self.min_value, other.min_value)
self.max_value = max(self.max_value, other.max_value)
self.count += other.count
def as_dict(self) -> Dict[str, float]:
return {
"value": self.value,
"min": self.min_value,
"max": self.max_value,
"count": self.count,
}
| GaugeNode |
python | falconry__falcon | docs/ext/cibuildwheel.py | {
"start": 1871,
"end": 5461
} | class ____(sphinx.util.docutils.SphinxDirective):
"""Directive to tabulate build info from a YAML workflow."""
required_arguments = 1
has_content = True
@classmethod
def _emit_table(cls, data):
columns = len(data[0])
assert all(len(row) == columns for row in data), (
'All rows must have the same number of columns'
)
# NOTE(vytas): +2 is padding inside cell borders.
width = max(len(cell) for cell in itertools.chain(*data)) + 2
hline = ('+' + '-' * width) * columns + '+\n'
output = [hline]
for row in data:
for cell in row:
# NOTE(vytas): Emojis take two spaces...
padded_width = width - 1 if _CHECKBOX in cell else width
output.append('|' + cell.center(padded_width))
output.append('|\n')
header_line = row == data[0]
output.append(hline.replace('-', '=') if header_line else hline)
return ''.join(output)
@classmethod
def _render_cell(cls, supported, free_threading):
cell = _CHECKBOX if supported else ''
if cell and free_threading:
cell += '\\ :sup:`1`'
return cell
def run(self):
workflow_path = pathlib.Path(self.arguments[0])
if not workflow_path.is_absolute():
workflow_path = FALCON_ROOT / workflow_path
# TODO(vytas): Should we package cibuildwheel.yaml into sdist too?
# For now, if .github is missing, we simply hide the table.
if not workflow_path.is_file() and not DOT_GITHUB.exists():
return []
with open(workflow_path) as fp:
workflow = yaml.safe_load(fp)
matrix = workflow['jobs']['build-wheels']['strategy']['matrix']
platforms = matrix['platform']
include = matrix.get('include', [])
assert not matrix.get('exclude'), 'TODO: exclude is not supported yet'
supported = set(
itertools.product(
[platform['name'] for platform in platforms], matrix['python']
)
)
supported.update(
(item['platform']['name'], item['python'])
for item in include
if not item['python'].endswith('t')
)
cpythons = sorted(
{cp for _, cp in supported} | _EXTEND_CPYTHONS,
key=lambda val: (len(val), val),
)
# TODO(vytas): Currently free-threading is always configured via include.
free_threading = {
(item['platform']['name'], item['python'].rstrip('t'))
for item in include
if item['python'].endswith('t')
}
header = ['Platform / CPython version']
table = [header + [cp.replace('cp3', '3.') for cp in cpythons]]
table.extend(
[description]
+ [
self._render_cell((name, cp) in supported, (name, cp) in free_threading)
for cp in cpythons
]
for name, description in _CPYTHON_PLATFORMS.items()
)
content = '\n'.join(self.content) + '\n\n' + self._emit_table(table)
if free_threading:
content += (
'\n\n:sup:`1`\\ '
'*A binary wheel is also available for free-threaded CPython.*'
)
return self.parse_text_to_nodes(content)
def setup(app):
app.add_directive('wheels', WheelsDirective)
return {
'version': '0.1',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| WheelsDirective |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_http_status_name.py | {
"start": 740,
"end": 1755
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_http_status_name"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_http_status_name(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidHttpStatusName |
python | cherrypy__cherrypy | cherrypy/lib/auth_digest.py | {
"start": 4781,
"end": 16275
} | class ____(object):
"""Digest Authorization implementation.
Parses a Digest Authorization header and performs
re-calculation of the digest.
"""
scheme = 'digest'
def errmsg(self, s):
"""Make an error message for HTTP Digest Authorization."""
return 'Digest Authorization header: %s' % s
@classmethod
def matches(cls, header):
"""Check if header scheme matches auth implementation."""
scheme, _, _ = header.partition(' ')
return scheme.lower() == cls.scheme
def __init__(
self,
auth_header,
http_method,
debug=False,
accept_charset=DEFAULT_CHARSET[:],
):
"""Initialize an HTTP Digest Authorization parser."""
self.http_method = http_method
self.debug = debug
if not self.matches(auth_header):
raise ValueError('Authorization scheme is not "Digest"')
self.auth_header = _try_decode_header(auth_header, accept_charset)
scheme, params = self.auth_header.split(' ', 1)
# make a dict of the params
items = parse_http_list(params)
paramsd = parse_keqv_list(items)
self.realm = paramsd.get('realm')
self.username = paramsd.get('username')
self.nonce = paramsd.get('nonce')
self.uri = paramsd.get('uri')
self.method = paramsd.get('method')
self.response = paramsd.get('response') # the response digest
self.algorithm = paramsd.get('algorithm', 'MD5').upper()
self.cnonce = paramsd.get('cnonce')
self.opaque = paramsd.get('opaque')
self.qop = paramsd.get('qop') # qop
self.nc = paramsd.get('nc') # nonce count
# perform some correctness checks
if self.algorithm not in valid_algorithms:
raise ValueError(
self.errmsg(
"Unsupported value for algorithm: '%s'" % self.algorithm,
),
)
has_reqd = (
self.username
and self.realm
and self.nonce
and self.uri
and self.response
)
if not has_reqd:
raise ValueError(
self.errmsg('Not all required parameters are present.'),
)
if self.qop:
if self.qop not in valid_qops:
raise ValueError(
self.errmsg("Unsupported value for qop: '%s'" % self.qop),
)
if not (self.cnonce and self.nc):
raise ValueError(
self.errmsg(
'If qop is sent then cnonce and nc MUST be present',
),
)
else:
if self.cnonce or self.nc:
raise ValueError(
self.errmsg(
'If qop is not sent, '
'neither cnonce nor nc can be present',
),
)
def __str__(self):
"""Render an HTTP Digest Auth header as a string."""
return 'authorization : %s' % self.auth_header
def validate_nonce(self, s, key):
"""Validate the nonce.
Returns True if nonce was generated by synthesize_nonce() and the
timestamp is not spoofed, else returns False.
s
A string related to the resource, such as the hostname of
the server.
key
A secret string known only to the server.
Both s and key must be the same values which were used to synthesize
the nonce we are trying to validate.
"""
try:
timestamp, hashpart = self.nonce.split(':', 1)
s_timestamp, s_hashpart = synthesize_nonce(
s,
key,
timestamp,
).split(':', 1)
is_valid = s_hashpart == hashpart
if self.debug:
TRACE('validate_nonce: %s' % is_valid)
return is_valid
except ValueError: # split() error
pass
return False
def is_nonce_stale(self, max_age_seconds=600):
"""Return True if a validated nonce is stale.
The nonce contains a timestamp in plaintext and also a secure
hash of the timestamp. You should first validate the nonce to
ensure the plaintext timestamp is not spoofed.
"""
try:
timestamp, hashpart = self.nonce.split(':', 1)
if int(timestamp) + max_age_seconds > int(time.time()):
return False
except ValueError: # int() error
pass
if self.debug:
TRACE('nonce is stale')
return True
def HA2(self, entity_body=''):
"""Return the H(A2) string.
See :rfc:`2617` section 3.2.2.3.
"""
# RFC 2617 3.2.2.3
# If the "qop" directive's value is "auth" or is unspecified,
# then A2 is:
# A2 = method ":" digest-uri-value
#
# If the "qop" value is "auth-int", then A2 is:
# A2 = method ":" digest-uri-value ":" H(entity-body)
if self.qop is None or self.qop == 'auth':
a2 = '%s:%s' % (self.http_method, self.uri)
elif self.qop == 'auth-int':
a2 = '%s:%s:%s' % (self.http_method, self.uri, H(entity_body))
else:
# in theory, this should never happen, since I validate qop in
# __init__()
raise ValueError(self.errmsg('Unrecognized value for qop!'))
return H(a2)
def request_digest(self, ha1, entity_body=''):
"""Calculate the Request-Digest. See :rfc:`2617` section 3.2.2.1.
ha1
The HA1 string obtained from the credentials store.
entity_body
If 'qop' is set to 'auth-int', then A2 includes a hash
of the "entity body". The entity body is the part of the
message which follows the HTTP headers. See :rfc:`2617` section
4.3. This refers to the entity the user agent sent in the
request which has the Authorization header. Typically GET
requests don't have an entity, and POST requests do.
"""
ha2 = self.HA2(entity_body)
# Request-Digest -- RFC 2617 3.2.2.1
if self.qop:
req = '%s:%s:%s:%s:%s' % (
self.nonce,
self.nc,
self.cnonce,
self.qop,
ha2,
)
else:
req = '%s:%s' % (self.nonce, ha2)
# RFC 2617 3.2.2.2
#
# If the "algorithm" directive's value is "MD5" or is unspecified,
# then A1 is:
# A1 = unq(username-value) ":" unq(realm-value) ":" passwd
#
# If the "algorithm" directive's value is "MD5-sess", then A1 is
# calculated only once - on the first request by the client following
# receipt of a WWW-Authenticate challenge from the server.
# A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
# ":" unq(nonce-value) ":" unq(cnonce-value)
if self.algorithm == 'MD5-sess':
ha1 = H('%s:%s:%s' % (ha1, self.nonce, self.cnonce))
digest = H('%s:%s' % (ha1, req))
return digest
def _get_charset_declaration(charset):
global FALLBACK_CHARSET
charset = charset.upper()
return (', charset="%s"' % charset) if charset != FALLBACK_CHARSET else ''
def www_authenticate(
realm,
key,
algorithm='MD5',
nonce=None,
qop=qop_auth,
stale=False,
accept_charset=DEFAULT_CHARSET[:],
):
"""Construct a WWW-Authenticate header for Digest authentication."""
if qop not in valid_qops:
raise ValueError("Unsupported value for qop: '%s'" % qop)
if algorithm not in valid_algorithms:
raise ValueError("Unsupported value for algorithm: '%s'" % algorithm)
HEADER_PATTERN = (
'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"%s%s'
)
if nonce is None:
nonce = synthesize_nonce(realm, key)
stale_param = ', stale="true"' if stale else ''
charset_declaration = _get_charset_declaration(accept_charset)
return HEADER_PATTERN % (
realm,
nonce,
algorithm,
qop,
stale_param,
charset_declaration,
)
def digest_auth(realm, get_ha1, key, debug=False, accept_charset='utf-8'):
"""Perform HTTP Digest Access Authentication.
A CherryPy tool that hooks at ``before_handler`` to perform
HTTP Digest Access Authentication, as specified in :rfc:`2617`.
If the request has an 'authorization' header with a 'Digest' scheme,
this tool authenticates the credentials supplied in that header.
If the request has no 'authorization' header, or if it does but the
scheme is not "Digest", or if authentication fails, the tool sends
a 401 response with a 'WWW-Authenticate' Digest header.
realm
A string containing the authentication realm.
get_ha1
A callable that looks up a username in a credentials store
and returns the HA1 string, which is defined in the RFC to be
MD5(username : realm : password). The function's signature is:
``get_ha1(realm, username)``
where username is obtained from the request's 'authorization' header.
If username is not found in the credentials store, get_ha1() returns
None.
key
A secret string known only to the server, used in the synthesis
of nonces.
"""
request = cherrypy.serving.request
auth_header = request.headers.get('authorization')
respond_401 = functools.partial(
_respond_401,
realm,
key,
accept_charset,
debug,
)
if not HttpDigestAuthorization.matches(auth_header or ''):
respond_401()
msg = 'The Authorization header could not be parsed.'
with cherrypy.HTTPError.handle(ValueError, 400, msg):
auth = HttpDigestAuthorization(
auth_header,
request.method,
debug=debug,
accept_charset=accept_charset,
)
if debug:
TRACE(str(auth))
if not auth.validate_nonce(realm, key):
respond_401()
ha1 = get_ha1(realm, auth.username)
if ha1 is None:
respond_401()
# note that for request.body to be available we need to
# hook in at before_handler, not on_start_resource like
# 3.1.x digest_auth does.
digest = auth.request_digest(ha1, entity_body=request.body)
if digest != auth.response:
respond_401()
# authenticated
if debug:
TRACE('digest matches auth.response')
# Now check if nonce is stale.
# The choice of ten minutes' lifetime for nonce is somewhat
# arbitrary
if auth.is_nonce_stale(max_age_seconds=600):
respond_401(stale=True)
request.login = auth.username
if debug:
TRACE('authentication of %s successful' % auth.username)
def _respond_401(realm, key, accept_charset, debug, **kwargs):
"""Respond with 401 status and a WWW-Authenticate header."""
header = www_authenticate(
realm,
key,
accept_charset=accept_charset,
**kwargs,
)
if debug:
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
raise cherrypy.HTTPError(
401,
'You are not authorized to access that resource',
)
| HttpDigestAuthorization |
python | pandas-dev__pandas | pandas/core/dtypes/dtypes.py | {
"start": 3586,
"end": 23998
} | class ____(PandasExtensionDtype, ExtensionDtype):
"""
Type for categorical data with the categories and orderedness.
It is a dtype representation for categorical data, which allows users to define
a fixed set of values and optionally impose an ordering. This is particularly
useful for handling categorical variables efficiently, as it can significantly
reduce memory usage compared to using object dtypes.
Parameters
----------
categories : sequence, optional
Must be unique, and must not contain any nulls.
The categories are stored in an Index,
and if an index is provided the dtype of that index will be used.
ordered : bool or None, default False
Whether or not this categorical is treated as an ordered categorical.
None can be used to maintain the ordered value of existing categoricals when
used in operations that combine categoricals, e.g. astype, and will resolve to
False if there is no existing ordered to maintain.
Attributes
----------
categories
ordered
Methods
-------
None
See Also
--------
Categorical : Represent a categorical variable in classic R / S-plus fashion.
Notes
-----
This class is useful for specifying the type of a ``Categorical``
independent of the values. See :ref:`categorical.categoricaldtype`
for more.
Examples
--------
>>> t = pd.CategoricalDtype(categories=["b", "a"], ordered=True)
>>> pd.Series(["a", "b", "a", None], dtype=t)
0 a
1 b
2 a
3 NaN
dtype: category
Categories (2, str): ['b' < 'a']
An empty CategoricalDtype with a specific dtype can be created
by providing an empty index. As follows,
>>> pd.CategoricalDtype(pd.DatetimeIndex([])).categories.dtype
dtype('<M8[s]')
"""
# TODO: Document public vs. private API
name = "category"
type: type[CategoricalDtypeType] = CategoricalDtypeType
kind: str_type = "O"
str = "|O08"
base = np.dtype("O")
_metadata = ("categories", "ordered")
_cache_dtypes: dict[str_type, PandasExtensionDtype] = {}
_supports_2d = False
_can_fast_transpose = False
def __init__(self, categories=None, ordered: Ordered = False) -> None:
self._finalize(categories, ordered, fastpath=False)
@classmethod
def _from_fastpath(
cls, categories=None, ordered: bool | None = None
) -> CategoricalDtype:
self = cls.__new__(cls)
self._finalize(categories, ordered, fastpath=True)
return self
@classmethod
def _from_categorical_dtype(
cls, dtype: CategoricalDtype, categories=None, ordered: Ordered | None = None
) -> CategoricalDtype:
if categories is ordered is None:
return dtype
if categories is None:
categories = dtype.categories
if ordered is None:
ordered = dtype.ordered
return cls(categories, ordered)
@classmethod
def _from_values_or_dtype(
cls,
values=None,
categories=None,
ordered: bool | None = None,
dtype: Dtype | None = None,
) -> CategoricalDtype:
"""
Construct dtype from the input parameters used in :class:`Categorical`.
This constructor method specifically does not do the factorization
step, if that is needed to find the categories. This constructor may
therefore return ``CategoricalDtype(categories=None, ordered=None)``,
which may not be useful. Additional steps may therefore have to be
taken to create the final dtype.
The return dtype is specified from the inputs in this prioritized
order:
1. if dtype is a CategoricalDtype, return dtype
2. if dtype is the string 'category', create a CategoricalDtype from
the supplied categories and ordered parameters, and return that.
3. if values is a categorical, use value.dtype, but override it with
categories and ordered if either/both of those are not None.
4. if dtype is None and values is not a categorical, construct the
dtype from categories and ordered, even if either of those is None.
Parameters
----------
values : list-like, optional
The list-like must be 1-dimensional.
categories : list-like, optional
Categories for the CategoricalDtype.
ordered : bool, optional
Designating if the categories are ordered.
dtype : CategoricalDtype or the string "category", optional
If ``CategoricalDtype``, cannot be used together with
`categories` or `ordered`.
Returns
-------
CategoricalDtype
Examples
--------
>>> pd.CategoricalDtype._from_values_or_dtype()
CategoricalDtype(categories=None, ordered=None, categories_dtype=None)
>>> pd.CategoricalDtype._from_values_or_dtype(
... categories=["a", "b"], ordered=True
... )
CategoricalDtype(categories=['a', 'b'], ordered=True, categories_dtype=str)
>>> dtype1 = pd.CategoricalDtype(["a", "b"], ordered=True)
>>> dtype2 = pd.CategoricalDtype(["x", "y"], ordered=False)
>>> c = pd.Categorical([0, 1], dtype=dtype1)
>>> pd.CategoricalDtype._from_values_or_dtype(
... c, ["x", "y"], ordered=True, dtype=dtype2
... )
Traceback (most recent call last):
...
ValueError: Cannot specify `categories` or `ordered` together with
`dtype`.
The supplied dtype takes precedence over values' dtype:
>>> pd.CategoricalDtype._from_values_or_dtype(c, dtype=dtype2)
CategoricalDtype(categories=['x', 'y'], ordered=False, categories_dtype=str)
"""
if dtype is not None:
# The dtype argument takes precedence over values.dtype (if any)
if isinstance(dtype, str):
if dtype == "category":
if ordered is None and cls.is_dtype(values):
# GH#49309 preserve orderedness
ordered = values.dtype.ordered
dtype = CategoricalDtype(categories, ordered)
else:
raise ValueError(f"Unknown dtype {dtype!r}")
elif categories is not None or ordered is not None:
raise ValueError(
"Cannot specify `categories` or `ordered` together with `dtype`."
)
elif not isinstance(dtype, CategoricalDtype):
raise ValueError(f"Cannot not construct CategoricalDtype from {dtype}")
elif cls.is_dtype(values):
# If no "dtype" was passed, use the one from "values", but honor
# the "ordered" and "categories" arguments
dtype = values.dtype._from_categorical_dtype(
values.dtype, categories, ordered
)
else:
# If dtype=None and values is not categorical, create a new dtype.
# Note: This could potentially have categories=None and
# ordered=None.
dtype = CategoricalDtype(categories, ordered)
return cast(CategoricalDtype, dtype)
@classmethod
def construct_from_string(cls, string: str_type) -> CategoricalDtype:
"""
Construct a CategoricalDtype from a string.
Parameters
----------
string : str
Must be the string "category" in order to be successfully constructed.
Returns
-------
CategoricalDtype
Instance of the dtype.
Raises
------
TypeError
If a CategoricalDtype cannot be constructed from the input.
"""
if not isinstance(string, str):
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)
if string != cls.name:
raise TypeError(f"Cannot construct a 'CategoricalDtype' from '{string}'")
# need ordered=None to ensure that operations specifying dtype="category" don't
# override the ordered value for existing categoricals
return cls(ordered=None)
def _finalize(self, categories, ordered: Ordered, fastpath: bool = False) -> None:
if ordered is not None:
self.validate_ordered(ordered)
if categories is not None:
categories = self.validate_categories(categories, fastpath=fastpath)
self._categories = categories
self._ordered = ordered
def __setstate__(self, state: MutableMapping[str_type, Any]) -> None:
# for pickle compat. __get_state__ is defined in the
# PandasExtensionDtype superclass and uses the public properties to
# pickle -> need to set the settable private ones here (see GH26067)
self._categories = state.pop("categories", None)
self._ordered = state.pop("ordered", False)
def __hash__(self) -> int:
# _hash_categories returns a uint64, so use the negative
# space for when we have unknown categories to avoid a conflict
if self.categories is None:
if self.ordered:
return -1
else:
return -2
# We *do* want to include the real self.ordered here
return int(self._hash_categories)
def __eq__(self, other: object) -> bool:
"""
Rules for CDT equality:
1) Any CDT is equal to the string 'category'
2) Any CDT is equal to itself
3) Any CDT is equal to a CDT with categories=None regardless of ordered
4) A CDT with ordered=True is only equal to another CDT with
ordered=True and identical categories in the same order
5) A CDT with ordered={False, None} is only equal to another CDT with
ordered={False, None} and identical categories, but same order is
not required. There is no distinction between False/None.
6) Any other comparison returns False
"""
if isinstance(other, str):
return other == self.name
elif other is self:
return True
elif not (hasattr(other, "ordered") and hasattr(other, "categories")):
return False
elif self.categories is None or other.categories is None:
# For non-fully-initialized dtypes, these are only equal to
# - the string "category" (handled above)
# - other CategoricalDtype with categories=None
return self.categories is other.categories
elif self.ordered or other.ordered:
# At least one has ordered=True; equal if both have ordered=True
# and the same values for categories in the same order.
return (self.ordered == other.ordered) and self.categories.equals(
other.categories
)
else:
# Neither has ordered=True; equal if both have the same categories,
# but same order is not necessary. There is no distinction between
# ordered=False and ordered=None: CDT(., False) and CDT(., None)
# will be equal if they have the same categories.
left = self.categories
right = other.categories
# GH#36280 the ordering of checks here is for performance
if not left.dtype == right.dtype:
return False
if len(left) != len(right):
return False
if self.categories.equals(other.categories):
# Check and see if they happen to be identical categories
return True
if left.dtype != object:
# Faster than calculating hash
indexer = left.get_indexer(right)
# Because left and right have the same length and are unique,
# `indexer` not having any -1s implies that there is a
# bijection between `left` and `right`.
return bool((indexer != -1).all())
# With object-dtype we need a comparison that identifies
# e.g. int(2) as distinct from float(2)
return set(left) == set(right)
def __repr__(self) -> str_type:
if self.categories is None:
data = "None"
dtype = "None"
else:
data = self.categories._format_data(name=type(self).__name__)
if isinstance(self.categories, ABCRangeIndex):
data = str(self.categories._range)
data = data.rstrip(", ")
dtype = self.categories.dtype
return (
f"CategoricalDtype(categories={data}, ordered={self.ordered}, "
f"categories_dtype={dtype})"
)
@cache_readonly
def _hash_categories(self) -> int:
from pandas.core.util.hashing import (
combine_hash_arrays,
hash_array,
hash_tuples,
)
categories = self.categories
ordered = self.ordered
if len(categories) and isinstance(categories[0], tuple):
# assumes if any individual category is a tuple, then all our. ATM
# I don't really want to support just some of the categories being
# tuples.
cat_list = list(categories) # breaks if an np.array of categories
cat_array = hash_tuples(cat_list)
else:
if categories.dtype == "O" and len({type(x) for x in categories}) != 1:
# TODO: hash_array doesn't handle mixed types. It casts
# everything to a str first, which means we treat
# {'1', '2'} the same as {'1', 2}
# find a better solution
hashed = hash((tuple(categories), ordered))
return hashed
if DatetimeTZDtype.is_dtype(categories.dtype):
# Avoid future warning.
categories = categories.view("datetime64[ns]")
cat_array = hash_array(np.asarray(categories), categorize=False)
if ordered:
cat_array = np.vstack(
[cat_array, np.arange(len(cat_array), dtype=cat_array.dtype)]
)
else:
cat_array = cat_array.reshape(1, len(cat_array))
combined_hashed = combine_hash_arrays(iter(cat_array), num_items=len(cat_array))
return np.bitwise_xor.reduce(combined_hashed)
def construct_array_type(self) -> type_t[Categorical]:
"""
Return the array type associated with this dtype.
Returns
-------
type
"""
from pandas import Categorical
return Categorical
@staticmethod
def validate_ordered(ordered: Ordered) -> None:
"""
Validates that we have a valid ordered parameter. If
it is not a boolean, a TypeError will be raised.
Parameters
----------
ordered : object
The parameter to be verified.
Raises
------
TypeError
If 'ordered' is not a boolean.
"""
if not is_bool(ordered):
raise TypeError("'ordered' must either be 'True' or 'False'")
@staticmethod
def validate_categories(categories, fastpath: bool = False) -> Index:
"""
Validates that we have good categories
Parameters
----------
categories : array-like
fastpath : bool
Whether to skip nan and uniqueness checks
Returns
-------
categories : Index
"""
from pandas.core.indexes.base import Index
if not fastpath and not is_list_like(categories):
raise TypeError(
f"Parameter 'categories' must be list-like, was {categories!r}"
)
if not isinstance(categories, ABCIndex):
categories = Index._with_infer(categories, tupleize_cols=False)
if not fastpath:
if categories.hasnans:
raise ValueError("Categorical categories cannot be null")
if not categories.is_unique:
raise ValueError("Categorical categories must be unique")
if isinstance(categories, ABCCategoricalIndex):
categories = categories.categories
return categories
def update_dtype(self, dtype: str_type | CategoricalDtype) -> CategoricalDtype:
"""
Returns a CategoricalDtype with categories and ordered taken from dtype
if specified, otherwise falling back to self if unspecified
Parameters
----------
dtype : CategoricalDtype
Returns
-------
new_dtype : CategoricalDtype
"""
if isinstance(dtype, str) and dtype == "category":
# dtype='category' should not change anything
return self
elif not self.is_dtype(dtype):
raise ValueError(
f"a CategoricalDtype must be passed to perform an update, got {dtype!r}"
)
else:
# from here on, dtype is a CategoricalDtype
dtype = cast(CategoricalDtype, dtype)
# update categories/ordered unless they've been explicitly passed as None
if (
isinstance(dtype, CategoricalDtype)
and dtype.categories is not None
and dtype.ordered is not None
):
# Avoid re-validation in CategoricalDtype constructor
return dtype
new_categories = (
dtype.categories if dtype.categories is not None else self.categories
)
new_ordered = dtype.ordered if dtype.ordered is not None else self.ordered
return CategoricalDtype(new_categories, new_ordered)
@property
def categories(self) -> Index:
"""
An ``Index`` containing the unique categories allowed.
See Also
--------
ordered : Whether the categories have an ordered relationship.
Examples
--------
>>> cat_type = pd.CategoricalDtype(categories=["a", "b"], ordered=True)
>>> cat_type.categories
Index(['a', 'b'], dtype='str')
"""
return self._categories
@property
def ordered(self) -> Ordered:
"""
Whether the categories have an ordered relationship.
See Also
--------
categories : An Index containing the unique categories allowed.
Examples
--------
>>> cat_type = pd.CategoricalDtype(categories=["a", "b"], ordered=True)
>>> cat_type.ordered
True
>>> cat_type = pd.CategoricalDtype(categories=["a", "b"], ordered=False)
>>> cat_type.ordered
False
"""
return self._ordered
@property
def _is_boolean(self) -> bool:
from pandas.core.dtypes.common import is_bool_dtype
return is_bool_dtype(self.categories)
def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None:
# check if we have all categorical dtype with identical categories
if all(isinstance(x, CategoricalDtype) for x in dtypes):
first = dtypes[0]
if all(first == other for other in dtypes[1:]):
return first
# special case non-initialized categorical
# TODO we should figure out the expected return value in general
non_init_cats = [
isinstance(x, CategoricalDtype) and x.categories is None for x in dtypes
]
if all(non_init_cats):
return self
elif any(non_init_cats):
return None
# categorical is aware of Sparse -> extract sparse subdtypes
subtypes = (x.subtype if isinstance(x, SparseDtype) else x for x in dtypes)
# extract the categories' dtype
non_cat_dtypes = [
x.categories.dtype if isinstance(x, CategoricalDtype) else x
for x in subtypes
]
# TODO should categorical always give an answer?
from pandas.core.dtypes.cast import find_common_type
return find_common_type(non_cat_dtypes)
@cache_readonly
def index_class(self) -> type_t[CategoricalIndex]:
from pandas import CategoricalIndex
return CategoricalIndex
@register_extension_dtype
@set_module("pandas")
| CategoricalDtype |
python | django__django | tests/async/models.py | {
"start": 65,
"end": 174
} | class ____(models.Model):
simple = models.ForeignKey("SimpleModel", models.CASCADE, null=True)
| RelatedModel |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_ops.py | {
"start": 4069,
"end": 4423
} | class ____(TestCase):
def test_quantize(self):
x = torch.randn(3, 4, 5, dtype=torch.float32, device="openreg")
quantized_tensor = torch.quantize_per_tensor(x, 0.1, 10, torch.qint8)
self.assertEqual(quantized_tensor.device, torch.device("openreg:0"))
self.assertEqual(quantized_tensor.dtype, torch.qint8)
| TestQuantization |
python | huggingface__transformers | src/transformers/models/vitpose_backbone/configuration_vitpose_backbone.py | {
"start": 887,
"end": 6651
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VitPoseBackbone`]. It is used to instantiate a
VitPose model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the VitPose
[usyd-community/vitpose-base-simple](https://huggingface.co/usyd-community/vitpose-base-simple) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
image_size (`int`, *optional*, defaults to `[256, 192]`):
The size (resolution) of each image.
patch_size (`list[int]`, *optional*, defaults to `[16, 16]`):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
mlp_ratio (`int`, *optional*, defaults to 4):
The ratio of the hidden size in the feedforward network to the hidden size in the attention layers.
num_experts (`int`, *optional*, defaults to 1):
The number of experts in the MoE layer.
part_features (`int`, *optional*):
The number of part features to output. Only used in case `num_experts` is greater than 1.
hidden_act (`str`, *optional*, defaults to `"gelu"`):
The non-linear activation function in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether to add a bias to the queries, keys and values.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
Example:
```python
>>> from transformers import VitPoseBackboneConfig, VitPoseBackbone
>>> # Initializing a VitPose configuration
>>> configuration = VitPoseBackboneConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = VitPoseBackbone(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "vitpose_backbone"
def __init__(
self,
image_size=[256, 192],
patch_size=[16, 16],
num_channels=3,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
mlp_ratio=4,
num_experts=1,
part_features=256,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
qkv_bias=True,
out_features=None,
out_indices=None,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.mlp_ratio = mlp_ratio
self.num_experts = num_experts
self.part_features = part_features
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.qkv_bias = qkv_bias
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, num_hidden_layers + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
__all__ = ["VitPoseBackboneConfig"]
| VitPoseBackboneConfig |
python | rushter__MLAlgorithms | mla/neuralnet/parameters.py | {
"start": 95,
"end": 2892
} | class ____(object):
def __init__(
self,
init="glorot_uniform",
scale=0.5,
bias=1.0,
regularizers=None,
constraints=None,
):
"""A container for layer's parameters.
Parameters
----------
init : str, default 'glorot_uniform'.
The name of the weight initialization function.
scale : float, default 0.5
bias : float, default 1.0
Initial values for bias.
regularizers : dict
Weight regularizers.
>>> {'W' : L2()}
constraints : dict
Weight constraints.
>>> {'b' : MaxNorm()}
"""
if constraints is None:
self.constraints = {}
else:
self.constraints = constraints
if regularizers is None:
self.regularizers = {}
else:
self.regularizers = regularizers
self.initial_bias = bias
self.scale = scale
self.init = get_initializer(init)
self._params = {}
self._grads = {}
def setup_weights(self, W_shape, b_shape=None):
if "W" not in self._params:
self._params["W"] = self.init(shape=W_shape, scale=self.scale)
if b_shape is None:
self._params["b"] = np.full(W_shape[1], self.initial_bias)
else:
self._params["b"] = np.full(b_shape, self.initial_bias)
self.init_grad()
def init_grad(self):
"""Init gradient arrays corresponding to each weight array."""
for key in self._params.keys():
if key not in self._grads:
self._grads[key] = np.zeros_like(self._params[key])
def step(self, name, step):
"""Increase specific weight by amount of the step parameter."""
self._params[name] += step
if name in self.constraints:
self._params[name] = self.constraints[name].clip(self._params[name])
def update_grad(self, name, value):
"""Update gradient values."""
self._grads[name] = value
if name in self.regularizers:
self._grads[name] += self.regularizers[name](self._params[name])
@property
def n_params(self):
"""Count the number of parameters in this layer."""
return sum([np.prod(self._params[x].shape) for x in self._params.keys()])
def keys(self):
return self._params.keys()
@property
def grad(self):
return self._grads
# Allow access to the fields using dict syntax, e.g. parameters['W']
def __getitem__(self, item):
if item in self._params:
return self._params[item]
else:
raise ValueError
def __setitem__(self, key, value):
self._params[key] = value
| Parameters |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 181252,
"end": 181549
} | class ____(_MatrixMixin, TestCSC):
@classmethod
def spcreator(cls, *args, **kwargs):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", WMSG, SparseEfficiencyWarning)
return csc_matrix(*args, **kwargs)
TestCSCMatrix.init_class()
| TestCSCMatrix |
python | keon__algorithms | tests/test_graph.py | {
"start": 9176,
"end": 9729
} | class ____(unittest.TestCase):
def test_digraph_strongly_connected(self):
g1 = check_digraph_strongly_connected.Graph(5)
g1.add_edge(0, 1)
g1.add_edge(1, 2)
g1.add_edge(2, 3)
g1.add_edge(3, 0)
g1.add_edge(2, 4)
g1.add_edge(4, 2)
self.assertTrue(g1.is_strongly_connected())
g2 = check_digraph_strongly_connected.Graph(4)
g2.add_edge(0, 1)
g2.add_edge(1, 2)
g2.add_edge(2, 3)
self.assertFalse(g2.is_strongly_connected())
| TestDigraphStronglyConnected |
python | PyCQA__mccabe | mccabe.py | {
"start": 1291,
"end": 1583
} | class ____(object):
def __init__(self, name, look="circle"):
self.name = name
self.look = look
def to_dot(self):
print('node [shape=%s,label="%s"] %d;' % (
self.look, self.name, self.dot_id()))
def dot_id(self):
return id(self)
| PathNode |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/win32_types.py | {
"start": 2285,
"end": 2507
} | class ____(Structure):
"""
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687093(v=vs.85).aspx
"""
if TYPE_CHECKING:
Size: COORD
_fields_ = [("Size", COORD)]
| WINDOW_BUFFER_SIZE_RECORD |
python | GoogleCloudPlatform__python-docs-samples | endpoints/bookstore-grpc-transcoding/bookstore.py | {
"start": 595,
"end": 776
} | class ____:
"""The contents of a single shelf."""
def __init__(self, shelf):
self._shelf = shelf
self._last_book_id = 0
self._books = dict()
| ShelfInfo |
python | realpython__materials | python-oop/dogbreeds.py | {
"start": 282,
"end": 385
} | class ____(Dog):
def speak(self, sound="Arf"):
return super().speak(sound)
| JackRussellTerrier |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/database.py | {
"start": 3682,
"end": 5557
} | class ____(abc.ABCMeta):
def __call__(self, *args: Any, **kwargs: Any) -> "ExampleDatabase":
if self is ExampleDatabase:
note_deprecation(
"Creating a database using the abstract ExampleDatabase() class "
"is deprecated. Prefer using a concrete subclass, like "
"InMemoryExampleDatabase() or DirectoryBasedExampleDatabase(path). "
'In particular, the special string ExampleDatabase(":memory:") '
"should be replaced by InMemoryExampleDatabase().",
since="2025-04-07",
has_codemod=False,
)
return _db_for_path(*args, **kwargs)
return super().__call__(*args, **kwargs)
# This __call__ method is picked up by Sphinx as the signature of all ExampleDatabase
# subclasses, which is accurate, reasonable, and unhelpful. Fortunately Sphinx
# maintains a list of metaclass-call-methods to ignore, and while they would prefer
# not to maintain it upstream (https://github.com/sphinx-doc/sphinx/pull/8262) we
# can insert ourselves here.
#
# This code only runs if Sphinx has already been imported; and it would live in our
# docs/conf.py except that we would also like it to work for anyone documenting
# downstream ExampleDatabase subclasses too.
if "sphinx" in sys.modules:
try:
import sphinx.ext.autodoc
signature = "hypothesis.database._EDMeta.__call__"
# _METACLASS_CALL_BLACKLIST is a frozenset in later sphinx versions
if isinstance(sphinx.ext.autodoc._METACLASS_CALL_BLACKLIST, frozenset):
sphinx.ext.autodoc._METACLASS_CALL_BLACKLIST = (
sphinx.ext.autodoc._METACLASS_CALL_BLACKLIST | {signature}
)
else:
sphinx.ext.autodoc._METACLASS_CALL_BLACKLIST.append(signature)
except Exception:
pass
| _EDMeta |
python | PrefectHQ__prefect | src/prefect/server/schemas/graph.py | {
"start": 569,
"end": 614
} | class ____(PrefectBaseModel):
id: UUID
| Edge |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/utils.py | {
"start": 2552,
"end": 3246
} | class ____:
"""
Enum for Apache Arrow C type format strings.
The Arrow C data interface:
https://arrow.apache.org/docs/format/CDataInterface.html#data-type-description-format-strings
"""
NULL = "n"
BOOL = "b"
INT8 = "c"
UINT8 = "C"
INT16 = "s"
UINT16 = "S"
INT32 = "i"
UINT32 = "I"
INT64 = "l"
UINT64 = "L"
FLOAT16 = "e"
FLOAT32 = "f"
FLOAT64 = "g"
STRING = "u" # utf-8
DATE32 = "tdD"
DATE64 = "tdm"
# Resoulution:
# - seconds -> 's'
# - miliseconds -> 'm'
# - microseconds -> 'u'
# - nanoseconds -> 'n'
TIMESTAMP = "ts{resolution}:{tz}"
TIME = "tt{resolution}"
| ArrowCTypes |
python | huggingface__transformers | src/transformers/generation/watermarking.py | {
"start": 12292,
"end": 12814
} | class ____(ModelOutput):
"""
Base class for outputs of models predicting if the text is watermarked.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
Multiple choice classification loss.
"""
loss: torch.FloatTensor | None = None
posterior_probabilities: torch.FloatTensor | None = None
| BayesianWatermarkDetectorModelOutput |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 85709,
"end": 86550
} | class ____(nn.Module):
def __init__(self, config: DFineConfig):
super().__init__()
self.top_prob_values = config.top_prob_values
self.max_num_bins = config.max_num_bins
self.reg_conf = DFineMLP(4 * (self.top_prob_values + 1), config.lqe_hidden_dim, 1, config.lqe_layers)
def forward(self, scores: torch.Tensor, pred_corners: torch.Tensor) -> torch.Tensor:
batch_size, length, _ = pred_corners.size()
prob = F.softmax(pred_corners.reshape(batch_size, length, 4, self.max_num_bins + 1), dim=-1)
prob_topk, _ = prob.topk(self.top_prob_values, dim=-1)
stat = torch.cat([prob_topk, prob_topk.mean(dim=-1, keepdim=True)], dim=-1)
quality_score = self.reg_conf(stat.reshape(batch_size, length, -1))
scores = scores + quality_score
return scores
| DFineLQE |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 160426,
"end": 161254
} | class ____(torch.nn.Module):
def forward(self, L_model_parameters_weight_: "f32[3, 3]", L_model_parameters_bias_: "f32[3]", L_inputs_: "f32[64, 3]", L_targets_: "f32[64, 3]"):
l_model_parameters_weight_ = L_model_parameters_weight_
l_model_parameters_bias_ = L_model_parameters_bias_
l_inputs_ = L_inputs_
l_targets_ = L_targets_
prediction: "f32[64, 3]" = torch._C._nn.linear(l_inputs_, l_model_parameters_weight_, l_model_parameters_bias_); l_inputs_ = l_model_parameters_weight_ = l_model_parameters_bias_ = None
mse_loss: "f32[]" = torch.nn.functional.mse_loss(prediction, l_targets_); prediction = l_targets_ = None
return (mse_loss,)
""",
)
else:
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 14719,
"end": 20677
} | class ____(unittest.TestCase):
@unittest.skipIf(_testcapi is None, 'need _testcapi')
def test_socket(self):
# use a subprocess to have only one thread
code = """if 1:
import signal
import socket
import struct
import _testcapi
signum = signal.SIGINT
signals = (signum,)
def handler(signum, frame):
pass
signal.signal(signum, handler)
read, write = socket.socketpair()
write.setblocking(False)
signal.set_wakeup_fd(write.fileno())
signal.raise_signal(signum)
data = read.recv(1)
if not data:
raise Exception("no signum written")
raised = struct.unpack('B', data)
if raised != signals:
raise Exception("%r != %r" % (raised, signals))
read.close()
write.close()
"""
assert_python_ok('-c', code)
@unittest.skipIf(_testcapi is None, 'need _testcapi')
def test_send_error(self):
# Use a subprocess to have only one thread.
if os.name == 'nt':
action = 'send'
else:
action = 'write'
code = """if 1:
import errno
import signal
import socket
import sys
import time
import _testcapi
from test.support import captured_stderr
signum = signal.SIGINT
def handler(signum, frame):
pass
signal.signal(signum, handler)
read, write = socket.socketpair()
read.setblocking(False)
write.setblocking(False)
signal.set_wakeup_fd(write.fileno())
# Close sockets: send() will fail
read.close()
write.close()
with captured_stderr() as err:
signal.raise_signal(signum)
err = err.getvalue()
if ('Exception ignored when trying to {action} to the signal wakeup fd'
not in err):
raise AssertionError(err)
""".format(action=action)
assert_python_ok('-c', code)
@unittest.skipIf(_testcapi is None, 'need _testcapi')
def test_warn_on_full_buffer(self):
# Use a subprocess to have only one thread.
if os.name == 'nt':
action = 'send'
else:
action = 'write'
code = """if 1:
import errno
import signal
import socket
import sys
import time
import _testcapi
from test.support import captured_stderr
signum = signal.SIGINT
# This handler will be called, but we intentionally won't read from
# the wakeup fd.
def handler(signum, frame):
pass
signal.signal(signum, handler)
read, write = socket.socketpair()
# Fill the socketpair buffer
if sys.platform == 'win32':
# bpo-34130: On Windows, sometimes non-blocking send fails to fill
# the full socketpair buffer, so use a timeout of 50 ms instead.
write.settimeout(0.050)
else:
write.setblocking(False)
written = 0
if sys.platform == "vxworks":
CHUNK_SIZES = (1,)
else:
# Start with large chunk size to reduce the
# number of send needed to fill the buffer.
CHUNK_SIZES = (2 ** 16, 2 ** 8, 1)
for chunk_size in CHUNK_SIZES:
chunk = b"x" * chunk_size
try:
while True:
write.send(chunk)
written += chunk_size
except (BlockingIOError, TimeoutError):
pass
print(f"%s bytes written into the socketpair" % written, flush=True)
write.setblocking(False)
try:
write.send(b"x")
except BlockingIOError:
# The socketpair buffer seems full
pass
else:
raise AssertionError("%s bytes failed to fill the socketpair "
"buffer" % written)
# By default, we get a warning when a signal arrives
msg = ('Exception ignored when trying to {action} '
'to the signal wakeup fd')
signal.set_wakeup_fd(write.fileno())
with captured_stderr() as err:
signal.raise_signal(signum)
err = err.getvalue()
if msg not in err:
raise AssertionError("first set_wakeup_fd() test failed, "
"stderr: %r" % err)
# And also if warn_on_full_buffer=True
signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=True)
with captured_stderr() as err:
signal.raise_signal(signum)
err = err.getvalue()
if msg not in err:
raise AssertionError("set_wakeup_fd(warn_on_full_buffer=True) "
"test failed, stderr: %r" % err)
# But not if warn_on_full_buffer=False
signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False)
with captured_stderr() as err:
signal.raise_signal(signum)
err = err.getvalue()
if err != "":
raise AssertionError("set_wakeup_fd(warn_on_full_buffer=False) "
"test failed, stderr: %r" % err)
# And then check the default again, to make sure warn_on_full_buffer
# settings don't leak across calls.
signal.set_wakeup_fd(write.fileno())
with captured_stderr() as err:
signal.raise_signal(signum)
err = err.getvalue()
if msg not in err:
raise AssertionError("second set_wakeup_fd() test failed, "
"stderr: %r" % err)
""".format(action=action)
assert_python_ok('-c', code)
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
@unittest.skipUnless(hasattr(signal, 'siginterrupt'), "needs signal.siginterrupt()")
| WakeupSocketSignalTests |
python | sympy__sympy | sympy/physics/mechanics/tests/test_wrapping_geometry.py | {
"start": 669,
"end": 4343
} | class ____:
@staticmethod
def test_valid_constructor():
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
assert isinstance(sphere, WrappingSphere)
assert hasattr(sphere, 'radius')
assert sphere.radius == r
assert hasattr(sphere, 'point')
assert sphere.point == pO
@staticmethod
@pytest.mark.parametrize(
'position_1, position_2, expected',
[
(r*N.x, r*N.x, S.Zero),
(r*N.x, r*N.y, S.Half*pi*r),
(r*N.x, r*-N.x, pi*r),
(r*-N.x, r*N.x, pi*r),
(r*N.x, r*sqrt(2)*S.Half*(N.x + N.y), Rational(1, 4)*pi*r),
(
r*sqrt(2)*S.Half*(N.x + N.y),
r*sqrt(3)*Rational(1, 3)*(N.x + N.y + N.z),
r*acos(sqrt(6)*Rational(1, 3)),
),
]
)
def test_geodesic_length(position_1, position_2, expected):
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
p1 = Point('p1')
p1.set_pos(pO, position_1)
p2 = Point('p2')
p2.set_pos(pO, position_2)
assert simplify(Eq(sphere.geodesic_length(p1, p2), expected))
@staticmethod
@pytest.mark.parametrize(
'position_1, position_2, vector_1, vector_2',
[
(r * N.x, r * N.y, N.y, N.x),
(r * N.x, -r * N.y, -N.y, N.x),
(
r * N.y,
sqrt(2)/2 * r * N.x - sqrt(2)/2 * r * N.y,
N.x,
sqrt(2)/2 * N.x + sqrt(2)/2 * N.y,
),
(
r * N.x,
r / 2 * N.x + sqrt(3)/2 * r * N.y,
N.y,
sqrt(3)/2 * N.x - 1/2 * N.y,
),
(
r * N.x,
sqrt(2)/2 * r * N.x + sqrt(2)/2 * r * N.y,
N.y,
sqrt(2)/2 * N.x - sqrt(2)/2 * N.y,
),
]
)
def test_geodesic_end_vectors(position_1, position_2, vector_1, vector_2):
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
p1 = Point('p1')
p1.set_pos(pO, position_1)
p2 = Point('p2')
p2.set_pos(pO, position_2)
expected = (vector_1, vector_2)
assert sphere.geodesic_end_vectors(p1, p2) == expected
@staticmethod
@pytest.mark.parametrize(
'position',
[r * N.x, r * cos(q) * N.x + r * sin(q) * N.y]
)
def test_geodesic_end_vectors_invalid_coincident(position):
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
p1 = Point('p1')
p1.set_pos(pO, position)
p2 = Point('p2')
p2.set_pos(pO, position)
with pytest.raises(ValueError):
_ = sphere.geodesic_end_vectors(p1, p2)
@staticmethod
@pytest.mark.parametrize(
'position_1, position_2',
[
(r * N.x, -r * N.x),
(-r * N.y, r * N.y),
(
r * cos(q) * N.x + r * sin(q) * N.y,
-r * cos(q) * N.x - r * sin(q) * N.y,
)
]
)
def test_geodesic_end_vectors_invalid_diametrically_opposite(
position_1,
position_2,
):
r = Symbol('r', positive=True)
pO = Point('pO')
sphere = WrappingSphere(r, pO)
p1 = Point('p1')
p1.set_pos(pO, position_1)
p2 = Point('p2')
p2.set_pos(pO, position_2)
with pytest.raises(ValueError):
_ = sphere.geodesic_end_vectors(p1, p2)
| TestWrappingSphere |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/conditional_accumulator_test.py | {
"start": 1336,
"end": 17514
} | class ____(test.TestCase):
def testConstructorWithInvalidArg(self):
with ops.Graph().as_default():
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", reduction_type="Invalid")
@test_util.run_deprecated_v1
def testAccumulatorSizeEmpty(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(dtypes_lib.float32, name="Q")
self.assertEqual(q.num_accumulated().eval(), 0)
@test_util.run_deprecated_v1
def testAccumulatorSetGlobalStep(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
set_global_step_op = q.set_global_step(1)
set_global_step_op.run()
@test_util.run_deprecated_v1
def testAccumulatorApplyGradFloat32(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
accum_op.run()
@test_util.run_deprecated_v1
def testDtypes(self):
with self.cached_session() as sess:
dtypes = [dtypes_lib.float16, dtypes_lib.float32, dtypes_lib.float64]
for i in range(len(dtypes)):
dtype = dtypes[i]
q = data_flow_ops.ConditionalAccumulator(
dtype, shape=tensor_shape.TensorShape([1]))
elems = np.arange(10).astype(dtype.as_numpy_dtype)
for e in elems:
q.apply_grad((e,)).run()
result = self.evaluate(q.take_grad(1))
self.assertEqual(sum(elems) / len(elems), result)
@test_util.run_deprecated_v1
def testAccumulatorMultipleAccumulators(self):
with self.cached_session():
q_f32_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f32_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
accums = [q_f16_0, q_f16_1, q_f32_0, q_f32_1]
for i in range(len(accums)):
accums[i].apply_grad((i + 10.0,)).run()
for i in range(len(accums)):
result = accums[i].take_grad(1).eval()
self.assertEqual(result, i + 10.0)
@test_util.run_deprecated_v1
def testAccumulatorApplyAndTakeGradWithShape(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(x, y)]
for x, y in zip(elems[0], elems[1])]
accum_ops = [q.apply_grad(x) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
is_all_equal = True
val = self.evaluate(takeg_t)
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
@test_util.run_deprecated_v1
def testAccumulatorApplyGradWithWrongShape(self):
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
with self.assertRaises(ValueError):
q.apply_grad([[1.0, 2.0], [3.0, 4.0]])
with self.assertRaises(ValueError):
q.apply_grad([[1.0], [2.0], [3.0]])
@test_util.run_deprecated_v1
def testAccumulatorDynamicShape(self):
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(c, d)]
for c, d in zip(elems[0], elems[1])]
takeg_t = q.take_grad(1)
for elem in elems:
sess.run(accum_op, feed_dict={x: elem})
is_all_equal = True
val = self.evaluate(takeg_t)
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
@test_util.run_v1_only("b/120545219")
def testAccumulatorWrongDynamicShape(self):
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
# First successful apply_grad determines shape
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0], [2.0], [3.0]]})
@test_util.run_deprecated_v1
def testAccumulatorSizeAfterApplyGrad(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
@test_util.run_deprecated_v1
def testAccumulatorSizeAfterApplyGradAndTakeGrad(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
extract_t = q.take_grad(2)
# Applying gradient multiple times to increase size from 0 to 2.
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
# Extract will reduce size to 0
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
# Take gradients always sets the size back to 0 if successful.
accum_op = q.apply_grad((10.0,), local_step=1)
accum_op.run()
accum_op.run()
accum_op.run()
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 4)
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
@test_util.run_deprecated_v1
def testAccumulatorTakeGradMean(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(15.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(15.0, val)
@test_util.run_deprecated_v1
def testAccumulatorTakeGradSum(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(30.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(30.0, val)
@test_util.run_deprecated_v1
def testAccumulatorTakeGradInvalidReductionType(self):
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="Invalid")
@test_util.run_v1_only("b/120545219")
def testAccumulatorInvalidTakeGrad(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,)) for x in elems]
takeg_t = q.take_grad(-1)
for accum_op in accum_ops:
accum_op.run()
with self.assertRaises(errors_impl.InvalidArgumentError):
self.evaluate(takeg_t)
@test_util.run_deprecated_v1
def testAccumulatorRepeatedTakeGradMean(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(elems_ave, val)
elems = [20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(elems_ave + 0.0, val)
@test_util.run_deprecated_v1
def testAccumulatorRepeatedTakeGradSum(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
elems_sum = 30.0
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(elems_sum, val)
elems = [20.0, 30.0]
elems_sum = 50.0
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = self.evaluate(takeg_t)
self.assertEqual(elems_sum, val)
@test_util.run_deprecated_v1
def testAccumulatorIncrementGlobalStep(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
global_step = variables.Variable(0, name="global_step")
new_global_step = math_ops.add(global_step, 1)
inc_global_step = state_ops.assign(global_step, new_global_step)
set_global_step_op = q.set_global_step(new_global_step)
self.evaluate(variables.global_variables_initializer())
for _ in range(3):
set_global_step_op.run()
self.evaluate(inc_global_step)
@test_util.run_deprecated_v1
def testAccumulatorSetGlobalStepPreventsAccumulation(self):
with self.cached_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
local_steps = range(1000, 1005)
accum_ops = [q.apply_grad((0.0 + x,), local_step=x) for x in local_steps]
for ls in local_steps:
set_global_step_op = q.set_global_step(ls)
set_global_step_op.run()
for accum_op in accum_ops:
accum_op.run()
takeg_t = q.take_grad(1)
val = self.evaluate(takeg_t)
self.assertEqual(0.0 + sum(x for x in local_steps
if x >= ls) / sum(1 for x in local_steps
if x >= ls), val)
@test_util.run_v1_only("b/120545219")
def testParallelApplyGrad(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
def apply_grad(accum_op):
self.evaluate(accum_op)
threads = [
self.checkedThread(
target=apply_grad, args=(o,)) for o in accum_ops
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
val = self.evaluate(takeg_t)
self.assertEqual(val, sum(elems) / len(elems))
@test_util.run_v1_only("b/120545219")
def testParallelTakeGrad(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [e for e in range(10)]
accum_ops = [q.apply_grad((np.float32(e),), local_step=e) for e in elems]
takeg_t = q.take_grad(1)
def apply_grad():
for accum_op in accum_ops:
time.sleep(1.0)
self.evaluate(accum_op)
apply_grad_thread = self.checkedThread(target=apply_grad)
results = []
def take_grad():
results.append(self.evaluate(takeg_t))
threads = [self.checkedThread(target=take_grad) for _ in range(10)]
for thread in threads:
thread.start()
apply_grad_thread.start()
for thread in threads:
thread.join()
apply_grad_thread.join()
self.assertItemsEqual(elems, results)
@test_util.run_v1_only("b/120545219")
def testAccumulatorApplyAndBlockingTake(self):
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.get_default_graph().switch_to_thread_local()
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(3)
def apply_grad():
time.sleep(1.0)
for accum_op in accum_ops:
self.evaluate(accum_op)
return_array = []
def take_grad():
return_array.append(self.evaluate(takeg_t))
accum_thread = self.checkedThread(target=apply_grad)
takeg_thread = self.checkedThread(target=take_grad)
accum_thread.start()
takeg_thread.start()
accum_thread.join()
takeg_thread.join()
self.assertEqual([elems_ave], return_array)
def _blocking_takeg(self, sess, takeg_op):
with self.assertRaisesOpError("was cancelled"):
self.evaluate(takeg_op)
@test_util.run_v1_only("b/120545219")
def testAccumulatorCancel(self):
with self.cached_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
takeg_t = q.take_grad(1)
takeg_thread = self.checkedThread(
self._blocking_takeg, args=(sess, takeg_t))
takeg_thread.start()
time.sleep(1.0)
sess.close() # Will cancel blocked operation
takeg_thread.join()
if __name__ == "__main__":
test.main()
| ConditionalAccumulatorTest |
python | django__django | tests/delete/models.py | {
"start": 420,
"end": 490
} | class ____(models.Model):
r = models.ForeignKey(R, models.CASCADE)
| S |
python | hynek__structlog | src/structlog/exceptions.py | {
"start": 320,
"end": 505
} | class ____(BaseException):
"""
If raised by an processor, the event gets silently dropped.
Derives from BaseException because it's technically not an error.
"""
| DropEvent |
python | doocs__leetcode | solution/0800-0899/0812.Largest Triangle Area/Solution.py | {
"start": 0,
"end": 403
} | class ____:
def largestTriangleArea(self, points: List[List[int]]) -> float:
ans = 0
for x1, y1 in points:
for x2, y2 in points:
for x3, y3 in points:
u1, v1 = x2 - x1, y2 - y1
u2, v2 = x3 - x1, y3 - y1
t = abs(u1 * v2 - u2 * v1) / 2
ans = max(ans, t)
return ans
| Solution |
python | ray-project__ray | python/ray/dashboard/modules/reporter/healthz_agent.py | {
"start": 311,
"end": 2069
} | class ____(dashboard_utils.DashboardAgentModule):
"""Health check in the agent.
This module adds health check related endpoint to the agent to check
local components' health.
"""
def __init__(self, dashboard_agent):
super().__init__(dashboard_agent)
node_id = (
NodeID.from_hex(dashboard_agent.node_id)
if dashboard_agent.node_id
else None
)
self._health_checker = HealthChecker(
dashboard_agent.gcs_client,
node_id,
)
@routes.get("/api/local_raylet_healthz")
async def health_check(self, req: Request) -> Response:
try:
alive = await self._health_checker.check_local_raylet_liveness()
if alive is False:
return Response(status=503, text="Local Raylet failed")
except ray.exceptions.RpcError as e:
# We only consider the error other than GCS unreachable as raylet failure
# to avoid false positive.
# In case of GCS failed, Raylet will crash eventually if GCS is not back
# within a given time and the check will fail since agent can't live
# without a local raylet.
if e.rpc_code not in (
ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE,
ray._raylet.GRPC_STATUS_CODE_UNKNOWN,
ray._raylet.GRPC_STATUS_CODE_DEADLINE_EXCEEDED,
):
return Response(status=503, text=f"Health check failed due to: {e}")
return Response(
text="success",
content_type="application/text",
)
async def run(self, server):
pass
@staticmethod
def is_minimal_module():
return False
| HealthzAgent |
python | huggingface__transformers | src/transformers/integrations/executorch.py | {
"start": 26543,
"end": 34411
} | class ____(torch.nn.Module):
"""
A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
specifically for decoder-only LM to hybrid `StaticCache`. This module ensures that the
exported model is compatible with further lowering and execution in `ExecuTorch`.
"""
def __init__(
self,
model: PreTrainedModel,
batch_size: int | None = None,
max_cache_len: int | None = None,
device: torch.device | None = None,
) -> None:
"""
Initializes the exportable module.
Args:
model (`PreTrainedModel`): The pretrained model to wrap.
batch_size (`Optional[int]`): The batch size of the model. If not provided, we check if a value can be found
in `generation_config.cache_config` and otherwise we raise a ValueError.
max_cache_len (`Optional[int]`): The maximum cache length for generation. Same mechanism as `batch_size` if
not provided.
device (`Optional[torch.device]`): The device to use. If not provided, we check if a value can be found
in `generation_config.cache_config` and otherwise we use `model.device` (no error is raised).
Raises:
AssertionError: If the model doesn't have the expected configuration for hybrid StaticCache.
ValueError: If `batch_size` or `max_cache_len` is not provided, either as an argument or in `cache_config`.
"""
super().__init__()
self.model = model
config = model.config.get_text_config()
generation_config = model.generation_config
# Sanity checks
if generation_config is None:
raise AssertionError(
"The model must have a generation config to be exported with static caching. "
"Please set `generation_config` in `model`."
)
if not config.use_cache:
raise AssertionError("Model must have caching enabled.")
cache_config = {} if generation_config.cache_config is None else generation_config.cache_config
# Ensure batch_size and max_cache_len are set
if batch_size is None:
batch_size = cache_config.get("batch_size", None)
if batch_size is None:
raise ValueError("batch_size must be provided, either as an argument or in cache_config.")
if max_cache_len is None:
max_cache_len = cache_config.get("max_cache_len", None)
if max_cache_len is None:
raise ValueError("max_cache_len must be provided, either as an argument or in cache_config.")
# Infer device if not provided
if device is None:
device = cache_config.get("device", model.device)
# Initialize the cache
self.cache = StaticCache(config=config, max_cache_len=max_cache_len)
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
num_heads = getattr(config, "num_key_value_heads", config.num_attention_heads)
dtype = self.model.dtype
# We need this call to initialize all the layers (otherwise it's done lazily, which is not exportable)
self.cache.early_initialization(batch_size, num_heads, head_dim, dtype, device)
# Register all key and value cache tensors as buffers
for i in range(len(self.cache)):
self.register_buffer(f"key_cache_{i}", self.cache.layers[i].keys, persistent=False)
self.register_buffer(f"value_cache_{i}", self.cache.layers[i].values, persistent=False)
def forward(
self,
input_ids: torch.LongTensor | None = None,
inputs_embeds: torch.Tensor | None = None,
cache_position: torch.Tensor | None = None,
) -> torch.Tensor:
"""
Forward pass of the module, which is compatible with the ExecuTorch llm runner.
Args:
input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
inputs_embeds (`Optional[torch.Tensor]`): Tensor representing current input embeddings to the module.
cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
Returns:
torch.Tensor: Logits output from the model.
"""
# Forward pass with the model
outputs = self.model(
input_ids=input_ids,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
attention_mask=None,
past_key_values=self.cache,
use_cache=True,
)
# Return only the logits to simplify the export
return outputs.logits
def convert_and_export_with_cache(
model: PreTrainedModel,
example_input_ids: torch.Tensor | None = None,
example_cache_position: torch.Tensor | None = None,
dynamic_shapes: dict | None = None,
strict: bool | None = None,
):
"""
Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`,
ensuring the exported model is compatible with `ExecuTorch`.
Args:
model (`PreTrainedModel`): The pretrained model to be exported.
example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
example_cache_position (`Optional[torch.Tensor]`): Example current cache position used by `torch.export`.
dynamic_shapes(`Optional[dict]`): Dynamic shapes used by `torch.export`.
strict(`Optional[bool]`): Flag to instruct `torch.export` to use `torchdynamo`.
Returns:
Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
"""
if not is_torch_greater_or_equal_than_2_3:
raise ImportError("torch >= 2.3 is required.")
import torch.export._trace
with torch.no_grad():
# TODO: The default inputs only work for text models. We need to add support for vision/audio models.
example_input_ids = (
example_input_ids
if example_input_ids is not None
else torch.tensor([[1]], dtype=torch.long, device=model.device)
)
example_cache_position = (
example_cache_position
if example_cache_position is not None
else torch.tensor([0], dtype=torch.long, device=model.device)
)
if is_torch_greater_or_equal("2.6.0"):
exported_program = torch.export.export(
TorchExportableModuleWithStaticCache(model),
args=(),
kwargs={"input_ids": example_input_ids, "cache_position": example_cache_position},
dynamic_shapes=dynamic_shapes,
strict=strict if strict is not None else True,
)
else:
if dynamic_shapes is not None:
logging.warning(
"Dynamic shapes spec will be ignored by convert_and_export_with_cache for torch < 2.6.0."
)
if strict is not None:
logging.warning("The strict flag will be ignored by convert_and_export_with_cache for torch < 2.6.0.")
# We have to keep this path for BC.
#
# Due to issue https://github.com/pytorch/pytorch/issues/128394, we need to switch to use an internal
# export API and pre_dispatch=False. Switch to use the public API once the issue is included in 2.5 release.
exported_program = torch.export._trace._export(
TorchExportableModuleWithStaticCache(model),
args=(),
kwargs={"input_ids": example_input_ids, "cache_position": example_cache_position},
pre_dispatch=False,
strict=True,
)
return exported_program
| TorchExportableModuleWithHybridCache |
python | ipython__ipython | tests/test_pretty.py | {
"start": 14741,
"end": 15084
} | class ____(set): # Override repr of a basic type
def __repr__(self):
return "mine"
def test_custom_repr():
"""A custom repr should override a pretty printer for a parent type"""
oc = OrderedCounter("abracadabra")
assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
assert pretty.pretty(MySet()) == "mine"
| MySet |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/hooks/kubernetes.py | {
"start": 29517,
"end": 40688
} | class ____(KubernetesHook):
"""Hook to use Kubernetes SDK asynchronously."""
def __init__(self, config_dict: dict | None = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config_dict = config_dict
self._extras: dict | None = None
async def _load_config(self):
"""Return Kubernetes API session for use with requests."""
in_cluster = self._coalesce_param(self.in_cluster, await self._get_field("in_cluster"))
cluster_context = self._coalesce_param(self.cluster_context, await self._get_field("cluster_context"))
kubeconfig_path = await self._get_field("kube_config_path")
kubeconfig = await self._get_field("kube_config")
num_selected_configuration = sum(
1 for o in [in_cluster, kubeconfig, kubeconfig_path, self.config_dict] if o
)
async def api_client_from_kubeconfig_file(_kubeconfig_path: str | None):
await async_config.load_kube_config(
config_file=_kubeconfig_path,
client_configuration=self.client_configuration,
context=cluster_context,
)
return async_client.ApiClient()
if num_selected_configuration > 1:
raise AirflowException(
"Invalid connection configuration. Options kube_config_path, "
"kube_config, in_cluster are mutually exclusive. "
"You can only use one option at a time."
)
if in_cluster:
self.log.debug(LOADING_KUBE_CONFIG_FILE_RESOURCE.format("within a pod"))
self._is_in_cluster = True
async_config.load_incluster_config()
return async_client.ApiClient()
if self.config_dict:
self.log.debug(LOADING_KUBE_CONFIG_FILE_RESOURCE.format("config dictionary"))
self._is_in_cluster = False
await async_config.load_kube_config_from_dict(self.config_dict, context=cluster_context)
return async_client.ApiClient()
if kubeconfig_path is not None:
self.log.debug("loading kube_config from: %s", kubeconfig_path)
self._is_in_cluster = False
return await api_client_from_kubeconfig_file(kubeconfig_path)
if kubeconfig is not None:
async with aiofiles.tempfile.NamedTemporaryFile() as temp_config:
self.log.debug(
"Reading kubernetes configuration file from connection "
"object and writing temporary config file with its content",
)
if isinstance(kubeconfig, dict):
self.log.debug(
LOADING_KUBE_CONFIG_FILE_RESOURCE.format(
"connection kube_config dictionary (serializing)"
)
)
kubeconfig = json.dumps(kubeconfig)
await temp_config.write(kubeconfig.encode())
await temp_config.flush()
self._is_in_cluster = False
return await api_client_from_kubeconfig_file(temp_config.name)
self.log.debug(LOADING_KUBE_CONFIG_FILE_RESOURCE.format("default configuration file"))
await async_config.load_kube_config(
client_configuration=self.client_configuration,
context=cluster_context,
)
async def get_conn_extras(self) -> dict:
if self._extras is None:
if self.conn_id:
connection = await sync_to_async(self.get_connection)(self.conn_id)
self._extras = connection.extra_dejson
else:
self._extras = {}
return self._extras
async def _get_field(self, field_name):
if field_name.startswith("extra__"):
raise ValueError(
f"Got prefixed name {field_name}; please remove the 'extra__kubernetes__' prefix "
"when using this method."
)
extras = await self.get_conn_extras()
if field_name in extras:
return extras.get(field_name)
prefixed_name = f"extra__kubernetes__{field_name}"
return extras.get(prefixed_name)
@contextlib.asynccontextmanager
async def get_conn(self) -> async_client.ApiClient:
kube_client = None
try:
kube_client = await self._load_config() or async_client.ApiClient()
yield kube_client
finally:
if kube_client is not None:
await kube_client.close()
@generic_api_retry
async def get_pod(self, name: str, namespace: str) -> V1Pod:
"""
Get pod's object.
:param name: Name of the pod.
:param namespace: Name of the pod's namespace.
"""
async with self.get_conn() as connection:
try:
v1_api = async_client.CoreV1Api(connection)
pod: V1Pod = await v1_api.read_namespaced_pod(
name=name,
namespace=namespace,
)
return pod
except HTTPError as e:
if hasattr(e, "status") and e.status == 403:
raise KubernetesApiPermissionError("Permission denied (403) from Kubernetes API.") from e
raise KubernetesApiError from e
@generic_api_retry
async def delete_pod(self, name: str, namespace: str):
"""
Delete pod's object.
:param name: Name of the pod.
:param namespace: Name of the pod's namespace.
"""
async with self.get_conn() as connection:
try:
v1_api = async_client.CoreV1Api(connection)
await v1_api.delete_namespaced_pod(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)
except async_client.ApiException as e:
# If the pod is already deleted
if str(e.status) != "404":
raise
@generic_api_retry
async def read_logs(
self, name: str, namespace: str, container_name: str | None = None, since_seconds: int | None = None
) -> list[str]:
"""
Read logs inside the pod while starting containers inside.
All the logs will be outputted with its timestamp to track
the logs after the execution of the pod is completed. The
method is used for async output of the logs only in the pod
failed it execution or the task was cancelled by the user.
:param name: Name of the pod.
:param namespace: Name of the pod's namespace.
:param container_name: Name of the container inside the pod.
:param since_seconds: Only return logs newer than a relative duration in seconds.
"""
async with self.get_conn() as connection:
try:
v1_api = async_client.CoreV1Api(connection)
logs = await v1_api.read_namespaced_pod_log(
name=name,
namespace=namespace,
container=container_name,
follow=False,
timestamps=True,
since_seconds=since_seconds,
)
logs = logs.splitlines()
return logs
except HTTPError as e:
raise KubernetesApiError from e
@generic_api_retry
async def get_pod_events(self, name: str, namespace: str) -> CoreV1EventList:
"""Get pod's events."""
async with self.get_conn() as connection:
try:
v1_api = async_client.CoreV1Api(connection)
events: CoreV1EventList = await v1_api.list_namespaced_event(
field_selector=f"involvedObject.name={name}",
namespace=namespace,
)
return events
except HTTPError as e:
if hasattr(e, "status") and e.status == 403:
raise KubernetesApiPermissionError("Permission denied (403) from Kubernetes API.") from e
raise KubernetesApiError from e
@generic_api_retry
async def get_job_status(self, name: str, namespace: str) -> V1Job:
"""
Get job's status object.
:param name: Name of the pod.
:param namespace: Name of the pod's namespace.
"""
async with self.get_conn() as connection:
v1_api = async_client.BatchV1Api(connection)
job: V1Job = await v1_api.read_namespaced_job_status(
name=name,
namespace=namespace,
)
return job
async def wait_until_job_complete(self, name: str, namespace: str, poll_interval: float = 10) -> V1Job:
"""
Block job of specified name and namespace until it is complete or failed.
:param name: Name of Job to fetch.
:param namespace: Namespace of the Job.
:param poll_interval: Interval in seconds between polling the job status
:return: Job object
"""
while True:
self.log.info("Requesting status for the job '%s' ", name)
job: V1Job = await self.get_job_status(name=name, namespace=namespace)
if self.is_job_complete(job=job):
return job
self.log.info("The job '%s' is incomplete. Sleeping for %i sec.", name, poll_interval)
await asyncio.sleep(poll_interval)
async def wait_until_container_complete(
self, name: str, namespace: str, container_name: str, poll_interval: float = 10
) -> None:
"""
Wait for the given container in the given pod to be completed.
:param name: Name of Pod to fetch.
:param namespace: Namespace of the Pod.
:param container_name: name of the container within the pod to monitor
:param poll_interval: Interval in seconds between polling the container status
"""
while True:
pod = await self.get_pod(name=name, namespace=namespace)
if container_is_completed(pod=pod, container_name=container_name):
break
self.log.info("Waiting for container '%s' state to be completed", container_name)
await asyncio.sleep(poll_interval)
async def wait_until_container_started(
self, name: str, namespace: str, container_name: str, poll_interval: float = 10
) -> None:
"""
Wait for the given container in the given pod to be started.
:param name: Name of Pod to fetch.
:param namespace: Namespace of the Pod.
:param container_name: name of the container within the pod to monitor
:param poll_interval: Interval in seconds between polling the container status
"""
while True:
pod = await self.get_pod(name=name, namespace=namespace)
if container_is_running(pod=pod, container_name=container_name):
break
self.log.info("Waiting for container '%s' state to be running", container_name)
await asyncio.sleep(poll_interval)
| AsyncKubernetesHook |
python | PrefectHQ__prefect | src/prefect/logging/handlers.py | {
"start": 1597,
"end": 3297
} | class ____(BatchedQueueService[Dict[str, Any]]):
@property
def max_batch_size(self) -> int:
return max(
PREFECT_LOGGING_TO_API_BATCH_SIZE.value()
- PREFECT_LOGGING_TO_API_MAX_LOG_SIZE.value(),
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE.value(),
)
@property
def min_interval(self) -> float | None:
return PREFECT_LOGGING_TO_API_BATCH_INTERVAL.value()
async def _handle_batch(self, items: list[dict[str, Any]]):
try:
await self._client.create_logs(items)
except Exception as e:
# Roughly replicate the behavior of the stdlib logger error handling
if logging.raiseExceptions and sys.stderr:
sys.stderr.write("--- Error logging to API ---\n")
if PREFECT_LOGGING_INTERNAL_LEVEL.value() == "DEBUG":
traceback.print_exc(file=sys.stderr)
else:
# Only log the exception message in non-DEBUG mode
sys.stderr.write(str(e))
@asynccontextmanager
async def _lifespan(self):
async with get_client() as self._client:
yield
@classmethod
def instance(cls: Type[Self], *args: Any) -> Self:
settings = (
PREFECT_LOGGING_TO_API_BATCH_SIZE.value(),
PREFECT_API_URL.value(),
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE.value(),
)
# Ensure a unique worker is retrieved per relevant logging settings
return super().instance(*settings, *args)
def _get_size(self, item: Dict[str, Any]) -> int:
return item.pop("__payload_size__", None) or len(json.dumps(item).encode())
| APILogWorker |
python | openai__openai-python | src/openai/types/responses/response_input_image.py | {
"start": 223,
"end": 778
} | class ____(BaseModel):
detail: Literal["low", "high", "auto"]
"""The detail level of the image to be sent to the model.
One of `high`, `low`, or `auto`. Defaults to `auto`.
"""
type: Literal["input_image"]
"""The type of the input item. Always `input_image`."""
file_id: Optional[str] = None
"""The ID of the file to be sent to the model."""
image_url: Optional[str] = None
"""The URL of the image to be sent to the model.
A fully qualified URL or base64 encoded image in a data URL.
"""
| ResponseInputImage |
python | skorch-dev__skorch | skorch/callbacks/training.py | {
"start": 23039,
"end": 23307
} | class ____(ParamMapper):
"""Inverse operation of :class:`.Freezer`."""
def __init__(self, *args, **kwargs):
kwargs['at'] = kwargs.get('at', 1)
kwargs['fn'] = kwargs.get('fn', unfreeze_parameter)
super().__init__(*args, **kwargs)
| Unfreezer |
python | kamyu104__LeetCode-Solutions | Python/evaluate-the-bracket-pairs-of-a-string.py | {
"start": 37,
"end": 671
} | class ____(object):
def evaluate(self, s, knowledge):
"""
:type s: str
:type knowledge: List[List[str]]
:rtype: str
"""
lookup = {k: v for k, v in knowledge}
result, curr = [], []
has_pair = False
for c in s:
if c == '(':
has_pair = True
elif c == ')':
has_pair = False
result.append(lookup.get("".join(curr), '?'))
curr = []
elif has_pair:
curr.append(c)
else:
result.append(c)
return "".join(result)
| Solution |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_querysets.py | {
"start": 5859,
"end": 8146
} | class ____(TestVersionQuerySetWithManagerBase):
"""
Queries using Internal Manager should only include Internal Versions.
It will exclude EXTERNAL type Versions from the queries
and only include BRANCH, TAG, UNKNOWN type Versions.
"""
def test_all(self):
query = Version.internal.all()
versions = {
self.version_latest,
self.version,
self.version_private,
self.another_version_latest,
self.another_version,
self.another_version_private,
self.shared_version_latest,
self.shared_version,
self.shared_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public(self):
query = Version.internal.public()
versions = {
self.version_latest,
self.version,
self.another_version,
self.another_version_latest,
self.shared_version,
self.shared_version_latest,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_user(self):
query = Version.internal.public(user=self.user)
versions = self.user_versions | {
self.another_version_latest,
self.another_version,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_project(self):
query = self.project.versions(manager=INTERNAL).public(user=self.user)
versions = {
self.version,
self.version_latest,
self.version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_api(self):
query = Version.internal.api()
versions = {
self.version_latest,
self.version,
self.another_version,
self.another_version_latest,
self.shared_version,
self.shared_version_latest,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
| VersionQuerySetWithInternalManagerTest |
python | pydantic__pydantic | tests/mypy/modules/plugin_success_baseConfig.py | {
"start": 1388,
"end": 1576
} | class ____(NoMutationModel):
a: int = 1
model_config = dict(frozen=False, from_attributes=True)
MutationModel(x=1).x = 2
MutationModel.model_validate(model.__dict__)
| MutationModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/definitions_load_context.py | {
"start": 2277,
"end": 11312
} | class ____:
"""Holds data that's made available to Definitions-loading code when a DefinitionsLoader is
invoked.
User construction of this object is not supported.
"""
_instance: ClassVar[Optional["DefinitionsLoadContext"]] = None
def __init__(
self,
load_type: DefinitionsLoadType,
repository_load_data: Optional["RepositoryLoadData"] = None,
):
self._load_type = load_type
self._repository_load_data = repository_load_data
self._pending_reconstruction_metadata = {}
defs_state_info = repository_load_data.defs_state_info if repository_load_data else None
# keep track of the keys that have been accessed during the load process
self._accessed_defs_state_keys = (
set() if defs_state_info is None else set(defs_state_info.info_mapping.keys())
)
if load_type == DefinitionsLoadType.INITIALIZATION and defs_state_info is None:
# defs_state_info is passed in during INITIALIZATION if explicit state versions
# are provided via CLI arguments, otherwise we use the latest available state info
state_storage = DefsStateStorage.get()
self._defs_state_info = (
state_storage.get_latest_defs_state_info() if state_storage else None
)
else:
self._defs_state_info = defs_state_info
@classmethod
def get(cls) -> "DefinitionsLoadContext":
"""Get the current DefinitionsLoadContext. If it has not been set, the
context is assumed to be in initialization, and the state versions are
set to the latest available versions.
"""
return DefinitionsLoadContext._instance or cls(load_type=DefinitionsLoadType.INITIALIZATION)
@classmethod
def set(cls, instance: "DefinitionsLoadContext") -> None:
"""Get the current DefinitionsLoadContext."""
cls._instance = instance
@classmethod
def is_set(cls) -> bool:
"""bool: Whether the context has been set."""
return cls._instance is not None
@property
def load_type(self) -> DefinitionsLoadType:
"""DefinitionsLoadType: Classifier for scenario in which Definitions are being loaded."""
return self._load_type
def add_to_pending_reconstruction_metadata(self, key: str, metadata: Any) -> None:
self._pending_reconstruction_metadata[key] = metadata
def add_code_server_defs_state_info(self, key: str, metadata: Any) -> None:
"""Marks state that was stored during the code server initialization process."""
self._defs_state_info = DefsStateInfo.add_version(
self._defs_state_info, key, CODE_SERVER_STATE_VERSION
)
self.add_to_pending_reconstruction_metadata(get_code_server_metadata_key(key), metadata)
def get_pending_reconstruction_metadata(self) -> Mapping[str, Any]:
return self._pending_reconstruction_metadata
@property
def cacheable_asset_data(self) -> Mapping[str, Sequence[AssetsDefinitionCacheableData]]:
"""Sequence[AssetDefinitionCacheableData]: A sequence of cacheable asset data created
during code location initialization. Accessing this during initialization will raise an
error.
"""
if self._load_type == DefinitionsLoadType.INITIALIZATION:
raise DagsterInvariantViolationError(
"Attempted to access cacheable asset data during code location initialization."
" Cacheable asset data is only available during reconstruction of a code location."
)
return self._repository_load_data.cacheable_asset_data if self._repository_load_data else {}
@cached_property
def reconstruction_metadata(self) -> Mapping[str, Any]:
"""Mapping[str, Any]: A dictionary containing metadata from the returned Definitions object
at initial code location initialization. Accessing this during initialization will raise an
error.
"""
if self._load_type == DefinitionsLoadType.INITIALIZATION:
raise DagsterInvariantViolationError(
"Attempted to access code location metadata during code location initialization."
" Code location metadata is only available during reconstruction of a code location."
)
# Expose the wrapped metadata values so that users access exactly what they put in.
return (
{
k: v.data if isinstance(v, CodeLocationReconstructionMetadataValue) else v
for k, v in self._repository_load_data.reconstruction_metadata.items()
}
if self._repository_load_data
else {}
)
@property
def accessed_defs_state_info(self) -> Optional[DefsStateInfo]:
return (
self._defs_state_info.for_keys(self._accessed_defs_state_keys)
if self._defs_state_info
else None
)
def _mark_defs_key_accessed(self, key: str) -> None:
self._accessed_defs_state_keys.add(key)
def _get_defs_key_state_info(self, key: str) -> Optional[DefsKeyStateInfo]:
"""Ensures that if we attempt to access a key that doesn't exist, we mark it as None."""
self._mark_defs_key_accessed(key)
current_info = self._defs_state_info or DefsStateInfo.empty()
key_info = current_info.info_mapping.get(key)
if key_info is None:
self._defs_state_info = DefsStateInfo.add_version(current_info, key, None)
return key_info
def _get_defs_state_from_reconstruction_metadata(self, key: str) -> str:
metadata_key = get_code_server_metadata_key(key)
if self.load_type == DefinitionsLoadType.RECONSTRUCTION:
return self.reconstruction_metadata[metadata_key]
else:
return self._pending_reconstruction_metadata[metadata_key]
def add_defs_state_info(
self, key: str, version: str, create_timestamp: Optional[float] = None
) -> None:
self._mark_defs_key_accessed(key)
self._defs_state_info = DefsStateInfo.add_version(
self._defs_state_info, key, version, create_timestamp
)
@contextmanager
def state_path(
self, config: DefsStateConfig, state_storage: Optional[DefsStateStorage], project_root: Path
) -> Iterator[Optional[Path]]:
"""Context manager that creates a temporary path to hold local state for a component.
Args:
config: The state configuration for the component.
state_storage: The state storage instance.
project_root: The root directory of the project.
"""
# if no state has ever been written for this key, we return None to indicate that no state is available
key = config.key
key_info = self._get_defs_key_state_info(key)
if config.management_type == DefsStateManagementType.LOCAL_FILESYSTEM:
# it is possible for local state to exist without the defs_state_storage being aware
# of it if the state was added during docker build
state_path = get_local_state_path(key, project_root)
if not state_path.exists():
yield None
return
self.add_defs_state_info(key, LOCAL_STATE_VERSION, state_path.stat().st_ctime)
yield state_path
elif config.management_type == DefsStateManagementType.VERSIONED_STATE_STORAGE:
if state_storage is None:
raise DagsterInvalidInvocationError(
f"Attempted to access state for key {config.key} with management type {config.management_type} "
"without a StateStorage in context. This is likely the result of an internal framework error."
)
key_info = self._get_defs_key_state_info(key)
# this implies that no state has been stored since the management type was changed
if key_info is None or key_info.management_type != config.management_type:
yield None
return
# grab state for storage
with tempfile.TemporaryDirectory() as temp_dir:
state_path = Path(temp_dir) / "state"
state_storage.download_state_to_path(key, key_info.version, state_path)
yield state_path
elif config.management_type == DefsStateManagementType.LEGACY_CODE_SERVER_SNAPSHOTS:
# state is stored in the reconstruction metadata
with tempfile.TemporaryDirectory() as temp_dir:
state_path = Path(temp_dir) / "state"
state = self._get_defs_state_from_reconstruction_metadata(key)
state_path.write_text(state)
yield state_path
else:
raise DagsterInvariantViolationError(
f"Invalid management type: {config.management_type}"
)
TState = TypeVar("TState", bound=PackableValue)
| DefinitionsLoadContext |
python | django-debug-toolbar__django-debug-toolbar | tests/sync.py | {
"start": 115,
"end": 594
} | class ____(SyncToAsync):
"""
SyncToAsync version that cleans up old database connections when it exits.
"""
def thread_handler(self, loop, *args, **kwargs):
close_old_connections()
try:
return super().thread_handler(loop, *args, **kwargs)
finally:
close_old_connections()
# The class is TitleCased, but we want to encourage use as a callable/decorator
database_sync_to_async = DatabaseSyncToAsync
| DatabaseSyncToAsync |
python | kamyu104__LeetCode-Solutions | Python/prime-subtraction-operation.py | {
"start": 632,
"end": 1055
} | class ____(object):
def primeSubOperation(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
for i in xrange(len(nums)):
j = bisect.bisect_left(PRIMES, nums[i]-nums[i-1] if i-1 >= 0 else nums[i])
if j-1 >= 0:
nums[i] -= PRIMES[j-1]
if i-1 >= 0 and nums[i-1] >=nums[i]:
return False
return True
| Solution |
python | pytest-dev__pytest | testing/test_config.py | {
"start": 71855,
"end": 85582
} | class ____:
@pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
def test_override_ini_names(self, pytester: Pytester, name: str) -> None:
section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]"
pytester.path.joinpath(name).write_text(
textwrap.dedent(
f"""
{section}
custom = 1.0"""
),
encoding="utf-8",
)
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("custom", "")"""
)
pytester.makepyfile(
"""
def test_pass(pytestconfig):
ini_val = pytestconfig.getini("custom")
print('\\ncustom_option:%s\\n' % ini_val)"""
)
result = pytester.runpytest("--override-ini", "custom=2.0", "-s")
assert result.ret == 0
result.stdout.fnmatch_lines(["custom_option:2.0"])
result = pytester.runpytest(
"--override-ini", "custom=2.0", "--override-ini=custom=3.0", "-s"
)
assert result.ret == 0
result.stdout.fnmatch_lines(["custom_option:3.0"])
def test_override_ini_paths(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
parser.addini("paths", "my new ini value", type="paths")"""
)
pytester.makeini(
"""
[pytest]
paths=blah.py"""
)
pytester.makepyfile(
r"""
def test_overridden(pytestconfig):
config_paths = pytestconfig.getini("paths")
print(config_paths)
for cpf in config_paths:
print('\nuser_path:%s' % cpf.name)
"""
)
result = pytester.runpytest(
"--override-ini", "paths=foo/bar1.py foo/bar2.py", "-s"
)
result.stdout.fnmatch_lines(["user_path:bar1.py", "user_path:bar2.py"])
def test_override_multiple_and_default(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_addoption(parser):
addini = parser.addini
addini("custom_option_1", "", default="o1")
addini("custom_option_2", "", default="o2")
addini("custom_option_3", "", default=False, type="bool")
addini("custom_option_4", "", default=True, type="bool")"""
)
pytester.makeini(
"""
[pytest]
custom_option_1=custom_option_1
custom_option_2=custom_option_2
"""
)
pytester.makepyfile(
"""
def test_multiple_options(pytestconfig):
prefix = "custom_option"
for x in range(1, 5):
ini_value=pytestconfig.getini("%s_%d" % (prefix, x))
print('\\nini%d:%s' % (x, ini_value))
"""
)
result = pytester.runpytest(
"--override-ini",
"custom_option_1=fulldir=/tmp/user1",
"-o",
"custom_option_2=url=/tmp/user2?a=b&d=e",
"-o",
"custom_option_3=True",
"-o",
"custom_option_4=no",
"-s",
)
result.stdout.fnmatch_lines(
[
"ini1:fulldir=/tmp/user1",
"ini2:url=/tmp/user2?a=b&d=e",
"ini3:True",
"ini4:False",
]
)
def test_override_ini_usage_error_bad_style(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
xdist_strict=False
"""
)
result = pytester.runpytest("--override-ini", "xdist_strict", "True")
result.stderr.fnmatch_lines(
[
"ERROR: -o/--override-ini expects option=value style (got: 'xdist_strict').",
]
)
@pytest.mark.parametrize("with_ini", [True, False])
def test_override_ini_handled_asap(
self, pytester: Pytester, with_ini: bool
) -> None:
"""-o should be handled as soon as possible and always override what's in config files (#2238)"""
if with_ini:
pytester.makeini(
"""
[pytest]
python_files=test_*.py
"""
)
pytester.makepyfile(
unittest_ini_handle="""
def test():
pass
"""
)
result = pytester.runpytest("--override-ini", "python_files=unittest_*.py")
result.stdout.fnmatch_lines(["*1 passed in*"])
def test_addopts_before_initini(
self, monkeypatch: MonkeyPatch, _config_for_test, _sys_snapshot
) -> None:
cache_dir = ".custom_cache"
monkeypatch.setenv("PYTEST_ADDOPTS", f"-o cache_dir={cache_dir}")
config = _config_for_test
config.parse([], addopts=True)
assert config._inicfg.get("cache_dir") == ConfigValue(
cache_dir, origin="override", mode="ini"
)
def test_addopts_from_env_not_concatenated(
self, monkeypatch: MonkeyPatch, _config_for_test
) -> None:
"""PYTEST_ADDOPTS should not take values from normal args (#4265)."""
monkeypatch.setenv("PYTEST_ADDOPTS", "-o")
config = _config_for_test
with pytest.raises(UsageError) as excinfo:
config.parse(["cache_dir=ignored"], addopts=True)
assert (
"error: argument -o/--override-ini: expected one argument"
in excinfo.value.args[0]
)
assert "via PYTEST_ADDOPTS" in excinfo.value.args[0]
def test_addopts_from_ini_not_concatenated(self, pytester: Pytester) -> None:
"""`addopts` from configuration should not take values from normal args (#4265)."""
pytester.makeini(
"""
[pytest]
addopts=-o
"""
)
result = pytester.runpytest("cache_dir=ignored")
result.stderr.fnmatch_lines(
[
"*: error: argument -o/--override-ini: expected one argument",
" config source: via addopts config",
]
)
assert result.ret == _pytest.config.ExitCode.USAGE_ERROR
def test_override_ini_does_not_contain_paths(
self, _config_for_test, _sys_snapshot
) -> None:
"""Check that -o no longer swallows all options after it (#3103)"""
config = _config_for_test
config.parse(["-o", "cache_dir=/cache", "/some/test/path"])
assert config._inicfg.get("cache_dir") == ConfigValue(
"/cache", origin="override", mode="ini"
)
def test_multiple_override_ini_options(self, pytester: Pytester) -> None:
"""Ensure a file path following a '-o' option does not generate an error (#3103)"""
pytester.makepyfile(
**{
"conftest.py": """
def pytest_addoption(parser):
parser.addini('foo', default=None, help='some option')
parser.addini('bar', default=None, help='some option')
""",
"test_foo.py": """
def test(pytestconfig):
assert pytestconfig.getini('foo') == '1'
assert pytestconfig.getini('bar') == '0'
""",
"test_bar.py": """
def test():
assert False
""",
}
)
result = pytester.runpytest("-o", "foo=1", "-o", "bar=0", "test_foo.py")
assert "ERROR:" not in result.stderr.str()
result.stdout.fnmatch_lines(["collected 1 item", "*= 1 passed in *="])
def test_override_ini_without_config_file(self, pytester: Pytester) -> None:
pytester.makepyfile(**{"src/override_ini_without_config_file.py": ""})
pytester.makepyfile(
**{
"tests/test_override_ini_without_config_file.py": (
"import override_ini_without_config_file\ndef test(): pass"
),
}
)
result = pytester.runpytest("--override-ini", "pythonpath=src")
result.assert_outcomes(passed=1)
def test_override_ini_invalid_option(self, pytester: Pytester) -> None:
result = pytester.runpytest("--override-ini", "doesnotexist=true")
result.stdout.fnmatch_lines(
[
"=*= warnings summary =*=",
"*PytestConfigWarning:*Unknown config option: doesnotexist",
]
)
def test_help_via_addopts(pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
addopts = --unknown-option-should-allow-for-help --help
"""
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"usage: *",
"positional arguments:",
# Displays full/default help.
"to see available markers type: pytest --markers",
]
)
def test_help_and_version_after_argument_error(pytester: Pytester) -> None:
pytester.makeconftest(
"""
def validate(arg):
raise argparse.ArgumentTypeError("argerror")
def pytest_addoption(parser):
group = parser.getgroup('cov')
group.addoption(
"--invalid-option-should-allow-for-help",
type=validate,
)
"""
)
pytester.makeini(
"""
[pytest]
addopts = --invalid-option-should-allow-for-help
"""
)
result = pytester.runpytest("--help")
result.stdout.fnmatch_lines(
[
"usage: *",
"positional arguments:",
"NOTE: displaying only minimal help due to UsageError.",
]
)
result.stderr.fnmatch_lines(
[
"ERROR: usage: *",
"*: error: argument --invalid-option-should-allow-for-help: expected one argument",
]
)
# Does not display full/default help.
assert "to see available markers type: pytest --markers" not in result.stdout.lines
assert result.ret == ExitCode.USAGE_ERROR
result = pytester.runpytest("--version")
result.stdout.fnmatch_lines([f"pytest {pytest.__version__}"])
assert result.ret == ExitCode.OK
def test_help_formatter_uses_py_get_terminal_width(monkeypatch: MonkeyPatch) -> None:
from _pytest.config.argparsing import DropShorterLongHelpFormatter
monkeypatch.setenv("COLUMNS", "90")
formatter = DropShorterLongHelpFormatter("prog")
assert formatter._width == 90
monkeypatch.setattr("_pytest._io.get_terminal_width", lambda: 160)
formatter = DropShorterLongHelpFormatter("prog")
assert formatter._width == 160
formatter = DropShorterLongHelpFormatter("prog", width=42)
assert formatter._width == 42
def test_config_does_not_load_blocked_plugin_from_args(pytester: Pytester) -> None:
"""This tests that pytest's config setup handles "-p no:X"."""
p = pytester.makepyfile("def test(capfd): pass")
result = pytester.runpytest(str(p), "-pno:capture")
result.stdout.fnmatch_lines(["E fixture 'capfd' not found"])
assert result.ret == ExitCode.TESTS_FAILED
result = pytester.runpytest(str(p), "-pno:capture", "-s")
result.stderr.fnmatch_lines(["*: error: unrecognized arguments: -s"])
assert result.ret == ExitCode.USAGE_ERROR
result = pytester.runpytest(str(p), "-p no:capture", "-s")
result.stderr.fnmatch_lines(["*: error: unrecognized arguments: -s"])
assert result.ret == ExitCode.USAGE_ERROR
def test_invocation_args(pytester: Pytester) -> None:
"""Ensure that Config.invocation_* arguments are correctly defined"""
class DummyPlugin:
pass
p = pytester.makepyfile("def test(): pass")
plugin = DummyPlugin()
rec = pytester.inline_run(p, "-v", plugins=[plugin])
calls = rec.getcalls("pytest_runtest_protocol")
assert len(calls) == 1
call = calls[0]
config = call.item.config
assert config.invocation_params.args == (str(p), "-v")
assert config.invocation_params.dir == pytester.path
plugins = config.invocation_params.plugins
assert len(plugins) == 2
assert plugins[0] is plugin
# Installed by pytester.inline_run().
assert type(plugins[1]).__name__ == "PytesterHelperPlugin"
# args cannot be None
with pytest.raises(TypeError):
Config.InvocationParams(args=None, plugins=None, dir=Path()) # type: ignore[arg-type]
@pytest.mark.parametrize(
"plugin",
[
x
for x in _pytest.config.default_plugins
if x not in _pytest.config.essential_plugins
],
)
def test_config_blocked_default_plugins(pytester: Pytester, plugin: str) -> None:
p = pytester.makepyfile("def test(): pass")
result = pytester.runpytest(str(p), f"-pno:{plugin}")
if plugin == "python":
assert result.ret == ExitCode.USAGE_ERROR
result.stderr.fnmatch_lines(
[
"ERROR: not found: */test_config_blocked_default_plugins.py",
"(no match in any of *<Dir *>*",
]
)
return
assert result.ret == ExitCode.OK
if plugin != "terminal":
result.stdout.fnmatch_lines(["* 1 passed in *"])
p = pytester.makepyfile("def test(): assert 0")
result = pytester.runpytest(str(p), f"-pno:{plugin}")
assert result.ret == ExitCode.TESTS_FAILED
if plugin != "terminal":
result.stdout.fnmatch_lines(["* 1 failed in *"])
else:
assert result.stdout.lines == []
| TestOverrideIniArgs |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 12105,
"end": 12281
} | class ____:
"""
ODE problem
"""
stiff = False
cmplx = False
stop_t = 1
z0 = []
lband = None
uband = None
atol = 1e-6
rtol = 1e-5
| ODE |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/ref.py | {
"start": 4093,
"end": 5433
} | class ____(PathRefToDest, ExePathRef):
"""Link a exe path on the file system."""
def __init__(self, src, targets, dest, must=RefMust.NA, when=RefWhen.ANY) -> None:
ExePathRef.__init__(self, src, must, when)
PathRefToDest.__init__(self, src, dest, must, when)
if not self.FS_CASE_SENSITIVE:
targets = list(OrderedDict((i.lower(), None) for i in targets).keys())
self.base = targets[0]
self.aliases = targets[1:]
self.dest = dest
def run(self, creator, symlinks):
bin_dir = self.dest(creator, self.src).parent
dest = bin_dir / self.base
method = self.method(symlinks)
method(self.src, dest)
if not symlinks:
make_exe(dest)
for extra in self.aliases:
link_file = bin_dir / extra
if link_file.exists():
link_file.unlink()
if symlinks:
link_file.symlink_to(self.base)
else:
copy(self.src, link_file)
if not symlinks:
make_exe(link_file)
def __repr__(self) -> str:
return f"{self.__class__.__name__}(src={self.src}, alias={self.aliases})"
__all__ = [
"ExePathRef",
"ExePathRefToDest",
"PathRef",
"PathRefToDest",
"RefMust",
"RefWhen",
]
| ExePathRefToDest |
python | coleifer__peewee | tests/regressions.py | {
"start": 62070,
"end": 62145
} | class ____(TestModel):
p = ForeignKeyField(P)
s = ForeignKeyField(S)
| PS |
python | getsentry__sentry | src/sentry/utils/auth.py | {
"start": 15633,
"end": 15689
} | class ____(Request):
user: User
| AuthenticatedHttpRequest |
python | google__pytype | third_party/cpython/umarshal.py | {
"start": 2289,
"end": 9818
} | class ____:
# A fairly literal translation of the marshal reader.
def __init__(self, data: bytes):
self.data: bytes = data
self.end: int = len(self.data)
self.pos: int = 0
self.refs: list[Any] = []
self.level: int = 0
def r_string(self, n: int) -> bytes:
assert 0 <= n <= self.end - self.pos
buf = self.data[self.pos : self.pos + n]
self.pos += n
return buf
def r_byte(self) -> int:
buf = self.r_string(1)
return buf[0]
def r_short(self) -> int:
buf = self.r_string(2)
x = buf[0]
x |= buf[1] << 8
x |= -(x & (1<<15)) # Sign-extend
return x
def r_long(self) -> int:
buf = self.r_string(4)
x = buf[0]
x |= buf[1] << 8
x |= buf[2] << 16
x |= buf[3] << 24
x |= -(x & (1<<31)) # Sign-extend
return x
def r_long64(self) -> int:
buf = self.r_string(8)
x = buf[0]
x |= buf[1] << 8
x |= buf[2] << 16
x |= buf[3] << 24
x |= buf[1] << 32
x |= buf[1] << 40
x |= buf[1] << 48
x |= buf[1] << 56
x |= -(x & (1<<63)) # Sign-extend
return x
def r_PyLong(self) -> int:
n = self.r_long()
size = abs(n)
x = 0
# Pray this is right
for i in range(size):
x |= self.r_short() << i*15
if n < 0:
x = -x
return x
def r_float_bin(self) -> float:
buf = self.r_string(8)
import struct # Lazy import to avoid breaking UNIX build
return struct.unpack("d", buf)[0]
def r_float_str(self) -> float:
n = self.r_byte()
buf = self.r_string(n)
return ast.literal_eval(buf.decode("ascii"))
def r_ref_reserve(self, flag: int) -> int:
if flag:
idx = len(self.refs)
self.refs.append(None)
return idx
else:
return 0
def r_ref_insert(self, obj: Any, idx: int, flag: int) -> Any:
if flag:
self.refs[idx] = obj
return obj
def r_ref(self, obj: Any, flag: int) -> Any:
assert flag & FLAG_REF
self.refs.append(obj)
return obj
def r_object(self) -> Any:
old_level = self.level
try:
return self._r_object()
finally:
self.level = old_level
def _r_object(self) -> Any:
code = self.r_byte()
flag = code & FLAG_REF
type = code & ~FLAG_REF
# print(" "*self.level + f"{code} {flag} {type} {chr(type)!r}")
self.level += 1
def R_REF(obj: Any) -> Any:
if flag:
obj = self.r_ref(obj, flag)
return obj
if type == Type.NULL:
return NULL
elif type == Type.NONE:
return None
elif type == Type.ELLIPSIS:
return Ellipsis
elif type == Type.FALSE:
return False
elif type == Type.TRUE:
return True
elif type == Type.INT:
return R_REF(self.r_long())
elif type == Type.INT64:
return R_REF(self.r_long64())
elif type == Type.LONG:
return R_REF(self.r_PyLong())
elif type == Type.FLOAT:
return R_REF(self.r_float_str())
elif type == Type.BINARY_FLOAT:
return R_REF(self.r_float_bin())
elif type == Type.COMPLEX:
return R_REF(complex(self.r_float_str(),
self.r_float_str()))
elif type == Type.BINARY_COMPLEX:
return R_REF(complex(self.r_float_bin(),
self.r_float_bin()))
elif type == Type.STRING:
n = self.r_long()
return R_REF(self.r_string(n))
elif type == Type.ASCII_INTERNED or type == Type.ASCII:
n = self.r_long()
return R_REF(self.r_string(n).decode("ascii"))
elif type == Type.SHORT_ASCII_INTERNED or type == Type.SHORT_ASCII:
n = self.r_byte()
return R_REF(self.r_string(n).decode("ascii"))
elif type == Type.INTERNED or type == Type.UNICODE:
n = self.r_long()
return R_REF(self.r_string(n).decode("utf8", "surrogatepass"))
elif type == Type.SMALL_TUPLE:
n = self.r_byte()
idx = self.r_ref_reserve(flag)
retval: Any = tuple(self.r_object() for _ in range(n))
self.r_ref_insert(retval, idx, flag)
return retval
elif type == Type.TUPLE:
n = self.r_long()
idx = self.r_ref_reserve(flag)
retval = tuple(self.r_object() for _ in range(n))
self.r_ref_insert(retval, idx, flag)
return retval
elif type == Type.LIST:
n = self.r_long()
retval = R_REF([])
for _ in range(n):
retval.append(self.r_object())
return retval
elif type == Type.DICT:
retval = R_REF({})
while True:
key = self.r_object()
if key == NULL:
break
val = self.r_object()
retval[key] = val
return retval
elif type == Type.SET:
n = self.r_long()
retval = R_REF(set())
for _ in range(n):
v = self.r_object()
retval.add(v)
return retval
elif type == Type.FROZENSET:
n = self.r_long()
s: set[Any] = set()
idx = self.r_ref_reserve(flag)
for _ in range(n):
v = self.r_object()
s.add(v)
retval = frozenset(s)
self.r_ref_insert(retval, idx, flag)
return retval
elif type == Type.CODE:
retval = R_REF(Code())
retval.co_argcount = self.r_long()
retval.co_posonlyargcount = self.r_long()
retval.co_kwonlyargcount = self.r_long()
retval.co_stacksize = self.r_long()
retval.co_flags = self.r_long()
retval.co_code = self.r_object()
retval.co_consts = self.r_object()
retval.co_names = self.r_object()
retval.co_localsplusnames = self.r_object()
retval.co_localspluskinds = self.r_object()
retval.co_filename = self.r_object()
retval.co_name = self.r_object()
retval.co_qualname = self.r_object()
retval.co_firstlineno = self.r_long()
retval.co_linetable = self.r_object()
retval.co_exceptiontable = self.r_object()
return retval
elif type == Type.REF:
n = self.r_long()
retval = self.refs[n]
assert retval is not None
return retval
else:
breakpoint()
raise AssertionError(f"Unknown type {type} {chr(type)!r}")
def loads(data: bytes) -> Any:
assert isinstance(data, bytes)
r = Reader(data)
return r.r_object()
def main():
# Test
import marshal, pprint
sample = {'foo': {(42, "bar", 3.14)}}
data = marshal.dumps(sample)
retval = loads(data)
assert retval == sample, retval
sample = main.__code__
data = marshal.dumps(sample)
retval = loads(data)
assert isinstance(retval, Code), retval
pprint.pprint(retval.__dict__)
if __name__ == "__main__":
main()
| Reader |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 4011,
"end": 8185
} | class ____(nn.Module):
def __init__(self, config, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.use_bias)
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.use_bias)
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.use_bias)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.is_decoder = config.is_decoder
self.layer_idx = layer_idx
def forward(
self,
hidden_states,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
output_attentions=False,
cache_position=None,
):
batch_size, seq_length, _ = hidden_states.shape
query_layer = (
self.query(hidden_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
is_cross_attention = encoder_hidden_states is not None
current_states = encoder_hidden_states if is_cross_attention else hidden_states
attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
if is_cross_attention and past_key_values is not None and past_key_values.get_seq_length(self.layer_idx) > 0:
# reuse k,v, cross_attentions
key_layer = past_key_values.layers[self.layer_idx].keys
value_layer = past_key_values.layers[self.layer_idx].values
else:
key_layer = (
self.key(current_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
value_layer = (
self.value(current_states)
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
.transpose(1, 2)
)
if past_key_values is not None:
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
key_layer, value_layer = past_key_values.update(
key_layer,
value_layer,
self.layer_idx,
)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BigBirdPegasusModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer, attention_probs
# Copied from transformers.models.big_bird.modeling_big_bird.BigBirdBlockSparseAttention with BigBird->BigBirdPegasus
| BigBirdPegasusSelfAttention |
python | gevent__gevent | src/greentest/3.13/test_weakref.py | {
"start": 1515,
"end": 2142
} | class ____(unittest.TestCase):
def setUp(self):
self.cbcalled = 0
def callback(self, ref):
self.cbcalled += 1
@contextlib.contextmanager
def collect_in_thread(period=0.005):
"""
Ensure GC collections happen in a different thread, at a high frequency.
"""
please_stop = False
def collect():
while not please_stop:
time.sleep(period)
gc.collect()
with support.disable_gc():
t = threading.Thread(target=collect)
t.start()
try:
yield
finally:
please_stop = True
t.join()
| TestBase |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/orc_asset.py | {
"start": 1313,
"end": 1393
} | class ____(FileDataAsset, ORCAssetBase):
type: Literal["orc"] = "orc"
| ORCAsset |
python | pytorch__pytorch | torch/_inductor/autoheuristic/learnedheuristic_interface.py | {
"start": 790,
"end": 1680
} | class ____(LearnedHeuristic):
def get_feedback(self, context: AHContext, choice: Choice) -> float:
return 1.0
def get_decision(
self, context: AHContext, choices: list[Choice]
) -> Optional[Choice]:
choice2feedback = {}
for choice in choices:
predicted_feedback = self.get_feedback(context, choice)
choice2feedback[choice] = predicted_feedback
sorted_choices_feedback = sorted(
choice2feedback.items(), key=operator.itemgetter(1)
)
highest_feedback = sorted_choices_feedback[-1][1]
second_highest_feedback = sorted_choices_feedback[-2][1]
if highest_feedback / second_highest_feedback > self.get_confidence_threshold():
return sorted_choices_feedback[-1][0]
# We are not sure which choice is the best one
return None
| LearnedHeuristicRegression |
python | tensorflow__tensorflow | tensorflow/python/framework/ops.py | {
"start": 67260,
"end": 71284
} | class ____(object):
"""A decorator for registering the statistics function for an op type.
This decorator can be defined for an op type so that it gives a
report on the resources used by an instance of an operator, in the
form of an OpStats object.
Well-known types of statistics include these so far:
- flops: When running a graph, the bulk of the computation happens doing
numerical calculations like matrix multiplications. This type allows a node
to return how many floating-point operations it takes to complete. The
total number of FLOPs for a graph is a good guide to its expected latency.
You can add your own statistics just by picking a new type string, registering
functions for the ops you care about, and then calling get_stats_for_node_def.
If a statistic for an op is registered multiple times, a KeyError will be
raised.
Since the statistics is counted on a per-op basis. It is not suitable for
model parameters (capacity), which is expected to be counted only once, even
if it is shared by multiple ops. (e.g. RNN)
For example, you can define a new metric called doohickey for a Foo operation
by placing this in your code:
```python
@ops.RegisterStatistics("Foo", "doohickey")
def _calc_foo_bojangles(unused_graph, unused_node_def):
return ops.OpStats("doohickey", 20)
```
Then in client code you can retrieve the value by making this call:
```python
doohickey = ops.get_stats_for_node_def(graph, node_def, "doohickey")
```
If the NodeDef is for an op with a registered doohickey function, you'll get
back the calculated amount in doohickey.value, or None if it's not defined.
"""
__slots__ = ["_op_type", "_statistic_type"]
def __init__(self, op_type, statistic_type) -> None:
"""Saves the `op_type` as the `Operation` type."""
if not isinstance(op_type, str):
raise TypeError("op_type must be a string.")
if "," in op_type:
raise TypeError("op_type must not contain a comma.")
self._op_type = op_type
if not isinstance(statistic_type, str):
raise TypeError("statistic_type must be a string.")
if "," in statistic_type:
raise TypeError("statistic_type must not contain a comma.")
self._statistic_type = statistic_type
def __call__(self, f: _T) -> _T:
"""Registers "f" as the statistics function for "op_type"."""
_stats_registry.register(f, self._op_type + "," + self._statistic_type)
return f
def get_stats_for_node_def(graph, node, statistic_type) -> Any:
"""Looks up the node's statistics function in the registry and calls it.
This function takes a Graph object and a NodeDef from a GraphDef, and if
there's an associated statistics method, calls it and returns a result. If no
function has been registered for the particular node type, it returns an empty
statistics object.
Args:
graph: A Graph object that's been set up with the node's graph.
node: A NodeDef describing the operator.
statistic_type: A string identifying the statistic we're interested in.
Returns:
An OpStats object containing information about resource usage.
"""
try:
stats_func = _stats_registry.lookup(node.op + "," + statistic_type)
result = stats_func(graph, node)
except LookupError:
result = OpStats(statistic_type)
return result
def name_from_scope_name(name) -> str:
"""Returns the name of an op given the name of its scope.
Args:
name: the name of the scope.
Returns:
the name of the op (equal to scope name minus any trailing slash).
"""
return name[:-1] if (name and name[-1] == "/") else name
_MUTATION_LOCK_GROUP: int = 0
_SESSION_RUN_LOCK_GROUP: int = 1
@tf_contextlib.contextmanager
def resource_creator_scope(resource_type, resource_creator) -> Iterator[None]:
with get_default_graph()._resource_creator_scope(resource_type, # pylint: disable=protected-access
resource_creator):
yield
@tf_export("Graph")
| RegisterStatistics |
python | pallets__jinja | src/jinja2/compiler.py | {
"start": 4440,
"end": 4664
} | class ____:
def __init__(self, node: nodes.Macro | nodes.CallBlock) -> None:
self.node = node
self.accesses_caller = False
self.accesses_kwargs = False
self.accesses_varargs = False
| MacroRef |
python | ethereum__web3.py | web3/providers/base.py | {
"start": 872,
"end": 3655
} | class ____:
# Set generic logger for the provider. Override in subclasses for more specificity.
logger: logging.Logger = logging.getLogger("web3.providers.base.BaseProvider")
# a tuple of (middleware, request_func)
_request_func_cache: tuple[tuple[Middleware, ...], Callable[..., RPCResponse]] = (
None,
None,
)
is_async = False
has_persistent_connection = False
global_ccip_read_enabled: bool = True
ccip_read_max_redirects: int = 4
def __init__(
self,
cache_allowed_requests: bool = False,
cacheable_requests: set[RPCEndpoint] = None,
request_cache_validation_threshold: None
| (RequestCacheValidationThreshold | int | Empty) = empty,
) -> None:
self._request_cache = SimpleCache(1000)
self._request_cache_lock: threading.Lock = threading.Lock()
self.cache_allowed_requests = cache_allowed_requests
self.cacheable_requests = cacheable_requests or CACHEABLE_REQUESTS
self.request_cache_validation_threshold = request_cache_validation_threshold
self._batching_context: contextvars.ContextVar[
Optional["RequestBatcher[Any]"]
] = contextvars.ContextVar("batching_context", default=None)
self._batch_request_func_cache: tuple[
tuple[Middleware, ...], Callable[..., list[RPCResponse] | RPCResponse]
] = (None, None)
@property
def _is_batching(self) -> bool:
"""
Check if the provider is currently batching requests.
"""
return self._batching_context.get() is not None
def request_func(
self, w3: "Web3", middleware_onion: MiddlewareOnion
) -> Callable[..., RPCResponse]:
"""
@param w3 is the web3 instance
@param middleware_onion is an iterable of middleware,
ordered by first to execute
@returns a function that calls all the middleware and
eventually self.make_request()
"""
middleware: tuple[Middleware, ...] = middleware_onion.as_tuple_of_middleware()
cache_key = self._request_func_cache[0]
if cache_key != middleware:
self._request_func_cache = (
middleware,
combine_middleware(
middleware=middleware,
w3=w3,
provider_request_fn=self.make_request,
),
)
return self._request_func_cache[-1]
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
raise NotImplementedError("Providers must implement this method")
def is_connected(self, show_traceback: bool = False) -> bool:
raise NotImplementedError("Providers must implement this method")
| BaseProvider |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 167290,
"end": 167604
} | class ____:
def test_lmbda(self):
lam = special.lmbda(1,.1)
lamr = (
array([special.jn(0,.1), 2*special.jn(1,.1)/.1]),
array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])
)
assert_allclose(lam, lamr, atol=1.5e-8, rtol=0)
| TestLambda |
python | pypa__setuptools | setuptools/_distutils/command/install_headers.py | {
"start": 241,
"end": 1272
} | class ____(Command):
description = "install C/C++ header files"
user_options: ClassVar[list[tuple[str, str, str]]] = [
('install-dir=', 'd', "directory to install header files to"),
('force', 'f', "force installation (overwrite existing files)"),
]
boolean_options: ClassVar[list[str]] = ['force']
def initialize_options(self):
self.install_dir = None
self.force = False
self.outfiles = []
def finalize_options(self):
self.set_undefined_options(
'install', ('install_headers', 'install_dir'), ('force', 'force')
)
def run(self):
headers = self.distribution.headers
if not headers:
return
self.mkpath(self.install_dir)
for header in headers:
(out, _) = self.copy_file(header, self.install_dir)
self.outfiles.append(out)
def get_inputs(self):
return self.distribution.headers or []
def get_outputs(self):
return self.outfiles
| install_headers |
python | getsentry__sentry | tests/sentry/auth/providers/fly/test_provider.py | {
"start": 3026,
"end": 3278
} | class ____(FlyOAuth2ProviderTest):
def setUp(self) -> None:
self.auth_provider = AuthProvider.objects.create(
provider=ChannelName.FLY_NON_PARTNER.value, organization_id=self.organization.id
)
| NonPartnerFlyOAuth2ProviderTest |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 11688,
"end": 11837
} | class ____(LTTextContainer):
def __init__(self, objs):
LTTextContainer.__init__(self)
self.extend(objs)
return
| LTTextGroup |
python | plotly__plotly.py | plotly/graph_objs/scatter/selected/_marker.py | {
"start": 233,
"end": 3584
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.selected"
_path_str = "scatter.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
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 opacity(self):
"""
Sets the marker opacity of selected points.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
@property
def size(self):
"""
Sets the marker size of selected points.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the marker color of selected points.
opacity
Sets the marker opacity of selected points.
size
Sets the marker size of selected points.
"""
def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter.selected.Marker`
color
Sets the marker color of selected points.
opacity
Sets the marker opacity of selected points.
size
Sets the marker size of selected points.
Returns
-------
Marker
"""
super().__init__("marker")
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.scatter.selected.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter.selected.Marker`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("opacity", arg, opacity)
self._set_property("size", arg, size)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Marker |
python | django__django | tests/admin_views/models.py | {
"start": 11292,
"end": 11474
} | class ____(models.Model):
index = models.IntegerField(primary_key=True)
owner = models.ForeignKey(Collector, models.CASCADE)
name = models.CharField(max_length=100)
| Whatsit |
python | pytorch__pytorch | torch/utils/_device.py | {
"start": 1514,
"end": 3996
} | class ____(TorchFunctionMode):
def __init__(self, device) -> None:
# pyrefly: ignore [read-only]
self.device = torch.device(device)
def __enter__(self):
global CURRENT_DEVICE
self.old_device = CURRENT_DEVICE
CURRENT_DEVICE = self.device
# We need to put the device at the bottom of the stack
# If we set default device within a function mode context
# exiting that context mode will pop the device function mode off
# of the stack incorrectly
cur_stack = [_pop_mode() for _ in range(_len_torch_function_stack())]
_push_mode(self)
for mode in reversed(cur_stack):
_push_mode(mode)
def __exit__(self, exc_type, exc_val, exc_tb):
global CURRENT_DEVICE
CURRENT_DEVICE = self.old_device
cur_stack = []
# Invariant: there should only be one DeviceContext on the stack at any time
# (At the bottom), pop all modes until we hit the bottom, assert it's a DeviceContext
# or else someone else has popped it!
for _ in range(_len_torch_function_stack() - 1):
mode = _pop_mode()
if isinstance(mode, DeviceContext):
raise AssertionError(
"Found nested DeviceContext on the mode stack where none expected"
)
cur_stack.append(mode)
if _len_torch_function_stack() > 0:
mode = _pop_mode()
if not isinstance(mode, DeviceContext):
raise AssertionError(
"Expected a DeviceContext at the bottom of the mode stack"
)
for mode in reversed(cur_stack):
_push_mode(mode)
def __torch_function__(self, func, types, args=(), kwargs=None):
kwargs = kwargs or {}
if func in _device_constructors() and kwargs.get("device") is None:
kwargs["device"] = self.device
return func(*args, **kwargs)
# NB: This is directly called from C++ in torch/csrc/Device.cpp
def device_decorator(device, func):
return context_decorator(lambda: device, func)
def set_device(device):
"""
Set the default device inside of the wrapped function by decorating it with this function.
If you would like to use this as a context manager, use device as a
context manager directly, e.g., ``with torch.device(device)``.
"""
return lambda func: device_decorator(torch.device(device), func)
| DeviceContext |
python | streamlit__streamlit | lib/streamlit/elements/pdf.py | {
"start": 1533,
"end": 7163
} | class ____:
@gather_metrics("pdf")
def pdf(
self,
data: PdfData,
*,
height: HeightWithoutContent = 500,
key: str | None = None,
) -> DeltaGenerator:
"""Display a PDF viewer.
.. Important::
You must install |streamlit-pdf|_ to use this command. You can
install it as an extra with Streamlit:
.. code-block:: shell
pip install streamlit[pdf]
.. |streamlit-pdf| replace:: ``streamlit-pdf``
.. _streamlit-pdf: https://github.com/streamlit/streamlit-pdf
Parameters
----------
data : str, Path, BytesIO, or bytes
The PDF file to show. This can be one of the following:
- A URL (string) for a hosted PDF file.
- A path to a local PDF file. If you use a relative path, it must
be relative to the current working directory.
- A file-like object. For example, this can be an ``UploadedFile``
from ``st.file_uploader``, or this can be a local file opened
with ``open()``.
- Raw bytes data.
height : int or "stretch"
The height of the PDF viewer. This can be one of the following:
- An integer specifying the height in pixels: The viewer has a
fixed height. If the content is larger than the specified
height, scrolling is enabled. This is ``500`` by default.
- ``"stretch"``: The height of the viewer matches the height of
its content or the height of the parent container, whichever is
larger. If the viewer is not in a parent container, the height
of the viewer matches the height of its content.
Example
-------
>>> st.pdf("https://example.com/sample.pdf")
>>> st.pdf("https://example.com/sample.pdf", height=600)
"""
# Validate data parameter early
if data is None:
raise StreamlitAPIException(
"The PDF data cannot be None. Please provide a valid PDF file path, URL, "
"bytes data, or file-like object."
)
# Check if custom PDF component is available first
pdf_component = _get_pdf_component()
if pdf_component is None:
return self._show_pdf_warning()
return self._call_pdf_component(pdf_component, data, height, key)
def _call_pdf_component(
self,
pdf_component: Any,
data: PdfData,
height: HeightWithoutContent,
key: str | None,
) -> DeltaGenerator:
"""Call the custom PDF component with the provided data."""
# Validate height parameter after confirming component is available
validate_height(height, allow_content=False)
# Convert data to the format expected by pdf_viewer component
file_param: str | bytes
if isinstance(data, (str, Path)):
data_str = str(data).strip() # Strip whitespace from URLs
if url_util.is_url(data_str, allowed_schemas=("http", "https")):
# It's a URL - pass directly
file_param = data_str
else:
# It's a local file path - read the content as bytes for security
try:
with open(data_str, "rb") as file:
file_param = file.read()
except (FileNotFoundError, PermissionError) as e:
raise StreamlitAPIException(
f"Unable to read file '{data_str}': {e}"
)
elif isinstance(data, bytes):
# Pass bytes directly - the component will handle uploading to media storage
file_param = data
elif hasattr(data, "read") and hasattr(data, "getvalue"):
# Handle BytesIO and similar
file_param = data.getvalue()
elif hasattr(data, "read"):
# Handle other file-like objects
file_param = data.read()
else:
# Provide a more helpful error message
raise StreamlitAPIException(
f"Unsupported data type for PDF: {type(data).__name__}. "
f"Please provide a file path (str or Path), URL (str), bytes data, "
f"or file-like object (such as BytesIO or UploadedFile)."
)
# Convert to component-compatible format
if height == "stretch":
# For stretch, we need to pass a special value the component understands
# This maintains compatibility with the component while using standard layout
component_height = "stretch"
else:
component_height = str(height)
result = pdf_component(
file=file_param,
height=component_height,
key=key,
)
return cast("DeltaGenerator", result)
def _show_pdf_warning(self) -> DeltaGenerator:
"""Raise an exception that the PDF component is not available."""
raise StreamlitAPIException(
"The PDF viewer requires the `streamlit-pdf` component to be installed.\n\n"
"Please run `pip install streamlit[pdf]` to install it.\n\n"
"For more information, see the Streamlit PDF documentation at "
"https://docs.streamlit.io/develop/api-reference/media/st.pdf."
# TODO: Update this URL when docs are updated
)
@property
def dg(self) -> DeltaGenerator:
"""Get our DeltaGenerator."""
return cast("DeltaGenerator", self)
| PdfMixin |
python | kamyu104__LeetCode-Solutions | Python/pancake-sorting.py | {
"start": 1461,
"end": 3389
} | class ____(object):
def pancakeSort(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
def smallerMergeSort(idxs, start, end, counts):
if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.
return 0
mid = start + (end - start) // 2
smallerMergeSort(idxs, start, mid, counts)
smallerMergeSort(idxs, mid + 1, end, counts)
r = start
tmp = []
for i in xrange(mid+1, end + 1):
# Merge the two sorted arrays into tmp.
while r <= mid and idxs[r][0] < idxs[i][0]:
tmp.append(idxs[r])
r += 1
if r <= mid:
tmp.append(idxs[i])
counts[idxs[i][1]] += r - start
while r <= mid:
tmp.append(idxs[r])
r += 1
# Copy tmp back to idxs
idxs[start:start+len(tmp)] = tmp
idxs = []
smaller_counts = [0]*len(arr)
for i, x in enumerate(arr):
idxs.append((x, i))
smallerMergeSort(idxs, 0, len(idxs)-1, smaller_counts)
result = []
for i, n in enumerate(smaller_counts):
if n == i: # already sorted
continue
if n == 0: # (0..i-1)i
if i > 1:
result.append(i) # (i-1..0)i
result.append(i+1) # i(0..i-1)
else: # (0..n-1)n(n+1..i-1)i
if n > 1:
result.append(n) # (n-1..0)n(n+1..i-1)i
result.append(i) # (i-1..n+1)n(0..n-1)i
result.append(i+1) # i(n-1..0)n(n+1..i-1)
result.append(n+1) # (0..n-1)in(n+1..i-1)
return result
# Time: O(n^2)
# Space: O(1)
| Solution2 |
python | openai__openai-python | src/openai/lib/streaming/_assistants.py | {
"start": 16635,
"end": 17702
} | class ____(Generic[AssistantEventHandlerT]):
"""Wrapper over AssistantStreamEventHandler that is returned by `.stream()`
so that a context manager can be used.
```py
with client.threads.create_and_run_stream(...) as stream:
for event in stream:
...
```
"""
def __init__(
self,
api_request: Callable[[], Stream[AssistantStreamEvent]],
*,
event_handler: AssistantEventHandlerT,
) -> None:
self.__stream: Stream[AssistantStreamEvent] | None = None
self.__event_handler = event_handler
self.__api_request = api_request
def __enter__(self) -> AssistantEventHandlerT:
self.__stream = self.__api_request()
self.__event_handler._init(self.__stream)
return self.__event_handler
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self.__stream is not None:
self.__stream.close()
| AssistantStreamManager |
python | pytorch__pytorch | benchmarks/instruction_counts/execution/runner.py | {
"start": 707,
"end": 3122
} | class ____:
"""Allocator style helper class to assign individual tasks to a core range.
Pinning tasks to separate cores (or core ranges if `num_threads` > 1)
serves two purposes. First, it prevents the machine from being overloaded,
which can result in OOMs or Callgrind crashes. Second, it helps reduce
noise in the wall times, which are collected as a secondary metric. For
multi-threaded workloads, adjacency is important. Often pairs of cores
share silicon (e.g. cache), while far away cores may lie on separate NUMA
nodes. For this reason, CorePool will only allocate contiguous core ranges.
This falls short of full architecture awareness, and instead tries to find
a balance between rigor and engineering complexity.
"""
def __init__(self, min_core_id: int, max_core_id: int) -> None:
assert min_core_id >= 0
assert max_core_id >= min_core_id
assert max_core_id < CPU_COUNT
self._min_core_id: int = min_core_id
self._max_core_id: int = max_core_id
self._num_cores = max_core_id - min_core_id + 1
print(f"Core pool created: cores {self._min_core_id}-{self._max_core_id}")
self._available: list[bool] = [
True for _ in range(min_core_id, min_core_id + self._num_cores)
]
self._reservations: dict[str, tuple[int, ...]] = {}
self._lock = threading.Lock()
def reserve(self, n: int) -> Optional[str]:
"""Simple first-fit policy.
If successful, return a string for `taskset`. Otherwise, return None.
"""
with self._lock:
for lower_index in range(self._num_cores - n + 1):
indices = tuple(range(lower_index, lower_index + n))
if all(self._available[i] for i in indices):
for i in indices:
self._available[i] = False
lower_core = indices[0] + self._min_core_id
upper_core = indices[-1] + self._min_core_id
key = f"{lower_core}-{upper_core}" if n > 1 else f"{lower_core}"
self._reservations[key] = indices
return key
return None
def release(self, key: str) -> None:
with self._lock:
for i in self._reservations[key]:
self._available[i] = True
self._reservations.pop(key)
| CorePool |
python | pytorch__pytorch | torch/_guards.py | {
"start": 16614,
"end": 17456
} | class ____:
"""
The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
"""
dynamo_guards: set[Guard] = set()
def __init__(self, dynamo_guards: set[Guard]) -> None:
self.dynamo_guards = dynamo_guards
def diff(self, other: GuardsCheckpointState) -> Optional[set[Guard]]:
"""
Produces a delta against another GuardsCheckpointState.
Returns None if no delta is found, otherwise, return a set() of mismatched
Guard type objects.
"""
r = self.dynamo_guards.difference(other.dynamo_guards)
if len(r) == 0:
return None
return r
def __eq__(self, other: object) -> bool:
if not isinstance(other, GuardsCheckpointState):
return False
return self.diff(other) is None
| GuardsCheckpointState |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 36772,
"end": 40242
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a long-running DlpJob.
This method indicates that the client is no longer interested
in the DlpJob result. The job will be cancelled if possible.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPDeleteDLPJobOperator`
:param dlp_job_id: The ID of the DLP job resource to be deleted.
:param project_id: (Optional) Google Cloud project ID where the
DLP Instance exists. If set to None or missing, the default
project_id from the Google Cloud connection is used.
:param retry: (Optional) A retry object used to retry requests.
If None is specified, requests will not be retried.
:param timeout: (Optional) The amount of time, in seconds, to wait for the request
to complete. Note that if retry is specified, the timeout applies to each
individual attempt.
:param metadata: (Optional) Additional metadata that is provided to the method.
:param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"dlp_job_id",
"project_id",
"gcp_conn_id",
"impersonation_chain",
)
operator_extra_links = (CloudDLPJobsListLink(),)
def __init__(
self,
*,
dlp_job_id: str,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.dlp_job_id = dlp_job_id
self.project_id = project_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> None:
hook = CloudDLPHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
try:
hook.delete_dlp_job(
dlp_job_id=self.dlp_job_id,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
project_id = self.project_id or hook.project_id
if project_id:
CloudDLPJobsListLink.persist(
context=context,
project_id=project_id,
)
except NotFound:
self.log.error("Job %s id not found.", self.dlp_job_id)
| CloudDLPDeleteDLPJobOperator |
python | openai__openai-python | src/openai/types/audio/transcription_diarized_segment.py | {
"start": 205,
"end": 859
} | class ____(BaseModel):
id: str
"""Unique identifier for the segment."""
end: float
"""End timestamp of the segment in seconds."""
speaker: str
"""Speaker label for this segment.
When known speakers are provided, the label matches `known_speaker_names[]`.
Otherwise speakers are labeled sequentially using capital letters (`A`, `B`,
...).
"""
start: float
"""Start timestamp of the segment in seconds."""
text: str
"""Transcript text for this segment."""
type: Literal["transcript.text.segment"]
"""The type of the segment. Always `transcript.text.segment`."""
| TranscriptionDiarizedSegment |
python | huggingface__transformers | src/transformers/models/deberta_v2/modeling_deberta_v2.py | {
"start": 41224,
"end": 46165
} | class ____(DebertaV2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
num_labels = getattr(config, "num_labels", 2)
self.num_labels = num_labels
self.deberta = DebertaV2Model(config)
self.pooler = ContextPooler(config)
output_dim = self.pooler.output_dim
self.classifier = nn.Linear(output_dim, num_labels)
drop_out = getattr(config, "cls_dropout", None)
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
self.dropout = nn.Dropout(drop_out)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.deberta.get_input_embeddings()
def set_input_embeddings(self, new_embeddings):
self.deberta.set_input_embeddings(new_embeddings)
@auto_docstring
# Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification.forward with Deberta->DebertaV2
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta(
input_ids,
token_type_ids=token_type_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
encoder_layer = outputs[0]
pooled_output = self.pooler(encoder_layer)
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
# regression task
loss_fn = nn.MSELoss()
logits = logits.view(-1).to(labels.dtype)
loss = loss_fn(logits, labels.view(-1))
elif labels.dim() == 1 or labels.size(-1) == 1:
label_index = (labels >= 0).nonzero()
labels = labels.long()
if label_index.size(0) > 0:
labeled_logits = torch.gather(
logits, 0, label_index.expand(label_index.size(0), logits.size(1))
)
labels = torch.gather(labels, 0, label_index.view(-1))
loss_fct = CrossEntropyLoss()
loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1))
else:
loss = torch.tensor(0).to(logits)
else:
log_softmax = nn.LogSoftmax(-1)
loss = -((log_softmax(logits) * labels).sum(-1)).mean()
elif self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
)
@auto_docstring
# Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2
| DebertaV2ForSequenceClassification |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 94288,
"end": 97696
} | class ____:
@staticmethod
@functools.cache
def patch() -> None:
# A better way to disable the following would be decorate the source
# functions with @torch._disable_dynamo. However, this causes issues
# with torch.deploy internally.
from .decorators import disable
torch.jit.trace = disable(
torch.jit.trace, reason="tracing into TorchScript not fully supported"
)
torch.jit.trace_module = disable(
torch.jit.trace_module,
reason="tracing into TorchScript not fully supported",
)
torch.jit._get_trace_graph = disable(
torch.jit._get_trace_graph,
reason="tracing into TorchScript not fully supported",
)
torch.fx._symbolic_trace.Tracer.trace = disable(
torch.fx._symbolic_trace.Tracer.trace,
reason="tracing into FX not fully supported",
)
torch.distributions.Distribution.set_default_validate_args(False)
from torch.optim import (
adadelta,
adagrad,
adam,
adamax,
adamw,
asgd,
lbfgs,
nadam,
radam,
rmsprop,
rprop,
sgd,
sparse_adam,
)
optimizer_modules = {
adadelta,
adagrad,
adam,
adamax,
adamw,
asgd,
lbfgs,
nadam,
radam,
rmsprop,
rprop,
sgd,
sparse_adam,
}
for opt_mod in optimizer_modules:
opt_name = opt_mod.__name__.split(".")[-1]
fused_fn_name = f"_fused_{opt_name}"
if hasattr(opt_mod, fused_fn_name):
setattr(
opt_mod,
fused_fn_name,
disable(
getattr(opt_mod, fused_fn_name),
reason="don't trace into fused optimizer",
),
)
optimizer_classes = [
opt
for opt in torch.optim.__dict__.values()
if inspect.isclass(opt) and issubclass(opt, torch.optim.Optimizer)
]
# Note: we don't support sparsity or tracing through backwards
excluded_optimizer_classes = {
torch.optim.SparseAdam,
torch.optim.LBFGS,
}
for opt in optimizer_classes:
if opt in excluded_optimizer_classes:
opt.step = disable(
opt.step, reason=f"optimizer {opt} step not supported"
)
if hasattr(opt, "_init_group"):
opt._init_group = disable(
opt._init_group, reason=f"optimizer {opt} _init_group not supported"
)
@staticmethod
def suppress_torch_distributed_warnings(
fn: Callable[..., Any],
) -> Callable[..., Any]:
def inner_fn(*args: Any, **kwargs: Any) -> Any:
with torch._logging.hide_warnings(
torch._logging._internal.user_warning_filter
):
return fn(*args, **kwargs)
return inner_fn
def skip_code(code: types.CodeType) -> None:
set_code_exec_strategy(
code, FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT)
)
| TorchPatcher |
python | huggingface__transformers | tests/models/instructblip/test_modeling_instructblip.py | {
"start": 17542,
"end": 25157
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (
(
InstructBlipModel,
InstructBlipForConditionalGeneration,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = {"image-text-to-text": InstructBlipForConditionalGeneration}
additional_model_inputs = ["qformer_input_ids", "input_ids"]
test_resize_embeddings = True
test_attention_outputs = False
_is_composite = True
def setUp(self):
self.model_tester = InstructBlipForConditionalGenerationDecoderOnlyModelTester(self)
self.config_tester = ConfigTester(
self,
config_class=InstructBlipConfig,
has_text_modality=False,
common_properties=["num_query_tokens", "image_token_index"],
)
def test_config(self):
self.config_tester.run_common_tests()
def test_for_conditional_generation(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_conditional_generation(*config_and_inputs)
@unittest.skip(
reason=" InstructBlipQFormerModel does not support an attention implementation through torch.nn.functional.scaled_dot_product_attention yet."
)
def test_eager_matches_sdpa_generate(self):
pass
@unittest.skip(reason="Hidden_states is tested in individual model tests")
def test_hidden_states_output(self):
pass
@unittest.skip(reason="InstructBlipForConditionalGeneration doesn't support inputs_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Tied weights are tested in individual model tests")
def test_tied_weights_keys(self):
pass
@unittest.skip(reason="Retain_grad is tested in individual model tests")
def test_retain_grad_hidden_states_attentions(self):
pass
@unittest.skip(reason="InstructBlipModel does not have input/output embeddings")
def test_model_get_set_embeddings(self):
pass
@unittest.skip(reason="InstructBLIP has no separate base model without a head.")
def test_model_base_model_prefix(self):
pass
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = ["pixel_values"]
self.assertListEqual(arg_names[:1], expected_arg_names)
def test_load_vision_qformer_text_config(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
# Save InstructBlipConfig and check if we can load InstructBlipVisionConfig from it
with tempfile.TemporaryDirectory() as tmp_dir_name:
config.save_pretrained(tmp_dir_name)
vision_config = InstructBlipVisionConfig.from_pretrained(tmp_dir_name)
self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
# Save InstructBlipConfig and check if we can load InstructBlipQFormerConfig from it
with tempfile.TemporaryDirectory() as tmp_dir_name:
config.save_pretrained(tmp_dir_name)
qformer_config = InstructBlipQFormerConfig.from_pretrained(tmp_dir_name)
self.assertDictEqual(config.qformer_config.to_dict(), qformer_config.to_dict())
@slow
def test_model_from_pretrained(self):
model_name = "Salesforce/instructblip-flan-t5-xl"
model = InstructBlipForConditionalGeneration.from_pretrained(model_name)
self.assertIsNotNone(model)
# overwrite because InstructBLIP internally calls LM.generate() with embeds thus it cannot operate in no cache format
def _check_generate_outputs(self, output, config, use_cache=False, num_return_sequences=1, num_beams=1):
use_cache = True # force this to be True in case False is passed
super()._check_generate_outputs(
output, config, use_cache=use_cache, num_return_sequences=num_return_sequences, num_beams=num_beams
)
def test_sdpa_can_dispatch_composite_models(self):
"""
Tests if composite models dispatch correctly on SDPA/eager when requested so when loading the model.
This tests only by looking at layer names, as usually SDPA layers are called "SDPAAttention".
In contrast to the above test, this one checks if the "config._attn_implementation" is a dict after the model
is loaded, because we manually replicate requested attn implementation on each sub-config when loading.
See https://github.com/huggingface/transformers/pull/32238 for more info
The test tries to cover most general cases of composite models, VLMs with vision and text configs. Any model
that has a different set of sub-configs has to overwrite this test.
"""
if not self.has_attentions:
self.skipTest(reason="Model architecture does not support attentions")
if not self._is_composite:
self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA")
for model_class in self.all_model_classes:
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model_sdpa = model_class.from_pretrained(tmpdirname)
model_sdpa = model_sdpa.eval().to(torch_device)
# `None` as it is the requested one which will be assigned to each sub-config
# Sub-model will dispatch to SDPA if it can (checked below that `SDPA` layers are present)
self.assertTrue(model.language_model.config._attn_implementation == "sdpa")
self.assertTrue(model.vision_model.config._attn_implementation == "sdpa")
self.assertTrue(model.qformer.config._attn_implementation == "eager")
model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager")
model_eager = model_eager.eval().to(torch_device)
self.assertTrue(model_eager.config._attn_implementation == "eager")
self.assertTrue(model_eager.language_model.config._attn_implementation == "eager")
self.assertTrue(model_eager.vision_model.config._attn_implementation == "eager")
self.assertTrue(model_eager.qformer.config._attn_implementation == "eager")
for name, submodule in model_eager.named_modules():
class_name = submodule.__class__.__name__
if (
class_name.endswith("Attention")
and getattr(submodule, "config", None)
and submodule.config._attn_implementation == "sdpa"
):
raise ValueError("The eager model should not have SDPA attention layers")
# We will verify our results on an image of cute cats
def prepare_img():
url = "https://huggingface.co/hf-internal-testing/blip-test-image/resolve/main/demo.jpg"
image = Image.open(requests.get(url, stream=True).raw)
return image
@require_vision
@require_torch
@slow
| InstructBlipForConditionalGenerationDecoderOnlyTest |
python | kubernetes-client__python | kubernetes/client/models/v1_role_binding.py | {
"start": 383,
"end": 7647
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'role_ref': 'V1RoleRef',
'subjects': 'list[RbacV1Subject]'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'role_ref': 'roleRef',
'subjects': 'subjects'
}
def __init__(self, api_version=None, kind=None, metadata=None, role_ref=None, subjects=None, local_vars_configuration=None): # noqa: E501
"""V1RoleBinding - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._kind = None
self._metadata = None
self._role_ref = None
self._subjects = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
self.role_ref = role_ref
if subjects is not None:
self.subjects = subjects
@property
def api_version(self):
"""Gets the api_version of this V1RoleBinding. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1RoleBinding. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1RoleBinding.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1RoleBinding. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this V1RoleBinding. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1RoleBinding. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1RoleBinding.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1RoleBinding. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1RoleBinding. # noqa: E501
:return: The metadata of this V1RoleBinding. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1RoleBinding.
:param metadata: The metadata of this V1RoleBinding. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def role_ref(self):
"""Gets the role_ref of this V1RoleBinding. # noqa: E501
:return: The role_ref of this V1RoleBinding. # noqa: E501
:rtype: V1RoleRef
"""
return self._role_ref
@role_ref.setter
def role_ref(self, role_ref):
"""Sets the role_ref of this V1RoleBinding.
:param role_ref: The role_ref of this V1RoleBinding. # noqa: E501
:type: V1RoleRef
"""
if self.local_vars_configuration.client_side_validation and role_ref is None: # noqa: E501
raise ValueError("Invalid value for `role_ref`, must not be `None`") # noqa: E501
self._role_ref = role_ref
@property
def subjects(self):
"""Gets the subjects of this V1RoleBinding. # noqa: E501
Subjects holds references to the objects the role applies to. # noqa: E501
:return: The subjects of this V1RoleBinding. # noqa: E501
:rtype: list[RbacV1Subject]
"""
return self._subjects
@subjects.setter
def subjects(self, subjects):
"""Sets the subjects of this V1RoleBinding.
Subjects holds references to the objects the role applies to. # noqa: E501
:param subjects: The subjects of this V1RoleBinding. # noqa: E501
:type: list[RbacV1Subject]
"""
self._subjects = subjects
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1RoleBinding):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1RoleBinding):
return True
return self.to_dict() != other.to_dict()
| V1RoleBinding |
python | scrapy__scrapy | scrapy/core/http2/stream.py | {
"start": 1636,
"end": 2324
} | class ____(Enum):
# Received a StreamEnded event from the remote
ENDED = 1
# Received a StreamReset event -- ended abruptly
RESET = 2
# Transport connection was lost
CONNECTION_LOST = 3
# Expected response body size is more than allowed limit
MAXSIZE_EXCEEDED = 4
# Response deferred is cancelled by the client
# (happens when client called response_deferred.cancel())
CANCELLED = 5
# Connection lost and the stream was not initiated
INACTIVE = 6
# The hostname of the request is not same as of connected peer hostname
# As a result sending this request will the end the connection
INVALID_HOSTNAME = 7
| StreamCloseReason |
python | numpy__numpy | numpy/lib/tests/test_shape_base.py | {
"start": 17571,
"end": 18504
} | class ____:
def test_non_iterable(self):
assert_raises(TypeError, column_stack, 1)
def test_1D_arrays(self):
# example from docstring
a = np.array((1, 2, 3))
b = np.array((2, 3, 4))
expected = np.array([[1, 2],
[2, 3],
[3, 4]])
actual = np.column_stack((a, b))
assert_equal(actual, expected)
def test_2D_arrays(self):
# same as hstack 2D docstring example
a = np.array([[1], [2], [3]])
b = np.array([[2], [3], [4]])
expected = np.array([[1, 2],
[2, 3],
[3, 4]])
actual = np.column_stack((a, b))
assert_equal(actual, expected)
def test_generator(self):
with pytest.raises(TypeError, match="arrays to stack must be"):
column_stack(np.arange(3) for _ in range(2))
| TestColumnStack |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/merge.py | {
"start": 1201,
"end": 8201
} | class ____(Layer):
"""Generic merge layer for elementwise merge functions.
Used to implement `Sum`, `Average`, etc.
"""
def __init__(self, **kwargs):
"""Initializes a Merge layer.
Args:
**kwargs: standard layer keyword arguments.
"""
super(_Merge, self).__init__(**kwargs)
self.supports_masking = True
def _merge_function(self, inputs):
raise NotImplementedError
def _compute_elemwise_op_output_shape(self, shape1, shape2):
"""Computes the shape of the resultant of an elementwise operation.
Args:
shape1: tuple or None. Shape of the first tensor
shape2: tuple or None. Shape of the second tensor
Returns:
expected output shape when an element-wise operation is
carried out on 2 tensors with shapes shape1 and shape2.
tuple or None.
Raises:
ValueError: if shape1 and shape2 are not compatible for
element-wise operations.
"""
if None in [shape1, shape2]:
return None
elif len(shape1) < len(shape2):
return self._compute_elemwise_op_output_shape(shape2, shape1)
elif not shape2:
return shape1
output_shape = list(shape1[:-len(shape2)])
for i, j in zip(shape1[-len(shape2):], shape2):
if i is None or j is None:
output_shape.append(None)
elif i == 1:
output_shape.append(j)
elif j == 1:
output_shape.append(i)
else:
if i != j:
raise ValueError(
'Operands could not be broadcast '
'together with shapes ' + str(shape1) + ' ' + str(shape2))
output_shape.append(i)
return tuple(output_shape)
@tf_utils.shape_type_conversion
def build(self, input_shape):
# Used purely for shape validation.
if not isinstance(input_shape[0], tuple):
raise ValueError('A merge layer should be called on a list of inputs.')
if len(input_shape) < 2:
raise ValueError('A merge layer should be called '
'on a list of at least 2 inputs. '
'Got ' + str(len(input_shape)) + ' inputs.')
batch_sizes = {s[0] for s in input_shape if s} - {None}
if len(batch_sizes) > 1:
raise ValueError(
'Can not merge tensors with different '
'batch sizes. Got tensors with shapes : ' + str(input_shape))
if input_shape[0] is None:
output_shape = None
else:
output_shape = input_shape[0][1:]
for i in range(1, len(input_shape)):
if input_shape[i] is None:
shape = None
else:
shape = input_shape[i][1:]
output_shape = self._compute_elemwise_op_output_shape(output_shape, shape)
# If the inputs have different ranks, we have to reshape them
# to make them broadcastable.
if None not in input_shape and len(set(map(len, input_shape))) == 1:
self._reshape_required = False
else:
self._reshape_required = True
def call(self, inputs):
if not isinstance(inputs, (list, tuple)):
raise ValueError('A merge layer should be called on a list of inputs.')
if self._reshape_required:
reshaped_inputs = []
input_ndims = list(map(backend.ndim, inputs))
if None not in input_ndims:
# If ranks of all inputs are available,
# we simply expand each of them at axis=1
# until all of them have the same rank.
max_ndim = max(input_ndims)
for x in inputs:
x_ndim = backend.ndim(x)
for _ in range(max_ndim - x_ndim):
x = array_ops.expand_dims(x, axis=1)
reshaped_inputs.append(x)
return self._merge_function(reshaped_inputs)
else:
# Transpose all inputs so that batch size is the last dimension.
# (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... , batch_size)
transposed = False
for x in inputs:
x_ndim = backend.ndim(x)
if x_ndim is None:
x_shape = array_ops.shape(x)
batch_size = x_shape[0]
new_shape = backend.concatenate(
[x_shape[1:],
array_ops.expand_dims(batch_size, axis=-1)])
x_transposed = array_ops.reshape(
x,
array_ops_stack.stack(
[batch_size, math_ops.reduce_prod(x_shape[1:])], axis=0))
x_transposed = array_ops.transpose(x_transposed, perm=(1, 0))
x_transposed = array_ops.reshape(x_transposed, new_shape)
reshaped_inputs.append(x_transposed)
transposed = True
elif x_ndim > 1:
dims = list(range(1, x_ndim)) + [0]
reshaped_inputs.append(array_ops.transpose(x, perm=dims))
transposed = True
else:
# We don't transpose inputs if they are 1D vectors or scalars.
reshaped_inputs.append(x)
y = self._merge_function(reshaped_inputs)
y_ndim = backend.ndim(y)
if transposed:
# If inputs have been transposed, we have to transpose the output too.
if y_ndim is None:
y_shape = array_ops.shape(y)
y_ndim = array_ops.shape(y_shape)[0]
batch_size = y_shape[y_ndim - 1]
new_shape = backend.concatenate([
array_ops.expand_dims(batch_size, axis=-1), y_shape[:y_ndim - 1]
])
y = array_ops.reshape(y, (-1, batch_size))
y = array_ops.transpose(y, perm=(1, 0))
y = array_ops.reshape(y, new_shape)
elif y_ndim > 1:
dims = [y_ndim - 1] + list(range(y_ndim - 1))
y = array_ops.transpose(y, perm=dims)
return y
else:
return self._merge_function(inputs)
@tf_utils.shape_type_conversion
def compute_output_shape(self, input_shape):
if input_shape[0] is None:
output_shape = None
else:
output_shape = input_shape[0][1:]
for i in range(1, len(input_shape)):
if input_shape[i] is None:
shape = None
else:
shape = input_shape[i][1:]
output_shape = self._compute_elemwise_op_output_shape(output_shape, shape)
batch_sizes = {s[0] for s in input_shape if s is not None} - {None}
if len(batch_sizes) == 1:
output_shape = (list(batch_sizes)[0],) + output_shape
else:
output_shape = (None,) + output_shape
return output_shape
def compute_mask(self, inputs, mask=None):
if mask is None:
return None
if not isinstance(mask, (tuple, list)):
raise ValueError('`mask` should be a list.')
if not isinstance(inputs, (tuple, list)):
raise ValueError('`inputs` should be a list.')
if len(mask) != len(inputs):
raise ValueError('The lists `inputs` and `mask` '
'should have the same length.')
if all(m is None for m in mask):
return None
masks = [array_ops.expand_dims(m, axis=0) for m in mask if m is not None]
return backend.all(
backend.concatenate(masks, axis=0), axis=0, keepdims=False)
| _Merge |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 50802,
"end": 51100
} | class ____:
def test_default_none_parameter_imports(self):
stub = FunctionStub('test', inspect.signature(default_none_parameter), FunctionKind.MODULE)
expected = {'typing': {'Optional'}}
assert get_imports_for_signature(stub.signature) == expected
| TestGetImportsForSignature |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.