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 | django__django | tests/migrations/test_base.py | {
"start": 776,
"end": 8700
} | class ____(TransactionTestCase):
"""
Contains an extended set of asserts for testing migrations and schema
operations.
"""
available_apps = ["migrations"]
databases = {"default", "other"}
def tearDown(self):
# Reset applied-migrations state.
for db in self.databases:
recorder = MigrationRecorder(connections[db])
recorder.migration_qs.filter(app="migrations").delete()
def get_table_description(self, table, using="default"):
with connections[using].cursor() as cursor:
return connections[using].introspection.get_table_description(cursor, table)
def assertTableExists(self, table, using="default"):
with connections[using].cursor() as cursor:
self.assertIn(table, connections[using].introspection.table_names(cursor))
def assertTableNotExists(self, table, using="default"):
with connections[using].cursor() as cursor:
self.assertNotIn(
table, connections[using].introspection.table_names(cursor)
)
def assertColumnExists(self, table, column, using="default"):
self.assertIn(
column, [c.name for c in self.get_table_description(table, using=using)]
)
def assertColumnNotExists(self, table, column, using="default"):
self.assertNotIn(
column, [c.name for c in self.get_table_description(table, using=using)]
)
def _get_column_allows_null(self, table, column, using):
return [
c.null_ok
for c in self.get_table_description(table, using=using)
if c.name == column
][0]
def assertColumnNull(self, table, column, using="default"):
self.assertTrue(self._get_column_allows_null(table, column, using))
def assertColumnNotNull(self, table, column, using="default"):
self.assertFalse(self._get_column_allows_null(table, column, using))
def _get_column_collation(self, table, column, using):
return next(
f.collation
for f in self.get_table_description(table, using=using)
if f.name == column
)
def assertColumnCollation(self, table, column, collation, using="default"):
self.assertEqual(self._get_column_collation(table, column, using), collation)
def _get_table_comment(self, table, using):
with connections[using].cursor() as cursor:
return next(
t.comment
for t in connections[using].introspection.get_table_list(cursor)
if t.name == table
)
def assertTableComment(self, table, comment, using="default"):
self.assertEqual(self._get_table_comment(table, using), comment)
def assertTableCommentNotExists(self, table, using="default"):
self.assertIn(self._get_table_comment(table, using), [None, ""])
def assertIndexExists(
self, table, columns, value=True, using="default", index_type=None
):
with connections[using].cursor() as cursor:
self.assertEqual(
value,
any(
c["index"]
for c in connections[using]
.introspection.get_constraints(cursor, table)
.values()
if (
c["columns"] == list(columns)
and c["index"] is True
and (index_type is None or c["type"] == index_type)
and not c["unique"]
)
),
)
def assertIndexNotExists(self, table, columns):
return self.assertIndexExists(table, columns, False)
def assertIndexNameExists(self, table, index, using="default"):
with connections[using].cursor() as cursor:
self.assertIn(
index,
connection.introspection.get_constraints(cursor, table),
)
def assertIndexNameNotExists(self, table, index, using="default"):
with connections[using].cursor() as cursor:
self.assertNotIn(
index,
connection.introspection.get_constraints(cursor, table),
)
def assertConstraintExists(self, table, name, value=True, using="default"):
with connections[using].cursor() as cursor:
constraints = (
connections[using].introspection.get_constraints(cursor, table).items()
)
self.assertEqual(
value,
any(c["check"] for n, c in constraints if n == name),
)
def assertConstraintNotExists(self, table, name):
return self.assertConstraintExists(table, name, False)
def assertUniqueConstraintExists(self, table, columns, value=True, using="default"):
with connections[using].cursor() as cursor:
constraints = (
connections[using].introspection.get_constraints(cursor, table).values()
)
self.assertEqual(
value,
any(c["unique"] for c in constraints if c["columns"] == list(columns)),
)
def assertFKExists(self, table, columns, to, value=True, using="default"):
if not connections[using].features.can_introspect_foreign_keys:
return
with connections[using].cursor() as cursor:
self.assertEqual(
value,
any(
c["foreign_key"] == to
for c in connections[using]
.introspection.get_constraints(cursor, table)
.values()
if c["columns"] == list(columns)
),
)
def assertFKNotExists(self, table, columns, to):
return self.assertFKExists(table, columns, to, False)
def assertFormatterFailureCaught(
self, *args, module="migrations.test_migrations", **kwargs
):
with (
self.temporary_migration_module(module=module),
AssertFormatterFailureCaughtContext(self) as ctx,
):
call_command(*args, stdout=ctx.stdout, stderr=ctx.stderr, **kwargs)
@contextmanager
def temporary_migration_module(self, app_label="migrations", module=None):
"""
Allows testing management commands in a temporary migrations module.
Wrap all invocations to makemigrations and squashmigrations with this
context manager in order to avoid creating migration files in your
source tree inadvertently.
Takes the application label that will be passed to makemigrations or
squashmigrations and the Python path to a migrations module.
The migrations module is used as a template for creating the temporary
migrations module. If it isn't provided, the application's migrations
module is used, if it exists.
Returns the filesystem path to the temporary migrations module.
"""
with tempfile.TemporaryDirectory() as temp_dir:
target_dir = tempfile.mkdtemp(dir=temp_dir)
with open(os.path.join(target_dir, "__init__.py"), "w"):
pass
target_migrations_dir = os.path.join(target_dir, "migrations")
if module is None:
module = apps.get_app_config(app_label).name + ".migrations"
try:
source_migrations_dir = module_dir(import_module(module))
except (ImportError, ValueError):
pass
else:
shutil.copytree(source_migrations_dir, target_migrations_dir)
with extend_sys_path(temp_dir):
new_module = os.path.basename(target_dir) + ".migrations"
with self.settings(MIGRATION_MODULES={app_label: new_module}):
yield target_migrations_dir
| MigrationTestBase |
python | PyCQA__pylint | doc/data/messages/n/no-method-argument/bad.py | {
"start": 0,
"end": 87
} | class ____:
def print_greeting(): # [no-method-argument]
print("hello")
| Person |
python | google__jax | tests/lax_numpy_indexing_test.py | {
"start": 52563,
"end": 54538
} | class ____(enum.Enum):
UPDATE = 0
ADD = 1
SUB = 2
MUL = 3
DIV = 4
POW = 5
MIN = 6
MAX = 7
def np_fn(op, indexer, x, y):
x = x.copy()
if op == UpdateOps.UPDATE:
x[indexer] = y
elif op == UpdateOps.ADD:
np.add.at(x, indexer, y)
elif op == UpdateOps.SUB:
np.subtract.at(x, indexer, y)
elif op == UpdateOps.MUL:
np.multiply.at(x, indexer, y)
elif op == UpdateOps.DIV:
with jtu.ignore_warning(category=RuntimeWarning):
np.divide.at(x, indexer, y)
elif op == UpdateOps.POW:
with jtu.ignore_warning(category=RuntimeWarning):
np.power.at(x, indexer, y)
elif op == UpdateOps.MIN:
np.minimum.at(x, indexer, y.astype(x.dtype))
elif op == UpdateOps.MAX:
np.maximum.at(x, indexer, y.astype(x.dtype))
else:
raise ValueError(f"{op=}")
return x
def jax_fn(op, indexer, x, y, indices_are_sorted=False,
unique_indices=False, mode=None, wrap_negative_indices=True):
x = jnp.array(x)
return {
UpdateOps.UPDATE: x.at[indexer].set,
UpdateOps.ADD: x.at[indexer].add,
UpdateOps.SUB: x.at[indexer].subtract,
UpdateOps.MUL: x.at[indexer].multiply,
UpdateOps.DIV: x.at[indexer].divide,
UpdateOps.POW: x.at[indexer].power,
UpdateOps.MIN: x.at[indexer].min,
UpdateOps.MAX: x.at[indexer].max,
}[op](y, indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
wrap_negative_indices=wrap_negative_indices)
def dtypes(op):
if op == UpdateOps.UPDATE:
return all_dtypes
elif op == UpdateOps.DIV or op == UpdateOps.POW:
return jtu.dtypes.inexact
else:
return default_dtypes
def _update_tol(op):
if op == UpdateOps.POW:
f32_tol = 2e-4 if jtu.test_device_matches(["tpu"]) else 1e-5
tol = {np.float32: f32_tol, np.complex64: f32_tol, np.complex128: 1e-14}
else:
tol = {np.complex128: 1e-14}
return tol
| UpdateOps |
python | spyder-ide__spyder | spyder/plugins/help/widgets.py | {
"start": 1743,
"end": 2177
} | class ____:
# Toggles
ToggleAutomaticImport = 'toggle_automatic_import_action'
ToggleLocked = 'toggle_locked_action'
TogglePlainMode = 'toggle_plain_mode_action'
ToggleRichMode = 'toggle_rich_mode_action'
ToggleShowSource = 'toggle_show_source_action'
ToggleWrap = 'toggle_wrap_action'
CopyAction = "help_widget_copy_action"
SelectAll = "select_all_action",
Home = 'home_action'
| HelpWidgetActions |
python | getsentry__sentry | src/sentry/api/serializers/models/group.py | {
"start": 33723,
"end": 35201
} | class ____(GroupSerializer):
def serialize( # type: ignore[override] # return value is a subset
self,
obj: Group,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> SharedGroupSerializerResponse:
result = super().serialize(obj, attrs, user)
# avoids a circular import
from sentry.api.serializers.models import SharedEventSerializer, SharedProjectSerializer
event = obj.get_latest_event()
return {
"culprit": result["culprit"],
"id": result["id"],
"isUnhandled": result.get("isUnhandled"),
"issueCategory": result["issueCategory"],
"permalink": result["permalink"],
"shortId": result["shortId"],
"title": result["title"],
"latestEvent": serialize(event, user, SharedEventSerializer()),
"project": serialize(obj.project, user, SharedProjectSerializer()),
}
SKIP_SNUBA_FIELDS = frozenset(
(
"status",
"substatus",
"detector",
"bookmarked_by",
"assigned_to",
"for_review",
"assigned_or_suggested",
"unassigned",
"linked",
"subscribed_by",
"first_release",
"first_seen",
"issue.category",
"issue.priority",
"issue.type",
"issue.seer_actionability",
"issue.seer_last_run",
)
)
| SharedGroupSerializer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 10869,
"end": 11980
} | class ____(_AbstractORMCompileState):
"""ORM compile state that is a passthrough, except for autoflush."""
@classmethod
def orm_pre_session_exec(
cls,
session,
statement,
params,
execution_options,
bind_arguments,
is_pre_event,
):
# consume result-level load_options. These may have been set up
# in an ORMExecuteState hook
(
load_options,
execution_options,
) = QueryContext.default_load_options.from_execution_options(
"_sa_orm_load_options",
{
"autoflush",
},
execution_options,
statement._execution_options,
)
if not is_pre_event and load_options._autoflush:
session._autoflush()
return statement, execution_options, params
@classmethod
def orm_setup_cursor_result(
cls,
session,
statement,
params,
execution_options,
bind_arguments,
result,
):
return result
| _AutoflushOnlyORMCompileState |
python | huggingface__transformers | tests/utils/import_structures/import_structure_raw_register_with_versions.py | {
"start": 1273,
"end": 1415
} | class ____:
def __init__(self):
pass
@requires(backends=("torch==2.5",))
def d4():
pass
@requires(backends=("torch!=2.5",))
| D4 |
python | django__django | tests/gis_tests/geoapp/feeds.py | {
"start": 341,
"end": 859
} | class ____(TestGeoRSS1):
def geometry(self, obj):
# This should attach a <georss:box> element for the extent of
# the cities in the database. This tuple came from
# calling `City.objects.aggregate(Extent())` -- we can't do that call
# here because `Extent` is not implemented for MySQL/Oracle.
return (-123.30, -41.32, 174.78, 48.46)
def item_geometry(self, item):
# Returning a simple tuple for the geometry.
return item.point.x, item.point.y
| TestGeoRSS2 |
python | getsentry__sentry | src/sentry/consumers/synchronized.py | {
"start": 701,
"end": 1500
} | class ____(Generic[T]):
"""
This class wraps a value that is shared between multiple threads,
providing thread-safe ``get`` and ``set`` methods for reading and writing
(replacing) the value.
"""
def __init__(self, value: T) -> None:
self.__value = value
self.__lock = Lock()
# TODO: For future use, it might make sense to expose the other lock
# arguments on `get` and `set`, such as `timeout`, `block`, etc.
@contextmanager
def get(self) -> Generator[T]:
"""
Get the synchronized value.
"""
with self.__lock:
yield self.__value
def set(self, value: T) -> None:
"""
Set the synchronized value.
"""
with self.__lock:
self.__value = value
| Synchronized |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 264844,
"end": 265197
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("CreatedRepositoryContribution", graphql_name="node")
| CreatedRepositoryContributionEdge |
python | xlwings__xlwings | tests/test_names.py | {
"start": 48,
"end": 4875
} | class ____(TestBase):
def test_get_names_index(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.wb1.sheets[0].range("A1").name = "test2"
self.assertEqual(self.wb1.names(1).name, "test1")
self.assertEqual(self.wb1.names[1].name, "test2")
def test_names_contain(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.assertTrue("test1" in self.wb1.names)
def test_len(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.wb1.sheets[0].range("A1").name = "test2"
self.assertEqual(len(self.wb1.names), 2)
def test_count(self):
self.assertEqual(len(self.wb1.names), self.wb1.names.count)
def test_names_iter(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.wb1.sheets[0].range("A1").name = "test2"
for ix, n in enumerate(self.wb1.names):
if ix == 0:
self.assertEqual(n.name, "test1")
if ix == 1:
self.assertEqual(n.name, "test2")
def test_get_inexisting_name(self):
self.assertIsNone(self.wb1.sheets[0].range("A1").name)
def test_get_set_named_range(self):
self.wb1.sheets[0].range("A100").name = "test1"
self.assertEqual(self.wb1.sheets[0].range("A100").name.name, "test1")
self.wb1.sheets[0].range("A200:B204").name = "test2"
self.assertEqual(self.wb1.sheets[0].range("A200:B204").name.name, "test2")
def test_delete_named_item1(self):
self.wb1.sheets[0].range("B10:C11").name = "to_be_deleted"
self.assertEqual(
self.wb1.sheets[0].range("to_be_deleted").name.name, "to_be_deleted"
)
del self.wb1.names["to_be_deleted"]
self.assertIsNone(self.wb1.sheets[0].range("B10:C11").name)
def test_delete_named_item2(self):
self.wb1.sheets[0].range("B10:C11").name = "to_be_deleted"
self.assertEqual(
self.wb1.sheets[0].range("to_be_deleted").name.name, "to_be_deleted"
)
self.wb1.names["to_be_deleted"].delete()
self.assertIsNone(self.wb1.sheets[0].range("B10:C11").name)
def test_delete_named_item3(self):
self.wb1.sheets[0].range("B10:C11").name = "to_be_deleted"
self.assertEqual(
self.wb1.sheets[0].range("to_be_deleted").name.name, "to_be_deleted"
)
self.wb1.sheets[0].range("to_be_deleted").name.delete()
self.assertIsNone(self.wb1.sheets[0].range("B10:C11").name)
def test_names_collection(self):
self.wb1.sheets[0].range("A1").name = "name1"
self.wb1.sheets[0].range("A2").name = "name2"
self.assertTrue("name1" in self.wb1.names and "name2" in self.wb1.names)
self.wb1.sheets[0].range("A3").name = "name3"
self.assertTrue(
"name1" in self.wb1.names
and "name2" in self.wb1.names
and "name3" in self.wb1.names
)
def test_sheet_scope(self):
self.wb2.sheets[0].range("B2:C3").name = "Sheet1!sheet_scope1"
self.wb2.sheets[0].range("sheet_scope1").value = [[1.0, 2.0], [3.0, 4.0]]
self.assertEqual(
self.wb2.sheets[0].range("B2:C3").value, [[1.0, 2.0], [3.0, 4.0]]
)
with self.assertRaises(Exception):
self.wb2.sheets[1].range("sheet_scope1").value
def test_workbook_scope(self):
self.wb1.sheets[0].range("A1").name = "test1"
self.wb1.sheets[0].range("test1").value = 123.0
self.assertEqual(self.wb1.names["test1"].refers_to_range.value, 123.0)
def test_contains_name(self):
self.wb1.sheets[0].range("A1").name = "test1"
self.assertTrue(self.wb1.names.contains("test1"))
self.assertFalse(self.wb1.names.contains("test2"))
def test_wb_names_add(self):
self.wb1.names.add("test1", "=Sheet1!$A$1:$B$3")
self.assertEqual(self.wb1.sheets[0].range("A1:B3").name.name, "test1")
def test_sht_names_add(self):
self.wb1.sheets[0].names.add("test1", "=Sheet1!$A$1:$B$3")
self.assertEqual(self.wb1.sheets[0].range("A1:B3").name.name, "Sheet1!test1")
def test_refers_to_range(self):
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.assertEqual(
self.wb1.sheets[0].range("B2:D10"),
self.wb1.sheets[0].range("B2:D10").name.refers_to_range,
)
def test_refers_to_range_sheet_with_spaces(self):
# This will cause quotes around sheet reference which caused a bug on mac
self.wb1.sheets[0].name = "She et1"
self.wb1.sheets[0].range("B2:D10").name = "test1"
self.assertEqual(
self.wb1.sheets["She et1"].range("B2:D10"),
self.wb1.names["test1"].refers_to_range,
)
if __name__ == "__main__":
unittest.main()
| TestNames |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 27590,
"end": 27724
} | class ____(RayError):
"""Raised when an asyncio actor intentionally exits via exit_actor()."""
pass
@PublicAPI
| AsyncioActorExit |
python | numba__numba | numba/tests/test_debug.py | {
"start": 4986,
"end": 5903
} | class ____(DebugTestBase):
func_name = 'simple_gen'
def compile_simple_gen(self):
with captured_stdout() as out:
cfunc = njit((types.int64, types.int64))(simple_gen)
# Sanity check compiled function
self.assertPreciseEqual(list(cfunc(2, 5)), [2, 5])
return out.getvalue()
def test_dump_ir_generator(self):
with override_config('DUMP_IR', True):
out = self.compile_simple_gen()
self.check_debug_output(out, ['ir'])
self.assertIn('--GENERATOR INFO: %s' % self.func_name, out)
expected_gen_info = textwrap.dedent("""
generator state variables: ['x', 'y']
yield point #1: live variables = ['y'], weak live variables = ['x']
yield point #2: live variables = [], weak live variables = ['y']
""")
self.assertIn(expected_gen_info, out)
| TestGeneratorDebugOutput |
python | getsentry__sentry | src/sentry/notifications/api/endpoints/notification_actions_index.py | {
"start": 1667,
"end": 7578
} | class ____(OrganizationEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
"""
View existing NotificationActions or create a new one.
GET: Returns paginated, serialized NotificationActions for an organization
POST: Create a new NotificationAction
"""
permission_classes = (NotificationActionsPermission,)
@extend_schema(
operation_id="List Spike Protection Notifications",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
OrganizationParams.PROJECT,
OrganizationParams.PROJECT_ID_OR_SLUG,
NotificationParams.TRIGGER_TYPE,
],
responses={
201: OutgoingNotificationActionSerializer,
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
},
examples=NotificationActionExamples.CREATE_NOTIFICATION_ACTION,
)
def get(self, request: Request, organization: Organization) -> Response:
"""
Returns all Spike Protection Notification Actions for an organization.
Notification Actions notify a set of members when an action has been triggered through a notification service such as Slack or Sentry.
For example, organization owners and managers can receive an email when a spike occurs.
You can use either the `project` or `projectSlug` query parameter to filter for certain projects. Note that if both are present, `projectSlug` takes priority.
"""
queryset = NotificationAction.objects.filter(organization_id=organization.id)
# If a project query is specified, filter out non-project-specific actions
# otherwise, include them but still ensure project permissions are enforced
project_query = (
Q(projects__in=self.get_projects(request, organization))
if self.get_requested_project_ids_unchecked(request)
else Q(projects=None) | Q(projects__in=self.get_projects(request, organization))
)
queryset = queryset.filter(project_query).distinct()
trigger_type_query = request.GET.getlist("triggerType")
if trigger_type_query:
triggers: dict[str, int] = {v: k for k, v in NotificationAction.get_trigger_types()}
trigger_types = map(lambda t: triggers.get(t), trigger_type_query)
queryset = queryset.filter(trigger_type__in=trigger_types)
logger.info(
"notification_action.get_all",
extra={
"organization_id": organization.id,
"trigger_type_query": trigger_type_query,
"project_query": self.get_requested_project_ids_unchecked(request),
},
)
return self.paginate(
request=request,
queryset=queryset,
on_results=lambda action: serialize(action, request.user),
paginator_cls=OffsetPaginator,
)
@extend_schema(
operation_id="Create a Spike Protection Notification Action",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
],
request=NotificationActionSerializer,
responses={
201: OutgoingNotificationActionSerializer,
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
},
examples=NotificationActionExamples.CREATE_NOTIFICATION_ACTION,
)
def post(self, request: Request, organization: Organization) -> Response:
"""
Creates a new Notification Action for Spike Protection.
Notification Actions notify a set of members when an action has been triggered through a notification service such as Slack or Sentry.
For example, organization owners and managers can receive an email when a spike occurs.
"""
# team admins and regular org members don't have project:write on an org level
if not request.access.has_scope("project:write"):
# check if user has access to create notification actions for all requested projects
requested_projects = request.data.get("projects", [])
projects = self.get_projects(request, organization)
project_slugs = [project.slug for project in projects]
missing_access_projects = set(requested_projects).difference(set(project_slugs))
if missing_access_projects:
raise PermissionDenied(
detail="You do not have permission to create notification actions for projects "
+ str(list(missing_access_projects))
)
# team admins will have project:write scoped to their projects, members will not
team_admin_has_access = all(
[request.access.has_project_scope(project, "project:write") for project in projects]
)
# all() returns True for empty list, so include a check for it
if not team_admin_has_access or not projects:
raise PermissionDenied
serializer = NotificationActionSerializer(
context={"access": request.access, "organization": organization},
data=request.data,
)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
action = serializer.save()
logger.info(
"notification_action.create",
extra={"organization_id": organization.id, "action_id": action.id},
)
self.create_audit_entry(
request=request,
organization=organization,
target_object=action.id,
event=audit_log.get_event_id("NOTIFICATION_ACTION_ADD"),
data=action.get_audit_log_data(),
)
return Response(serialize(action, request.user), status=status.HTTP_201_CREATED)
| NotificationActionsIndexEndpoint |
python | tiangolo__fastapi | tests/test_sub_callbacks.py | {
"start": 669,
"end": 14142
} | class ____(BaseModel):
name: str
total: float
events_callback_router = APIRouter()
@events_callback_router.get("{$callback_url}/events/{$request.body.title}")
def event_callback(event: Event):
pass # pragma: nocover
subrouter = APIRouter()
@subrouter.post("/invoices/", callbacks=invoices_callback_router.routes)
def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None):
"""
Create an invoice.
This will (let's imagine) let the API user (some external developer) create an
invoice.
And this path operation will:
* Send the invoice to the client.
* Collect the money from the client.
* Send a notification back to the API user (the external developer), as a callback.
* At this point is that the API will somehow send a POST request to the
external API with the notification of the invoice event
(e.g. "payment successful").
"""
# Send the invoice, collect the money, send the notification (the callback)
return {"msg": "Invoice received"}
app.include_router(subrouter, callbacks=events_callback_router.routes)
client = TestClient(app)
def test_get():
response = client.post(
"/invoices/", json={"id": "fooinvoice", "customer": "John", "total": 5.3}
)
assert response.status_code == 200, response.text
assert response.json() == {"msg": "Invoice received"}
def test_openapi_schema():
with client:
response = client.get("/openapi.json")
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/invoices/": {
"post": {
"summary": "Create Invoice",
"description": 'Create an invoice.\n\nThis will (let\'s imagine) let the API user (some external developer) create an\ninvoice.\n\nAnd this path operation will:\n\n* Send the invoice to the client.\n* Collect the money from the client.\n* Send a notification back to the API user (the external developer), as a callback.\n * At this point is that the API will somehow send a POST request to the\n external API with the notification of the invoice event\n (e.g. "payment successful").',
"operationId": "create_invoice_invoices__post",
"parameters": [
{
"required": False,
"schema": IsDict(
{
"title": "Callback Url",
"anyOf": [
{
"type": "string",
"format": "uri",
"minLength": 1,
"maxLength": 2083,
},
{"type": "null"},
],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{
"title": "Callback Url",
"maxLength": 2083,
"minLength": 1,
"type": "string",
"format": "uri",
}
),
"name": "callback_url",
"in": "query",
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Invoice"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"callbacks": {
"event_callback": {
"{$callback_url}/events/{$request.body.title}": {
"get": {
"summary": "Event Callback",
"operationId": "event_callback__callback_url__events___request_body_title__get",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Event"
}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"invoice_notification": {
"{$callback_url}/invoices/{$request.body.id}": {
"post": {
"summary": "Invoice Notification",
"operationId": "invoice_notification__callback_url__invoices___request_body_id__post",
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/InvoiceEvent"
}
}
},
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/InvoiceEventReceived"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
},
}
}
},
"components": {
"schemas": {
"Event": {
"title": "Event",
"required": ["name", "total"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"total": {"title": "Total", "type": "number"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {
"$ref": "#/components/schemas/ValidationError"
},
}
},
},
"Invoice": {
"title": "Invoice",
"required": ["id", "customer", "total"],
"type": "object",
"properties": {
"id": {"title": "Id", "type": "string"},
"title": IsDict(
{
"title": "Title",
"anyOf": [{"type": "string"}, {"type": "null"}],
}
)
| IsDict(
# TODO: remove when deprecating Pydantic v1
{"title": "Title", "type": "string"}
),
"customer": {"title": "Customer", "type": "string"},
"total": {"title": "Total", "type": "number"},
},
},
"InvoiceEvent": {
"title": "InvoiceEvent",
"required": ["description", "paid"],
"type": "object",
"properties": {
"description": {"title": "Description", "type": "string"},
"paid": {"title": "Paid", "type": "boolean"},
},
},
"InvoiceEventReceived": {
"title": "InvoiceEventReceived",
"required": ["ok"],
"type": "object",
"properties": {"ok": {"title": "Ok", "type": "boolean"}},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
| Event |
python | getsentry__sentry | tests/sentry/issues/test_ingest_incident_integration.py | {
"start": 1449,
"end": 13977
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
self.alert_rule = self.create_alert_rule(
organization=self.organization,
projects=[self.project],
name="Test Alert Rule",
)
self.detector = self.create_detector(
project=self.project,
name="Test Detector",
)
self.alert_rule_detector = self.create_alert_rule_detector(
alert_rule_id=self.alert_rule.id,
detector=self.detector,
)
with self.tasks():
self.snuba_query = create_snuba_query(
query_type=SnubaQuery.Type.ERROR,
dataset=Dataset.Events,
query="hello",
aggregate="count()",
time_window=timedelta(minutes=1),
resolution=timedelta(minutes=1),
environment=self.environment,
event_types=[SnubaQueryEventType.EventType.ERROR],
)
self.query_subscription = create_snuba_subscription(
project=self.detector.project,
subscription_type=INCIDENTS_SNUBA_SUBSCRIPTION_TYPE,
snuba_query=self.snuba_query,
)
self.mock_status_change_message: StatusChangeMessageData = {
"id": "1",
"fingerprint": ["test-fingerprint"],
"project_id": self.project.id,
"new_status": GroupStatus.RESOLVED,
"new_substatus": None,
"detector_id": self.detector.id,
"activity_data": {"test": "test"},
}
def save_issue_occurrence(
self,
group_type: int = MetricIssue.type_id,
priority: int = DetectorPriorityLevel.HIGH,
) -> tuple[IssueOccurrence, GroupInfo]:
event = self.store_event(
data={"timestamp": timezone.now().isoformat()}, project_id=self.project.id
)
occurrence_data: IssueOccurrenceData = {
"id": "1",
"project_id": self.project.id,
"event_id": event.event_id,
"fingerprint": ["test-fingerprint"],
"issue_title": "Test Issue",
"subtitle": "Test Subtitle",
"resource_id": None,
"evidence_data": {
"detector_id": self.detector.id,
"data_packet_source_id": str(self.query_subscription.id),
},
"evidence_display": [
{"name": "Test Evidence", "value": "Test Value", "important": True}
],
"type": group_type,
"detection_time": timezone.now().timestamp(),
"level": "error",
"culprit": "test-culprit",
"priority": priority,
}
with patch("sentry.issues.ingest.eventstream") as _:
occurrence, group_info = save_issue_occurrence(occurrence_data, event)
assert group_info is not None
assert group_info.group.type == group_type
return occurrence, group_info
def test_save_issue_occurrence_creates_incident_and_relationship(self) -> None:
"""Test that save_issue_occurrence creates the relationship and incident"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
open_period = GroupOpenPeriod.objects.get(group=group)
item = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=item.incident_id)
activity = IncidentActivity.objects.filter(incident_id=incident.id)
assert len(activity) == 3 # detected, created, status change
def test_save_issue_occurrence_no_relationship_for_non_metric_issues(self) -> None:
# Test that save_issue_occurrence doesn't create relationships for non-metric issues
_, group_info = self.save_issue_occurrence(group_type=FeedbackGroup.type_id)
group = group_info.group
assert group is not None
open_period = GroupOpenPeriod.objects.get(group=group)
assert not IncidentGroupOpenPeriod.objects.filter(group_open_period=open_period).exists()
def test_updating_group_priority_updates_incident(self) -> None:
"""Test that a group priority update creates an equivalent IncidentActivity entry"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
assert GroupOpenPeriod.objects.filter(group=group, project=self.project).exists()
open_period = GroupOpenPeriod.objects.get(group=group, project=self.project)
_, group_info = self.save_issue_occurrence(priority=DetectorPriorityLevel.MEDIUM)
group = group_info.group
assert group is not None
item = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=item.incident_id)
activity = IncidentActivity.objects.filter(incident_id=incident.id)
assert len(activity) == 4
last_activity_entry = activity[3]
assert last_activity_entry.type == 2
assert last_activity_entry.value == str(IncidentStatus.WARNING.value)
assert last_activity_entry.previous_value == str(IncidentStatus.CRITICAL.value)
def test_resolving_group_updates_incident(self) -> None:
"""Test that save_issue_occurrence creates the relationship and incident"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
with self.tasks():
update_status(group, self.mock_status_change_message)
open_period = GroupOpenPeriod.objects.get(group=group)
assert open_period.date_ended is not None
item = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=item.incident_id)
activity = IncidentActivity.objects.filter(incident_id=incident.id)
assert len(activity) == 4 # detected, created, priority change, close
def test_can_close_outstanding_incident(self) -> None:
"""Test that we close incidents that are left open as a result of IGOP linkage bugs"""
four_minutes_ago = timezone.now() - timedelta(minutes=4)
three_minutes_ago = timezone.now() - timedelta(minutes=3)
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
assert GroupOpenPeriod.objects.filter(group=group, project=self.project).exists()
open_period = GroupOpenPeriod.objects.get(group=group, project=self.project)
# replicate the following conditions in the DB: an open incident is tied to
# a closed open period, and a new open period is being passed to create_from_occurrence()
dummy_relationship = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
dummy_open_period = GroupOpenPeriod.objects.create(
group=group,
date_started=four_minutes_ago,
date_ended=three_minutes_ago,
project=self.project,
)
incident = Incident.objects.get(id=dummy_relationship.incident_id)
dummy_relationship.delete()
IncidentGroupOpenPeriod.objects.create(
incident_id=incident.id,
incident_identifier=incident.identifier,
group_open_period=dummy_open_period,
)
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
incident.refresh_from_db()
assert IncidentGroupOpenPeriod.objects.count() == 2
assert incident.date_closed is not None
item = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
new_incident = Incident.objects.get(id=item.incident_id)
activity = IncidentActivity.objects.filter(incident_id=new_incident.id)
assert len(activity) == 3 # detected, created, status change
def test_can_resolve_outstanding_incident(self) -> None:
"""Test that we link and update an incident that was opened before the org started single processing on resolution"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
assert GroupOpenPeriod.objects.filter(group=group, project=self.project).exists()
open_period = GroupOpenPeriod.objects.get(group=group, project=self.project)
dummy_relationship = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=dummy_relationship.incident_id)
# this is a little hacky, but to emulate dual processing -> single processing I will
# just delete the IGOP relationship
IncidentGroupOpenPeriod.objects.all().delete()
with self.tasks():
update_status(group, self.mock_status_change_message)
open_period = GroupOpenPeriod.objects.get(group=group)
assert open_period.date_ended is not None
item = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
assert item.incident_id == incident.id
activity = IncidentActivity.objects.filter(incident_id=incident.id)
assert len(activity) == 4 # detected, created, priority change, close
last_activity_entry = activity[3]
assert last_activity_entry.type == 2
assert last_activity_entry.previous_value == str(IncidentStatus.CRITICAL.value)
assert last_activity_entry.value == str(IncidentStatus.CLOSED.value)
@mock.patch("sentry.models.group.logger")
def test_bulk_transition_new_group_to_ongoing__metric_issues__no_incident_activites(
self, mock_logger
) -> None:
"""Ensure we do not trigger an IGOP write for a new to ongoing status change"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
open_period = GroupOpenPeriod.objects.get(group=group, project=self.project)
assert open_period
dummy_relationship = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=dummy_relationship.incident_id)
assert len(IncidentActivity.objects.filter(incident_id=incident.id)) == 3
group.substatus = GroupSubStatus.NEW
group.save()
bulk_transition_group_to_ongoing(GroupStatus.UNRESOLVED, GroupSubStatus.NEW, [group.id])
assert Activity.objects.filter(
group=group, type=ActivityType.AUTO_SET_ONGOING.value
).exists()
assert GroupHistory.objects.filter(
group=group, status=GroupHistoryStatus.UNRESOLVED
).exists()
assert mock_logger.error.call_count == 0
assert (
len(IncidentActivity.objects.filter(incident_id=incident.id)) == 3
) # no new IGOP entry
@mock.patch("sentry.models.group.logger")
def test_bulk_transition_regressed_group_to_ongoing__metric_issues__no_incident_activites(
self, mock_logger
) -> None:
"""Ensure we do not trigger an IGOP write for a regressed to ongoing status change"""
_, group_info = self.save_issue_occurrence()
group = group_info.group
assert group is not None
open_period = GroupOpenPeriod.objects.get(group=group, project=self.project)
assert open_period
dummy_relationship = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period)
incident = Incident.objects.get(id=dummy_relationship.incident_id)
assert len(IncidentActivity.objects.filter(incident_id=incident.id)) == 3
group.substatus = GroupSubStatus.REGRESSED
group.save()
bulk_transition_group_to_ongoing(
GroupStatus.UNRESOLVED, GroupSubStatus.REGRESSED, [group.id]
)
assert Activity.objects.filter(
group=group, type=ActivityType.AUTO_SET_ONGOING.value
).exists()
assert GroupHistory.objects.filter(
group=group, status=GroupHistoryStatus.UNRESOLVED
).exists()
assert mock_logger.error.call_count == 0
assert (
len(IncidentActivity.objects.filter(incident_id=incident.id)) == 3
) # no new IGOP entry
| IncidentGroupOpenPeriodIntegrationTest |
python | django__django | tests/admin_inlines/admin.py | {
"start": 2881,
"end": 3404
} | class ____(admin.ModelAdmin):
fieldsets = [
(None, {"fields": ["firstname", "fullname"]}),
("Advanced options", {"fields": ["nationality", "residency"]}),
(
"Advanced options", # Fieldset name intentionally duplicated
{"fields": ["siblings", "children"], "classes": ["collapse"]},
),
]
inlines = [
PhotoTabularInline,
PhotoStackedExtra2Inline,
PhotoStackedExtra3Inline,
PhotoStackedCollapsibleInline,
]
| PhotographerAdmin |
python | coleifer__peewee | peewee.py | {
"start": 151693,
"end": 152019
} | class ____(CursorWrapper):
def initialize(self):
description = self.cursor.description
self.tuple_class = collections.namedtuple('Row', [
t[0][t[0].rfind('.') + 1:].strip('()"`') for t in description])
def process_row(self, row):
return self.tuple_class(*row)
| NamedTupleCursorWrapper |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 9535,
"end": 11350
} | class ____(DatabricksBaseTask[jobs.PythonWheelTask]):
@property
def task_type(self) -> str:
return "python_wheel"
@property
def task_config_metadata(self) -> Mapping[str, Any]:
task_config_metadata = {}
wheel_config = self.task_config["python_wheel_task"]
task_config_metadata["package_name"] = wheel_config["package_name"]
task_config_metadata["entry_point"] = wheel_config["entry_point"]
task_config_metadata["parameters"] = self.task_parameters
return task_config_metadata
@classmethod
def from_job_task_config(
cls, job_task_config: Mapping[str, Any]
) -> "DatabricksPythonWheelTask":
python_wheel_task = job_task_config["python_wheel_task"]
task_config = {"python_wheel_task": python_wheel_task}
# Python wheel tasks use parameters differently
task_parameters = python_wheel_task.get("parameters", [])
return cls(
task_key=job_task_config["task_key"],
task_config=task_config,
task_parameters=task_parameters,
depends_on=parse_depends_on(job_task_config.get("depends_on", [])),
job_name=job_task_config["job_name"],
libraries=job_task_config.get("libraries", []),
)
@property
def needs_cluster(self) -> bool:
return True
@property
def submit_task_key(self) -> str:
return "python_wheel_task"
def to_databricks_sdk_task(self) -> jobs.PythonWheelTask:
wheel_config = self.task_config["python_wheel_task"]
return jobs.PythonWheelTask(
package_name=wheel_config["package_name"],
entry_point=wheel_config["entry_point"],
parameters=check.is_list(self.task_parameters),
)
@record
| DatabricksPythonWheelTask |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/looker.py | {
"start": 7418,
"end": 8900
} | class ____(api_settings.ApiSettings):
"""Custom implementation of Looker SDK's `ApiSettings` class."""
def __init__(
self,
conn: Connection,
) -> None:
self.conn = conn # need to init before `read_config` is called in super
super().__init__()
def read_config(self):
"""
Fetch the connection settings from Airflow's connection object.
Overrides the default logic of getting connection settings.
"""
config = {}
if self.conn.host is None:
raise AirflowException(f"No `host` was supplied in connection: {self.conn.id}.")
if self.conn.port:
config["base_url"] = f"{self.conn.host}:{self.conn.port}" # port is optional
else:
config["base_url"] = self.conn.host
if self.conn.login:
config["client_id"] = self.conn.login
else:
raise AirflowException(f"No `login` was supplied in connection: {self.conn.id}.")
if self.conn.password:
config["client_secret"] = self.conn.password
else:
raise AirflowException(f"No `password` was supplied in connection: {self.conn.id}.")
extras: dict = self.conn.extra_dejson
if "verify_ssl" in extras:
config["verify_ssl"] = extras["verify_ssl"] # optional
if "timeout" in extras:
config["timeout"] = extras["timeout"] # optional
return config
| LookerApiSettings |
python | doocs__leetcode | solution/2100-2199/2125.Number of Laser Beams in a Bank/Solution.py | {
"start": 0,
"end": 238
} | class ____:
def numberOfBeams(self, bank: List[str]) -> int:
ans = pre = 0
for row in bank:
if (cur := row.count("1")) > 0:
ans += pre * cur
pre = cur
return ans
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 105880,
"end": 107855
} | class ____(Response):
"""
Response of projects.get_model_metadata_values endpoint.
:param total: Total number of distinct values
:type total: int
:param values: The list of the unique values
:type values: Sequence[str]
"""
_service = "projects"
_action = "get_model_metadata_values"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"total": {
"description": "Total number of distinct values",
"type": ["integer", "null"],
},
"values": {
"description": "The list of the unique values",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, total: Optional[int] = None, values: Optional[List[str]] = None, **kwargs: Any) -> None:
super(GetModelMetadataValuesResponse, self).__init__(**kwargs)
self.total = total
self.values = values
@schema_property("total")
def total(self) -> Optional[int]:
return self._property_total
@total.setter
def total(self, value: Optional[int]) -> None:
if value is None:
self._property_total = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "total", six.integer_types)
self._property_total = value
@schema_property("values")
def values(self) -> Optional[List[str]]:
return self._property_values
@values.setter
def values(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_values = None
return
self.assert_isinstance(value, "values", (list, tuple))
self.assert_isinstance(value, "values", six.string_types, is_array=True)
self._property_values = value
| GetModelMetadataValuesResponse |
python | tensorflow__tensorflow | tensorflow/python/summary/writer/writer_test.py | {
"start": 1861,
"end": 16410
} | class ____:
def _FileWriter(self, *args, **kwargs):
return writer.FileWriter(*args, **kwargs)
def _TestDir(self, test_name):
test_dir = os.path.join(self.get_temp_dir(), test_name)
return test_dir
def _CleanTestDir(self, test_name):
test_dir = self._TestDir(test_name)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
return test_dir
def _EventsReader(self, test_dir):
event_paths = glob.glob(os.path.join(test_dir, "event*"))
# If the tests runs multiple times in the same directory we can have
# more than one matching event file. We only want to read the last one.
self.assertTrue(event_paths)
return summary_iterator.summary_iterator(event_paths[-1])
def assertRecent(self, t):
# We want to ensure the timestamp is something plausible, and aren't able
# to mock out the actual clock used through many layers of the stack, so
# just assert that it's within the past hour, which should always be true.
self.assertLessEqual(t, time.time())
self.assertLess(abs(t - time.time()), 3600)
def assertEventsWithGraph(self, test_dir, g, has_shapes):
meta_graph_def = meta_graph.create_meta_graph_def(
graph_def=g.as_graph_def(add_shapes=has_shapes))
rr = self._EventsReader(test_dir)
# The first event should list the file_version.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should have the graph.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(0, ev.step)
ev_graph = graph_pb2.GraphDef()
ev_graph.ParseFromString(ev.graph_def)
self.assertProtoEquals(g.as_graph_def(add_shapes=has_shapes), ev_graph)
# The next event should have the metagraph.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(0, ev.step)
ev_meta_graph = meta_graph_pb2.MetaGraphDef()
ev_meta_graph.ParseFromString(ev.meta_graph_def)
self.assertProtoEquals(meta_graph_def, ev_meta_graph)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
@test_util.run_deprecated_v1
def testAddingSummaryGraphAndRunMetadata(self):
test_dir = self._CleanTestDir("basics")
sw = self._FileWriter(test_dir)
sw.add_session_log(event_pb2.SessionLog(status=SessionLog.START), 1)
sw.add_summary(
summary_pb2.Summary(
value=[summary_pb2.Summary.Value(
tag="mee", simple_value=10.0)]),
10)
sw.add_summary(
summary_pb2.Summary(
value=[summary_pb2.Summary.Value(
tag="boo", simple_value=20.0)]),
20)
with ops.Graph().as_default() as g:
constant_op.constant([0], name="zero")
sw.add_graph(g, global_step=30)
run_metadata = config_pb2.RunMetadata()
device_stats = run_metadata.step_stats.dev_stats.add()
device_stats.device = "test"
sw.add_run_metadata(run_metadata, "test run", global_step=40)
sw.close()
rr = self._EventsReader(test_dir)
# The first event should list the file_version.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should be the START message.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(1, ev.step)
self.assertEqual(SessionLog.START, ev.session_log.status)
# The next event should have the value 'mee=10.0'.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(10, ev.step)
self.assertProtoEquals("""
value { tag: 'mee' simple_value: 10.0 }
""", ev.summary)
# The next event should have the value 'boo=20.0'.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(20, ev.step)
self.assertProtoEquals("""
value { tag: 'boo' simple_value: 20.0 }
""", ev.summary)
# The next event should have the graph_def.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(30, ev.step)
ev_graph = graph_pb2.GraphDef()
ev_graph.ParseFromString(ev.graph_def)
self.assertProtoEquals(g.as_graph_def(add_shapes=True), ev_graph)
# The next event should have metadata for the run.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(40, ev.step)
self.assertEqual("test run", ev.tagged_run_metadata.tag)
parsed_run_metadata = config_pb2.RunMetadata()
parsed_run_metadata.ParseFromString(ev.tagged_run_metadata.run_metadata)
self.assertProtoEquals(run_metadata, parsed_run_metadata)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
@test_util.run_deprecated_v1
def testGraphAsNamed(self):
test_dir = self._CleanTestDir("basics_named_graph")
with ops.Graph().as_default() as g:
constant_op.constant([12], name="douze")
sw = self._FileWriter(test_dir, graph=g)
sw.close()
self.assertEventsWithGraph(test_dir, g, True)
@test_util.run_deprecated_v1
def testGraphAsPositional(self):
test_dir = self._CleanTestDir("basics_positional_graph")
with ops.Graph().as_default() as g:
constant_op.constant([12], name="douze")
sw = self._FileWriter(test_dir, g)
sw.close()
self.assertEventsWithGraph(test_dir, g, True)
@test_util.run_deprecated_v1
def testGraphDefAsNamed(self):
test_dir = self._CleanTestDir("basics_named_graph_def")
with ops.Graph().as_default() as g:
constant_op.constant([12], name="douze")
gd = g.as_graph_def()
sw = self._FileWriter(test_dir, graph_def=gd)
sw.close()
self.assertEventsWithGraph(test_dir, g, False)
@test_util.run_deprecated_v1
def testGraphDefAsPositional(self):
test_dir = self._CleanTestDir("basics_positional_graph_def")
with ops.Graph().as_default() as g:
constant_op.constant([12], name="douze")
gd = g.as_graph_def()
sw = self._FileWriter(test_dir, gd)
sw.close()
self.assertEventsWithGraph(test_dir, g, False)
@test_util.run_deprecated_v1
def testGraphAndGraphDef(self):
with self.assertRaises(ValueError):
test_dir = self._CleanTestDir("basics_graph_and_graph_def")
with ops.Graph().as_default() as g:
constant_op.constant([12], name="douze")
gd = g.as_graph_def()
sw = self._FileWriter(test_dir, graph=g, graph_def=gd)
sw.close()
@test_util.run_deprecated_v1
def testNeitherGraphNorGraphDef(self):
with self.assertRaises(TypeError):
test_dir = self._CleanTestDir("basics_string_instead_of_graph")
sw = self._FileWriter(test_dir, "string instead of graph object")
sw.close()
@test_util.run_deprecated_v1
def testCloseAndReopen(self):
test_dir = self._CleanTestDir("close_and_reopen")
sw = self._FileWriter(test_dir)
sw.add_session_log(event_pb2.SessionLog(status=SessionLog.START), 1)
sw.close()
# Sleep at least one second to make sure we get a new event file name.
time.sleep(1.2)
sw.reopen()
sw.add_session_log(event_pb2.SessionLog(status=SessionLog.START), 2)
sw.close()
# We should now have 2 events files.
event_paths = sorted(glob.glob(os.path.join(test_dir, "event*")))
self.assertEqual(2, len(event_paths))
# Check the first file contents.
rr = summary_iterator.summary_iterator(event_paths[0])
# The first event should list the file_version.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should be the START message.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(1, ev.step)
self.assertEqual(SessionLog.START, ev.session_log.status)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
# Check the second file contents.
rr = summary_iterator.summary_iterator(event_paths[1])
# The first event should list the file_version.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should be the START message.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(2, ev.step)
self.assertEqual(SessionLog.START, ev.session_log.status)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
@test_util.run_deprecated_v1
def testNonBlockingClose(self):
test_dir = self._CleanTestDir("non_blocking_close")
sw = self._FileWriter(test_dir)
# Sleep 1.2 seconds to make sure event queue is empty.
time.sleep(1.2)
time_before_close = time.time()
sw.close()
self.assertRecent(time_before_close)
@test_util.run_deprecated_v1
def testUseAfterClose(self):
test_dir = self._CleanTestDir("use_after_close")
sw = self._FileWriter(test_dir)
sw.close()
with warnings.catch_warnings(record=True) as triggered:
warnings.simplefilter("always")
self.assertFalse(triggered)
sw.add_summary(summary_pb2.Summary())
sw.add_session_log(event_pb2.SessionLog())
sw.add_graph(ops.Graph())
self.assertEqual(len(triggered), 3)
for w in triggered:
self.assertEqual(w.category, UserWarning)
@test_util.run_deprecated_v1
def testWithStatement(self):
test_dir = self._CleanTestDir("with_statement")
with self._FileWriter(test_dir) as sw:
sw.add_session_log(event_pb2.SessionLog(status=SessionLog.START), 1)
event_paths = sorted(glob.glob(os.path.join(test_dir, "event*")))
self.assertEqual(1, len(event_paths))
# Checks that values returned from session Run() calls are added correctly to
# summaries. These are numpy types so we need to check they fit in the
# protocol buffers correctly.
@test_util.run_deprecated_v1
def testAddingSummariesFromSessionRunCalls(self):
test_dir = self._CleanTestDir("global_step")
sw = self._FileWriter(test_dir)
with self.cached_session():
i = constant_op.constant(1, dtype=dtypes.int32, shape=[])
l = constant_op.constant(2, dtype=dtypes.int64, shape=[])
# Test the summary can be passed serialized.
summ = summary_pb2.Summary(
value=[summary_pb2.Summary.Value(
tag="i", simple_value=1.0)])
sw.add_summary(summ.SerializeToString(), self.evaluate(i))
sw.add_summary(
summary_pb2.Summary(
value=[summary_pb2.Summary.Value(tag="l", simple_value=2.0)]),
self.evaluate(l))
sw.close()
rr = self._EventsReader(test_dir)
# File_version.
ev = next(rr)
self.assertTrue(ev)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# Summary passed serialized.
ev = next(rr)
self.assertTrue(ev)
self.assertRecent(ev.wall_time)
self.assertEqual(1, ev.step)
self.assertProtoEquals("""
value { tag: 'i' simple_value: 1.0 }
""", ev.summary)
# Summary passed as SummaryObject.
ev = next(rr)
self.assertTrue(ev)
self.assertRecent(ev.wall_time)
self.assertEqual(2, ev.step)
self.assertProtoEquals("""
value { tag: 'l' simple_value: 2.0 }
""", ev.summary)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
@test_util.run_deprecated_v1
def testPluginMetadataStrippedFromSubsequentEvents(self):
test_dir = self._CleanTestDir("basics")
sw = self._FileWriter(test_dir)
sw.add_session_log(event_pb2.SessionLog(status=SessionLog.START), 1)
# We add 2 summaries with the same tags. They both have metadata. The writer
# should strip the metadata from the second one.
value = summary_pb2.Summary.Value(tag="foo", simple_value=10.0)
value.metadata.plugin_data.plugin_name = "bar"
value.metadata.plugin_data.content = compat.as_bytes("... content ...")
sw.add_summary(summary_pb2.Summary(value=[value]), 10)
value = summary_pb2.Summary.Value(tag="foo", simple_value=10.0)
value.metadata.plugin_data.plugin_name = "bar"
value.metadata.plugin_data.content = compat.as_bytes("... content ...")
sw.add_summary(summary_pb2.Summary(value=[value]), 10)
sw.close()
rr = self._EventsReader(test_dir)
# The first event should list the file_version.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should be the START message.
ev = next(rr)
self.assertRecent(ev.wall_time)
self.assertEqual(1, ev.step)
self.assertEqual(SessionLog.START, ev.session_log.status)
# This is the first event with tag foo. It should contain SummaryMetadata.
ev = next(rr)
self.assertProtoEquals("""
value {
tag: "foo"
simple_value: 10.0
metadata {
plugin_data {
plugin_name: "bar"
content: "... content ..."
}
}
}
""", ev.summary)
# This is the second event with tag foo. It should lack SummaryMetadata
# because the file writer should have stripped it.
ev = next(rr)
self.assertProtoEquals("""
value {
tag: "foo"
simple_value: 10.0
}
""", ev.summary)
# We should be done.
self.assertRaises(StopIteration, lambda: next(rr))
@test_util.run_deprecated_v1
def testFileWriterWithSuffix(self):
test_dir = self._CleanTestDir("test_suffix")
sw = self._FileWriter(test_dir, filename_suffix="_test_suffix")
for _ in range(10):
sw.add_summary(
summary_pb2.Summary(value=[
summary_pb2.Summary.Value(tag="float_ten", simple_value=10.0)
]),
10)
sw.close()
sw.reopen()
sw.close()
event_filenames = glob.glob(os.path.join(test_dir, "event*"))
for filename in event_filenames:
self.assertTrue(filename.endswith("_test_suffix"))
def testPluginAssetSerialized(self):
class ExamplePluginAsset(plugin_asset.PluginAsset):
plugin_name = "example"
def assets(self):
return {"foo.txt": "foo!", "bar.txt": "bar!"}
with ops.Graph().as_default() as g:
plugin_asset.get_plugin_asset(ExamplePluginAsset)
logdir = self.get_temp_dir()
fw = self._FileWriter(logdir)
fw.add_graph(g)
plugin_dir = os.path.join(logdir, writer._PLUGINS_DIR, "example")
with gfile.Open(os.path.join(plugin_dir, "foo.txt"), "r") as f:
content = f.read()
self.assertEqual(content, "foo!")
with gfile.Open(os.path.join(plugin_dir, "bar.txt"), "r") as f:
content = f.read()
self.assertEqual(content, "bar!")
| FileWriterTestBase |
python | kamyu104__LeetCode-Solutions | Python/coin-path.py | {
"start": 33,
"end": 801
} | class ____(object):
def cheapestJump(self, A, B):
"""
:type A: List[int]
:type B: int
:rtype: List[int]
"""
result = []
if not A or A[-1] == -1:
return result
n = len(A)
dp, next_pos = [float("inf")] * n, [-1] * n
dp[n-1] = A[n-1]
for i in reversed(xrange(n-1)):
if A[i] == -1:
continue
for j in xrange(i+1, min(i+B+1,n)):
if A[i] + dp[j] < dp[i]:
dp[i] = A[i] + dp[j]
next_pos[i] = j
if dp[0] == float("inf"):
return result
k = 0
while k != -1:
result.append(k+1)
k = next_pos[k]
return result
| Solution |
python | fluentpython__example-code-2e | 01-data-model/vector2d.py | {
"start": 522,
"end": 1010
} | class ____:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
| Vector |
python | kubernetes-client__python | kubernetes/client/models/v2_hpa_scaling_rules.py | {
"start": 383,
"end": 8995
} | 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 = {
'policies': 'list[V2HPAScalingPolicy]',
'select_policy': 'str',
'stabilization_window_seconds': 'int',
'tolerance': 'str'
}
attribute_map = {
'policies': 'policies',
'select_policy': 'selectPolicy',
'stabilization_window_seconds': 'stabilizationWindowSeconds',
'tolerance': 'tolerance'
}
def __init__(self, policies=None, select_policy=None, stabilization_window_seconds=None, tolerance=None, local_vars_configuration=None): # noqa: E501
"""V2HPAScalingRules - 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._policies = None
self._select_policy = None
self._stabilization_window_seconds = None
self._tolerance = None
self.discriminator = None
if policies is not None:
self.policies = policies
if select_policy is not None:
self.select_policy = select_policy
if stabilization_window_seconds is not None:
self.stabilization_window_seconds = stabilization_window_seconds
if tolerance is not None:
self.tolerance = tolerance
@property
def policies(self):
"""Gets the policies of this V2HPAScalingRules. # noqa: E501
policies is a list of potential scaling polices which can be used during scaling. If not set, use the default values: - For scale up: allow doubling the number of pods, or an absolute change of 4 pods in a 15s window. - For scale down: allow all pods to be removed in a 15s window. # noqa: E501
:return: The policies of this V2HPAScalingRules. # noqa: E501
:rtype: list[V2HPAScalingPolicy]
"""
return self._policies
@policies.setter
def policies(self, policies):
"""Sets the policies of this V2HPAScalingRules.
policies is a list of potential scaling polices which can be used during scaling. If not set, use the default values: - For scale up: allow doubling the number of pods, or an absolute change of 4 pods in a 15s window. - For scale down: allow all pods to be removed in a 15s window. # noqa: E501
:param policies: The policies of this V2HPAScalingRules. # noqa: E501
:type: list[V2HPAScalingPolicy]
"""
self._policies = policies
@property
def select_policy(self):
"""Gets the select_policy of this V2HPAScalingRules. # noqa: E501
selectPolicy is used to specify which policy should be used. If not set, the default value Max is used. # noqa: E501
:return: The select_policy of this V2HPAScalingRules. # noqa: E501
:rtype: str
"""
return self._select_policy
@select_policy.setter
def select_policy(self, select_policy):
"""Sets the select_policy of this V2HPAScalingRules.
selectPolicy is used to specify which policy should be used. If not set, the default value Max is used. # noqa: E501
:param select_policy: The select_policy of this V2HPAScalingRules. # noqa: E501
:type: str
"""
self._select_policy = select_policy
@property
def stabilization_window_seconds(self):
"""Gets the stabilization_window_seconds of this V2HPAScalingRules. # noqa: E501
stabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long). # noqa: E501
:return: The stabilization_window_seconds of this V2HPAScalingRules. # noqa: E501
:rtype: int
"""
return self._stabilization_window_seconds
@stabilization_window_seconds.setter
def stabilization_window_seconds(self, stabilization_window_seconds):
"""Sets the stabilization_window_seconds of this V2HPAScalingRules.
stabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long). # noqa: E501
:param stabilization_window_seconds: The stabilization_window_seconds of this V2HPAScalingRules. # noqa: E501
:type: int
"""
self._stabilization_window_seconds = stabilization_window_seconds
@property
def tolerance(self):
"""Gets the tolerance of this V2HPAScalingRules. # noqa: E501
tolerance is the tolerance on the ratio between the current and desired metric value under which no updates are made to the desired number of replicas (e.g. 0.01 for 1%). Must be greater than or equal to zero. If not set, the default cluster-wide tolerance is applied (by default 10%). For example, if autoscaling is configured with a memory consumption target of 100Mi, and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be triggered when the actual consumption falls below 95Mi or exceeds 101Mi. This is an alpha field and requires enabling the HPAConfigurableTolerance feature gate. # noqa: E501
:return: The tolerance of this V2HPAScalingRules. # noqa: E501
:rtype: str
"""
return self._tolerance
@tolerance.setter
def tolerance(self, tolerance):
"""Sets the tolerance of this V2HPAScalingRules.
tolerance is the tolerance on the ratio between the current and desired metric value under which no updates are made to the desired number of replicas (e.g. 0.01 for 1%). Must be greater than or equal to zero. If not set, the default cluster-wide tolerance is applied (by default 10%). For example, if autoscaling is configured with a memory consumption target of 100Mi, and scale-down and scale-up tolerances of 5% and 1% respectively, scaling will be triggered when the actual consumption falls below 95Mi or exceeds 101Mi. This is an alpha field and requires enabling the HPAConfigurableTolerance feature gate. # noqa: E501
:param tolerance: The tolerance of this V2HPAScalingRules. # noqa: E501
:type: str
"""
self._tolerance = tolerance
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, V2HPAScalingRules):
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, V2HPAScalingRules):
return True
return self.to_dict() != other.to_dict()
| V2HPAScalingRules |
python | kamyu104__LeetCode-Solutions | Python/handshakes-that-dont-cross.py | {
"start": 641,
"end": 1021
} | class ____(object):
def numberOfWays(self, num_people):
"""
:type num_people: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(num_people//2+1)
dp[0] = 1
for k in xrange(1, num_people//2+1):
for i in xrange(k):
dp[k] = (dp[k] + dp[i]*dp[k-1-i]) % MOD
return dp[num_people//2]
| Solution2 |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/unconstrainable_conflict/package.py | {
"start": 216,
"end": 730
} | class ____(Package):
"""Package with a conflict whose trigger cannot constrain its constraint."""
homepage = "http://www.realurl.com"
url = "http://www.realurl.com/unconstrainable-conflict-1.0.tar.gz"
version("1.0", sha256="2e34cc4505556d1c1f085758e26f2f8eea0972db9382f051b2dcfb1d7d9e1825")
# Two conflicts so there's always one that is not the current platform
conflicts("target=x86_64", when="platform=darwin")
conflicts("target=aarch64", when="platform=linux")
| UnconstrainableConflict |
python | pandas-dev__pandas | pandas/tests/groupby/test_counting.py | {
"start": 266,
"end": 13495
} | class ____:
def test_cumcount(self):
df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"])
g = df.groupby("A")
sg = g.A
expected = Series([0, 1, 2, 0, 3])
tm.assert_series_equal(expected, g.cumcount())
tm.assert_series_equal(expected, sg.cumcount())
def test_cumcount_empty(self):
ge = DataFrame().groupby(level=0)
se = Series(dtype=object).groupby(level=0)
# edge case, as this is usually considered float
e = Series(dtype="int64")
tm.assert_series_equal(e, ge.cumcount())
tm.assert_series_equal(e, se.cumcount())
def test_cumcount_dupe_index(self):
df = DataFrame(
[["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5
)
g = df.groupby("A")
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
tm.assert_series_equal(expected, g.cumcount())
tm.assert_series_equal(expected, sg.cumcount())
def test_cumcount_mi(self):
mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=mi)
g = df.groupby("A")
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=mi)
tm.assert_series_equal(expected, g.cumcount())
tm.assert_series_equal(expected, sg.cumcount())
def test_cumcount_groupby_not_col(self):
df = DataFrame(
[["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5
)
g = df.groupby([0, 0, 0, 1, 0])
sg = g.A
expected = Series([0, 1, 2, 0, 3], index=[0] * 5)
tm.assert_series_equal(expected, g.cumcount())
tm.assert_series_equal(expected, sg.cumcount())
def test_ngroup(self):
df = DataFrame({"A": list("aaaba")})
g = df.groupby("A")
sg = g.A
expected = Series([0, 0, 0, 1, 0])
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_distinct(self):
df = DataFrame({"A": list("abcde")})
g = df.groupby("A")
sg = g.A
expected = Series(range(5), dtype="int64")
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_one_group(self):
df = DataFrame({"A": [0] * 5})
g = df.groupby("A")
sg = g.A
expected = Series([0] * 5)
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_empty(self):
ge = DataFrame().groupby(level=0)
se = Series(dtype=object).groupby(level=0)
# edge case, as this is usually considered float
e = Series(dtype="int64")
tm.assert_series_equal(e, ge.ngroup())
tm.assert_series_equal(e, se.ngroup())
def test_ngroup_series_matches_frame(self):
df = DataFrame({"A": list("aaaba")})
s = Series(list("aaaba"))
tm.assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup())
def test_ngroup_dupe_index(self):
df = DataFrame({"A": list("aaaba")}, index=[0] * 5)
g = df.groupby("A")
sg = g.A
expected = Series([0, 0, 0, 1, 0], index=[0] * 5)
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_mi(self):
mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]])
df = DataFrame({"A": list("aaaba")}, index=mi)
g = df.groupby("A")
sg = g.A
expected = Series([0, 0, 0, 1, 0], index=mi)
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_groupby_not_col(self):
df = DataFrame({"A": list("aaaba")}, index=[0] * 5)
g = df.groupby([0, 0, 0, 1, 0])
sg = g.A
expected = Series([0, 0, 0, 1, 0], index=[0] * 5)
tm.assert_series_equal(expected, g.ngroup())
tm.assert_series_equal(expected, sg.ngroup())
def test_ngroup_descending(self):
df = DataFrame(["a", "a", "b", "a", "b"], columns=["A"])
g = df.groupby(["A"])
ascending = Series([0, 0, 1, 0, 1])
descending = Series([1, 1, 0, 1, 0])
tm.assert_series_equal(descending, (g.ngroups - 1) - ascending)
tm.assert_series_equal(ascending, g.ngroup(ascending=True))
tm.assert_series_equal(descending, g.ngroup(ascending=False))
def test_ngroup_matches_cumcount(self):
# verify one manually-worked out case works
df = DataFrame(
[["a", "x"], ["a", "y"], ["b", "x"], ["a", "x"], ["b", "y"]],
columns=["A", "X"],
)
g = df.groupby(["A", "X"])
g_ngroup = g.ngroup()
g_cumcount = g.cumcount()
expected_ngroup = Series([0, 1, 2, 0, 3])
expected_cumcount = Series([0, 0, 0, 1, 0])
tm.assert_series_equal(g_ngroup, expected_ngroup)
tm.assert_series_equal(g_cumcount, expected_cumcount)
def test_ngroup_cumcount_pair(self):
# brute force comparison for all small series
for p in product(range(3), repeat=4):
df = DataFrame({"a": p})
g = df.groupby(["a"])
order = sorted(set(p))
ngroupd = [order.index(val) for val in p]
cumcounted = [p[:i].count(val) for i, val in enumerate(p)]
tm.assert_series_equal(g.ngroup(), Series(ngroupd))
tm.assert_series_equal(g.cumcount(), Series(cumcounted))
def test_ngroup_respects_groupby_order(self, sort):
df = DataFrame({"a": np.random.default_rng(2).choice(list("abcdef"), 100)})
g = df.groupby("a", sort=sort)
df["group_id"] = -1
df["group_index"] = -1
for i, (_, group) in enumerate(g):
df.loc[group.index, "group_id"] = i
for j, ind in enumerate(group.index):
df.loc[ind, "group_index"] = j
tm.assert_series_equal(Series(df["group_id"].values), g.ngroup())
tm.assert_series_equal(Series(df["group_index"].values), g.cumcount())
@pytest.mark.parametrize(
"datetimelike",
[
[Timestamp(f"2016-05-{i:02d} 20:09:25+00:00") for i in range(1, 4)],
[Timestamp(f"2016-05-{i:02d} 20:09:25") for i in range(1, 4)],
[Timestamp(f"2016-05-{i:02d} 20:09:25", tz="UTC") for i in range(1, 4)],
[Timedelta(x, unit="h") for x in range(1, 4)],
[Period(freq="2W", year=2017, month=x) for x in range(1, 4)],
],
)
def test_count_with_datetimelike(self, datetimelike):
# test for #13393, where DataframeGroupBy.count() fails
# when counting a datetimelike column.
df = DataFrame({"x": ["a", "a", "b"], "y": datetimelike})
res = df.groupby("x").count()
expected = DataFrame({"y": [2, 1]}, index=["a", "b"])
expected.index.name = "x"
tm.assert_frame_equal(expected, res)
def test_count_with_only_nans_in_first_group(self):
# GH21956
df = DataFrame({"A": [np.nan, np.nan], "B": ["a", "b"], "C": [1, 2]})
result = df.groupby(["A", "B"]).C.count()
mi = MultiIndex(levels=[[], ["a", "b"]], codes=[[], []], names=["A", "B"])
expected = Series([], index=mi, dtype=np.int64, name="C")
tm.assert_series_equal(result, expected, check_index_type=False)
def test_count_groupby_column_with_nan_in_groupby_column(self):
# https://github.com/pandas-dev/pandas/issues/32841
df = DataFrame({"A": [1, 1, 1, 1, 1], "B": [5, 4, np.nan, 3, 0]})
res = df.groupby(["B"]).count()
expected = DataFrame(
index=Index([0.0, 3.0, 4.0, 5.0], name="B"), data={"A": [1, 1, 1, 1]}
)
tm.assert_frame_equal(expected, res)
def test_groupby_count_dateparseerror(self):
dr = date_range(start="1/1/2012", freq="5min", periods=10)
# BAD Example, datetimes first
ser = Series(np.arange(10), index=[dr, np.arange(10)])
grouped = ser.groupby(lambda x: x[1] % 2 == 0)
result = grouped.count()
ser = Series(np.arange(10), index=[np.arange(10), dr])
grouped = ser.groupby(lambda x: x[0] % 2 == 0)
expected = grouped.count()
tm.assert_series_equal(result, expected)
def test_groupby_timedelta_cython_count():
df = DataFrame(
{"g": list("ab" * 2), "delta": np.arange(4).astype("timedelta64[ns]")}
)
expected = Series([2, 2], index=Index(["a", "b"], name="g"), name="delta")
result = df.groupby("g").delta.count()
tm.assert_series_equal(expected, result)
def test_count():
n = 1 << 15
dr = date_range("2015-08-30", periods=n // 10, freq="min")
df = DataFrame(
{
"1st": np.random.default_rng(2).choice(list(ascii_lowercase), n),
"2nd": np.random.default_rng(2).integers(0, 5, n),
"3rd": np.random.default_rng(2).standard_normal(n).round(3),
"4th": np.random.default_rng(2).integers(-10, 10, n),
"5th": np.random.default_rng(2).choice(dr, n),
"6th": np.random.default_rng(2).standard_normal(n).round(3),
"7th": np.random.default_rng(2).standard_normal(n).round(3),
"8th": np.random.default_rng(2).choice(dr, n)
- np.random.default_rng(2).choice(dr, 1),
"9th": np.random.default_rng(2).choice(list(ascii_lowercase), n),
}
)
for col in df.columns.drop(["1st", "2nd", "4th"]):
df.loc[np.random.default_rng(2).choice(n, n // 10), col] = np.nan
df["9th"] = df["9th"].astype("category")
for key in ["1st", "2nd", ["1st", "2nd"]]:
left = df.groupby(key).count()
right = df.groupby(key).apply(DataFrame.count)
tm.assert_frame_equal(left, right)
def test_count_non_nulls():
# GH#5610
# count counts non-nulls
df = DataFrame(
[[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, np.nan]],
columns=["A", "B", "C"],
)
count_as = df.groupby("A").count()
count_not_as = df.groupby("A", as_index=False).count()
expected = DataFrame([[1, 2], [0, 0]], columns=["B", "C"], index=[1, 3])
expected.index.name = "A"
tm.assert_frame_equal(count_not_as, expected.reset_index())
tm.assert_frame_equal(count_as, expected)
count_B = df.groupby("A")["B"].count()
tm.assert_series_equal(count_B, expected["B"])
def test_count_object():
df = DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3})
result = df.groupby("c").a.count()
expected = Series([3, 3], index=Index([2, 3], name="c"), name="a")
tm.assert_series_equal(result, expected)
def test_count_object_nan():
df = DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3})
result = df.groupby("c").a.count()
expected = Series([1, 3], index=Index([2, 3], name="c"), name="a")
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("typ", ["object", "float32"])
def test_count_cross_type(typ):
# GH8169
# Set float64 dtype to avoid upcast when setting nan below
vals = np.hstack(
(
np.random.default_rng(2).integers(0, 5, (10, 2)),
np.random.default_rng(2).integers(0, 2, (10, 2)),
)
).astype("float64")
df = DataFrame(vals, columns=["a", "b", "c", "d"])
df[df == 2] = np.nan
expected = df.groupby(["c", "d"]).count()
df["a"] = df["a"].astype(typ)
df["b"] = df["b"].astype(typ)
result = df.groupby(["c", "d"]).count()
tm.assert_frame_equal(result, expected)
def test_lower_int_prec_count():
df = DataFrame(
{
"a": np.array([0, 1, 2, 100], np.int8),
"b": np.array([1, 2, 3, 6], np.uint32),
"c": np.array([4, 5, 6, 8], np.int16),
"grp": list("ab" * 2),
}
)
result = df.groupby("grp").count()
expected = DataFrame(
{"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=Index(list("ab"), name="grp")
)
tm.assert_frame_equal(result, expected)
def test_count_uses_size_on_exception():
class RaisingObjectException(Exception):
pass
class RaisingObject:
def __init__(self, msg="I will raise inside Cython") -> None:
super().__init__()
self.msg = msg
def __eq__(self, other):
# gets called in Cython to check that raising calls the method
raise RaisingObjectException(self.msg)
df = DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)})
result = df.groupby("grp").count()
expected = DataFrame({"a": [2, 2]}, index=Index(list("ab"), name="grp"))
tm.assert_frame_equal(result, expected)
def test_count_arrow_string_array(any_string_dtype):
# GH#54751
pytest.importorskip("pyarrow")
df = DataFrame(
{"a": [1, 2, 3], "b": Series(["a", "b", "a"], dtype=any_string_dtype)}
)
result = df.groupby("a").count()
expected = DataFrame({"b": 1}, index=Index([1, 2, 3], name="a"))
tm.assert_frame_equal(result, expected)
| TestCounting |
python | astropy__astropy | astropy/modeling/core.py | {
"start": 2308,
"end": 19271
} | class ____(abc.ABCMeta):
"""
Metaclass for Model.
Currently just handles auto-generating the param_names list based on
Parameter descriptors declared at the class-level of Model subclasses.
"""
_is_dynamic = False
"""
This flag signifies whether this class was created in the "normal" way,
with a class statement in the body of a module, as opposed to a call to
`type` or some other metaclass constructor, such that the resulting class
does not belong to a specific module. This is important for pickling of
dynamic classes.
This flag is always forced to False for new classes, so code that creates
dynamic classes should manually set it to True on those classes when
creating them.
"""
# Default empty dict for _parameters_, which will be empty on model
# classes that don't have any Parameters
def __new__(cls, name, bases, members, **kwds):
# See the docstring for _is_dynamic above
if "_is_dynamic" not in members:
members["_is_dynamic"] = cls._is_dynamic
opermethods = [
("__add__", _model_oper("+")),
("__sub__", _model_oper("-")),
("__mul__", _model_oper("*")),
("__truediv__", _model_oper("/")),
("__pow__", _model_oper("**")),
("__or__", _model_oper("|")),
("__and__", _model_oper("&")),
("_fix_inputs", _model_oper("fix_inputs")),
]
members["_parameters_"] = {
k: v for k, v in members.items() if isinstance(v, Parameter)
}
for opermethod, opercall in opermethods:
members[opermethod] = opercall
self = super().__new__(cls, name, bases, members, **kwds)
param_names = list(members["_parameters_"])
# Need to walk each base MRO to collect all parameter names
for base in bases:
for tbase in base.__mro__:
if issubclass(tbase, Model):
# Preserve order of definitions
param_names = list(tbase._parameters_) + param_names
# Remove duplicates (arising from redefinition in subclass).
param_names = list(dict.fromkeys(param_names))
if self._parameters_:
if hasattr(self, "_param_names"):
# Slight kludge to support compound models, where
# param_names is a property; could be improved with a
# little refactoring but fine for now
self._param_names = tuple(param_names)
else:
self.param_names = tuple(param_names)
return self
def __init__(cls, name, bases, members, **kwds):
super().__init__(name, bases, members, **kwds)
cls._create_inverse_property(members)
cls._create_bounding_box_property(members)
pdict = {}
for base in bases:
for tbase in base.__mro__:
if not issubclass(tbase, Model):
continue
pdict |= cls._parameters_
cls._handle_special_methods(members, pdict)
def __repr__(cls):
"""
Custom repr for Model subclasses.
"""
return cls._format_cls_repr()
def _repr_pretty_(cls, p, cycle):
"""
Repr for IPython's pretty printer.
By default IPython "pretty prints" classes, so we need to implement
this so that IPython displays the custom repr for Models.
"""
p.text(repr(cls))
def __reduce__(cls):
if not cls._is_dynamic:
# Just return a string specifying where the class can be imported
# from
return cls.__name__
members = dict(cls.__dict__)
# Delete any ABC-related attributes--these will be restored when
# the class is reconstructed:
for key in list(members):
if key.startswith("_abc_"):
del members[key]
# Delete custom __init__ and __call__ if they exist:
for key in ("__init__", "__call__"):
members.pop(key, None)
return (type(cls), (cls.__name__, cls.__bases__, members))
@property
def name(cls):
"""
The name of this model class--equivalent to ``cls.__name__``.
This attribute is provided for symmetry with the
`~astropy.modeling.Model.name` attribute of model instances.
"""
return cls.__name__
@property
def _is_concrete(cls):
"""
A class-level property that determines whether the class is a concrete
implementation of a Model--i.e. it is not some abstract base class or
internal implementation detail (i.e. begins with '_').
"""
return not (cls.__name__.startswith("_") or inspect.isabstract(cls))
def rename(cls, name=None, inputs=None, outputs=None):
"""
Creates a copy of this model class with a new name, inputs or outputs.
The new class is technically a subclass of the original class, so that
instance and type checks will still work. For example::
>>> from astropy.modeling.models import Rotation2D
>>> SkyRotation = Rotation2D.rename('SkyRotation')
>>> SkyRotation
<class 'astropy.modeling.core.SkyRotation'>
Name: SkyRotation (Rotation2D)
N_inputs: 2
N_outputs: 2
Fittable parameters: ('angle',)
>>> issubclass(SkyRotation, Rotation2D)
True
>>> r = SkyRotation(90)
>>> isinstance(r, Rotation2D)
True
"""
mod = find_current_module(2)
if mod:
modname = mod.__name__
else:
modname = "__main__"
if name is None:
name = cls.name
if inputs is None:
inputs = cls.inputs
else:
if not isinstance(inputs, tuple):
raise TypeError("Expected 'inputs' to be a tuple of strings.")
elif len(inputs) != len(cls.inputs):
raise ValueError(f"{cls.name} expects {len(cls.inputs)} inputs")
if outputs is None:
outputs = cls.outputs
else:
if not isinstance(outputs, tuple):
raise TypeError("Expected 'outputs' to be a tuple of strings.")
elif len(outputs) != len(cls.outputs):
raise ValueError(f"{cls.name} expects {len(cls.outputs)} outputs")
new_cls = type(name, (cls,), {"inputs": inputs, "outputs": outputs})
new_cls.__module__ = modname
new_cls.__qualname__ = name
return new_cls
def _create_inverse_property(cls, members):
inverse = members.get("inverse")
if inverse is None or cls.__bases__[0] is object:
# The latter clause is the prevent the below code from running on
# the Model base class, which implements the default getter and
# setter for .inverse
return
if isinstance(inverse, property):
# We allow the @property decorator to be omitted entirely from
# the class definition, though its use should be encouraged for
# clarity
inverse = inverse.fget
# Store the inverse getter internally, then delete the given .inverse
# attribute so that cls.inverse resolves to Model.inverse instead
cls._inverse = inverse
del cls.inverse
def _create_bounding_box_property(cls, members):
"""
Takes any bounding_box defined on a concrete Model subclass (either
as a fixed tuple or a property or method) and wraps it in the generic
getter/setter interface for the bounding_box attribute.
"""
# TODO: Much of this is verbatim from _create_inverse_property--I feel
# like there could be a way to generify properties that work this way,
# but for the time being that would probably only confuse things more.
bounding_box = members.get("bounding_box")
if bounding_box is None or cls.__bases__[0] is object:
return
if isinstance(bounding_box, property):
bounding_box = bounding_box.fget
if not callable(bounding_box):
# See if it's a hard-coded bounding_box (as a sequence) and
# normalize it
try:
bounding_box = ModelBoundingBox.validate(
cls, bounding_box, _preserve_ignore=True
)
except ValueError as exc:
raise ModelDefinitionError(exc.args[0])
else:
sig = signature(bounding_box)
# May be a method that only takes 'self' as an argument (like a
# property, but the @property decorator was forgotten)
#
# However, if the method takes additional arguments then this is a
# parameterized bounding box and should be callable
if len(sig.parameters) > 1:
bounding_box = cls._create_bounding_box_subclass(bounding_box, sig)
# See the Model.bounding_box getter definition for how this attribute
# is used
cls._bounding_box = bounding_box
del cls.bounding_box
def _create_bounding_box_subclass(cls, func, sig):
"""
For Models that take optional arguments for defining their bounding
box, we create a subclass of ModelBoundingBox with a ``__call__`` method
that supports those additional arguments.
Takes the function's Signature as an argument since that is already
computed in _create_bounding_box_property, so no need to duplicate that
effort.
"""
# TODO: Might be convenient if calling the bounding box also
# automatically sets the _user_bounding_box. So that
#
# >>> model.bounding_box(arg=1)
#
# in addition to returning the computed bbox, also sets it, so that
# it's a shortcut for
#
# >>> model.bounding_box = model.bounding_box(arg=1)
#
# Not sure if that would be non-obvious / confusing though...
def __call__(self, **kwargs):
return func(self._model, **kwargs)
kwargs = []
for idx, param in enumerate(sig.parameters.values()):
if idx == 0:
# Presumed to be a 'self' argument
continue
if param.default is param.empty:
raise ModelDefinitionError(
f"The bounding_box method for {cls.name} is not correctly "
"defined: If defined as a method all arguments to that "
"method (besides self) must be keyword arguments with "
"default values that can be used to compute a default "
"bounding box."
)
kwargs.append((param.name, param.default))
__call__.__signature__ = sig
return type(
f"{cls.name}ModelBoundingBox", (ModelBoundingBox,), {"__call__": __call__}
)
def _handle_special_methods(cls, members, pdict):
# Handle init creation from inputs
def update_wrapper(wrapper, cls):
# Set up the new __call__'s metadata attributes as though it were
# manually defined in the class definition
# A bit like functools.update_wrapper but uses the class instead of
# the wrapped function
wrapper.__module__ = cls.__module__
wrapper.__doc__ = getattr(cls, wrapper.__name__).__doc__
if hasattr(cls, "__qualname__"):
wrapper.__qualname__ = f"{cls.__qualname__}.{wrapper.__name__}"
if (
"__call__" not in members
and "n_inputs" in members
and isinstance(members["n_inputs"], int)
and members["n_inputs"] > 0
):
# Don't create a custom __call__ for classes that already have one
# explicitly defined (this includes the Model base class, and any
# other classes that manually override __call__
def __call__(self, *inputs, **kwargs):
"""Evaluate this model on the supplied inputs."""
return super(cls, self).__call__(*inputs, **kwargs)
# When called, models can take two optional keyword arguments:
#
# * model_set_axis, which indicates (for multi-dimensional input)
# which axis is used to indicate different models
#
# * equivalencies, a dictionary of equivalencies to be applied to
# the input values, where each key should correspond to one of
# the inputs.
#
# The following code creates the __call__ function with these
# two keyword arguments.
args = ("self",)
kwargs = {
"model_set_axis": None,
"with_bounding_box": False,
"fill_value": np.nan,
"equivalencies": None,
"inputs_map": None,
}
new_call = make_function_with_signature(
__call__, args, kwargs, varargs="inputs", varkwargs="new_inputs"
)
# The following makes it look like __call__
# was defined in the class
update_wrapper(new_call, cls)
cls.__call__ = new_call
if (
"__init__" not in members
and not inspect.isabstract(cls)
and cls._parameters_
):
# Build list of all parameters including inherited ones
# If *all* the parameters have default values we can make them
# keyword arguments; otherwise they must all be positional
# arguments
if all(p.default is not None for p in pdict.values()):
args = ("self",)
kwargs = []
for param_name, param_val in pdict.items():
default = param_val.default
unit = param_val.unit
# If the unit was specified in the parameter but the
# default is not a Quantity, attach the unit to the
# default.
if unit is not None:
default = Quantity(
default, unit, copy=COPY_IF_NEEDED, subok=True
)
kwargs.append((param_name, default))
else:
args = ("self",) + tuple(pdict.keys())
kwargs = {}
def __init__(self, *params, **kwargs):
return super(cls, self).__init__(*params, **kwargs)
new_init = make_function_with_signature(
__init__, args, kwargs, varkwargs="kwargs"
)
update_wrapper(new_init, cls)
cls.__init__ = new_init
# *** Arithmetic operators for creating compound models ***
__add__ = _model_oper("+")
__sub__ = _model_oper("-")
__mul__ = _model_oper("*")
__truediv__ = _model_oper("/")
__pow__ = _model_oper("**")
__or__ = _model_oper("|")
__and__ = _model_oper("&")
_fix_inputs = _model_oper("fix_inputs")
# *** Other utilities ***
def _format_cls_repr(cls, keywords=[]):
"""
Internal implementation of ``__repr__``.
This is separated out for ease of use by subclasses that wish to
override the default ``__repr__`` while keeping the same basic
formatting.
"""
# For the sake of familiarity start the output with the standard class
# __repr__
parts = [super().__repr__()]
if not cls._is_concrete:
return parts[0]
def format_inheritance(cls):
bases = []
for base in cls.mro()[1:]:
if not issubclass(base, Model):
continue
elif inspect.isabstract(base) or base.__name__.startswith("_"):
break
bases.append(base.name)
if bases:
return f"{cls.name} ({' -> '.join(bases)})"
return cls.name
try:
default_keywords = [
("Name", format_inheritance(cls)),
("N_inputs", cls.n_inputs),
("N_outputs", cls.n_outputs),
]
if cls.param_names:
default_keywords.append(("Fittable parameters", cls.param_names))
for keyword, value in default_keywords + keywords:
if value is not None:
parts.append(f"{keyword}: {value}")
return "\n".join(parts)
except Exception:
# If any of the above formatting fails fall back on the basic repr
# (this is particularly useful in debugging)
return parts[0]
| _ModelMeta |
python | numba__numba | numba/core/ir.py | {
"start": 28746,
"end": 29458
} | class ____(Stmt):
"""Enter a "with" context
"""
def __init__(self, contextmanager, begin, end, loc):
"""
Parameters
----------
contextmanager : IR value
begin, end : int
The beginning and the ending offset of the with-body.
loc : ir.Loc instance
Source location
"""
assert isinstance(contextmanager, Var)
assert isinstance(loc, Loc)
self.contextmanager = contextmanager
self.begin = begin
self.end = end
self.loc = loc
def __str__(self):
return 'enter_with {}'.format(self.contextmanager)
def list_vars(self):
return [self.contextmanager]
| EnterWith |
python | django__django | tests/auth_tests/test_validators.py | {
"start": 11907,
"end": 14172
} | class ____(SimpleTestCase):
def test_validate(self):
expected_error = "This password is too common."
self.assertIsNone(CommonPasswordValidator().validate("a-safe-password"))
with self.assertRaises(ValidationError) as cm:
CommonPasswordValidator().validate("godzilla")
self.assertEqual(cm.exception.messages, [expected_error])
def test_common_hexed_codes(self):
expected_error = "This password is too common."
common_hexed_passwords = ["asdfjkl:", "ठ:"]
for password in common_hexed_passwords:
with self.subTest(password=password):
with self.assertRaises(ValidationError) as cm:
CommonPasswordValidator().validate(password)
self.assertEqual(cm.exception.messages, [expected_error])
def test_validate_custom_list(self):
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "common-passwords-custom.txt"
)
validator = CommonPasswordValidator(password_list_path=path)
expected_error = "This password is too common."
self.assertIsNone(validator.validate("a-safe-password"))
with self.assertRaises(ValidationError) as cm:
validator.validate("from-my-custom-list")
self.assertEqual(cm.exception.messages, [expected_error])
self.assertEqual(cm.exception.error_list[0].code, "password_too_common")
def test_validate_django_supplied_file(self):
validator = CommonPasswordValidator()
for password in validator.passwords:
self.assertEqual(password, password.lower())
def test_help_text(self):
self.assertEqual(
CommonPasswordValidator().get_help_text(),
"Your password can’t be a commonly used password.",
)
def test_custom_error(self):
class CustomCommonPasswordValidator(CommonPasswordValidator):
def get_error_message(self):
return "This password has been used too much."
expected_error = "This password has been used too much."
with self.assertRaisesMessage(ValidationError, expected_error):
CustomCommonPasswordValidator().validate("godzilla")
| CommonPasswordValidatorTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/untappd/views.py | {
"start": 222,
"end": 1111
} | class ____(OAuth2Adapter):
client_class = UntappdOAuth2Client
provider_id = "untappd"
access_token_url = "https://untappd.com/oauth/authorize/" # nosec
access_token_method = "GET" # nosec
authorize_url = "https://untappd.com/oauth/authenticate/"
user_info_url = "https://api.untappd.com/v4/user/info/"
def complete_login(self, request, app, token, **kwargs):
resp = (
get_adapter()
.get_requests_session()
.get(self.user_info_url, params={"access_token": token.token})
)
extra_data = resp.json()
# TODO: get and store the email from the user info json
return self.get_provider().sociallogin_from_response(request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(UntappdOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(UntappdOAuth2Adapter)
| UntappdOAuth2Adapter |
python | ray-project__ray | doc/source/serve/doc_code/custom_request_router.py | {
"start": 1199,
"end": 3921
} | class ____(
FIFOMixin, MultiplexMixin, LocalityMixin, RequestRouter
):
async def choose_replicas(
self,
candidate_replicas: List[RunningReplica],
pending_request: Optional[PendingRequest] = None,
) -> List[List[RunningReplica]]:
"""
This method chooses the best replica for the request based on
multiplexed, locality, and custom throughput stats. The algorithm
works as follows:
1. Populate top_ranked_replicas based on available replicas based on
multiplex_id
2. Populate and override top_ranked_replicas info based on locality
information of replicas (we want to prefer replicas that are in the
same vicinity to this deployment)
3. Select the replica with minimum throughput.
"""
# Dictionary to hold the top-ranked replicas
top_ranked_replicas: Dict[ReplicaID, RunningReplica] = {}
# Take the best set of replicas for the multiplexed model
if (
pending_request is not None
and pending_request.metadata.multiplexed_model_id
):
ranked_replicas_multiplex: List[RunningReplica] = (
self.rank_replicas_via_multiplex(
replicas=candidate_replicas,
multiplexed_model_id=pending_request.metadata.multiplexed_model_id,
)
)[0]
# Filter out replicas that are not available (queue length exceed max ongoing request)
ranked_replicas_multiplex = self.select_available_replicas(
candidates=ranked_replicas_multiplex
)
for replica in ranked_replicas_multiplex:
top_ranked_replicas[replica.replica_id] = replica
# Take the best set of replicas in terms of locality
ranked_replicas_locality: List[
RunningReplica
] = self.rank_replicas_via_locality(replicas=candidate_replicas)[0]
# Filter out replicas that are not available (queue length exceed max ongoing request)
ranked_replicas_locality = self.select_available_replicas(
candidates=ranked_replicas_locality
)
for replica in ranked_replicas_locality:
top_ranked_replicas[replica.replica_id] = replica
print("ThroughputAwareRequestRouter routing request")
# Take the replica with minimum throughput.
min_throughput_replicas = min(
[replica for replica in top_ranked_replicas.values()],
key=lambda r: r.routing_stats.get("throughput", 0),
)
return [[min_throughput_replicas]]
# __end_define_throughput_aware_request_router__
| ThroughputAwareRequestRouter |
python | GoogleCloudPlatform__python-docs-samples | monitoring/snippets/v3/alerts-client/snippets_test.py | {
"start": 1513,
"end": 8459
} | class ____:
"""A test fixture that creates an alert POlicy and a notification CHANnel,
hence the name, pochan.
"""
def __init__(self):
self.project_id = snippets.project_id()
self.project_name = snippets.project_name()
self.alert_policy_client = monitoring_v3.AlertPolicyServiceClient()
self.notification_channel_client = (
monitoring_v3.NotificationChannelServiceClient()
)
# delete all existing policies older than 1 hour prior to testing
for policy in self.alert_policy_client.list_alert_policies(
name=self.project_name
):
seconds_since_creation = datetime.timestamp(
datetime.utcnow()
) - datetime.timestamp(policy.creation_record.mutate_time)
if seconds_since_creation > 3600:
try:
self.alert_policy_client.delete_alert_policy(name=policy.name)
except NotFound:
print("Ignored NotFound when deleting a policy.")
def __enter__(self):
@retry(
wait_exponential_multiplier=1000,
wait_exponential_max=10000,
stop_max_attempt_number=10,
retry_on_exception=retry_on_exceptions,
)
def setup():
# Create a policy.
json = open("test_alert_policy.json").read()
policy = monitoring_v3.AlertPolicy.from_json(json)
policy.display_name = "snippets-test-" + random_name(10)
self.alert_policy = self.alert_policy_client.create_alert_policy(
name=self.project_name, alert_policy=policy
)
# Create a notification channel.
json = open("test_notification_channel.json").read()
notification_channel = monitoring_v3.NotificationChannel.from_json(json)
notification_channel.display_name = "snippets-test-" + random_name(10)
self.notification_channel = (
self.notification_channel_client.create_notification_channel(
name=self.project_name, notification_channel=notification_channel
)
)
setup()
return self
def __exit__(self, type, value, traceback):
# Delete the policy and channel we created.
@retry(
wait_exponential_multiplier=1000,
wait_exponential_max=10000,
stop_max_attempt_number=10,
retry_on_exception=retry_on_exceptions,
)
def teardown():
try:
self.alert_policy_client.delete_alert_policy(
name=self.alert_policy.name
)
except NotFound:
print("Ignored NotFound when deleting a policy.")
try:
if self.notification_channel.name:
self.notification_channel_client.delete_notification_channel(
self.notification_channel.name
)
except NotFound:
print("Ignored NotFound when deleting a channel.")
teardown()
@pytest.fixture(scope="session")
def pochan():
with PochanFixture() as pochan:
yield pochan
def test_list_alert_policies(capsys, pochan):
# Query snippets.list_alert_policies() for up to 50 seconds
# to allow the newly created policy to appear in the list.
retry = 5
while retry:
snippets.list_alert_policies(pochan.project_name)
out, _ = capsys.readouterr()
if pochan.alert_policy.display_name in out:
break
retry = retry - 1
time.sleep(10)
assert retry > 0
@pytest.mark.flaky(rerun_filter=delay_on_aborted, max_runs=5)
def test_enable_alert_policies(capsys, pochan):
# These sleep calls are for mitigating the following error:
# "409 Too many concurrent edits to the project configuration.
# Please try again."
# Having multiple projects will void these `sleep()` calls.
# See also #3310
time.sleep(2)
snippets.enable_alert_policies(
pochan.project_name, True, "name='{}'".format(pochan.alert_policy.name)
)
out, _ = capsys.readouterr()
assert (
"Enabled {0}".format(pochan.project_name) in out
or "{} is already enabled".format(pochan.alert_policy.name) in out
)
time.sleep(2)
snippets.enable_alert_policies(
pochan.project_name, False, "name='{}'".format(pochan.alert_policy.name)
)
out, _ = capsys.readouterr()
assert (
"Disabled {}".format(pochan.project_name) in out
or "{} is already disabled".format(pochan.alert_policy.name) in out
)
@pytest.mark.flaky(rerun_filter=delay_on_aborted, max_runs=5)
def test_replace_channels(capsys, pochan):
alert_policy_id = pochan.alert_policy.name.split("/")[-1]
notification_channel_id = pochan.notification_channel.name.split("/")[-1]
# This sleep call is for mitigating the following error:
# "409 Too many concurrent edits to the project configuration.
# Please try again."
# Having multiple projects will void this `sleep()` call.
# See also #3310
time.sleep(2)
snippets.replace_notification_channels(
pochan.project_name, alert_policy_id, [notification_channel_id]
)
out, _ = capsys.readouterr()
assert "Updated {0}".format(pochan.alert_policy.name) in out
@pytest.mark.flaky(rerun_filter=delay_on_aborted, max_runs=5)
@pytest.mark.skip(reason="Needs fixing by CODEOWNER - issue #8975")
def test_backup_and_restore(capsys, pochan):
# These sleep calls are for mitigating the following error:
# "409 Too many concurrent edits to the project configuration.
# Please try again."
# Having multiple projects will void this `sleep()` call.
# See also #3310
time.sleep(2)
snippets.backup(pochan.project_name, "backup.json")
out, _ = capsys.readouterr()
time.sleep(2)
snippets.restore(pochan.project_name, "backup.json")
out, _ = capsys.readouterr()
assert "Updated {0}".format(pochan.alert_policy.name) in out
assert (
"Updating channel {0}".format(pochan.notification_channel.display_name) in out
)
@pytest.mark.flaky(rerun_filter=delay_on_aborted, max_runs=5)
def test_delete_channels(capsys, pochan):
notification_channel_id = pochan.notification_channel.name.split("/")[-1]
# This sleep call is for mitigating the following error:
# "409 Too many concurrent edits to the project configuration.
# Please try again."
# Having multiple projects will void these `sleep()` calls.
# See also #3310
time.sleep(2)
snippets.delete_notification_channels(
pochan.project_name, [notification_channel_id], force=True
)
out, _ = capsys.readouterr()
assert "{0} deleted".format(notification_channel_id) in out
pochan.notification_channel.name = "" # So teardown is not tried
| PochanFixture |
python | huggingface__transformers | tests/models/blenderbot_small/test_modeling_blenderbot_small.py | {
"start": 20483,
"end": 21691
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (BlenderbotSmallDecoder, BlenderbotSmallForCausalLM) if is_torch_available() else ()
is_encoder_decoder = False
def setUp(
self,
):
self.model_tester = BlenderbotSmallStandaloneDecoderModelTester(self, is_training=False)
self.config_tester = ConfigTester(self, config_class=BlenderbotSmallConfig)
def test_config(self):
self.config_tester.run_common_tests()
def test_decoder_model_past(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
def test_decoder_model_attn_mask_past(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
@unittest.skip(reason="decoder cannot keep gradients")
def test_retain_grad_hidden_states_attentions(self):
return
@unittest.skip(reason="Decoder cannot keep gradients")
def test_flex_attention_with_grads():
return
| BlenderbotSmallStandaloneDecoderModelTest |
python | optuna__optuna | optuna/exceptions.py | {
"start": 0,
"end": 91
} | class ____(Exception):
"""Base class for Optuna specific errors."""
pass
| OptunaError |
python | Pylons__pyramid | src/pyramid/events.py | {
"start": 6309,
"end": 7302
} | class ____:
"""An instance of this class is emitted as an :term:`event` after
the :app:`Pyramid` :term:`router` finds a :term:`context`
object (after it performs traversal) but before any view code is
executed. The instance has an attribute, ``request``, which is
the request object generated by :app:`Pyramid`.
Notably, the request object will have an attribute named
``context``, which is the context that will be provided to the
view which will eventually be called, as well as other attributes
attached by context-finding code.
This class implements the
:class:`pyramid.interfaces.IContextFound` interface.
.. note::
As of :app:`Pyramid` 1.0, for backwards compatibility purposes, this
event may also be imported as :class:`pyramid.events.AfterTraversal`.
"""
def __init__(self, request):
self.request = request
AfterTraversal = ContextFound # b/c as of 1.0
@implementer(IApplicationCreated)
| ContextFound |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/color.py | {
"start": 141,
"end": 556
} | class ____(WidgetParameterItem):
"""Registered parameter type which displays a :class:`ColorButton <pyqtgraph.ColorButton>` """
def makeWidget(self):
w = ColorButton()
w.sigChanged = w.sigColorChanged
w.sigChanging = w.sigColorChanging
w.value = w.color
w.setValue = w.setColor
self.hideWidget = False
w.setFlat(True)
return w
| ColorParameterItem |
python | celery__celery | t/unit/backends/test_asynchronous.py | {
"start": 7553,
"end": 8066
} | class ____(DrainerTests):
@pytest.fixture(autouse=True)
def setup_drainer(self):
self.drainer = self.get_drainer('default')
@cached_property
def sleep(self):
from time import sleep
return sleep
def result_consumer_drain_events(self, timeout=None):
time.sleep(timeout)
def schedule_thread(self, thread):
t = threading.Thread(target=thread)
t.start()
return t
def teardown_thread(self, thread):
thread.join()
| test_Drainer |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/alloy_db.py | {
"start": 1708,
"end": 1910
} | class ____(BaseGoogleLink):
"""Helper class for constructing AlloyDB backups Link."""
name = "AlloyDB Backups"
key = "alloy_db_backups"
format_str = ALLOY_DB_BACKUPS_LINK
| AlloyDBBackupsLink |
python | doocs__leetcode | solution/0700-0799/0704.Binary Search/Solution.py | {
"start": 0,
"end": 311
} | class ____:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) >> 1
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l if nums[l] == target else -1
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/db_io_manager.py | {
"start": 1011,
"end": 1129
} | class ____(NamedTuple):
partition_expr: str
partitions: Union[TimeWindow, Sequence[str]]
| TablePartitionDimension |
python | nedbat__coveragepy | coverage/results.py | {
"start": 10386,
"end": 17242
} | class ____:
"""The numerical results of measuring coverage.
This holds the basic statistics from `Analysis`, and is used to roll
up statistics across files.
"""
precision: int = 0
n_files: int = 0
n_statements: int = 0
n_excluded: int = 0
n_missing: int = 0
n_branches: int = 0
n_partial_branches: int = 0
n_missing_branches: int = 0
@property
def n_executed(self) -> int:
"""Returns the number of executed statements."""
return self.n_statements - self.n_missing
@property
def n_executed_branches(self) -> int:
"""Returns the number of executed branches."""
return self.n_branches - self.n_missing_branches
@property
def ratio_statements(self) -> tuple[int, int]:
"""Return numerator/denominator for statement coverage."""
return self.n_executed, self.n_statements
@property
def ratio_branches(self) -> tuple[int, int]:
"""Return numerator/denominator for branch coverage."""
return self.n_executed_branches, self.n_branches
def _percent(self, numerator: int, denominator: int) -> float:
"""Helper for pc_* properties."""
if denominator > 0:
return (100.0 * numerator) / denominator
return 100.0
@property
def pc_covered(self) -> float:
"""Returns a single percentage value for coverage."""
return self._percent(*self.ratio_covered)
@property
def pc_statements(self) -> float:
"""Returns the percentage covered for statements."""
return self._percent(*self.ratio_statements)
@property
def pc_branches(self) -> float:
"""Returns the percentage covered for branches."""
return self._percent(*self.ratio_branches)
@property
def pc_covered_str(self) -> str:
"""Returns the percent covered, as a string, without a percent sign.
Note that "0" is only returned when the value is truly zero, and "100"
is only returned when the value is truly 100. Rounding can never
result in either "0" or "100".
"""
return display_covered(self.pc_covered, self.precision)
@property
def pc_statements_str(self) -> str:
"""Returns the statement percent covered without a percent sign."""
return display_covered(self.pc_statements, self.precision)
@property
def pc_branches_str(self) -> str:
"""Returns the branch percent covered without a percent sign."""
return display_covered(self.pc_branches, self.precision)
@property
def ratio_covered(self) -> tuple[int, int]:
"""Return a numerator and denominator for the coverage ratio."""
numerator = self.n_executed + self.n_executed_branches
denominator = self.n_statements + self.n_branches
return numerator, denominator
def __add__(self, other: Numbers) -> Numbers:
return Numbers(
self.precision,
self.n_files + other.n_files,
self.n_statements + other.n_statements,
self.n_excluded + other.n_excluded,
self.n_missing + other.n_missing,
self.n_branches + other.n_branches,
self.n_partial_branches + other.n_partial_branches,
self.n_missing_branches + other.n_missing_branches,
)
def __radd__(self, other: int) -> Numbers:
# Implementing 0+Numbers allows us to sum() a list of Numbers.
assert other == 0 # we only ever call it this way.
return self
def display_covered(pc: float, precision: int) -> str:
"""Return a displayable total percentage, as a string.
Note that "0" is only returned when the value is truly zero, and "100"
is only returned when the value is truly 100. Rounding can never
result in either "0" or "100".
"""
near0 = 1.0 / 10**precision
if 0 < pc < near0:
pc = near0
elif (100.0 - near0) < pc < 100:
pc = 100.0 - near0
else:
pc = round(pc, precision)
return f"{pc:.{precision}f}"
def _line_ranges(
statements: Iterable[TLineNo],
lines: Iterable[TLineNo],
) -> list[tuple[TLineNo, TLineNo]]:
"""Produce a list of ranges for `format_lines`."""
statements = sorted(statements)
lines = sorted(lines)
pairs = []
start: TLineNo | None = None
lidx = 0
for stmt in statements:
if lidx >= len(lines):
break
if stmt == lines[lidx]:
lidx += 1
if not start:
start = stmt
end = stmt
elif start:
pairs.append((start, end))
start = None
if start:
pairs.append((start, end))
return pairs
def format_lines(
statements: Iterable[TLineNo],
lines: Iterable[TLineNo],
arcs: Iterable[tuple[TLineNo, list[TLineNo]]] | None = None,
) -> str:
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".
Both `lines` and `statements` can be any iterable. All of the elements of
`lines` must be in `statements`, and all of the values must be positive
integers.
If `arcs` is provided, they are (start,[end,end,end]) pairs that will be
included in the output as long as start isn't in `lines`.
"""
line_items = [(pair[0], nice_pair(pair)) for pair in _line_ranges(statements, lines)]
if arcs is not None:
line_exits = sorted(arcs)
for line, exits in line_exits:
for ex in sorted(exits):
if line not in lines and ex not in lines:
dest = ex if ex > 0 else "exit"
line_items.append((line, f"{line}->{dest}"))
ret = ", ".join(t[-1] for t in sorted(line_items))
return ret
def should_fail_under(total: float, fail_under: float, precision: int) -> bool:
"""Determine if a total should fail due to fail-under.
`total` is a float, the coverage measurement total. `fail_under` is the
fail_under setting to compare with. `precision` is the number of digits
to consider after the decimal point.
Returns True if the total should fail.
"""
# We can never achieve higher than 100% coverage, or less than zero.
if not (0 <= fail_under <= 100.0):
msg = f"fail_under={fail_under} is invalid. Must be between 0 and 100."
raise ConfigError(msg)
# Special case for fail_under=100, it must really be 100.
if fail_under == 100.0 and total != 100.0:
return True
return round(total, precision) < fail_under
| Numbers |
python | django__django | tests/cache/tests.py | {
"start": 112855,
"end": 115030
} | class ____(SimpleTestCase):
def test_same_instance(self):
"""
Attempting to retrieve the same alias should yield the same instance.
"""
cache1 = caches["default"]
cache2 = caches["default"]
self.assertIs(cache1, cache2)
def test_per_thread(self):
"""
Requesting the same alias from separate threads should yield separate
instances.
"""
c = []
def runner():
c.append(caches["default"])
for x in range(2):
t = threading.Thread(target=runner)
t.start()
t.join()
self.assertIsNot(c[0], c[1])
def test_nonexistent_alias(self):
msg = "The connection 'nonexistent' doesn't exist."
with self.assertRaisesMessage(InvalidCacheBackendError, msg):
caches["nonexistent"]
def test_nonexistent_backend(self):
test_caches = CacheHandler(
{
"invalid_backend": {
"BACKEND": "django.nonexistent.NonexistentBackend",
},
}
)
msg = (
"Could not find backend 'django.nonexistent.NonexistentBackend': "
"No module named 'django.nonexistent'"
)
with self.assertRaisesMessage(InvalidCacheBackendError, msg):
test_caches["invalid_backend"]
def test_all(self):
test_caches = CacheHandler(
{
"cache_1": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
},
"cache_2": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
},
}
)
self.assertEqual(test_caches.all(initialized_only=True), [])
cache_1 = test_caches["cache_1"]
self.assertEqual(test_caches.all(initialized_only=True), [cache_1])
self.assertEqual(len(test_caches.all()), 2)
# .all() initializes all caches.
self.assertEqual(len(test_caches.all(initialized_only=True)), 2)
self.assertEqual(test_caches.all(), test_caches.all(initialized_only=True))
| CacheHandlerTest |
python | openai__gym | gym/error.py | {
"start": 4227,
"end": 4323
} | class ____(Error):
"""Error message for using wrap after configure."""
| WrapAfterConfigureError |
python | weaviate__weaviate-python-client | weaviate/collections/aggregations/hybrid/sync.py | {
"start": 188,
"end": 245
} | class ____(_HybridExecutor[ConnectionSync]):
pass
| _Hybrid |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 6201,
"end": 6569
} | class ____(TestAtomFeed):
"""
A feed with timezone-aware dates.
"""
def item_pubdate(self, item):
# Provide a weird offset so that the test can know it's getting this
# specific offset and not accidentally getting on from
# settings.TIME_ZONE.
return item.published.replace(tzinfo=get_fixed_timezone(42))
| TZAwareDatesFeed |
python | django__django | tests/queries/models.py | {
"start": 2925,
"end": 3284
} | class ____(models.Model):
rank = models.IntegerField()
author = models.ForeignKey(Author, models.CASCADE)
class Meta:
# A complex ordering specification. Should stress the system a bit.
ordering = ("author__extra__note", "author__name", "rank")
def __str__(self):
return "%d: %s" % (self.rank, self.author.name)
| Ranking |
python | Lightning-AI__lightning | src/lightning/pytorch/tuner/lr_finder.py | {
"start": 18133,
"end": 19144
} | class ____(LRScheduler):
"""Linearly increases the learning rate between two boundaries over a number of iterations.
Args:
optimizer: wrapped optimizer.
end_lr: the final learning rate.
num_iter: the number of iterations over which the test occurs.
last_epoch: the index of last epoch. Default: -1.
"""
def __init__(self, optimizer: torch.optim.Optimizer, end_lr: float, num_iter: int, last_epoch: int = -1):
self.end_lr = end_lr
self.num_iter = num_iter
super().__init__(optimizer, last_epoch)
@override
def get_lr(self) -> list[float]:
curr_iter = self.last_epoch + 1
r = curr_iter / self.num_iter
if self.last_epoch > 0:
val = [base_lr + r * (self.end_lr - base_lr) for base_lr in self.base_lrs]
else:
val = list(self.base_lrs)
self._lr = val
return val
@property
def lr(self) -> Union[float, list[float]]:
return self._lr
| _LinearLR |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/special_math_test.py | {
"start": 7507,
"end": 8020
} | class ____(NdtrTest):
_use_log = True
_grid32 = GridSpec(min=-100., max=sm.LOGNDTR_FLOAT32_LOWER, shape=[100])
_grid64 = GridSpec(min=-100., max=sm.LOGNDTR_FLOAT64_LOWER, shape=[100])
_error32 = ErrorSpec(rtol=1e-4, atol=0.)
_error64 = ErrorSpec(rtol=1e-4, atol=0.)
# The errors are quite large when the input is > 6 or so. Also,
# scipy.special.log_ndtr becomes zero very early, before 10,
# (due to ndtr becoming 1). We approximate Log[1 + epsilon] as epsilon, and
# avoid this issue.
| LogNdtrTestLower |
python | conda__conda | conda/auxlib/collection.py | {
"start": 264,
"end": 1941
} | class ____(dict):
"""Sub-classes dict, and further allows attribute-like access to dictionary items.
Examples:
>>> d = AttrDict({'a': 1})
>>> d.a, d['a'], d.get('a')
(1, 1, 1)
>>> d.b = 2
>>> d.b, d['b']
(2, 2)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
def first(seq, key=bool, default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq that passes key, mutated with optional apply
Examples:
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
def last(seq, key=bool, default=None, apply=lambda x: x):
return next((apply(x) for x in reversed(seq) if key(x)), default)
| AttrDict |
python | getsentry__sentry | src/sentry/integrations/types.py | {
"start": 157,
"end": 637
} | class ____(ValueEqualityEnum):
UNUSED_GH = 0
UNUSED_GL = 1
EMAIL = 100
SLACK = 110
MSTEAMS = 120
PAGERDUTY = 130
DISCORD = 140
OPSGENIE = 150
GITHUB = 200
GITHUB_ENTERPRISE = 201
GITLAB = 210
JIRA_SERVER = 300
PERFORCE = 400
# TODO: do migration to delete this from database
CUSTOM = 700
@property
def name(self) -> str:
return EXTERNAL_PROVIDERS.get(ExternalProviders(self.value), "")
| ExternalProviders |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 6681,
"end": 6840
} | class ____:
def setup(self):
self.df = DataFrame(np.random.randn(100, 10))
def time_to_string_floats(self):
self.df.to_string()
| ToString |
python | doocs__leetcode | solution/1600-1699/1687.Delivering Boxes from Storage to Ports/Solution.py | {
"start": 0,
"end": 775
} | class ____:
def boxDelivering(
self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int
) -> int:
n = len(boxes)
ws = list(accumulate((box[1] for box in boxes), initial=0))
c = [int(a != b) for a, b in pairwise(box[0] for box in boxes)]
cs = list(accumulate(c, initial=0))
f = [0] * (n + 1)
q = deque([0])
for i in range(1, n + 1):
while q and (i - q[0] > maxBoxes or ws[i] - ws[q[0]] > maxWeight):
q.popleft()
if q:
f[i] = cs[i - 1] + f[q[0]] - cs[q[0]] + 2
if i < n:
while q and f[q[-1]] - cs[q[-1]] >= f[i] - cs[i]:
q.pop()
q.append(i)
return f[n]
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-airflow/dagster_airflow/resources/airflow_persistent_db.py | {
"start": 519,
"end": 4257
} | class ____(AirflowDatabase):
"""A persistent Airflow database Dagster resource."""
def __init__(self, dagster_run: DagsterRun, uri: str, dag_run_config: Optional[dict] = None):
self.uri = uri
super().__init__(dagster_run=dagster_run, dag_run_config=dag_run_config)
@staticmethod
def _initialize_database(uri: str, connections: list[Connection] = []):
if is_airflow_2_loaded_in_environment("2.3.0"):
os.environ["AIRFLOW__DATABASE__SQL_ALCHEMY_CONN"] = uri
importlib.reload(airflow.configuration)
importlib.reload(airflow.settings)
importlib.reload(airflow)
else:
os.environ["AIRFLOW__CORE__SQL_ALCHEMY_CONN"] = uri
importlib.reload(airflow)
create_airflow_connections(connections)
@staticmethod
def from_resource_context(context: InitResourceContext) -> "AirflowPersistentDatabase":
uri = context.resource_config["uri"]
AirflowPersistentDatabase._initialize_database(
uri=uri, connections=[Connection(**c) for c in context.resource_config["connections"]]
)
return AirflowPersistentDatabase(
dagster_run=check.not_none(context.dagster_run, "Context must have run"),
uri=uri,
dag_run_config=context.resource_config["dag_run_config"],
)
@superseded(
additional_warn_text=(
"`make_persistent_airflow_db_resource` has been superseded "
"by the functionality in the `dagster-airlift` library."
)
)
def make_persistent_airflow_db_resource(
uri: str = "",
connections: list[Connection] = [],
dag_run_config: Optional[dict] = {},
) -> ResourceDefinition:
"""Creates a Dagster resource that provides an persistent Airflow database.
Usage:
.. code-block:: python
from dagster_airflow import (
make_dagster_definitions_from_airflow_dags_path,
make_persistent_airflow_db_resource,
)
postgres_airflow_db = "postgresql+psycopg2://airflow:airflow@localhost:5432/airflow"
airflow_db = make_persistent_airflow_db_resource(uri=postgres_airflow_db)
definitions = make_dagster_definitions_from_airflow_example_dags(
'/path/to/dags/',
resource_defs={"airflow_db": airflow_db}
)
Args:
uri: SQLAlchemy URI of the Airflow DB to be used
connections (List[Connection]): List of Airflow Connections to be created in the Airflow DB
dag_run_config (Optional[dict]): dag_run configuration to be used when creating a DagRun
Returns:
ResourceDefinition: The persistent Airflow DB resource
"""
if is_airflow_2_loaded_in_environment():
os.environ["AIRFLOW__DATABASE__SQL_ALCHEMY_CONN"] = uri
else:
os.environ["AIRFLOW__CORE__SQL_ALCHEMY_CONN"] = uri
serialized_connections = serialize_connections(connections)
airflow_db_resource_def = ResourceDefinition(
resource_fn=AirflowPersistentDatabase.from_resource_context,
config_schema={
"uri": Field(
StringSource,
default_value=uri,
is_required=False,
),
"connections": Field(
Array(inner_type=dict),
default_value=serialized_connections,
is_required=False,
),
"dag_run_config": Field(
dict,
default_value=dag_run_config,
is_required=False,
),
},
description="Persistent Airflow DB to be used by dagster-airflow ",
)
return airflow_db_resource_def
| AirflowPersistentDatabase |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 21166,
"end": 21272
} | class ____(Resolvable, Model):
existing_cluster_id: str
@preview
| ResolvedDatabricksExistingClusterConfig |
python | has2k1__plotnine | tests/test_save_as_pdf_pages.py | {
"start": 2472,
"end": 3329
} | class ____:
def test_plot_exception(self):
# Force an error in drawing
fn = next(filename_gen)
plots = list(p())
plots[0] += aes(color="unknown")
with pytest.raises(PlotnineError):
save_as_pdf_pages(plots, fn, verbose=False)
# TODO: Remove when MPL>=3.10.0
if fn.exists():
fn.unlink()
assert not fn.exists()
# This should be the last function in the file since it can catch
# "leakages" due to the tests in this test module.
def test_save_as_pdf_pages_closes_plots():
assert plt.get_fignums() == [], "There are unsaved test plots"
fn = next(filename_gen)
with pytest.warns(PlotnineWarning):
save_as_pdf_pages(p(), fn)
assert_exist_and_clean(fn, "exist")
assert plt.get_fignums() == [], "ggplot.save did not close the plot"
| TestExceptions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/types.py | {
"start": 2616,
"end": 2739
} | class ____(FromDictMixin):
prefix: str
suffix: str
FieldType = Dict[Any, Any]
@dataclasses.dataclass
| AutoNumberDict |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor2.py | {
"start": 473,
"end": 530
} | class ____(Animal[int, int], Generic[_T3]):
pass
| Donkey |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 26950,
"end": 33324
} | class ____(MoshiAttention):
"""
Moshi flash attention module. This module inherits from `MoshiAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in case the input contains any of them.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask()
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: bool = False,
use_cache: bool = False,
cache_position: Optional[torch.LongTensor] = None,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
if isinstance(past_key_values, StaticCache):
raise ValueError(
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
)
output_attentions = False
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states, cache_position) # Ignore copy
key_states = self.k_proj(hidden_states, cache_position) # Ignore copy
value_states = self.v_proj(hidden_states, cache_position) # Ignore copy
# Flash attention requires the input to have the shape
# batch_size x seq_length x head_dim x hidden_dim
# therefore we just need to keep the original shape
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
if self.rotary_emb is not None: # Ignore copy
cos, sin = self.rotary_emb(value_states, position_ids) # Ignore copy
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) # Ignore copy
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = (
{"sin": sin, "cos": cos, "cache_position": cache_position}
if self.rotary_emb is not None
else {"cache_position": cache_position}
) # Ignore copy
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
# to be able to avoid many of these transpose/reshape/view.
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
dropout_rate = self.attention_dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
# therefore the input hidden states gets silently casted in float32. Hence, we need
# cast them back in the correct dtype just to be sure everything works as expected.
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
# in fp32. (MoshiRMSNorm handles it correctly)
input_dtype = query_states.dtype
device_type = query_states.device.type if query_states.device.type != "mps" else "cpu"
if input_dtype == torch.float32:
if torch.is_autocast_enabled():
# NOTE: `torch.get_autocast_dtype` is there starting from PyTorch 2.4
target_dtype = (
torch.get_autocast_dtype(device_type)
if hasattr(torch, "get_autocast_dtype")
else torch.get_autocast_gpu_dtype()
)
# Handle the case where the model is quantized
elif hasattr(self.config, "_pre_quantization_dtype"):
target_dtype = self.config._pre_quantization_dtype
else:
target_dtype = self.q_proj.weight.dtype
logger.warning_once(
f"The input hidden states seems to be silently casted in float32, this might be related to"
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
f" {target_dtype}."
)
query_states = query_states.to(target_dtype)
key_states = key_states.to(target_dtype)
value_states = value_states.to(target_dtype)
attn_output = _flash_attention_forward(
query_states,
key_states,
value_states,
attention_mask,
q_len,
position_ids=position_ids,
dropout=dropout_rate,
sliding_window=getattr(self, "sliding_window", None),
is_causal=self.is_causal,
use_top_left_mask=self._flash_attn_uses_top_left_mask,
)
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
attn_output = self.o_proj(attn_output, cache_position) # Ignore copy
if not output_attentions:
attn_weights = None
return attn_output, attn_weights
# Copied from transformers.models.mimi.modeling_mimi.MimiSdpaAttention with Mimi->Moshi
| MoshiFlashAttention2 |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 8915,
"end": 10190
} | class ____(BosonicOperator, Annihilator):
"""
Bosonic annihilation operator.
Examples
========
>>> from sympy.physics.secondquant import B
>>> from sympy.abc import x
>>> B(x)
AnnihilateBoson(x)
"""
op_symbol = 'b'
def _dagger_(self):
return CreateBoson(self.state)
def apply_operator(self, state):
"""
Apply state to self if self is not symbolic and state is a FockStateKet, else
multiply self by state.
Examples
========
>>> from sympy.physics.secondquant import B, BKet
>>> from sympy.abc import x, y, n
>>> B(x).apply_operator(y)
y*AnnihilateBoson(x)
>>> B(0).apply_operator(BKet((n,)))
sqrt(n)*FockStateBosonKet((n - 1,))
"""
if not self.is_symbolic and isinstance(state, FockStateKet):
element = self.state
amp = sqrt(state[element])
return amp*state.down(element)
else:
return Mul(self, state)
def __repr__(self):
return "AnnihilateBoson(%s)" % self.state
def _latex(self, printer):
if self.state is S.Zero:
return "b_{0}"
else:
return "b_{%s}" % printer._print(self.state)
| AnnihilateBoson |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_retry.py | {
"start": 792,
"end": 30563
} | class ____:
"""Tool that fails a certain number of times before succeeding."""
def __init__(self, fail_count: int):
"""Initialize with the number of times to fail.
Args:
fail_count: Number of times to fail before succeeding.
"""
self.fail_count = fail_count
self.attempt = 0
def __call__(self, input: str) -> str:
"""Execute the tool.
Args:
input: Input string.
Returns:
Success message if attempt >= fail_count.
Raises:
ValueError: If attempt < fail_count.
"""
self.attempt += 1
if self.attempt <= self.fail_count:
msg = f"Temporary failure {self.attempt}"
raise ValueError(msg)
return f"Success after {self.attempt} attempts: {input}"
def test_tool_retry_initialization_defaults() -> None:
"""Test ToolRetryMiddlewareinitialization with default values."""
retry = ToolRetryMiddleware()
assert retry.max_retries == 2
assert retry._tool_filter is None
assert retry.tools == []
assert retry.on_failure == "continue"
assert retry.backoff_factor == 2.0
assert retry.initial_delay == 1.0
assert retry.max_delay == 60.0
assert retry.jitter is True
def test_tool_retry_initialization_custom() -> None:
"""Test ToolRetryMiddlewareinitialization with custom values."""
retry = ToolRetryMiddleware(
max_retries=5,
tools=["tool1", "tool2"],
retry_on=(ValueError, RuntimeError),
on_failure="error",
backoff_factor=1.5,
initial_delay=0.5,
max_delay=30.0,
jitter=False,
)
assert retry.max_retries == 5
assert retry._tool_filter == ["tool1", "tool2"]
assert retry.tools == []
assert retry.retry_on == (ValueError, RuntimeError)
assert retry.on_failure == "error"
assert retry.backoff_factor == 1.5
assert retry.initial_delay == 0.5
assert retry.max_delay == 30.0
assert retry.jitter is False
def test_tool_retry_initialization_with_base_tools() -> None:
"""Test ToolRetryMiddleware initialization with BaseTool instances."""
retry = ToolRetryMiddleware(
max_retries=3,
tools=[working_tool, failing_tool], # Pass BaseTool instances
)
assert retry.max_retries == 3
# Should extract names from BaseTool instances
assert retry._tool_filter == ["working_tool", "failing_tool"]
assert retry.tools == []
def test_tool_retry_initialization_with_mixed_tools() -> None:
"""Test ToolRetryMiddleware initialization with mixed tool types."""
retry = ToolRetryMiddleware(
max_retries=2,
tools=[working_tool, "failing_tool"], # Mix of BaseTool and string
)
assert retry.max_retries == 2
# Should handle both BaseTool instances and strings
assert retry._tool_filter == ["working_tool", "failing_tool"]
assert retry.tools == []
def test_tool_retry_invalid_max_retries() -> None:
"""Test ToolRetryMiddlewareraises error for invalid max_retries."""
with pytest.raises(ValueError, match="max_retries must be >= 0"):
ToolRetryMiddleware(max_retries=-1)
def test_tool_retry_invalid_initial_delay() -> None:
"""Test ToolRetryMiddlewareraises error for invalid initial_delay."""
with pytest.raises(ValueError, match="initial_delay must be >= 0"):
ToolRetryMiddleware(initial_delay=-1.0)
def test_tool_retry_invalid_max_delay() -> None:
"""Test ToolRetryMiddlewareraises error for invalid max_delay."""
with pytest.raises(ValueError, match="max_delay must be >= 0"):
ToolRetryMiddleware(max_delay=-1.0)
def test_tool_retry_invalid_backoff_factor() -> None:
"""Test ToolRetryMiddlewareraises error for invalid backoff_factor."""
with pytest.raises(ValueError, match="backoff_factor must be >= 0"):
ToolRetryMiddleware(backoff_factor=-1.0)
def test_tool_retry_working_tool_no_retry_needed() -> None:
"""Test ToolRetryMiddlewarewith a working tool (no retry needed)."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="working_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)
agent = create_agent(
model=model,
tools=[working_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use working tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "Success: test" in tool_messages[0].content
assert tool_messages[0].status != "error"
def test_tool_retry_failing_tool_returns_message() -> None:
"""Test ToolRetryMiddlewarewith failing tool returns error message."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Should contain error message with tool name and attempts
assert "failing_tool" in tool_messages[0].content
assert "3 attempts" in tool_messages[0].content
assert "ValueError" in tool_messages[0].content
assert tool_messages[0].status == "error"
def test_tool_retry_failing_tool_raises() -> None:
"""Test ToolRetryMiddlewarewith on_failure='error' re-raises exception."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.01,
jitter=False,
on_failure="error",
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
# Should raise the ValueError from the tool
with pytest.raises(ValueError, match="Failed: test"):
agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
def test_tool_retry_custom_failure_formatter() -> None:
"""Test ToolRetryMiddlewarewith custom failure message formatter."""
def custom_formatter(exc: Exception) -> str:
return f"Custom error: {type(exc).__name__}"
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=1,
initial_delay=0.01,
jitter=False,
on_failure=custom_formatter,
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "Custom error: ValueError" in tool_messages[0].content
def test_tool_retry_succeeds_after_retries() -> None:
"""Test ToolRetryMiddlewaresucceeds after temporary failures."""
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
def temp_failing_tool(input: str) -> str:
"""Tool that fails temporarily."""
return temp_fail(input)
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=3,
initial_delay=0.01,
jitter=False,
)
agent = create_agent(
model=model,
tools=[temp_failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use temp failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Should succeed on 3rd attempt
assert "Success after 3 attempts" in tool_messages[0].content
assert tool_messages[0].status != "error"
def test_tool_retry_specific_tools_only() -> None:
"""Test ToolRetryMiddlewareonly applies to specific tools."""
model = FakeToolCallingModel(
tool_calls=[
[
ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),
ToolCall(name="working_tool", args={"input": "test2"}, id="2"),
],
[],
]
)
# Only retry failing_tool
retry = ToolRetryMiddleware(
max_retries=2,
tools=["failing_tool"],
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[failing_tool, working_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use both tools")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 2
# failing_tool should have error message
failing_msg = next(m for m in tool_messages if m.name == "failing_tool")
assert failing_msg.status == "error"
assert "3 attempts" in failing_msg.content
# working_tool should succeed normally (no retry applied)
working_msg = next(m for m in tool_messages if m.name == "working_tool")
assert "Success: test2" in working_msg.content
assert working_msg.status != "error"
def test_tool_retry_specific_tools_with_base_tool() -> None:
"""Test ToolRetryMiddleware accepts BaseTool instances for filtering."""
model = FakeToolCallingModel(
tool_calls=[
[
ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),
ToolCall(name="working_tool", args={"input": "test2"}, id="2"),
],
[],
]
)
# Only retry failing_tool, passed as BaseTool instance
retry = ToolRetryMiddleware(
max_retries=2,
tools=[failing_tool], # Pass BaseTool instance
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[failing_tool, working_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use both tools")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 2
# failing_tool should have error message (with retries)
failing_msg = next(m for m in tool_messages if m.name == "failing_tool")
assert failing_msg.status == "error"
assert "3 attempts" in failing_msg.content
# working_tool should succeed normally (no retry applied)
working_msg = next(m for m in tool_messages if m.name == "working_tool")
assert "Success: test2" in working_msg.content
assert working_msg.status != "error"
def test_tool_retry_specific_exceptions() -> None:
"""Test ToolRetryMiddlewareonly retries specific exception types."""
@tool
def value_error_tool(input: str) -> str:
"""Tool that raises ValueError."""
msg = f"ValueError: {input}"
raise ValueError(msg)
@tool
def runtime_error_tool(input: str) -> str:
"""Tool that raises RuntimeError."""
msg = f"RuntimeError: {input}"
raise RuntimeError(msg)
model = FakeToolCallingModel(
tool_calls=[
[
ToolCall(name="value_error_tool", args={"input": "test1"}, id="1"),
ToolCall(name="runtime_error_tool", args={"input": "test2"}, id="2"),
],
[],
]
)
# Only retry ValueError
retry = ToolRetryMiddleware(
max_retries=2,
retry_on=(ValueError,),
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[value_error_tool, runtime_error_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use both tools")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 2
# ValueError should be retried (3 attempts)
value_error_msg = next(m for m in tool_messages if m.name == "value_error_tool")
assert "3 attempts" in value_error_msg.content
# RuntimeError should fail immediately (1 attempt only)
runtime_error_msg = next(m for m in tool_messages if m.name == "runtime_error_tool")
assert "1 attempt" in runtime_error_msg.content
def test_tool_retry_custom_exception_filter() -> None:
"""Test ToolRetryMiddlewarewith custom exception filter function."""
class CustomError(Exception):
"""Custom exception with retry_me attribute."""
def __init__(self, message: str, retry_me: bool):
"""Initialize custom error.
Args:
message: Error message.
retry_me: Whether this error should be retried.
"""
super().__init__(message)
self.retry_me = retry_me
attempt_count = {"value": 0}
@tool
def custom_error_tool(input: str) -> str:
"""Tool that raises CustomError."""
attempt_count["value"] += 1
if attempt_count["value"] == 1:
raise CustomError("Retryable error", retry_me=True)
raise CustomError("Non-retryable error", retry_me=False)
def should_retry(exc: Exception) -> bool:
return isinstance(exc, CustomError) and exc.retry_me
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="custom_error_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=3,
retry_on=should_retry,
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[custom_error_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use custom error tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Should retry once (attempt 1 with retry_me=True), then fail on attempt 2 (retry_me=False)
assert attempt_count["value"] == 2
assert "2 attempts" in tool_messages[0].content
def test_tool_retry_backoff_timing() -> None:
"""Test ToolRetryMiddlewareapplies correct backoff delays."""
temp_fail = TemporaryFailureTool(fail_count=3)
@tool
def temp_failing_tool(input: str) -> str:
"""Tool that fails temporarily."""
return temp_fail(input)
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=3,
initial_delay=0.1,
backoff_factor=2.0,
jitter=False,
)
agent = create_agent(
model=model,
tools=[temp_failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
start_time = time.time()
result = agent.invoke(
{"messages": [HumanMessage("Use temp failing tool")]},
{"configurable": {"thread_id": "test"}},
)
elapsed = time.time() - start_time
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Expected delays: 0.1 + 0.2 + 0.4 = 0.7 seconds
# Allow some margin for execution time
assert elapsed >= 0.6, f"Expected at least 0.6s, got {elapsed}s"
def test_tool_retry_constant_backoff() -> None:
"""Test ToolRetryMiddlewarewith constant backoff (backoff_factor=0)."""
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
def temp_failing_tool(input: str) -> str:
"""Tool that fails temporarily."""
return temp_fail(input)
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.1,
backoff_factor=0.0, # Constant backoff
jitter=False,
)
agent = create_agent(
model=model,
tools=[temp_failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
start_time = time.time()
result = agent.invoke(
{"messages": [HumanMessage("Use temp failing tool")]},
{"configurable": {"thread_id": "test"}},
)
elapsed = time.time() - start_time
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Expected delays: 0.1 + 0.1 = 0.2 seconds (constant)
assert elapsed >= 0.15, f"Expected at least 0.15s, got {elapsed}s"
assert elapsed < 0.5, f"Expected less than 0.5s (exponential would be longer), got {elapsed}s"
def test_tool_retry_max_delay_cap() -> None:
"""Test calculate_delay caps delay at max_delay."""
# Test delay calculation with aggressive backoff and max_delay cap
delay_0 = calculate_delay(
0,
backoff_factor=10.0, # Very aggressive backoff
initial_delay=1.0,
max_delay=2.0, # Cap at 2 seconds
jitter=False,
) # 1.0
delay_1 = calculate_delay(
1,
backoff_factor=10.0,
initial_delay=1.0,
max_delay=2.0,
jitter=False,
) # 10.0 -> capped to 2.0
delay_2 = calculate_delay(
2,
backoff_factor=10.0,
initial_delay=1.0,
max_delay=2.0,
jitter=False,
) # 100.0 -> capped to 2.0
assert delay_0 == 1.0
assert delay_1 == 2.0
assert delay_2 == 2.0
def test_tool_retry_jitter_variation() -> None:
"""Test calculate_delay adds jitter to delays."""
# Generate multiple delays and ensure they vary
delays = [
calculate_delay(
0,
backoff_factor=1.0,
initial_delay=1.0,
max_delay=60.0,
jitter=True,
)
for _ in range(10)
]
# All delays should be within ±25% of 1.0 (i.e., between 0.75 and 1.25)
for delay in delays:
assert 0.75 <= delay <= 1.25
# Delays should vary (not all the same)
assert len(set(delays)) > 1
@pytest.mark.asyncio
async def test_tool_retry_async_working_tool() -> None:
"""Test ToolRetryMiddlewarewith async execution and working tool."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="working_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)
agent = create_agent(
model=model,
tools=[working_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = await agent.ainvoke(
{"messages": [HumanMessage("Use working tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "Success: test" in tool_messages[0].content
@pytest.mark.asyncio
async def test_tool_retry_async_failing_tool() -> None:
"""Test ToolRetryMiddlewarewith async execution and failing tool."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.01,
jitter=False,
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = await agent.ainvoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "failing_tool" in tool_messages[0].content
assert "3 attempts" in tool_messages[0].content
assert tool_messages[0].status == "error"
@pytest.mark.asyncio
async def test_tool_retry_async_succeeds_after_retries() -> None:
"""Test ToolRetryMiddlewareasync execution succeeds after temporary failures."""
temp_fail = TemporaryFailureTool(fail_count=2)
@tool
def temp_failing_tool(input: str) -> str:
"""Tool that fails temporarily."""
return temp_fail(input)
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=3,
initial_delay=0.01,
jitter=False,
)
agent = create_agent(
model=model,
tools=[temp_failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = await agent.ainvoke(
{"messages": [HumanMessage("Use temp failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "Success after 3 attempts" in tool_messages[0].content
@pytest.mark.asyncio
async def test_tool_retry_async_backoff_timing() -> None:
"""Test ToolRetryMiddlewareasync applies correct backoff delays."""
temp_fail = TemporaryFailureTool(fail_count=3)
@tool
def temp_failing_tool(input: str) -> str:
"""Tool that fails temporarily."""
return temp_fail(input)
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=3,
initial_delay=0.1,
backoff_factor=2.0,
jitter=False,
)
agent = create_agent(
model=model,
tools=[temp_failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
start_time = time.time()
result = await agent.ainvoke(
{"messages": [HumanMessage("Use temp failing tool")]},
{"configurable": {"thread_id": "test"}},
)
elapsed = time.time() - start_time
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Expected delays: 0.1 + 0.2 + 0.4 = 0.7 seconds
assert elapsed >= 0.6, f"Expected at least 0.6s, got {elapsed}s"
def test_tool_retry_zero_retries() -> None:
"""Test ToolRetryMiddlewarewith max_retries=0 (no retries)."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(
max_retries=0, # No retries
on_failure="continue",
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Should fail after 1 attempt (no retries)
assert "1 attempt" in tool_messages[0].content
assert tool_messages[0].status == "error"
def test_tool_retry_multiple_middleware_composition() -> None:
"""Test ToolRetryMiddlewarecomposes correctly with other middleware."""
call_log = []
# Custom middleware that logs calls
from langchain.agents.middleware.types import wrap_tool_call
@wrap_tool_call
def logging_middleware(
request: "ToolCallRequest", handler: Callable
) -> "ToolMessage | Command":
call_log.append(f"before_{request.tool.name}")
response = handler(request)
call_log.append(f"after_{request.tool.name}")
return response
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="working_tool", args={"input": "test"}, id="1")],
[],
]
)
retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)
agent = create_agent(
model=model,
tools=[working_tool],
middleware=[logging_middleware, retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use working tool")]},
{"configurable": {"thread_id": "test"}},
)
# Both middleware should be called
assert call_log == ["before_working_tool", "after_working_tool"]
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
assert "Success: test" in tool_messages[0].content
def test_tool_retry_deprecated_raise_keyword() -> None:
"""Test ToolRetryMiddleware with deprecated 'raise' keyword shows deprecation warning."""
with pytest.warns(DeprecationWarning, match="on_failure='raise' is deprecated"):
retry = ToolRetryMiddleware(
max_retries=2,
on_failure="raise",
)
# Should be converted to 'error'
assert retry.on_failure == "error"
def test_tool_retry_deprecated_return_message_keyword() -> None:
"""Test ToolRetryMiddleware with deprecated 'return_message' keyword shows deprecation warning."""
# Use string concatenation to avoid batch replace affecting test code
deprecated_value = "return" + "_message"
with pytest.warns(DeprecationWarning, match="on_failure='return_message' is deprecated"):
retry = ToolRetryMiddleware(
max_retries=2,
on_failure=deprecated_value, # type: ignore[arg-type]
)
# Should be converted to 'continue'
assert retry.on_failure == "continue"
def test_tool_retry_deprecated_raise_behavior() -> None:
"""Test ToolRetryMiddleware with deprecated 'raise' forwards to 'error' behavior."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
with pytest.warns(DeprecationWarning, match="on_failure='raise' is deprecated"):
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.01,
jitter=False,
on_failure="raise",
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
# Should raise the ValueError from the tool (same as 'error')
with pytest.raises(ValueError, match="Failed: test"):
agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
def test_tool_retry_deprecated_return_message_behavior() -> None:
"""Test ToolRetryMiddleware with deprecated 'return_message' forwards to 'continue' behavior."""
model = FakeToolCallingModel(
tool_calls=[
[ToolCall(name="failing_tool", args={"input": "test"}, id="1")],
[],
]
)
# Use string concatenation to avoid batch replace affecting test code
deprecated_value = "return" + "_message"
with pytest.warns(DeprecationWarning, match="on_failure='return_message' is deprecated"):
retry = ToolRetryMiddleware(
max_retries=2,
initial_delay=0.01,
jitter=False,
on_failure=deprecated_value, # type: ignore[arg-type]
)
agent = create_agent(
model=model,
tools=[failing_tool],
middleware=[retry],
checkpointer=InMemorySaver(),
)
result = agent.invoke(
{"messages": [HumanMessage("Use failing tool")]},
{"configurable": {"thread_id": "test"}},
)
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
assert len(tool_messages) == 1
# Should contain error message (same as 'continue')
assert "failing_tool" in tool_messages[0].content
assert "3 attempts" in tool_messages[0].content
assert "ValueError" in tool_messages[0].content
assert tool_messages[0].status == "error"
| TemporaryFailureTool |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_details.py | {
"start": 5042,
"end": 30190
} | class ____(SentryAppDetailsTest):
method = "PUT"
def _validate_updated_published_app(self, response: Response) -> None:
data = response.data
data["featureData"] = sorted(data["featureData"], key=lambda a: a["featureId"])
assert data == {
"name": self.published_app.name,
"author": "A Company",
"slug": self.published_app.slug,
"scopes": [],
"events": set(),
"status": self.published_app.get_status_display(),
"uuid": self.published_app.uuid,
"webhookUrl": "https://newurl.com",
"redirectUrl": "https://newredirecturl.com",
"isAlertable": True,
"verifyInstall": self.published_app.verify_install,
"clientId": self.published_app.application.client_id,
"clientSecret": self.published_app.application.client_secret,
"overview": self.published_app.overview,
"allowedOrigins": [],
"schema": {},
"owner": {"id": self.organization.id, "slug": self.organization.slug},
"featureData": [
{
"featureId": 1,
"featureGate": "integrations-issue-link",
"description": "Organizations can **create or link Sentry issues** to another service.",
},
{
"featureId": 2,
"featureGate": "integrations-stacktrace-link",
"description": "Organizations can **open a line to Sentry's stack trace** in another service.",
},
],
"popularity": self.popularity,
"avatars": set(),
"metadata": {},
}
def test_superuser_update_published_app(self) -> None:
self.login_as(user=self.superuser, superuser=True)
response = self.get_success_response(
self.published_app.slug,
name=self.published_app.name,
author="A Company",
webhookUrl="https://newurl.com",
redirectUrl="https://newredirecturl.com",
isAlertable=True,
features=[1, 2],
status_code=200,
)
self._validate_updated_published_app(response)
@override_options({"staff.ga-rollout": True})
def test_staff_update_published_app(self) -> None:
self.login_as(user=self.staff_user, staff=True)
response = self.get_success_response(
self.published_app.slug,
name=self.published_app.name,
author="A Company",
webhookUrl="https://newurl.com",
redirectUrl="https://newredirecturl.com",
isAlertable=True,
features=[1, 2],
status_code=200,
)
self._validate_updated_published_app(response)
def test_update_unpublished_app(self) -> None:
response = self.get_success_response(
self.unpublished_app.slug,
name="NewName",
webhookUrl="https://newurl.com",
scopes=("event:read",),
events=("issue",),
features=[1, 2],
status_code=200,
)
assert response.data["name"] == "NewName"
assert response.data["slug"] == self.unpublished_app.slug
assert response.data["scopes"] == ["event:read"]
assert response.data["events"] == {"issue"}
assert response.data["uuid"] == self.unpublished_app.uuid
assert response.data["webhookUrl"] == "https://newurl.com"
assert sorted(response.data["featureData"], key=lambda a: a["featureId"]) == [
{
"featureId": 1,
"featureGate": "integrations-issue-link",
"description": "Organizations can **create or link Sentry issues** to another service.",
},
{
"featureId": 2,
"featureGate": "integrations-stacktrace-link",
"description": "Organizations can **open a line to Sentry's stack trace** in another service.",
},
]
assert not SentryAppInstallation.objects.filter(sentry_app=self.unpublished_app).exists()
with assume_test_silo_mode(SiloMode.REGION):
assert not ServiceHook.objects.filter(
application_id=self.unpublished_app.application_id
).exists()
def test_update_internal_app(self) -> None:
self.get_success_response(
self.internal_integration.slug,
webhookUrl="https://newurl.com",
scopes=("event:read",),
events=("issue",),
status_code=200,
)
self.internal_integration.refresh_from_db()
assert self.internal_integration.webhook_url == "https://newurl.com"
installation = SentryAppInstallation.objects.get(sentry_app=self.internal_integration)
with assume_test_silo_mode(SiloMode.REGION):
hook = ServiceHook.objects.get(application_id=self.internal_integration.application_id)
assert hook.application_id == self.internal_integration.application_id
assert hook.organization_id == self.internal_integration.owner_id
assert hook.actor_id == installation.id
assert hook.url == "https://newurl.com"
assert set(hook.events) == {
"issue.assigned",
"issue.created",
"issue.ignored",
"issue.resolved",
"issue.unresolved",
}
assert hook.project_id is None
# New test to check if the internal integration's webhook URL is updated correctly
self.get_success_response(
self.internal_integration.slug,
webhookUrl="https://updatedurl.com",
status_code=200,
)
self.internal_integration.refresh_from_db()
assert self.internal_integration.webhook_url == "https://updatedurl.com"
# Verify the service hook URL is also updated
hook.refresh_from_db()
assert hook.url == "https://updatedurl.com"
def test_can_update_name_with_non_unique_name(self) -> None:
sentry_app = self.create_sentry_app(name="Foo Bar", organization=self.organization)
deletions.exec_sync(sentry_app)
self.get_success_response(
self.published_app.slug,
name=sentry_app.name,
status_code=200,
)
def test_cannot_update_events_without_permissions(self) -> None:
response = self.get_error_response(
self.unpublished_app.slug,
name="NewName",
webhookUrl="https://newurl.com",
scopes=("project:read",),
events=("issue",),
status_code=400,
)
assert response.data == {"events": ["issue webhooks require the event:read permission."]}
def test_cannot_update_scopes_published_app(self) -> None:
response = self.get_error_response(
self.published_app.slug,
name="NewName",
webhookUrl="https://newurl.com",
scopes=("project:read",),
status_code=400,
)
assert response.data["detail"] == "Cannot update permissions on a published integration."
def test_add_service_hooks_and_update_scope(self) -> None:
# first install the app on two organizations
org1 = self.create_organization(name="Org1")
org2 = self.create_organization(name="Org2")
installation1 = self.create_sentry_app_installation(
organization=org1, slug=self.published_app.slug
)
installation2 = self.create_sentry_app_installation(
organization=org2, slug=self.published_app.slug
)
assert installation1.organization_id == org1.id
assert installation2.organization_id == org2.id
assert installation1.sentry_app == self.published_app
assert installation2.sentry_app == self.published_app
self.published_app.scope_list = ("event:write", "event:read")
self.published_app.save()
# for published integrations, it runs in a task
with self.tasks(), outbox_runner():
self.get_success_response(
self.published_app.slug,
webhookUrl="https://newurl.com",
scopes=("event:read", "event:write"),
events=("issue",),
status_code=200,
)
self.published_app.refresh_from_db()
assert set(self.published_app.scope_list) == {"event:write", "event:read"}
assert (
self.published_app.webhook_url == "https://newurl.com"
), f"Unexpected webhook URL: {self.published_app.webhook_url}"
# Check service hooks for each organization
with assume_test_silo_mode(SiloMode.REGION):
service_hooks_org1 = ServiceHook.objects.filter(
organization_id=org1.id, application_id=self.published_app.application_id
)
service_hooks_org2 = ServiceHook.objects.filter(
organization_id=org2.id, application_id=self.published_app.application_id
)
assert len(service_hooks_org1) > 0, f"No service hooks found for Org1 (ID: {org1.id})"
assert len(service_hooks_org2) > 0, f"No service hooks found for Org2 (ID: {org2.id})"
for hook in service_hooks_org1:
assert hook.application_id == self.published_app.application_id
assert hook.organization_id == org1.id
assert hook.actor_id == installation1.id
assert hook.url == "https://newurl.com"
assert set(hook.events) == {
"issue.assigned",
"issue.created",
"issue.ignored",
"issue.resolved",
"issue.unresolved",
}
assert hook.project_id is None
for hook in service_hooks_org2:
assert hook.application_id == self.published_app.application_id
assert hook.organization_id == org2.id
assert hook.actor_id == installation2.id
assert hook.url == "https://newurl.com"
assert set(hook.events) == {
"issue.assigned",
"issue.created",
"issue.ignored",
"issue.resolved",
"issue.unresolved",
}
assert hook.project_id is None
def test_update_existing_published_integration_with_webhooks(self) -> None:
org1 = self.create_organization()
org2 = self.create_organization()
# add the webhooks but no events yet
published_app = self.create_sentry_app(
name="TestApp",
organization=self.organization,
webhook_url="https://oldurl.com",
scopes=("event:read", "event:write"),
published=True,
)
installation1 = self.create_sentry_app_installation(
slug=published_app.slug, organization=org1
)
installation2 = self.create_sentry_app_installation(
slug=published_app.slug, organization=org2
)
# Assert initial service hooks are created
with assume_test_silo_mode(SiloMode.REGION):
service_hooks_org1 = ServiceHook.objects.filter(
organization_id=org1.id, application_id=published_app.application_id
)
service_hooks_org2 = ServiceHook.objects.filter(
organization_id=org2.id, application_id=published_app.application_id
)
assert len(service_hooks_org1) > 0, "No service hooks found for Org1"
assert len(service_hooks_org2) > 0, "No service hooks found for Org2"
for hook in service_hooks_org1:
assert hook.url == "https://oldurl.com"
assert set(hook.events) == set()
for hook in service_hooks_org2:
assert hook.url == "https://oldurl.com"
assert set(hook.events) == set()
# Update the webhook URL and events
with self.tasks():
self.get_success_response(
published_app.slug,
webhookUrl="https://newurl.com",
events=("issue",),
status_code=200,
)
# Assert the service hooks are updated
published_app.refresh_from_db()
assert published_app.webhook_url == "https://newurl.com"
with assume_test_silo_mode(SiloMode.REGION):
service_hooks_org1 = ServiceHook.objects.filter(
organization_id=org1.id, application_id=published_app.application_id
)
service_hooks_org2 = ServiceHook.objects.filter(
organization_id=org2.id, application_id=published_app.application_id
)
for hook in service_hooks_org1:
assert hook.application_id == published_app.application_id
assert hook.organization_id == org1.id
assert hook.actor_id == installation1.id
assert hook.url == "https://newurl.com"
assert set(hook.events) == {
"issue.assigned",
"issue.created",
"issue.ignored",
"issue.resolved",
"issue.unresolved",
}
assert hook.project_id is None
for hook in service_hooks_org2:
assert hook.application_id == published_app.application_id
assert hook.organization_id == org2.id
assert hook.actor_id == installation2.id
assert hook.url == "https://newurl.com"
assert set(hook.events) == {
"issue.assigned",
"issue.created",
"issue.ignored",
"issue.resolved",
"issue.unresolved",
}
assert hook.project_id is None
def test_cannot_update_features_published_app_permissions(self) -> None:
response = self.get_error_response(
self.published_app.slug,
features=[1, 2, 3],
status_code=400,
)
assert response.data["detail"] == "Cannot update features on a published integration."
def test_cannot_update_non_owned_apps(self) -> None:
app = self.create_sentry_app(name="SampleApp", organization=self.create_organization())
response = self.get_error_response(
app.slug,
name="NewName",
webhookUrl="https://newurl.com",
status_code=403,
)
assert (
response.data["detail"]
== "User must be in the app owner's organization for unpublished apps"
)
assert response.data["context"] == {
"user_organizations": [self.organization.slug],
}
def test_superuser_can_update_popularity(self) -> None:
self.login_as(user=self.superuser, superuser=True)
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
assert not app.date_published
popularity = 100
self.get_success_response(
app.slug,
popularity=popularity,
status_code=200,
)
assert SentryApp.objects.get(id=app.id).popularity == popularity
@override_options({"staff.ga-rollout": True})
def test_staff_can_update_popularity(self) -> None:
self.login_as(user=self.staff_user, staff=True)
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
assert not app.date_published
popularity = 100
self.get_success_response(
app.slug,
popularity=popularity,
status_code=200,
)
assert SentryApp.objects.get(id=app.id).popularity == popularity
def test_nonsuperuser_nonstaff_cannot_update_popularity(self) -> None:
app = self.create_sentry_app(
name="SampleApp", organization=self.organization, popularity=self.popularity
)
self.get_success_response(
app.slug,
popularity=100,
status_code=200,
)
assert SentryApp.objects.get(id=app.id).popularity == self.popularity
def test_superuser_can_publish_apps(self) -> None:
self.login_as(user=self.superuser, superuser=True)
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
assert not app.date_published
self.get_success_response(
app.slug,
status="published",
status_code=200,
)
app.refresh_from_db()
assert app.status == SentryAppStatus.PUBLISHED
assert app.date_published
@override_options({"staff.ga-rollout": True})
def test_staff_can_publish_apps(self) -> None:
self.login_as(user=self.staff_user, staff=True)
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
assert not app.date_published
self.get_success_response(
app.slug,
status="published",
status_code=200,
)
app.refresh_from_db()
assert app.status == SentryAppStatus.PUBLISHED
assert app.date_published
def test_nonsuperuser_nonstaff_cannot_publish_apps(self) -> None:
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
self.get_success_response(
app.slug,
status="published",
status_code=200,
)
assert SentryApp.objects.get(id=app.id).status == SentryAppStatus.UNPUBLISHED
@with_feature({"organizations:integrations-event-hooks": False})
def test_cannot_add_error_created_hook_without_flag(self) -> None:
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
self.get_error_response(
app.slug,
events=["error"],
status_code=403,
)
@with_feature("organizations:integrations-event-hooks")
def test_can_add_error_created_hook_with_flag(self) -> None:
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
self.get_success_response(
app.slug,
events=["error"],
scopes=("event:read",),
status_code=200,
)
def test_staff_can_mutate_scopes(self) -> None:
self.login_as(user=self.staff_user, staff=True)
app = self.create_sentry_app(
name="SampleApp", organization=self.organization, scopes=("event:read",)
)
assert SentryApp.objects.get(id=app.id).get_scopes() == ["event:read"]
# scopes is empty array which should not be treated as none
self.get_success_response(
app.slug,
scopes=(),
status_code=200,
)
assert SentryApp.objects.get(id=app.id).get_scopes() == []
# update with hierarchy
self.get_success_response(
app.slug,
scopes=("event:write",),
status_code=200,
)
assert SentryApp.objects.get(id=app.id).get_scopes() == ["event:read", "event:write"]
def test_remove_scopes(self) -> None:
app = self.create_sentry_app(
name="SampleApp", organization=self.organization, scopes=("event:read",)
)
assert SentryApp.objects.get(id=app.id).get_scopes() == ["event:read"]
# scopes is empty array which should not be treated as none
self.get_success_response(
app.slug,
scopes=(),
status_code=200,
)
assert SentryApp.objects.get(id=app.id).get_scopes() == []
def test_keep_scope_unchanged(self) -> None:
app = self.create_sentry_app(
name="SampleApp", organization=self.organization, scopes=("event:read",)
)
# scopes is None here
self.get_success_response(
app.slug,
status_code=200,
)
assert SentryApp.objects.get(id=app.id).get_scopes() == ["event:read"]
def test_updating_scopes_maintains_scope_hierarchy(self) -> None:
app = self.create_sentry_app(
name="SampleApp", organization=self.organization, scopes=["event:read", "event:write"]
)
self.get_success_response(
app.slug,
scopes=("event:write",),
status_code=200,
)
assert SentryApp.objects.get(id=app.id).get_scopes() == ["event:read", "event:write"]
@patch("sentry.analytics.record")
def test_bad_schema(self, record: MagicMock) -> None:
app = self.create_sentry_app(name="SampleApp", organization=self.organization)
schema = {"bad_key": "bad_value"}
response = self.get_error_response(
app.slug,
schema=schema,
status_code=400,
)
assert response.data == {"schema": ["'elements' is a required property"]}
assert_last_analytics_event(
record,
SentryAppSchemaValidationError(
user_id=self.user.id,
organization_id=self.organization.id,
sentry_app_id=app.id,
sentry_app_name="SampleApp",
error_message="'elements' is a required property",
schema=orjson.dumps(schema).decode(),
),
)
def test_no_webhook_public_integration(self) -> None:
response = self.get_error_response(
self.published_app.slug,
webhookUrl="",
status_code=400,
)
assert response.data == {"webhookUrl": ["webhookUrl required for public integrations"]}
def test_no_webhook_has_events(self) -> None:
response = self.get_error_response(
self.internal_integration.slug, webhookUrl="", events=("issue",), status_code=400
)
assert response.data == {
"webhookUrl": ["webhookUrl required if webhook events are enabled"]
}
def test_no_webhook_has_alerts(self) -> None:
# make sure we test at least one time with the webhookUrl set to none before the put request
self.internal_integration.webhook_url = None
self.internal_integration.save()
response = self.get_error_response(
self.internal_integration.slug, isAlertable=True, status_code=400
)
assert response.data == {
"webhookUrl": ["webhookUrl required if alert rule action is enabled"]
}
def test_set_allowed_origins(self) -> None:
self.get_success_response(
self.published_app.slug,
allowedOrigins=["google.com", "sentry.io"],
status_code=200,
)
assert self.published_app.application.get_allowed_origins() == ["google.com", "sentry.io"]
def test_allowed_origins_with_star(self) -> None:
response = self.get_error_response(
self.published_app.slug,
allowedOrigins=["*.google.com"],
status_code=400,
)
assert response.data == {"allowedOrigins": ["'*' not allowed in origin"]}
def test_members_cant_update(self) -> None:
with assume_test_silo_mode(SiloMode.REGION):
# create extra owner because we are demoting one
self.create_member(
organization=self.organization, user=self.create_user(), role="owner"
)
member_om = OrganizationMember.objects.get(
user_id=self.user.id, organization=self.organization
)
member_om.role = "member"
member_om.save()
self.get_error_response(
self.unpublished_app.slug,
scopes=("member:read",),
status_code=403,
)
def test_create_integration_exceeding_scopes(self) -> None:
with assume_test_silo_mode(SiloMode.REGION):
# create extra owner because we are demoting one
self.create_member(
organization=self.organization, user=self.create_user(), role="owner"
)
member_om = OrganizationMember.objects.get(
user_id=self.user.id, organization=self.organization
)
member_om.role = "manager"
member_om.save()
response = self.get_error_response(
self.unpublished_app.slug,
scopes=("org:read", "org:write", "org:admin"),
status_code=400,
)
assert response.data == {
"scopes": [
"Requested permission of org:admin exceeds requester's permission. Please contact an administrator to make the requested change.",
]
}
def test_cannot_update_partner_apps(self) -> None:
self.published_app.update(metadata={"partnership_restricted": True})
self.get_error_response(
self.published_app.slug,
name="A Company",
webhookUrl="https://newurl.com",
redirectUrl="https://newredirecturl.com",
isAlertable=True,
status_code=403,
)
@control_silo_test
| UpdateSentryAppDetailsTest |
python | pytorch__pytorch | test/functorch/test_eager_transforms.py | {
"start": 7402,
"end": 35662
} | class ____(TestCase):
def test_primitive(self, device):
x = torch.randn([], device=device)
result = grad(torch.sin)(x)
self.assertEqual(result, torch.cos(x))
def test_composite_simple(self, device):
x = torch.randn(2, 3, 4, device=device)
result = grad(lambda x: torch.flatten(x).sum())(x)
self.assertEqual(result, torch.ones_like(x))
def test_fn_with_kwargs(self, device):
def foo(x, y):
return (x * y).sum()
x = torch.randn(3, device=device)
y = torch.randn(3, device=device)
expected = grad(foo)(x, y)
result = grad(foo)(x, y=y)
self.assertEqual(result, expected)
def test_composite_complicated(self, device):
x = torch.randn(3, device=device)
y = torch.randn(3, 5, device=device)
def foo(x, y):
result = x @ y
return result.sum()
result = grad(foo)(x, y)
x.requires_grad_()
out = foo(x, y)
(expected,) = torch.autograd.grad(out, x)
self.assertEqual(result, expected)
def test_composite_two_ops(self, device):
N, C = 2, 5
y = torch.randn(N, C, device=device)
targets = torch.randint(0, C, (N,), device=device)
def foo(y, targets):
return F.cross_entropy(y, targets)
result = grad(foo)(y, targets)
y.requires_grad_()
(expected,) = torch.autograd.grad(foo(y, targets), y)
self.assertEqual(result, expected)
def _test_attributes(self, get_attr_lambda, device):
x = torch.randn(2, 3, 5, dtype=torch.double, device=device)
expected = get_attr_lambda(x)
def foo(x):
self.assertEqual(get_attr_lambda(x), expected)
return x.sum()
grad(foo)(x)
def test_shape(self, device):
self._test_attributes(lambda x: x.shape, device)
def test_dtype(self, device):
self._test_attributes(lambda x: x.dtype, device)
def test_is_cuda(self, device):
self._test_attributes(lambda x: x.is_cuda, device)
def test_numel(self, device):
self._test_attributes(lambda x: x.numel(), device)
def test_layout_sparse(self, device):
indices = torch.tensor([[0, 1, 1], [2, 0, 2]], device=device)
values = torch.tensor([3.0, 4.0, 5.0], device=device)
sparse_x = torch.sparse_coo_tensor(indices, values, (2, 3), device=device)
# Verify the input is sparse
self.assertEqual(sparse_x.layout, torch.sparse_coo)
def foo(x):
# assert GradTrackingTensor still reports sparse layout
self.assertEqual(x.layout, torch.sparse_coo)
return x.coalesce()._values().sum()
result = grad(foo)(sparse_x)
# The gradient should also be sparse
self.assertEqual(result.layout, torch.sparse_coo)
def test_inplace(self, device):
x = torch.randn([], device=device)
def foo(x):
return x.clone().sin_()
result = grad(foo)(x)
self.assertEqual(result, x.cos())
def test_inplace_on_view(self, device):
x = torch.randn(3, device=device)
def foo(x):
y = x.clone()
y0 = y[0]
y0.sin_()
return y.sum()
result = grad(foo)(x)
x.requires_grad_()
out = foo(x)
(expected,) = torch.autograd.grad(out, x)
self.assertEqual(result, expected)
def test_inplace_on_view_base(self, device):
x = torch.randn(3, device=device)
def foo(x):
y = x.clone()
y0 = y[0]
y.sin_()
return y0
result = grad(foo)(x)
x.requires_grad_()
out = foo(x)
(expected,) = torch.autograd.grad(out, x)
self.assertEqual(result, expected)
def test_inplace_on_captures(self, device):
x = torch.tensor([1.0, 2.0, 3.0], device=device)
captured = torch.randn(3, device=device)
def foo(x):
captured.copy_(x)
return (x * captured).sum()
with self.assertRaisesRegex(RuntimeError, "mutate a captured Tensor"):
grad(foo)(x)
def test_nesting_simple(self, device):
x = torch.randn([], device=device)
result = grad(grad(torch.sin))(x)
self.assertEqual(result, -torch.sin(x))
@skipIfTorchDynamo("Ref: https://github.com/pytorch/pytorch/issues/103613")
def test_escaped_wrappers_are_marked_as_dead(self, device):
x = torch.randn([], device=device)
escaped = []
def foo(x):
y = x.sin()
escaped.append(y)
return y
grad(foo)(x)
self.assertEqual(torch._C._functorch.dlevel(escaped[0]), -1)
@skipIfTorchDynamo("Ref: https://github.com/pytorch/pytorch/issues/103613")
def test_escaped_wrappers_are_ignored(self, device):
x = torch.randn([], device=device)
escaped = []
def foo(x):
y = x.sin()
escaped.append(y)
return y
grad(foo)(x)
something = escaped[0].sum()
self.assertEqual(torch._C._functorch.dlevel(something), 0)
self.assertEqual(something, x.sin().sum())
def test_manual_seed_inside_grad(self, device):
x = torch.randn([], device=device)
def f(x):
torch.manual_seed(0)
return x * torch.randn_like(x)
with freeze_rng_state():
result = grad(f)(x)
x.requires_grad_()
(expected,) = torch.autograd.grad(f(x), x)
self.assertEqual(result, expected)
def test_vjp(self, device):
x = torch.randn([], device=device)
out, vjp_fn = vjp(torch.sin, x)
self.assertEqual(out, x.sin())
v = torch.randn([], device=device)
(result,) = vjp_fn(v)
self.assertEqual(result, v * x.cos())
def test_vjp_two_outputs(self, device):
def f(x):
return x, x
result, vjp_fn = vjp(f, torch.tensor(1.0))
vjp_fn(result)
def test_conj_bit(self):
x = torch.tensor(1 + 1j)
def foo(x):
assert not x.is_conj()
y = x.conj()
assert y.is_conj()
return y.abs()
res = grad(foo)(x)
with torch.no_grad():
self.assertEqual(res, torch.ones_like(res) * torch.sgn(x))
def test_composed_with_autograd(self, device):
x = torch.randn([], requires_grad=True, device=device)
y = grad(torch.sin)(x)
(result,) = torch.autograd.grad(y, x)
self.assertEqual(result, -x.sin())
def test_grad_of_vjp_composition(self, device):
x = torch.randn([], device=device)
y = torch.randn([], device=device)
def foo(x, y):
out, vjp_fn = vjp(torch.sin, x)
return grad(lambda y: vjp_fn(y)[0])(y)
result = foo(x, y)
expected = x.cos()
self.assertEqual(result, expected)
def test_vjp_of_grad_composition(self, device):
x = torch.randn([], device=device)
y = torch.randn([], device=device)
def foo(x, y):
out, vjp_fn = vjp(grad(torch.sin), x)
return vjp_fn(y)[0]
result = foo(x, y)
expected = -y * x.sin()
self.assertEqual(result, expected)
def test_grad_of_vjp_of_grad_composition(self, device):
x = torch.randn([], device=device)
y = torch.randn([], device=device)
def foo(x, y):
df, vjp_fn = vjp(grad(lambda x: -torch.cos(x)), x)
return grad(lambda y: vjp_fn(y)[0])(y)
result = foo(x, y)
expected = x.cos()
self.assertEqual(result, expected)
def test_views(self, device):
x = torch.randn([], requires_grad=True, device=device)
y = torch.randn([], requires_grad=True, device=device)
def silly_sin(x):
x = x.view([])
x = x.sin()
return x
def foo(x, y):
z1 = grad(silly_sin)(x)
z2 = torch.cos(y)
return z1 + z2
result = foo(x, y)
grads = torch.autograd.grad(result, [x, y])
self.assertEqual(grads[0], -x.sin())
self.assertEqual(grads[1], -y.sin())
def test_view_inplace_simple(self, device):
def foo(x):
x = x.clone()
x.view([]).sin_()
return x
x = torch.randn([], requires_grad=True, device=device)
result = grad(foo)(x)
self.assertEqual(result, x.cos())
def test_invalid_argnums(self, device):
x = torch.randn([])
y = torch.randn([])
with self.assertRaisesRegex(RuntimeError, "but only"):
grad(torch.mul, argnums=-3)(x, y)
with self.assertRaisesRegex(RuntimeError, "but only"):
grad(torch.mul, argnums=2)(x, y)
with self.assertRaisesRegex(RuntimeError, "int or Tuple"):
grad(torch.mul, argnums=[0])(x, y)
with self.assertRaisesRegex(RuntimeError, "must be int"):
grad(torch.mul, argnums=("0",))(x, y)
with self.assertRaisesRegex(RuntimeError, "must be unique"):
grad(torch.mul, argnums=(0, 0))(x, y)
with self.assertRaisesRegex(RuntimeError, "must be unique"):
grad(torch.mul, argnums=(0, -2))(x, y)
def test_argnums(self, device):
x = torch.randn([])
y = torch.randn([])
gx = grad(torch.mul, argnums=0)(x, y)
self.assertEqual(gx, y)
gy = grad(torch.mul, argnums=1)(x, y)
self.assertEqual(gy, x)
(gx,) = grad(torch.mul, argnums=(0,))(x, y)
self.assertEqual(gx, y)
gx, gy = grad(torch.mul, argnums=(0, 1))(x, y)
self.assertEqual(gx, y)
self.assertEqual(gy, x)
def test_out_of_order_argnums(self, device):
x = torch.randn([])
y = torch.randn([])
gy, gx = grad(torch.mul, argnums=(1, 0))(x, y)
self.assertEqual(gx, y)
self.assertEqual(gy, x)
def test_negative_argnums(self, device):
x = torch.randn([])
y = torch.randn([])
gx = grad(torch.mul, argnums=-2)(x, y)
self.assertEqual(gx, y)
gy = grad(torch.mul, argnums=-1)(x, y)
self.assertEqual(gy, x)
(gx,) = grad(torch.mul, argnums=(-2,))(x, y)
self.assertEqual(gx, y)
gx, gy = grad(torch.mul, argnums=(-2, -1))(x, y)
self.assertEqual(gx, y)
self.assertEqual(gy, x)
def test_grad_pytree_inputs(self, device):
x = torch.randn([], device=device)
def f(a, b):
x, y = a
return 1 * x + 2 * y + 3 * b["foo"]
args = ((x, x), {"foo": x})
gx, gy = grad(f)(*args)
self.assertEqual(gx, torch.tensor(1.0, device=device))
self.assertEqual(gy, torch.tensor(2.0, device=device))
((gx, gy),) = grad(f, argnums=(0,))(*args)
self.assertEqual(gx, torch.tensor(1.0, device=device))
self.assertEqual(gy, torch.tensor(2.0, device=device))
(gx, gy), gz = grad(f, argnums=(0, 1))(*args)
self.assertEqual(gx, torch.tensor(1.0, device=device))
self.assertEqual(gy, torch.tensor(2.0, device=device))
self.assertEqual(gz["foo"], torch.tensor(3.0, device=device))
def test_grad_aux_tensor(self, device):
x = torch.randn(3, device=device)
with self.assertRaisesRegex(
RuntimeError,
r"grad_and_value\(f\)\(\*args\): output of function f should be a tuple",
):
grad(lambda t: [t, t], has_aux=True)(x)
with self.assertRaisesRegex(
RuntimeError,
r"grad_and_value\(f\)\(\*args\): output of function f should be a tuple",
):
grad(lambda t: (t, t + 2, t + 3), has_aux=True)(x)
def f(t):
y = t.sin()
return y.sum(), t.cos()
out, aux = grad(f, has_aux=True)(x)
self.assertEqual(aux, x.cos())
self.assertEqual(out, x.cos())
def test_grad_aux_pytree(self, device):
def f(x):
y = x.sin()
return y.sum(), {"a": x.cos(), "b": [x.tan()]}
x = torch.randn(3, device=device)
out, aux = grad(f, has_aux=True)(x)
_, expected_aux = f(x)
self.assertEqual(aux, expected_aux)
self.assertEqual(out, x.cos())
for aux in [1, 1.0, "abc"]:
with self.assertRaisesRegex(
RuntimeError, r"Expected tensors, got unsupported type"
):
_ = grad(lambda x: (x.sum(), aux), has_aux=True)(x)
with self.assertRaisesRegex(
RuntimeError, r"Expected tensors, got unsupported type"
):
_ = grad(lambda x: (x.sum(), [x, aux]), has_aux=True)(x)
def test_zero_grad(self, device):
def f(x):
return (x["a"] ** 2.0).sum()
inps = {
"a": torch.randn(10, device=device) + 3,
"b": torch.randn(10, device=device),
}
grads = grad(f)(inps)
self.assertNotEqual(grads["a"].sum(), 0.0)
self.assertEqual(grads["b"].sum(), 0.0)
def test_unrelated_grad(self, device):
x = torch.tensor(1.0, device=device)
y = torch.tensor(2.0, device=device)
def unrelated(x):
return y
result = grad(unrelated)(x)
self.assertEqual(result, torch.zeros_like(x))
def test_unrelated_vjp(self, device):
x = torch.tensor(1.0, device=device)
y = torch.tensor(2.0, device=device)
v = torch.tensor(1.0, device=device)
def unrelated(x):
return y
out, vjp_fn = vjp(unrelated, x)
result = vjp_fn(v)
expected = (torch.zeros_like(x),)
self.assertEqual(result, expected)
def test_unrelated_vjp_multiple_inputs_outputs(self, device):
w = torch.tensor(3.0, device=device)
x = torch.tensor(4.0, device=device)
y = torch.tensor(2.0, device=device)
v = torch.tensor(1.0, device=device)
def unrelated(w, x):
return y, y, x
out, vjp_fn = vjp(unrelated, w, x)
result = vjp_fn((v, v, v))
expected = (torch.zeros_like(x), torch.ones_like(x))
self.assertEqual(result, expected)
# TODO: https://github.com/pytorch/functorch/issues/12
@onlyCPU
def test_unrelated_hessian(self, device):
N = 5
M = 3
W = torch.randn(N, M, device=device)
def f(x):
return W @ x
x = torch.randn(M)
result = jacrev(jacrev(f))(x)
expected = torch.zeros(N, M, M, device=device)
self.assertEqual(result, expected)
def test_vjp_pytree_input(self, device):
def f(x):
return x[0] * x[1][0]
x = torch.randn([], device=device)
v = torch.randn([], device=device)
out, vjp_fn = vjp(f, (x, (x, x)))
self.assertEqual(out, x * x)
result = vjp_fn(v)
self.assertEqual(result, ((x * v, (x * v, 0.0)),))
def test_vjp_pytree_output(self, device):
def f(x):
return x, (x, x)
x = torch.randn([], device=device)
v1 = torch.randn([], device=device)
v2 = torch.randn([], device=device)
v3 = torch.randn([], device=device)
_, vjp_fn = vjp(f, x)
(result,) = vjp_fn((v1, (v2, v3)))
self.assertEqual(result, v1 + v2 + v3)
def test_vjp_outputs_can_any_pytree(self, device):
x = torch.randn(2, 3, device=device)
t = torch.randn(2, 3, device=device)
for output in [None, ()]:
with self.assertRaisesRegex(
RuntimeError,
r"vjp\(f, \*primals\): Expected f to be a function that has non-empty output",
):
_, vjp_fn = vjp(lambda _: output, x)
vjp_fn(t)
for output in [1, True, 12.2, "abc"]:
with self.assertRaisesRegex(
RuntimeError,
r"vjp\(f, \*primals\): expected f\(\*primals\) to return only tensors",
):
_, vjp_fn = vjp(lambda _: output, x)
vjp_fn(t)
# Check list output
output, vjp_fn = vjp(lambda x: [x, x.sum()], x)
(vjp_out,) = vjp_fn([t, t.sum()])
assert isinstance(output, list) and len(output) == 2
assert isinstance(vjp_out, torch.Tensor)
# Check dict output
output, vjp_fn = vjp(lambda x: {"x": x, "xsum": x.sum()}, x)
(vjp_out,) = vjp_fn({"x": t, "xsum": t.sum()})
assert isinstance(output, dict) and len(output) == 2 and "xsum" in output
assert isinstance(vjp_out, torch.Tensor)
def composite_output(x):
out = x.sum()
return [
(out, {"a": x, "out": [x, out]}),
]
output, vjp_fn = vjp(composite_output, x)
(vjp_out,) = vjp_fn(
[
(t.sum(), {"a": t, "out": [t, t.sum()]}),
]
)
assert isinstance(output, list)
assert isinstance(output[0], tuple) and isinstance(output[0][1], dict)
assert isinstance(vjp_out, torch.Tensor)
def test_vjp_pytree_error(self, device):
def f(x):
return x, (x, x)
x = torch.randn([], device=device)
v1 = torch.randn([], device=device)
v2 = torch.randn([], device=device)
v3 = torch.randn([], device=device)
_, vjp_fn = vjp(f, x)
with self.assertRaisesRegex(RuntimeError, "Expected pytree structure"):
(result,) = vjp_fn(((v1, (v2, v3)),))
def test_vjp_aux_tensor(self, device):
x = torch.randn(3, device=device)
with self.assertRaisesRegex(
RuntimeError, r"vjp\(f, \*primals\): output of function f should be a tuple"
):
vjp(lambda t: [t, t], x, has_aux=True)
with self.assertRaisesRegex(
RuntimeError, r"vjp\(f, \*primals\): output of function f should be a tuple"
):
vjp(lambda t: (t, t + 2, t + 3), x, has_aux=True)
def f(t):
y = t.sin()
return y, t.cos()
out, vjp_fn, aux = vjp(f, x, has_aux=True)
self.assertEqual(aux, x.cos())
self.assertEqual(out, x.sin())
v = torch.randn(3, device=device)
(grad_x,) = vjp_fn(v)
self.assertEqual(grad_x, v * x.cos())
def test_vjp_aux_pytree(self, device):
def f(x):
y = x.sin()
return y, {"a": x.cos(), "b": [x.tan()]}
x = torch.randn(3, device=device)
out, vjp_fn, aux = vjp(f, x, has_aux=True)
expected_out, expected_aux = f(x)
self.assertEqual(out, expected_out)
self.assertEqual(aux, expected_aux)
v = torch.randn(3, device=device)
(grad_x,) = vjp_fn(v)
self.assertEqual(grad_x, v * x.cos())
for aux in [1, 1.0, "abc"]:
with self.assertRaisesRegex(
RuntimeError, r"Expected tensors, got unsupported type"
):
_ = vjp(lambda x: (x, aux), x, has_aux=True)
with self.assertRaisesRegex(
RuntimeError, r"Expected tensors, got unsupported type"
):
_ = vjp(lambda x: (x, [x, aux]), x, has_aux=True)
def test_functional_init(self, device):
class MLPClassifier(nn.Module):
def __init__(self, hidden_dim=32, n_classes=2):
super().__init__()
self.hidden_dim = hidden_dim
self.n_classes = n_classes
self.fc1 = nn.Linear(2, self.hidden_dim)
self.fc2 = nn.Linear(self.hidden_dim, self.n_classes)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.log_softmax(x, -1)
return x
B = 10
weights, fn, _ = functional_init(MLPClassifier, (B,), device=device)(32, 2)
inputs = torch.randn(B, 7, 2, device=device)
vmap(fn)(weights, (inputs,))
def test_functional_init_with_buffers(self, device):
class MLPClassifier(nn.Module):
def __init__(self, hidden_dim=32, n_classes=2):
super().__init__()
self.hidden_dim = hidden_dim
self.n_classes = n_classes
self.fc1 = nn.Linear(2, self.hidden_dim)
self.bn = nn.BatchNorm1d(self.hidden_dim, affine=True)
self.fc2 = nn.Linear(self.hidden_dim, self.n_classes)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.bn(x)
x = self.fc2(x)
x = F.log_softmax(x, -1)
return x
B = 10
weights, buffers, fn, _, _ = functional_init_with_buffers(
MLPClassifier, [B], device=device
)(32, 2)
inputs = torch.randn(B, 7, 2, device=device)
vmap(fn)(weights, buffers, (inputs,))
def test_advanced_indexing(self, device):
def f(value):
log_prob = torch.ones((), device=device)
val = torch.zeros(()) > 0
log_prob[val] = 0
return value
result = grad(f)(torch.randn((), device=device))
self.assertEqual(result, torch.ones_like(result))
def f2(value):
value = value.clone()
value[value > 0] = 0
return value.sum()
x = torch.randn(100, device=device)
result = grad(f2)(x)
self.assertEqual(result, (x <= 0).type_as(x))
def test_tensor_ctor_inside_grad(self, device):
def foo(x):
return x * torch.tensor(2.0, device=device)
x = torch.tensor(3.14, device=device)
functorch.grad(foo)(x)
@parametrize(
"op_list_data",
[
subtest(
(
[
vmap,
],
[(4, 2), (64, 3, 32, 32)],
),
name="vmap",
),
subtest(([vmap, vmap], [(4, 3, 2), (64, 3, 32, 32)]), name="vmap_vmap"),
subtest(
(
[
grad,
],
[(0,), [], (4, 2), (64, 3, 32, 32)],
),
name="grad",
),
subtest(
(
[grad, grad],
[
[],
],
),
name="grad_grad",
),
subtest(([vmap, grad], [(4, 2)]), name="vmap_grad"),
],
)
def test_tensor_print(self, device, op_list_data):
op_list, shapes = op_list_data
for dt in get_all_fp_dtypes():
data = [torch.randn(s, dtype=dt, device=device) for s in shapes]
for x in data:
buf = None
def foo(t):
nonlocal buf
buf = repr(t)
return t.mean()
fn = foo
bdim = 0
for op in reversed(op_list):
if op is vmap:
fn = op(fn, in_dims=bdim)
bdim += 1
else:
fn = op(fn)
expected = f"{repr(x)}"
for level, op in enumerate(op_list):
if op is grad:
expected = (
f"GradTrackingTensor(lvl={level + 1}, value={expected})"
)
elif op is vmap:
bdim -= 1
expected = f"BatchedTensor(lvl={level + 1}, bdim={bdim}, value={expected})"
fn(x)
buf = buf.replace("\n", "").replace(" ", "")
expected = expected.replace("\n", "").replace(" ", "")
self.assertEqual(expected, buf)
def test_print_captured_tensor_inside_transform(self, device):
x = torch.tensor([1.0, 2.0, 3.0], device=device)
out = None
def f(y):
nonlocal out
out = repr(x)
return y
vjp(f, torch.randn(4, device=device))
self.assertEqual(out, repr(x))
def test_no_grad_outside(self, device):
x = torch.randn([], device=device, requires_grad=True)
with torch.no_grad():
y = grad(torch.sin)(x)
self.assertEqual(y, x.cos())
self.assertFalse(y.requires_grad)
def test_no_grad_inside(self, device):
def f(x):
with torch.no_grad():
shift = x**2
return x**2 - shift
x = torch.randn([], device=device)
y = grad(f)(x)
self.assertEqual(y, 2 * x)
y = grad(grad(f))(x)
self.assertEqual(y, 2)
x = torch.randn([], device=device, requires_grad=True)
y = grad(f)(x)
(z,) = torch.autograd.grad(y, x)
self.assertEqual(z, 2)
def test_no_grad_mixed(self, device):
def f(x):
with torch.no_grad():
shift = x**2
return x**2 - shift
x = torch.randn([], device=device, requires_grad=True)
with torch.no_grad():
y = grad(f)(x)
self.assertEqual(y, 2 * x)
self.assertFalse(y.requires_grad)
def test_no_grad_nested_simple(self, device):
def h(x):
with torch.no_grad():
shift = grad(lambda x: 0.25 * x**4)(x)
return x**3 - shift
x = torch.tensor(1.5, device=device, requires_grad=True)
y = grad(h)(x)
self.assertEqual(y, 3 * x**2)
(z,) = torch.autograd.grad(y, x)
self.assertEqual(z, 6 * x)
def test_no_grad_nested_complicated(self, device):
def f(x):
with torch.no_grad():
shift = x**3
return x**3 - shift
def g(x):
r1 = grad(f)(x)
with torch.no_grad():
shift = grad(f)(x)
return r1 - shift
x = torch.randn([], requires_grad=True, device=device)
y = grad(g)(x)
# The only differential part of g is x ** 3
self.assertEqual(y, 6 * x)
(z,) = torch.autograd.grad(y, x)
self.assertEqual(z, 6)
def test_no_grad_value(self, device):
def h(x):
with torch.no_grad():
gvalue, value = grad_and_value(lambda x: x**3)(x)
return x**3 - value
x = torch.tensor(1.6, device=device, requires_grad=True)
y = grad(h)(x)
self.assertEqual(y, 3 * x**2)
(z,) = torch.autograd.grad(y, x)
self.assertEqual(z, 6 * x)
def test_no_grad_outside_vjp(self, device):
def h(x):
return x**2
x = torch.tensor(2.0, requires_grad=True, device=device)
with torch.no_grad():
out, vjp_fn = vjp(h, x)
(y,) = vjp_fn(torch.tensor(1.0, device=device))
self.assertEqual(y, 2 * x)
self.assertFalse(y.requires_grad)
self.assertFalse(out.requires_grad)
def test_no_grad_outside_vjp_fn(self, device):
def h(x):
return x**2
x = torch.tensor(3.14, requires_grad=True, device=device)
out, vjp_fn = vjp(h, x)
with torch.no_grad():
(y,) = vjp_fn(torch.tensor(1.0, device=device))
self.assertEqual(y, 2 * x)
self.assertFalse(y.requires_grad)
self.assertTrue(out.requires_grad)
(z,) = torch.autograd.grad(out, x)
self.assertEqual(z, 2 * x)
def test_no_grad_outside_vjp_only(self, device):
def h(x):
return x**2
x = torch.tensor(3.14, requires_grad=True, device=device)
with torch.no_grad():
out, vjp_fn = vjp(h, x)
(y,) = vjp_fn(torch.tensor(1.0, device=device))
self.assertEqual(y, 2 * x)
self.assertFalse(out.requires_grad)
# This one is a little weird...
self.assertTrue(y.requires_grad)
(z,) = torch.autograd.grad(y, x)
self.assertEqual(z, 2)
@markDynamoStrictTest
| TestGradTransform |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 72472,
"end": 77469
} | class ____(MoshiPreTrainedModel, GenerationMixin):
input_modalities = ("text",)
# Copied from transformers.models.gemma.modeling_gemma.GemmaForCausalLM.__init__ with Gemma->Moshi
def __init__(self, config):
super().__init__(config)
self.model = MoshiModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs,
) -> Union[tuple, MoshiCausalLMOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from transformers import AutoTokenizer, MoshiForCausalLM
>>> model = MoshiForCausalLM.from_pretrained("kmhf/hf-moshiko")
>>> tokenizer = AutoTokenizer.from_pretrained("kmhf/hf-moshiko")
>>> prompt = "What is your favorite condiment?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is your favorite condiment?"
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
# Upcast to float if we need to compute the loss to avoid potential precision issues
logits = logits.float()
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
shift_logits = shift_logits.view(-1, self.config.vocab_size)
shift_labels = shift_labels.view(-1)
shift_labels = shift_labels.to(shift_logits.device)
loss = self.loss_function(
shift_logits,
shift_labels,
vocab_size=self.config.vocab_size,
**kwargs,
)
if not return_dict:
output = (
logits,
hidden_states,
) + outputs[1:]
return (loss,) + output if loss is not None else output
return MoshiCausalLMOutputWithPast(
loss=loss,
logits=logits,
last_hidden_state=hidden_states, # Ignore copy
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring(
custom_intro="""
The original Moshi model with an audio encoder, a Moshi depth decoder and a Moshi decoder, for speech-to-speech.
"""
)
| MoshiForCausalLM |
python | pallets__click | src/click/exceptions.py | {
"start": 9662,
"end": 9954
} | class ____(RuntimeError):
"""An exception that indicates that the application should exit with some
status code.
:param code: the status code to exit with.
"""
__slots__ = ("exit_code",)
def __init__(self, code: int = 0) -> None:
self.exit_code: int = code
| Exit |
python | doocs__leetcode | solution/1400-1499/1462.Course Schedule IV/Solution2.py | {
"start": 0,
"end": 724
} | class ____:
def checkIfPrerequisite(
self, n: int, prerequisites: List[List[int]], queries: List[List[int]]
) -> List[bool]:
f = [[False] * n for _ in range(n)]
g = [[] for _ in range(n)]
indeg = [0] * n
for a, b in prerequisites:
g[a].append(b)
indeg[b] += 1
q = deque(i for i, x in enumerate(indeg) if x == 0)
while q:
i = q.popleft()
for j in g[i]:
f[i][j] = True
for h in range(n):
f[h][j] = f[h][j] or f[h][i]
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return [f[a][b] for a, b in queries]
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/attributes.py | {
"start": 50656,
"end": 52759
} | class ____:
__slots__ = ()
collection: bool
_is_has_collection_adapter = True
def _dispose_previous_collection(
self,
state: InstanceState[Any],
collection: _AdaptedCollectionProtocol,
adapter: CollectionAdapter,
fire_event: bool,
) -> None:
raise NotImplementedError()
@overload
def get_collection(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
user_data: Literal[None] = ...,
passive: Literal[PassiveFlag.PASSIVE_OFF] = ...,
) -> CollectionAdapter: ...
@overload
def get_collection(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
user_data: _AdaptedCollectionProtocol = ...,
passive: PassiveFlag = ...,
) -> CollectionAdapter: ...
@overload
def get_collection(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
user_data: Optional[_AdaptedCollectionProtocol] = ...,
passive: PassiveFlag = ...,
) -> Union[
Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter
]: ...
def get_collection(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
user_data: Optional[_AdaptedCollectionProtocol] = None,
passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
) -> Union[
Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter
]:
raise NotImplementedError()
def set(
self,
state: InstanceState[Any],
dict_: _InstanceDict,
value: Any,
initiator: Optional[AttributeEventToken] = None,
passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
check_old: Any = None,
pop: bool = False,
_adapt: bool = True,
) -> None:
raise NotImplementedError()
if TYPE_CHECKING:
def _is_collection_attribute_impl(
impl: _AttributeImpl,
) -> TypeGuard[_CollectionAttributeImpl]: ...
else:
_is_collection_attribute_impl = operator.attrgetter("collection")
| _HasCollectionAdapter |
python | django__django | tests/template_tests/filter_tests/test_wordcount.py | {
"start": 868,
"end": 1236
} | class ____(SimpleTestCase):
def test_empty_string(self):
self.assertEqual(wordcount(""), 0)
def test_count_one(self):
self.assertEqual(wordcount("oneword"), 1)
def test_count_multiple(self):
self.assertEqual(wordcount("lots of words"), 3)
def test_non_string_input(self):
self.assertEqual(wordcount(123), 1)
| FunctionTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py | {
"start": 41669,
"end": 45112
} | class ____(GKEOperatorMixin, KubernetesCreateResourceOperator):
"""
Create a resource in the specified Google Kubernetes Engine cluster.
This Operator assumes that the system has gcloud installed and has configured a
connection id with a service account.
.. seealso::
For more detail about Kubernetes Engine authentication have a look at the reference:
https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl#internal_ip
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GKECreateCustomResourceOperator`
:param location: The name of the Google Kubernetes Engine zone or region in which the
cluster resides, e.g. 'us-central1-a'
:param cluster_name: The name of the Google Kubernetes Engine cluster.
:param use_internal_ip: Use the internal IP address as the endpoint.
:param use_dns_endpoint: Use the DNS address as the endpoint.
:param project_id: The Google Developers Console project id
:param gcp_conn_id: The Google cloud connection id to use. This allows for
users to specify a service account.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or 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] = tuple(
set(GKEOperatorMixin.template_fields) | set(KubernetesCreateResourceOperator.template_fields)
)
def __init__(
self,
location: str,
cluster_name: str,
use_internal_ip: bool = False,
use_dns_endpoint: bool = False,
project_id: str = PROVIDE_PROJECT_ID,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.project_id = project_id
self.location = location
self.cluster_name = cluster_name
self.gcp_conn_id = gcp_conn_id
self.use_internal_ip = use_internal_ip
self.use_dns_endpoint = use_dns_endpoint
self.impersonation_chain = impersonation_chain
if self.gcp_conn_id is None:
raise AirflowException(
"The gcp_conn_id parameter has become required. If you want to use Application Default "
"Credentials (ADC) strategy for authorization, create an empty connection "
"called `google_cloud_default`.",
)
# There is no need to manage the kube_config file, as it will be generated automatically.
# All Kubernetes parameters (except config_file) are also valid for the GKECreateCustomResourceOperator.
if self.config_file:
raise AirflowException(
"config_file is not an allowed parameter for the GKECreateCustomResourceOperator."
)
| GKECreateCustomResourceOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 56700,
"end": 63217
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "search_query_performance_report_hourly"
report_file = "search_query_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "search_query_performance_report_hourly_incremental"
report_file_with_records_further_start_date = "search_query_performance_report_hourly_with_records_further_config_start_date"
state_file_legacy = "hourly_reports_state_legacy"
state_file_after_migration = "hourly_reports_state_after_migration"
state_file_after_migration_with_cursor_further_config_start_date = (
"hourly_reports_state_after_migration_with_cursor_further_config_start_date"
)
incremental_report_file_with_records_further_cursor = "search_query_performance_report_hourly_incremental_with_records_further_cursor"
def mock_report_apis(self):
self.mock_user_query_api(response_template="user_query")
self.mock_accounts_search_api(
response_template="accounts_search_for_report",
body=b'{"PageInfo": {"Index": 0, "Size": 1000}, "Predicates": [{"Field": "UserId", "Operator": "Equals", "Value": "123456789"}], "ReturnAdditionalFields": "TaxCertificate,AccountMode"}',
)
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "SearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "SearchQueryPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountName", "AccountNumber", "AccountId", "TimePeriod", "CampaignName", "CampaignId", "AdGroupName", "AdGroupId", "AdId", "AdType", "DestinationUrl", "BidMatchType", "DeliveredMatchType", "CampaignStatus", "AdStatus", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "AveragePosition", "SearchQuery", "Keyword", "AdGroupCriterionId", "Conversions", "ConversionRate", "CostPerConversion", "Language", "KeywordId", "Network", "TopVsOther", "DeviceType", "DeviceOS", "Assists", "Revenue", "ReturnOnAdSpend", "CostPerAssist", "RevenuePerConversion", "RevenuePerAssist", "AccountStatus", "AdGroupStatus", "KeywordStatus", "CampaignType", "CustomerId", "CustomerName", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllReturnOnAdSpend", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "TopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AllConversionsQualified"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2024}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
# for second read
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "SearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "SearchQueryPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountName", "AccountNumber", "AccountId", "TimePeriod", "CampaignName", "CampaignId", "AdGroupName", "AdGroupId", "AdId", "AdType", "DestinationUrl", "BidMatchType", "DeliveredMatchType", "CampaignStatus", "AdStatus", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "AveragePosition", "SearchQuery", "Keyword", "AdGroupCriterionId", "Conversions", "ConversionRate", "CostPerConversion", "Language", "KeywordId", "Network", "TopVsOther", "DeviceType", "DeviceOS", "Assists", "Revenue", "ReturnOnAdSpend", "CostPerAssist", "RevenuePerConversion", "RevenuePerAssist", "AccountStatus", "AdGroupStatus", "KeywordStatus", "CampaignType", "CustomerId", "CustomerName", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllReturnOnAdSpend", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "TopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AllConversionsQualified"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 6, "Month": 5, "Year": 2024}, "CustomDateRangeEnd": {"Day": 8, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
# for no config start date test
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "SearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "SearchQueryPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountName", "AccountNumber", "AccountId", "TimePeriod", "CampaignName", "CampaignId", "AdGroupName", "AdGroupId", "AdId", "AdType", "DestinationUrl", "BidMatchType", "DeliveredMatchType", "CampaignStatus", "AdStatus", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "AveragePosition", "SearchQuery", "Keyword", "AdGroupCriterionId", "Conversions", "ConversionRate", "CostPerConversion", "Language", "KeywordId", "Network", "TopVsOther", "DeviceType", "DeviceOS", "Assists", "Revenue", "ReturnOnAdSpend", "CostPerAssist", "RevenuePerConversion", "RevenuePerAssist", "AccountStatus", "AdGroupStatus", "KeywordStatus", "CampaignType", "CustomerId", "CustomerName", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllReturnOnAdSpend", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "TopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AllConversionsQualified"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2023}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
self.mock_generate_report_api(
endpoint="Poll", response_template="generate_report_poll", body=b'{"ReportRequestId": "thisisthereport_requestid"}'
)
| TestSearchQueryPerformanceReportHourlyStream |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 18231,
"end": 18901
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->ChineseCLIPText
| ChineseCLIPTextIntermediate |
python | django__django | tests/queries/tests.py | {
"start": 85734,
"end": 86559
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Note.objects.create(note="n1", misc="foo", id=1)
def test_ticket14729(self):
# Test representation of raw query with one or few parameters passed as
# list
query = "SELECT * FROM queries_note WHERE note = %s"
params = ["n1"]
qs = Note.objects.raw(query, params=params)
self.assertEqual(
repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1>"
)
query = "SELECT * FROM queries_note WHERE note = %s and misc = %s"
params = ["n1", "foo"]
qs = Note.objects.raw(query, params=params)
self.assertEqual(
repr(qs),
"<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>",
)
| RawQueriesTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/slots3.py | {
"start": 139,
"end": 337
} | class ____:
def __init__(self, *, slot: str): ...
def __set__(self, instance: object, value: object) -> None: ...
def __get__(self, instance: object, owner: Any) -> Any: ...
| MyDescriptor |
python | doocs__leetcode | lcof/面试题58 - I. 翻转单词顺序/Solution2.py | {
"start": 0,
"end": 104
} | class ____:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 179,
"end": 247
} | class ____:
if ...:
def __eq__(self, other): ...
| MaybeEqIf |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 1067,
"end": 1733
} | class ____(TestCase):
def test_basic(self):
y1 = [0, 0, 1, 0]
y2 = [0, 0, 0, 0]
y3 = [1, 0, 1, 0]
assert np.any(y1)
assert np.any(y3)
assert not np.any(y2)
def test_nd(self):
y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
assert np.any(y1)
assert_equal(np.any(y1, axis=0), [1, 1, 0])
assert_equal(np.any(y1, axis=1), [0, 1, 1])
assert_equal(np.any(y1), True)
assert isinstance(np.any(y1, axis=1), np.ndarray)
# YYY: deduplicate
def test_method_vs_function(self):
y = np.array([[0, 1, 0, 3], [1, 0, 2, 0]])
assert_equal(np.any(y), y.any())
| TestAny |
python | huggingface__transformers | src/transformers/models/aria/modular_aria.py | {
"start": 40512,
"end": 40899
} | class ____(ProcessingKwargs, total=False):
images_kwargs: AriaImagesKwargs
_defaults = {
"text_kwargs": {
"padding": False,
"return_mm_token_type_ids": False,
},
"images_kwargs": {
"max_image_size": 980,
"split_image": False,
},
"return_tensors": TensorType.PYTORCH,
}
| AriaProcessorKwargs |
python | kamyu104__LeetCode-Solutions | Python/find-minimum-time-to-reach-last-room-i.py | {
"start": 89,
"end": 1274
} | class ____(object):
def minTimeToReach(self, moveTime):
"""
:type moveTime: List[List[int]]
:rtype: int
"""
def dijkstra(start, target):
DIRECTIONS = [(1, 0), (0, 1), (-1, 0), (0, -1)]
dist = [[float("inf")]*len(moveTime[0]) for _ in xrange(len(moveTime))]
dist[start[0]][start[1]] = 0
min_heap = [(dist[start[0]][start[1]], start[0], start[1])]
while min_heap:
curr, i, j = heapq.heappop(min_heap)
if curr != dist[i][j]:
continue
if (i, j) == target:
break
for di, dj in DIRECTIONS:
ni, nj = i+di, j+dj
c = 1
if not (0 <= ni < len(moveTime) and 0 <= nj < len(moveTime[0]) and dist[ni][nj] > max(moveTime[ni][nj], curr)+c):
continue
dist[ni][nj] = max(moveTime[ni][nj], curr)+c
heapq.heappush(min_heap, (dist[ni][nj], ni, nj))
return dist[target[0]][target[1]]
return dijkstra((0, 0), (len(moveTime)-1, len(moveTime[0])-1))
| Solution |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/api_test.py | {
"start": 7715,
"end": 10152
} | class ____(TestCase):
def setUp(self) -> None:
self._params = RendezvousParameters(
backend="dummy_backend",
endpoint="dummy_endpoint",
run_id="dummy_run_id",
min_nodes=1,
max_nodes=1,
)
self._registry = RendezvousHandlerRegistry()
@staticmethod
def _create_handler(params: RendezvousParameters) -> RendezvousHandler:
return _DummyRendezvousHandler(params)
def test_register_registers_once_if_called_twice_with_same_creator(self) -> None:
self._registry.register("dummy_backend", self._create_handler)
self._registry.register("dummy_backend", self._create_handler)
def test_register_raises_error_if_called_twice_with_different_creators(
self,
) -> None:
self._registry.register("dummy_backend", self._create_handler)
other_create_handler = lambda p: _DummyRendezvousHandler(p) # noqa: E731
with self.assertRaisesRegex(
ValueError,
r"^The rendezvous backend 'dummy_backend' cannot be registered with "
rf"'{other_create_handler}' as it is already registered with '{self._create_handler}'.$",
):
self._registry.register("dummy_backend", other_create_handler)
def test_create_handler_returns_handler(self) -> None:
self._registry.register("dummy_backend", self._create_handler)
handler = self._registry.create_handler(self._params)
self.assertIsInstance(handler, _DummyRendezvousHandler)
self.assertIs(handler.params, self._params)
def test_create_handler_raises_error_if_backend_is_not_registered(self) -> None:
with self.assertRaisesRegex(
ValueError,
r"^The rendezvous backend 'dummy_backend' is not registered. Did you forget to call "
r"`register`\?$",
):
self._registry.create_handler(self._params)
def test_create_handler_raises_error_if_backend_names_do_not_match(self) -> None:
self._registry.register("dummy_backend_2", self._create_handler)
with self.assertRaisesRegex(
RuntimeError,
r"^The rendezvous backend 'dummy_backend' does not match the requested backend "
r"'dummy_backend_2'.$",
):
self._params.backend = "dummy_backend_2"
self._registry.create_handler(self._params)
| RendezvousHandlerRegistryTest |
python | walkccc__LeetCode | solutions/190. Reverse Bits/190.py | {
"start": 0,
"end": 157
} | class ____:
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
if n >> i & 1:
ans |= 1 << 31 - i
return ans
| Solution |
python | apache__airflow | providers/amazon/tests/system/amazon/aws/utils/__init__.py | {
"start": 6650,
"end": 14933
} | class ____:
"""
This builder class ultimately constructs a TaskFlow task which is run at
runtime (task execution time). This task generates and stores the test ENV_ID as well
as any external resources requested (e.g.g IAM Roles, VPC, etc)
"""
def __init__(self):
self.variables = set()
self.test_name = _get_test_name()
def add_variable(
self,
variable_name: str,
split_string: bool = False,
delimiter: str | None = None,
optional: bool = False,
**kwargs,
):
"""Register a variable to fetch from environment or cloud parameter store"""
if variable_name in [variable.name for variable in self.variables]:
raise ValueError(f"Variable name {variable_name} already exists in the fetched variables list.")
new_variable = Variable(
name=variable_name,
to_split=split_string,
delimiter=delimiter,
test_name=self.test_name,
optional=optional,
)
# default_value is accepted via kwargs so that it is completely optional and no
# default value needs to be provided in the method stub. For example, if we
# set it to None, we would have no way to know if that was our default or the
# legitimate default value that the caller wishes to pass through.
if "default_value" in kwargs:
new_variable.set_default(kwargs["default_value"])
self.variables.add(new_variable)
return self # Builder recipe; returning self allows chaining
def build(self):
"""Build and return a TaskFlow task which will create an env_id and
fetch requested variables. Storing everything in xcom for downstream
tasks to use."""
@task
def variable_fetcher(ti=None):
ti.xcom_push(ENV_ID_KEY, set_env_id(self.test_name))
for variable in self.variables:
ti.xcom_push(variable.name, variable.get_value())
return variable_fetcher
def fetch_variable(
key: str,
test_name: str,
default_value: str | None = None,
optional: bool = False,
) -> str | None:
"""
Given a Parameter name: first check for an existing Environment Variable,
then check SSM for a value. If neither are available, fall back on the
optional default value.
:param key: The name of the Parameter to fetch a value for.
:param default_value: The default value to use if no value can be found.
:param test_name: The system test name.
:param optional: Whether the variable is optional. If True, does not raise `ValueError` if variable
does not exist
:return: The value of the parameter.
"""
value: str | None = os.getenv(key, _fetch_from_ssm(key, test_name)) or default_value
if not optional and not value:
raise ValueError(NO_VALUE_MSG.format(key=key))
return value
def set_env_id(test_name) -> str:
"""
Retrieves or generates an Environment ID, validate that it is suitable,
export it as an Environment Variable, and return it.
If an Environment ID has already been generated, use that.
Otherwise, try to fetch it and export it as an Environment Variable.
If there is not one available to fetch then generate one and export it as an Environment Variable.
:return: A valid System Test Environment ID.
"""
env_id: str = str(fetch_variable(ENV_ID_ENVIRON_KEY, test_name, DEFAULT_ENV_ID))
env_id = _validate_env_id(env_id)
os.environ[ENV_ID_ENVIRON_KEY] = env_id
return env_id
def all_tasks_passed(ti) -> bool:
if AIRFLOW_V_3_0_PLUS:
# If the test is being run with task SDK, ti is an instance of RuntimeTaskInstance
# This is the case when executed with an executor
from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
if isinstance(ti, RuntimeTaskInstance):
return RuntimeTaskInstance.get_dagrun_state(ti.dag_id, ti.run_id) != DagRunState.FAILED
task_runs = ti.get_dagrun().get_task_instances()
return all([_task.state != State.FAILED for _task in task_runs])
@task(trigger_rule=TriggerRule.ALL_DONE)
def prune_logs(
logs: list[tuple[str, str | None]],
force_delete: bool = False,
retry: bool = False,
retry_times: int = 3,
delete_log_groups: bool = True,
ti=None,
):
"""
If all tasks in this dagrun have succeeded, then delete the associated logs.
Otherwise, append the logs with a retention policy. This allows the logs
to be used for troubleshooting but assures they won't build up indefinitely.
:param logs: A list of log_group/stream_prefix tuples to delete.
:param force_delete: Whether to check log streams within the log group before
removal. If True, removes the log group and all its log streams inside it.
:param retry: Whether to retry if the log group/stream was not found. In some
cases, the log group/stream is created seconds after the main resource has
been created. By default, it retries for 3 times with a 5s waiting period.
:param retry_times: Number of retries.
:param delete_log_groups: Whether to delete the log groups if they are empty.
Overridden by force_delete.
:param ti: Used to check the status of the tasks. This gets pulled from the
DAG's context and does not need to be passed manually.
"""
if all_tasks_passed(ti):
_purge_logs(logs, force_delete, retry, retry_times, delete_log_groups)
else:
client: BaseClient = boto3.client("logs")
for group, _ in logs:
client.put_retention_policy(logGroupName=group, retentionInDays=30)
def _purge_logs(
test_logs: list[tuple[str, str | None]],
force_delete: bool = False,
retry: bool = False,
retry_times: int = 3,
delete_log_groups: bool = True,
) -> None:
"""
Accepts a tuple in the format: ('log group name', 'log stream prefix').
For each log group, it will delete any log streams matching the provided
prefix then if the log group is empty, delete the group. If the group
is not empty that indicates there are logs not generated by the test and
those are left intact. If `check_log_streams` is True, it will simply delete the log group regardless
of log streams within that log group.
:param test_logs: A list of log_group/stream_prefix tuples to delete.
:param force_delete: Whether to check log streams within the log group before removal. If True,
removes the log group and all its log streams inside it
:param retry: Whether to retry if the log group/stream was not found. In some cases, the log group/stream
is created seconds after the main resource has been created. By default, it retries for 3 times
with a 5s waiting period
:param retry_times: Number of retries
:param delete_log_groups: Whether to delete the log groups if they are empty.
Overridden by force_delete.
"""
client: BaseClient = boto3.client("logs")
for group, prefix in test_logs:
try:
if prefix:
log_streams = client.describe_log_streams(
logGroupName=group,
logStreamNamePrefix=prefix,
)["logStreams"]
for stream_name in [stream["logStreamName"] for stream in log_streams]:
client.delete_log_stream(logGroupName=group, logStreamName=stream_name)
if force_delete or (
delete_log_groups and not client.describe_log_streams(logGroupName=group)["logStreams"]
):
client.delete_log_group(logGroupName=group)
except ClientError as e:
if not retry or retry_times == 0 or e.response["Error"]["Code"] != "ResourceNotFoundException":
raise e
time.sleep(PURGE_LOGS_INTERVAL_PERIOD)
_purge_logs(
test_logs=test_logs,
force_delete=force_delete,
retry=retry,
retry_times=retry_times - 1,
)
@task
def split_string(string):
return string.split(",")
@task
def get_role_name(arn: str) -> str:
return arn.split("/")[-1]
| SystemTestContextBuilder |
python | pyinstaller__pyinstaller | PyInstaller/depend/imphook.py | {
"start": 26690,
"end": 27568
} | class ____:
"""
Cache for storing what binaries and datas were pushed by what modules when import hooks were processed.
"""
def __init__(self):
self._binaries = {}
self._datas = {}
def add(self, modname, binaries, datas):
self._binaries.setdefault(modname, [])
self._binaries[modname].extend(binaries or [])
self._datas.setdefault(modname, [])
self._datas[modname].extend(datas or [])
def __contains__(self, name):
return name in self._binaries or name in self._datas
def binaries(self, modname):
"""
Return list of binaries for given module name.
"""
return self._binaries.get(modname, [])
def datas(self, modname):
"""
Return list of datas for given module name.
"""
return self._datas.get(modname, [])
| AdditionalFilesCache |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 19525,
"end": 19638
} | class ____(OpcodeWithArg):
_FLAGS = HAS_ARGUMENT | HAS_JREL | NO_NEXT
__slots__ = ()
| JUMP_BACKWARD_NO_INTERRUPT |
python | pallets__click | src/click/core.py | {
"start": 74961,
"end": 75122
} | class ____(Group, metaclass=_FakeSubclassCheck):
"""
.. deprecated:: 8.2
Will be removed in Click 9.0. Use ``Group`` instead.
"""
| _MultiCommand |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/shell-script-component/with-config-schema-meta-yaml.py | {
"start": 61,
"end": 558
} | class ____(dg.Component, dg.Model, dg.Resolvable):
"""Models a shell script as a Dagster asset."""
script_path: str
asset_specs: Sequence[dg.ResolvedAssetSpec]
# highlight-start
@classmethod
def get_spec(cls) -> dg.ComponentTypeSpec:
return dg.ComponentTypeSpec(
owners=["john@dagster.io"],
tags=["shell", "script"],
)
# highlight-end
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: ...
| ShellCommand |
python | walkccc__LeetCode | solutions/3347. Maximum Frequency of an Element After Performing Operations II/3347.py | {
"start": 42,
"end": 740
} | class ____:
# Same as 3346. Maximum Frequency of an Element After Performing Operations I
def maxFrequency(self, nums: list[int], k: int, numOperations: int) -> int:
ans = 1
adjustable = 0
count = collections.Counter(nums)
line = SortedDict()
candidates = set()
for num in nums:
line[num - k] = line.get(num - k, 0) + 1
line[num + k + 1] = line.get(num + k + 1, 0) - 1
candidates.add(num)
candidates.add(num - k)
candidates.add(num + k + 1)
for num in sorted(candidates):
adjustable += line.get(num, 0)
adjusted = adjustable - count[num]
ans = max(ans, count[num] + min(numOperations, adjusted))
return ans
| Solution |
python | ApeWorX__ape | src/ape_ethereum/ecosystem.py | {
"start": 11537,
"end": 12781
} | class ____(BlockAPI):
"""
Class for representing a block on a chain.
"""
gas_limit: HexInt = Field(alias="gasLimit")
gas_used: HexInt = Field(alias="gasUsed")
base_fee: HexInt = Field(default=0, alias="baseFeePerGas")
difficulty: HexInt = 0
total_difficulty: HexInt = Field(default=0, alias="totalDifficulty")
uncles: list[HexBytes] = []
# Type re-declares.
hash: Optional[HexBytes] = None
parent_hash: HexBytes = Field(
default=EMPTY_BYTES32, alias="parentHash"
) # NOTE: genesis block has no parent hash
@computed_field() # type: ignore[misc]
@property
def size(self) -> int:
if self._size is not None:
# The size was provided with the rest of the model
# (normal).
return self._size
number = self.number
if number is None:
raise APINotImplementedError()
# Try to get it from the provider.
elif provider := self.network_manager.active_provider:
block = provider.get_block(number)
size = block._size
if size is not None and size > -1:
self._size = size
return size
raise APINotImplementedError()
| Block |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_process_event.py | {
"start": 27014,
"end": 27862
} | class ____(LanguageSpecificDeriveCodeMappings):
platform = "python"
def test_auto_source_code_config_stack_and_source_root_do_not_match(self) -> None:
self._process_and_assert_configuration_changes(
repo_trees={REPO1: ["src/sentry/foo/bar.py"]},
frames=[self.frame("sentry/foo/bar.py", True)],
platform=self.platform,
expected_new_code_mappings=[self.code_mapping("sentry/", "src/sentry/")],
)
def test_auto_source_code_config_no_normalization(self) -> None:
self._process_and_assert_configuration_changes(
repo_trees={REPO1: ["sentry/foo/bar.py"]},
frames=[self.frame("sentry/foo/bar.py", True)],
platform=self.platform,
expected_new_code_mappings=[self.code_mapping("", "")],
)
| TestPythonDeriveCodeMappings |
python | spack__spack | lib/spack/spack/test/installer_tui.py | {
"start": 6215,
"end": 10467
} | class ____:
"""Test output rendering for TTY and non-TTY modes"""
def test_non_tty_output(self):
"""Test that non-TTY mode prints simple state changes"""
status, _, fake_stdout = create_build_status(is_tty=False)
spec = MockSpec("mypackage", "1.0")
status.add_build(spec, explicit=True, control_w_conn=MockConnection())
build_id = spec.dag_hash()
status.update_state(build_id, "finished")
output = fake_stdout.getvalue()
assert "mypackage" in output
assert "1.0" in output
assert "finished" in output
# Non-TTY output should not contain ANSI escape codes
assert "\033[" not in output
def test_tty_output_contains_ansi(self):
"""Test that TTY mode produces ANSI codes"""
status, _, fake_stdout = create_build_status()
add_mock_builds(status, 1)
# Call update to render
status.update()
output = fake_stdout.getvalue()
# Should contain ANSI escape sequences
assert "\033[" in output
# Should contain progress header
assert "Progress:" in output
def test_no_output_when_not_dirty(self):
"""Test that update() skips rendering when not dirty"""
status, _, fake_stdout = create_build_status()
add_mock_builds(status, 1)
status.update()
# Clear stdout and mark not dirty
fake_stdout.clear()
status.dirty = False
# Update should not produce output
status.update()
assert fake_stdout.getvalue() == ""
def test_update_throttling(self):
"""Test that update() throttles redraws"""
status, fake_time, fake_stdout = create_build_status()
add_mock_builds(status, 1)
# First update at time 0
fake_time[0] = 0.0
status.update()
first_output = fake_stdout.getvalue()
assert first_output != ""
# Mark dirty and try to update immediately
fake_stdout.clear()
status.dirty = True
fake_time[0] = 0.01 # Very small time advance
# Should be throttled (next_update not reached)
status.update()
assert fake_stdout.getvalue() == ""
# Advance time past throttle and try again
fake_time[0] = 1.0
status.update()
assert fake_stdout.getvalue() != ""
def test_cursor_movement_vs_newlines(self):
"""Test that finished builds get newlines, active builds get cursor movements"""
status, fake_time, fake_stdout = create_build_status(total=5)
specs = add_mock_builds(status, 3)
# First update renders 3 active builds
fake_time[0] = 0.0
status.update()
output1 = fake_stdout.getvalue()
# Count newlines (\n) and cursor movements (\033[1E = move down 1 line)
newlines1 = output1.count("\n")
cursor_moves1 = output1.count("\033[1E")
# Initially all lines should be newlines (nothing in history yet)
assert newlines1 > 0
assert cursor_moves1 == 0
# Now finish 2 builds and add 2 more
fake_stdout.clear()
fake_time[0] = inst.CLEANUP_TIMEOUT + 0.1
status.update_state(specs[0].dag_hash(), "finished")
status.update_state(specs[1].dag_hash(), "finished")
spec4 = MockSpec("pkg3", "3.0")
spec5 = MockSpec("pkg4", "4.0")
status.add_build(spec4, explicit=True, control_w_conn=MockConnection())
status.add_build(spec5, explicit=True, control_w_conn=MockConnection())
# Second update: finished builds persist (newlines), active area updates (cursor moves)
status.update()
output2 = fake_stdout.getvalue()
newlines2 = output2.count("\n")
cursor_moves2 = output2.count("\033[1E")
# Should have newlines for the 2 finished builds persisted to history
# and cursor movements for the active area (header + 3 active builds)
assert newlines2 > 0, "Should have newlines for finished builds"
assert cursor_moves2 > 0, "Should have cursor movements for active area"
# Finished builds should be printed with newlines
assert "pkg0" in output2
assert "pkg1" in output2
| TestOutputRendering |
python | pypa__warehouse | tests/common/db/accounts.py | {
"start": 2356,
"end": 2482
} | class ____(WarehouseFactory):
class Meta:
model = User.Event
source = factory.SubFactory(User)
| UserEventFactory |
python | conda__conda | conda/plugins/types.py | {
"start": 8052,
"end": 8394
} | class ____(ChannelNameMixin, AuthBase):
"""
Base class that we require all plugin implementations to use to be compatible.
Authentication is tightly coupled with individual channels. Therefore, an additional
``channel_name`` property must be set on the ``requests.auth.AuthBase`` based class.
"""
@dataclass
| ChannelAuthBase |
python | django__django | tests/admin_filters/tests.py | {
"start": 5693,
"end": 5787
} | class ____(UserAdmin):
list_filter = ("books_authored", "books_contributed")
| CustomUserAdmin |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_required.py | {
"start": 1349,
"end": 2888
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpr.Required()
def test_valid(self) -> None:
prop = bcpr.Required(List(Int))
assert prop.is_valid([])
assert prop.is_valid([1, 2, 3])
def test_invalid(self) -> None:
prop = bcpr.Required(List(Int))
assert not prop.is_valid(None)
assert not prop.is_valid(-100)
assert not prop.is_valid("yyy")
assert not prop.is_valid([1, 2, ""])
assert not prop.is_valid(())
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
def test_has_ref(self) -> None:
prop0 = bcpr.Required(Int)
assert not prop0.has_ref
prop1 = bcpr.Required(Instance(_TestModel))
assert prop1.has_ref
def test_str(self) -> None:
prop = bcpr.Required(List(Int))
assert str(prop) == "Required(List(Int))"
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
Test___all__ = verify_all(bcpr, ALL)
| Test_Required |
python | ray-project__ray | rllib/examples/algorithms/appo_custom_algorithm_w_shared_data_actor.py | {
"start": 5949,
"end": 7729
} | class ____(ConnectorV2):
def __call__(self, *, episodes, batch, metrics, **kwargs):
if not isinstance(episodes[0], SingleAgentEpisode):
raise ValueError("This connector only works on `SingleAgentEpisodes`.")
# Get the manipulated rewards from the shared actor and add them to the train
# batch.
for sa_episode in self.single_agent_episode_iterator(episodes):
unique_key = sa_episode.custom_data[UNIQUE_EPISODE_CHUNK_KEY]
special_rewards = ray.get(
self._shared_data_actor.get.remote(unique_key, delete=True)
)
if special_rewards is None:
continue
assert int(special_rewards[0]) == sa_episode.custom_data[ENV_RUNNER_IDX_KEY]
# Add one more fake reward, b/c all episodes will be extended
# (in PPO-style algos) by one artificial timestep for GAE/v-trace
# computation purposes.
special_rewards += [0.0]
self.add_n_batch_items(
batch=batch,
column=Columns.REWARDS,
items_to_add=special_rewards[-len(sa_episode) :],
num_items=len(sa_episode),
single_agent_episode=sa_episode,
)
return batch
if __name__ == "__main__":
args = parser.parse_args()
base_config = (
APPOConfig(algo_class=APPOWithSharedDataActor)
.environment("CartPole-v1")
.callbacks(
on_episode_step=on_episode_step,
on_sample_end=on_sample_end,
)
.training(
learner_connector=(lambda obs_sp, act_sp: ManipulatedRewardConnector()),
)
)
run_rllib_example_script_experiment(base_config, args)
| ManipulatedRewardConnector |
python | wandb__wandb | wandb/vendor/pygments/lexers/lisp.py | {
"start": 652,
"end": 7071
} | class ____(RegexLexer):
"""
A Scheme lexer, parsing a stream and outputting the tokens
needed to highlight scheme code.
This lexer could be most probably easily subclassed to parse
other LISP-Dialects like Common Lisp, Emacs Lisp or AutoLisp.
This parser is checked with pastes from the LISP pastebin
at http://paste.lisp.org/ to cover as much syntax as possible.
It supports the full Scheme syntax as defined in R5RS.
.. versionadded:: 0.6
"""
name = 'Scheme'
aliases = ['scheme', 'scm']
filenames = ['*.scm', '*.ss']
mimetypes = ['text/x-scheme', 'application/x-scheme']
# list of known keywords and builtins taken form vim 6.4 scheme.vim
# syntax file.
keywords = (
'lambda', 'define', 'if', 'else', 'cond', 'and', 'or', 'case', 'let',
'let*', 'letrec', 'begin', 'do', 'delay', 'set!', '=>', 'quote',
'quasiquote', 'unquote', 'unquote-splicing', 'define-syntax',
'let-syntax', 'letrec-syntax', 'syntax-rules'
)
builtins = (
'*', '+', '-', '/', '<', '<=', '=', '>', '>=', 'abs', 'acos', 'angle',
'append', 'apply', 'asin', 'assoc', 'assq', 'assv', 'atan',
'boolean?', 'caaaar', 'caaadr', 'caaar', 'caadar', 'caaddr', 'caadr',
'caar', 'cadaar', 'cadadr', 'cadar', 'caddar', 'cadddr', 'caddr',
'cadr', 'call-with-current-continuation', 'call-with-input-file',
'call-with-output-file', 'call-with-values', 'call/cc', 'car',
'cdaaar', 'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar',
'cddaar', 'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr',
'cdr', 'ceiling', 'char->integer', 'char-alphabetic?', 'char-ci<=?',
'char-ci<?', 'char-ci=?', 'char-ci>=?', 'char-ci>?', 'char-downcase',
'char-lower-case?', 'char-numeric?', 'char-ready?', 'char-upcase',
'char-upper-case?', 'char-whitespace?', 'char<=?', 'char<?', 'char=?',
'char>=?', 'char>?', 'char?', 'close-input-port', 'close-output-port',
'complex?', 'cons', 'cos', 'current-input-port', 'current-output-port',
'denominator', 'display', 'dynamic-wind', 'eof-object?', 'eq?',
'equal?', 'eqv?', 'eval', 'even?', 'exact->inexact', 'exact?', 'exp',
'expt', 'floor', 'for-each', 'force', 'gcd', 'imag-part',
'inexact->exact', 'inexact?', 'input-port?', 'integer->char',
'integer?', 'interaction-environment', 'lcm', 'length', 'list',
'list->string', 'list->vector', 'list-ref', 'list-tail', 'list?',
'load', 'log', 'magnitude', 'make-polar', 'make-rectangular',
'make-string', 'make-vector', 'map', 'max', 'member', 'memq', 'memv',
'min', 'modulo', 'negative?', 'newline', 'not', 'null-environment',
'null?', 'number->string', 'number?', 'numerator', 'odd?',
'open-input-file', 'open-output-file', 'output-port?', 'pair?',
'peek-char', 'port?', 'positive?', 'procedure?', 'quotient',
'rational?', 'rationalize', 'read', 'read-char', 'real-part', 'real?',
'remainder', 'reverse', 'round', 'scheme-report-environment',
'set-car!', 'set-cdr!', 'sin', 'sqrt', 'string', 'string->list',
'string->number', 'string->symbol', 'string-append', 'string-ci<=?',
'string-ci<?', 'string-ci=?', 'string-ci>=?', 'string-ci>?',
'string-copy', 'string-fill!', 'string-length', 'string-ref',
'string-set!', 'string<=?', 'string<?', 'string=?', 'string>=?',
'string>?', 'string?', 'substring', 'symbol->string', 'symbol?',
'tan', 'transcript-off', 'transcript-on', 'truncate', 'values',
'vector', 'vector->list', 'vector-fill!', 'vector-length',
'vector-ref', 'vector-set!', 'vector?', 'with-input-from-file',
'with-output-to-file', 'write', 'write-char', 'zero?'
)
# valid names for identifiers
# well, names can only not consist fully of numbers
# but this should be good enough for now
valid_name = r'[\w!$%&*+,/:<=>?@^~|-]+'
tokens = {
'root': [
# the comments
# and going to the end of the line
(r';.*$', Comment.Single),
# multi-line comment
(r'#\|', Comment.Multiline, 'multiline-comment'),
# commented form (entire sexpr folliwng)
(r'#;\s*\(', Comment, 'commented-form'),
# signifies that the program text that follows is written with the
# lexical and datum syntax described in r6rs
(r'#!r6rs', Comment),
# whitespaces - usually not relevant
(r'\s+', Text),
# numbers
(r'-?\d+\.\d+', Number.Float),
(r'-?\d+', Number.Integer),
# support for uncommon kinds of numbers -
# have to figure out what the characters mean
# (r'(#e|#i|#b|#o|#d|#x)[\d.]+', Number),
# strings, symbols and characters
(r'"(\\\\|\\"|[^"])*"', String),
(r"'" + valid_name, String.Symbol),
(r"#\\([()/'\"._!§$%& ?=+-]|[a-zA-Z0-9]+)", String.Char),
# constants
(r'(#t|#f)', Name.Constant),
# special operators
(r"('|#|`|,@|,|\.)", Operator),
# highlight the keywords
('(%s)' % '|'.join(re.escape(entry) + ' ' for entry in keywords),
Keyword),
# first variable in a quoted string like
# '(this is syntactic sugar)
(r"(?<='\()" + valid_name, Name.Variable),
(r"(?<=#\()" + valid_name, Name.Variable),
# highlight the builtins
("(?<=\()(%s)" % '|'.join(re.escape(entry) + ' ' for entry in builtins),
Name.Builtin),
# the remaining functions
(r'(?<=\()' + valid_name, Name.Function),
# find the remaining variables
(valid_name, Name.Variable),
# the famous parentheses!
(r'(\(|\))', Punctuation),
(r'(\[|\])', Punctuation),
],
'multiline-comment': [
(r'#\|', Comment.Multiline, '#push'),
(r'\|#', Comment.Multiline, '#pop'),
(r'[^|#]+', Comment.Multiline),
(r'[|#]', Comment.Multiline),
],
'commented-form': [
(r'\(', Comment, '#push'),
(r'\)', Comment, '#pop'),
(r'[^()]+', Comment),
],
}
| SchemeLexer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_write_col.py | {
"start": 297,
"end": 749
} | class ____(unittest.TestCase):
"""
Test the Drawing _write_col() method.
"""
def setUp(self):
self.fh = StringIO()
self.drawing = Drawing()
self.drawing._set_filehandle(self.fh)
def test_write_col(self):
"""Test the _write_col() method"""
self.drawing._write_col(4)
exp = """<xdr:col>4</xdr:col>"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestWriteXdrcol |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_L.py | {
"start": 5637,
"end": 7203
} | class ____(Benchmark):
r"""
Levy 3 objective function.
This class defines the Levy 3 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Levy03}}(\mathbf{x}) =
\sin^2(\pi y_1)+\sum_{i=1}^{n-1}(y_i-1)^2[1+10\sin^2(\pi y_{i+1})]+(y_n-1)^2
Where, in this exercise:
.. math::
y_i=1+\frac{x_i-1}{4}
Here, :math:`n` represents the number of dimensions and
:math:`x_i \in [-10, 10]` for :math:`i=1,...,n`.
*Global optimum*: :math:`f(x_i) = 0` for :math:`x_i = 1` for :math:`i=1,...,n`
.. [1] Mishra, S. Global Optimization by Differential Evolution and
Particle Swarm Methods: Evaluation on Some Benchmark Functions.
Munich Personal RePEc Archive, 2006, 1005
TODO: not clear what the Levy function definition is. Gavana, Mishra,
Adorio have different forms. Indeed Levy 3 docstring from Gavana
disagrees with the Gavana code! The following code is from the Mishra
listing of Levy08.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N))
self.custom_bounds = [(-5, 5), (-5, 5)]
self.global_optimum = [[1 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
y = 1 + (x - 1) / 4
v = sum((y[:-1] - 1) ** 2 * (1 + 10 * sin(pi * y[1:]) ** 2))
z = (y[-1] - 1) ** 2
return sin(pi * y[0]) ** 2 + v + z
| Levy03 |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 3738,
"end": 3887
} | class ____(SlotsManipulationTest):
__slots__ += ["d", "e", "f"] # pylint: disable=undefined-variable
T = TestChild()
print(T.__slots__)
| TestChild |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.