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 | vyperlang__vyper | tests/evm_backends/abi_contract.py | {
"start": 7756,
"end": 10236
} | class ____:
"""
Represents a set of functions that have the same name but different
argument types. This is used to implement function overloading.
"""
@staticmethod
def create(
functions: list[ABIFunction], contract: "ABIContract"
) -> Union["ABIOverload", ABIFunction]:
"""
Create an ABIOverload if there are multiple functions, otherwise
return the single function.
:param functions: a list of functions with the same name
:param contract: the ABIContract that these functions belong to
"""
for f in functions:
f.contract = contract
if len(functions) == 1:
return functions[0]
return ABIOverload(functions)
def __init__(self, functions: list[ABIFunction]):
self.functions = functions
@cached_property
def name(self) -> str:
return self.functions[0].name
def __call__(
self, *args, value=0, gas=None, sender=None, disambiguate_signature=None, **kwargs
):
"""
Call the function that matches the given arguments.
:raises Exception: if a single function is not found
"""
function = self._pick_overload(
*args, disambiguate_signature=disambiguate_signature, **kwargs
)
return function(*args, value=value, gas=gas, sender=sender, **kwargs)
def _pick_overload(self, *args, disambiguate_signature=None, **kwargs) -> ABIFunction:
"""Pick the function that matches the given arguments."""
if disambiguate_signature is None:
matches = [f for f in self.functions if f.is_encodable(*args, **kwargs)]
else:
matches = [f for f in self.functions if disambiguate_signature == f.full_signature]
assert len(matches) <= 1, "ABI signature must be unique"
match matches:
case [function]:
return function
case []:
raise Exception(
f"Could not find matching {self.name} function for given arguments."
)
case multiple:
raise Exception(
f"Ambiguous call to {self.name}. "
f"Arguments can be encoded to multiple overloads: "
f"{', '.join(self.name + f._args_signature for f in multiple)}. "
f"(Hint: try using `disambiguate_signature=` to disambiguate)."
)
| ABIOverload |
python | numba__numba | numba/tests/test_numpy_support.py | {
"start": 9647,
"end": 17397
} | class ____(TestCase):
"""
Test ufunc helpers.
"""
def test_ufunc_find_matching_loop(self):
f = numpy_support.ufunc_find_matching_loop
np_add = FakeUFunc(_add_types)
np_mul = FakeUFunc(_mul_types)
np_isnan = FakeUFunc(_isnan_types)
np_sqrt = FakeUFunc(_sqrt_types)
def check(ufunc, input_types, sigs, output_types=()):
"""
Check that ufunc_find_matching_loop() finds one of the given
*sigs* for *ufunc*, *input_types* and optional *output_types*.
"""
loop = f(ufunc, input_types + output_types)
self.assertTrue(loop)
if isinstance(sigs, str):
sigs = (sigs,)
self.assertIn(loop.ufunc_sig, sigs,
"inputs=%s and outputs=%s should have selected "
"one of %s, got %s"
% (input_types, output_types, sigs, loop.ufunc_sig))
self.assertEqual(len(loop.numpy_inputs), len(loop.inputs))
self.assertEqual(len(loop.numpy_outputs), len(loop.outputs))
if not output_types:
# Add explicit outputs and check the result is the same
loop_explicit = f(ufunc, list(input_types) + loop.outputs)
self.assertEqual(loop_explicit, loop)
else:
self.assertEqual(loop.outputs, list(output_types))
# Round-tripping inputs and outputs
loop_rt = f(ufunc, loop.inputs + loop.outputs)
self.assertEqual(loop_rt, loop)
return loop
def check_exact(ufunc, input_types, sigs, output_types=()):
"""
Like check(), but also ensure no casting of inputs occurred.
"""
loop = check(ufunc, input_types, sigs, output_types)
self.assertEqual(loop.inputs, list(input_types))
def check_no_match(ufunc, input_types):
loop = f(ufunc, input_types)
self.assertIs(loop, None)
# Exact matching for number types
check_exact(np_add, (types.bool_, types.bool_), '??->?')
check_exact(np_add, (types.int8, types.int8), 'bb->b')
check_exact(np_add, (types.uint8, types.uint8), 'BB->B')
check_exact(np_add, (types.int64, types.int64), ('ll->l', 'qq->q'))
check_exact(np_add, (types.uint64, types.uint64), ('LL->L', 'QQ->Q'))
check_exact(np_add, (types.float32, types.float32), 'ff->f')
check_exact(np_add, (types.float64, types.float64), 'dd->d')
check_exact(np_add, (types.complex64, types.complex64), 'FF->F')
check_exact(np_add, (types.complex128, types.complex128), 'DD->D')
# Exact matching for datetime64 and timedelta64 types
check_exact(np_add, (types.NPTimedelta('s'), types.NPTimedelta('s')),
'mm->m', output_types=(types.NPTimedelta('s'),))
check_exact(np_add, (types.NPTimedelta('ms'), types.NPDatetime('s')),
'mM->M', output_types=(types.NPDatetime('ms'),))
check_exact(np_add, (types.NPDatetime('s'), types.NPTimedelta('s')),
'Mm->M', output_types=(types.NPDatetime('s'),))
check_exact(np_add, (types.NPDatetime('s'), types.NPTimedelta('')),
'Mm->M', output_types=(types.NPDatetime('s'),))
check_exact(np_add, (types.NPDatetime('ns'), types.NPTimedelta('')),
'Mm->M', output_types=(types.NPDatetime('ns'),))
check_exact(np_add, (types.NPTimedelta(''), types.NPDatetime('s')),
'mM->M', output_types=(types.NPDatetime('s'),))
check_exact(np_add, (types.NPTimedelta(''), types.NPDatetime('ns')),
'mM->M', output_types=(types.NPDatetime('ns'),))
check_exact(np_mul, (types.NPTimedelta('s'), types.int64),
'mq->m', output_types=(types.NPTimedelta('s'),))
check_exact(np_mul, (types.float64, types.NPTimedelta('s')),
'dm->m', output_types=(types.NPTimedelta('s'),))
# Mix and match number types, with casting
check(np_add, (types.bool_, types.int8), 'bb->b')
check(np_add, (types.uint8, types.bool_), 'BB->B')
check(np_add, (types.int16, types.uint16), 'ii->i')
check(np_add, (types.complex64, types.float64), 'DD->D')
check(np_add, (types.float64, types.complex64), 'DD->D')
# Integers, when used together with floating-point numbers,
# should cast to any real or complex (see #2006)
int_types = [types.int32, types.uint32, types.int64, types.uint64]
for intty in int_types:
check(np_add, (types.float32, intty), 'ff->f')
check(np_add, (types.float64, intty), 'dd->d')
check(np_add, (types.complex64, intty), 'FF->F')
check(np_add, (types.complex128, intty), 'DD->D')
# However, when used alone, they should cast only to
# floating-point types of sufficient precision
# (typical use case: np.sqrt(2) should give an accurate enough value)
for intty in int_types:
check(np_sqrt, (intty,), 'd->d')
check(np_isnan, (intty,), 'd->?')
# With some timedelta64 arguments as well
check(np_mul, (types.NPTimedelta('s'), types.int32),
'mq->m', output_types=(types.NPTimedelta('s'),))
check(np_mul, (types.NPTimedelta('s'), types.uint32),
'mq->m', output_types=(types.NPTimedelta('s'),))
check(np_mul, (types.NPTimedelta('s'), types.float32),
'md->m', output_types=(types.NPTimedelta('s'),))
check(np_mul, (types.float32, types.NPTimedelta('s')),
'dm->m', output_types=(types.NPTimedelta('s'),))
# No match
check_no_match(np_add, (types.NPDatetime('s'), types.NPDatetime('s')))
# No implicit casting from int64 to timedelta64 (Numpy would allow
# this).
check_no_match(np_add, (types.NPTimedelta('s'), types.int64))
def test_layout_checker(self):
def check_arr(arr):
dims = arr.shape
strides = arr.strides
itemsize = arr.dtype.itemsize
is_c = numpy_support.is_contiguous(dims, strides, itemsize)
is_f = numpy_support.is_fortran(dims, strides, itemsize)
expect_c = arr.flags['C_CONTIGUOUS']
expect_f = arr.flags['F_CONTIGUOUS']
self.assertEqual(is_c, expect_c)
self.assertEqual(is_f, expect_f)
arr = np.arange(24)
# 1D
check_arr(arr)
# 2D
check_arr(arr.reshape((3, 8)))
check_arr(arr.reshape((3, 8)).T)
check_arr(arr.reshape((3, 8))[::2])
# 3D
check_arr(arr.reshape((2, 3, 4)))
check_arr(arr.reshape((2, 3, 4)).T)
# middle axis is shape 1
check_arr(arr.reshape((2, 3, 4))[:, ::3])
check_arr(arr.reshape((2, 3, 4)).T[:, ::3])
# leading axis is shape 1
check_arr(arr.reshape((2, 3, 4))[::2])
check_arr(arr.reshape((2, 3, 4)).T[:, :, ::2])
# 2 leading axis are shape 1
check_arr(arr.reshape((2, 3, 4))[::2, ::3])
check_arr(arr.reshape((2, 3, 4)).T[:, ::3, ::2])
# single item slices for all axis
check_arr(arr.reshape((2, 3, 4))[::2, ::3, ::4])
check_arr(arr.reshape((2, 3, 4)).T[::4, ::3, ::2])
# 4D
check_arr(arr.reshape((2, 2, 3, 2))[::2, ::2, ::3])
check_arr(arr.reshape((2, 2, 3, 2)).T[:, ::3, ::2, ::2])
# outer zero dims
check_arr(arr.reshape((2, 2, 3, 2))[::5, ::2, ::3])
check_arr(arr.reshape((2, 2, 3, 2)).T[:, ::3, ::2, ::5])
if __name__ == '__main__':
unittest.main()
| TestUFuncs |
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 22210,
"end": 22384
} | class ____(serializers.Serializer):
trace = TraceContextValidator(required=False)
@extend_schema_serializer(exclude_fields=["monitor_config", "contexts"])
| ContextsValidator |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 14221,
"end": 20890
} | class ____(AbstractNotificationAction):
"""
This model represents an action that occurs when a trigger (over/under) is fired. This is
typically some sort of notification.
NOTE: AlertRuleTrigger is the 'threshold' for the AlertRule
"""
__relocation_scope__ = RelocationScope.Global
Type = ActionService
TargetType = ActionTarget
# As a test utility, TemporaryAlertRuleTriggerActionRegistry has privileged
# access to this otherwise private class variable
_factory_registrations = _FactoryRegistry()
INTEGRATION_TYPES = frozenset(
(
Type.PAGERDUTY.value,
Type.SLACK.value,
Type.MSTEAMS.value,
Type.OPSGENIE.value,
Type.DISCORD.value,
)
)
# ActionService items which are not supported for AlertRuleTriggerActions
EXEMPT_SERVICES = frozenset((Type.SENTRY_NOTIFICATION.value,))
objects: ClassVar[AlertRuleTriggerActionManager] = AlertRuleTriggerActionManager()
objects_for_deletion: ClassVar[BaseManager] = BaseManager()
alert_rule_trigger = FlexibleForeignKey("sentry.AlertRuleTrigger")
date_added = models.DateTimeField(default=timezone.now)
sentry_app_config: models.Field[
# list of dicts if this is a sentry app, otherwise can be singular dict
dict[str, Any] | list[dict[str, Any]] | None,
dict[str, Any] | list[dict[str, Any]] | None,
] = JSONField(null=True)
status = BoundedPositiveIntegerField(
default=ObjectStatus.ACTIVE,
db_default=ObjectStatus.ACTIVE,
choices=ObjectStatus.as_choices(),
)
class Meta:
app_label = "sentry"
db_table = "sentry_alertruletriggeraction"
@property
def target(self) -> OrganizationMember | Team | str | None:
if self.target_identifier is None:
return None
if self.target_type == self.TargetType.USER.value:
try:
return OrganizationMember.objects.get(
user_id=int(self.target_identifier),
organization=self.alert_rule_trigger.alert_rule.organization_id,
)
except OrganizationMember.DoesNotExist:
pass
elif self.target_type == self.TargetType.TEAM.value:
try:
return Team.objects.get(id=int(self.target_identifier))
except Team.DoesNotExist:
pass
elif self.target_type == self.TargetType.SPECIFIC.value:
# TODO: This is only for email. We should have a way of validating that it's
# ok to contact this email.
return self.target_identifier
return None
@staticmethod
def build_handler(type: ActionService) -> ActionHandler | None:
factory = AlertRuleTriggerAction._factory_registrations.by_action_service.get(type)
if factory is not None:
return factory.build_handler()
else:
metrics.incr(f"alert_rule_trigger.unhandled_type.{type}")
return None
def fire(
self,
action: AlertRuleTriggerAction,
incident: Incident,
project: Project,
metric_value: int | float | None,
new_status: IncidentStatus,
notification_uuid: str | None = None,
) -> None:
handler = AlertRuleTriggerAction.build_handler(AlertRuleTriggerAction.Type(self.type))
if handler:
return handler.fire(
action=action,
incident=incident,
project=project,
new_status=new_status,
metric_value=metric_value,
notification_uuid=notification_uuid,
)
def resolve(
self,
action: AlertRuleTriggerAction,
incident: Incident,
project: Project,
metric_value: int | float | None,
new_status: IncidentStatus,
notification_uuid: str | None = None,
) -> None:
handler = AlertRuleTriggerAction.build_handler(AlertRuleTriggerAction.Type(self.type))
if handler:
return handler.resolve(
action=action,
incident=incident,
project=project,
metric_value=metric_value,
new_status=new_status,
notification_uuid=notification_uuid,
)
def get_single_sentry_app_config(self) -> dict[str, Any] | None:
value = self.sentry_app_config
if isinstance(value, list):
raise ValueError("Sentry app actions have a list of configs")
return value
@classmethod
def register_factory(cls, factory: ActionHandlerFactory) -> None:
cls._factory_registrations.register(factory)
@classmethod
def register_type(
cls,
slug: str,
service_type: ActionService,
supported_target_types: Collection[ActionTarget],
integration_provider: str | None = None,
) -> Callable[[type[ActionHandler]], type[ActionHandler]]:
"""
Register a factory for the decorated ActionHandler class, for a given service type.
:param slug: A string representing the name of this type registration
:param service_type: The action service type the decorated handler supports.
:param supported_target_types: The target types the decorated handler supports.
:param integration_provider: String representing the integration provider
related to this type.
"""
def inner(handler: type[ActionHandler]) -> type[ActionHandler]:
"""
:param handler: A subclass of `ActionHandler` that accepts the
`AlertRuleActionHandler` and `Incident`.
"""
factory = _AlertRuleActionHandlerClassFactory(
slug, service_type, supported_target_types, integration_provider, handler
)
cls.register_factory(factory)
return handler
return inner
@classmethod
def get_registered_factory(cls, service_type: ActionService) -> ActionHandlerFactory:
return cls._factory_registrations.by_action_service[service_type]
@classmethod
def get_registered_factories(cls) -> list[ActionHandlerFactory]:
return list(cls._factory_registrations.by_action_service.values())
@classmethod
def look_up_factory_by_slug(cls, slug: str) -> ActionHandlerFactory | None:
return cls._factory_registrations.by_slug.get(slug)
@classmethod
def get_all_slugs(cls) -> list[str]:
return list(cls._factory_registrations.by_slug)
| AlertRuleTriggerAction |
python | facelessuser__pymdown-extensions | pymdownx/smartsymbols.py | {
"start": 3491,
"end": 3960
} | class ____(HtmlInlineProcessor):
"""Smart symbols patterns handler."""
def __init__(self, pattern, replace, md):
"""Setup replace pattern."""
super().__init__(pattern, md)
self.replace = replace
def handleMatch(self, m, data):
"""Replace symbol."""
return self.md.htmlStash.store(
m.expand(self.replace(m) if callable(self.replace) else self.replace),
), m.start(0), m.end(0)
| SmartSymbolsPattern |
python | PrefectHQ__prefect | src/prefect/server/events/filters.py | {
"start": 13976,
"end": 18378
} | class ____(EventDataFilter):
id: Optional[list[str]] = Field(
None, description="Only include events for related resources with these IDs"
)
role: Optional[list[str]] = Field(
None, description="Only include events for related resources in these roles"
)
resources_in_roles: Optional[list[tuple[str, str]]] = Field(
None,
description=(
"Only include events with specific related resources in specific roles"
),
)
labels: Optional[ResourceSpecification] = Field(
None, description="Only include events for related resources with these labels"
)
@db_injector
def build_where_clauses(
self, db: PrefectDBInterface
) -> Sequence["ColumnExpressionArgument[bool]"]:
filters: list["ColumnExpressionArgument[bool]"] = []
if self.id:
filters.append(db.EventResource.resource_id.in_(self.id))
if self.role:
filters.append(db.EventResource.resource_role.in_(self.role))
if self.resources_in_roles:
filters.append(
sa.or_(
*(
sa.and_(
db.EventResource.resource_id == resource_id,
db.EventResource.resource_role == role,
)
for resource_id, role in self.resources_in_roles
)
)
)
if self.labels:
label_filters: list[ColumnElement[bool]] = []
labels = self.labels.deepcopy()
# On the event_resources table, resource_id and resource_role are unpacked
# into columns, so we should search there for them
if resource_ids := labels.pop("prefect.resource.id", None):
label_ops = LabelOperations(resource_ids)
resource_id_column = db.EventResource.resource_id
if values := label_ops.positive.simple:
label_filters.append(resource_id_column.in_(values))
if values := label_ops.negative.simple:
label_filters.append(resource_id_column.notin_(values))
for prefix in label_ops.positive.prefixes:
label_filters.append(resource_id_column.startswith(prefix))
for prefix in label_ops.negative.prefixes:
label_filters.append(sa.not_(resource_id_column.startswith(prefix)))
if roles := labels.pop("prefect.resource.role", None):
label_filters.append(db.EventResource.resource_role.in_(roles))
if labels:
for _, (label, values) in enumerate(labels.items()):
# Empty label value arrays should match nothing
if not values:
label_filters.append(sa.false())
continue
label_ops = LabelOperations(values)
label_column = db.EventResource.resource[label].astext
if label_ops.negative.simple or label_ops.negative.prefixes:
label_filters.append(label_column.is_not(None))
if values := label_ops.positive.simple:
label_filters.append(label_column.in_(values))
if values := label_ops.negative.simple:
label_filters.append(label_column.notin_(values))
for prefix in label_ops.positive.prefixes:
label_filters.append(label_column.startswith(prefix))
for prefix in label_ops.negative.prefixes:
label_filters.append(sa.not_(label_column.startswith(prefix)))
filters.append(sa.and_(*label_filters))
if filters:
# This filter is explicitly searching for related resources, so if no other
# role is specified, and we're doing any kind of filtering with this filter,
# also filter out primary resources (those with an empty role) for any of
# these queries
if not self.role:
filters.append(db.EventResource.resource_role != "")
assert self._top_level_filter is not None
filters = [db.Event.id.in_(self._top_level_filter.where(*filters))]
return filters
| EventRelatedFilter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/spec.py | {
"start": 1942,
"end": 2519
} | class ____(BaseModel):
class Config(OneOfOptionConfig):
title = "Authenticate via Storage Account Key"
discriminator = "auth_type"
auth_type: Literal["storage_account_key"] = Field("storage_account_key", const=True)
azure_blob_storage_account_key: str = Field(
title="Azure Blob Storage account key",
description="The Azure blob storage account key.",
airbyte_secret=True,
examples=["Z8ZkZpteggFx394vm+PJHnGTvdRncaYS+JhLKdj789YNmD+iyGTnG+PV+POiuYNhBg/ACS+LKjd%4FG3FHGN12Nd=="],
order=3,
)
| StorageAccountKey |
python | getsentry__sentry | src/sentry/data_secrecy/models/data_access_grant.py | {
"start": 332,
"end": 1990
} | class ____(DefaultFieldsModel):
__relocation_scope__ = RelocationScope.Excluded
class GrantType(StrEnum):
ZENDESK = "zendesk"
MANUAL = "manual"
class RevocationReason(StrEnum):
TICKET_RESOLVED = "ticket_resolved"
MANUAL_REVOCATION = "manual_revocation"
organization_id = HybridCloudForeignKey("sentry.Organization", null=False, on_delete="CASCADE")
grant_type = models.CharField(max_length=24, choices=[(t.value, t.value) for t in GrantType])
ticket_id = models.CharField(max_length=64, null=True)
# For MANUAL type grants, store the user who granted the access
granted_by_user = FlexibleForeignKey(
"sentry.User",
null=True,
on_delete=models.SET_NULL,
related_name="granted_data_access_grants",
)
# Access window for the grant
grant_start = models.DateTimeField(default=timezone.now)
grant_end = models.DateTimeField(default=timezone.now)
# If the grant is revoked, we store the date and reason
revocation_date = models.DateTimeField(null=True, blank=True)
revocation_reason = models.CharField(
max_length=20, choices=[(t.value, t.value) for t in RevocationReason], null=True, blank=True
)
# If the grant is manually revoked record the user who revoked it
revoked_by_user = FlexibleForeignKey(
"sentry.User",
null=True,
on_delete=models.SET_NULL,
related_name="revoked_data_access_grants",
)
class Meta:
app_label = "sentry"
db_table = "sentry_dataaccessgrant"
unique_together = (("organization_id", "grant_type", "ticket_id"),)
| DataAccessGrant |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 23046,
"end": 24918
} | class ____(PluginInstallError):
"""
An error related to specified plugin version.
"""
def __init__(
self, operation: str, reason: Optional[str] = None, resolution: Optional[str] = None
):
message = f"Unable to {operation} plugin."
if reason:
message = f"{message}\nReason: {reason}"
if resolution:
message = f"{message}\nTo resolve: {resolution}"
super().__init__(message)
def handle_ape_exception(err: ApeException, base_paths: Iterable[Union[Path, str]]) -> bool:
"""
Handle a transaction error by showing relevant stack frames,
including custom contract frames added to the exception.
This method must be called within an ``except`` block or with
an exception on the exc-stack.
Args:
err (:class:`~ape.exceptions.TransactionError`): The transaction error
being handled.
base_paths (Optional[Iterable[Union[Path, str]]]): Optionally include additional
source-path prefixes to use when finding relevant frames.
Returns:
bool: ``True`` if outputted something.
"""
home_str = str(Path.home())
if not (relevant_frames := _get_relevant_frames(base_paths)):
return False
formatted_tb = [x.replace(home_str, "$HOME") for x in relevant_frames]
rich_print(f"\n{''.join(formatted_tb)}")
# Prevent double logging of a traceback by using `show_traceback=False`.
logger.error(Abort.from_ape_exception(err, show_traceback=False))
return True
def _get_relevant_frames(base_paths: Iterable[Union[Path, str]]):
# Abstracted for testing easement.
tb = traceback.extract_tb(sys.exc_info()[2])
if relevant_tb := [f for f in tb if any(str(p) in f.filename for p in base_paths)]:
return [x for x in traceback.format_list(relevant_tb)]
return []
| PluginVersionError |
python | apache__airflow | airflow-core/src/airflow/utils/log/task_handler_with_custom_formatter.py | {
"start": 1188,
"end": 2561
} | class ____(logging.StreamHandler):
"""Custom implementation of StreamHandler, a class which writes logging records for Airflow."""
prefix_jinja_template: Template | None = None
def set_context(self, ti) -> None:
"""
Accept the run-time context (i.e. the current task) and configure the formatter accordingly.
:param ti:
:return:
"""
# Returns if there is no formatter or if the prefix has already been set
if ti.raw or self.formatter is None or self.prefix_jinja_template is not None:
return
prefix = conf.get("logging", "task_log_prefix_template")
if prefix:
_, self.prefix_jinja_template = parse_template_string(prefix)
rendered_prefix = self._render_prefix(ti)
else:
rendered_prefix = ""
formatter = logging.Formatter(f"{rendered_prefix}:{self.formatter._fmt}")
self.setFormatter(formatter)
self.setLevel(self.level)
def _render_prefix(self, ti: TaskInstance) -> str:
if self.prefix_jinja_template:
jinja_context = ti.get_template_context()
return _render_template_to_string(self.prefix_jinja_template, jinja_context)
logger.warning("'task_log_prefix_template' is in invalid format, ignoring the variable value")
return ""
| TaskHandlerWithCustomFormatter |
python | run-llama__llama_index | llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-sqlite/llama_index/storage/chat_store/sqlite/base.py | {
"start": 3729,
"end": 13741
} | class ____(BaseChatStore):
table_name: Optional[str] = Field(
default="chatstore", description="SQLite table name."
)
_table_class: TableProtocol = PrivateAttr() # type: ignore
_session: sessionmaker = PrivateAttr() # type: ignore
_async_session: async_sessionmaker = PrivateAttr() # type: ignore
def __init__(
self,
session: sessionmaker,
async_session: async_sessionmaker,
table_name: str,
):
super().__init__(
table_name=table_name.lower(),
)
# sqlalchemy model
base = declarative_base()
self._table_class = get_data_model(
base,
table_name,
)
self._session = session
self._async_session = async_session
self._initialize(base)
@classmethod
def from_params(
cls,
database: str,
table_name: str = "chatstore",
connection_string: Optional[str] = None,
async_connection_string: Optional[str] = None,
debug: bool = False,
) -> "SQLiteChatStore":
"""Return connection string from database parameters."""
conn_str = connection_string or f"sqlite:///{database}"
async_conn_str = async_connection_string or (f"sqlite+aiosqlite:///{database}")
session, async_session = cls._connect(conn_str, async_conn_str, debug)
return cls(
session=session,
async_session=async_session,
table_name=table_name,
)
@classmethod
def from_uri(
cls,
uri: str,
table_name: str = "chatstore",
debug: bool = False,
) -> "SQLiteChatStore":
"""Return connection string from database parameters."""
params = params_from_uri(uri)
return cls.from_params(
**params,
table_name=table_name,
debug=debug,
)
@classmethod
def _connect(
cls, connection_string: str, async_connection_string: str, debug: bool
) -> tuple[sessionmaker, async_sessionmaker]:
_engine = create_engine(connection_string, echo=debug)
session = sessionmaker(_engine)
_async_engine = create_async_engine(async_connection_string)
async_session = async_sessionmaker(_async_engine, class_=AsyncSession)
return session, async_session
def _create_tables_if_not_exists(self, base) -> None:
with self._session() as session, session.begin():
base.metadata.create_all(session.connection())
def _initialize(self, base) -> None:
self._create_tables_if_not_exists(base)
def set_messages(self, key: str, messages: list[ChatMessage]) -> None:
"""Set messages for a key."""
with self._session() as session:
session.execute(
insert(self._table_class),
[
{"key": key, "value": message.model_dump(mode="json")}
for message in messages
],
)
session.commit()
async def aset_messages(self, key: str, messages: list[ChatMessage]) -> None:
"""Async version of Get messages for a key."""
async with self._async_session() as session:
await session.execute(
insert(self._table_class),
[
{"key": key, "value": message.model_dump(mode="json")}
for message in messages
],
)
await session.commit()
def get_messages(self, key: str) -> list[ChatMessage]:
"""Get messages for a key."""
with self._session() as session:
result = session.execute(
select(self._table_class)
.where(self._table_class.key == key)
.order_by(self._table_class.id)
)
result = result.scalars().all()
if result:
return [ChatMessage.model_validate(row.value) for row in result]
return []
async def aget_messages(self, key: str) -> list[ChatMessage]:
"""Async version of Get messages for a key."""
async with self._async_session() as session:
result = await session.execute(
select(self._table_class)
.where(self._table_class.key == key)
.order_by(self._table_class.id)
)
result = result.scalars().all()
if result:
return [ChatMessage.model_validate(row.value) for row in result]
return []
def add_message(self, key: str, message: ChatMessage) -> None:
"""Add a message for a key."""
with self._session() as session:
session.execute(
insert(self._table_class),
[{"key": key, "value": message.model_dump(mode="json")}],
)
session.commit()
async def async_add_message(self, key: str, message: ChatMessage) -> None:
"""Async version of Add a message for a key."""
async with self._async_session() as session:
await session.execute(
insert(self._table_class),
[{"key": key, "value": message.model_dump(mode="json")}],
)
await session.commit()
def delete_messages(self, key: str) -> Optional[list[ChatMessage]]:
"""Delete messages for a key."""
with self._session() as session:
session.execute(
delete(self._table_class).where(self._table_class.key == key)
)
session.commit()
return None
async def adelete_messages(self, key: str) -> Optional[list[ChatMessage]]:
"""Async version of Delete messages for a key."""
async with self._async_session() as session:
await session.execute(
delete(self._table_class).where(self._table_class.key == key)
)
await session.commit()
return None
def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
"""Delete specific message for a key."""
with self._session() as session:
# First, retrieve message
result = session.execute(
select(self._table_class.value).where(
self._table_class.key == key, self._table_class.id == idx
)
).scalar_one_or_none()
if result is None:
return None
session.execute(
delete(self._table_class).where(
self._table_class.key == key, self._table_class.id == idx
)
)
session.commit()
return ChatMessage.model_validate(result)
async def adelete_message(self, key: str, idx: int) -> Optional[ChatMessage]:
"""Async version of Delete specific message for a key."""
async with self._async_session() as session:
# First, retrieve message
result = (
await session.execute(
select(self._table_class.value).where(
self._table_class.key == key, self._table_class.id == idx
)
)
).scalar_one_or_none()
if result is None:
return None
await session.execute(
delete(self._table_class).where(
self._table_class.key == key, self._table_class.id == idx
)
)
await session.commit()
return ChatMessage.model_validate(result)
def delete_last_message(self, key: str) -> Optional[ChatMessage]:
"""Delete last message for a key."""
with self._session() as session:
# First, retrieve the current list of messages
stmt = (
select(self._table_class.id, self._table_class.value)
.where(self._table_class.key == key)
.order_by(self._table_class.id.desc())
.limit(1)
)
result = session.execute(stmt).all()
if not result:
# If the key doesn't exist or the array is empty
return None
session.execute(
delete(self._table_class).where(self._table_class.id == result[0][0])
)
session.commit()
return ChatMessage.model_validate(result[0][1])
async def adelete_last_message(self, key: str) -> Optional[ChatMessage]:
"""Async version of Delete last message for a key."""
async with self._async_session() as session:
# First, retrieve the current list of messages
stmt = (
select(self._table_class.id, self._table_class.value)
.where(self._table_class.key == key)
.order_by(self._table_class.id.desc())
.limit(1)
)
result = (await session.execute(stmt)).all()
if not result:
# If the key doesn't exist or the array is empty
return None
await session.execute(
delete(self._table_class).where(self._table_class.id == result[0][0])
)
await session.commit()
return ChatMessage.model_validate(result[0][1])
def get_keys(self) -> list[str]:
"""Get all keys."""
with self._session() as session:
stmt = select(self._table_class.key.distinct())
return session.execute(stmt).scalars().all()
async def aget_keys(self) -> list[str]:
"""Async version of Get all keys."""
async with self._async_session() as session:
stmt = select(self._table_class.key.distinct())
return (await session.execute(stmt)).scalars().all()
def params_from_uri(uri: str) -> dict:
result = urlparse(uri)
database = result.path[1:]
return {"database": database}
| SQLiteChatStore |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_pie04.py | {
"start": 315,
"end": 1252
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_pie04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "pie"})
data = [
[2, 4, 6],
[60, 30, 10],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$3",
"values": "=Sheet1!$B$1:$B$3",
}
)
chart.set_legend({"position": "overlay_right"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 63466,
"end": 65419
} | class ____(unittest.TestCase):
def mock_server_class(self):
return mock.MagicMock(
return_value=mock.MagicMock(
__enter__=mock.MagicMock(
return_value=mock.MagicMock(
socket=mock.MagicMock(
getsockname=lambda: ('', 0),
),
),
),
),
)
@mock.patch('builtins.print')
def test_server_test_unspec(self, _):
mock_server = self.mock_server_class()
server.test(ServerClass=mock_server, bind=None)
self.assertIn(
mock_server.address_family,
(socket.AF_INET6, socket.AF_INET),
)
@mock.patch('builtins.print')
def test_server_test_localhost(self, _):
mock_server = self.mock_server_class()
server.test(ServerClass=mock_server, bind="localhost")
self.assertIn(
mock_server.address_family,
(socket.AF_INET6, socket.AF_INET),
)
ipv6_addrs = (
"::",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"::1",
)
ipv4_addrs = (
"0.0.0.0",
"8.8.8.8",
"127.0.0.1",
)
@mock.patch('builtins.print')
def test_server_test_ipv6(self, _):
for bind in self.ipv6_addrs:
mock_server = self.mock_server_class()
server.test(ServerClass=mock_server, bind=bind)
self.assertEqual(mock_server.address_family, socket.AF_INET6)
@mock.patch('builtins.print')
def test_server_test_ipv4(self, _):
for bind in self.ipv4_addrs:
mock_server = self.mock_server_class()
server.test(ServerClass=mock_server, bind=bind)
self.assertEqual(mock_server.address_family, socket.AF_INET)
def setUpModule():
unittest.addModuleCleanup(os.chdir, os.getcwd())
if __name__ == '__main__':
unittest.main()
| ScriptTestCase |
python | spack__spack | lib/spack/spack/util/windows_registry.py | {
"start": 15529,
"end": 16065
} | class ____(RegistryError):
"""A Runtime Error ecountered when a registry operation is invalid for
an indeterminate reason"""
def __init__(self, name, e, *args, **kwargs):
message = (
f"Windows registry operations: {name} encountered error: {str(e)}"
"\nMethod invoked with parameters:\n"
)
message += "\n\t".join([f"{k}:{v}" for k, v in kwargs.items()])
message += "\n"
message += "\n\t".join(args)
super().__init__(self, message)
| InvalidRegistryOperation |
python | doocs__leetcode | solution/0900-0999/0956.Tallest Billboard/Solution2.py | {
"start": 0,
"end": 634
} | class ____:
def tallestBillboard(self, rods: List[int]) -> int:
n = len(rods)
s = sum(rods)
f = [[-inf] * (s + 1) for _ in range(n + 1)]
f[0][0] = 0
t = 0
for i, x in enumerate(rods, 1):
t += x
for j in range(t + 1):
f[i][j] = f[i - 1][j]
if j >= x:
f[i][j] = max(f[i][j], f[i - 1][j - x])
if j + x <= t:
f[i][j] = max(f[i][j], f[i - 1][j + x] + x)
if j < x:
f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j)
return f[n][0]
| Solution |
python | spyder-ide__spyder | spyder/api/widgets/comboboxes.py | {
"start": 2410,
"end": 5078
} | class ____(QLineEdit):
"""Lineedit used for comboboxes."""
sig_mouse_clicked = Signal()
def __init__(self, parent, editable, elide_mode=None):
super().__init__(parent)
self._editable = editable
self._elide_mode = elide_mode
self._focus_in = False
# Fix style issues
css = qstylizer.style.StyleSheet()
css.QLineEdit.setValues(
# These are necessary on Windows to prevent some ugly visual
# glitches.
backgroundColor="transparent",
border="none",
padding="0px",
# Make text look centered for short comboboxes
paddingRight=f"-{3 if WIN else 2}px"
)
self.setStyleSheet(css.toString())
def mouseReleaseEvent(self, event):
if not self._editable:
# Emit a signal to display the popup afterwards
self.sig_mouse_clicked.emit()
super().mouseReleaseEvent(event)
def mouseDoubleClickEvent(self, event):
if not self._editable:
# Avoid selecting the lineedit text with double clicks
pass
else:
super().mouseDoubleClickEvent(event)
def focusInEvent(self, event):
self._focus_in = True
super().focusInEvent(event)
def focusOutEvent(self, event):
self._focus_in = False
super().focusOutEvent(event)
def paintEvent(self, event):
if self._elide_mode is not None and not self._focus_in:
# This code is taken for the most part from the
# AmountEdit.paintEvent method, part of the Electrum project. See
# the Electrum entry in our NOTICE.txt file for the details.
# Licensed under the MIT license.
painter = QPainter(self)
option = QStyleOptionFrame()
self.initStyleOption(option)
text_rect = self.style().subElementRect(
QStyle.SE_LineEditContents, option, self
)
# Neded so the text is placed correctly according to our style
text_rect.adjust(2, 0, 0, 0)
fm = QFontMetrics(self.font())
text = fm.elidedText(
self.text(), self._elide_mode, text_rect.width()
)
color = (
SpyderPalette.COLOR_TEXT_1
if self.isEnabled()
else SpyderPalette.COLOR_DISABLED
)
painter.setPen(QColor(color))
painter.drawText(
text_rect, int(Qt.AlignLeft | Qt.AlignVCenter), text
)
return
super().paintEvent(event)
| _SpyderComboBoxLineEdit |
python | apache__airflow | task-sdk/tests/task_sdk/api/test_client.py | {
"start": 36898,
"end": 38878
} | class ____:
"""
Test that the TestConnectionOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for connections including endpoint and
response parsing.
"""
def test_connection_get_success(self):
# Simulate a successful response from the server with a connection
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/connections/test_conn":
return httpx.Response(
status_code=200,
json={
"conn_id": "test_conn",
"conn_type": "mysql",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.connections.get(conn_id="test_conn")
assert isinstance(result, ConnectionResponse)
assert result.conn_id == "test_conn"
assert result.conn_type == "mysql"
def test_connection_get_404_not_found(self):
# Simulate a successful response from the server with a connection
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/connections/test_conn":
return httpx.Response(
status_code=404,
json={
"reason": "not_found",
"message": "Connection with ID test_conn not found",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.connections.get(conn_id="test_conn")
assert isinstance(result, ErrorResponse)
assert result.error == ErrorType.CONNECTION_NOT_FOUND
| TestConnectionOperations |
python | ansible__ansible | test/integration/targets/ansible-test-container/runme.py | {
"start": 39572,
"end": 41334
} | class ____(Bootstrapper):
"""Bootstrapper for apk based systems."""
@classmethod
def install_podman(cls) -> bool:
"""Return True if podman will be installed."""
return True
@classmethod
def install_docker(cls) -> bool:
"""Return True if docker will be installed."""
return True
@classmethod
def usable(cls) -> bool:
"""Return True if the bootstrapper can be used, otherwise False."""
return bool(shutil.which('apk'))
@classmethod
def run(cls) -> None:
"""Run the bootstrapper."""
# The `openssl` package is used to generate hashed passwords.
# The `crun` package must be explicitly installed since podman won't install it as dep if `runc` is present.
packages = ['docker', 'podman', 'openssl', 'crun']
if os_release.version_id.startswith('3.18.'):
# The 3.19 `crun` package installed below requires `ip6tables`, but depends on the `iptables` package.
# In 3.19, the `iptables` package includes `ip6tables`, but in 3.18 they are separate packages.
# Remove once 3.18 is no longer tested.
packages.append('ip6tables')
run_command('apk', 'add', *packages)
if os_release.version_id.startswith('3.18.'):
# 3.18 only contains `crun` 1.8.4, to get a newer version that resolves the run/shm issue, install `crun` from 3.19.
# Remove once 3.18 is no longer tested.
run_command('apk', 'upgrade', '-U', '--repository=http://dl-cdn.alpinelinux.org/alpine/v3.19/community', 'crun')
run_command('service', 'docker', 'start')
run_command('modprobe', 'tun')
super().run()
@dataclasses.dataclass(frozen=True)
| ApkBootstrapper |
python | Farama-Foundation__Gymnasium | tests/testing_env.py | {
"start": 5318,
"end": 8436
} | class ____(VectorEnv):
"""A generic testing vector environment similar to GenericTestEnv.
Some tests cannot use SyncVectorEnv, e.g. when returning non-numpy arrays in the observations.
In these cases, GenericTestVectorEnv can be used to simulate a vector environment.
"""
def __init__(
self,
num_envs: int = 1,
action_space: spaces.Space = spaces.Box(0, 1, (1,)),
observation_space: spaces.Space = spaces.Box(0, 1, (1,)),
reset_func: Callable = basic_vector_reset_func,
step_func: Callable = basic_vector_step_func,
render_func: Callable = basic_vector_render_func,
metadata: dict[str, Any] = {
"render_modes": [],
"autoreset_mode": AutoresetMode.NEXT_STEP,
},
render_mode: str | None = None,
spec: EnvSpec = EnvSpec(
"TestingVectorEnv-v0",
"tests.testing_env:GenericTestVectorEnv",
max_episode_steps=100,
),
):
"""Generic testing vector environment constructor.
Args:
num_envs: The number of environments to create
action_space: The environment action space
observation_space: The environment observation space
reset_func: The environment reset function
step_func: The environment step function
render_func: The environment render function
metadata: The environment metadata
render_mode: The render mode of the environment
spec: The environment spec
"""
super().__init__()
self.num_envs = num_envs
self.metadata = metadata
self.render_mode = render_mode
self.spec = spec
# Set the single spaces and create batched spaces
self.single_observation_space = observation_space
self.single_action_space = action_space
self.observation_space = batch_space(observation_space, num_envs)
self.action_space = batch_space(action_space, num_envs)
# Bind the functions to the instance
if reset_func is not None:
self.reset = types.MethodType(reset_func, self)
if step_func is not None:
self.step = types.MethodType(step_func, self)
if render_func is not None:
self.render = types.MethodType(render_func, self)
def reset(
self,
*,
seed: int | None = None,
options: dict | None = None,
) -> tuple[ObsType, dict]:
"""Resets the environment."""
# If you need a default working reset function, use `basic_vector_reset_fn` above
raise NotImplementedError("TestingVectorEnv reset_fn is not set.")
def step(
self, action: ActType
) -> tuple[ObsType, np.ndarray, np.ndarray, np.ndarray, dict]:
"""Steps through the environment."""
raise NotImplementedError("TestingVectorEnv step_fn is not set.")
def render(self) -> tuple[Any, ...] | None:
"""Renders the environment."""
raise NotImplementedError("TestingVectorEnv render_fn is not set.")
| GenericTestVectorEnv |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 53552,
"end": 56395
} | class ____(Kosmos2PreTrainedModel):
config: Kosmos2TextConfig
input_modalities = ("text",)
def __init__(self, config: Kosmos2TextConfig):
super().__init__(config)
self.model = Kosmos2TextTransformer(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.model.embed_tokens
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
image_embeds: Optional[torch.Tensor] = None,
image_embeds_position_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = 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.Tensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]:
r"""
image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
1]`:
- 1 for places where to put the image features,
- 0 for places that are not for image features (i.e. for text tokens).
"""
return self.model(
input_ids=input_ids,
attention_mask=attention_mask,
image_embeds=image_embeds,
image_embeds_position_mask=image_embeds_position_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
position_ids=position_ids,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)
@auto_docstring(
custom_intro="""
The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
embeddings).
"""
)
| Kosmos2TextModel |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_superfences.py | {
"start": 22366,
"end": 24728
} | class ____(util.MdCase):
"""Test classes and ids without attribute lists."""
extension = ['pymdownx.superfences']
extension_configs = {}
def test_classes(self):
"""Test extra classes."""
self.check_markdown(
r'''
```{.python .more}
import test
```
''',
r'''
<div class="more highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
</code></pre></div>
''', # noqa: E501
True
)
def test_id(self):
"""Test extra id."""
self.check_markdown(
r'''
```{.python #id}
import test
```
''',
r'''
<div id="id" class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
</code></pre></div>
''', # noqa: E501
True
)
def test_attr(self):
"""Test extra attributes."""
self.check_markdown(
r'''
```{.python #id attr="test"}
import test
```
''',
r'''
<div id="id" class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
</code></pre></div>
''', # noqa: E501
True
)
def test_attrs_alternate_form(self):
"""Test attributes with new alternate form."""
self.check_markdown(
r'''
```python {.test .class #class}
import test
```
''',
r'''
<div id="class" class="test class highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
</code></pre></div>
''', # noqa: E501
True
)
def test_issue_2479(self):
"""Test issue #2479."""
self.check_markdown(
"""```test_test_test_test_test_test_test_test``` test test.""",
"""
<p><code>test_test_test_test_test_test_test_test</code> test test.</p>
""",
True
)
| TestSuperFencesClassesIds |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_mep.py | {
"start": 146434,
"end": 150674
} | class ____(
OrganizationEventsMetricsEnhancedPerformanceEndpointTest
):
def setUp(self) -> None:
super().setUp()
self.features["organizations:use-metrics-layer"] = True
@pytest.mark.xfail(reason="Not supported")
def test_time_spent(self) -> None:
super().test_time_spent()
@pytest.mark.xfail(reason="Not supported")
def test_http_error_rate(self) -> None:
super().test_http_error_rate()
@pytest.mark.xfail(reason="Multiple aliases to same column not supported")
def test_title_and_transaction_alias(self) -> None:
super().test_title_and_transaction_alias()
@pytest.mark.xfail(reason="Sort order is flaking when querying multiple datasets")
def test_maintain_sort_order_across_datasets(self) -> None:
"""You may need to run this test a few times to get it to fail"""
super().test_maintain_sort_order_across_datasets()
@pytest.mark.xfail(reason="Not implemented")
def test_avg_compare(self) -> None:
super().test_avg_compare()
@pytest.mark.xfail(reason="Not implemented")
def test_avg_if(self) -> None:
super().test_avg_if()
@pytest.mark.xfail(reason="Not implemented")
def test_count_if(self) -> None:
super().test_count_if()
@pytest.mark.xfail(reason="Not implemented")
def test_device_class(self) -> None:
super().test_device_class()
@pytest.mark.xfail(reason="Not implemented")
def test_device_class_filter(self) -> None:
super().test_device_class_filter()
@pytest.mark.xfail(reason="Not implemented")
def test_performance_score(self) -> None:
super().test_performance_score()
@pytest.mark.xfail(reason="Not implemented")
def test_performance_score_boundaries(self) -> None:
super().test_performance_score_boundaries()
@pytest.mark.xfail(reason="Not implemented")
def test_total_performance_score(self) -> None:
super().test_total_performance_score()
@pytest.mark.xfail(reason="Not implemented")
def test_total_performance_score_with_missing_vitals(self) -> None:
super().test_total_performance_score_with_missing_vitals()
@pytest.mark.xfail(reason="Not implemented")
def test_invalid_performance_score_column(self) -> None:
super().test_invalid_performance_score_column()
@pytest.mark.xfail(reason="Not implemented")
def test_opportunity_score(self) -> None:
super().test_opportunity_score()
@pytest.mark.xfail(reason="Not implemented")
def test_opportunity_score_with_fixed_weights_and_missing_vitals(self) -> None:
super().test_opportunity_score_with_fixed_weights_and_missing_vitals()
@pytest.mark.xfail(reason="Not implemented")
def test_count_scores(self) -> None:
super().test_count_scores()
@pytest.mark.xfail(reason="Not implemented")
def test_count_starts(self) -> None:
super().test_count_starts()
@pytest.mark.xfail(reason="Not implemented")
def test_count_starts_returns_all_counts_when_no_arg_is_passed(self) -> None:
super().test_count_starts_returns_all_counts_when_no_arg_is_passed()
@pytest.mark.xfail(reason="Not implemented")
def test_timestamp_groupby(self) -> None:
super().test_timestamp_groupby()
@pytest.mark.xfail(reason="Not implemented")
def test_on_demand_with_mep(self) -> None:
super().test_on_demand_with_mep()
@pytest.mark.xfail(reason="Not implemented")
def test_cache_miss_rate(self) -> None:
super().test_cache_miss_rate()
@pytest.mark.xfail(reason="Not implemented")
def test_http_response_rate(self) -> None:
super().test_http_response_rate()
@pytest.mark.xfail(reason="Not implemented")
def test_avg_span_self_time(self) -> None:
super().test_avg_span_self_time()
@pytest.mark.xfail(reason="Not implemented")
def test_avg_message_receive_latency_gauge_functions(self) -> None:
super().test_avg_message_receive_latency_gauge_functions()
@pytest.mark.xfail(reason="Not implemented")
def test_span_module_filter(self) -> None:
super().test_span_module_filter()
| OrganizationEventsMetricsEnhancedPerformanceEndpointTestWithMetricLayer |
python | coleifer__peewee | tests/regressions.py | {
"start": 8823,
"end": 9348
} | class ____(BaseTestCase):
def test_subquery_function_call(self):
Sample = Table('sample')
SA = Sample.alias('s2')
query = (Sample
.select(Sample.c.data)
.where(~fn.EXISTS(
SA.select(SQL('1')).where(SA.c.key == 'foo'))))
self.assertSQL(query, (
'SELECT "t1"."data" FROM "sample" AS "t1" '
'WHERE NOT EXISTS('
'SELECT 1 FROM "sample" AS "s2" WHERE ("s2"."key" = ?))'), ['foo'])
| TestSubqueryFunctionCall |
python | huggingface__transformers | src/transformers/models/colqwen2/modular_colqwen2.py | {
"start": 13944,
"end": 18473
} | class ____(ColPaliForRetrieval):
_checkpoint_conversion_mapping = {}
def __init__(self, config: ColQwen2Config):
super().__init__(config)
del self._tied_weights_keys
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
labels: Optional[torch.LongTensor] = 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,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
cache_position: Optional[torch.LongTensor] = None,
) -> ColQwen2ForRetrievalOutput:
r"""
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
The temporal, height and width of feature shape of each image in LLM.
"""
# Handle the custom "pixel_values" input obtained with `ColQwen2Processor` through unpadding
if pixel_values is not None and image_grid_thw is not None:
# NOTE: image_grid_thw: (batch_size, 3) where image_grid_thw[i] = (num_patches_h, num_patches_w, temporal_patch_size)
offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (num_patches_h, num_patches_w)
pixel_values = torch.cat(
[pixel_sequence[:offset] for pixel_sequence, offset in zip(pixel_values, offsets)],
dim=0,
) # (num_patches_h * num_patches_w, pixel_values)
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
position_ids, rope_deltas = self.vlm.model.get_rope_index(
input_ids=input_ids,
image_grid_thw=image_grid_thw,
video_grid_thw=None,
attention_mask=attention_mask,
)
# Custom data preparation to fix an issue with the gradient flow when training with multiple GPUs.
if inputs_embeds is None:
inputs_embeds = self.vlm.get_input_embeddings()(input_ids)
if pixel_values is not None:
image_embeds = self.vlm.model.visual(pixel_values, grid_thw=image_grid_thw)
image_mask = (
(input_ids == self.config.vlm_config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
)
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
vlm_output = self.vlm.model(
input_ids=None,
position_ids=position_ids,
attention_mask=attention_mask,
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,
)
vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
proj_dtype = self.embedding_proj_layer.weight.dtype
embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
# L2 normalization
embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
if attention_mask is not None:
embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
return ColQwen2ForRetrievalOutput(
embeddings=embeddings,
past_key_values=vlm_output.past_key_values,
hidden_states=vlm_hidden_states,
attentions=vlm_output.attentions,
)
__all__ = [
"ColQwen2ForRetrieval",
"ColQwen2PreTrainedModel",
"ColQwen2Processor",
]
| ColQwen2ForRetrieval |
python | spack__spack | lib/spack/spack/environment/depfile.py | {
"start": 3958,
"end": 10804
} | class ____:
"""This class produces all data to render a makefile for specs of an environment."""
def __init__(
self,
env: ev.Environment,
roots: List[spack.spec.Spec],
adjacency_list: List[DepfileNode],
make_prefix: Optional[str],
jobserver: bool,
):
"""
Args:
env: environment to generate the makefile for
roots: specs that get built in the default target
adjacency_list: list of DepfileNode, mapping specs to their dependencies
make_prefix: prefix for makefile targets
jobserver: when enabled, make will invoke Spack with jobserver support. For
dry-run this should be disabled.
"""
# Currently we can only use depfile with an environment since Spack needs to
# find the concrete specs somewhere.
self.env_path = env.path
# These specs are built in the default target.
self.roots = list(MakefileSpec(x) for x in roots)
# The SPACK_PACKAGE_IDS variable is "exported", which can be used when including
# generated makefiles to add post-install hooks, like pushing to a buildcache,
# running tests, etc.
if make_prefix is None:
self.make_prefix = os.path.join(env.env_subdir_path, "makedeps")
self.pkg_identifier_variable = "SPACK_PACKAGE_IDS"
else:
# NOTE: GNU Make allows directory separators in variable names, so for consistency
# we can namespace this variable with the same prefix as targets.
self.make_prefix = make_prefix
self.pkg_identifier_variable = os.path.join(make_prefix, "SPACK_PACKAGE_IDS")
# And here we collect a tuple of (target, prereqs, dag_hash, nice_name, buildcache_flag)
self.make_adjacency_list = [
(
item.target.safe_name(),
" ".join(self._install_target(s.safe_name()) for s in item.prereqs),
item.target.spec_hash(),
item.target.unsafe_format(
"{name}{@version}{variants}"
"{ platform=architecture.platform}{ os=architecture.os}"
"{ target=architecture.target}"
),
item.buildcache_flag,
)
for item in adjacency_list
]
# Root specs without deps are the prereqs for the environment target
self.root_install_targets = [self._install_target(s.safe_name()) for s in self.roots]
self.jobserver_support = "+" if jobserver else ""
# All package identifiers, used to generate the SPACK_PACKAGE_IDS variable
self.all_pkg_identifiers: List[str] = []
# All install and install-deps targets
self.all_install_related_targets: List[str] = []
# Convenience shortcuts: ensure that `make install/pkg-version-hash` triggers
# <absolute path to env>/.spack-env/makedeps/install/pkg-version-hash in case
# we don't have a custom make target prefix.
self.phony_convenience_targets: List[str] = []
for node in adjacency_list:
tgt = node.target.safe_name()
self.all_pkg_identifiers.append(tgt)
self.all_install_related_targets.append(self._install_target(tgt))
self.all_install_related_targets.append(self._install_deps_target(tgt))
if make_prefix is None:
self.phony_convenience_targets.append(os.path.join("install", tgt))
self.phony_convenience_targets.append(os.path.join("install-deps", tgt))
def _target(self, name: str) -> str:
# The `all` and `clean` targets are phony. It doesn't make sense to
# have /abs/path/to/env/metadir/{all,clean} targets. But it *does* make
# sense to have a prefix like `env/all`, `env/clean` when they are
# supposed to be included
if name in ("all", "clean") and os.path.isabs(self.make_prefix):
return name
else:
return os.path.join(self.make_prefix, name)
def _install_target(self, name: str) -> str:
return os.path.join(self.make_prefix, "install", name)
def _install_deps_target(self, name: str) -> str:
return os.path.join(self.make_prefix, "install-deps", name)
def to_dict(self):
return {
"all_target": self._target("all"),
"env_target": self._target("env"),
"clean_target": self._target("clean"),
"all_install_related_targets": " ".join(self.all_install_related_targets),
"root_install_targets": " ".join(self.root_install_targets),
"dirs_target": self._target("dirs"),
"environment": self.env_path,
"install_target": self._target("install"),
"install_deps_target": self._target("install-deps"),
"any_hash_target": self._target("%"),
"jobserver_support": self.jobserver_support,
"spack_script": shlex.quote(spack.paths.spack_script),
"adjacency_list": self.make_adjacency_list,
"phony_convenience_targets": " ".join(self.phony_convenience_targets),
"pkg_ids_variable": self.pkg_identifier_variable,
"pkg_ids": " ".join(self.all_pkg_identifiers),
}
@property
def empty(self):
return len(self.roots) == 0
@staticmethod
def from_env(
env: ev.Environment,
*,
filter_specs: Optional[List[spack.spec.Spec]] = None,
pkg_buildcache: UseBuildCache = UseBuildCache.AUTO,
dep_buildcache: UseBuildCache = UseBuildCache.AUTO,
make_prefix: Optional[str] = None,
jobserver: bool = True,
) -> "MakefileModel":
"""Produces a MakefileModel from an environment and a list of specs.
Args:
env: the environment to use
filter_specs: if provided, only these specs will be built from the environment,
otherwise the environment roots are used.
pkg_buildcache: whether to only use the buildcache for top-level specs.
dep_buildcache: whether to only use the buildcache for non-top-level specs.
make_prefix: the prefix for the makefile targets
jobserver: when enabled, make will invoke Spack with jobserver support. For
dry-run this should be disabled.
"""
roots = env.all_matching_specs(*filter_specs) if filter_specs else env.concrete_roots()
visitor = DepfileSpecVisitor(pkg_buildcache, dep_buildcache)
traverse.traverse_breadth_first_with_visitor(
roots, traverse.CoverNodesVisitor(visitor, key=lambda s: s.dag_hash())
)
return MakefileModel(env, roots, visitor.adjacency_list, make_prefix, jobserver)
| MakefileModel |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 7016,
"end": 7407
} | class ____(TestCase):
"""Smoke test (shape_like) -> array."""
shape = (3, 4)
@parametrize("func", shape_funcs)
def test_shape(self, func):
a = func(self.shape)
assert isinstance(a, w.ndarray)
assert a.shape == self.shape
seq_funcs = [w.atleast_1d, w.atleast_2d, w.atleast_3d, w.broadcast_arrays]
@instantiate_parametrized_tests
| TestShapeLikeToArray |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 39838,
"end": 41827
} | class ____(XYGlyph, LineGlyph, FillGlyph, HatchGlyph):
''' Render rectangles, characterised by center position (x and y), width,
height, and angle of rotation.
.. warning::
``Rect`` glyphs are not well defined on logarithmic scales. Use
:class:`~bokeh.models.Block` or :class:`~bokeh.models.Quad` glyphs
instead.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
__example__ = "examples/reference/models/Rect.py"
_args = ('x', 'y', 'width', 'height', 'angle', 'dilate')
x = NumberSpec(default=field("x"), help="""
The x-coordinates of the centers of the rectangles.
""")
y = NumberSpec(default=field("y"), help="""
The y-coordinates of the centers of the rectangles.
""")
width = DistanceSpec(default=field("width"), help="""
The overall widths of the rectangles.
""")
height = DistanceSpec(default=field("height"), help="""
The overall heights of the rectangles.
""")
angle = AngleSpec(default=0.0, help="""
The angles to rotate the rectangles, as measured from the horizontal.
""")
border_radius = BorderRadius(default=0, help="""
Allows the box to have rounded corners.
.. note::
This property is experimental and may change at any point.
""")
dilate = Bool(False, help="""
Whether to always round fractional pixel locations in such a way
as to make the rectangles bigger.
This setting may be useful if pixel rounding errors are causing
rectangles to have a gap between them, when they should appear
flush.
""")
line_props = Include(LineProps, help="""
The {prop} values for the rectangles.
""")
fill_props = Include(FillProps, help="""
The {prop} values for the rectangles.
""")
hatch_props = Include(HatchProps, help="""
The {prop} values for the rectangles.
""")
| Rect |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 33908,
"end": 34848
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a work queue."""
name: Name = Field(default=..., description="The name of the work queue.")
description: Optional[str] = Field(
default="", description="An optional description for the work queue."
)
is_paused: bool = Field(
default=False, description="Whether or not the work queue is paused."
)
concurrency_limit: Optional[NonNegativeInteger] = Field(
None, description="The work queue's concurrency limit."
)
priority: Optional[PositiveInteger] = Field(
None,
description=(
"The queue's priority. Lower values are higher priority (1 is the highest)."
),
)
# DEPRECATED
filter: Optional[schemas.core.QueueFilter] = Field(
None,
description="DEPRECATED: Filter criteria for the work queue.",
deprecated=True,
)
| WorkQueueCreate |
python | spyder-ide__spyder | spyder/utils/stylesheet.py | {
"start": 29703,
"end": 30992
} | class ____(SpyderFontsMixin):
"""Style constants for tour and about dialogs."""
IconScaleFactor = 0.5
BackgroundColor = SpyderPalette.COLOR_BACKGROUND_2
BorderColor = SpyderPalette.COLOR_BACKGROUND_5
@classproperty
def _fs(cls):
return cls.get_font(SpyderFontType.Interface).pointSize()
@classproperty
def TitleFontSize(cls):
if WIN:
return f"{cls._fs + 6}pt"
elif MAC:
return f"{cls._fs + 6}pt"
else:
return f"{cls._fs + 4}pt"
@classproperty
def ContentFontSize(cls):
if WIN:
return f"{cls._fs + 4}pt"
elif MAC:
return f"{cls._fs + 2}pt"
else:
return f"{cls._fs + 2}pt"
@classproperty
def ButtonsFontSize(cls):
if WIN:
return f"{cls._fs + 5}pt"
elif MAC:
return f"{cls._fs + 2}pt"
else:
return f"{cls._fs + 3}pt"
@classproperty
def ButtonsPadding(cls):
if WIN:
return f"{AppStyle.MarginSize + 1}px {5 * AppStyle.MarginSize}px"
elif MAC:
return f"{2 * AppStyle.MarginSize}px {4 * AppStyle.MarginSize}px"
else:
return f"{AppStyle.MarginSize + 1}px {AppStyle.MarginSize}px"
| DialogStyle |
python | kamyu104__LeetCode-Solutions | Python/cells-in-a-range-on-an-excel-sheet.py | {
"start": 46,
"end": 283
} | class ____(object):
def cellsInRange(self, s):
"""
:type s: str
:rtype: List[str]
"""
return [chr(x)+chr(y) for x in xrange(ord(s[0]), ord(s[3])+1) for y in xrange(ord(s[1]), ord(s[4])+1)]
| Solution |
python | aimacode__aima-python | text.py | {
"start": 3291,
"end": 4745
} | class ____(NgramCharModel):
def __init__(self, observation_sequence=None, default=0):
CountingProbDist.__init__(self, default=default)
self.n = 1
self.cond_prob = defaultdict()
self.add_sequence(observation_sequence or [])
def add_sequence(self, words):
for word in words:
for char in word:
self.add(char)
# ______________________________________________________________________________
def viterbi_segment(text, P):
"""Find the best segmentation of the string of characters, given the
UnigramWordModel P."""
# best[i] = best probability for text[0:i]
# words[i] = best word ending at position i
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
# Fill in the vectors best words via dynamic programming
for i in range(n + 1):
for j in range(0, i):
w = text[j:i]
curr_score = P[w] * best[i - len(w)]
if curr_score >= best[i]:
best[i] = curr_score
words[i] = w
# Now recover the sequence of best words
sequence = []
i = len(words) - 1
while i > 0:
sequence[0:0] = [words[i]]
i = i - len(words[i])
# Return sequence of best words and overall probability
return sequence, best[-1]
# ______________________________________________________________________________
# TODO(tmrts): Expose raw index
| UnigramCharModel |
python | ray-project__ray | rllib/utils/exploration/per_worker_ornstein_uhlenbeck_noise.py | {
"start": 275,
"end": 1947
} | class ____(OrnsteinUhlenbeckNoise):
"""A per-worker Ornstein Uhlenbeck noise class for distributed algorithms.
Sets the Gaussian `scale` schedules of individual workers to a constant:
0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7)
See Ape-X paper.
"""
def __init__(
self,
action_space: Space,
*,
framework: Optional[str],
num_workers: Optional[int],
worker_index: Optional[int],
**kwargs
):
"""
Args:
action_space: The gym action space used by the environment.
num_workers: The overall number of workers used.
worker_index: The index of the Worker using this
Exploration.
framework: One of None, "tf", "torch".
"""
scale_schedule = None
# Use a fixed, different epsilon per worker. See: Ape-X paper.
if num_workers > 0:
if worker_index > 0:
num_workers_minus_1 = float(num_workers - 1) if num_workers > 1 else 1.0
exponent = 1 + (worker_index / num_workers_minus_1) * 7
scale_schedule = ConstantSchedule(0.4**exponent, framework=framework)
# Local worker should have zero exploration so that eval
# rollouts run properly.
else:
scale_schedule = ConstantSchedule(0.0, framework=framework)
super().__init__(
action_space,
scale_schedule=scale_schedule,
num_workers=num_workers,
worker_index=worker_index,
framework=framework,
**kwargs
)
| PerWorkerOrnsteinUhlenbeckNoise |
python | joerick__pyinstrument | test/fake_time_util.py | {
"start": 776,
"end": 1912
} | class ____:
# this implementation mostly lifted from
# https://aiotools.readthedocs.io/en/latest/_modules/aiotools/timer.html#VirtualClock
# License: https://github.com/achimnol/aiotools/blob/800f7f1bce086b0c83658bad8377e6cb1908e22f/LICENSE
# Copyright (c) 2017 Joongi Kim
def __init__(self) -> None:
self.time = random.random() * 1e6
def get_time(self):
return self.time
def sleep(self, duration):
self.time += duration
def _virtual_select(self, orig_select, timeout):
self.time += timeout
return orig_select(0) # override the timeout to zero
@contextlib.contextmanager
def fake_time_asyncio(loop=None):
loop = loop or asyncio.get_running_loop()
fake_clock = FakeClockAsyncio()
# fmt: off
with mock.patch.object(
loop._selector, # type: ignore
"select",
new=functools.partial(fake_clock._virtual_select, loop._selector.select), # type: ignore
), mock.patch.object(
loop,
"time",
new=fake_clock.get_time
), fake_time(fake_clock):
yield fake_clock
# fmt: on
| FakeClockAsyncio |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 5467,
"end": 7000
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.add(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
output_dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1_sparse = getattr(x1, "sparse", False)
x2_sparse = getattr(x2, "sparse", False)
output_sparse = x1_sparse and x2_sparse
return KerasTensor(
output_shape, dtype=output_dtype, sparse=output_sparse
)
@keras_export(["keras.ops.add", "keras.ops.numpy.add"])
def add(x1, x2):
"""Add arguments element-wise.
Args:
x1: First input tensor.
x2: Second input tensor.
Returns:
The tensor containing the element-wise sum of `x1` and `x2`.
Examples:
>>> x1 = keras.ops.convert_to_tensor([1, 4])
>>> x2 = keras.ops.convert_to_tensor([5, 6])
>>> keras.ops.add(x1, x2)
array([6, 10], dtype=int32)
`keras.ops.add` also broadcasts shapes:
>>> x1 = keras.ops.convert_to_tensor(
... [[5, 4],
... [5, 6]]
... )
>>> x2 = keras.ops.convert_to_tensor([5, 6])
>>> keras.ops.add(x1, x2)
array([[10 10]
[10 12]], shape=(2, 2), dtype=int32)
"""
if any_symbolic_tensors((x1, x2)):
return Add().symbolic_call(x1, x2)
return backend.numpy.add(x1, x2)
| Add |
python | ansible__ansible | lib/ansible/module_utils/six/__init__.py | {
"start": 14646,
"end": 15342
} | class ____(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_urllib_error_moved_attributes = [
MovedAttribute("URLError", "urllib2", "urllib.error"),
MovedAttribute("HTTPError", "urllib2", "urllib.error"),
MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
]
for attr in _urllib_error_moved_attributes:
setattr(Module_six_moves_urllib_error, attr.name, attr)
del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
"moves.urllib_error", "moves.urllib.error")
| Module_six_moves_urllib_error |
python | getsentry__sentry | src/sentry/api/serializers/models/rule.py | {
"start": 1806,
"end": 1853
} | class ____(TypedDict):
detail: str
| _ErrorDict |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 3057,
"end": 3828
} | class ____:
def test_nodata(self):
# The file nodata.arff has no data in the @DATA section.
# Reading it should result in an array with length 0.
nodata_filename = os.path.join(data_path, 'nodata.arff')
data, meta = loadarff(nodata_filename)
if sys.byteorder == 'big':
end = '>'
else:
end = '<'
expected_dtype = np.dtype([('sepallength', f'{end}f8'),
('sepalwidth', f'{end}f8'),
('petallength', f'{end}f8'),
('petalwidth', f'{end}f8'),
('class', 'S15')])
assert_equal(data.dtype, expected_dtype)
assert_equal(data.size, 0)
| TestNoData |
python | jazzband__django-pipeline | pipeline/compilers/es6.py | {
"start": 87,
"end": 602
} | class ____(SubProcessCompiler):
output_extension = "js"
def match_file(self, path):
return path.endswith(".es6")
def compile_file(self, infile, outfile, outdated=False, force=False):
if not outdated and not force:
return # File doesn't need to be recompiled
command = (
settings.BABEL_BINARY,
settings.BABEL_ARGUMENTS,
infile,
"-o",
outfile,
)
return self.execute_command(command)
| ES6Compiler |
python | getsentry__sentry | src/sentry/relocation/api/endpoints/public_key.py | {
"start": 682,
"end": 1974
} | class ____(Endpoint):
owner = ApiOwner.HYBRID_CLOUD
publish_status = {
# TODO(getsentry/team-ospo#214): Stabilize before GA.
"GET": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (SentryIsAuthenticated,)
def get(self, request: Request) -> Response:
"""
Get your public key for relocation encryption.
``````````````````````````````````````````````
Returns a public key which can be used to create an encrypted export tarball.
:auth: required
"""
logger.info("publickeys.relocations.get.start", extra={"caller": request.user.id})
# We only honor the `relocation.enabled` flag for non-superusers/staff.
elevated_user = has_elevated_mode(request)
if not options.get("relocation.enabled") and not elevated_user:
return Response({"detail": ERR_FEATURE_DISABLED}, status=400)
# TODO(getsentry/team-ospo#190): We should support per-user keys in the future.
log_gcp_credentials_details(logger)
public_key_pem = GCPKMSEncryptor.from_crypto_key_version(
get_default_crypto_key_version()
).get_public_key_pem()
return Response({"public_key": public_key_pem.decode("utf-8")}, status=200)
| RelocationPublicKeyEndpoint |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/pod.py | {
"start": 3841,
"end": 3968
} | class ____(Enum):
"""Type of Events emitted by kubernetes pod."""
WARNING = "Warning"
NORMAL = "Normal"
| PodEventType |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/traversals.py | {
"start": 33091,
"end": 34278
} | class ____(TraversalComparatorStrategy):
def compare_column_element(
self, left, right, use_proxies=True, equivalents=(), **kw
):
"""Compare ColumnElements using proxies and equivalent collections.
This is a comparison strategy specific to the ORM.
"""
to_compare = (right,)
if equivalents and right in equivalents:
to_compare = equivalents[right].union(to_compare)
for oth in to_compare:
if use_proxies and left.shares_lineage(oth):
return SKIP_TRAVERSE
elif hash(left) == hash(right):
return SKIP_TRAVERSE
else:
return COMPARE_FAILED
def compare_column(self, left, right, **kw):
return self.compare_column_element(left, right, **kw)
def compare_label(self, left, right, **kw):
return self.compare_column_element(left, right, **kw)
def compare_table(self, left, right, **kw):
# tables compare on identity, since it's not really feasible to
# compare them column by column with the above rules
return SKIP_TRAVERSE if left is right else COMPARE_FAILED
| ColIdentityComparatorStrategy |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 114448,
"end": 119425
} | class ____(Request):
"""
Update project information
:param project: Project id
:type project: str
:param name: Project name. Unique within the company.
:type name: str
:param description: Project description
:type description: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param default_output_destination: The default output destination URL for new
tasks under this project
:type default_output_destination: str
"""
_service = "projects"
_action = "update"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": "string",
},
"description": {"description": "Project description", "type": "string"},
"name": {
"description": "Project name. Unique within the company.",
"type": "string",
},
"project": {"description": "Project id", "type": "string"},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["project"],
"type": "object",
}
def __init__(
self,
project: str,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
default_output_destination: Optional[str] = None,
**kwargs: Any
) -> None:
super(UpdateRequest, self).__init__(**kwargs)
self.project = project
self.name = name
self.description = description
self.tags = tags
self.system_tags = system_tags
self.default_output_destination = default_output_destination
@schema_property("project")
def project(self) -> str:
return self._property_project
@project.setter
def project(self, value: str) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("default_output_destination")
def default_output_destination(self) -> Optional[str]:
return self._property_default_output_destination
@default_output_destination.setter
def default_output_destination(self, value: Optional[str]) -> None:
if value is None:
self._property_default_output_destination = None
return
self.assert_isinstance(value, "default_output_destination", six.string_types)
self._property_default_output_destination = value
| UpdateRequest |
python | getsentry__sentry | src/sentry/api/serializers/models/debug_file.py | {
"start": 139,
"end": 735
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
d = {
"id": str(obj.id),
"uuid": obj.debug_id[:36],
"debugId": obj.debug_id,
"codeId": obj.code_id,
"cpuName": obj.cpu_name,
"objectName": obj.object_name,
"symbolType": obj.file_format,
"headers": obj.file.headers,
"size": obj.file.size,
"sha1": obj.file.checksum,
"dateCreated": obj.file.timestamp,
"data": obj.data or {},
}
return d
| DebugFileSerializer |
python | getsentry__sentry | src/sentry/notifications/platform/discord/provider.py | {
"start": 1117,
"end": 4518
} | class ____(NotificationRenderer[DiscordRenderable]):
provider_key = NotificationProviderKey.DISCORD
@classmethod
def render[DataT: NotificationData](
cls, *, data: DataT, rendered_template: NotificationRenderedTemplate
) -> DiscordRenderable:
from sentry.integrations.discord.message_builder.base.base import DiscordMessageBuilder
from sentry.integrations.discord.message_builder.base.component.action_row import (
DiscordActionRow,
)
from sentry.integrations.discord.message_builder.base.component.base import (
DiscordMessageComponent,
)
from sentry.integrations.discord.message_builder.base.component.button import (
DiscordLinkButton,
)
from sentry.integrations.discord.message_builder.base.embed.base import DiscordMessageEmbed
from sentry.integrations.discord.message_builder.base.embed.footer import (
DiscordMessageEmbedFooter,
)
from sentry.integrations.discord.message_builder.base.embed.image import (
DiscordMessageEmbedImage,
)
components: list[DiscordMessageComponent] = []
embeds = []
body_blocks = cls.render_body_blocks(rendered_template.body)
embeds.append(
DiscordMessageEmbed(
title=rendered_template.subject,
description=body_blocks,
image=(
DiscordMessageEmbedImage(url=rendered_template.chart.url)
if rendered_template.chart
else None
),
footer=(
DiscordMessageEmbedFooter(text=rendered_template.footer)
if rendered_template.footer
else None
),
)
)
if len(rendered_template.actions) > 0:
buttons = [
DiscordLinkButton(
label=action.label,
url=action.link,
)
for action in rendered_template.actions
]
components.append(DiscordActionRow(components=buttons))
builder = DiscordMessageBuilder(embeds=embeds, components=components)
return builder.build()
@classmethod
def render_body_blocks(cls, body: list[NotificationBodyFormattingBlock]) -> str:
description = []
for block in body:
if block.type == NotificationBodyFormattingBlockType.PARAGRAPH:
description.append(f"\n{cls.render_text_blocks(block.blocks)}")
elif block.type == NotificationBodyFormattingBlockType.CODE_BLOCK:
description.append(f"\n```{cls.render_text_blocks(block.blocks)}```")
return "".join(description)
@classmethod
def render_text_blocks(cls, blocks: list[NotificationBodyTextBlock]) -> str:
texts = []
for block in blocks:
if block.type == NotificationBodyTextBlockType.PLAIN_TEXT:
texts.append(block.text)
elif block.type == NotificationBodyTextBlockType.BOLD_TEXT:
texts.append(f"**{block.text}**")
elif block.type == NotificationBodyTextBlockType.CODE:
texts.append(f"`{block.text}`")
return " ".join(texts)
@provider_registry.register(NotificationProviderKey.DISCORD)
| DiscordRenderer |
python | psf__black | src/blib2to3/pygram.py | {
"start": 3235,
"end": 5020
} | class ____(Symbols):
Alternative: int
Alternatives: int
Details: int
Matcher: int
NegatedUnit: int
Repeater: int
Unit: int
python_grammar: Grammar
python_grammar_async_keywords: Grammar
python_grammar_soft_keywords: Grammar
pattern_grammar: Grammar
python_symbols: _python_symbols
pattern_symbols: _pattern_symbols
def initialize(cache_dir: Union[str, "os.PathLike[str]", None] = None) -> None:
global python_grammar
global python_grammar_async_keywords
global python_grammar_soft_keywords
global python_symbols
global pattern_grammar
global pattern_symbols
# The grammar file
_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt")
_PATTERN_GRAMMAR_FILE = os.path.join(
os.path.dirname(__file__), "PatternGrammar.txt"
)
python_grammar = driver.load_packaged_grammar("blib2to3", _GRAMMAR_FILE, cache_dir)
assert "print" not in python_grammar.keywords
assert "exec" not in python_grammar.keywords
soft_keywords = python_grammar.soft_keywords.copy()
python_grammar.soft_keywords.clear()
python_symbols = _python_symbols(python_grammar)
# Python 3.0-3.6
python_grammar.version = (3, 0)
# Python 3.7+
python_grammar_async_keywords = python_grammar.copy()
python_grammar_async_keywords.async_keywords = True
python_grammar_async_keywords.version = (3, 7)
# Python 3.10+
python_grammar_soft_keywords = python_grammar_async_keywords.copy()
python_grammar_soft_keywords.soft_keywords = soft_keywords
python_grammar_soft_keywords.version = (3, 10)
pattern_grammar = driver.load_packaged_grammar(
"blib2to3", _PATTERN_GRAMMAR_FILE, cache_dir
)
pattern_symbols = _pattern_symbols(pattern_grammar)
| _pattern_symbols |
python | pytorch__pytorch | test/distributed/checkpoint/e2e/test_e2e_save_and_load.py | {
"start": 17660,
"end": 19448
} | class ____(DTensorTestBase):
@with_temp_dir
def test_init_state_dict(self):
temp_dir = self.temp_dir
model = TestDummyModel()
optim = torch.optim.Adam(model.parameters(), lr=0.1)
state_dict_to_save = {
"model": get_model_state_dict(model),
"optimizer": get_optimizer_state_dict(model, optim),
}
DCP.save(state_dict_to_save, checkpoint_id=temp_dir)
torch.manual_seed(0)
model_2 = TestDummyModel()
# Changing the learning rate for optimizer, which is not a tensor.
optim_2 = torch.optim.Adam(model_2.parameters(), lr=0.2)
msd = get_model_state_dict(model_2)
osd = get_optimizer_state_dict(model_2, optim_2)
state_dict_to_load = {"model": msd, "optimizer": osd}
DCP.load(state_dict_to_load, checkpoint_id=temp_dir)
# We need to check that the two variables point to the same object in memory,
# since we claim DCP is in-place loading.
self.assertTrue(msd is state_dict_to_load["model"])
self.assertTrue(osd is state_dict_to_load["optimizer"])
# set_state_dict calls load_state_dict for model and optimizer.
# so we should see the optim_2.param_groups learning rate is 0.1 instead of 0.2 now.
set_state_dict(
model_2,
optim_2,
model_state_dict=state_dict_to_load["model"],
optim_state_dict=state_dict_to_load["optimizer"],
)
self.assertEqual(msd, get_model_state_dict(model_2))
self.assertEqual(osd, get_optimizer_state_dict(model_2, optim_2))
self.assertEqual(optim_2.param_groups[0]["lr"], 0.1)
instantiate_parametrized_tests(TestE2ESaveAndLoad)
if __name__ == "__main__":
run_tests()
| TestInitStateDict |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 311502,
"end": 311965
} | class ____(sgqlc.types.Input):
"""Ordering options for team repository connections"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(TeamRepositoryOrderField), graphql_name="field")
"""The field to order repositories by."""
direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction")
"""The ordering direction."""
| TeamRepositoryOrder |
python | doocs__leetcode | solution/2200-2299/2269.Find the K-Beauty of a Number/Solution2.py | {
"start": 0,
"end": 440
} | class ____:
def divisorSubstrings(self, num: int, k: int) -> int:
x, p = 0, 1
t = num
for _ in range(k):
t, v = divmod(t, 10)
x = p * v + x
p *= 10
ans = int(x != 0 and num % x == 0)
p //= 10
while t:
x //= 10
t, v = divmod(t, 10)
x = p * v + x
ans += int(x != 0 and num % x == 0)
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 3088,
"end": 3473
} | class ____(FBMarketingStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/custom-conversion"""
entity_prefix = "customconversion"
def list_objects(self, params: Mapping[str, Any], account_id: str) -> Iterable:
return self._api.get_account(account_id=account_id).get_custom_conversions(params=params, fields=self.fields())
| CustomConversions |
python | django__django | tests/fixtures_regress/models.py | {
"start": 7609,
"end": 7758
} | class ____(BaseNKModel):
a_set = models.ManyToManyField(
"M2MComplexCircular1A", through="M2MCircular1ThroughCA"
)
| M2MComplexCircular1C |
python | google__pytype | pytype/abstract/_classes.py | {
"start": 36180,
"end": 39774
} | class ____(ParameterizedClass, mixin.HasSlots): # pytype: disable=signature-mismatch
"""A Callable with a list of argument types.
The formal_type_parameters attribute stores the types of the individual
arguments under their indices, the overall argument type under "ARGS", and the
return type under "RET". So for
CallableClass[[int, bool], str]
formal_type_parameters is
{0: int, 1: bool, ARGS: int or bool, RET: str}
When there are no args (CallableClass[[], ...]), ARGS contains abstract.Empty.
"""
def __init__(
self, base_cls, formal_type_parameters, ctx, template=None
) -> None:
super().__init__(base_cls, formal_type_parameters, ctx, template)
mixin.HasSlots.init_mixin(self)
self.set_native_slot("__call__", self.call_slot)
# We subtract two to account for "ARGS" and "RET".
self.num_args = len(self.formal_type_parameters) - 2
def __repr__(self) -> str:
return f"CallableClass({self.formal_type_parameters})"
def get_formal_type_parameters(self) -> dict[Any, _base.BaseValue]:
return {
abstract_utils.full_type_name(
self, abstract_utils.ARGS
): self.formal_type_parameters[abstract_utils.ARGS],
abstract_utils.full_type_name(
self, abstract_utils.RET
): self.formal_type_parameters[abstract_utils.RET],
}
def call_slot(
self, node: cfg.CFGNode, *args, **kwargs
) -> tuple[cfg.CFGNode, Any]:
"""Implementation of CallableClass.__call__."""
if kwargs:
raise error_types.WrongKeywordArgs(
function.Signature.from_callable(self),
function.Args(posargs=args, namedargs=kwargs),
self.ctx,
kwargs.keys(),
)
if len(args) != self.num_args:
raise error_types.WrongArgCount(
function.Signature.from_callable(self),
function.Args(posargs=args),
self.ctx,
)
match_args = [
types.Arg(function.argname(i), args[i], self.formal_type_parameters[i])
for i in range(self.num_args)
]
matcher = self.ctx.matcher(node)
try:
matches = matcher.compute_matches(match_args, match_all_views=False)
except error_types.MatchError as e:
raise error_types.WrongArgTypes(
function.Signature.from_callable(self),
function.Args(posargs=args),
self.ctx,
bad_param=e.bad_type,
)
ret = self.ctx.annotation_utils.sub_one_annotation(
node,
self.formal_type_parameters[abstract_utils.RET],
[m.subst for m in matches],
)
if args and ret.full_name in abstract_utils.TYPE_GUARDS:
typeguard_return = function.handle_typeguard(
node, function.AbstractReturnType(ret, self.ctx), args[0], self.ctx
)
else:
typeguard_return = None
if typeguard_return:
retvar = typeguard_return
else:
retvar = self.ctx.vm.init_class(node, ret)
return node, retvar
def get_special_attribute(self, node, name, valself):
if (
valself
and not abstract_utils.equivalent_to(valself, self)
and name in self._slots
):
return mixin.HasSlots.get_special_attribute(self, node, name, valself)
return super().get_special_attribute(node, name, valself)
def get_args(self):
"""Get the callable's posargs as a list."""
return [self.formal_type_parameters[i] for i in range(self.num_args)]
def has_paramspec(self) -> bool:
return isinstance(
self.formal_type_parameters[abstract_utils.ARGS],
(_abstract.ParamSpec, _abstract.Concatenate),
)
| CallableClass |
python | ansible__ansible | lib/ansible/utils/plugin_docs.py | {
"start": 5587,
"end": 16119
} | class ____(AnsibleError):
pass
def add_fragments(doc, filename, fragment_loader, is_module=False, section='DOCUMENTATION'):
if section not in _FRAGMENTABLE:
raise AnsibleError(f"Invalid fragment section ({section}) passed to render {filename}, it can only be one of {_FRAGMENTABLE!r}")
fragments = doc.pop('extends_documentation_fragment', [])
if isinstance(fragments, str):
fragments = fragments.split(',')
unknown_fragments = []
# doc_fragments are allowed to specify a fragment var other than DOCUMENTATION or RETURN
# with a . separator; this is complicated by collections-hosted doc_fragments that
# use the same separator. Assume it's collection-hosted normally first, try to load
# as-specified. If failure, assume the right-most component is a var, split it off,
# and retry the load.
for fragment_slug in fragments:
fragment_name = fragment_slug.strip()
fragment_var = section
fragment_class = fragment_loader.get(fragment_name)
if fragment_class is None and '.' in fragment_slug:
splitname = fragment_slug.rsplit('.', 1)
fragment_name = splitname[0]
fragment_var = splitname[1].upper()
fragment_class = fragment_loader.get(fragment_name)
if fragment_class is None:
unknown_fragments.append(fragment_slug)
continue
# trust-tagged source propagates to loaded values; expressions and templates in config require trust
fragment_yaml = _tags.TrustedAsTemplate().tag(getattr(fragment_class, fragment_var, None))
if fragment_yaml is None:
if fragment_var not in _FRAGMENTABLE:
# if it's asking for something specific that's missing, that's an error
unknown_fragments.append(fragment_slug)
continue
else:
fragment_yaml = '{}' # TODO: this is still an error later since we require 'options' below...
fragment = yaml.load(_tags.Origin(path=filename).tag(fragment_yaml), Loader=AnsibleLoader)
real_fragment_name = getattr(fragment_class, 'ansible_name')
real_collection_name = '.'.join(real_fragment_name.split('.')[0:2]) if '.' in real_fragment_name else ''
add_collection_to_versions_and_dates(fragment, real_collection_name, is_module=is_module, return_docs=(section == 'RETURN'))
if section == 'DOCUMENTATION':
# notes, seealso, options and attributes entries are specificly merged, but only occur in documentation section
for doc_key in ['notes', 'seealso']:
if doc_key in fragment:
entries = fragment.pop(doc_key)
if entries:
if doc_key not in doc:
doc[doc_key] = []
doc[doc_key].extend(entries)
if 'options' not in fragment and 'attributes' not in fragment:
raise AnsibleFragmentError("missing options or attributes in fragment (%s), possibly misformatted?: %s" % (fragment_name, filename))
# ensure options themselves are directly merged
for doc_key in ['options', 'attributes']:
if doc_key in fragment:
if doc_key in doc:
try:
merge_fragment(doc[doc_key], fragment.pop(doc_key))
except Exception as e:
raise AnsibleFragmentError("%s %s (%s) of unknown type: %s" % (to_native(e), doc_key, fragment_name, filename))
else:
doc[doc_key] = fragment.pop(doc_key)
# merge rest of the sections
try:
merge_fragment(doc, fragment)
except Exception as e:
raise AnsibleFragmentError("%s (%s) of unknown type: %s" % (to_native(e), fragment_name, filename))
if unknown_fragments:
raise AnsibleFragmentError('unknown doc_fragment(s) in file {0}: {1}'.format(filename, to_native(', '.join(unknown_fragments))))
def get_docstring(filename, fragment_loader, verbose=False, ignore_errors=False, collection_name=None, is_module=None, plugin_type=None):
"""
DOCUMENTATION can be extended using documentation fragments loaded by the PluginLoader from the doc_fragments plugins.
"""
if is_module is None:
if plugin_type is None:
is_module = False
else:
is_module = (plugin_type == 'module')
else:
# TODO deprecate is_module argument, now that we have 'type'
pass
data = read_docstring(filename, verbose=verbose, ignore_errors=ignore_errors)
if data.get('doc', False):
# add collection name to versions and dates
if collection_name is not None:
add_collection_to_versions_and_dates(data['doc'], collection_name, is_module=is_module)
# add fragments to documentation
add_fragments(data['doc'], filename, fragment_loader=fragment_loader, is_module=is_module, section='DOCUMENTATION')
if data.get('returndocs', False):
# add collection name to versions and dates
if collection_name is not None:
add_collection_to_versions_and_dates(data['returndocs'], collection_name, is_module=is_module, return_docs=True)
# add fragments to return
add_fragments(data['returndocs'], filename, fragment_loader=fragment_loader, is_module=is_module, section='RETURN')
return data['doc'], data['plainexamples'], data['returndocs'], data['metadata']
def get_versioned_doclink(path):
"""
returns a versioned documentation link for the current Ansible major.minor version; used to generate
in-product warning/error links to the configured DOCSITE_ROOT_URL
(eg, https://docs.ansible.com/ansible/2.8/somepath/doc.html)
:param path: relative path to a document under docs/docsite/rst;
:return: absolute URL to the specified doc for the current version of Ansible
"""
path = to_native(path)
try:
base_url = C.config.get_config_value('DOCSITE_ROOT_URL')
if not base_url.endswith('/'):
base_url += '/'
if path.startswith('/'):
path = path[1:]
split_ver = ansible_version.split('.')
if len(split_ver) < 3:
raise RuntimeError('invalid version ({0})'.format(ansible_version))
doc_version = '{0}.{1}'.format(split_ver[0], split_ver[1])
# check to see if it's a X.Y.0 non-rc prerelease or dev release, if so, assume devel (since the X.Y doctree
# isn't published until beta-ish)
if split_ver[2].startswith('0'):
# exclude rc; we should have the X.Y doctree live by rc1
if any((pre in split_ver[2]) for pre in ['a', 'b']) or len(split_ver) > 3 and 'dev' in split_ver[3]:
doc_version = 'devel'
return '{0}{1}/{2}'.format(base_url, doc_version, path)
except Exception as ex:
return '(unable to create versioned doc link for path {0}: {1})'.format(path, to_native(ex))
def _find_adjacent(path, plugin, extensions):
adjacent = Path(path)
plugin_base_name = plugin.split('.')[-1]
if adjacent.stem != plugin_base_name:
# this should only affect filters/tests
adjacent = adjacent.with_name(plugin_base_name)
paths = []
for ext in extensions:
candidate = adjacent.with_suffix(ext)
if candidate == adjacent:
# we're looking for an adjacent file, skip this since it's identical
continue
if candidate.exists():
paths.append(to_native(candidate))
return paths
def find_plugin_docfile(plugin, plugin_type, loader):
""" if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding 'sidecar' file for docs """
context = loader.find_plugin_with_context(plugin, ignore_deprecated=False, check_aliases=True)
if (not context or not context.resolved) and plugin_type in ('filter', 'test'):
# should only happen for filters/test
plugin_obj, context = loader.get_with_context(plugin)
if not context or not context.resolved:
raise AnsiblePluginNotFound('%s was not found' % (plugin), plugin_load_context=context)
docfile = Path(context.plugin_resolved_path)
if docfile.suffix not in C.DOC_EXTENSIONS:
# only look for adjacent if plugin file does not support documents
filenames = _find_adjacent(docfile, plugin, C.DOC_EXTENSIONS)
filename = filenames[0] if filenames else None
else:
filename = to_native(docfile)
if filename is None:
raise AnsibleError('%s cannot contain DOCUMENTATION nor does it have a companion documentation file' % (plugin))
return filename, context
def get_plugin_docs(plugin, plugin_type, loader, fragment_loader, verbose):
# find plugin doc file, if it doesn't exist this will throw error, we let it through
# can raise exception and short circuit when 'not found'
filename, context = find_plugin_docfile(plugin, plugin_type, loader)
collection_name = context.plugin_resolved_collection
try:
docs = get_docstring(filename, fragment_loader, verbose=verbose, collection_name=collection_name, plugin_type=plugin_type)
except Exception as ex:
raise AnsibleParserError(f'{plugin_type} plugin {plugin!r} did not contain a DOCUMENTATION attribute in {filename!r}.') from ex
# no good? try adjacent
if not docs[0]:
for newfile in _find_adjacent(filename, plugin, C.DOC_EXTENSIONS):
try:
docs = get_docstring(newfile, fragment_loader, verbose=verbose, collection_name=collection_name, plugin_type=plugin_type)
filename = newfile
if docs[0] is not None:
break
except Exception as ex:
raise AnsibleParserError(f'{plugin_type} plugin {plugin!r} adjacent file did not contain a DOCUMENTATION attribute in {filename!r}.') from ex
# add extra data to docs[0] (aka 'DOCUMENTATION')
if docs[0] is None:
raise AnsibleParserError(f'No documentation available for {plugin_type} plugin {plugin!r} in {filename!r}.')
docs[0]['filename'] = filename
docs[0]['collection'] = collection_name
docs[0]['plugin_name'] = context.resolved_fqcn
return docs
def __getattr__(importable_name):
return _no_six.deprecate(importable_name, __name__, "string_types")
| AnsibleFragmentError |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 50921,
"end": 52424
} | class ____(PathTest, OptionsQueryTest):
run_create_tables = False
run_inserts = None
run_deletes = None
def _assert_opts(self, q, sub_opt, non_sub_opts):
attr_a = {}
for val in sub_opt._to_bind:
val._bind_loader(
[
ent.entity_zero
for ent in q._compile_state()._lead_mapper_entities
],
q._compile_options._current_path,
attr_a,
False,
)
attr_b = {}
for opt in non_sub_opts:
for val in opt._to_bind:
val._bind_loader(
[
ent.entity_zero
for ent in q._compile_state()._lead_mapper_entities
],
q._compile_options._current_path,
attr_b,
False,
)
for k, l in attr_b.items():
if not l.strategy:
del attr_b[k]
def strat_as_tuple(strat):
return (
strat.strategy,
strat.local_opts,
strat.propagate_to_loaders,
strat._of_type,
strat.is_class_strategy,
strat.is_opts_only,
)
eq_(
{path: strat_as_tuple(load) for path, load in attr_a.items()},
{path: strat_as_tuple(load) for path, load in attr_b.items()},
)
| SubOptionsTest |
python | getsentry__sentry | src/sentry/migrations/1005_add_groupemailthread_project_date_index.py | {
"start": 155,
"end": 1479
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
dependencies = [
("sentry", "1004_group_history_prev_history_delete"),
]
operations = [
migrations.AddIndex(
model_name="groupemailthread",
index=models.Index(fields=["project", "date"], name="sentry_grou_project_56b6ae_idx"),
),
]
| Migration |
python | ray-project__ray | python/ray/serve/_private/common.py | {
"start": 29491,
"end": 29660
} | class ____(str, Enum):
"""Determines what direction the target capacity is scaling."""
UP = "UP"
DOWN = "DOWN"
@dataclass(frozen=True)
| TargetCapacityDirection |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/configs.py | {
"start": 212,
"end": 1072
} | class ____(BaseModelExtended):
enabled: bool = Field(default=True, description="Whether this stage is enabled.")
# Optional overrides; processor-level defaults still apply
batch_size: Optional[int] = Field(default=None, description="Rows per batch.")
concurrency: Optional[Union[int, Tuple[int, int]]] = Field(
default=None, description="Actor pool size or range for this stage."
)
runtime_env: Optional[Dict[str, Any]] = Field(
default=None, description="Optional runtime env for this stage."
)
num_cpus: Optional[float] = Field(
default=None,
description="Number of CPUs to reserve for each map worker in this stage.",
)
memory: Optional[float] = Field(
default=None,
description="Heap memory in bytes to reserve for each map worker in this stage.",
)
| _StageConfigBase |
python | django__django | tests/check_framework/test_security.py | {
"start": 19344,
"end": 19689
} | class ____(SimpleTestCase):
@override_settings(DEBUG=True)
def test_debug_true(self):
"""
Warn if DEBUG is True.
"""
self.assertEqual(base.check_debug(None), [base.W018])
@override_settings(DEBUG=False)
def test_debug_false(self):
self.assertEqual(base.check_debug(None), [])
| CheckDebugTest |
python | django__django | tests/model_formsets/models.py | {
"start": 6967,
"end": 7156
} | class ____(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey(
ParentWithUUIDAlternateKey, models.CASCADE, to_field="uuid"
)
| ChildRelatedViaAK |
python | pytorch__pytorch | torch/testing/_internal/jit_utils.py | {
"start": 25645,
"end": 29554
} | class ____:
def __enter__(self):
self.prev = torch._C._jit_get_tracer_state_warn()
torch._C._jit_set_tracer_state_warn(False)
def __exit__(self, *args):
torch._C._jit_set_tracer_state_warn(self.prev)
@contextmanager
def inline_everything_mode(should_inline):
old = torch._C._jit_get_inline_everything_mode()
torch._C._jit_set_inline_everything_mode(should_inline)
try:
yield
finally:
torch._C._jit_set_inline_everything_mode(old)
@contextmanager
def set_fusion_group_inlining(inlining):
old = torch._C._debug_get_fusion_group_inlining()
torch._C._debug_set_fusion_group_inlining(inlining)
try:
yield
finally:
torch._C._debug_set_fusion_group_inlining(old)
# note: not re-entrant, use unnested only
@contextmanager
def disable_autodiff_subgraph_inlining(enabled=True):
torch._C._debug_set_autodiff_subgraph_inlining(not enabled)
try:
yield
finally:
torch._C._debug_set_autodiff_subgraph_inlining(True)
def _inline_everything(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
with inline_everything_mode(True):
fn(*args, **kwargs)
return wrapper
# this exists for forward compatibility reasons temporarily.
# TODO(suo) remove
def _tmp_donotuse_dont_inline_everything(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
with inline_everything_mode(False):
fn(*args, **kwargs)
return wrapper
# make it easy to quickly define/trace a function for these tests
def _trace(*args, **kwargs):
def wrapper(func):
return torch.jit.trace(func, args, **kwargs)
return wrapper
def enable_cpu_fuser(fn):
def wrapper(*args, **kwargs):
torch._C._jit_override_can_fuse_on_cpu_legacy(True)
torch._C._jit_override_can_fuse_on_cpu(True)
torch._C._jit_set_te_must_use_llvm_cpu(False)
try:
fn(*args, **kwargs)
finally:
torch._C._jit_override_can_fuse_on_cpu_legacy(False)
torch._C._jit_override_can_fuse_on_cpu(False)
torch._C._jit_set_te_must_use_llvm_cpu(True)
return wrapper
def enable_cpu_fuser_if(cond):
if cond:
return enable_cpu_fuser
else:
def noop_fuser(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
return noop_fuser
def get_forward(c):
return c._get_method('forward')
def get_forward_graph(c):
return c._get_method('forward').graph
def get_module_method(m, module, method):
return m._c.getattr(module)._get_method(method)
def attrs_with_prefix(module, prefix):
return [x for x, _ in module._modules._c.items()
if x.startswith(prefix)]
def warmup_backward(f, *args):
profiling_count = 3
results = []
for _ in range(profiling_count):
if len(args) > 0:
r = torch.autograd.grad(f, *args)
results.append(r)
else:
f.backward(retain_graph=True)
return results
# TODO: Remove me once https://bugs.python.org/issue42666 is resolved
def make_global(*args):
for arg in args:
setattr(sys.modules[arg.__module__], arg.__name__, arg)
# Helper function to eval Python3 code without causing a syntax error for
# this file under py2
def _get_py3_code(code, fn_name):
with tempfile.TemporaryDirectory() as tmp_dir:
script_path = os.path.join(tmp_dir, 'script.py')
with open(script_path, 'w') as f:
f.write(code)
spec = importlib.util.spec_from_file_location(fn_name, script_path)
module = importlib.util.module_from_spec(spec)
loader = spec.loader
assert isinstance(loader, Loader) # Assert type to meet MyPy requirement
loader.exec_module(module)
fn = getattr(module, fn_name)
return fn
| NoTracerWarnContextManager |
python | google__jax | tests/tree_util_test.py | {
"start": 4548,
"end": 4606
} | class ____(int):
pass
@tree_util.register_static
| StaticInt |
python | PyCQA__pylint | tests/functional/t/try_except_raise_crash.py | {
"start": 333,
"end": 539
} | class ____(TestBaseException):
pass
def test():
try:
1 / 0
except TestException: # [catching-non-exception,try-except-raise]
raise
except Exception:
pass
| TestException |
python | FactoryBoy__factory_boy | tests/test_base.py | {
"start": 786,
"end": 831
} | class ____(FakeDjangoModel):
pass
| TestModel |
python | kubernetes-client__python | kubernetes/client/models/v1_volume_attributes_class.py | {
"start": 383,
"end": 9573
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'driver_name': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'parameters': 'dict(str, str)'
}
attribute_map = {
'api_version': 'apiVersion',
'driver_name': 'driverName',
'kind': 'kind',
'metadata': 'metadata',
'parameters': 'parameters'
}
def __init__(self, api_version=None, driver_name=None, kind=None, metadata=None, parameters=None, local_vars_configuration=None): # noqa: E501
"""V1VolumeAttributesClass - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._driver_name = None
self._kind = None
self._metadata = None
self._parameters = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.driver_name = driver_name
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
if parameters is not None:
self.parameters = parameters
@property
def api_version(self):
"""Gets the api_version of this V1VolumeAttributesClass. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1VolumeAttributesClass. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1VolumeAttributesClass.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1VolumeAttributesClass. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def driver_name(self):
"""Gets the driver_name of this V1VolumeAttributesClass. # noqa: E501
Name of the CSI driver This field is immutable. # noqa: E501
:return: The driver_name of this V1VolumeAttributesClass. # noqa: E501
:rtype: str
"""
return self._driver_name
@driver_name.setter
def driver_name(self, driver_name):
"""Sets the driver_name of this V1VolumeAttributesClass.
Name of the CSI driver This field is immutable. # noqa: E501
:param driver_name: The driver_name of this V1VolumeAttributesClass. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and driver_name is None: # noqa: E501
raise ValueError("Invalid value for `driver_name`, must not be `None`") # noqa: E501
self._driver_name = driver_name
@property
def kind(self):
"""Gets the kind of this V1VolumeAttributesClass. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1VolumeAttributesClass. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1VolumeAttributesClass.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1VolumeAttributesClass. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1VolumeAttributesClass. # noqa: E501
:return: The metadata of this V1VolumeAttributesClass. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1VolumeAttributesClass.
:param metadata: The metadata of this V1VolumeAttributesClass. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def parameters(self):
"""Gets the parameters of this V1VolumeAttributesClass. # noqa: E501
parameters hold volume attributes defined by the CSI driver. These values are opaque to the Kubernetes and are passed directly to the CSI driver. The underlying storage provider supports changing these attributes on an existing volume, however the parameters field itself is immutable. To invoke a volume update, a new VolumeAttributesClass should be created with new parameters, and the PersistentVolumeClaim should be updated to reference the new VolumeAttributesClass. This field is required and must contain at least one key/value pair. The keys cannot be empty, and the maximum number of parameters is 512, with a cumulative max size of 256K. If the CSI driver rejects invalid parameters, the target PersistentVolumeClaim will be set to an \"Infeasible\" state in the modifyVolumeStatus field. # noqa: E501
:return: The parameters of this V1VolumeAttributesClass. # noqa: E501
:rtype: dict(str, str)
"""
return self._parameters
@parameters.setter
def parameters(self, parameters):
"""Sets the parameters of this V1VolumeAttributesClass.
parameters hold volume attributes defined by the CSI driver. These values are opaque to the Kubernetes and are passed directly to the CSI driver. The underlying storage provider supports changing these attributes on an existing volume, however the parameters field itself is immutable. To invoke a volume update, a new VolumeAttributesClass should be created with new parameters, and the PersistentVolumeClaim should be updated to reference the new VolumeAttributesClass. This field is required and must contain at least one key/value pair. The keys cannot be empty, and the maximum number of parameters is 512, with a cumulative max size of 256K. If the CSI driver rejects invalid parameters, the target PersistentVolumeClaim will be set to an \"Infeasible\" state in the modifyVolumeStatus field. # noqa: E501
:param parameters: The parameters of this V1VolumeAttributesClass. # noqa: E501
:type: dict(str, str)
"""
self._parameters = parameters
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, V1VolumeAttributesClass):
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, V1VolumeAttributesClass):
return True
return self.to_dict() != other.to_dict()
| V1VolumeAttributesClass |
python | wandb__wandb | tests/system_tests/test_core/test_torch_full.py | {
"start": 2297,
"end": 3354
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.lstm1 = nn.LSTMCell(1, 51)
self.lstm2 = nn.LSTMCell(51, 51)
self.linear = nn.Linear(51, 1)
def forward(self, input, future=0):
outputs = []
h_t = dummy_torch_tensor((input.size(0), 51))
c_t = dummy_torch_tensor((input.size(0), 51))
h_t2 = dummy_torch_tensor((input.size(0), 51))
c_t2 = dummy_torch_tensor((input.size(0), 51))
for _, input_t in enumerate(input.chunk(input.size(1), dim=1)):
h_t, c_t = self.lstm1(input_t, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
for _ in range(future): # if we should predict the future
h_t, c_t = self.lstm1(output, (h_t, c_t))
h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2))
output = self.linear(h_t2)
outputs += [output]
outputs = torch.stack(outputs, 1).squeeze(2)
return outputs
| Sequence |
python | viewflow__viewflow | viewflow/fsm/views.py | {
"start": 333,
"end": 1622
} | class ____(APIView):
flow_state_field = None
lookup_field = "pk"
lookup_url_kwarg = None
queryset = None
def get_queryset(self):
if self.queryset:
queryset = self.queryset
if isinstance(queryset, QuerySet):
# Ensure queryset is re-evaluated on each request.
queryset = queryset.all()
return queryset
def get_object(self):
queryset = self.get_queryset()
if queryset is None:
return
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in self.kwargs:
return
obj = queryset.filter(
**{self.lookup_field: self.kwargs[lookup_url_kwarg]}
).first()
if not obj:
return
self.check_object_permissions(self.request, obj)
return obj
def get_flow_graph(self, obj=None):
raise NotImplementedError("Subclasses must implement `get_flow_graph` method.")
def get(self, request, format=None):
obj = self.get_object()
flow = self.get_flow(obj)
completed_states = self.get_completed_states(flow, obj)
graph = self.get_get_flow_graph(completed_states)
return Response(graph.to_json())
| FlowGraphView |
python | tensorflow__tensorflow | tensorflow/lite/python/tflite_convert_test.py | {
"start": 19382,
"end": 22245
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.named_parameters(('v1', False), ('v2', True))
def test_without_experimental_new_converter(self, use_v2_converter):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
]
# Note that when the flag parses to None, the converter uses the default
# value, which is True.
parser = tflite_convert._get_parser(use_v2_converter=use_v2_converter)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
self.assertIsNone(parsed_args.experimental_new_quantizer)
@parameterized.named_parameters(('v1', False), ('v2', True))
def test_experimental_new_converter_none(self, use_v2_converter):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_converter',
]
parser = tflite_convert._get_parser(use_v2_converter=use_v2_converter)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
@parameterized.named_parameters(
('v1_true', False, True),
('v1_false', False, False),
('v2_true', True, True),
('v2_false', True, False),
)
def test_experimental_new_converter(self, use_v2_converter, new_converter):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_converter={}'.format(new_converter),
]
parser = tflite_convert._get_parser(use_v2_converter=use_v2_converter)
parsed_args = parser.parse_args(args)
self.assertEqual(parsed_args.experimental_new_converter, new_converter)
@parameterized.named_parameters(('v1', False), ('v2', True))
def test_experimental_new_quantizer_none(self, use_v2_converter):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_quantizer',
]
parser = tflite_convert._get_parser(use_v2_converter=use_v2_converter)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_quantizer)
@parameterized.named_parameters(
('v1_true', False, True),
('v1_false', False, False),
('v2_true', True, True),
('v2_false', True, False),
)
def test_experimental_new_quantizer(self, use_v2_converter, new_quantizer):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_quantizer={}'.format(new_quantizer),
]
parser = tflite_convert._get_parser(use_v2_converter=use_v2_converter)
parsed_args = parser.parse_args(args)
self.assertEqual(parsed_args.experimental_new_quantizer, new_quantizer)
if __name__ == '__main__':
test.main()
| ArgParserTest |
python | openai__openai-python | src/openai/types/beta/assistant_stream_event.py | {
"start": 2878,
"end": 3092
} | class ____(BaseModel):
data: Run
"""
Represents an execution run on a
[thread](https://platform.openai.com/docs/api-reference/threads).
"""
event: Literal["thread.run.failed"]
| ThreadRunFailed |
python | pypa__pipenv | pipenv/patched/pip/_internal/utils/hashes.py | {
"start": 674,
"end": 4366
} | class ____:
"""A wrapper that builds multiple hashes at once and checks them against
known-good values
"""
def __init__(self, hashes: Optional[Dict[str, List[str]]] = None) -> None:
"""
:param hashes: A dict of algorithm names pointing to lists of allowed
hex digests
"""
allowed = {}
if hashes is not None:
for alg, keys in hashes.items():
# Make sure values are always sorted (to ease equality checks)
allowed[alg] = [k.lower() for k in sorted(keys)]
self._allowed = allowed
def __and__(self, other: "Hashes") -> "Hashes":
if not isinstance(other, Hashes):
return NotImplemented
# If either of the Hashes object is entirely empty (i.e. no hash
# specified at all), all hashes from the other object are allowed.
if not other:
return self
if not self:
return other
# Otherwise only hashes that present in both objects are allowed.
new = {}
for alg, values in other._allowed.items():
if alg not in self._allowed:
continue
new[alg] = [v for v in values if v in self._allowed[alg]]
return Hashes(new)
@property
def digest_count(self) -> int:
return sum(len(digests) for digests in self._allowed.values())
def is_hash_allowed(self, hash_name: str, hex_digest: str) -> bool:
"""Return whether the given hex digest is allowed."""
return hex_digest in self._allowed.get(hash_name, [])
def check_against_chunks(self, chunks: Iterable[bytes]) -> None:
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in self._allowed.keys():
try:
gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError):
raise InstallationError(f"Unknown hash name: {hash_name}")
for chunk in chunks:
for hash in gots.values():
hash.update(chunk)
for hash_name, got in gots.items():
if got.hexdigest() in self._allowed[hash_name]:
return
self._raise(gots)
def _raise(self, gots: Dict[str, "_Hash"]) -> "NoReturn":
raise HashMismatch(self._allowed, gots)
def check_against_file(self, file: BinaryIO) -> None:
"""Check good hashes against a file-like object
Raise HashMismatch if none match.
"""
return self.check_against_chunks(read_chunks(file))
def check_against_path(self, path: str) -> None:
with open(path, "rb") as file:
return self.check_against_file(file)
def has_one_of(self, hashes: Dict[str, str]) -> bool:
"""Return whether any of the given hashes are allowed."""
for hash_name, hex_digest in hashes.items():
if self.is_hash_allowed(hash_name, hex_digest):
return True
return False
def __bool__(self) -> bool:
"""Return whether I know any known-good hashes."""
return bool(self._allowed)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Hashes):
return NotImplemented
return self._allowed == other._allowed
def __hash__(self) -> int:
return hash(
",".join(
sorted(
":".join((alg, digest))
for alg, digest_list in self._allowed.items()
for digest in digest_list
)
)
)
| Hashes |
python | django__django | tests/admin_checks/models.py | {
"start": 1503,
"end": 1745
} | class ____(models.Model):
name = models.TextField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
| Influence |
python | realpython__materials | duck-typing-python/readers.py | {
"start": 506,
"end": 731
} | class ____:
def __init__(self, filename):
self.filename = filename
def read(self):
with open(self.filename, encoding="utf-8", newline="") as file:
return list(csv.DictReader(file))
| CSVReader |
python | pytorch__pytorch | torch/distributed/checkpoint/examples/async_checkpointing_example.py | {
"start": 759,
"end": 3970
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.net1 = nn.Linear(8, 32)
self.net2 = nn.Linear(32, 128)
self.net3 = nn.Linear(128, 64)
self.net4 = nn.Linear(64, 8)
self.net5 = nn.Linear(8, 1)
def forward(self, x):
x = F.relu(self.net1(x))
x = F.relu(self.net2(x))
x = F.relu(self.net3(x))
x = F.relu(self.net4(x))
x = F.sigmoid(self.net5(x))
return x
def _init_model(rank, world_size):
device_mesh = init_device_mesh(DEVICE, (world_size,))
# Create a dummy model and wrap it in FSDP
model = Model().cuda()
device_mesh = init_device_mesh(DEVICE, (world_size,))
model = FSDP(model, device_mesh=device_mesh, use_orig_params=True)
optim = torch.optim.Adam(model.parameters(), lr=0.0001)
_patch_model_state_dict(model)
# pyrefly: ignore [bad-argument-type]
_patch_optimizer_state_dict(model, optimizers=optim)
return model, optim
def _print(msg):
if dist.get_rank() == 0:
print(msg)
def _input():
x = torch.rand(128, 8, device="cuda")
y = torch.zeros(128, 1, device="cuda")
y[torch.sum(x, dim=1) >= 4] = 1.0
return x, y
def run(rank, world_size):
# Set up world pg
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "12355"
dist.init_process_group("cpu:gloo,cuda:nccl", rank=rank, world_size=world_size)
torch.cuda.set_device(rank)
model, optim = _init_model(rank, world_size)
state_dict = {"model": model, "optim": optim}
loss_calc = torch.nn.BCELoss()
f = None
# pyrefly: ignore [bad-assignment]
for epoch in range(NUM_EPOCHS):
try:
torch.manual_seed(epoch)
x, y = _input()
loss = loss_calc(model(x), y)
_print(f"{epoch=} {loss=}")
loss.backward()
optim.step()
optim.zero_grad()
if epoch % SAVE_PERIOD == 0:
if f is not None:
if not isinstance(f, Future):
raise AssertionError("f should be a Future instance")
f.result()
f = dcp.state_dict_saver.async_save(
state_dict, checkpoint_id=CHECKPOINT_DIR
)
if FAULT_PERIOD > 0 and epoch % FAULT_PERIOD == 0:
raise InjectedException("Fault injection!")
except InjectedException as e:
dist.barrier()
_print("Trainer encountered exception:")
traceback.print_tb(e.__traceback__)
_print("Reloading model from last checkpoint!")
if f is not None:
if not isinstance(f, Future):
raise AssertionError("f should be a Future instance") from None
f.result()
dcp.load(state_dict)
if __name__ == "__main__":
world_size = torch.cuda.device_count()
print(f"Running an example of Async Checkpointing on {world_size} devices.")
shutil.rmtree(CHECKPOINT_DIR, ignore_errors=True)
mp.spawn(
run,
args=(world_size,),
nprocs=world_size,
join=True,
)
| Model |
python | huggingface__transformers | tests/models/ernie4_5/test_modeling_ernie4_5.py | {
"start": 1108,
"end": 1243
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = Ernie4_5Model
@require_torch
| Ernie4_5ModelTester |
python | wandb__wandb | wandb/sdk/wandb_metric.py | {
"start": 174,
"end": 3346
} | class ____:
"""Metric object."""
_callback: Optional[Callable[[pb.MetricRecord], None]]
_name: str
_step_metric: Optional[str]
_step_sync: Optional[bool]
_hidden: Optional[bool]
_summary: Optional[Sequence[str]]
_goal: Optional[str]
_overwrite: Optional[bool]
def __init__(
self,
name: str,
step_metric: Optional[str] = None,
step_sync: Optional[bool] = None,
hidden: Optional[bool] = None,
summary: Optional[Sequence[str]] = None,
goal: Optional[str] = None,
overwrite: Optional[bool] = None,
) -> None:
self._callback = None
self._name = name
self._step_metric = step_metric
# default to step_sync=True if step metric is set
step_sync = step_sync if step_sync is not None else step_metric is not None
self._step_sync = step_sync
self._hidden = hidden
self._summary = summary
self._goal = goal
self._overwrite = overwrite
def _set_callback(self, cb: Callable[[pb.MetricRecord], None]) -> None:
self._callback = cb
@property
def name(self) -> str:
return self._name
@property
def step_metric(self) -> Optional[str]:
return self._step_metric
@property
def step_sync(self) -> Optional[bool]:
return self._step_sync
@property
def summary(self) -> Optional[Tuple[str, ...]]:
if self._summary is None:
return None
return tuple(self._summary)
@property
def hidden(self) -> Optional[bool]:
return self._hidden
@property
def goal(self) -> Optional[str]:
goal_dict = dict(min="minimize", max="maximize")
return goal_dict[self._goal] if self._goal else None
def _commit(self) -> None:
m = pb.MetricRecord()
m.options.defined = True
if self._name.endswith("*"):
m.glob_name = self._name
else:
m.name = self._name
if self._step_metric:
m.step_metric = self._step_metric
if self._step_sync:
m.options.step_sync = self._step_sync
if self._hidden:
m.options.hidden = self._hidden
if self._summary:
summary_set = set(self._summary)
if "min" in summary_set:
m.summary.min = True
if "max" in summary_set:
m.summary.max = True
if "mean" in summary_set:
m.summary.mean = True
if "last" in summary_set:
m.summary.last = True
if "copy" in summary_set:
m.summary.copy = True
if "none" in summary_set:
m.summary.none = True
if "best" in summary_set:
m.summary.best = True
if "first" in summary_set:
m.summary.first = True
if self._goal == "min":
m.goal = m.GOAL_MINIMIZE
if self._goal == "max":
m.goal = m.GOAL_MAXIMIZE
if self._overwrite:
m._control.overwrite = self._overwrite
if self._callback:
self._callback(m)
| Metric |
python | ansible__ansible | lib/ansible/plugins/cache/__init__.py | {
"start": 10347,
"end": 12720
} | class ____(c.MutableMapping):
"""Batch update wrapper around a cache plugin."""
def __init__(self, plugin_name='memory', **kwargs):
self._cache = {}
self._retrieved = {}
self._plugin = cache_loader.get(plugin_name, **kwargs)
def update_cache_if_changed(self):
if self._retrieved != self._cache:
self.set_cache()
def set_cache(self):
for top_level_cache_key in self._cache.keys():
self._plugin.set(top_level_cache_key, self._cache[top_level_cache_key])
self._retrieved = copy.deepcopy(self._cache)
def load_whole_cache(self):
for key in self._plugin.keys():
self._cache[key] = self._plugin.get(key)
def __repr__(self):
return repr(self._cache)
def __iter__(self):
return iter(self.keys())
def __len__(self):
return len(self.keys())
def _do_load_key(self, key):
load = False
if key not in self._cache and key not in self._retrieved and self._plugin._persistent and self._plugin.contains(key):
load = True
return load
def __getitem__(self, key):
if self._do_load_key(key):
try:
self._cache[key] = self._plugin.get(key)
except KeyError:
pass
else:
self._retrieved[key] = self._cache[key]
return self._cache[key]
def get(self, key, default=None):
if self._do_load_key(key):
try:
self._cache[key] = self._plugin.get(key)
except KeyError:
pass
else:
self._retrieved[key] = self._cache[key]
return self._cache.get(key, default)
def items(self):
return self._cache.items()
def values(self):
return self._cache.values()
def keys(self):
return self._cache.keys()
def pop(self, key, *args):
if args:
return self._cache.pop(key, args[0])
return self._cache.pop(key)
def __delitem__(self, key):
del self._cache[key]
def __setitem__(self, key, value):
self._cache[key] = value
def clear(self):
self.flush()
def flush(self):
self._plugin.flush()
self._cache = {}
def update(self, value):
self._cache.update(value)
| CachePluginAdjudicator |
python | kamyu104__LeetCode-Solutions | Python/kth-smallest-instructions.py | {
"start": 37,
"end": 1070
} | class ____(object):
def kthSmallestPath(self, destination, k):
"""
:type destination: List[int]
:type k: int
:rtype: str
"""
def nCr(n, r): # Time: O(n), Space: O(1)
if n < r:
return 0
if n-r < r:
return nCr(n, n-r)
c = 1
for k in xrange(1, r+1):
c *= n-k+1
c //= k
return c
r, c = destination
result = []
while r+c:
count = nCr(r+(c-1), r) # the number of HX..X combinations
if k <= count: # the kth instruction is one of HX..X combinations, so go right
c -= 1
result.append('H')
else: # the kth instruction is one of VX..X combinations, so go down
k -= count # the kth one of XX..X combinations is the (k-count)th one of VX..X combinations
r -= 1
result.append('V')
return "".join(result)
| Solution |
python | pytorch__pytorch | test/quantization/fx/test_numeric_suite_fx.py | {
"start": 7002,
"end": 9862
} | class ____(torch.nn.Module):
def __init__(self, weight1d, weight2d, weight3d, bias1d, bias2d, bias3d):
super().__init__()
self.weight1d = torch.nn.Parameter(weight1d)
self.weight2d = torch.nn.Parameter(weight2d)
self.weight3d = torch.nn.Parameter(weight3d)
self.bias1d = torch.nn.Parameter(bias1d)
self.bias2d = torch.nn.Parameter(bias2d)
self.bias3d = torch.nn.Parameter(bias3d)
self.stride1d = 1
self.padding1d = 0
self.dilation1d = 1
self.stride2d = (1, 1)
self.padding2d = (0, 0)
self.dilation2d = (1, 1)
self.groups = 1
self.stride3d = (1, 1, 1)
self.padding3d = (0, 0, 0)
self.dilation3d = (1, 1, 1)
def forward(self, x):
x = F.conv1d(
x, self.weight1d, self.bias1d, self.stride1d, self.padding1d,
self.dilation1d, self.groups)
x = F.conv1d(
x, self.weight1d, self.bias1d, self.stride1d, self.padding1d,
self.dilation1d, self.groups)
x = F.relu(x)
x = F.conv2d(
x, self.weight2d, self.bias2d, self.stride2d, self.padding2d,
self.dilation2d, self.groups)
x = F.conv2d(
x, self.weight2d, self.bias2d, self.stride2d, self.padding2d,
self.dilation2d, self.groups)
x = F.relu(x)
x = F.conv3d(
x, self.weight3d, self.bias3d, self.stride3d, self.padding3d,
self.dilation3d, self.groups)
x = F.conv3d(
x, self.weight3d, self.bias3d, self.stride3d, self.padding3d,
self.dilation3d, self.groups)
x = F.relu(x)
return x
@torch.fx.wrap
def _wrapped_hardswish(x):
return F.hardswish(x)
@torch.fx.wrap
def _wrapped_hardswish_fp16(x):
x = x.dequantize()
x = F.hardswish(x)
x = x.to(torch.float16)
return x
@torch.fx.wrap
def _wrapped_sigmoid(x):
return F.sigmoid(x)
@torch.fx.wrap
def _wrapped_linear(x, w, b):
return F.linear(x, w, b)
def get_all_quant_patterns():
""" we are in the process to migrate the frontend of fx graph mode quant
to use backend_config_dict, so some of the patterns are moved to backend_config_dict
this function will include these patterns so that we can still have all the patterns
"""
# TODO: we can remove this call, and get all patterns from backend_config_dict in
# the future when the frontend refactor is done in fx graph mode quantization
all_quant_patterns = get_default_quant_patterns()
# some of the patterns are moved to (native) backend_config_dict so we need to
# add them back here
for pattern, quantize_handler in _get_pattern_to_quantize_handlers(get_native_backend_config()).items():
all_quant_patterns[pattern] = quantize_handler
return all_quant_patterns
| AllConvFunctional |
python | streamlit__streamlit | lib/tests/streamlit/runtime/runtime_test.py | {
"start": 19959,
"end": 22602
} | class ____(RuntimeTestCase):
"""Tests for Runtime.does_script_run_without_error"""
def setUp(self) -> None:
self._home = tempfile.mkdtemp()
self._old_home = os.environ["HOME"]
os.environ["HOME"] = self._home
self._fd, self._path = tempfile.mkstemp()
super().setUp()
async def asyncSetUp(self):
# We don't call super().asyncSetUp() here. (Our superclass creates
# its own Runtime instance with a mock script_path, but we want
# to specify a non-mocked path.)
config = RuntimeConfig(
script_path=self._path,
command_line=None,
component_registry=LocalComponentRegistry(),
media_file_storage=MemoryMediaFileStorage("/mock/media"),
uploaded_file_manager=MemoryUploadedFileManager("/mock/upload"),
session_manager_class=MagicMock,
session_storage=MagicMock(),
cache_storage_manager=MagicMock(),
is_hello=False,
)
self.runtime = Runtime(config)
await self.runtime.start()
def tearDown(self) -> None:
if event_based_path_watcher._MultiPathWatcher._singleton is not None:
event_based_path_watcher._MultiPathWatcher.get_singleton().close()
event_based_path_watcher._MultiPathWatcher._singleton = None
os.environ["HOME"] = self._old_home
os.remove(self._path)
shutil.rmtree(self._home)
super().tearDown()
@pytest.mark.slow
async def test_invalid_script(self):
script = """
import streamlit as st
st.not_a_function('test')
"""
await self._check_script_loading(script, False, "error")
@pytest.mark.slow
async def test_valid_script(self):
script = """
import streamlit as st
st.write('test')
"""
await self._check_script_loading(script, True, "ok")
@pytest.mark.slow
async def test_timeout_script(self):
script = """
import time
time.sleep(5)
"""
with patch("streamlit.runtime.runtime.SCRIPT_RUN_CHECK_TIMEOUT", new=0.1):
await self._check_script_loading(script, False, "timeout")
async def _check_script_loading(
self, script: str, expected_loads: bool, expected_msg: str
) -> None:
with os.fdopen(self._fd, "w") as tmp:
tmp.write(script)
ok, msg = await self.runtime.does_script_run_without_error()
event_based_path_watcher._MultiPathWatcher.get_singleton().close()
event_based_path_watcher._MultiPathWatcher._singleton = None
assert expected_loads == ok
assert expected_msg == msg
| ScriptCheckTest |
python | pdm-project__pdm | src/pdm/models/backends.py | {
"start": 319,
"end": 805
} | class ____(metaclass=abc.ABCMeta):
"""A build backend that does not support dynamic values in dependencies"""
def __init__(self, root: Path) -> None:
self.root = root
def expand_line(self, line: str, expand_env: bool = True) -> str:
return line
def relative_path_to_url(self, path: str) -> str:
return self.root.joinpath(path).as_uri()
@classmethod
@abc.abstractmethod
def build_system(cls) -> BuildSystem:
pass
| BuildBackend |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py | {
"start": 1706,
"end": 1838
} | class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
@attr.s(auto_attribs=[1, 2, 3]) # auto_attribs = False
| C |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 2939,
"end": 3443
} | class ____(BaseOp, ABC):
exprs: TupleOf[Union[FilterExpr, Op]]
@classmethod
def wrap(cls, expr: Any) -> Self:
return expr if isinstance(expr, cls) else cls(exprs=(expr,))
# Logical operator(s)
# https://www.mongodb.com/docs/manual/reference/operator/query/and/
# https://www.mongodb.com/docs/manual/reference/operator/query/or/
# https://www.mongodb.com/docs/manual/reference/operator/query/nor/
# https://www.mongodb.com/docs/manual/reference/operator/query/not/
| BaseVariadicLogicalOp |
python | dagster-io__dagster | python_modules/automation/automation/parse_dataproc_configs.py | {
"start": 272,
"end": 359
} | class ____:
def __init__(self, inner_type):
self.inner_type = inner_type
| List |
python | tensorflow__tensorflow | tensorflow/python/distribute/parameter_server_strategy_test.py | {
"start": 22723,
"end": 32727
} | class ____(
ParameterServerStrategyTestBase,
strategy_test_lib.DistributionTestBase,
strategy_test_lib.TwoDeviceDistributionTestBase,
parameterized.TestCase):
@classmethod
def setUpClass(cls):
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=2)
cls._default_target = 'grpc://' + cls._cluster_spec[WORKER][0]
@combinations.generate(combinations.combine(mode=['graph']))
def test_num_replicas_in_sync(self):
strategy, _, _ = create_test_objects(num_gpus=2)
# All the devices on a given worker are in sync which in this case is the
# number of gpus on each worker.
self.assertEqual(2, strategy.num_replicas_in_sync)
@combinations.generate(combinations.combine(mode=['graph']))
def testDeviceAssignmentLocalCPU(self):
strategy, _, _ = create_test_objects(num_gpus=0)
self._test_device_assignment_local(
strategy, compute_device='CPU', variable_device='CPU', num_gpus=0)
@combinations.generate(combinations.combine(mode=['graph']))
def testDeviceAssignmentLocalOneGPU(self):
strategy, _, _ = create_test_objects(num_gpus=1)
self._test_device_assignment_local(
strategy, compute_device='GPU', variable_device='GPU', num_gpus=1)
@combinations.generate(combinations.combine(mode=['graph']))
def testDeviceAssignmentLocalTwoGPUs(self):
strategy, _, _ = create_test_objects(num_gpus=2)
self._test_device_assignment_local(
strategy, compute_device='GPU', variable_device='CPU', num_gpus=2)
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testDeviceAssignmentDistributed(self, num_gpus):
self._test_device_assignment_distributed('worker', 1, num_gpus)
@combinations.generate(
combinations.combine(mode=['graph'], num_gpus=[0, 1, 2]))
def testDeviceAssignmentDistributedEnablePartitioner(self, num_gpus):
self._test_device_assignment_distributed_enable_partitioner(
'worker', 1, num_gpus)
@combinations.generate(combinations.combine(mode=['graph']))
def testSimpleBetweenGraph(self):
self._run_between_graph_clients(self._test_simple_increment,
self._cluster_spec, context.num_gpus())
@combinations.generate(
combinations.combine(mode=['graph'], required_gpus=[0, 1, 2]))
def testLocalSimpleIncrement(self, required_gpus):
self._test_simple_increment(None, 0, required_gpus)
@combinations.generate(
combinations.combine(mode=['graph'], required_gpus=[0, 1, 2]))
def testMinimizeLossGraphDistributed(self, required_gpus):
self._run_between_graph_clients(self._test_minimize_loss_graph,
self._cluster_spec, required_gpus)
@combinations.generate(
combinations.combine(mode=['graph'], required_gpus=[0, 1, 2]))
def testMinimizeLossGraphLocal(self, required_gpus):
self._test_minimize_loss_graph(None, None, required_gpus)
# TODO(priyag): Refactor this and other multi worker tests.
@combinations.generate(
combinations.combine(
mode=['graph'], required_gpus=[1, 2], use_dataset=[True, False]))
def testMakeInputFnIteratorDistributed(self, required_gpus, use_dataset):
if use_dataset:
fn = lambda: dataset_ops.Dataset.range(100)
else:
def fn():
dataset = dataset_ops.Dataset.range(100)
it = dataset_ops.make_one_shot_iterator(dataset)
return it.get_next
expected_values = [[i + j
for j in range(required_gpus)]
for i in range(0, 100, required_gpus)]
input_fn = self._input_fn_to_test_input_context(
fn,
expected_num_replicas_in_sync=required_gpus,
expected_num_input_pipelines=3,
expected_input_pipeline_id=1) # because task_id = 1
self._test_input_fn_iterator(
'worker',
1,
required_gpus,
input_fn,
expected_values,
test_reinitialize=use_dataset,
ignore_order=not use_dataset)
@combinations.generate(
combinations.combine(
mode=['graph'], required_gpus=[1, 2], use_dataset=[True, False]))
def testMakeInputFnIteratorLocal(self, required_gpus, use_dataset):
if use_dataset:
fn = lambda: dataset_ops.Dataset.range(100)
else:
def fn():
dataset = dataset_ops.Dataset.range(100)
it = dataset_ops.make_one_shot_iterator(dataset)
return it.get_next
expected_values = [[i + j
for j in range(required_gpus)]
for i in range(0, 100, required_gpus)]
input_fn = self._input_fn_to_test_input_context(
fn,
expected_num_replicas_in_sync=required_gpus,
expected_num_input_pipelines=1,
expected_input_pipeline_id=0) # only one worker and pipeline for local.
self._test_input_fn_iterator(
None,
None,
required_gpus,
input_fn,
expected_values,
test_reinitialize=use_dataset,
ignore_order=not use_dataset)
@combinations.generate(combinations.combine(mode=['graph']))
def testGlobalStepUpdate(self):
strategy, _, _ = create_test_objects()
self._test_global_step_update(strategy)
@combinations.generate(combinations.combine(mode=['graph']))
def testUpdateConfigProtoMultiWorker(self):
strategy, _, _ = create_test_objects(
cluster_spec=self._cluster_spec,
task_type='worker',
task_id=1,
num_gpus=2)
config_proto = config_pb2.ConfigProto(device_filters=['to_be_overridden'])
new_config = strategy.update_config_proto(config_proto)
# Verify device filters.
self.assertEqual(['/job:worker/task:1', '/job:ps'],
new_config.device_filters)
# Verify isolate_session_state
self.assertFalse(new_config.isolate_session_state)
@combinations.generate(combinations.combine(mode=['graph']))
def testUpdateConfigProtoLocal(self):
strategy, _, _ = create_test_objects(num_gpus=2)
config_proto = config_pb2.ConfigProto()
new_config = strategy.update_config_proto(config_proto)
# Verify isolate_session_state
self.assertTrue(new_config.isolate_session_state)
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
def testInMultiWorkerMode(self):
strategy, _, _ = create_test_objects(
cluster_spec=self._cluster_spec,
task_type='worker',
task_id=1,
num_gpus=0)
self.assertTrue(strategy.extended._in_multi_worker_mode())
@combinations.generate(combinations.combine(mode=['eager']))
def testEagerCustomTrainingUnimplementedError(self):
cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=2)
cluster_resolver = cluster_resolver_lib.SimpleClusterResolver(
cluster_spec=multi_worker_util.normalize_cluster_spec(cluster_spec),
task_type='worker',
task_id=1,
num_accelerators={'GPU': 0})
strategy = parameter_server_strategy.ParameterServerStrategyV1(
cluster_resolver)
dataset = dataset_ops.DatasetV2.from_tensor_slices([5., 6., 7., 8.])
def train_step(data):
return math_ops.square(data)
self.assertRaisesRegex(NotImplementedError, 'ParameterServerStrategy*',
strategy.experimental_distribute_dataset,
dataset.batch(2))
self.assertRaisesRegex(NotImplementedError, 'ParameterServerStrategy*',
strategy.distribute_datasets_from_function,
lambda _: dataset)
self.assertRaisesRegex(NotImplementedError, 'ParameterServerStrategy*',
strategy.scope)
self.assertRaisesRegex(NotImplementedError, 'ParameterServerStrategy*',
strategy.run, train_step)
@combinations.generate(combinations.combine(
mode=['graph'],
prefetch_to_device=[None, True]))
def test_prefetch_to_device_dataset(self, prefetch_to_device):
distribution, _, _ = create_test_objects(
cluster_spec=self._cluster_spec,
task_type='worker',
task_id=0,
num_gpus=2)
if prefetch_to_device is None:
input_options = None
else:
input_options = distribute_lib.InputOptions(
experimental_fetch_to_device=prefetch_to_device)
dataset = dataset_ops.Dataset.range(100)
dataset = dataset.batch(distribution.num_replicas_in_sync)
dataset = distribution.experimental_distribute_dataset( # pylint: disable=assignment-from-no-return
dataset,
options=input_options)
if isinstance(dataset, input_lib_v1.DistributedDatasetV1):
item = dataset.make_initializable_iterator().get_next()
else:
self.skipTest('unsupported test combination')
device_types = {
tf_device.DeviceSpec.from_string(tensor.device).device_type for
tensor in item.values}
self.assertAllEqual(list(device_types), ['GPU'])
@combinations.generate(combinations.combine(mode=['graph']))
def test_prefetch_to_host_dataset(self):
distribution, _, _ = create_test_objects(
cluster_spec=self._cluster_spec,
task_type='worker',
task_id=0,
num_gpus=2)
input_options = distribute_lib.InputOptions(
experimental_fetch_to_device=False)
dataset = dataset_ops.Dataset.range(100)
dataset = dataset.batch(distribution.num_replicas_in_sync)
dataset = distribution.experimental_distribute_dataset( # pylint: disable=assignment-from-no-return
dataset,
options=input_options)
if isinstance(dataset, input_lib_v1.DistributedDatasetV1):
item = dataset.make_initializable_iterator().get_next()
else:
self.skipTest('unsupported test combination')
device_types = {
tf_device.DeviceSpec.from_string(tensor.device).device_type for
tensor in item.values}
self.assertAllEqual(list(device_types), ['CPU'])
| ParameterServerStrategyTest |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/state.py | {
"start": 1250,
"end": 4361
} | class ____:
"""Builder for WorkerGroupState.
Example usage:
```python
builder = WorkerGroupStateBuilder()
builder.with_placement_group(placement_group)
builder.with_workers(workers)
builder.with_sync_actor(sync_actor)
state = builder.build()
builder.shutdown(patience_s=10)
```
"""
def __init__(self):
self.placement_group = None
self.workers = None
self.sync_actor = None
def with_placement_group(
self, placement_group: PlacementGroup
) -> "WorkerGroupStateBuilder":
self.placement_group = placement_group
return self
def with_workers(self, workers: List[Worker]) -> "WorkerGroupStateBuilder":
self.workers = workers
return self
def with_sync_actor(
self, sync_actor: SynchronizationActor
) -> "WorkerGroupStateBuilder":
self.sync_actor = sync_actor
return self
def build(self) -> WorkerGroupState:
required_attrs = {
"placement_group": self.placement_group,
"workers": self.workers,
"sync_actor": self.sync_actor,
}
missing = [name for name, attr in required_attrs.items() if attr is None]
if missing:
raise ValueError(
f"Cannot build incomplete state. Missing: {', '.join(missing)}"
)
return WorkerGroupState(
start_time=time_monotonic(),
placement_group=self.placement_group,
workers=self.workers,
sync_actor=self.sync_actor,
)
def shutdown(self):
if self.workers:
_shutdown_workers(self.workers)
self.workers = None
if self.placement_group:
_shutdown_placement_group(self.placement_group)
self.placement_group = None
if self.sync_actor:
_shutdown_sync_actor(self.sync_actor)
self.sync_actor = None
def _shutdown_workers(workers: List[Worker], patience_s: float = 5):
# Run the worker shutdown logic on each of the workers. This should
# be a non-blocking call to realize forceful shutdown after patience_s.
_ = [w.actor.shutdown.remote() for w in workers]
logger.debug(f"Shutting down {len(workers)} workers.")
if patience_s <= 0:
for worker in workers:
ray.kill(worker.actor)
else:
done_refs = [w.actor.__ray_terminate__.remote() for w in workers]
# Wait for actors to die gracefully.
_, not_done = ray.wait(
done_refs, num_returns=len(done_refs), timeout=patience_s
)
if not_done:
logger.debug("Graceful termination failed. Falling back to force kill.")
# If all actors are not able to die gracefully, then kill them.
for worker in workers:
ray.kill(worker.actor)
def _shutdown_sync_actor(sync_actor: SynchronizationActor):
ray.kill(sync_actor)
def _shutdown_placement_group(placement_group: PlacementGroup):
remove_placement_group(placement_group)
| WorkerGroupStateBuilder |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/combine_documents/reduce.py | {
"start": 643,
"end": 5102
} | class ____(Protocol):
"""Interface for the combine_docs method."""
async def __call__(self, docs: list[Document], **kwargs: Any) -> str:
"""Async interface for the combine_docs method."""
def split_list_of_docs(
docs: list[Document],
length_func: Callable,
token_max: int,
**kwargs: Any,
) -> list[list[Document]]:
"""Split `Document` objects to subsets that each meet a cumulative len. constraint.
Args:
docs: The full list of `Document` objects.
length_func: Function for computing the cumulative length of a set of `Document`
objects.
token_max: The maximum cumulative length of any subset of `Document` objects.
**kwargs: Arbitrary additional keyword params to pass to each call of the
`length_func`.
Returns:
A `list[list[Document]]`.
"""
new_result_doc_list = []
_sub_result_docs = []
for doc in docs:
_sub_result_docs.append(doc)
_num_tokens = length_func(_sub_result_docs, **kwargs)
if _num_tokens > token_max:
if len(_sub_result_docs) == 1:
msg = (
"A single document was longer than the context length,"
" we cannot handle this."
)
raise ValueError(msg)
new_result_doc_list.append(_sub_result_docs[:-1])
_sub_result_docs = _sub_result_docs[-1:]
new_result_doc_list.append(_sub_result_docs)
return new_result_doc_list
def collapse_docs(
docs: list[Document],
combine_document_func: CombineDocsProtocol,
**kwargs: Any,
) -> Document:
"""Execute a collapse function on a set of documents and merge their metadatas.
Args:
docs: A list of `Document` objects to combine.
combine_document_func: A function that takes in a list of `Document` objects and
optionally addition keyword parameters and combines them into a single
string.
**kwargs: Arbitrary additional keyword params to pass to the
`combine_document_func`.
Returns:
A single `Document` with the output of `combine_document_func` for the page
content and the combined metadata's of all the input documents. All metadata
values are strings, and where there are overlapping keys across documents
the values are joined by `', '`.
"""
result = combine_document_func(docs, **kwargs)
combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()}
for doc in docs[1:]:
for k, v in doc.metadata.items():
if k in combined_metadata:
combined_metadata[k] += f", {v}"
else:
combined_metadata[k] = str(v)
return Document(page_content=result, metadata=combined_metadata)
async def acollapse_docs(
docs: list[Document],
combine_document_func: AsyncCombineDocsProtocol,
**kwargs: Any,
) -> Document:
"""Execute a collapse function on a set of documents and merge their metadatas.
Args:
docs: A list of `Document` objects to combine.
combine_document_func: A function that takes in a list of `Document` objects and
optionally addition keyword parameters and combines them into a single
string.
**kwargs: Arbitrary additional keyword params to pass to the
`combine_document_func`.
Returns:
A single `Document` with the output of `combine_document_func` for the page
content and the combined metadata's of all the input documents. All metadata
values are strings, and where there are overlapping keys across documents
the values are joined by `', '`.
"""
result = await combine_document_func(docs, **kwargs)
combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()}
for doc in docs[1:]:
for k, v in doc.metadata.items():
if k in combined_metadata:
combined_metadata[k] += f", {v}"
else:
combined_metadata[k] = str(v)
return Document(page_content=result, metadata=combined_metadata)
@deprecated(
since="0.3.1",
removal="1.0",
message=(
"This class is deprecated. Please see the migration guide here for "
"a recommended replacement: "
"https://python.langchain.com/docs/versions/migrating_chains/map_reduce_chain/"
),
)
| AsyncCombineDocsProtocol |
python | pypa__pip | src/pip/_vendor/distlib/util.py | {
"start": 43970,
"end": 51863
} | class ____(object):
unknown = 'UNKNOWN'
def __init__(self, minval=0, maxval=100):
assert maxval is None or maxval >= minval
self.min = self.cur = minval
self.max = maxval
self.started = None
self.elapsed = 0
self.done = False
def update(self, curval):
assert self.min <= curval
assert self.max is None or curval <= self.max
self.cur = curval
now = time.time()
if self.started is None:
self.started = now
else:
self.elapsed = now - self.started
def increment(self, incr):
assert incr >= 0
self.update(self.cur + incr)
def start(self):
self.update(self.min)
return self
def stop(self):
if self.max is not None:
self.update(self.max)
self.done = True
@property
def maximum(self):
return self.unknown if self.max is None else self.max
@property
def percentage(self):
if self.done:
result = '100 %'
elif self.max is None:
result = ' ?? %'
else:
v = 100.0 * (self.cur - self.min) / (self.max - self.min)
result = '%3d %%' % v
return result
def format_duration(self, duration):
if (duration <= 0) and self.max is None or self.cur == self.min:
result = '??:??:??'
# elif duration < 1:
# result = '--:--:--'
else:
result = time.strftime('%H:%M:%S', time.gmtime(duration))
return result
@property
def ETA(self):
if self.done:
prefix = 'Done'
t = self.elapsed
# import pdb; pdb.set_trace()
else:
prefix = 'ETA '
if self.max is None:
t = -1
elif self.elapsed == 0 or (self.cur == self.min):
t = 0
else:
# import pdb; pdb.set_trace()
t = float(self.max - self.min)
t /= self.cur - self.min
t = (t - 1) * self.elapsed
return '%s: %s' % (prefix, self.format_duration(t))
@property
def speed(self):
if self.elapsed == 0:
result = 0.0
else:
result = (self.cur - self.min) / self.elapsed
for unit in UNITS:
if result < 1000:
break
result /= 1000.0
return '%d %sB/s' % (result, unit)
#
# Glob functionality
#
RICH_GLOB = re.compile(r'\{([^}]*)\}')
_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
def iglob(path_glob):
"""Extended globbing function that supports ** and {opt1,opt2,opt3}."""
if _CHECK_RECURSIVE_GLOB.search(path_glob):
msg = """invalid glob %r: recursive glob "**" must be used alone"""
raise ValueError(msg % path_glob)
if _CHECK_MISMATCH_SET.search(path_glob):
msg = """invalid glob %r: mismatching set marker '{' or '}'"""
raise ValueError(msg % path_glob)
return _iglob(path_glob)
def _iglob(path_glob):
rich_path_glob = RICH_GLOB.split(path_glob, 1)
if len(rich_path_glob) > 1:
assert len(rich_path_glob) == 3, rich_path_glob
prefix, set, suffix = rich_path_glob
for item in set.split(','):
for path in _iglob(''.join((prefix, item, suffix))):
yield path
else:
if '**' not in path_glob:
for item in std_iglob(path_glob):
yield item
else:
prefix, radical = path_glob.split('**', 1)
if prefix == '':
prefix = '.'
if radical == '':
radical = '*'
else:
# we support both
radical = radical.lstrip('/')
radical = radical.lstrip('\\')
for path, dir, files in os.walk(prefix):
path = os.path.normpath(path)
for fn in _iglob(os.path.join(path, radical)):
yield fn
if ssl:
from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, CertificateError)
#
# HTTPSConnection which verifies certificates/matches domains
#
class HTTPSConnection(httplib.HTTPSConnection):
ca_certs = None # set this to the path to the certs file (.pem)
check_domain = True # only used if ca_certs is not None
# noinspection PyPropertyAccess
def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if getattr(self, '_tunnel_host', False):
self.sock = sock
self._tunnel()
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
if hasattr(ssl, 'OP_NO_SSLv2'):
context.options |= ssl.OP_NO_SSLv2
if getattr(self, 'cert_file', None):
context.load_cert_chain(self.cert_file, self.key_file)
kwargs = {}
if self.ca_certs:
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(cafile=self.ca_certs)
if getattr(ssl, 'HAS_SNI', False):
kwargs['server_hostname'] = self.host
self.sock = context.wrap_socket(sock, **kwargs)
if self.ca_certs and self.check_domain:
try:
match_hostname(self.sock.getpeercert(), self.host)
logger.debug('Host verified: %s', self.host)
except CertificateError: # pragma: no cover
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
raise
class HTTPSHandler(BaseHTTPSHandler):
def __init__(self, ca_certs, check_domain=True):
BaseHTTPSHandler.__init__(self)
self.ca_certs = ca_certs
self.check_domain = check_domain
def _conn_maker(self, *args, **kwargs):
"""
This is called to create a connection instance. Normally you'd
pass a connection class to do_open, but it doesn't actually check for
a class, and just expects a callable. As long as we behave just as a
constructor would have, we should be OK. If it ever changes so that
we *must* pass a class, we'll create an UnsafeHTTPSConnection class
which just sets check_domain to False in the class definition, and
choose which one to pass to do_open.
"""
result = HTTPSConnection(*args, **kwargs)
if self.ca_certs:
result.ca_certs = self.ca_certs
result.check_domain = self.check_domain
return result
def https_open(self, req):
try:
return self.do_open(self._conn_maker, req)
except URLError as e:
if 'certificate verify failed' in str(e.reason):
raise CertificateError('Unable to verify server certificate '
'for %s' % req.host)
else:
raise
#
# To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
# Middle proxy using HTTP listens on port 443, or an index mistakenly serves
# HTML containing a http://xyz link when it should be https://xyz),
# you can use the following handler class, which does not allow HTTP traffic.
#
# It works by inheriting from HTTPHandler - so build_opener won't add a
# handler for HTTP itself.
#
class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
def http_open(self, req):
raise URLError('Unexpected HTTP request on what should be a secure '
'connection: %s' % req)
#
# XML-RPC with timeouts
#
| Progress |
python | neetcode-gh__leetcode | python/0071-simplify-path.py | {
"start": 0,
"end": 487
} | class ____:
def simplifyPath(self, path: str) -> str:
stack = []
for i in path.split("/"):
# if i == "/" or i == '//', it becomes '' (empty string)
if i == "..":
if stack:
stack.pop()
elif i == "." or i == '':
# skip "." or an empty string
continue
else:
stack.append(i)
res = "/" + "/".join(stack)
return res
| Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/configs.py | {
"start": 10996,
"end": 17589
} | class ____(RegexLexer):
"""
Lexer for `squid <http://www.squid-cache.org/>`_ configuration files.
.. versionadded:: 0.9
"""
name = 'SquidConf'
aliases = ['squidconf', 'squid.conf', 'squid']
filenames = ['squid.conf']
mimetypes = ['text/x-squidconf']
flags = re.IGNORECASE
keywords = (
"access_log", "acl", "always_direct", "announce_host",
"announce_period", "announce_port", "announce_to", "anonymize_headers",
"append_domain", "as_whois_server", "auth_param_basic",
"authenticate_children", "authenticate_program", "authenticate_ttl",
"broken_posts", "buffered_logs", "cache_access_log", "cache_announce",
"cache_dir", "cache_dns_program", "cache_effective_group",
"cache_effective_user", "cache_host", "cache_host_acl",
"cache_host_domain", "cache_log", "cache_mem", "cache_mem_high",
"cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer",
"cache_peer_access", "cahce_replacement_policy", "cache_stoplist",
"cache_stoplist_pattern", "cache_store_log", "cache_swap",
"cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db",
"client_lifetime", "client_netmask", "connect_timeout", "coredump_dir",
"dead_peer_timeout", "debug_options", "delay_access", "delay_class",
"delay_initial_bucket_level", "delay_parameters", "delay_pools",
"deny_info", "dns_children", "dns_defnames", "dns_nameservers",
"dns_testnames", "emulate_httpd_log", "err_html_text",
"fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port",
"fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width",
"ftp_passive", "ftp_user", "half_closed_clients", "header_access",
"header_replace", "hierarchy_stoplist", "high_response_time_warning",
"high_page_fault_warning", "hosts_file", "htcp_port", "http_access",
"http_anonymizer", "httpd_accel", "httpd_accel_host",
"httpd_accel_port", "httpd_accel_uses_host_header",
"httpd_accel_with_proxy", "http_port", "http_reply_access",
"icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout",
"ident_lookup", "ident_lookup_access", "ident_timeout",
"incoming_http_average", "incoming_icp_average", "inside_firewall",
"ipcache_high", "ipcache_low", "ipcache_size", "local_domain",
"local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries",
"log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries",
"mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr",
"mcast_miss_encode_key", "mcast_miss_port", "memory_pools",
"memory_pools_limit", "memory_replacement_policy", "mime_table",
"min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops",
"minimum_object_size", "minimum_retry_timeout", "miss_access",
"negative_dns_ttl", "negative_ttl", "neighbor_timeout",
"neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period",
"netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy",
"pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl",
"prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp",
"quick_abort", "quick_abort_max", "quick_abort_min",
"quick_abort_pct", "range_offset_limit", "read_timeout",
"redirect_children", "redirect_program",
"redirect_rewrites_host_header", "reference_age",
"refresh_pattern", "reload_into_ims", "request_body_max_size",
"request_size", "request_timeout", "shutdown_lifetime",
"single_parent_bypass", "siteselect_timeout", "snmp_access",
"snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy",
"store_avg_object_size", "store_objects_per_bucket",
"strip_query_terms", "swap_level1_dirs", "swap_level2_dirs",
"tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize",
"test_reachability", "udp_hit_obj", "udp_hit_obj_size",
"udp_incoming_address", "udp_outgoing_address", "unique_hostname",
"unlinkd_program", "uri_whitespace", "useragent_log",
"visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port",
)
opts = (
"proxy-only", "weight", "ttl", "no-query", "default", "round-robin",
"multicast-responder", "on", "off", "all", "deny", "allow", "via",
"parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2",
"credentialsttl", "none", "disable", "offline_toggle", "diskd",
)
actions = (
"shutdown", "info", "parameter", "server_list", "client_list",
r'squid.conf',
)
actions_stats = (
"objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns",
"redirector", "io", "reply_headers", "filedescriptors", "netdb",
)
actions_log = ("status", "enable", "disable", "clear")
acls = (
"url_regex", "urlpath_regex", "referer_regex", "port", "proto",
"req_mime_type", "rep_mime_type", "method", "browser", "user", "src",
"dst", "time", "dstdomain", "ident", "snmp_community",
)
ip_re = (
r'(?:(?:(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|0x0*[0-9a-f]{1,2}|'
r'0+[1-3]?[0-7]{0,2})(?:\.(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|'
r'0x0*[0-9a-f]{1,2}|0+[1-3]?[0-7]{0,2})){3})|(?!.*::.*::)(?:(?!:)|'
r':(?=:))(?:[0-9a-f]{0,4}(?:(?<=::)|(?<!::):)){6}(?:[0-9a-f]{0,4}'
r'(?:(?<=::)|(?<!::):)[0-9a-f]{0,4}(?:(?<=::)|(?<!:)|(?<=:)(?<!::):)|'
r'(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|'
r'[1-9]?\d)){3}))'
)
tokens = {
'root': [
(r'\s+', Whitespace),
(r'#', Comment, 'comment'),
(words(keywords, prefix=r'\b', suffix=r'\b'), Keyword),
(words(opts, prefix=r'\b', suffix=r'\b'), Name.Constant),
# Actions
(words(actions, prefix=r'\b', suffix=r'\b'), String),
(words(actions_stats, prefix=r'stats/', suffix=r'\b'), String),
(words(actions_log, prefix=r'log/', suffix=r'='), String),
(words(acls, prefix=r'\b', suffix=r'\b'), Keyword),
(ip_re + r'(?:/(?:' + ip_re + r'|\b\d+\b))?', Number.Float),
(r'(?:\b\d+\b(?:-\b\d+|%)?)', Number),
(r'\S+', Text),
],
'comment': [
(r'\s*TAG:.*', String.Escape, '#pop'),
(r'.+', Comment, '#pop'),
default('#pop'),
],
}
| SquidConfLexer |
python | sympy__sympy | sympy/physics/quantum/cartesian.py | {
"start": 1855,
"end": 2237
} | class ____(HermitianOperator):
""" Y cartesian coordinate operator (for 2D or 3D systems) """
@classmethod
def default_args(self):
return ("Y",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PositionKet3D(self, ket, **options):
return ket.position_y*ket
| YOp |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/job/asset_out.py | {
"start": 1852,
"end": 12380
} | class ____:
"""Defines one of the assets produced by a :py:func:`@multi_asset <multi_asset>`.
Args:
key_prefix (Optional[Union[str, Sequence[str]]]): If provided, the asset's key is the
concatenation of the key_prefix and the asset's name. When using ``@multi_asset``, the
asset name defaults to the key of the "outs" dictionary Only one of the "key_prefix" and
"key" arguments should be provided.
key (Optional[Union[str, Sequence[str], AssetKey]]): The asset's key. Only one of the
"key_prefix" and "key" arguments should be provided.
dagster_type (Optional[Union[Type, DagsterType]]]):
The type of this output. Should only be set if the correct type can not
be inferred directly from the type signature of the decorated function.
description (Optional[str]): Human-readable description of the output.
is_required (bool): Whether the presence of this field is required. (default: True)
io_manager_key (Optional[str]): The resource key of the IO manager used for this output.
(default: "io_manager").
metadata (Optional[Dict[str, Any]]): A dict of the metadata for the output.
For example, users can provide a file path if the data object will be stored in a
filesystem, or provide information of a database table when it is going to load the data
into the table.
group_name (Optional[str]): A string name used to organize multiple assets into groups. If
not provided, the name "default" is used.
code_version (Optional[str]): The version of the code that generates this asset.
automation_condition (Optional[AutomationCondition]): AutomationCondition to apply to the
specified asset.
backfill_policy (Optional[BackfillPolicy]): BackfillPolicy to apply to the specified asset.
owners (Optional[Sequence[str]]): A list of strings representing owners of the asset. Each
string can be a user's email address, or a team name prefixed with `team:`,
e.g. `team:finops`.
tags (Optional[Mapping[str, str]]): Tags for filtering and organizing. These tags are not
attached to runs of the asset.
kinds (Optional[set[str]]): A set of strings representing the kinds of the asset. These
will be made visible in the Dagster UI.
"""
_spec: AssetSpec
key_prefix: Optional[Sequence[str]]
dagster_type: Union[type, DagsterType]
is_required: bool
io_manager_key: Optional[str]
backfill_policy: Optional[BackfillPolicy]
def __init__(
self,
key_prefix: Optional[CoercibleToAssetKeyPrefix] = None,
key: Optional[CoercibleToAssetKey] = None,
dagster_type: Union[type, DagsterType] = NoValueSentinel,
description: Optional[str] = None,
is_required: bool = True,
io_manager_key: Optional[str] = None,
metadata: Optional[Mapping[str, Any]] = None,
group_name: Optional[str] = None,
code_version: Optional[str] = None,
automation_condition: Optional[AutomationCondition] = None,
backfill_policy: Optional[BackfillPolicy] = None,
owners: Optional[Sequence[str]] = None,
tags: Optional[Mapping[str, str]] = None,
kinds: Optional[set[str]] = None,
freshness_policy: Optional[FreshnessPolicy] = None,
**kwargs,
):
# Accept a hidden "spec" argument to allow for the AssetOut to be constructed from an AssetSpec
# directly. This is used in the AssetOut.from_spec method.
spec = kwargs.get("spec")
if spec:
del kwargs["spec"]
only_allow_hidden_params_in_kwargs(AssetOut, kwargs)
if isinstance(key_prefix, str):
key_prefix = [key_prefix]
check.invariant(
not (key_prefix and key), "Only one of key_prefix and key should be provided"
)
auto_materialize_policy = kwargs.get("auto_materialize_policy")
legacy_freshness_policy = kwargs.get("legacy_freshness_policy")
has_any_spec_args = any(
[
key,
description,
metadata,
group_name,
code_version,
automation_condition,
auto_materialize_policy,
legacy_freshness_policy,
freshness_policy,
owners,
tags,
kinds,
]
)
check.invariant(
not has_any_spec_args or not spec,
"Cannot provide both spec and spec-related arguments (key, description, metadata, etc.)",
)
with disable_dagster_warnings():
# This is a bit of a hack, since technically AssetOut does not hold all of the
# properties of an AssetSpec - chiefly, it is missing a key. Still, this reduces
# the amount of code duplication storing each of the properties in both AssetOut
# and AssetSpec, and allows us to implement the from_spec method below.
self._spec = spec or AssetSpec(
key=AssetKey.from_coercible(key) if key is not None else EMPTY_ASSET_KEY_SENTINEL,
description=check.opt_str_param(description, "description"),
metadata=check.opt_mapping_param(metadata, "metadata", key_type=str),
group_name=check.opt_str_param(group_name, "group_name"),
code_version=check.opt_str_param(code_version, "code_version"),
automation_condition=check.opt_inst_param(
resolve_automation_condition(automation_condition, auto_materialize_policy),
"automation_condition",
AutomationCondition,
),
legacy_freshness_policy=check.opt_inst_param(
legacy_freshness_policy,
"legacy_freshness_policy",
LegacyFreshnessPolicy,
),
freshness_policy=check.opt_inst_param(
freshness_policy,
"freshness_policy",
FreshnessPolicy,
),
owners=check.opt_sequence_param(owners, "owners", of_type=str),
tags=normalize_tags(tags or {}, strict=True),
kinds=check.opt_set_param(kinds, "kinds", of_type=str),
)
self.key_prefix = key_prefix
self.dagster_type = dagster_type
self.is_required = is_required
self.io_manager_key = io_manager_key
self.backfill_policy = backfill_policy
@property
def key(self) -> Optional[AssetKey]:
return self._spec.key if self._spec.key != EMPTY_ASSET_KEY_SENTINEL else None
@property
def metadata(self) -> Optional[Mapping[str, Any]]:
return self._spec.metadata
@property
def description(self) -> Optional[str]:
return self._spec.description
@property
def group_name(self) -> Optional[str]:
return self._spec.group_name
@property
def code_version(self) -> Optional[str]:
return self._spec.code_version
@property
def legacy_freshness_policy(self) -> Optional[LegacyFreshnessPolicy]:
return self._spec.legacy_freshness_policy
@property
def freshness_policy(self) -> Optional[FreshnessPolicy]:
return self._spec.freshness_policy
@property
def automation_condition(self) -> Optional[AutomationCondition]:
return self._spec.automation_condition
@property
def owners(self) -> Optional[Sequence[str]]:
return self._spec.owners
@property
def tags(self) -> Optional[Mapping[str, str]]:
return self._spec.tags
@property
def kinds(self) -> Optional[set[str]]:
return self._spec.kinds
def to_out(self) -> Out:
return Out(
dagster_type=self.dagster_type,
description=self.description,
metadata=self.metadata,
is_required=self.is_required,
io_manager_key=self.io_manager_key,
code_version=self.code_version,
)
def to_spec(
self,
key: AssetKey,
deps: Sequence[AssetDep],
additional_tags: Mapping[str, str] = {},
partitions_def: Optional[PartitionsDefinition] | EllipsisType = ...,
) -> AssetSpec:
return self._spec.replace_attributes(
key=key,
tags={**additional_tags, **self.tags} if self.tags else additional_tags,
kinds=self.kinds,
deps=[*self._spec.deps, *deps],
partitions_def=partitions_def if partitions_def is not None else ...,
)
@public
@staticmethod
def from_spec(
spec: AssetSpec,
dagster_type: Union[type, DagsterType] = NoValueSentinel,
is_required: bool = True,
io_manager_key: Optional[str] = None,
backfill_policy: Optional[BackfillPolicy] = None,
) -> "AssetOut":
"""Builds an AssetOut from the passed spec.
Args:
spec (AssetSpec): The spec to build the AssetOut from.
dagster_type (Optional[Union[Type, DagsterType]]): The type of this output. Should only
be set if the correct type can not be inferred directly from the type signature of
the decorated function.
is_required (bool): Whether the presence of this field is required. (default: True)
io_manager_key (Optional[str]): The resource key of the IO manager used for this output.
(default: "io_manager").
backfill_policy (Optional[BackfillPolicy]): BackfillPolicy to apply to the specified
asset.
Returns:
AssetOut: The AssetOut built from the spec.
"""
if spec.deps:
raise DagsterInvalidDefinitionError(
"Currently, cannot build AssetOut from spec with deps"
)
return AssetOut(
spec=spec,
dagster_type=dagster_type,
is_required=is_required,
io_manager_key=io_manager_key,
backfill_policy=backfill_policy,
)
@property
def auto_materialize_policy(self) -> Optional[AutoMaterializePolicy]:
return (
self.automation_condition.as_auto_materialize_policy()
if self.automation_condition
else None
)
| AssetOut |
python | wandb__wandb | wandb/vendor/pygments/lexers/r.py | {
"start": 22534,
"end": 23755
} | class ____(RegexLexer):
"""
Pygments Lexer for R documentation (Rd) files
This is a very minimal implementation, highlighting little more
than the macros. A description of Rd syntax is found in `Writing R
Extensions <http://cran.r-project.org/doc/manuals/R-exts.html>`_
and `Parsing Rd files <developer.r-project.org/parseRd.pdf>`_.
.. versionadded:: 1.6
"""
name = 'Rd'
aliases = ['rd']
filenames = ['*.Rd']
mimetypes = ['text/x-r-doc']
# To account for verbatim / LaTeX-like / and R-like areas
# would require parsing.
tokens = {
'root': [
# catch escaped brackets and percent sign
(r'\\[\\{}%]', String.Escape),
# comments
(r'%.*$', Comment),
# special macros with no arguments
(r'\\(?:cr|l?dots|R|tab)\b', Keyword.Constant),
# macros
(r'\\[a-zA-Z]+\b', Keyword),
# special preprocessor macros
(r'^\s*#(?:ifn?def|endif).*\b', Comment.Preproc),
# non-escaped brackets
(r'[{}]', Name.Builtin),
# everything else
(r'[^\\%\n{}]+', Text),
(r'.', Text),
]
}
| RdLexer |
python | apache__airflow | airflow-core/tests/unit/plugins/test_plugin.py | {
"start": 5732,
"end": 5790
} | class ____(AirflowPlugin):
name = "plugin-c"
| MockPluginC |
python | kubernetes-client__python | kubernetes/client/models/v1_custom_resource_definition_list.py | {
"start": 383,
"end": 7265
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'items': 'list[V1CustomResourceDefinition]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1CustomResourceDefinitionList - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1CustomResourceDefinitionList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1CustomResourceDefinitionList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1CustomResourceDefinitionList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1CustomResourceDefinitionList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1CustomResourceDefinitionList. # noqa: E501
items list individual CustomResourceDefinition objects # noqa: E501
:return: The items of this V1CustomResourceDefinitionList. # noqa: E501
:rtype: list[V1CustomResourceDefinition]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1CustomResourceDefinitionList.
items list individual CustomResourceDefinition objects # noqa: E501
:param items: The items of this V1CustomResourceDefinitionList. # noqa: E501
:type: list[V1CustomResourceDefinition]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1CustomResourceDefinitionList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1CustomResourceDefinitionList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1CustomResourceDefinitionList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1CustomResourceDefinitionList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1CustomResourceDefinitionList. # noqa: E501
:return: The metadata of this V1CustomResourceDefinitionList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1CustomResourceDefinitionList.
:param metadata: The metadata of this V1CustomResourceDefinitionList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
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, V1CustomResourceDefinitionList):
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, V1CustomResourceDefinitionList):
return True
return self.to_dict() != other.to_dict()
| V1CustomResourceDefinitionList |
python | scikit-learn__scikit-learn | sklearn/metrics/_plot/confusion_matrix.py | {
"start": 401,
"end": 17363
} | class ____:
"""Confusion Matrix visualization.
It is recommended to use
:func:`~sklearn.metrics.ConfusionMatrixDisplay.from_estimator` or
:func:`~sklearn.metrics.ConfusionMatrixDisplay.from_predictions` to
create a :class:`ConfusionMatrixDisplay`. All parameters are stored as
attributes.
For general information regarding `scikit-learn` visualization tools, see
the :ref:`Visualization Guide <visualizations>`.
For guidance on interpreting these plots, refer to the
:ref:`Model Evaluation Guide <confusion_matrix>`.
Parameters
----------
confusion_matrix : ndarray of shape (n_classes, n_classes)
Confusion matrix.
display_labels : ndarray of shape (n_classes,), default=None
Display labels for plot. If None, display labels are set from 0 to
`n_classes - 1`.
Attributes
----------
im_ : matplotlib AxesImage
Image representing the confusion matrix.
text_ : ndarray of shape (n_classes, n_classes), dtype=matplotlib Text, \
or None
Array of matplotlib axes. `None` if `include_values` is false.
ax_ : matplotlib Axes
Axes with confusion matrix.
figure_ : matplotlib Figure
Figure containing the confusion matrix.
See Also
--------
confusion_matrix : Compute Confusion Matrix to evaluate the accuracy of a
classification.
ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
given an estimator, the data, and the label.
ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
given the true and predicted labels.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y,
... random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> predictions = clf.predict(X_test)
>>> cm = confusion_matrix(y_test, predictions, labels=clf.classes_)
>>> disp = ConfusionMatrixDisplay(confusion_matrix=cm,
... display_labels=clf.classes_)
>>> disp.plot()
<...>
>>> plt.show()
"""
def __init__(self, confusion_matrix, *, display_labels=None):
self.confusion_matrix = confusion_matrix
self.display_labels = display_labels
def plot(
self,
*,
include_values=True,
cmap="viridis",
xticks_rotation="horizontal",
values_format=None,
ax=None,
colorbar=True,
im_kw=None,
text_kw=None,
):
"""Plot visualization.
Parameters
----------
include_values : bool, default=True
Includes values in confusion matrix.
cmap : str or matplotlib Colormap, default='viridis'
Colormap recognized by matplotlib.
xticks_rotation : {'vertical', 'horizontal'} or float, \
default='horizontal'
Rotation of xtick labels.
values_format : str, default=None
Format specification for values in confusion matrix. If `None`,
the format specification is 'd' or '.2g' whichever is shorter.
ax : matplotlib axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
colorbar : bool, default=True
Whether or not to add a colorbar to the plot.
im_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.imshow` call.
text_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.text` call.
.. versionadded:: 1.2
Returns
-------
display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
Returns a :class:`~sklearn.metrics.ConfusionMatrixDisplay` instance
that contains all the information to plot the confusion matrix.
"""
check_matplotlib_support("ConfusionMatrixDisplay.plot")
import matplotlib.pyplot as plt
if ax is None:
fig, ax = plt.subplots()
else:
fig = ax.figure
cm = self.confusion_matrix
n_classes = cm.shape[0]
default_im_kw = dict(interpolation="nearest", cmap=cmap)
im_kw = im_kw or {}
im_kw = _validate_style_kwargs(default_im_kw, im_kw)
text_kw = text_kw or {}
self.im_ = ax.imshow(cm, **im_kw)
self.text_ = None
cmap_min, cmap_max = self.im_.cmap(0), self.im_.cmap(1.0)
if include_values:
self.text_ = np.empty_like(cm, dtype=object)
# print text with appropriate color depending on background
thresh = (cm.max() + cm.min()) / 2.0
for i, j in product(range(n_classes), range(n_classes)):
color = cmap_max if cm[i, j] < thresh else cmap_min
if values_format is None:
text_cm = format(cm[i, j], ".2g")
if cm.dtype.kind != "f":
text_d = format(cm[i, j], "d")
if len(text_d) < len(text_cm):
text_cm = text_d
else:
text_cm = format(cm[i, j], values_format)
default_text_kwargs = dict(ha="center", va="center", color=color)
text_kwargs = _validate_style_kwargs(default_text_kwargs, text_kw)
self.text_[i, j] = ax.text(j, i, text_cm, **text_kwargs)
if self.display_labels is None:
display_labels = np.arange(n_classes)
else:
display_labels = self.display_labels
if colorbar:
fig.colorbar(self.im_, ax=ax)
ax.set(
xticks=np.arange(n_classes),
yticks=np.arange(n_classes),
xticklabels=display_labels,
yticklabels=display_labels,
ylabel="True label",
xlabel="Predicted label",
)
ax.set_ylim((n_classes - 0.5, -0.5))
plt.setp(ax.get_xticklabels(), rotation=xticks_rotation)
self.figure_ = fig
self.ax_ = ax
return self
@classmethod
def from_estimator(
cls,
estimator,
X,
y,
*,
labels=None,
sample_weight=None,
normalize=None,
display_labels=None,
include_values=True,
xticks_rotation="horizontal",
values_format=None,
cmap="viridis",
ax=None,
colorbar=True,
im_kw=None,
text_kw=None,
):
"""Plot Confusion Matrix given an estimator and some data.
For general information regarding `scikit-learn` visualization tools, see
the :ref:`Visualization Guide <visualizations>`.
For guidance on interpreting these plots, refer to the
:ref:`Model Evaluation Guide <confusion_matrix>`.
.. versionadded:: 1.0
Parameters
----------
estimator : estimator instance
Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
in which the last estimator is a classifier.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input values.
y : array-like of shape (n_samples,)
Target values.
labels : array-like of shape (n_classes,), default=None
List of labels to index the confusion matrix. This may be used to
reorder or select a subset of labels. If `None` is given, those
that appear at least once in `y_true` or `y_pred` are used in
sorted order.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
normalize : {'true', 'pred', 'all'}, default=None
Either to normalize the counts display in the matrix:
- if `'true'`, the confusion matrix is normalized over the true
conditions (e.g. rows);
- if `'pred'`, the confusion matrix is normalized over the
predicted conditions (e.g. columns);
- if `'all'`, the confusion matrix is normalized by the total
number of samples;
- if `None` (default), the confusion matrix will not be normalized.
display_labels : array-like of shape (n_classes,), default=None
Target names used for plotting. By default, `labels` will be used
if it is defined, otherwise the unique labels of `y_true` and
`y_pred` will be used.
include_values : bool, default=True
Includes values in confusion matrix.
xticks_rotation : {'vertical', 'horizontal'} or float, \
default='horizontal'
Rotation of xtick labels.
values_format : str, default=None
Format specification for values in confusion matrix. If `None`, the
format specification is 'd' or '.2g' whichever is shorter.
cmap : str or matplotlib Colormap, default='viridis'
Colormap recognized by matplotlib.
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
colorbar : bool, default=True
Whether or not to add a colorbar to the plot.
im_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.imshow` call.
text_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.text` call.
.. versionadded:: 1.2
Returns
-------
display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
See Also
--------
ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
given the true and predicted labels.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import ConfusionMatrixDisplay
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> ConfusionMatrixDisplay.from_estimator(
... clf, X_test, y_test)
<...>
>>> plt.show()
For a detailed example of using a confusion matrix to evaluate a
Support Vector Classifier, please see
:ref:`sphx_glr_auto_examples_model_selection_plot_confusion_matrix.py`
"""
method_name = f"{cls.__name__}.from_estimator"
check_matplotlib_support(method_name)
if not is_classifier(estimator):
raise ValueError(f"{method_name} only supports classifiers")
y_pred = estimator.predict(X)
return cls.from_predictions(
y,
y_pred,
sample_weight=sample_weight,
labels=labels,
normalize=normalize,
display_labels=display_labels,
include_values=include_values,
cmap=cmap,
ax=ax,
xticks_rotation=xticks_rotation,
values_format=values_format,
colorbar=colorbar,
im_kw=im_kw,
text_kw=text_kw,
)
@classmethod
def from_predictions(
cls,
y_true,
y_pred,
*,
labels=None,
sample_weight=None,
normalize=None,
display_labels=None,
include_values=True,
xticks_rotation="horizontal",
values_format=None,
cmap="viridis",
ax=None,
colorbar=True,
im_kw=None,
text_kw=None,
):
"""Plot Confusion Matrix given true and predicted labels.
For general information regarding `scikit-learn` visualization tools, see
the :ref:`Visualization Guide <visualizations>`.
For guidance on interpreting these plots, refer to the
:ref:`Model Evaluation Guide <confusion_matrix>`.
.. versionadded:: 1.0
Parameters
----------
y_true : array-like of shape (n_samples,)
True labels.
y_pred : array-like of shape (n_samples,)
The predicted labels given by the method `predict` of an
classifier.
labels : array-like of shape (n_classes,), default=None
List of labels to index the confusion matrix. This may be used to
reorder or select a subset of labels. If `None` is given, those
that appear at least once in `y_true` or `y_pred` are used in
sorted order.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
normalize : {'true', 'pred', 'all'}, default=None
Either to normalize the counts display in the matrix:
- if `'true'`, the confusion matrix is normalized over the true
conditions (e.g. rows);
- if `'pred'`, the confusion matrix is normalized over the
predicted conditions (e.g. columns);
- if `'all'`, the confusion matrix is normalized by the total
number of samples;
- if `None` (default), the confusion matrix will not be normalized.
display_labels : array-like of shape (n_classes,), default=None
Target names used for plotting. By default, `labels` will be used
if it is defined, otherwise the unique labels of `y_true` and
`y_pred` will be used.
include_values : bool, default=True
Includes values in confusion matrix.
xticks_rotation : {'vertical', 'horizontal'} or float, \
default='horizontal'
Rotation of xtick labels.
values_format : str, default=None
Format specification for values in confusion matrix. If `None`, the
format specification is 'd' or '.2g' whichever is shorter.
cmap : str or matplotlib Colormap, default='viridis'
Colormap recognized by matplotlib.
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
colorbar : bool, default=True
Whether or not to add a colorbar to the plot.
im_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.imshow` call.
text_kw : dict, default=None
Dict with keywords passed to `matplotlib.pyplot.text` call.
.. versionadded:: 1.2
Returns
-------
display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
See Also
--------
ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
given an estimator, the data, and the label.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.metrics import ConfusionMatrixDisplay
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.svm import SVC
>>> X, y = make_classification(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, random_state=0)
>>> clf = SVC(random_state=0)
>>> clf.fit(X_train, y_train)
SVC(random_state=0)
>>> y_pred = clf.predict(X_test)
>>> ConfusionMatrixDisplay.from_predictions(
... y_test, y_pred)
<...>
>>> plt.show()
"""
check_matplotlib_support(f"{cls.__name__}.from_predictions")
if display_labels is None:
if labels is None:
display_labels = unique_labels(y_true, y_pred)
else:
display_labels = labels
cm = confusion_matrix(
y_true,
y_pred,
sample_weight=sample_weight,
labels=labels,
normalize=normalize,
)
disp = cls(confusion_matrix=cm, display_labels=display_labels)
return disp.plot(
include_values=include_values,
cmap=cmap,
ax=ax,
xticks_rotation=xticks_rotation,
values_format=values_format,
colorbar=colorbar,
im_kw=im_kw,
text_kw=text_kw,
)
| ConfusionMatrixDisplay |
python | gevent__gevent | src/gevent/tests/test__server_pywsgi.py | {
"start": 2826,
"end": 2916
} | class ____(test__server.TestSSLGetCertificate):
Settings = Settings
| TestSSLGetCertificate |
python | python-markdown__markdown | markdown/extensions/admonition.py | {
"start": 1403,
"end": 6566
} | class ____(BlockProcessor):
CLASSNAME = 'admonition'
CLASSNAME_TITLE = 'admonition-title'
RE = re.compile(r'(?:^|\n)!!! ?([\w\-]+(?: +[\w\-]+)*)(?: +"(.*?)")? *(?:\n|$)')
RE_SPACES = re.compile(' +')
def __init__(self, parser: blockparser.BlockParser):
"""Initialization."""
super().__init__(parser)
self.current_sibling: etree.Element | None = None
self.content_indent = 0
def parse_content(self, parent: etree.Element, block: str) -> tuple[etree.Element | None, str, str]:
"""Get sibling admonition.
Retrieve the appropriate sibling element. This can get tricky when
dealing with lists.
"""
old_block = block
the_rest = ''
# We already acquired the block via test
if self.current_sibling is not None:
sibling = self.current_sibling
block, the_rest = self.detab(block, self.content_indent)
self.current_sibling = None
self.content_indent = 0
return sibling, block, the_rest
sibling = self.lastChild(parent)
if sibling is None or sibling.tag != 'div' or sibling.get('class', '').find(self.CLASSNAME) == -1:
sibling = None
else:
# If the last child is a list and the content is sufficiently indented
# to be under it, then the content's sibling is in the list.
last_child = self.lastChild(sibling)
indent = 0
while last_child is not None:
if (
sibling is not None and block.startswith(' ' * self.tab_length * 2) and
last_child is not None and last_child.tag in ('ul', 'ol', 'dl')
):
# The expectation is that we'll find an `<li>` or `<dt>`.
# We should get its last child as well.
sibling = self.lastChild(last_child)
last_child = self.lastChild(sibling) if sibling is not None else None
# Context has been lost at this point, so we must adjust the
# text's indentation level so it will be evaluated correctly
# under the list.
block = block[self.tab_length:]
indent += self.tab_length
else:
last_child = None
if not block.startswith(' ' * self.tab_length):
sibling = None
if sibling is not None:
indent += self.tab_length
block, the_rest = self.detab(old_block, indent)
self.current_sibling = sibling
self.content_indent = indent
return sibling, block, the_rest
def test(self, parent: etree.Element, block: str) -> bool:
if self.RE.search(block):
return True
else:
return self.parse_content(parent, block)[0] is not None
def run(self, parent: etree.Element, blocks: list[str]) -> None:
block = blocks.pop(0)
m = self.RE.search(block)
if m:
if m.start() > 0:
self.parser.parseBlocks(parent, [block[:m.start()]])
block = block[m.end():] # removes the first line
block, theRest = self.detab(block)
else:
sibling, block, theRest = self.parse_content(parent, block)
if m:
klass, title = self.get_class_and_title(m)
div = etree.SubElement(parent, 'div')
div.set('class', '{} {}'.format(self.CLASSNAME, klass))
if title:
p = etree.SubElement(div, 'p')
p.text = title
p.set('class', self.CLASSNAME_TITLE)
else:
# Sibling is a list item, but we need to wrap it's content should be wrapped in <p>
if sibling.tag in ('li', 'dd') and sibling.text:
text = sibling.text
sibling.text = ''
p = etree.SubElement(sibling, 'p')
p.text = text
div = sibling
self.parser.parseChunk(div, block)
if theRest:
# This block contained unindented line(s) after the first indented
# line. Insert these lines as the first block of the master blocks
# list for future processing.
blocks.insert(0, theRest)
def get_class_and_title(self, match: re.Match[str]) -> tuple[str, str | None]:
klass, title = match.group(1).lower(), match.group(2)
klass = self.RE_SPACES.sub(' ', klass)
if title is None:
# no title was provided, use the capitalized class name as title
# e.g.: `!!! note` will render
# `<p class="admonition-title">Note</p>`
title = klass.split(' ', 1)[0].capitalize()
elif title == '':
# an explicit blank title should not be rendered
# e.g.: `!!! warning ""` will *not* render `p` with a title
title = None
return klass, title
def makeExtension(**kwargs): # pragma: no cover
return AdmonitionExtension(**kwargs)
| AdmonitionProcessor |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 1400,
"end": 7633
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings and visual embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
# For Visual Features
# Token type and position embedding for image features
self.visual_token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.visual_position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
if config.special_visual_initialize:
self.visual_token_type_embeddings.weight.data = nn.Parameter(
self.token_type_embeddings.weight.data.clone(), requires_grad=True
)
self.visual_position_embeddings.weight.data = nn.Parameter(
self.position_embeddings.weight.data.clone(), requires_grad=True
)
self.visual_projection = nn.Linear(config.visual_embedding_dim, config.hidden_size)
def forward(
self,
input_ids=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
visual_embeds=None,
visual_token_type_ids=None,
image_text_alignment=None,
):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + token_type_embeddings
# Absolute Position Embeddings
position_embeddings = self.position_embeddings(position_ids)
embeddings += position_embeddings
if visual_embeds is not None:
if visual_token_type_ids is None:
visual_token_type_ids = torch.ones(
visual_embeds.size()[:-1], dtype=torch.long, device=self.position_ids.device
)
visual_embeds = self.visual_projection(visual_embeds)
visual_token_type_embeddings = self.visual_token_type_embeddings(visual_token_type_ids)
if image_text_alignment is not None:
# image_text_alignment = Batch x image_length x alignment_number.
# Each element denotes the position of the word corresponding to the image feature. -1 is the padding value.
dtype = token_type_embeddings.dtype
image_text_alignment_mask = (image_text_alignment != -1).long()
# Get rid of the -1.
image_text_alignment = image_text_alignment_mask * image_text_alignment
# Batch x image_length x alignment length x dim
visual_position_embeddings = self.position_embeddings(image_text_alignment)
visual_position_embeddings *= image_text_alignment_mask.to(dtype=dtype).unsqueeze(-1)
visual_position_embeddings = visual_position_embeddings.sum(2)
# We want to average along the alignment_number dimension.
image_text_alignment_mask = image_text_alignment_mask.to(dtype=dtype).sum(2)
if (image_text_alignment_mask == 0).sum() != 0:
image_text_alignment_mask[image_text_alignment_mask == 0] = 1 # Avoid divide by zero error
logger.warning(
"Found 0 values in `image_text_alignment_mask`. Setting them to 1 to avoid divide-by-zero"
" error."
)
visual_position_embeddings = visual_position_embeddings / image_text_alignment_mask.unsqueeze(-1)
visual_position_ids = torch.zeros(
*visual_embeds.size()[:-1], dtype=torch.long, device=visual_embeds.device
)
# When fine-tuning the detector , the image_text_alignment is sometimes padded too long.
if visual_position_embeddings.size(1) != visual_embeds.size(1):
if visual_position_embeddings.size(1) < visual_embeds.size(1):
raise ValueError(
f"Visual position embeddings length: {visual_position_embeddings.size(1)} "
f"should be the same as `visual_embeds` length: {visual_embeds.size(1)}"
)
visual_position_embeddings = visual_position_embeddings[:, : visual_embeds.size(1), :]
visual_position_embeddings = visual_position_embeddings + self.visual_position_embeddings(
visual_position_ids
)
else:
visual_position_ids = torch.zeros(
*visual_embeds.size()[:-1], dtype=torch.long, device=visual_embeds.device
)
visual_position_embeddings = self.visual_position_embeddings(visual_position_ids)
visual_embeddings = visual_embeds + visual_position_embeddings + visual_token_type_embeddings
embeddings = torch.cat((embeddings, visual_embeddings), dim=1)
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
| VisualBertEmbeddings |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP050.py | {
"start": 19,
"end": 54
} | class ____(metaclass=type):
...
| A |
python | celery__celery | t/unit/tasks/test_chord.py | {
"start": 9710,
"end": 11371
} | class ____:
def setup_method(self):
@self.app.task(shared=False)
def add(x, y):
return x + y
self.add = add
@self.app.task(shared=False, bind=True)
def adds(self, sig, lazy=False):
return self.add_to_chord(sig, lazy)
self.adds = adds
@patch('celery.Celery.backend', new=PropertyMock(name='backend'))
def test_add_to_chord(self):
sig = self.add.s(2, 2)
sig.delay = Mock(name='sig.delay')
self.adds.request.group = uuid()
self.adds.request.id = uuid()
with pytest.raises(ValueError):
# task not part of chord
self.adds.run(sig)
self.adds.request.chord = self.add.s()
res1 = self.adds.run(sig, True)
assert res1 == sig
assert sig.options['task_id']
assert sig.options['group_id'] == self.adds.request.group
assert sig.options['chord'] == self.adds.request.chord
sig.delay.assert_not_called()
self.app.backend.add_to_chord.assert_called_with(
self.adds.request.group, sig.freeze(),
)
self.app.backend.reset_mock()
sig2 = self.add.s(4, 4)
sig2.delay = Mock(name='sig2.delay')
res2 = self.adds.run(sig2)
assert res2 == sig2.delay.return_value
assert sig2.options['task_id']
assert sig2.options['group_id'] == self.adds.request.group
assert sig2.options['chord'] == self.adds.request.chord
sig2.delay.assert_called_with()
self.app.backend.add_to_chord.assert_called_with(
self.adds.request.group, sig2.freeze(),
)
| test_add_to_chord |
python | networkx__networkx | networkx/generators/tests/test_lattice.py | {
"start": 3820,
"end": 5325
} | class ____:
"""Unit tests for :func:`networkx.generators.lattice.grid_graph`"""
def test_grid_graph(self):
"""grid_graph([n,m]) is a connected simple graph with the
following properties:
number_of_nodes = n*m
degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)]
"""
for n, m in [(3, 5), (5, 3), (4, 5), (5, 4)]:
dim = [n, m]
g = nx.grid_graph(dim)
assert len(g) == n * m
assert nx.degree_histogram(g) == [
0,
0,
4,
2 * (n + m) - 8,
(n - 2) * (m - 2),
]
for n, m in [(1, 5), (5, 1)]:
dim = [n, m]
g = nx.grid_graph(dim)
assert len(g) == n * m
assert nx.is_isomorphic(g, nx.path_graph(5))
# mg = nx.grid_graph([n,m], create_using=MultiGraph())
# assert_equal(mg.edges(), g.edges())
def test_node_input(self):
G = nx.grid_graph([range(7, 9), range(3, 6)])
assert len(G) == 2 * 3
assert nx.is_isomorphic(G, nx.grid_graph([2, 3]))
def test_periodic_iterable(self):
m, n, k = 3, 7, 5
for a, b, c in product([0, 1], [0, 1], [0, 1]):
G = nx.grid_graph([m, n, k], periodic=(a, b, c))
num_e = (m + a - 1) * n * k + (n + b - 1) * m * k + (k + c - 1) * m * n
assert G.number_of_nodes() == m * n * k
assert G.number_of_edges() == num_e
| TestGridGraph |
python | pytorch__pytorch | test/distributed/test_c10d_pypg.py | {
"start": 661,
"end": 1084
} | class ____(dist._Work):
def __init__(self, result, pg):
super().__init__()
self.result_ = result
self.future_ = torch.futures.Future()
self.future_.set_result(result)
self.pg_ = weakref.ref(pg)
def wait(self, timeout):
self.pg_().wait_count += 1
return True
def get_future(self):
self.pg_().get_future_count += 1
return self.future_
| MyWork |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.