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 | agronholm__apscheduler | src/apscheduler/_retry.py | {
"start": 864,
"end": 1991
} | class ____:
"""
Mixin that provides support for retrying operations.
:param retry_settings: Tenacity settings for retrying operations in case of a
database connecitivty problem
"""
retry_settings: RetrySettings = attrs.field(default=RetrySettings())
_logger: Logger = attrs.field(init=False)
@property
def _temporary_failure_exceptions(self) -> tuple[type[Exception], ...]:
"""
Tuple of exception classes which indicate that the operation should be retried.
"""
return ()
def _retry(self) -> AsyncRetrying:
def after_attempt(retry_state: RetryCallState) -> None:
self._logger.warning(
"Temporary data store error (attempt %d): %s",
retry_state.attempt_number,
retry_state.outcome.exception(),
)
return AsyncRetrying(
stop=self.retry_settings.stop,
wait=self.retry_settings.wait,
retry=retry_if_exception_type(self._temporary_failure_exceptions),
after=after_attempt,
reraise=True,
)
| RetryMixin |
python | ray-project__ray | python/ray/util/queue.py | {
"start": 326,
"end": 8650
} | class ____:
"""A first-in, first-out queue implementation on Ray.
The behavior and use cases are similar to those of the asyncio.Queue class.
Features both sync and async put and get methods. Provides the option to
block until space is available when calling put on a full queue,
or to block until items are available when calling get on an empty queue.
Optionally supports batched put and get operations to minimize
serialization overhead.
Args:
maxsize (optional, int): maximum size of the queue. If zero, size is
unbounded.
actor_options (optional, Dict): Dictionary of options to pass into
the QueueActor during creation. These are directly passed into
QueueActor.options(...). This could be useful if you
need to pass in custom resource requirements, for example.
Examples:
.. testcode::
from ray.util.queue import Queue
q = Queue()
items = list(range(10))
for item in items:
q.put(item)
for item in items:
assert item == q.get()
# Create Queue with the underlying actor reserving 1 CPU.
q = Queue(actor_options={"num_cpus": 1})
"""
def __init__(self, maxsize: int = 0, actor_options: Optional[Dict] = None) -> None:
from ray._common.usage.usage_lib import record_library_usage
record_library_usage("util.Queue")
actor_options = actor_options or {}
self.maxsize = maxsize
self.actor = (
ray.remote(_QueueActor).options(**actor_options).remote(self.maxsize)
)
def __len__(self) -> int:
return self.size()
def size(self) -> int:
"""The size of the queue."""
return ray.get(self.actor.qsize.remote())
def qsize(self) -> int:
"""The size of the queue."""
return self.size()
def empty(self) -> bool:
"""Whether the queue is empty."""
return ray.get(self.actor.empty.remote())
def full(self) -> bool:
"""Whether the queue is full."""
return ray.get(self.actor.full.remote())
def put(
self, item: Any, block: bool = True, timeout: Optional[float] = None
) -> None:
"""Adds an item to the queue.
If block is True and the queue is full, blocks until the queue is no
longer full or until timeout.
There is no guarantee of order if multiple producers put to the same
full queue.
Raises:
Full: if the queue is full and blocking is False.
Full: if the queue is full, blocking is True, and it timed out.
ValueError: if timeout is negative.
"""
if not block:
try:
ray.get(self.actor.put_nowait.remote(item))
except asyncio.QueueFull:
raise Full
else:
if timeout is not None and timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
ray.get(self.actor.put.remote(item, timeout))
async def put_async(
self, item: Any, block: bool = True, timeout: Optional[float] = None
) -> None:
"""Adds an item to the queue.
If block is True and the queue is full,
blocks until the queue is no longer full or until timeout.
There is no guarantee of order if multiple producers put to the same
full queue.
Raises:
Full: if the queue is full and blocking is False.
Full: if the queue is full, blocking is True, and it timed out.
ValueError: if timeout is negative.
"""
if not block:
try:
await self.actor.put_nowait.remote(item)
except asyncio.QueueFull:
raise Full
else:
if timeout is not None and timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
await self.actor.put.remote(item, timeout)
def get(self, block: bool = True, timeout: Optional[float] = None) -> Any:
"""Gets an item from the queue.
If block is True and the queue is empty, blocks until the queue is no
longer empty or until timeout.
There is no guarantee of order if multiple consumers get from the
same empty queue.
Returns:
The next item in the queue.
Raises:
Empty: if the queue is empty and blocking is False.
Empty: if the queue is empty, blocking is True, and it timed out.
ValueError: if timeout is negative.
"""
if not block:
try:
return ray.get(self.actor.get_nowait.remote())
except asyncio.QueueEmpty:
raise Empty
else:
if timeout is not None and timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
return ray.get(self.actor.get.remote(timeout))
async def get_async(
self, block: bool = True, timeout: Optional[float] = None
) -> Any:
"""Gets an item from the queue.
There is no guarantee of order if multiple consumers get from the
same empty queue.
Returns:
The next item in the queue.
Raises:
Empty: if the queue is empty and blocking is False.
Empty: if the queue is empty, blocking is True, and it timed out.
ValueError: if timeout is negative.
"""
if not block:
try:
return await self.actor.get_nowait.remote()
except asyncio.QueueEmpty:
raise Empty
else:
if timeout is not None and timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
return await self.actor.get.remote(timeout)
def put_nowait(self, item: Any) -> None:
"""Equivalent to put(item, block=False).
Raises:
Full: if the queue is full.
"""
return self.put(item, block=False)
def put_nowait_batch(self, items: Iterable) -> None:
"""Takes in a list of items and puts them into the queue in order.
Raises:
Full: if the items will not fit in the queue
"""
if not isinstance(items, Iterable):
raise TypeError("Argument 'items' must be an Iterable")
ray.get(self.actor.put_nowait_batch.remote(items))
def get_nowait(self) -> Any:
"""Equivalent to get(block=False).
Raises:
Empty: if the queue is empty.
"""
return self.get(block=False)
def get_nowait_batch(self, num_items: int) -> List[Any]:
"""Gets items from the queue and returns them in a
list in order.
Raises:
Empty: if the queue does not contain the desired number of items
"""
if not isinstance(num_items, int):
raise TypeError("Argument 'num_items' must be an int")
if num_items < 0:
raise ValueError("'num_items' must be nonnegative")
return ray.get(self.actor.get_nowait_batch.remote(num_items))
def shutdown(self, force: bool = False, grace_period_s: int = 5) -> None:
"""Terminates the underlying QueueActor.
All of the resources reserved by the queue will be released.
Args:
force: If True, forcefully kill the actor, causing an
immediate failure. If False, graceful
actor termination will be attempted first, before falling back
to a forceful kill.
grace_period_s: If force is False, how long in seconds to
wait for graceful termination before falling back to
forceful kill.
"""
if self.actor:
if force:
ray.kill(self.actor, no_restart=True)
else:
done_ref = self.actor.__ray_terminate__.remote()
done, not_done = ray.wait([done_ref], timeout=grace_period_s)
if not_done:
ray.kill(self.actor, no_restart=True)
self.actor = None
| Queue |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 68512,
"end": 69432
} | class ____(Request):
"""
Get the tasks's latest scalar values
:param task: Task ID
:type task: str
"""
_service = "events"
_action = "get_task_latest_scalar_values"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task ID", "type": "string"}},
"required": ["task"],
"type": "object",
}
def __init__(self, task: str, **kwargs: Any) -> None:
super(GetTaskLatestScalarValuesRequest, self).__init__(**kwargs)
self.task = task
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
| GetTaskLatestScalarValuesRequest |
python | pytorch__pytorch | benchmarks/tensorexpr/pooling.py | {
"start": 1306,
"end": 1478
} | class ____(PoolingBench):
def __init__(self, *args):
super().__init__("maxpool", *args)
@staticmethod
def module():
return "maxpool"
| MaxPoolBench |
python | pennersr__django-allauth | allauth/socialaccount/views.py | {
"start": 2652,
"end": 2894
} | class ____(TemplateView):
template_name = (
"socialaccount/authentication_error." + account_settings.TEMPLATE_EXTENSION
)
login_error = LoginErrorView.as_view()
@method_decorator(login_required, name="dispatch")
| LoginErrorView |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/deprecated2.py | {
"start": 1598,
"end": 3075
} | class ____:
@overload
def __new__(cls, x: int) -> Self: ...
@overload
@deprecated("str no longer supported")
def __new__(cls, x: str) -> Self: ...
def __new__(cls, x: int | str) -> Self: ...
ClassE(3)
# This should generate an error if reportDeprecated is enabled.
ClassE("")
@deprecated("Deprecated async function")
async def func3(): ...
async def func4():
# This should generate an error if reportDeprecated is enabled.
await func3()
@overload
def func5(val: int): ...
@overload
def func5(val: str): ...
@deprecated("All overloads are deprecated")
def func5(val: object): ...
# This should generate an error if reportDeprecated is enabled.
func5(1)
# This should generate an error if reportDeprecated is enabled.
func5("")
# This should generate an error if reportDeprecated is enabled.
v1 = func5
T = TypeVar("T", bound=Callable[..., Any])
@deprecated("Use different decorator")
@overload
def deco1(value: T) -> T: ...
@overload
def deco1(value: str): ...
def deco1(value: object) -> object: ...
# This should generate an error if reportDeprecated is enabled.
@deco1
def func6(): ...
@contextmanager
@deprecated("Func is deprecated")
def func7():
yield
# This should generate an error if reportDeprecated is enabled.
with func7():
...
@deprecated("Func is deprecated")
@contextmanager
def func8():
yield
# This should generate an error if reportDeprecated is enabled.
with func8():
...
| ClassE |
python | milvus-io__pymilvus | pymilvus/orm/schema.py | {
"start": 36522,
"end": 44488
} | class ____:
def __init__(
self,
functions: Union[Function, List[Function]],
params: Optional[Dict] = None,
):
if isinstance(functions, Function):
self._functions = [functions]
else:
self._functions = functions
self._params = params
@property
def params(self):
return self._params
@property
def functions(self):
return self._functions
def is_valid_insert_data(data: Union[pd.DataFrame, list, dict]) -> bool:
"""DataFrame, list, dict are valid insert data"""
return isinstance(data, (pd.DataFrame, list, dict))
def is_row_based(data: Union[Dict, List[Dict]]) -> bool:
"""Dict or List[Dict] are row-based"""
return isinstance(data, dict) or (
isinstance(data, list) and len(data) > 0 and isinstance(data[0], Dict)
)
def check_is_row_based(data: Union[List[List], List[Dict], Dict, pd.DataFrame]) -> bool:
if not isinstance(data, (pd.DataFrame, list, dict)):
raise DataTypeNotSupportException(
message="The type of data should be list or pandas.DataFrame or dict"
)
if isinstance(data, pd.DataFrame):
return False
if isinstance(data, dict):
return True
if isinstance(data, list):
if len(data) == 0:
return False
if isinstance(data[0], Dict):
return True
return False
def _check_insert_data(data: Union[List[List], pd.DataFrame]):
if not isinstance(data, (pd.DataFrame, list)):
raise DataTypeNotSupportException(
message="The type of data should be list or pandas.DataFrame"
)
is_dataframe = isinstance(data, pd.DataFrame)
for col in data:
if not is_dataframe and not is_list_like(col):
raise DataTypeNotSupportException(message="The data should be a list of list")
def _check_data_schema_cnt(fields: List, data: Union[List[List], pd.DataFrame]):
field_cnt = len([f for f in fields if not f.is_function_output])
is_dataframe = isinstance(data, pd.DataFrame)
data_cnt = len(data.columns) if is_dataframe else len(data)
if field_cnt != data_cnt:
message = (
f"The data doesn't match with schema fields, expect {field_cnt} list, got {len(data)}"
)
if is_dataframe:
i_name = [f.name for f in fields]
t_name = list(data.columns)
message = f"The fields don't match with schema fields, expected: {i_name}, got {t_name}"
raise DataNotMatchException(message=message)
if is_dataframe:
for x, y in zip(list(data.columns), fields):
if x != y.name:
raise DataNotMatchException(
message=f"The name of field doesn't match, expected: {y.name}, got {x}"
)
def check_insert_schema(schema: CollectionSchema, data: Union[List[List], pd.DataFrame]):
if schema is None:
raise SchemaNotReadyException(message="Schema shouldn't be None")
if schema.auto_id and isinstance(data, pd.DataFrame) and schema.primary_field.name in data:
if not data[schema.primary_field.name].isnull().all():
msg = f"Expect no data for auto_id primary field: {schema.primary_field.name}"
raise DataNotMatchException(message=msg)
columns = list(data.columns)
columns.remove(schema.primary_field)
data = data[columns]
tmp_fields = list(
filter(
lambda field: not (field.is_primary and field.auto_id) and not field.is_function_output,
schema.fields,
)
)
_check_data_schema_cnt(tmp_fields, data)
_check_insert_data(data)
def check_upsert_schema(schema: CollectionSchema, data: Union[List[List], pd.DataFrame]):
if schema is None:
raise SchemaNotReadyException(message="Schema shouldn't be None")
if isinstance(data, pd.DataFrame):
if schema.primary_field.name not in data or data[schema.primary_field.name].isnull().all():
raise DataNotMatchException(message=ExceptionsMessage.UpsertPrimaryKeyEmpty)
columns = list(data.columns)
data = data[columns]
_check_data_schema_cnt(copy.deepcopy(schema.fields), data)
_check_insert_data(data)
def construct_fields_from_dataframe(df: pd.DataFrame) -> List[FieldSchema]:
col_names, data_types, column_params_map = prepare_fields_from_dataframe(df)
fields = []
for name, dtype in zip(col_names, data_types):
type_params = column_params_map.get(name, {})
field_schema = FieldSchema(name, dtype, **type_params)
fields.append(field_schema)
return fields
def prepare_fields_from_dataframe(df: pd.DataFrame):
# TODO: infer pd.SparseDtype as DataType.SPARSE_FLOAT_VECTOR
d_types = list(df.dtypes)
data_types = list(map(map_numpy_dtype_to_datatype, d_types))
col_names = list(df.columns)
column_params_map = {}
if DataType.UNKNOWN in data_types:
if len(df) == 0:
raise CannotInferSchemaException(message=ExceptionsMessage.DataFrameInvalid)
values = df.head(1).to_numpy()[0]
for i, dtype in enumerate(data_types):
if dtype == DataType.UNKNOWN:
new_dtype = infer_dtype_bydata(values[i])
if new_dtype in (
DataType.BINARY_VECTOR,
DataType.FLOAT_VECTOR,
DataType.FLOAT16_VECTOR,
DataType.BFLOAT16_VECTOR,
DataType.INT8_VECTOR,
):
vector_type_params = {}
if new_dtype == DataType.BINARY_VECTOR:
vector_type_params["dim"] = len(values[i]) * 8
elif new_dtype in (DataType.FLOAT16_VECTOR, DataType.BFLOAT16_VECTOR):
vector_type_params["dim"] = int(len(values[i]) // 2)
elif new_dtype == DataType.INT8_VECTOR:
vector_type_params["dim"] = len(values[i])
else:
vector_type_params["dim"] = len(values[i])
column_params_map[col_names[i]] = vector_type_params
data_types[i] = new_dtype
if DataType.UNKNOWN in data_types:
raise CannotInferSchemaException(message=ExceptionsMessage.DataFrameInvalid)
return col_names, data_types, column_params_map
def check_schema(schema: CollectionSchema):
if schema is None:
raise SchemaNotReadyException(message=ExceptionsMessage.NoSchema)
if len(schema.fields) < 1:
raise SchemaNotReadyException(message=ExceptionsMessage.EmptySchema)
vector_fields = []
for field in schema.fields:
if field.dtype in (
DataType.FLOAT_VECTOR,
DataType.BINARY_VECTOR,
DataType.FLOAT16_VECTOR,
DataType.BFLOAT16_VECTOR,
DataType.SPARSE_FLOAT_VECTOR,
DataType.INT8_VECTOR,
):
vector_fields.append(field.name)
if len(vector_fields) < 1:
raise SchemaNotReadyException(message=ExceptionsMessage.NoVector)
def infer_default_value_bydata(data: Any):
if data is None:
return None
default_data = schema_types.ValueField()
d_type = DataType.UNKNOWN
if is_scalar(data):
d_type = infer_dtype_by_scalar_data(data)
if d_type is DataType.BOOL:
default_data.bool_data = data
elif d_type in (DataType.INT8, DataType.INT16, DataType.INT32):
default_data.int_data = data
elif d_type is DataType.INT64:
default_data.long_data = data
elif d_type is DataType.FLOAT:
default_data.float_data = data
elif d_type is DataType.DOUBLE:
default_data.double_data = data
elif d_type is DataType.VARCHAR:
default_data.string_data = data
else:
raise ParamError(message=f"Default value unsupported data type: {d_type}")
return default_data
| FunctionScore |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/base.py | {
"start": 2751,
"end": 4186
} | class ____:
"""
Table data source information.
Notes
-----
This class should be sub-classed for specific
data source types (e.g. Parquet, DataFrame, etc.).
The required properties/methods enable lazy
sampling of the underlying datasource.
"""
_unique_stats_columns: set[str]
_read_columns: set[str]
@property
def row_count(self) -> ColumnStat[int]: # pragma: no cover
"""Data source row-count estimate."""
raise NotImplementedError("Sub-class must implement row_count.")
def unique_stats(
self,
column: str,
) -> UniqueStats: # pragma: no cover
"""Return unique-value statistics for a column."""
raise NotImplementedError("Sub-class must implement unique_stats.")
def storage_size(self, column: str) -> ColumnStat[int]:
"""Return the average column size for a single file."""
return ColumnStat[int]()
@property
def unique_stats_columns(self) -> set[str]:
"""Return the set of columns needing unique-value information."""
return self._unique_stats_columns
def add_unique_stats_column(self, column: str) -> None:
"""Add a column needing unique-value information."""
self._unique_stats_columns.add(column)
def add_read_column(self, column: str) -> None:
"""Add a column needing to be read."""
self._read_columns.add(column)
| DataSourceInfo |
python | davidhalter__jedi | jedi/inference/signature.py | {
"start": 1101,
"end": 1947
} | class ____(_SignatureMixin):
def __init__(self, value, is_bound=False):
self.value = value
self.is_bound = is_bound
@property
def name(self):
return self.value.name
@property
def annotation_string(self):
return ''
def get_param_names(self, resolve_stars=False):
param_names = self._function_value.get_param_names()
if self.is_bound:
return param_names[1:]
return param_names
def bind(self, value):
raise NotImplementedError
def matches_signature(self, arguments):
return True
def __repr__(self):
if self.value is self._function_value:
return '<%s: %s>' % (self.__class__.__name__, self.value)
return '<%s: %s, %s>' % (self.__class__.__name__, self.value, self._function_value)
| AbstractSignature |
python | getsentry__sentry | src/sentry_plugins/splunk/plugin.py | {
"start": 874,
"end": 9022
} | class ____(CorePluginMixin, DataForwardingPlugin):
"""
- Turn on HTTP Event Collector by enabling its endpoint. HEC is not enabled by default.
- http://dev.splunk.com/view/event-collector/SP-CAAAE7F
- Settings > Data Inputs > HTTP Event Collector > Add new
- Name: Sentry
- You'll be given an HEC token, which is needed to configure Sentry.
- On the client that will log to HEC, create a POST request, and set its
authentication header or key/value pair to include the HEC token.
- POST data to the HEC token receiver.
Note: Managed Splunk Cloud customers can turn on HTTP Event Collector by filing a request ticket with Splunk Support.
Note: Managed Splunk Cloud customers can create a HEC token by filing a request ticket with Splunk Support.
For more details on the payload: http://dev.splunk.com/view/event-collector/SP-CAAAE6M
"""
title = "Splunk"
slug = "splunk"
description = DESCRIPTION
conf_key = "splunk"
resource_links = [("Splunk Setup Instructions", SETUP_URL)] + CorePluginMixin.resource_links
required_field = "instance"
project_token: str | None = None
project_index: str | None = None
project_source: str | None = None
project_instance: str | None = None
host: str | None = None
feature_descriptions = [
FeatureDescription(
"""
Forward Sentry errors and events to Splunk.
""",
IntegrationFeatures.DATA_FORWARDING,
)
]
def get_rate_limit(self) -> tuple[int, int]:
# number of requests, number of seconds (window)
return (1000, 1)
def get_config(self, project, user=None, initial=None, add_additional_fields: bool = False):
return [
{
"name": "instance",
"label": "Instance URL",
"type": "url",
"required": True,
"help": "The HTTP Event Collector endpoint for your Splunk instance.",
"placeholder": "e.g. https://input-foo.cloud.splunk.com:8088",
},
{
"name": "index",
"label": "Index",
"type": "string",
"required": True,
"default": "main",
},
{
"name": "source",
"label": "Source",
"type": "string",
"required": True,
"default": "sentry",
},
get_secret_field_config(
name="token", label="Token", secret=self.get_option("token", project)
),
]
def get_host_for_splunk(self, event):
host = event.get_tag("server_name")
if host:
return host
user_interface = event.interfaces.get("user")
if user_interface:
host = user_interface.ip_address
if host:
return host
return None
def get_event_payload_properties(self, event):
props = {
"event_id": event.event_id,
"issue_id": event.group_id,
"project_id": event.project.slug,
"transaction": event.get_tag("transaction") or "",
"release": event.get_tag("sentry:release") or "",
"environment": event.get_tag("environment") or "",
"type": event.get_event_type(),
}
props["tags"] = [
[k.format(tagstore.backend.get_standardized_key(k)), v] for k, v in event.tags
]
for key, value in event.interfaces.items():
if key == "request":
headers = value.headers
if not isinstance(headers, dict):
headers = dict(headers or ())
props.update(
{
"request_url": value.url,
"request_method": value.method,
"request_referer": headers.get("Referer", ""),
}
)
elif key == "exception":
exc = value.values[0]
props.update({"exception_type": exc.type, "exception_value": exc.value})
elif key == "logentry":
props.update({"message": value.formatted or value.message})
elif key in ("csp", "expectct", "expectstable", "hpkp"):
props.update(
{
"{}_{}".format(key.rsplit(".", 1)[-1].lower(), k): v
for k, v in value.to_json().items()
}
)
elif key == "user":
user_payload = {}
if value.id:
user_payload["user_id"] = value.id
if value.email:
user_payload["user_email_hash"] = md5_text(value.email).hexdigest()
if value.ip_address:
user_payload["user_ip_trunc"] = anonymize_ip(value.ip_address)
if user_payload:
props.update(user_payload)
return props
def initialize_variables(self, event):
self.project_token = self.get_option("token", event.project)
self.project_index = self.get_option("index", event.project)
self.project_instance = self.get_option("instance", event.project)
self.host = self.get_host_for_splunk(event)
if self.project_instance and not self.project_instance.endswith("/services/collector"):
self.project_instance = self.project_instance.rstrip("/") + "/services/collector"
self.project_source = self.get_option("source", event.project) or "sentry"
def get_rl_key(self, event) -> str:
return f"{self.conf_key}:{md5_text(self.project_token).hexdigest()}"
def is_ratelimited(self, event):
if super().is_ratelimited(event):
metrics.incr(
"integrations.splunk.forward-event.rate-limited",
tags={"event_type": event.get_event_type()},
)
return True
return False
def get_event_payload(self, event):
payload = {
"time": int(event.datetime.strftime("%s")),
"source": self.project_source,
"index": self.project_index,
"event": self.get_event_payload_properties(event),
}
return payload
def forward_event(self, event: Event, payload: MutableMapping[str, Any]) -> bool:
if not (self.project_token and self.project_index and self.project_instance):
metrics.incr(
"integrations.splunk.forward-event.unconfigured",
tags={"event_type": event.get_event_type()},
)
return False
if self.host:
payload["host"] = self.host
client = SplunkApiClient(self.project_instance, self.project_token)
try:
# https://docs.splunk.com/Documentation/Splunk/7.2.3/Data/TroubleshootHTTPEventCollector
client.request(payload)
except Exception as exc:
metric = "integrations.splunk.forward-event.error"
metrics.incr(metric, tags={"event_type": event.get_event_type()})
logger.info(
metric,
extra={
"instance": self.project_instance,
"project_id": event.project_id,
"organization_id": event.project.organization_id,
"error": str(exc),
},
)
if isinstance(exc, ApiError) and (
# These two are already handled by the API client, Just log and return.
isinstance(exc, (ApiHostError, ApiTimeoutError))
# Most 4xxs are not errors or actionable for us do not re-raise.
or (exc.code is not None and (401 <= exc.code <= 405) or exc.code in (502, 504))
):
return False
raise
metrics.incr(
"integrations.splunk.forward-event.success", tags={"event_type": event.get_event_type()}
)
return True
| SplunkPlugin |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/RemoteGraphicsView.py | {
"start": 717,
"end": 2123
} | class ____(QtGui.QMouseEvent):
@staticmethod
def get_state(obj, picklable=False):
typ = obj.type()
if isinstance(typ, int):
# PyQt6 returns an int here instead of QEvent.Type,
# but its QtGui.QMouseEvent constructor takes only QEvent.Type.
# Note however that its QtCore.QEvent constructor accepts both
# QEvent.Type and int.
typ = QtCore.QEvent.Type(typ)
lpos = obj.position() if hasattr(obj, 'position') else obj.localPos()
gpos = obj.globalPosition() if hasattr(obj, 'globalPosition') else obj.screenPos()
btn, btns, mods = obj.button(), obj.buttons(), obj.modifiers()
if picklable:
typ, btn, btns, mods = serialize_mouse_enum(typ, btn, btns, mods)
return typ, lpos, gpos, btn, btns, mods
def __init__(self, rhs):
super().__init__(*self.get_state(rhs))
def __getstate__(self):
return self.get_state(self, picklable=True)
def __setstate__(self, state):
typ, lpos, gpos, btn, btns, mods = state
typ = QtCore.QEvent.Type(typ)
btn = QtCore.Qt.MouseButton(btn)
if not isinstance(btns, enum.Enum):
btns = QtCore.Qt.MouseButtons(btns)
if not isinstance(mods, enum.Enum):
mods = QtCore.Qt.KeyboardModifiers(mods)
super().__init__(typ, lpos, gpos, btn, btns, mods)
| MouseEvent |
python | optuna__optuna | optuna/storages/_rdb/models.py | {
"start": 4239,
"end": 5310
} | class ____(BaseModel):
__tablename__ = "study_system_attributes"
__table_args__: Any = (UniqueConstraint("study_id", "key"),)
study_system_attribute_id = _Column(Integer, primary_key=True)
study_id = _Column(Integer, ForeignKey("studies.study_id"))
key = _Column(String(MAX_INDEXED_STRING_LENGTH))
value_json = _Column(Text())
study = orm.relationship(
StudyModel, backref=orm.backref("system_attributes", cascade="all, delete-orphan")
)
@classmethod
def find_by_study_and_key(
cls, study: StudyModel, key: str, session: orm.Session
) -> "StudySystemAttributeModel" | None:
attribute = (
session.query(cls)
.filter(cls.study_id == study.study_id)
.filter(cls.key == key)
.one_or_none()
)
return attribute
@classmethod
def where_study_id(
cls, study_id: int, session: orm.Session
) -> list["StudySystemAttributeModel"]:
return session.query(cls).filter(cls.study_id == study_id).all()
| StudySystemAttributeModel |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_ops.py | {
"start": 27449,
"end": 29062
} | class ____(TestDTensorOps):
_op_db = repurpose_ops(op_db, "TestDTensorOps", "TestLocalDTensorOps")
def setUp(self) -> None:
super().setUp()
torch.distributed.init_process_group("fake", rank=0, world_size=self.world_size)
self.fake_pg = torch.distributed.distributed_c10d._get_default_group()
def tearDown(self):
super().tearDown()
try:
dist.destroy_process_group()
except AssertionError:
pass
@suppress_warnings
@ops(_op_db, allowed_dtypes=(torch.float,))
@skipOps(
_op_db,
"TestLocalDTensorOps",
"test_dtensor_op_db",
dtensor_fails,
)
def test_dtensor_op_db(self, dtype, op):
self.run_opinfo_test(dtype, op)
def test_mean(self):
with LocalTensorMode(frozenset(range(self.world_size))):
self.run_mean()
def test_one_hot(self):
self.run_one_hot()
def run_opinfo_test(
self, dtype, op, requires_grad=True, sample_inputs_filter=lambda s: True
):
with LocalTensorMode(frozenset(range(self.world_size))):
super().run_opinfo_test(dtype, op, requires_grad, sample_inputs_filter)
def assertEqualOnRank(self, x, y, msg=None, *, rank=0):
self.assertEqual(x, y, msg)
# only instantiate tests for DEVICE_TYPE alone (i.e. either CPU or GPU)
instantiate_device_type_tests(
TestMultiThreadedDTensorOps, globals(), only_for=(DEVICE_TYPE,)
)
instantiate_device_type_tests(TestLocalDTensorOps, globals(), only_for=(DEVICE_TYPE,))
if __name__ == "__main__":
run_tests()
| TestLocalDTensorOps |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/training_epoch_loop.py | {
"start": 2272,
"end": 28249
} | class ____(loops._Loop):
"""Iterates over all batches in the dataloader (one epoch) that the user returns in their
:meth:`~lightning.pytorch.core.LightningModule.train_dataloader` method.
Its main responsibilities are calling the ``*_epoch_{start,end}`` hooks, accumulating outputs if the user request
them in one of these hooks, and running validation at the requested interval.
The validation is carried out by yet another loop,
:class:`~lightning.pytorch.loops._EvaluationLoop`.
In the ``run()`` method, the training epoch loop could in theory simply call the
``LightningModule.training_step`` already and perform the optimization.
However, Lightning has built-in support for automatic optimization with multiple optimizers.
For this reason there are actually two more loops nested under
:class:`~lightning.pytorch.loops._TrainingEpochLoop`.
Args:
min_steps: The minimum number of steps (batches) to process
max_steps: The maximum number of steps (batches) to process
"""
def __init__(self, trainer: "pl.Trainer", min_steps: Optional[int] = None, max_steps: int = -1) -> None:
super().__init__(trainer)
if max_steps < -1:
raise MisconfigurationException(
f"`max_steps` must be a non-negative integer or -1 (infinite steps). You passed in {max_steps}."
)
self.min_steps = min_steps
self.max_steps = max_steps
self.batch_progress = _BatchProgress()
self.scheduler_progress = _SchedulerProgress()
self.automatic_optimization = _AutomaticOptimization(trainer)
self.manual_optimization = _ManualOptimization(trainer)
self.val_loop = loops._EvaluationLoop(
trainer, TrainerFn.FITTING, RunningStage.VALIDATING, verbose=False, inference_mode=False
)
self._results = _ResultCollection(training=True)
self._warning_cache = WarningCache()
self._batches_that_stepped: int = 0
self._restart_stage = RestartStage.NONE
self._skip_next_val = False
@property
def total_batch_idx(self) -> int:
"""Returns the current batch index (across epochs)"""
# use `ready` instead of `completed` in case this is accessed after `completed` has been increased
# but before the next `ready` increase
return self.batch_progress.total.ready - 1
@property
def batch_idx(self) -> int:
"""Returns the current batch index (within this epoch)"""
# use `ready` instead of `completed` in case this is accessed after `completed` has been increased
# but before the next `ready` increase
return self.batch_progress.current.ready - 1
@property
def global_step(self) -> int:
lightning_module = self.trainer.lightning_module
if lightning_module is None or lightning_module.automatic_optimization:
return self.automatic_optimization.optim_progress.optimizer_steps
return self.manual_optimization.optim_step_progress.total.completed
@property
def _is_training_done(self) -> bool:
max_steps_reached = _is_max_limit_reached(self.global_step, self.max_steps)
return max_steps_reached or self._num_ready_batches_reached()
@property
def _is_validation_done(self) -> bool:
# when we are restarting we want to check whether the val loop has finished
return not self.restarting or self.val_loop._has_run
@property
def done(self) -> bool:
"""Evaluates when to leave the loop."""
if self._is_training_done and self._is_validation_done:
return True
if self.trainer.should_stop:
# early stopping
min_epochs = self.trainer.fit_loop.min_epochs
can_stop_early = self.trainer.fit_loop._can_stop_early
if not can_stop_early:
self._warning_cache.info(
f"Trainer was signaled to stop but the required `min_epochs={min_epochs!r}` or"
f" `min_steps={self.min_steps!r}` has not been met. Training will continue..."
)
return can_stop_early
return False
def run(self, data_fetcher: _DataFetcher) -> None:
self.reset()
self.on_run_start(data_fetcher)
while not self.done:
try:
self.advance(data_fetcher)
self.on_advance_end(data_fetcher)
except StopIteration:
break
finally:
self.on_iteration_done()
@property
def restarted_on_train_batch_end(self) -> bool:
return self._restart_stage == RestartStage.RESTARTED_ON_TRAIN_BATCH_END
@property
def restarted_on_last(self) -> bool:
return self._restart_stage == RestartStage.RESTARTED_ON_LAST
def update_restart_stage(self) -> None:
if (
self.restarting
and self.batch_progress.total.started == self.batch_progress.total.ready
and self.batch_progress.total.processed == self.batch_progress.total.started
and self.batch_progress.total.completed == self.batch_progress.total.processed - 1
):
self._restart_stage = RestartStage.RESTARTED_ON_TRAIN_BATCH_END
elif (
self.restarting
and self.batch_progress.total.started == self.batch_progress.total.ready
and self.batch_progress.total.processed == self.batch_progress.total.started
and self.batch_progress.total.completed == self.batch_progress.total.processed
):
self._restart_stage = RestartStage.RESTARTED_ON_LAST
else:
self._restart_stage = RestartStage.NONE
self.val_loop.update_restart_stage()
def reset_restart_stage(self) -> None:
self._restart_stage = RestartStage.NONE
def reset(self) -> None:
"""Resets the internal state of the loop for a new run."""
if (
self.restarting
and not self._should_accumulate()
and (self.restarted_on_train_batch_end or not self.restarted_on_last)
):
# batches_that_stepped is never set prior to saving a checkpoint, even when saving
# happens on_validation_end
# we could set it in the checkpoint but we prefer to keep checkpoints backward compatible
self._batches_that_stepped += 1
if self.restarted_on_train_batch_end:
self.batch_progress.increment_completed()
# handle situation in which save happened on_train_batch_end and epoch is at end
if self.batch_progress.current.completed >= self.trainer.num_training_batches:
self.batch_progress.reset_on_run()
self.scheduler_progress.reset_on_run()
self.automatic_optimization.optim_progress.reset_on_run()
self.val_loop.batch_progress.total.reset()
if self.restarting:
self.batch_progress.reset_on_restart()
self.scheduler_progress.reset_on_restart()
self.automatic_optimization.optim_progress.reset_on_restart()
trainer = self.trainer
if trainer.num_training_batches != float("inf"):
expected_steps = math.ceil(trainer.num_training_batches / trainer.accumulate_grad_batches)
loader = trainer.fit_loop._combined_loader
assert loader is not None
is_resumable_loader = all(isinstance(loader, _Stateful) for loader in loader.flattened)
if self.global_step % expected_steps != 0 and not is_resumable_loader:
rank_zero_warn(
"You're resuming from a checkpoint that ended before the epoch ended and your dataloader is"
" not resumable. This can cause unreliable results if further training is done."
" Consider using an end-of-epoch checkpoint or make your dataloader resumable by implementing"
" the `state_dict` / `load_state_dict` interface.",
category=PossibleUserWarning,
)
else:
self.batch_progress.reset_on_run()
self.scheduler_progress.reset_on_run()
self.automatic_optimization.optim_progress.reset_on_run()
# when the epoch starts, the total val batch progress should be reset as it's supposed to count the batches
# seen per epoch, this is useful for tracking when validation is run multiple times per epoch
self.val_loop.batch_progress.total.reset()
def on_run_start(self, data_fetcher: _DataFetcher) -> None:
# `iter()` was called once in `FitLoop.setup_data()` already
# Call `iter()` again only when:
# 1. Not restarting
# 2. Not resuming from checkpoint (not is_resuming)
# 3. Past first epoch (current_epoch > 0)
if self.trainer.current_epoch > 0 and not self.trainer.fit_loop.is_resuming and not self.restarting:
iter(data_fetcher) # creates the iterator inside the fetcher
# add the previous `fetched` value to properly track `is_last_batch` with no prefetching
data_fetcher.fetched += self.batch_progress.current.ready
data_fetcher._start_profiler = self._on_before_fetch
data_fetcher._stop_profiler = self._on_after_fetch
def _on_before_fetch(self) -> None:
self.trainer.profiler.start(f"[{self.__class__.__name__}].train_dataloader_next")
def _on_after_fetch(self) -> None:
self.trainer.profiler.stop(f"[{self.__class__.__name__}].train_dataloader_next")
def _broadcast_sigterm_tensor(self) -> None:
try:
sigterm_tensor = torch.tensor(
[1 if getattr(self.trainer, "received_sigterm", False) else 0],
device=self.trainer.strategy.root_device,
)
torch.distributed.broadcast(sigterm_tensor, src=0)
except Exception:
sigterm_tensor = torch.tensor([0], device=self.trainer.strategy.root_device)
if sigterm_tensor.item() == 1:
with contextlib.suppress(Exception):
torch.distributed.barrier() # prevent deadlocks by syncing all ranks before exit
raise SIGTERMException()
def advance(self, data_fetcher: _DataFetcher) -> None:
"""Runs a single training batch.
Raises:
StopIteration: When the epoch is canceled by the user returning -1
"""
if self.restarting and self._should_check_val_fx(data_fetcher):
if self.val_loop.restarted_mid_evaluation:
# Go back and finish running validation
return
if self.restarted_on_last:
# Avoid running validation again if we saved on last
self._skip_next_val = True
return
# fast forward progress counters to end of validation
self.val_loop.increment_progress_to_evaluation_end()
# we are going to train first so the val loop does not need to restart
self.val_loop.restarting = False
# =====================================================================
if torch.distributed.is_available() and torch.distributed.is_initialized() and self.trainer.world_size > 1:
self._broadcast_sigterm_tensor()
# =====================================================================
if using_dataloader_iter := isinstance(data_fetcher, _DataLoaderIterDataFetcher):
dataloader_iter = next(data_fetcher)
# hook's batch_idx and dataloader_idx arguments correctness cannot be guaranteed in this setting
batch = data_fetcher._batch
batch_idx = data_fetcher._batch_idx
else:
dataloader_iter = None
batch, _, __ = next(data_fetcher)
# TODO: we should instead use the batch_idx returned by the fetcher, however, that will require saving the
# fetcher state so that the batch_idx is correct after restarting
batch_idx = self.batch_idx + 1
# Note: `is_last_batch` is not yet determined if data fetcher is a `_DataLoaderIterDataFetcher`
self.batch_progress.is_last_batch = data_fetcher.done
trainer = self.trainer
if not using_dataloader_iter:
batch = trainer.precision_plugin.convert_input(batch)
batch = trainer.lightning_module._on_before_batch_transfer(batch, dataloader_idx=0)
batch = call._call_strategy_hook(trainer, "batch_to_device", batch, dataloader_idx=0)
self.batch_progress.increment_ready()
trainer._logger_connector.on_batch_start(batch)
batch_output: _BATCH_OUTPUTS_TYPE = None # for mypy
should_skip_rest_of_epoch = False
if batch is None and not using_dataloader_iter:
self._warning_cache.warn("train_dataloader yielded None. If this was on purpose, ignore this warning...")
else:
# hook
call._call_callback_hooks(trainer, "on_train_batch_start", batch, batch_idx)
response = call._call_lightning_module_hook(trainer, "on_train_batch_start", batch, batch_idx)
call._call_strategy_hook(trainer, "on_train_batch_start", batch, batch_idx)
should_skip_rest_of_epoch = response == -1
# Signal this is the last batch for the current epoch
if should_skip_rest_of_epoch:
self.batch_progress.increment_by(0, is_last_batch=True)
else:
self.batch_progress.increment_started()
kwargs = (
self._build_kwargs(OrderedDict(), batch, batch_idx)
if not using_dataloader_iter
else OrderedDict(any=dataloader_iter)
)
with trainer.profiler.profile("run_training_batch"):
if trainer.lightning_module.automatic_optimization:
# in automatic optimization, there can only be one optimizer
batch_output = self.automatic_optimization.run(trainer.optimizers[0], batch_idx, kwargs)
else:
batch_output = self.manual_optimization.run(kwargs)
self.batch_progress.increment_processed()
# update non-plateau LR schedulers
# update epoch-interval ones only when we are at the end of training epoch
self.update_lr_schedulers("step", update_plateau_schedulers=False)
if self._num_ready_batches_reached():
self.update_lr_schedulers("epoch", update_plateau_schedulers=False)
if should_skip_rest_of_epoch:
# Only raise StopIteration now so that the training epoch loop can finish
raise StopIteration
if using_dataloader_iter:
# update the hook kwargs now that the step method might have consumed the iterator
batch = data_fetcher._batch
batch_idx = data_fetcher._batch_idx
# update `is_last_batch` again after dataloader_iter was fetched in `training_step()`
self.batch_progress.is_last_batch = data_fetcher.done
call._call_callback_hooks(trainer, "on_train_batch_end", batch_output, batch, batch_idx)
call._call_lightning_module_hook(trainer, "on_train_batch_end", batch_output, batch, batch_idx)
trainer._logger_connector.on_batch_end()
self.batch_progress.increment_completed()
# -----------------------------------------
# SAVE METRICS TO LOGGERS AND PROGRESS_BAR
# -----------------------------------------
trainer._logger_connector.update_train_step_metrics()
def on_advance_end(self, data_fetcher: _DataFetcher) -> None:
# -----------------------------------------
# VALIDATE IF NEEDED
# -----------------------------------------
should_check_val = self._should_check_val_fx(data_fetcher)
if self._skip_next_val:
should_check_val = False
self._skip_next_val = False
if should_check_val:
# this needs to be set so the correct `trainer._active_loop` is picked
self.trainer.validating = True
# save and reset this state in case validation runs inside training loop (val_check_interval<1.0)
first_loop_iter = self.trainer._logger_connector._first_loop_iter
if not self._should_accumulate():
# clear gradients to not leave any unused memory during validation
call._call_lightning_module_hook(self.trainer, "on_validation_model_zero_grad")
self.val_loop.run()
self.trainer.training = True
self.trainer._logger_connector._first_loop_iter = first_loop_iter
# update plateau LR scheduler after metrics are logged
self.update_lr_schedulers("step", update_plateau_schedulers=True)
if not self._should_accumulate():
# this is increased once per batch disregarding multiple optimizers on purpose for loggers
self._batches_that_stepped += 1
# this will save based on the `batches_that_stepped` value
self._save_loggers_on_train_batch_end()
# if training finished, defer exit to the parent. this assumes there will be enough time in between
# which might not be the case depending on what's in the `*_epoch_end` hooks
if not self._is_training_done and self.trainer.received_sigterm:
raise SIGTERMException
def teardown(self) -> None:
self._results.cpu()
self.val_loop.teardown()
@override
def on_save_checkpoint(self) -> dict:
state_dict = super().on_save_checkpoint()
state_dict["_batches_that_stepped"] = self._batches_that_stepped
return state_dict
@override
def on_load_checkpoint(self, state_dict: dict) -> None:
self._batches_that_stepped = state_dict.get("_batches_that_stepped", 0)
def _accumulated_batches_reached(self) -> bool:
"""Determine if accumulation will be finished by the end of the current batch."""
return self.batch_progress.current.ready % self.trainer.accumulate_grad_batches == 0
def _num_ready_batches_reached(self) -> bool:
"""Checks if we are in the last batch or if there are more batches to follow."""
epoch_finished_on_ready = self.batch_progress.current.ready == self.trainer.num_training_batches
return epoch_finished_on_ready or self.batch_progress.is_last_batch
def _should_accumulate(self) -> bool:
"""Checks if the optimizer step should be performed or gradients should be accumulated for the current step."""
accumulation_done = self._accumulated_batches_reached()
# Lightning steps on the final batch
is_final_batch = self._num_ready_batches_reached()
# but the strategy might not
strategy_accumulates_on_final_batch = self.trainer.strategy.handles_gradient_accumulation or not is_final_batch
return not accumulation_done and strategy_accumulates_on_final_batch
def update_lr_schedulers(self, interval: str, update_plateau_schedulers: bool) -> None:
"""Updates the lr schedulers based on the given interval."""
if interval == "step" and self._should_accumulate():
return
self._update_learning_rates(interval=interval, update_plateau_schedulers=update_plateau_schedulers)
def _update_learning_rates(self, interval: str, update_plateau_schedulers: bool) -> None:
"""Update learning rates.
Args:
interval: either 'epoch' or 'step'.
update_plateau_schedulers: control whether ``ReduceLROnPlateau`` or non-plateau schedulers get updated.
This is used so non-plateau schedulers can be updated before running validation. Checkpoints are
commonly saved during validation, however, on-plateau schedulers might monitor a validation metric
so they have to be updated separately.
"""
trainer = self.trainer
if not trainer.lr_scheduler_configs or not trainer.lightning_module.automatic_optimization:
return
for config in trainer.lr_scheduler_configs:
if update_plateau_schedulers ^ config.reduce_on_plateau:
continue
current_idx = self.batch_idx if interval == "step" else trainer.current_epoch
current_idx += 1 # account for both batch and epoch starts from 0
# Take step if call to update_learning_rates matches the interval key and
# the current step modulo the schedulers frequency is zero
if config.interval == interval and current_idx % config.frequency == 0:
monitor_val = None
if config.reduce_on_plateau:
monitor_key = config.monitor
assert monitor_key is not None
monitor_val = self._get_monitor_value(monitor_key)
if monitor_val is None:
if config.strict:
avail_metrics = list(trainer.callback_metrics)
raise MisconfigurationException(
f"ReduceLROnPlateau conditioned on metric {monitor_key}"
f" which is not available. Available metrics are: {avail_metrics}."
" Condition can be set using `monitor` key in lr scheduler dict"
)
rank_zero_warn(
f"ReduceLROnPlateau conditioned on metric {monitor_key}"
" which is not available but strict is set to `False`."
" Skipping learning rate update.",
category=RuntimeWarning,
)
continue
self.scheduler_progress.increment_ready()
# update LR
call._call_lightning_module_hook(
trainer,
"lr_scheduler_step",
config.scheduler,
monitor_val,
)
self.scheduler_progress.increment_completed()
def _get_monitor_value(self, key: str) -> Optional[Any]:
# this is a separate method to aid in testing
return self.trainer.callback_metrics.get(key)
def _should_check_val_epoch(self) -> bool:
return self.trainer.enable_validation and (
self.trainer.check_val_every_n_epoch is None
or (self.trainer.current_epoch + 1) % self.trainer.check_val_every_n_epoch == 0
)
def _should_check_val_fx(self, data_fetcher: _DataFetcher) -> bool:
"""Decide if we should run validation."""
if not self._should_check_val_epoch():
return False
# val_check_batch is inf for iterable datasets with no length defined
is_infinite_dataset = self.trainer.val_check_batch == float("inf")
is_last_batch = self.batch_progress.is_last_batch
if is_last_batch and (is_infinite_dataset or isinstance(data_fetcher, _DataLoaderIterDataFetcher)):
return True
if self.trainer.should_stop and self.trainer.fit_loop._can_stop_early:
# allow validation if requesting to stop early through `Trainer.should_stop` (e.g. by early stopping)
# and when the loop allows to stop (min_epochs/steps met)
return True
interval = self.trainer._val_check_time_interval
if interval is not None:
now = time.monotonic()
# if time’s up → tell Trainer to validate
return now - self.trainer._last_val_time >= interval
# TODO: let training/eval loop handle logic around limit_*_batches and val_check_batch
is_val_check_batch = is_last_batch
if isinstance(self.trainer.limit_train_batches, int) and is_infinite_dataset:
is_val_check_batch = (self.batch_idx + 1) % self.trainer.limit_train_batches == 0
elif self.trainer.val_check_batch != float("inf"):
# if we got here, we’re in batch-based mode, so this can’t be None
assert self.trainer.val_check_batch is not None
# if `check_val_every_n_epoch is `None`, run a validation loop every n training batches
# else condition it based on the batch_idx of the current epoch
current_iteration = self.total_batch_idx if self.trainer.check_val_every_n_epoch is None else self.batch_idx
is_val_check_batch = (current_iteration + 1) % self.trainer.val_check_batch == 0
return is_val_check_batch
def _save_loggers_on_train_batch_end(self) -> None:
"""Flushes loggers to disk."""
if self.trainer.should_stop:
for logger in self.trainer.loggers:
logger.save()
def _build_kwargs(self, kwargs: OrderedDict, batch: Any, batch_idx: int) -> OrderedDict:
"""Helper method to build the arguments for the current step.
Args:
kwargs: The kwargs passed down to the hooks.
batch: The current batch to run through the step.
batch_idx: the index of the current batch.
Returns:
The kwargs passed down to the hooks.
"""
kwargs["batch"] = batch
training_step_fx = getattr(self.trainer.lightning_module, "training_step")
# the `batch_idx` is optional, but its name can be anything
# as long as there are two arguments after 'self', we assume they are the `batch` and `batch_idx`
if is_param_in_hook_signature(training_step_fx, "batch_idx", min_args=2):
kwargs["batch_idx"] = batch_idx
return kwargs
| _TrainingEpochLoop |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py | {
"start": 5925,
"end": 6299
} | class ____:
"""Page lengths to use when testing pagination."""
SMALL: int = 3
LARGE: int = 10
FARGATE_PROFILE_UUID_PATTERN: str = (
r"(?P<fargate_uuid>[-0-9a-z]{8}-[-0-9a-z]{4}-[-0-9a-z]{4}-[-0-9a-z]{4}-[-0-9a-z]{12})"
)
NODEGROUP_UUID_PATTERN: str = (
r"(?P<nodegroup_uuid>[-0-9a-z]{8}-[-0-9a-z]{4}-[-0-9a-z]{4}-[-0-9a-z]{4}-[-0-9a-z]{12})"
)
| PageCount |
python | pytorch__pytorch | test/test_ops_fwd_gradients.py | {
"start": 964,
"end": 4074
} | class ____(TestGradients):
# Test that forward-over-reverse gradgrad is computed correctly
@_gradcheck_ops(op_db)
def test_fn_fwgrad_bwgrad(self, device, dtype, op):
self._skip_helper(op, device, dtype)
if op.supports_fwgrad_bwgrad:
self._check_helper(device, dtype, op, op.get_op(), "fwgrad_bwgrad")
else:
err_msg = r"Trying to use forward AD with .* that does not support it"
hint_msg = (
"Running forward-over-backward gradgrad for an OP that has does not support it did not "
"raise any error. If your op supports forward AD, you should set supports_fwgrad_bwgrad=True."
)
with self.assertRaisesRegex(NotImplementedError, err_msg, msg=hint_msg):
self._check_helper(device, dtype, op, op.get_op(), "fwgrad_bwgrad")
def _forward_grad_helper(self, device, dtype, op, variant, is_inplace):
# TODO: clean up how attributes are passed to gradcheck from OpInfos
def call_grad_test_helper():
check_batched_forward_grad = (
op.check_batched_forward_grad and not is_inplace
) or (op.check_inplace_batched_forward_grad and is_inplace)
self._grad_test_helper(
device,
dtype,
op,
variant,
check_forward_ad=True,
check_backward_ad=False,
check_batched_grad=False,
check_batched_forward_grad=check_batched_forward_grad,
)
if op.supports_forward_ad:
call_grad_test_helper()
else:
err_msg = r"Trying to use forward AD with .* that does not support it"
hint_msg = (
"Running forward AD for an OP that has does not support it did not "
"raise any error. If your op supports forward AD, you should set supports_forward_ad=True"
)
with self.assertRaisesRegex(NotImplementedError, err_msg, msg=hint_msg):
call_grad_test_helper()
@_gradcheck_ops(op_db)
@skipif(
platform.machine() == "s390x",
reason="Different precision of openblas functions: https://github.com/OpenMathLib/OpenBLAS/issues/4194",
)
def test_forward_mode_AD(self, device, dtype, op):
self._skip_helper(op, device, dtype)
self._forward_grad_helper(device, dtype, op, op.get_op(), is_inplace=False)
@_gradcheck_ops(op_db)
@skipIfTorchInductor("to be fixed")
def test_inplace_forward_mode_AD(self, device, dtype, op):
self._skip_helper(op, device, dtype)
if not op.inplace_variant or not op.supports_inplace_autograd:
self.skipTest("Skipped! Operation does not support inplace autograd.")
self._forward_grad_helper(
device, dtype, op, self._get_safe_inplace(op.get_inplace()), is_inplace=True
)
instantiate_device_type_tests(TestFwdGradients, globals())
if __name__ == "__main__":
TestCase._default_dtype_check_enabled = True
run_tests()
| TestFwdGradients |
python | django__django | tests/m2m_signals/models.py | {
"start": 393,
"end": 451
} | class ____(Car):
price = models.IntegerField()
| SportsCar |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_low_rank_update_test.py | {
"start": 9100,
"end": 9917
} | class ____(
BaseLinearOperatorLowRankUpdatetest,
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""A = L + UU^H, L > 0 ==> A > 0 and we can use a Cholesky."""
_use_diag_update = False
_is_diag_update_positive = None
_use_v = False
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enabled()
config.enable_tensor_float_32_execution(False)
# Decrease tolerance since we are testing with condition numbers as high as
# 1e4.
self._atol[dtypes.float32] = 1e-5
self._rtol[dtypes.float32] = 1e-5
self._atol[dtypes.float64] = 1e-10
self._rtol[dtypes.float64] = 1e-10
self._rtol[dtypes.complex64] = 1e-4
| LinearOperatorLowRankUpdatetestNoDiagUseCholesky |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/run_config_schema.py | {
"start": 285,
"end": 1521
} | class ____(NamedTuple):
run_config_schema_type: ConfigType
config_type_dict_by_name: Mapping[str, ConfigType]
config_type_dict_by_key: Mapping[str, ConfigType]
config_mapping: Optional[ConfigMapping]
def has_config_type(self, name: str) -> bool:
check.str_param(name, "name")
return name in self.config_type_dict_by_name
def config_type_named(self, name: str) -> ConfigType:
check.str_param(name, "name")
return self.config_type_dict_by_name[name]
def config_type_keyed(self, key: str) -> ConfigType:
check.str_param(key, "key")
return self.config_type_dict_by_key[key]
def all_config_types(self) -> Iterable[ConfigType]:
return self.config_type_dict_by_key.values()
@property
def config_type(self) -> ConfigType:
if self.config_mapping:
mapped_type = self.config_mapping.config_schema.config_type
if mapped_type is None:
check.failed("ConfigMapping config type unexpectedly None")
return mapped_type
return self.run_config_schema_type
def create_run_config_schema(
job_def: JobDefinition,
) -> RunConfigSchema:
return job_def.run_config_schema
| RunConfigSchema |
python | huggingface__transformers | src/transformers/models/evolla/modular_evolla.py | {
"start": 5924,
"end": 5970
} | class ____(EsmLayer):
pass
| EvollaSaProtLayer |
python | PyCQA__pydocstyle | src/pydocstyle/parser.py | {
"start": 8905,
"end": 9306
} | class ____(str):
"""Represent a docstring.
This is a string, but has additional start/end attributes representing
the start and end of the token.
"""
def __new__(cls, v, start, end):
return str.__new__(cls, v)
def __init__(self, v, start, end):
self.start = start
self.end = end
VARIADIC_MAGIC_METHODS = ('__init__', '__call__', '__new__')
| Docstring |
python | numba__numba | numba/tests/doc_examples/test_interval_example.py | {
"start": 186,
"end": 8867
} | class ____(unittest.TestCase):
def test_interval_class_usage(self):
# magictoken.interval_py_class.begin
class Interval(object):
"""
A half-open interval on the real number line.
"""
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
def __repr__(self):
return 'Interval(%f, %f)' % (self.lo, self.hi)
@property
def width(self):
return self.hi - self.lo
# magictoken.interval_py_class.end
# magictoken.interval_type_class.begin
from numba import types
class IntervalType(types.Type):
def __init__(self):
super(IntervalType, self).__init__(name='Interval')
interval_type = IntervalType()
# magictoken.interval_type_class.end
# magictoken.interval_typeof_register.begin
from numba.extending import typeof_impl
@typeof_impl.register(Interval)
def typeof_index(val, c):
return interval_type
# magictoken.interval_typeof_register.end
# magictoken.numba_type_register.begin
from numba.extending import as_numba_type
as_numba_type.register(Interval, interval_type)
# magictoken.numba_type_register.end
# magictoken.numba_type_callable.begin
from numba.extending import type_callable
@type_callable(Interval)
def type_interval(context):
def typer(lo, hi):
if isinstance(lo, types.Float) and isinstance(hi, types.Float):
return interval_type
return typer
# magictoken.numba_type_callable.end
# magictoken.interval_model.begin
from numba.extending import models, register_model
@register_model(IntervalType)
class IntervalModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [('lo', types.float64),
('hi', types.float64),]
models.StructModel.__init__(self, dmm, fe_type, members)
# magictoken.interval_model.end
# magictoken.interval_attribute_wrapper.begin
from numba.extending import make_attribute_wrapper
make_attribute_wrapper(IntervalType, 'lo', 'lo')
make_attribute_wrapper(IntervalType, 'hi', 'hi')
# magictoken.interval_attribute_wrapper.end
# magictoken.interval_overload_attribute.begin
from numba.extending import overload_attribute
@overload_attribute(IntervalType, "width")
def get_width(interval):
def getter(interval):
return interval.hi - interval.lo
return getter
# magictoken.interval_overload_attribute.end
# magictoken.interval_lower_builtin.begin
from numba.extending import lower_builtin
from numba.core import cgutils
@lower_builtin(Interval, types.Float, types.Float)
def impl_interval(context, builder, sig, args):
typ = sig.return_type
lo, hi = args
interval = cgutils.create_struct_proxy(typ)(context, builder)
interval.lo = lo
interval.hi = hi
return interval._getvalue()
# magictoken.interval_lower_builtin.end
# magictoken.interval_unbox.begin
from numba.extending import unbox, NativeValue
from contextlib import ExitStack
@unbox(IntervalType)
def unbox_interval(typ, obj, c):
"""
Convert a Interval object to a native interval structure.
"""
is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
interval = cgutils.create_struct_proxy(typ)(c.context, c.builder)
with ExitStack() as stack:
lo_obj = c.pyapi.object_getattr_string(obj, "lo")
with cgutils.early_exit_if_null(c.builder, stack, lo_obj):
c.builder.store(cgutils.true_bit, is_error_ptr)
lo_native = c.unbox(types.float64, lo_obj)
c.pyapi.decref(lo_obj)
with cgutils.early_exit_if(c.builder, stack, lo_native.is_error):
c.builder.store(cgutils.true_bit, is_error_ptr)
hi_obj = c.pyapi.object_getattr_string(obj, "hi")
with cgutils.early_exit_if_null(c.builder, stack, hi_obj):
c.builder.store(cgutils.true_bit, is_error_ptr)
hi_native = c.unbox(types.float64, hi_obj)
c.pyapi.decref(hi_obj)
with cgutils.early_exit_if(c.builder, stack, hi_native.is_error):
c.builder.store(cgutils.true_bit, is_error_ptr)
interval.lo = lo_native.value
interval.hi = hi_native.value
return NativeValue(interval._getvalue(), is_error=c.builder.load(is_error_ptr))
# magictoken.interval_unbox.end
# magictoken.interval_box.begin
from numba.extending import box
@box(IntervalType)
def box_interval(typ, val, c):
"""
Convert a native interval structure to an Interval object.
"""
ret_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj)
fail_obj = c.pyapi.get_null_object()
with ExitStack() as stack:
interval = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
lo_obj = c.box(types.float64, interval.lo)
with cgutils.early_exit_if_null(c.builder, stack, lo_obj):
c.builder.store(fail_obj, ret_ptr)
hi_obj = c.box(types.float64, interval.hi)
with cgutils.early_exit_if_null(c.builder, stack, hi_obj):
c.pyapi.decref(lo_obj)
c.builder.store(fail_obj, ret_ptr)
class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Interval))
with cgutils.early_exit_if_null(c.builder, stack, class_obj):
c.pyapi.decref(lo_obj)
c.pyapi.decref(hi_obj)
c.builder.store(fail_obj, ret_ptr)
# NOTE: The result of this call is not checked as the clean up
# has to occur regardless of whether it is successful. If it
# fails `res` is set to NULL and a Python exception is set.
res = c.pyapi.call_function_objargs(class_obj, (lo_obj, hi_obj))
c.pyapi.decref(lo_obj)
c.pyapi.decref(hi_obj)
c.pyapi.decref(class_obj)
c.builder.store(res, ret_ptr)
return c.builder.load(ret_ptr)
# magictoken.interval_box.end
# magictoken.interval_usage.begin
from numba import njit
@njit
def inside_interval(interval, x):
return interval.lo <= x < interval.hi
@njit
def interval_width(interval):
return interval.width
@njit
def sum_intervals(i, j):
return Interval(i.lo + j.lo, i.hi + j.hi)
# magictoken.interval_usage.end
def check_equal_intervals(x, y):
self.assertIsInstance(x, Interval)
self.assertIsInstance(y, Interval)
self.assertEqual(x.lo, y.lo)
self.assertEqual(x.hi, y.hi)
a = Interval(2, 3)
b = Interval(4, 5)
c = Interval(6, 8)
# Test box-unbox
return_func = njit(lambda x: x)
check_equal_intervals(a, return_func(a))
# Test .width attribute
self.assertEqual(a.width, interval_width(a))
# Test exceptions
class NotAFloat:
def __float__(self):
raise RuntimeError("I am not a float")
# TODO: This should produce a `RuntimeError`, but the `unbox` handler for `float` ignores
# the error raised by `__float__`, leading to a subsequent `TypeError` cause by passing
# `NULL` to `PyFloat_AsDouble`.
# This isn't the fault of the `Interval` extension that is being testing
# in this file.
with self.assertRaises(TypeError):
interval_width(Interval(2, NotAFloat()))
bad_interval = Interval(1, 2)
del bad_interval.hi
with self.assertRaises(AttributeError):
interval_width(bad_interval)
# Test .lo and .hi usage
self.assertFalse(inside_interval(a, 5))
# Test native Interval constructor
check_equal_intervals(c, sum_intervals(a, b))
if __name__ == '__main__':
unittest.main()
| IntervalExampleTest |
python | kamyu104__LeetCode-Solutions | Python/count-numbers-with-unique-digits-ii.py | {
"start": 1216,
"end": 2184
} | class ____(object):
def numberCount(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
fact = [1]*2
def nPr(n, k):
while len(fact) <= n: # lazy initialization
fact.append(fact[-1]*len(fact))
return fact[n]//fact[n-k]
def popcount(x):
return bin(x).count('1')
def count(x):
digits = map(int, str(x))
result = 9*sum(nPr(9, i) for i in xrange(len(digits)-1))
lookup = 0
for i, d in enumerate(digits):
mask = lookup&(((1<<d)-1)-int(i == 0))
result += ((d-int(i == 0))-popcount(mask))*nPr(10-(i+1), len(digits)-(i+1))
if lookup&(1<<d):
break
lookup |= 1<<d
return result
return count(b+1)-count(a)
# Time: O(blogb)
# Space: O(1)
# brute force, hash table, bitmasks
| Solution2 |
python | allegroai__clearml | clearml/binding/frameworks/pytorch_bind.py | {
"start": 431,
"end": 13200
} | class ____(PatchBaseModelIO):
_current_task = None
_checkpoint_filename = {}
__patched = None
__patched_lightning = None
__patched_pytorch_lightning = None
__patched_mmcv = None
@staticmethod
def update_current_task(task: Any, **_: Any) -> None:
PatchPyTorchModelIO._current_task = task
if not task:
return
PatchPyTorchModelIO._patch_model_io()
PatchPyTorchModelIO._patch_lightning_io()
PatchPyTorchModelIO._patch_pytorch_lightning_io()
PatchPyTorchModelIO._patch_mmcv()
PostImportHookPatching.add_on_import("torch", PatchPyTorchModelIO._patch_model_io)
PostImportHookPatching.add_on_import("lightning", PatchPyTorchModelIO._patch_lightning_io)
PostImportHookPatching.add_on_import("pytorch_lightning", PatchPyTorchModelIO._patch_pytorch_lightning_io)
@staticmethod
def _patch_model_io() -> None:
if PatchPyTorchModelIO.__patched:
return
if "torch" not in sys.modules:
return
PatchPyTorchModelIO.__patched = True
# noinspection PyBroadException
try:
import torch # noqa
torch.save = _patched_call(torch.save, PatchPyTorchModelIO._save)
torch.load = _patched_call(torch.load, PatchPyTorchModelIO._load)
# noinspection PyBroadException
try:
# noinspection PyProtectedMember
torch.jit._script.RecursiveScriptModule.save = _patched_call(
torch.jit._script.RecursiveScriptModule.save,
PatchPyTorchModelIO._save,
)
except BaseException:
pass
# no need to worry about recursive calls, _patched_call takes care of that
if hasattr(torch, "serialization") and hasattr(torch.serialization, "_save"):
torch.serialization._save = _patched_call(torch.serialization._save, PatchPyTorchModelIO._save) # noqa
if hasattr(torch, "serialization") and hasattr(torch.serialization, "_load"):
torch.serialization._load = _patched_call(torch.serialization._load, PatchPyTorchModelIO._load) # noqa
if hasattr(torch, "serialization") and hasattr(torch.serialization, "_legacy_save"):
torch.serialization._legacy_save = _patched_call(
torch.serialization._legacy_save, PatchPyTorchModelIO._save
) # noqa
if hasattr(torch, "serialization") and hasattr(torch.serialization, "_legacy_load"):
torch.serialization._legacy_load = _patched_call(
torch.serialization._legacy_load, PatchPyTorchModelIO._load
) # noqa
except ImportError:
pass
except Exception:
pass # print('Failed patching pytorch')
@staticmethod
def _patch_mmcv() -> None:
if PatchPyTorchModelIO.__patched_mmcv:
return
if "mmcv" not in sys.modules:
return
PatchPyTorchModelIO.__patched_mmcv = True
# noinspection PyBroadException
try:
from mmcv.runner import epoch_based_runner, iter_based_runner
# we don't want the recursion check here because it guards pytorch's patched save functions
# which we need in order to log the saved model/checkpoint
epoch_based_runner.save_checkpoint = _patched_call_no_recursion_guard(
epoch_based_runner.save_checkpoint,
PatchPyTorchModelIO._mmcv_save_checkpoint,
)
iter_based_runner.save_checkpoint = _patched_call_no_recursion_guard(
iter_based_runner.save_checkpoint,
PatchPyTorchModelIO._mmcv_save_checkpoint,
)
except Exception:
pass
@staticmethod
def _mmcv_save_checkpoint(original_fn: Callable, model: Any, filename: str, *args: Any, **kwargs: Any) -> Any:
# note that mmcv.runner.save_checkpoint doesn't return anything, hence the need for this
# patch function, but we return from it just in case this changes in the future
if not PatchPyTorchModelIO._current_task:
return original_fn(model, filename, *args, **kwargs)
tid = threading.current_thread().ident
PatchPyTorchModelIO._checkpoint_filename[tid] = filename
ret = original_fn(model, filename, *args, **kwargs)
del PatchPyTorchModelIO._checkpoint_filename[tid]
return ret
@staticmethod
def _patch_lightning_io_internal(lightning_name: str) -> None:
"""
:param lightning_name: lightning module name, use "lightning" or "pytorch_lightning"
"""
try:
pytorch_lightning = importlib.import_module(lightning_name)
except ImportError:
# lightning is not installed
# Nothing to do
return
if lightning_name == "lightning":
pytorch_lightning = pytorch_lightning.pytorch
def patch_method(cls, method_name: str, patched_method: Callable) -> None:
"""
Patch a method of a class if it exists.
Otherwise, no effect.
"""
try:
method = getattr(cls, method_name)
except AttributeError:
# the method is not defined on the given class
pass
else:
setattr(cls, method_name, _patched_call(method, patched_method))
patch_method(
pytorch_lightning.trainer.Trainer,
"save_checkpoint",
PatchPyTorchModelIO._save,
)
patch_method(
pytorch_lightning.trainer.Trainer,
"restore",
PatchPyTorchModelIO._load_from_obj,
)
try:
checkpoint_connector = pytorch_lightning.trainer.connectors.checkpoint_connector
except AttributeError:
# checkpoint_connector does not yet exist; lightning version is < 0.10.0
# Nothing left to do
return
try:
CheckpointConnector = checkpoint_connector._CheckpointConnector
except AttributeError:
# CheckpointConnector has not yet been made protected
# lighting version is < 2.0.0
try:
CheckpointConnector = checkpoint_connector.CheckpointConnector
except AttributeError:
# Unexpected future breaking change in lightning
# No way to automatically handle
return
patch_method(CheckpointConnector, "save_checkpoint", PatchPyTorchModelIO._save)
patch_method(CheckpointConnector, "restore", PatchPyTorchModelIO._load_from_obj)
@staticmethod
def _patch_lightning_io() -> None:
if PatchPyTorchModelIO.__patched_lightning:
return
if "lightning" not in sys.modules:
return
PatchPyTorchModelIO.__patched_lightning = True
PatchPyTorchModelIO._patch_lightning_io_internal("lightning")
@staticmethod
def _patch_pytorch_lightning_io() -> None:
if PatchPyTorchModelIO.__patched_pytorch_lightning:
return
if "pytorch_lightning" not in sys.modules:
return
PatchPyTorchModelIO.__patched_pytorch_lightning = True
PatchPyTorchModelIO._patch_lightning_io_internal("pytorch_lightning")
@staticmethod
def _save(original_fn: Callable, obj: Any, f: Any, *args: Any, **kwargs: Any) -> Any:
ret = original_fn(obj, f, *args, **kwargs)
# if there is no main task or this is a nested call
if not PatchPyTorchModelIO._current_task:
return ret
# pytorch-lightning check if rank is zero
if hasattr(obj, "is_global_zero"):
if not obj.is_global_zero:
return ret
elif hasattr(obj, "trainer") and hasattr(obj.trainer, "is_global_zero"):
if not obj.trainer.is_global_zero:
return ret
# noinspection PyBroadException
try:
if isinstance(f, six.string_types):
filename = f
elif hasattr(f, "as_posix"):
filename = f.as_posix()
elif hasattr(f, "name"):
# noinspection PyBroadException
try:
f.flush()
except Exception:
pass
if not isinstance(f.name, six.string_types):
# Probably a BufferedRandom object that has no meaningful name (still no harm flushing)
return ret
filename = f.name
else:
filename = PatchPyTorchModelIO.__get_cached_checkpoint_filename()
except Exception:
filename = PatchPyTorchModelIO.__get_cached_checkpoint_filename()
# give the model a descriptive name based on the file name
# noinspection PyBroadException
try:
model_name = Path(filename).stem if filename is not None else None
except Exception:
model_name = None
WeightsFileHandler.create_output_model(
obj,
filename,
Framework.pytorch,
PatchPyTorchModelIO._current_task,
singlefile=True,
model_name=model_name,
)
return ret
@staticmethod
def _load(original_fn: Callable, f: Any, *args: Any, **kwargs: Any) -> Any:
# if there is no main task or this is a nested call
if not PatchPyTorchModelIO._current_task:
return original_fn(f, *args, **kwargs)
# noinspection PyBroadException
try:
if isinstance(f, six.string_types):
filename = f
elif hasattr(f, "as_posix"):
filename = f.as_posix()
elif hasattr(f, "name"):
filename = f.name
else:
filename = None
except Exception:
filename = None
# register input model
empty = _Empty()
# Hack: disabled
if False and running_remotely():
filename = WeightsFileHandler.restore_weights_file(
empty, filename, Framework.pytorch, PatchPyTorchModelIO._current_task
)
model = original_fn(filename or f, *args, **kwargs)
else:
# try to load model before registering, in case we fail
model = original_fn(f, *args, **kwargs)
WeightsFileHandler.restore_weights_file(
empty, filename, Framework.pytorch, PatchPyTorchModelIO._current_task
)
if empty.trains_in_model:
# noinspection PyBroadException
try:
model.trains_in_model = empty.trains_in_model
except Exception:
pass
return model
@staticmethod
def _load_from_obj(original_fn: Callable, obj: Any, f: Any, *args: Any, **kwargs: Any) -> Any:
# if there is no main task or this is a nested call
if not PatchPyTorchModelIO._current_task:
return original_fn(obj, f, *args, **kwargs)
# noinspection PyBroadException
try:
if isinstance(f, six.string_types):
filename = f
elif hasattr(f, "as_posix"):
filename = f.as_posix()
elif hasattr(f, "name"):
filename = f.name
else:
filename = None
except Exception:
filename = None
# register input model
empty = _Empty()
# Hack: disabled
if False and running_remotely():
filename = WeightsFileHandler.restore_weights_file(
empty, filename, Framework.pytorch, PatchPyTorchModelIO._current_task
)
model = original_fn(obj, filename or f, *args, **kwargs)
else:
# try to load model before registering, in case we fail
model = original_fn(obj, f, *args, **kwargs)
WeightsFileHandler.restore_weights_file(
empty, filename, Framework.pytorch, PatchPyTorchModelIO._current_task
)
if empty.trains_in_model:
# noinspection PyBroadException
try:
model.trains_in_model = empty.trains_in_model
except Exception:
pass
return model
@staticmethod
def __get_cached_checkpoint_filename() -> Optional[str]:
tid = threading.current_thread().ident
checkpoint_filename = PatchPyTorchModelIO._checkpoint_filename.get(tid)
return checkpoint_filename or None
| PatchPyTorchModelIO |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 11370,
"end": 11572
} | class ____(ModelActivityMixin, JSONActivityFeed):
"""
JSON feed of Activity for a given model (where actions involve the given model as any of the entities).
"""
pass
| ModelJSONActivityFeed |
python | rq__rq | tests/test_retry.py | {
"start": 384,
"end": 6168
} | class ____(RQTestCase):
"""Tests from test_retry.py"""
def test_persistence_of_retry_data(self):
"""Retry related data is stored and restored properly"""
job = Job.create(func=say_hello, connection=self.connection)
job.retries_left = 3
job.retry_intervals = [1, 2, 3]
job.save()
job.retries_left = None
job.retry_intervals = None
job.refresh()
self.assertEqual(job.retries_left, 3)
self.assertEqual(job.retry_intervals, [1, 2, 3])
def test_retry_class(self):
"""Retry parses `max` and `interval` correctly"""
retry = Retry(max=1)
self.assertEqual(retry.max, 1)
self.assertEqual(retry.intervals, [0])
self.assertRaises(ValueError, Retry, max=0)
retry = Retry(max=2, interval=5)
self.assertEqual(retry.max, 2)
self.assertEqual(retry.intervals, [5])
retry = Retry(max=3, interval=[5, 10])
self.assertEqual(retry.max, 3)
self.assertEqual(retry.intervals, [5, 10])
# interval can't be negative
self.assertRaises(ValueError, Retry, max=1, interval=-5)
self.assertRaises(ValueError, Retry, max=1, interval=[1, -5])
def test_get_retry_interval(self):
"""get_retry_interval() returns the right retry interval"""
job = Job.create(func=say_hello, connection=self.connection)
# Handle case where self.retry_intervals is None
job.retries_left = 2
self.assertEqual(job.get_retry_interval(), 0)
# Handle the most common case
job.retry_intervals = [1, 2]
self.assertEqual(job.get_retry_interval(), 1)
job.retries_left = 1
self.assertEqual(job.get_retry_interval(), 2)
# Handle cases where number of retries > length of interval
job.retries_left = 4
job.retry_intervals = [1, 2, 3]
self.assertEqual(job.get_retry_interval(), 1)
job.retries_left = 3
self.assertEqual(job.get_retry_interval(), 1)
job.retries_left = 2
self.assertEqual(job.get_retry_interval(), 2)
job.retries_left = 1
self.assertEqual(job.get_retry_interval(), 3)
def test_job_retry(self):
"""job.retry() works properly"""
queue = Queue(connection=self.connection)
retry = Retry(max=3, interval=5)
job = queue.enqueue(div_by_zero, retry=retry)
with self.connection.pipeline() as pipeline:
job.retry(queue, pipeline)
pipeline.execute()
self.assertEqual(job.retries_left, 2)
# status should be scheduled since it's retried with 5 seconds interval
self.assertEqual(job.get_status(), JobStatus.SCHEDULED)
retry = Retry(max=3)
job = queue.enqueue(div_by_zero, retry=retry)
with self.connection.pipeline() as pipeline:
job.retry(queue, pipeline)
pipeline.execute()
self.assertEqual(job.retries_left, 2)
# status should be queued
self.assertEqual(job.get_status(), JobStatus.QUEUED)
def test_retry_interval(self):
"""Retries with intervals are scheduled"""
connection = self.connection
queue = Queue(connection=connection)
retry = Retry(max=1, interval=5)
job = queue.enqueue(div_by_zero, retry=retry)
worker = Worker([queue])
registry = queue.scheduled_job_registry
# If job if configured to retry with interval, it will be scheduled,
# not directly put back in the queue
queue.empty()
worker.handle_job_failure(job, queue)
job.refresh()
self.assertEqual(job.get_status(), JobStatus.SCHEDULED)
self.assertEqual(job.retries_left, 0)
self.assertEqual(len(registry), 1)
self.assertEqual(queue.job_ids, [])
# Scheduled time is roughly 5 seconds from now
scheduled_time = registry.get_scheduled_time(job)
now = datetime.now(timezone.utc)
self.assertTrue(now + timedelta(seconds=3) < scheduled_time < now + timedelta(seconds=10))
def test_cleanup_handles_retries(self):
"""Expired jobs should also be retried"""
queue = Queue(connection=self.connection)
registry = StartedJobRegistry(connection=self.connection)
failed_job_registry = FailedJobRegistry(connection=self.connection)
job = queue.enqueue(say_hello, retry=Retry(max=1))
# Add job to StartedJobRegistry with past expiration time
self.connection.zadd(registry.key, {job.id: 2})
registry.cleanup()
self.assertEqual(len(queue), 2)
self.assertEqual(job.get_status(), JobStatus.QUEUED)
self.assertNotIn(job, failed_job_registry)
self.connection.zadd(registry.key, {job.id: 2})
# Job goes to FailedJobRegistry because it's only retried once
registry.cleanup()
self.assertEqual(len(queue), 2)
self.assertEqual(job.get_status(), JobStatus.FAILED)
self.assertIn(job, failed_job_registry)
def test_retry_get_interval(self):
"""Retry.get_interval() returns the right retry interval"""
self.assertEqual(Retry.get_interval(0, [1, 2, 3]), 1)
self.assertEqual(Retry.get_interval(1, [1, 2, 3]), 2)
self.assertEqual(Retry.get_interval(3, [1, 2, 3]), 3)
self.assertEqual(Retry.get_interval(4, [1, 2, 3]), 3)
self.assertEqual(Retry.get_interval(5, [1, 2, 3]), 3)
# Handle case where interval is None
self.assertEqual(Retry.get_interval(1, None), 0)
self.assertEqual(Retry.get_interval(2, None), 0)
# Handle case where interval is a single integer
self.assertEqual(Retry.get_interval(1, 3), 3)
self.assertEqual(Retry.get_interval(2, 3), 3)
| TestRetry |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass3.py | {
"start": 554,
"end": 592
} | class ____(metaclass=Meta10): ...
| Base10 |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 37517,
"end": 38048
} | class ____(_TestBasicOps, __TestCase):
def setUp(self):
self.case = "unit set (tuple)"
self.values = [(0, "zero")]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 1
self.repr = "{(0, 'zero')}"
super().setUp()
def test_in(self):
self.assertIn((0, "zero"), self.set)
def test_not_in(self):
self.assertNotIn(9, self.set)
#------------------------------------------------------------------------------
| TestBasicOpsTuple |
python | falconry__falcon | tests/test_httperror.py | {
"start": 4855,
"end": 5065
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPMethodNotAllowed(
['PUT'], headers={'x-ping': 'pong', 'accept': 'GET,PUT'}
)
| MethodNotAllowedResourceWithHeadersWithAccept |
python | dask__dask | dask/layers.py | {
"start": 2621,
"end": 3262
} | class ____(ArrayBlockwiseDep):
def __init__(self, chunks: tuple[tuple[int, ...], ...], values: np.ndarray | dict):
super().__init__(chunks)
self.values = values
def __getitem__(self, idx: tuple):
return self.values[idx]
@normalize_token.register(ArraySliceDep)
def normalize_array_slice_dep(dep):
return "ArraySliceDep", dep.chunks
@normalize_token.register(ArrayBlockIdDep)
def normalize_array_block_id_dep(dep):
return "ArrayBlockIdDep", dep.chunks
@normalize_token.register(ArrayValuesDep)
def normalize_array_values_dep(dep):
return "ArrayValuesDep", dep.chunks, dep.values
| ArrayValuesDep |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/fields.py | {
"start": 13674,
"end": 14601
} | class ____(StringField):
"""Datetime field."""
types = (datetime.datetime,)
def __init__(self, str_format: str = None, *args: Any, **kwargs: Any) -> None:
"""Init.
:param str str_format: Format to cast datetime to (if `None` - casting
to ISO 8601 format).
"""
self.str_format = str_format
super(DateTimeField, self).__init__(*args, **kwargs)
def to_struct(self, value: datetime.datetime) -> str:
"""Cast `datetime` object to string."""
if self.str_format:
return value.strftime(self.str_format)
return value.isoformat()
def parse_value(self, value: Any) -> Optional[datetime.datetime]:
"""Parse string into instance of `datetime`."""
if isinstance(value, datetime.datetime):
return value
if value:
return parse(value)
else:
return None
| DateTimeField |
python | plotly__plotly.py | plotly/graph_objs/contourcarpet/_colorbar.py | {
"start": 233,
"end": 61611
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contourcarpet"
_path_str = "contourcarpet.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",
"nticks",
"orientation",
"outlinecolor",
"outlinewidth",
"separatethousands",
"showexponent",
"showticklabels",
"showtickprefix",
"showticksuffix",
"thickness",
"thicknessmode",
"tick0",
"tickangle",
"tickcolor",
"tickfont",
"tickformat",
"tickformatstopdefaults",
"tickformatstops",
"ticklabeloverflow",
"ticklabelposition",
"ticklabelstep",
"ticklen",
"tickmode",
"tickprefix",
"ticks",
"ticksuffix",
"ticktext",
"ticktextsrc",
"tickvals",
"tickvalssrc",
"tickwidth",
"title",
"x",
"xanchor",
"xpad",
"xref",
"y",
"yanchor",
"ypad",
"yref",
}
@property
def bgcolor(self):
"""
Sets the color of padded area.
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bordercolor(self):
"""
Sets the axis line color.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def borderwidth(self):
"""
Sets the width (in px) or the border enclosing this color bar.
The 'borderwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["borderwidth"]
@borderwidth.setter
def borderwidth(self, val):
self["borderwidth"] = val
@property
def dtick(self):
"""
Sets the step in-between ticks on this axis. Use with `tick0`.
Must be a positive number, or special strings available to
"log" and "date" axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick number. For
example, to set a tick mark at 1, 10, 100, 1000, ... set dtick
to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2.
To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special values;
"L<f>", where `f` is a positive number, gives ticks linearly
spaced in value (but not position). For example `tick0` = 0.1,
`dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To
show powers of 10 plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and
"D2". If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval between
ticks to one day, set `dtick` to 86400000.0. "date" also has
special values "M<n>" gives ticks spaced by a number of months.
`n` must be a positive integer. To set ticks on the 15th of
every third month, set `tick0` to "2000-01-15" and `dtick` to
"M3". To set ticks every 4 years, set `dtick` to "M48"
The 'dtick' property accepts values of any type
Returns
-------
Any
"""
return self["dtick"]
@dtick.setter
def dtick(self, val):
self["dtick"] = val
@property
def exponentformat(self):
"""
Determines a formatting rule for the tick exponents. For
example, consider the number 1,000,000,000. If "none", it
appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If "SI", 1G. If
"B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T
(10^12). *SI extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI
extended* is used and the exponent is beyond the above ranges,
the formatting rule will automatically be switched to the power
notation.
The 'exponentformat' property is an enumeration that may be specified as:
- One of the following enumeration values:
['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended']
Returns
-------
Any
"""
return self["exponentformat"]
@exponentformat.setter
def exponentformat(self, val):
self["exponentformat"] = val
@property
def labelalias(self):
"""
Replacement text for specific tick or hover labels. For example
using {US: 'USA', CA: 'Canada'} changes US to USA and CA to
Canada. The labels we would have shown must match the keys
exactly, after adding any tickprefix or ticksuffix. For
negative numbers the minus sign symbol used (U+2212) is wider
than the regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis type, and
both keys (if needed) and values (if desired) can include html-
like tags or MathJax.
The 'labelalias' property accepts values of any type
Returns
-------
Any
"""
return self["labelalias"]
@labelalias.setter
def labelalias(self, val):
self["labelalias"] = val
@property
def len(self):
"""
Sets the length of the color bar This measure excludes the
padding of both ends. That is, the color bar length is this
length minus the padding on both ends.
The 'len' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["len"]
@len.setter
def len(self, val):
self["len"] = val
@property
def lenmode(self):
"""
Determines whether this color bar's length (i.e. the measure in
the color variation direction) is set in units of plot
"fraction" or in *pixels. Use `len` to set the value.
The 'lenmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["lenmode"]
@lenmode.setter
def lenmode(self, val):
self["lenmode"] = val
@property
def minexponent(self):
"""
Hide SI prefix for 10^n if |n| is below this number. This only
has an effect when `tickformat` is "SI" or "B".
The 'minexponent' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["minexponent"]
@minexponent.setter
def minexponent(self, val):
self["minexponent"] = val
@property
def nticks(self):
"""
Specifies the maximum number of ticks for the particular axis.
The actual number of ticks will be chosen automatically to be
less than or equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
The 'nticks' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["nticks"]
@nticks.setter
def nticks(self, val):
self["nticks"] = val
@property
def orientation(self):
"""
Sets the orientation of the colorbar.
The 'orientation' property is an enumeration that may be specified as:
- One of the following enumeration values:
['h', 'v']
Returns
-------
Any
"""
return self["orientation"]
@orientation.setter
def orientation(self, val):
self["orientation"] = val
@property
def outlinecolor(self):
"""
Sets the axis line color.
The 'outlinecolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["outlinecolor"]
@outlinecolor.setter
def outlinecolor(self, val):
self["outlinecolor"] = val
@property
def outlinewidth(self):
"""
Sets the width (in px) of the axis line.
The 'outlinewidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["outlinewidth"]
@outlinewidth.setter
def outlinewidth(self, val):
self["outlinewidth"] = val
@property
def separatethousands(self):
"""
If "true", even 4-digit integers are separated
The 'separatethousands' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["separatethousands"]
@separatethousands.setter
def separatethousands(self, val):
self["separatethousands"] = val
@property
def showexponent(self):
"""
If "all", all exponents are shown besides their significands.
If "first", only the exponent of the first tick is shown. If
"last", only the exponent of the last tick is shown. If "none",
no exponents appear.
The 'showexponent' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showexponent"]
@showexponent.setter
def showexponent(self, val):
self["showexponent"] = val
@property
def showticklabels(self):
"""
Determines whether or not the tick labels are drawn.
The 'showticklabels' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showticklabels"]
@showticklabels.setter
def showticklabels(self, val):
self["showticklabels"] = val
@property
def showtickprefix(self):
"""
If "all", all tick labels are displayed with a prefix. If
"first", only the first tick is displayed with a prefix. If
"last", only the last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
The 'showtickprefix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showtickprefix"]
@showtickprefix.setter
def showtickprefix(self, val):
self["showtickprefix"] = val
@property
def showticksuffix(self):
"""
Same as `showtickprefix` but for tick suffixes.
The 'showticksuffix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showticksuffix"]
@showticksuffix.setter
def showticksuffix(self, val):
self["showticksuffix"] = val
@property
def thickness(self):
"""
Sets the thickness of the color bar This measure excludes the
size of the padding, ticks and labels.
The 'thickness' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["thickness"]
@thickness.setter
def thickness(self, val):
self["thickness"] = val
@property
def thicknessmode(self):
"""
Determines whether this color bar's thickness (i.e. the measure
in the constant color direction) is set in units of plot
"fraction" or in "pixels". Use `thickness` to set the value.
The 'thicknessmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["thicknessmode"]
@thicknessmode.setter
def thicknessmode(self, val):
self["thicknessmode"] = val
@property
def tick0(self):
"""
Sets the placement of the first tick on this axis. Use with
`dtick`. If the axis `type` is "log", then you must take the
log of your starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when `dtick`=*L<f>* (see
`dtick` for more info). If the axis `type` is "date", it should
be a date string, like date data. If the axis `type` is
"category", it should be a number, using the scale where each
category is assigned a serial number from zero in the order it
appears.
The 'tick0' property accepts values of any type
Returns
-------
Any
"""
return self["tick0"]
@tick0.setter
def tick0(self, val):
self["tick0"] = val
@property
def tickangle(self):
"""
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the tick
labels vertically.
The 'tickangle' property is a angle (in degrees) that may be
specified as a number between -180 and 180.
Numeric values outside this range are converted to the equivalent value
(e.g. 270 is converted to -90).
Returns
-------
int|float
"""
return self["tickangle"]
@tickangle.setter
def tickangle(self, val):
self["tickangle"] = val
@property
def tickcolor(self):
"""
Sets the tick color.
The 'tickcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["tickcolor"]
@tickcolor.setter
def tickcolor(self, val):
self["tickcolor"] = val
@property
def tickfont(self):
"""
Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Returns
-------
plotly.graph_objs.contourcarpet.colorbar.Tickfont
"""
return self["tickfont"]
@tickfont.setter
def tickfont(self, val):
self["tickfont"] = val
@property
def tickformat(self):
"""
Sets the tick label formatting rule using d3 formatting mini-
languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for
dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to d3's date
formatter: "%h" for half of the year as a decimal number as
well as "%{n}f" for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with tickformat
"%H~%M~%S.%2f" would display "09~15~23.46"
The 'tickformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickformat"]
@tickformat.setter
def tickformat(self, val):
self["tickformat"] = val
@property
def tickformatstops(self):
"""
The 'tickformatstops' property is a tuple of instances of
Tickformatstop that may be specified as:
- A list or tuple of instances of plotly.graph_objs.contourcarpet.colorbar.Tickformatstop
- A list or tuple of dicts of string/value properties that
will be passed to the Tickformatstop constructor
Returns
-------
tuple[plotly.graph_objs.contourcarpet.colorbar.Tickformatstop]
"""
return self["tickformatstops"]
@tickformatstops.setter
def tickformatstops(self, val):
self["tickformatstops"] = val
@property
def tickformatstopdefaults(self):
"""
When used in a template (as layout.template.data.contourcarpet.
colorbar.tickformatstopdefaults), sets the default property
values to use for elements of
contourcarpet.colorbar.tickformatstops
The 'tickformatstopdefaults' property is an instance of Tickformatstop
that may be specified as:
- An instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Tickformatstop`
- A dict of string/value properties that will be passed
to the Tickformatstop constructor
Returns
-------
plotly.graph_objs.contourcarpet.colorbar.Tickformatstop
"""
return self["tickformatstopdefaults"]
@tickformatstopdefaults.setter
def tickformatstopdefaults(self, val):
self["tickformatstopdefaults"] = val
@property
def ticklabeloverflow(self):
"""
Determines how we handle tick labels that would overflow either
the graph div or the domain of the axis. The default value for
inside tick labels is *hide past domain*. In other cases the
default is *hide past div*.
The 'ticklabeloverflow' property is an enumeration that may be specified as:
- One of the following enumeration values:
['allow', 'hide past div', 'hide past domain']
Returns
-------
Any
"""
return self["ticklabeloverflow"]
@ticklabeloverflow.setter
def ticklabeloverflow(self, val):
self["ticklabeloverflow"] = val
@property
def ticklabelposition(self):
"""
Determines where tick labels are drawn relative to the ticks.
Left and right options are used when `orientation` is "h", top
and bottom when `orientation` is "v".
The 'ticklabelposition' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', 'outside top', 'inside top',
'outside left', 'inside left', 'outside right', 'inside
right', 'outside bottom', 'inside bottom']
Returns
-------
Any
"""
return self["ticklabelposition"]
@ticklabelposition.setter
def ticklabelposition(self, val):
self["ticklabelposition"] = val
@property
def ticklabelstep(self):
"""
Sets the spacing between tick labels as compared to the spacing
between ticks. A value of 1 (default) means each tick gets a
label. A value of 2 means shows every 2nd label. A larger value
n means only every nth tick is labeled. `tick0` determines
which labels are shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is "array".
The 'ticklabelstep' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 9223372036854775807]
Returns
-------
int
"""
return self["ticklabelstep"]
@ticklabelstep.setter
def ticklabelstep(self, val):
self["ticklabelstep"] = val
@property
def ticklen(self):
"""
Sets the tick length (in px).
The 'ticklen' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ticklen"]
@ticklen.setter
def ticklen(self, val):
self["ticklen"] = val
@property
def tickmode(self):
"""
Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any
"""
return self["tickmode"]
@tickmode.setter
def tickmode(self, val):
self["tickmode"] = val
@property
def tickprefix(self):
"""
Sets a tick label prefix.
The 'tickprefix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickprefix"]
@tickprefix.setter
def tickprefix(self, val):
self["tickprefix"] = val
@property
def ticks(self):
"""
Determines whether ticks are drawn or not. If "", this axis'
ticks are not drawn. If "outside" ("inside"), this axis' are
drawn outside (inside) the axis lines.
The 'ticks' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', '']
Returns
-------
Any
"""
return self["ticks"]
@ticks.setter
def ticks(self, val):
self["ticks"] = val
@property
def ticksuffix(self):
"""
Sets a tick label suffix.
The 'ticksuffix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["ticksuffix"]
@ticksuffix.setter
def ticksuffix(self, val):
self["ticksuffix"] = val
@property
def ticktext(self):
"""
Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["ticktext"]
@ticktext.setter
def ticktext(self, val):
self["ticktext"] = val
@property
def ticktextsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `ticktext`.
The 'ticktextsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["ticktextsrc"]
@ticktextsrc.setter
def ticktextsrc(self, val):
self["ticktextsrc"] = val
@property
def tickvals(self):
"""
Sets the values at which ticks on this axis appear. Only has an
effect if `tickmode` is set to "array". Used with `ticktext`.
The 'tickvals' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["tickvals"]
@tickvals.setter
def tickvals(self, val):
self["tickvals"] = val
@property
def tickvalssrc(self):
"""
Sets the source reference on Chart Studio Cloud for `tickvals`.
The 'tickvalssrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["tickvalssrc"]
@tickvalssrc.setter
def tickvalssrc(self, val):
self["tickvalssrc"] = val
@property
def tickwidth(self):
"""
Sets the tick width (in px).
The 'tickwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["tickwidth"]
@tickwidth.setter
def tickwidth(self, val):
self["tickwidth"] = val
@property
def title(self):
"""
The 'title' property is an instance of Title
that may be specified as:
- An instance of :class:`plotly.graph_objs.contourcarpet.colorbar.Title`
- A dict of string/value properties that will be passed
to the Title constructor
Returns
-------
plotly.graph_objs.contourcarpet.colorbar.Title
"""
return self["title"]
@title.setter
def title(self, val):
self["title"] = val
@property
def x(self):
"""
Sets the x position with respect to `xref` of the color bar (in
plot fraction). When `xref` is "paper", defaults to 1.02 when
`orientation` is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when `orientation` is "v"
and 0.5 when `orientation` is "h". Must be between 0 and 1 if
`xref` is "container" and between "-2" and 3 if `xref` is
"paper".
The 'x' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def xanchor(self):
"""
Sets this color bar's horizontal position anchor. This anchor
binds the `x` position to the "left", "center" or "right" of
the color bar. Defaults to "left" when `orientation` is "v" and
"center" when `orientation` is "h".
The 'xanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'center', 'right']
Returns
-------
Any
"""
return self["xanchor"]
@xanchor.setter
def xanchor(self, val):
self["xanchor"] = val
@property
def xpad(self):
"""
Sets the amount of padding (in px) along the x direction.
The 'xpad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["xpad"]
@xpad.setter
def xpad(self, val):
self["xpad"] = val
@property
def xref(self):
"""
Sets the container `x` refers to. "container" spans the entire
`width` of the plot. "paper" refers to the width of the
plotting area only.
The 'xref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["xref"]
@xref.setter
def xref(self, val):
self["xref"] = val
@property
def y(self):
"""
Sets the y position with respect to `yref` of the color bar (in
plot fraction). When `yref` is "paper", defaults to 0.5 when
`orientation` is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when `orientation` is
"v" and 1 when `orientation` is "h". Must be between 0 and 1 if
`yref` is "container" and between "-2" and 3 if `yref` is
"paper".
The 'y' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def yanchor(self):
"""
Sets this color bar's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or "bottom" of
the color bar. Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
The 'yanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['top', 'middle', 'bottom']
Returns
-------
Any
"""
return self["yanchor"]
@yanchor.setter
def yanchor(self, val):
self["yanchor"] = val
@property
def ypad(self):
"""
Sets the amount of padding (in px) along the y direction.
The 'ypad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ypad"]
@ypad.setter
def ypad(self, val):
self["ypad"] = val
@property
def yref(self):
"""
Sets the container `y` refers to. "container" spans the entire
`height` of the plot. "paper" refers to the height of the
plotting area only.
The 'yref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["yref"]
@yref.setter
def yref(self, val):
self["yref"] = val
@property
def _prop_descriptions(self):
return """\
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.contourcarpet.c
olorbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.contou
rcarpet.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
contourcarpet.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.contourcarpet.colorbar.Tit
le` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
"""
def __init__(
self,
arg=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
dtick=None,
exponentformat=None,
labelalias=None,
len=None,
lenmode=None,
minexponent=None,
nticks=None,
orientation=None,
outlinecolor=None,
outlinewidth=None,
separatethousands=None,
showexponent=None,
showticklabels=None,
showtickprefix=None,
showticksuffix=None,
thickness=None,
thicknessmode=None,
tick0=None,
tickangle=None,
tickcolor=None,
tickfont=None,
tickformat=None,
tickformatstops=None,
tickformatstopdefaults=None,
ticklabeloverflow=None,
ticklabelposition=None,
ticklabelstep=None,
ticklen=None,
tickmode=None,
tickprefix=None,
ticks=None,
ticksuffix=None,
ticktext=None,
ticktextsrc=None,
tickvals=None,
tickvalssrc=None,
tickwidth=None,
title=None,
x=None,
xanchor=None,
xpad=None,
xref=None,
y=None,
yanchor=None,
ypad=None,
yref=None,
**kwargs,
):
"""
Construct a new ColorBar object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.contourcarpet.ColorBar`
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.contourcarpet.c
olorbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.contou
rcarpet.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
contourcarpet.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.contourcarpet.colorbar.Tit
le` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
Returns
-------
ColorBar
"""
super().__init__("colorbar")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.contourcarpet.ColorBar
constructor must be a dict or
an instance of :class:`plotly.graph_objs.contourcarpet.ColorBar`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("borderwidth", arg, borderwidth)
self._set_property("dtick", arg, dtick)
self._set_property("exponentformat", arg, exponentformat)
self._set_property("labelalias", arg, labelalias)
self._set_property("len", arg, len)
self._set_property("lenmode", arg, lenmode)
self._set_property("minexponent", arg, minexponent)
self._set_property("nticks", arg, nticks)
self._set_property("orientation", arg, orientation)
self._set_property("outlinecolor", arg, outlinecolor)
self._set_property("outlinewidth", arg, outlinewidth)
self._set_property("separatethousands", arg, separatethousands)
self._set_property("showexponent", arg, showexponent)
self._set_property("showticklabels", arg, showticklabels)
self._set_property("showtickprefix", arg, showtickprefix)
self._set_property("showticksuffix", arg, showticksuffix)
self._set_property("thickness", arg, thickness)
self._set_property("thicknessmode", arg, thicknessmode)
self._set_property("tick0", arg, tick0)
self._set_property("tickangle", arg, tickangle)
self._set_property("tickcolor", arg, tickcolor)
self._set_property("tickfont", arg, tickfont)
self._set_property("tickformat", arg, tickformat)
self._set_property("tickformatstops", arg, tickformatstops)
self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults)
self._set_property("ticklabeloverflow", arg, ticklabeloverflow)
self._set_property("ticklabelposition", arg, ticklabelposition)
self._set_property("ticklabelstep", arg, ticklabelstep)
self._set_property("ticklen", arg, ticklen)
self._set_property("tickmode", arg, tickmode)
self._set_property("tickprefix", arg, tickprefix)
self._set_property("ticks", arg, ticks)
self._set_property("ticksuffix", arg, ticksuffix)
self._set_property("ticktext", arg, ticktext)
self._set_property("ticktextsrc", arg, ticktextsrc)
self._set_property("tickvals", arg, tickvals)
self._set_property("tickvalssrc", arg, tickvalssrc)
self._set_property("tickwidth", arg, tickwidth)
self._set_property("title", arg, title)
self._set_property("x", arg, x)
self._set_property("xanchor", arg, xanchor)
self._set_property("xpad", arg, xpad)
self._set_property("xref", arg, xref)
self._set_property("y", arg, y)
self._set_property("yanchor", arg, yanchor)
self._set_property("ypad", arg, ypad)
self._set_property("yref", arg, yref)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| ColorBar |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_arguments.py | {
"start": 714,
"end": 1260
} | class ____:
def f(self, y, z, a, b, c, *, u, v, w): # Too many arguments (8/5)
pass
def f(self, y, z, a, b, c): # OK
pass
@classmethod
def f(cls, y, z, a, b, c, *, u, v, w): # Too many arguments (8/5)
pass
@classmethod
def f(cls, y, z, a, b, c): # OK
pass
@staticmethod
def f(y, z, a, b, c, *, u, v, w): # Too many arguments (8/5)
pass
@staticmethod
def f(y, z, a, b, c, d): # OK
pass
@staticmethod
def f(y, z, a, b, c): # OK
pass
| C |
python | pytorch__pytorch | test/fx/test_partitioner_order.py | {
"start": 272,
"end": 461
} | class ____(OperatorSupport):
def is_node_supported(
self, submodules: Mapping[str, torch.nn.Module], node: torch.fx.Node
) -> bool:
return True
| DummyDevOperatorSupport |
python | PrefectHQ__prefect | src/prefect/server/utilities/database.py | {
"start": 6658,
"end": 8440
} | class ____(TypeDecorator[Any]):
"""
JSON type that returns SQLAlchemy's dialect-specific JSON types, where
possible. Uses generic JSON otherwise.
The "base" type is postgresql.JSONB to expose useful methods prior
to SQL compilation
"""
impl: type[postgresql.JSONB] | type[TypeEngine[Any]] | TypeEngine[Any] = (
postgresql.JSONB
)
cache_ok: bool | None = True
def load_dialect_impl(self, dialect: sa.Dialect) -> TypeEngine[Any]:
if dialect.name == "postgresql":
return dialect.type_descriptor(postgresql.JSONB(none_as_null=True))
elif dialect.name == "sqlite":
return dialect.type_descriptor(sqlite.JSON(none_as_null=True))
else:
return dialect.type_descriptor(sa.JSON(none_as_null=True))
def process_bind_param(
self, value: Optional[Any], dialect: sa.Dialect
) -> Optional[Any]:
"""Prepares the given value to be used as a JSON field in a parameter binding"""
if not value:
return value
# PostgreSQL does not support the floating point extrema values `NaN`,
# `-Infinity`, or `Infinity`
# https://www.postgresql.org/docs/current/datatype-json.html#JSON-TYPE-MAPPING-TABLE
#
# SQLite supports storing and retrieving full JSON values that include
# `NaN`, `-Infinity`, or `Infinity`, but any query that requires SQLite to parse
# the value (like `json_extract`) will fail.
#
# Replace any `NaN`, `-Infinity`, or `Infinity` values with `None` in the
# returned value. See more about `parse_constant` at
# https://docs.python.org/3/library/json.html#json.load.
return json.loads(json.dumps(value), parse_constant=lambda c: None)
| JSON |
python | huggingface__transformers | tests/models/vitdet/test_modeling_vitdet.py | {
"start": 5784,
"end": 11708
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as VitDet does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (VitDetModel, VitDetBackbone) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": VitDetModel} if is_torch_available() else {}
test_resize_embeddings = False
test_torch_exportable = True
def setUp(self):
self.model_tester = VitDetModelTester(self)
self.config_tester = ConfigTester(self, config_class=VitDetConfig, has_text_modality=False, hidden_size=37)
# TODO: Fix me (once this model gets more usage)
@unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
def test_cpu_offload(self):
pass
# TODO: Fix me (once this model gets more usage)
@unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
def test_disk_offload_bin(self):
pass
@unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
def test_disk_offload_safetensors(self):
pass
# TODO: Fix me (once this model gets more usage)
@unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
def test_model_parallelism(self):
pass
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(reason="VitDet does not use inputs_embeds")
def test_inputs_embeds(self):
pass
def test_model_get_set_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_backbone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_backbone(*config_and_inputs)
def test_hidden_states_output(self):
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.hidden_states
expected_num_stages = self.model_tester.num_hidden_layers
self.assertEqual(len(hidden_states), expected_num_stages + 1)
# VitDet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:]),
[
self.model_tester.num_patches_one_direction,
self.model_tester.num_patches_one_direction,
],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
check_hidden_states_output(inputs_dict, config, model_class)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
check_hidden_states_output(inputs_dict, config, model_class)
# overwrite since VitDet only supports retraining gradients of hidden states
def test_retain_grad_hidden_states_attentions(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.output_hidden_states = True
config.output_attentions = self.has_attentions
# no need to test all models as different heads yield the same functionality
model_class = self.all_model_classes[0]
model = model_class(config)
model.to(torch_device)
inputs = self._prepare_for_class(inputs_dict, model_class)
outputs = model(**inputs)
output = outputs[0]
# Encoder-/Decoder-only models
hidden_states = outputs.hidden_states[0]
hidden_states.retain_grad()
output.flatten()[0].backward(retain_graph=True)
self.assertIsNotNone(hidden_states.grad)
@unittest.skip(reason="VitDet does not support feedforward chunking")
def test_feed_forward_chunking(self):
pass
@unittest.skip(reason="VitDet does not have standalone checkpoints since it used as backbone in other models")
def test_model_from_pretrained(self):
pass
def test_non_square_image(self):
non_square_image_size = (32, 40)
patch_size = (2, 2)
config = self.model_tester.get_config()
config.image_size = non_square_image_size
config.patch_size = patch_size
model = VitDetModel(config=config)
model.to(torch_device)
model.eval()
batch_size = self.model_tester.batch_size
# Create a dummy input tensor with non-square spatial dimensions.
pixel_values = floats_tensor(
[batch_size, config.num_channels, non_square_image_size[0], non_square_image_size[1]]
)
result = model(pixel_values)
expected_height = non_square_image_size[0] / patch_size[0]
expected_width = non_square_image_size[1] / patch_size[1]
expected_shape = (batch_size, config.hidden_size, expected_height, expected_width)
self.assertEqual(result.last_hidden_state.shape, expected_shape)
@require_torch
| VitDetModelTest |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_to_have_no_days_missing.py | {
"start": 1806,
"end": 5169
} | class ____(ColumnAggregateExpectation):
"""Expect No missing days in date column."""
from datetime import datetime, timedelta
today = datetime.now()
yesterday = today - timedelta(days=1)
two_days_ago = today - timedelta(days=2)
thirty_days_ago = today - timedelta(days=30)
sixty_days_ago = today - timedelta(days=60)
examples = [
{
"data": {
"column_a": [today, yesterday, thirty_days_ago, sixty_days_ago],
"column_b": [today, yesterday, yesterday, two_days_ago],
"column_c": [today, two_days_ago, two_days_ago, two_days_ago],
},
"suppress_test_for": ["mssql"],
"tests": [
{
"title": "missing_many_days",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "column_a", "threshold": 4},
"out": {"success": False},
},
{
"title": "missing_one_day",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "column_c", "threshold": 1},
"out": {"success": True},
},
{
"title": "positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "column_b", "threshold": 2},
"out": {"success": True},
},
],
}
]
# Setting necessary computation metric dependencies and defining kwargs, as well as assigning kwargs default values
metric_dependencies = ("column.distinct_dates",)
success_keys = ("threshold",)
# Default values
default_kwarg_values = {}
library_metadata = {
"maturity": "experimental",
"contributors": [
"@itaise",
],
"tags": ["date-column"],
}
def _validate(
self,
metrics: Dict,
runtime_configuration: dict = None,
execution_engine: ExecutionEngine = None,
):
from datetime import datetime, timedelta
# returns the distinct dates of the column
dist_dates_as_str = metrics["column.distinct_dates"]
distinct_dates_sorted = sorted(
[datetime.strptime(date_str, "%Y-%m-%d") for date_str in dist_dates_as_str]
)
min_date, max_date = distinct_dates_sorted[0], distinct_dates_sorted[-1]
days_diff = (max_date - min_date).days
date_set = {distinct_dates_sorted[0] + timedelta(x) for x in range(days_diff)}
missing_days = sorted(date_set - set(distinct_dates_sorted))
threshold = self._get_success_kwargs().get("threshold")
success: bool = len(missing_days) <= threshold
return {
"success": success,
"result": {
"Number of missing days": len(missing_days),
"Total unique days": len(distinct_dates_sorted),
"Threshold": threshold,
"Min date": min_date,
"Max date": max_date,
},
}
if __name__ == "__main__":
ExpectColumnToHaveNoDaysMissing().print_diagnostic_checklist()
| ExpectColumnToHaveNoDaysMissing |
python | huggingface__transformers | tests/models/glm4v_moe/test_modeling_glm4v_moe.py | {
"start": 1264,
"end": 6582
} | class ____:
def __init__(
self,
parent,
batch_size=3,
seq_length=7,
num_channels=3,
ignore_index=-100,
image_size=112,
video_start_token_id=3,
video_end_token_id=4,
image_start_token_id=5,
image_end_token_id=6,
image_token_id=7,
video_token_id=8,
is_training=True,
text_config={
"vocab_size": 99,
"hidden_size": 16,
"intermediate_size": 22,
"num_hidden_layers": 2,
"num_attention_heads": 2,
"num_key_value_heads": 1,
"output_channels": 64,
"hidden_act": "silu",
"max_position_embeddings": 512,
"rope_parameters": {"type": "default", "mrope_section": [1, 1]},
"rope_theta": 10000,
"tie_word_embeddings": True,
"bos_token_id": 0,
"eos_token_id": 0,
"pad_token_id": 0,
"n_routed_experts": 8,
"n_shared_experts": 1,
"n_group": 1,
"topk_group": 1,
"num_experts_per_tok": 8,
},
vision_config={
"depth": 2,
"hidden_act": "silu",
"hidden_size": 48,
"out_hidden_size": 16,
"intermediate_size": 22,
"patch_size": 14,
"spatial_merge_size": 1,
"temporal_patch_size": 2,
},
):
self.parent = parent
self.ignore_index = ignore_index
self.bos_token_id = text_config["bos_token_id"]
self.eos_token_id = text_config["eos_token_id"]
self.pad_token_id = text_config["pad_token_id"]
self.video_start_token_id = video_start_token_id
self.video_end_token_id = video_end_token_id
self.image_start_token_id = image_start_token_id
self.image_end_token_id = image_end_token_id
self.image_token_id = image_token_id
self.video_token_id = video_token_id
self.text_config = text_config
self.vision_config = vision_config
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.is_training = is_training
self.hidden_size = text_config["hidden_size"]
self.num_hidden_layers = text_config["num_hidden_layers"]
self.num_attention_heads = text_config["num_attention_heads"]
self.vocab_size = text_config["vocab_size"]
self.num_image_tokens = 64
self.seq_length = seq_length + self.num_image_tokens
self.n_routed_experts = text_config["n_routed_experts"]
self.n_shared_experts = text_config["n_shared_experts"]
self.num_experts_per_tok = text_config["num_experts_per_tok"]
self.n_group = text_config["n_group"]
self.topk_group = text_config["topk_group"]
def get_config(self):
return Glm4vMoeConfig(
text_config=self.text_config,
vision_config=self.vision_config,
image_token_id=self.image_token_id,
video_token_id=self.video_token_id,
video_start_token_id=self.video_start_token_id,
video_end_token_id=self.video_end_token_id,
image_start_token_id=self.image_start_token_id,
image_end_token_id=self.image_end_token_id,
)
def prepare_config_and_inputs(self):
config = self.get_config()
patch_size = config.vision_config.patch_size
temporal_patch_size = config.vision_config.temporal_patch_size
pixel_values = floats_tensor(
[
self.batch_size * (self.image_size**2) // (patch_size**2),
self.num_channels * (patch_size**2) * temporal_patch_size,
]
)
return config, pixel_values
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values = config_and_inputs
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
input_ids[input_ids == self.video_token_id] = self.pad_token_id
input_ids[input_ids == self.image_token_id] = self.pad_token_id
input_ids[input_ids == self.video_start_token_id] = self.pad_token_id
input_ids[input_ids == self.image_start_token_id] = self.pad_token_id
input_ids[input_ids == self.video_end_token_id] = self.pad_token_id
input_ids[input_ids == self.image_end_token_id] = self.pad_token_id
input_ids[:, 0] = self.image_start_token_id
input_ids[:, 1 : 1 + self.num_image_tokens] = self.image_token_id
input_ids[:, 1 + self.num_image_tokens] = self.image_end_token_id
patch_size = config.vision_config.patch_size
patches_per_side = self.image_size // patch_size
inputs_dict = {
"pixel_values": pixel_values,
"image_grid_thw": torch.tensor(
[[1, patches_per_side, patches_per_side]] * self.batch_size, device=torch_device
),
"input_ids": input_ids,
"attention_mask": attention_mask,
}
return config, inputs_dict
@require_torch
| Glm4vMoeVisionText2TextModelTester |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 1858,
"end": 3200
} | class ____(BaseModelOutputWithCrossAttentions):
r"""
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
used to compute the weighted average in the cross-attention heads.
intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
layernorm.
"""
intermediate_hidden_states: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for outputs of the DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
"""
)
| DetrDecoderOutput |
python | ray-project__ray | python/ray/tests/test_runtime_env_packaging.py | {
"start": 5100,
"end": 8296
} | class ____:
def test_invalid_directory(self):
with pytest.raises(ValueError):
get_uri_for_directory("/does/not/exist", include_gitignore=True)
with pytest.raises(ValueError):
get_uri_for_directory("does/not/exist", include_gitignore=True)
def test_determinism(self, random_dir):
# Check that it's deterministic for same data.
uris = {
get_uri_for_directory(random_dir, include_gitignore=True) for _ in range(10)
}
assert len(uris) == 1
# Add one file, should be different now.
with open(random_dir / f"test_{random_string()}", "w") as f:
f.write(random_string())
assert {get_uri_for_directory(random_dir, include_gitignore=True)} != uris
def test_relative_paths(self, random_dir):
# Check that relative or absolute paths result in the same URI.
p = Path(random_dir)
relative_uri = get_uri_for_directory(os.path.relpath(p), include_gitignore=True)
absolute_uri = get_uri_for_directory(p.resolve(), include_gitignore=True)
assert relative_uri == absolute_uri
def test_excludes(self, random_dir):
# Excluding a directory should modify the URI.
included_uri = get_uri_for_directory(random_dir, include_gitignore=True)
excluded_uri = get_uri_for_directory(
random_dir, include_gitignore=True, excludes=["subdir"]
)
assert included_uri != excluded_uri
# Excluding a directory should be the same as deleting it.
rmtree((Path(random_dir) / "subdir").resolve())
deleted_uri = get_uri_for_directory(random_dir, include_gitignore=True)
assert deleted_uri == excluded_uri
def test_empty_directory(self):
try:
os.mkdir("d1")
os.mkdir("d2")
assert get_uri_for_directory(
"d1", include_gitignore=True
) == get_uri_for_directory("d2", include_gitignore=True)
finally:
os.rmdir("d1")
os.rmdir("d2")
def test_uri_hash_length(self, random_dir):
uri = get_uri_for_directory(random_dir, include_gitignore=True)
hex_hash = uri.split("_")[-1][: -len(".zip")]
assert len(hex_hash) == 16
@pytest.mark.skipif(
sys.platform == "win32",
reason="Unix sockets not available on windows",
)
def test_unopenable_files_skipped(self, random_dir, short_path_dir):
"""Test that unopenable files can be present in the working_dir.
Some files such as `.sock` files are unopenable. This test ensures that
we skip those files when generating the content hash. Previously this
would raise an exception, see #25411.
"""
# Create a socket file.
sock = socket.socket(socket.AF_UNIX)
sock.bind(str(short_path_dir / "test_socket"))
# Check that opening the socket raises an exception.
with pytest.raises(OSError):
(short_path_dir / "test_socket").open()
# Check that the hash can still be generated without errors.
get_uri_for_directory(short_path_dir, include_gitignore=True)
| TestGetURIForDirectory |
python | pennersr__django-allauth | allauth/socialaccount/providers/facebook/forms.py | {
"start": 27,
"end": 116
} | class ____(forms.Form):
access_token = forms.CharField(required=True)
| FacebookConnectForm |
python | lazyprogrammer__machine_learning_examples | tf2.0/mlp_trader.py | {
"start": 6364,
"end": 10959
} | class ____(object):
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.memory = ReplayBuffer(state_size, action_size, size=500)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.model = mlp(state_size, action_size)
def update_replay_memory(self, state, action, reward, next_state, done):
self.memory.store(state, action, reward, next_state, done)
def act(self, state):
if np.random.rand() <= self.epsilon:
return np.random.choice(self.action_size)
act_values = self.model.predict(state)
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size=32):
# first check if replay buffer contains enough data
if self.memory.size < batch_size:
return
# sample a batch of data from the replay memory
minibatch = self.memory.sample_batch(batch_size)
states = minibatch['s']
actions = minibatch['a']
rewards = minibatch['r']
next_states = minibatch['s2']
done = minibatch['d']
# Calculate the tentative target: Q(s',a)
target = rewards + (1 - done) * self.gamma * np.amax(self.model.predict(next_states), axis=1)
# With the Keras API, the target (usually) must have the same
# shape as the predictions.
# However, we only need to update the network for the actions
# which were actually taken.
# We can accomplish this by setting the target to be equal to
# the prediction for all values.
# Then, only change the targets for the actions taken.
# Q(s,a)
target_full = self.model.predict(states)
target_full[np.arange(batch_size), actions] = target
# Run one training step
self.model.partial_fit(states, target_full)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def load(self, name):
with open(name, "rb") as f:
self.model = pickle.load(f)
def save(self, name):
with open(name, "wb") as f:
pickle.dump(self.model, f)
def play_one_episode(agent, env, is_train):
# note: after transforming states are already 1xD
state = env.reset()
state = scaler.transform([state])
done = False
while not done:
action = agent.act(state)
next_state, reward, done, info = env.step(action)
next_state = scaler.transform([next_state])
if is_train == 'train':
agent.update_replay_memory(state, action, reward, next_state, done)
agent.replay(batch_size)
state = next_state
return info['cur_val']
if __name__ == '__main__':
# config
models_folder = 'rl_trader_models'
rewards_folder = 'rl_trader_rewards'
num_episodes = 2000
batch_size = 32
initial_investment = 20000
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mode', type=str, required=True,
help='either "train" or "test"')
args = parser.parse_args()
maybe_make_dir(models_folder)
maybe_make_dir(rewards_folder)
data = get_data()
n_timesteps, n_stocks = data.shape
n_train = n_timesteps // 2
train_data = data[:n_train]
test_data = data[n_train:]
env = MultiStockEnv(train_data, initial_investment)
state_size = env.state_dim
action_size = len(env.action_space)
agent = DQNAgent(state_size, action_size)
scaler = get_scaler(env)
# store the final value of the portfolio (end of episode)
portfolio_value = []
if args.mode == 'test':
# then load the previous scaler
with open(f'{models_folder}/scaler.pkl', 'rb') as f:
scaler = pickle.load(f)
# remake the env with test data
env = MultiStockEnv(test_data, initial_investment)
# make sure epsilon is not 1!
# no need to run multiple episodes if epsilon = 0, it's deterministic
agent.epsilon = 0.01
# load trained weights
agent.load(f'{models_folder}/mlp.pkl')
# play the game num_episodes times
for e in range(num_episodes):
t0 = datetime.now()
val = play_one_episode(agent, env, args.mode)
dt = datetime.now() - t0
print(f"episode: {e + 1}/{num_episodes}, episode end value: {val:.2f}, duration: {dt}")
portfolio_value.append(val) # append episode end portfolio value
# save the weights when we are done
if args.mode == 'train':
# save the DQN
agent.save(f'{models_folder}/mlp.pkl')
# save the scaler
with open(f'{models_folder}/scaler.pkl', 'wb') as f:
pickle.dump(scaler, f)
# save portfolio value for each episode
np.save(f'{rewards_folder}/{args.mode}.npy', portfolio_value)
| DQNAgent |
python | ionelmc__pytest-benchmark | tests/test_sample.py | {
"start": 65,
"end": 266
} | class ____:
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
| cached_property |
python | getsentry__sentry | fixtures/page_objects/base.py | {
"start": 843,
"end": 1020
} | class ____(ButtonElement):
@property
def icon_href(self):
return self.element.find_element(by=By.TAG_NAME, value="use").get_attribute("href")
| ButtonWithIconElement |
python | redis__redis-py | redis/backoff.py | {
"start": 190,
"end": 589
} | class ____(ABC):
"""Backoff interface"""
def reset(self):
"""
Reset internal state before an operation.
`reset` is called once at the beginning of
every call to `Retry.call_with_retry`
"""
pass
@abstractmethod
def compute(self, failures: int) -> float:
"""Compute backoff in seconds upon failure"""
pass
| AbstractBackoff |
python | getsentry__sentry | src/sentry/flags/providers.py | {
"start": 18471,
"end": 19943
} | class ____:
"""Abstract payload validator. Uses HMAC-SHA256 by default.
Allows us to inject dependencies for differing use cases. Specifically
the test suite.
"""
def __init__(
self,
organization_id: int,
provider: str,
message: bytes,
signature: str | None,
secret_finder: Callable[[int, str], Iterator[str]] | None = None,
secret_validator: Callable[[str, bytes], str] | None = None,
) -> None:
self.organization_id = organization_id
self.provider = provider
self.message = message
self.signature = signature
self.secret_finder = secret_finder or _query_signing_secrets
self.secret_validator = secret_validator or hmac_sha256_hex_digest
def validate(self) -> bool:
if self.signature is None:
return False
for secret in self.secret_finder(self.organization_id, self.provider):
if self.secret_validator(secret, self.message) == self.signature:
return True
return False
def _query_signing_secrets(organization_id: int, provider: str) -> Iterator[str]:
for model in FlagWebHookSigningSecretModel.objects.filter(
organization_id=organization_id,
provider=provider,
).all():
yield model.secret
def hmac_sha256_hex_digest(key: str, message: bytes):
return hmac.new(key.encode(), message, hashlib.sha256).hexdigest()
| PayloadSignatureValidator |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 121089,
"end": 121301
} | class ____:
xlTextQualifierDoubleQuote = 1 # from enum XlTextQualifier
xlTextQualifierNone = -4142 # from enum XlTextQualifier
xlTextQualifierSingleQuote = 2 # from enum XlTextQualifier
| TextQualifier |
python | pandas-dev__pandas | pandas/io/excel/_xlsxwriter.py | {
"start": 393,
"end": 6035
} | class ____:
# Map from openpyxl-oriented styles to flatter xlsxwriter representation
# Ordering necessary for both determinism and because some are keyed by
# prefixes of others.
STYLE_MAPPING: dict[str, list[tuple[tuple[str, ...], str]]] = {
"font": [
(("name",), "font_name"),
(("sz",), "font_size"),
(("size",), "font_size"),
(("color", "rgb"), "font_color"),
(("color",), "font_color"),
(("b",), "bold"),
(("bold",), "bold"),
(("i",), "italic"),
(("italic",), "italic"),
(("u",), "underline"),
(("underline",), "underline"),
(("strike",), "font_strikeout"),
(("vertAlign",), "font_script"),
(("vertalign",), "font_script"),
],
"number_format": [(("format_code",), "num_format"), ((), "num_format")],
"protection": [(("locked",), "locked"), (("hidden",), "hidden")],
"alignment": [
(("horizontal",), "align"),
(("vertical",), "valign"),
(("text_rotation",), "rotation"),
(("wrap_text",), "text_wrap"),
(("indent",), "indent"),
(("shrink_to_fit",), "shrink"),
],
"fill": [
(("patternType",), "pattern"),
(("patterntype",), "pattern"),
(("fill_type",), "pattern"),
(("start_color", "rgb"), "fg_color"),
(("fgColor", "rgb"), "fg_color"),
(("fgcolor", "rgb"), "fg_color"),
(("start_color",), "fg_color"),
(("fgColor",), "fg_color"),
(("fgcolor",), "fg_color"),
(("end_color", "rgb"), "bg_color"),
(("bgColor", "rgb"), "bg_color"),
(("bgcolor", "rgb"), "bg_color"),
(("end_color",), "bg_color"),
(("bgColor",), "bg_color"),
(("bgcolor",), "bg_color"),
],
"border": [
(("color", "rgb"), "border_color"),
(("color",), "border_color"),
(("style",), "border"),
(("top", "color", "rgb"), "top_color"),
(("top", "color"), "top_color"),
(("top", "style"), "top"),
(("top",), "top"),
(("right", "color", "rgb"), "right_color"),
(("right", "color"), "right_color"),
(("right", "style"), "right"),
(("right",), "right"),
(("bottom", "color", "rgb"), "bottom_color"),
(("bottom", "color"), "bottom_color"),
(("bottom", "style"), "bottom"),
(("bottom",), "bottom"),
(("left", "color", "rgb"), "left_color"),
(("left", "color"), "left_color"),
(("left", "style"), "left"),
(("left",), "left"),
],
}
@classmethod
def convert(cls, style_dict, num_format_str=None) -> dict[str, Any]:
"""
converts a style_dict to an xlsxwriter format dict
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string
"""
# Create an XlsxWriter format object.
props = {}
if num_format_str is not None:
props["num_format"] = num_format_str
if style_dict is None:
return props
if "borders" in style_dict:
style_dict = style_dict.copy()
style_dict["border"] = style_dict.pop("borders")
for style_group_key, style_group in style_dict.items():
for src, dst in cls.STYLE_MAPPING.get(style_group_key, []):
# src is a sequence of keys into a nested dict
# dst is a flat key
if dst in props:
continue
v = style_group
for k in src:
try:
v = v[k]
except (KeyError, TypeError):
break
else:
props[dst] = v
if isinstance(props.get("pattern"), str):
# TODO: support other fill patterns
props["pattern"] = 0 if props["pattern"] == "none" else 1
for k in ["border", "top", "right", "bottom", "left"]:
if isinstance(props.get(k), str):
try:
props[k] = [
"none",
"thin",
"medium",
"dashed",
"dotted",
"thick",
"double",
"hair",
"mediumDashed",
"dashDot",
"mediumDashDot",
"dashDotDot",
"mediumDashDotDot",
"slantDashDot",
].index(props[k])
except ValueError:
props[k] = 2
if isinstance(props.get("font_script"), str):
props["font_script"] = ["baseline", "superscript", "subscript"].index(
props["font_script"]
)
if isinstance(props.get("underline"), str):
props["underline"] = {
"none": 0,
"single": 1,
"double": 2,
"singleAccounting": 33,
"doubleAccounting": 34,
}[props["underline"]]
# GH 30107 - xlsxwriter uses different name
if props.get("valign") == "center":
props["valign"] = "vcenter"
return props
| _XlsxStyler |
python | lepture__authlib | authlib/integrations/flask_oauth2/requests.py | {
"start": 1093,
"end": 1281
} | class ____(JsonPayload):
def __init__(self, request: Request):
self._request = request
@property
def data(self):
return self._request.get_json()
| FlaskJsonPayload |
python | doocs__leetcode | lcof2/剑指 Offer II 067. 最大的异或/Solution2.py | {
"start": 649,
"end": 840
} | class ____:
def findMaximumXOR(self, nums: List[int]) -> int:
trie = Trie()
for v in nums:
trie.insert(v)
return max(trie.search(v) for v in nums)
| Solution |
python | scrapy__scrapy | scrapy/utils/log.py | {
"start": 6975,
"end": 8059
} | class ____(logging.Handler):
"""Record log levels count into a crawler stats"""
def __init__(self, crawler: Crawler, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.crawler: Crawler = crawler
def emit(self, record: logging.LogRecord) -> None:
sname = f"log_count/{record.levelname}"
assert self.crawler.stats
self.crawler.stats.inc_value(sname)
def logformatter_adapter(
logkws: LogFormatterResult,
) -> tuple[int, str, dict[str, Any] | tuple[Any, ...]]:
"""
Helper that takes the dictionary output from the methods in LogFormatter
and adapts it into a tuple of positional arguments for logger.log calls,
handling backward compatibility as well.
"""
level = logkws.get("level", logging.INFO)
message = logkws.get("msg") or ""
# NOTE: This also handles 'args' being an empty dict, that case doesn't
# play well in logger.log calls
args = cast("dict[str, Any]", logkws) if not logkws.get("args") else logkws["args"]
return (level, message, args)
| LogCounterHandler |
python | PyCQA__pylint | tests/functional/s/singledispatch/singledispatch_functions.py | {
"start": 337,
"end": 1396
} | class ____:
@staticmethod
def register(function):
return function
def __call__(self, function):
return function
fake_singledispatch_decorator = FakeSingleDispatch()
@singledispatch
def func(arg):
return arg
@func.register(str)
def _(arg):
return 42
@func.register(float)
@func.register(int)
def _(arg):
return 42
@my_single_dispatch
def func2(arg):
return arg
@func2.register(int)
def _(arg):
return 42
@singledispatch
def with_extra_arg(arg, verbose=False):
if verbose:
print(arg)
return arg
@with_extra_arg.register(str)
def _(arg, verbose=False):
unused = 42 # [unused-variable]
return arg[::-1]
@fake_singledispatch_decorator
def not_single_dispatch(arg): # [unused-argument]
return 'not yet implemented'
@fake_singledispatch_decorator.register(str)
def bad_single_dispatch(arg): # [unused-argument]
return 42
@fake_singledispatch_decorator.register(str)
def bad_single_dispatch(arg): # [unused-argument, function-redefined]
return 24
| FakeSingleDispatch |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/feishu/tests.py | {
"start": 211,
"end": 1721
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = FeishuProvider.id
def get_mocked_response(self):
return [
MockedResponse(
0,
"""
{"data": {"access_token": "testac"}}
""",
),
MockedResponse(
0,
"""
{
"code": 0,
"data": {
"access_token": "u-6U1SbDiM6XIH2DcTCPyeub",
"avatar_url": "www.feishu.cn/avatar/icon",
"avatar_thumb": "www.feishu.cn/avatar/icon_thumb",
"avatar_middle": "www.feishu.cn/avatar/icon_middle",
"avatar_big": "www.feishu.cn/avatar/icon_big",
"expires_in": 7140,
"name": "zhangsan",
"en_name": "Three Zhang",
"open_id": "ou-caecc734c2e3328a62489fe0648c4b98779515d3",
"tenant_key": "736588c92lxf175d",
"refresh_expires_in": 2591940,
"refresh_token": "ur-t9HHgRCjMqGqIU9v05Zhos",
"token_type": "Bearer"
}
}
""",
),
]
def get_expected_to_str(self):
return "zhangsan"
def get_login_response_json(self, with_refresh_token=True):
return """{"app_access_token":"testac"}"""
| FeishuTests |
python | django__django | django/core/validators.py | {
"start": 16551,
"end": 19915
} | class ____:
"""
Validate that the input does not exceed the maximum number of digits
expected, otherwise raise ValidationError.
"""
messages = {
"invalid": _("Enter a number."),
"max_digits": ngettext_lazy(
"Ensure that there are no more than %(max)s digit in total.",
"Ensure that there are no more than %(max)s digits in total.",
"max",
),
"max_decimal_places": ngettext_lazy(
"Ensure that there are no more than %(max)s decimal place.",
"Ensure that there are no more than %(max)s decimal places.",
"max",
),
"max_whole_digits": ngettext_lazy(
"Ensure that there are no more than %(max)s digit before the decimal "
"point.",
"Ensure that there are no more than %(max)s digits before the decimal "
"point.",
"max",
),
}
def __init__(self, max_digits, decimal_places):
self.max_digits = max_digits
self.decimal_places = decimal_places
def __call__(self, value):
digit_tuple, exponent = value.as_tuple()[1:]
if exponent in {"F", "n", "N"}:
raise ValidationError(
self.messages["invalid"], code="invalid", params={"value": value}
)
if exponent >= 0:
digits = len(digit_tuple)
if digit_tuple != (0,):
# A positive exponent adds that many trailing zeros.
digits += exponent
decimals = 0
else:
# If the absolute value of the negative exponent is larger than the
# number of digits, then it's the same as the number of digits,
# because it'll consume all of the digits in digit_tuple and then
# add abs(exponent) - len(digit_tuple) leading zeros after the
# decimal point.
if abs(exponent) > len(digit_tuple):
digits = decimals = abs(exponent)
else:
digits = len(digit_tuple)
decimals = abs(exponent)
whole_digits = digits - decimals
if self.max_digits is not None and digits > self.max_digits:
raise ValidationError(
self.messages["max_digits"],
code="max_digits",
params={"max": self.max_digits, "value": value},
)
if self.decimal_places is not None and decimals > self.decimal_places:
raise ValidationError(
self.messages["max_decimal_places"],
code="max_decimal_places",
params={"max": self.decimal_places, "value": value},
)
if (
self.max_digits is not None
and self.decimal_places is not None
and whole_digits > (self.max_digits - self.decimal_places)
):
raise ValidationError(
self.messages["max_whole_digits"],
code="max_whole_digits",
params={"max": (self.max_digits - self.decimal_places), "value": value},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.max_digits == other.max_digits
and self.decimal_places == other.decimal_places
)
@deconstructible
| DecimalValidator |
python | tensorflow__tensorflow | tensorflow/python/training/proximal_adagrad_test.py | {
"start": 1304,
"end": 10020
} | class ____(test.TestCase):
def doTestProximalAdagradwithoutRegularization(self, use_resource=False):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([0.0, 0.0])
var1 = variables.Variable([0.0, 0.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose([0.0, 0.0], v0_val)
self.assertAllClose([0.0, 0.0], v1_val)
# Run 3 steps Proximal Adagrad.
for _ in range(3):
update.run()
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose(np.array([-2.60260963, -4.29698515]), v0_val)
self.assertAllClose(np.array([-0.28432083, -0.56694895]), v1_val)
opt_vars = opt.variables()
self.assertStartsWith(opt_vars[0].name, var0._shared_name)
self.assertStartsWith(opt_vars[1].name, var1._shared_name)
self.assertEqual(2, len(opt_vars))
def testProximalAdagradwithoutRegularization(self):
self.doTestProximalAdagradwithoutRegularization(use_resource=False)
def testResourceProximalAdagradwithoutRegularization(self):
self.doTestProximalAdagradwithoutRegularization(use_resource=True)
def testProximalAdagradwithoutRegularization2(self):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([1.0, 2.0])
var1 = variables.Variable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose([1.0, 2.0], v0_val)
self.assertAllClose([4.0, 3.0], v1_val)
# Run 3 steps Proximal Adagrad.
for _ in range(3):
update.run()
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose(np.array([-1.60261, -2.296985]), v0_val)
self.assertAllClose(np.array([3.715679, 2.433051]), v1_val)
def testMinimizeSparseResourceVariable(self):
for dtype in [dtypes.float32, dtypes.float64]:
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = proximal_adagrad.ProximalAdagradOptimizer(1.0).minimize(loss)
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([[0, 1]],
self.evaluate(var0),
atol=0.01)
def testProximalAdagradWithL1(self):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([1.0, 2.0])
var1 = variables.Variable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose([1.0, 2.0], v0_val)
self.assertAllClose([4.0, 3.0], v1_val)
# Run 10 steps Proximal Adagrad
for _ in range(10):
update.run()
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose(np.array([-6.663634, -9.190331]), v0_val)
self.assertAllClose(np.array([2.959304, 1.029232]), v1_val)
def testProximalAdagradWithL1_L2(self):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([1.0, 2.0])
var1 = variables.Variable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=2.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose([1.0, 2.0], v0_val)
self.assertAllClose([4.0, 3.0], v1_val)
# Run 10 steps Proximal Adagrad.
for _ in range(10):
update.run()
v0_val, v1_val = self.evaluate([var0, var1])
self.assertAllClose(np.array([-0.0495, -0.0995]), v0_val)
self.assertAllClose(np.array([-0.0045, -0.0095]), v1_val)
def applyOptimizer(self, opt, steps=5, is_sparse=False):
if is_sparse:
var0 = variables.Variable([[1.0], [2.0]])
var1 = variables.Variable([[3.0], [4.0]])
grads0 = indexed_slices.IndexedSlices(
constant_op.constant(
[0.1], shape=[1, 1]),
constant_op.constant([0]),
constant_op.constant([2, 1]))
grads1 = indexed_slices.IndexedSlices(
constant_op.constant(
[0.02], shape=[1, 1]),
constant_op.constant([1]),
constant_op.constant([2, 1]))
else:
var0 = variables.Variable([1.0, 2.0])
var1 = variables.Variable([3.0, 4.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
sess = ops.get_default_session()
v0_val, v1_val = self.evaluate([var0, var1])
if is_sparse:
self.assertAllClose([[1.0], [2.0]], v0_val)
self.assertAllClose([[3.0], [4.0]], v1_val)
else:
self.assertAllClose([1.0, 2.0], v0_val)
self.assertAllClose([3.0, 4.0], v1_val)
# Run ProximalAdagrad for a few steps
for _ in range(steps):
update.run()
v0_val, v1_val = self.evaluate([var0, var1])
return v0_val, v1_val
def testEquivAdagradwithoutRegularization(self):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
val0, val1 = self.applyOptimizer(
proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0))
with ops.Graph().as_default(), self.cached_session():
val2, val3 = self.applyOptimizer(
adagrad.AdagradOptimizer(
3.0, initial_accumulator_value=0.1))
self.assertAllClose(val0, val2)
self.assertAllClose(val1, val3)
def testEquivSparseAdagradwithoutRegularization(self):
# ProximalAdagradOptimizer is supported only in V1.
with ops.Graph().as_default(), self.cached_session():
val0, val1 = self.applyOptimizer(
proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0),
is_sparse=True)
with ops.Graph().as_default(), self.cached_session():
val2, val3 = self.applyOptimizer(
adagrad.AdagradOptimizer(
3.0, initial_accumulator_value=0.1),
is_sparse=True)
self.assertAllClose(val0, val2)
self.assertAllClose(val1, val3)
if __name__ == "__main__":
test.main()
| ProximalAdagradOptimizerTest |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 25322,
"end": 25637
} | class ____(unittest.TestCase):
def test_contains(self):
lines = ['# heading\n', '\n', 'paragraph\n', 'with\n', '`code`\n']
token = block_token.Document(lines)
self.assertTrue('heading' in token)
self.assertTrue('code' in token)
self.assertFalse('foo' in token)
| TestContains |
python | aimacode__aima-python | search.py | {
"start": 48799,
"end": 50191
} | class ____:
"""This class holds a list of words. You can use (word in wordlist)
to check if a word is in the list, or wordlist.lookup(prefix)
to see if prefix starts any of the words in the list."""
def __init__(self, file, min_len=3):
lines = file.read().upper().split()
self.words = [word for word in lines if len(word) >= min_len]
self.words.sort()
self.bounds = {}
for c in ALPHABET:
c2 = chr(ord(c) + 1)
self.bounds[c] = (bisect.bisect(self.words, c),
bisect.bisect(self.words, c2))
def lookup(self, prefix, lo=0, hi=None):
"""See if prefix is in dictionary, as a full word or as a prefix.
Return two values: the first is the lowest i such that
words[i].startswith(prefix), or is None; the second is
True iff prefix itself is in the Wordlist."""
words = self.words
if hi is None:
hi = len(words)
i = bisect.bisect_left(words, prefix, lo, hi)
if i < len(words) and words[i].startswith(prefix):
return i, (words[i] == prefix)
else:
return None, False
def __contains__(self, word):
return self.lookup(word)[1]
def __len__(self):
return len(self.words)
# _____________________________________________________________________________
| Wordlist |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_compute.py | {
"start": 38747,
"end": 43399
} | class ____:
@mock.patch(COMPUTE_ENGINE_HOOK_PATH)
def test_delete_template_should_execute_successfully(self, mock_hook):
op = ComputeEngineDeleteInstanceTemplateOperator(
resource_id=GCE_RESOURCE_ID,
project_id=GCP_PROJECT_ID,
task_id=TASK_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
api_version=API_VERSION,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.delete_instance_template.assert_called_once_with(
project_id=GCP_PROJECT_ID,
request_id=None,
resource_id=GCE_RESOURCE_ID,
)
def test_delete_template_should_throw_ex_when_missing_project_id(self):
with pytest.raises(AirflowException, match=r"The required parameter 'project_id' is missing"):
ComputeEngineDeleteInstanceTemplateOperator(
project_id="",
resource_id=GCE_RESOURCE_ID,
task_id=TASK_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
@mock.patch(COMPUTE_ENGINE_HOOK_PATH)
def test_delete_template_should_not_throw_ex_when_project_id_none(self, mock_hook):
op = ComputeEngineDeleteInstanceTemplateOperator(
resource_id=GCE_RESOURCE_ID,
task_id=TASK_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
api_version=API_VERSION,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.delete_instance_template.assert_called_once_with(
resource_id=GCE_RESOURCE_ID,
project_id=None,
request_id=None,
)
def test_delete_template_should_throw_ex_when_missing_resource_id(self):
with pytest.raises(AirflowException, match=r"The required parameter 'resource_id' is missing"):
ComputeEngineDeleteInstanceTemplateOperator(
resource_id="",
project_id=GCP_PROJECT_ID,
task_id=TASK_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
GCE_INSTANCE_TEMPLATE_NAME = "instance-template-test"
GCE_INSTANCE_TEMPLATE_NEW_NAME = "instance-template-test-new"
GCE_INSTANCE_TEMPLATE_REQUEST_ID = "e12d5b48-4826-4ba9-ada6-0cff1e0b36a6"
GCE_INSTANCE_TEMPLATE_BODY_GET = {
"kind": "compute#instanceTemplate",
"id": "6950321349997439715",
"creation_timestamp": "2018-10-15T06:20:12.777-07:00",
"name": GCE_INSTANCE_TEMPLATE_NAME,
"description": "",
"properties": {
"machine_type": "n1-standard-1",
"network_interfaces": [
{
"kind": "compute#networkInterface",
"network": "https://www.googleapis.com/compute/v1/projects/project/global/networks/default",
"access_configs": [
{
"kind": "compute#accessConfig",
"type": "ONE_TO_ONE_NAT",
}
],
},
{
"network": "https://www.googleapis.com/compute/v1/projects/project/global/networks/default",
"access_configs": [{"kind": "compute#accessConfig", "networkTier": "PREMIUM"}],
},
],
"disks": [
{
"kind": "compute#attachedDisk",
"type": "PERSISTENT",
"licenses": [
"A String",
],
}
],
},
"self_link": "https://www.googleapis.com/compute/v1/projects/project"
"/global/instanceTemplates/instance-template-test",
}
GCE_INSTANCE_TEMPLATE_BODY_INSERT = {
"name": GCE_INSTANCE_TEMPLATE_NEW_NAME,
}
GCE_INSTANCE_TEMPLATE_BODY_GET_NEW = deepcopy(GCE_INSTANCE_TEMPLATE_BODY_GET)
GCE_INSTANCE_TEMPLATE_BODY_GET_NEW["name"] = GCE_INSTANCE_TEMPLATE_NEW_NAME
| TestGceTemplateDelete |
python | pytorch__pytorch | torch/profiler/_memory_profiler.py | {
"start": 25057,
"end": 40400
} | class ____:
def __init__(self, result: _ProfilerResult) -> None:
self._op_tree = OpTree(result)
self._data_flow_graph = DataFlowGraph(self._op_tree)
self._size_map = SizeMap(self._op_tree)
self._categories = CategoryDict()
self._set_gradients_and_temporaries()
self._set_parameters_using_python_tracer()
self._set_inputs()
self._set_parameters_using_data_flow()
self._set_activations()
self._set_optimizer_state()
self._set_autograd_detail()
@property
def timeline(self) -> tuple[tuple[int, Action, KeyAndID, int], ...]:
output: list[tuple[int, Action, KeyAndID, int]] = []
allocation_times: dict[tuple[TensorKey, bool], int] = {}
live_unknown: dict[tuple[int, torch.device], Literal[True]] = {}
for event in self._op_tree.dfs():
if event.typed[0] == _EventType.Allocation:
alloc_fields = event.typed[1]
alloc_size = alloc_fields.alloc_size
is_allocation = alloc_size > 0
t = event.start_time_ns
tkey = TensorKey.from_allocation(alloc_fields)
if tkey is not None:
allocation_times[(tkey, is_allocation)] = t
else:
key = Key(alloc_fields.device)
ptr_and_device = (alloc_fields.ptr, key.device)
if is_allocation:
if ptr_and_device in live_unknown:
output.append(
(t, Action.INCREMENT_VERSION, (key, 0), alloc_size)
)
else:
live_unknown[ptr_and_device] = True
output.append((t, Action.CREATE, (key, 0), alloc_size))
else:
output.append((t, Action.DESTROY, (key, 0), -alloc_size))
if not live_unknown.pop(ptr_and_device, False):
output.append(
(-1, Action.PREEXISTING, (key, 0), -alloc_size)
)
snapshot = self._category_snapshot()
last_version = dict(sorted(snapshot.keys()))
events: list[tuple[int, Action, TensorAndID]] = [
(-1, Action.PREEXISTING, (key, version))
for key, version in snapshot
if (key, True) not in allocation_times and version == 0
]
for node in self._data_flow_graph.flow_nodes:
for key, edge in node._edges.items():
if edge.is_allocation:
t = allocation_times[(key, True)]
events.append((t, Action.CREATE, (key, 0)))
elif edge.mutated:
t = node._event.start_time_ns
version = edge.input_version
assert version is not None
events.append((t, Action.INCREMENT_VERSION, (key, version)))
if edge.is_deletion:
t = allocation_times[(key, False)]
events.append((t, Action.DESTROY, (key, last_version[key])))
output.extend(
(time, action, (key, version), self._size_map[key])
for time, action, (key, version) in events
)
output.sort(key=lambda x: (x[0], x[1].value))
return tuple(output)
def _is_gradient(self, *args, **kwargs) -> bool:
return self._categories.get(*args, **kwargs) == Category.GRADIENT
def _category_snapshot(self) -> dict[TensorAndID, Optional[Category]]:
all_tensor_versions: set[TensorAndID] = set()
for node in self._data_flow_graph.flow_nodes:
all_tensor_versions.update(((k, v) for k, (_, v) in node.inputs.items()))
all_tensor_versions.update((key, 0) for key in node.intermediates)
all_tensor_versions.update(node.outputs.items())
for i in self._categories._values.values():
all_tensor_versions.update((key, 0) for key in i._by_id_keyset)
return {
(key, version): self._categories.get(key, version)
for key, version in sorted(all_tensor_versions)
}
def _any_version_depends_on_gradient(self) -> set[int]:
"""Extract IDs of Tensors which depend or will depend on a gradient.
Note that this weakened definition of "depends" requires us to loop
over the data flow graph multiple times because it allows dependency
information to flow backward through edges and removes the guarantee
that nodes are topologically sorted. (Or indeed, even that a valid
topological order exists.) Put another way, we have converted an
acyclic data flow graph into a cyclic graph and we are attempting to
partition cycles involving a gradient from the rest of the graph.
"""
depends_on_gradient: set[int] = set()
while True:
start_size = len(depends_on_gradient)
for node in self._data_flow_graph.flow_nodes:
ids = tuple(
key.id
for key, (_, version) in node.inputs.items()
if self._categories.get(key, version)
in (Category.GRADIENT, Category.PARAMETER)
or key.id in depends_on_gradient
)
if ids:
depends_on_gradient.update(ids)
depends_on_gradient.update(key.id for key in node.outputs)
# We are guaranteed to exit because there is a finite set of
# TensorAndID pairs. In practice we do not expect to loop more than
# three times: once to identify the core parameter update loop,
# once to fold the first step into that loop, and a third time
# where no new elements are added.
if len(depends_on_gradient) == start_size:
return depends_on_gradient
def _set_gradients_and_temporaries(self) -> None:
"""Mark Tensors which are unambiguous and simple to reason about."""
# Gradients are straightforward to detect. We directly check the
# `.grad` property in the Python tracer, and we can detect any new
# gradient Tensors from `AccumulateGrad` ops.
for event in self._op_tree.dfs():
for _, p_grad in extract_gradients(event):
self._categories.set_by_id(p_grad, Category.GRADIENT)
# Similarly, temporary Tensors are easy to identify and are useful to
# flag since they can make memory use "spikier" than one would
# otherwise expect.
for node in self._data_flow_graph.flow_nodes:
for i in node.intermediates:
self._categories.set_by_key(i, Category.TEMPORARY)
def _set_parameters_using_python_tracer(self) -> None:
for event in self._op_tree.dfs():
for p in extract_parameters(event):
if p is not None:
self._categories.set_by_id(p, Category.PARAMETER)
def _set_inputs(self) -> None:
"""Mark inputs based on which Tensors are updated using gradients.
The process for differentiating between inputs and activations is more
involved. Most Tensors in a training loop depend on at least one
gradient: parameters depend on them through updates, and activations
and optimizer state depend on them transitively through parameters.
Critically, we do not need to know which Tensors are parameters to
apply this method; we can simply walk the data flow graph to build the
set of all values which depend on a gradient and then obtain the set
of inputs from the conjugate set.
There is, however, one hiccup. The first time we see a parameter is
generally on the forward pass of the first step. We know from
inspection of the data flow graph that v1 of that Tensor depends on
a gradient (provided we profile an optimizer step), but not v0. To
address this problem we weaken the definition of "depends on a
gradient" to "any version of this Tensor depends on a gradient",
which in turn strengthens the criteria for the input set enough to
filter the activations in the forward pass of the first step."""
# All of this analysis is predicated on using at least one training
# step (or parameters from the python tracer) to partition the graph.
# Absent that we cannot determine which Tensors are inputs and which
# ones are part of the model.
depends_on_gradient = self._any_version_depends_on_gradient()
# We only want to annotate Tensors which actually contribute to the
# model calculation.
produces_gradient: set[TensorAndID] = set()
for node in reversed(self._data_flow_graph.flow_nodes):
tensors = {(key, version) for key, (_, version) in node.inputs.items()}
tensors |= node.outputs.items()
if any(
self._categories.get(*i) in (Category.GRADIENT, Category.PARAMETER)
or i in produces_gradient
for i in tensors
):
produces_gradient |= tensors
# Don't include Tensors created in the backward pass, as these are
# generally Autograd implementation details rather than proper inputs.
input_candidates = produces_gradient.copy()
for node in self._data_flow_graph.flow_nodes:
if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
input_candidates -= set(node.outputs.items())
for key, version in input_candidates:
if key.id not in depends_on_gradient:
self._categories.setdefault_by_version(key, version, Category.INPUT)
def _set_parameters_using_data_flow(self) -> None:
"""Deduce which Tensors are parameters.
Consider the following code for the step of SGD with momentum
(nesterov=False), where `d_p` is the gradient of `param` and `buf` is
the momentum buffer.
```
buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
d_p = buf
param.add_(d_p, alpha=-lr)
```
Both `param` and `buf` take a gradient and perform an in-place update.
The python tracer will inspect calls to `nn.Module.forward` and
`optim.Optimizer.step` to extract parameter and optimizer state
respectively (including parameters), so this is generally a non-issue.
However as a fallback we can also exploit several properties of
parameters to distinguish them from other model state.
First, they are directly used in the forward pass. (At this point we
haven't established which parts of the graph correspond to the forward
pass but we can deduce enough to suffice.) Some mutable state such as
batch norm moving averages also contribute to the forward pass, but
optimizer state does not.
Second, a parameter is by definition used to compute at least one
gradient and depends on at least one gradient.
"""
snapshot = self._category_snapshot()
# Determine which Tensors might be parameters based on forward pass
# data flow. Note this these are only candidates; we filter nodes that
# we know are part of the backward pass but that doesn't guarantee that
# they are part of the forward pass.
candidate_parameters: set[TensorAndID] = set()
candidate_fwd_tensors: set[TensorAndID] = {
i for i, category in snapshot.items() if category == Category.INPUT
}
for node in self._data_flow_graph.flow_nodes:
inputs = {(key, value) for key, (_, value) in node.inputs.items()}
if (
# Don't check nodes in the backward pass.
RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
and not any(self._is_gradient(*i) for i in inputs)
and not any(self._is_gradient(*i) for i in node.outputs.items())
#
# and only check nodes which depend on an input.
and candidate_fwd_tensors.intersection(inputs)
):
candidate_fwd_tensors |= node.outputs.items()
candidate_parameters |= inputs.difference(candidate_fwd_tensors)
# Require that each parameter eventually contributes to the value of a gradient
used_for_gradient: set[TensorAndID] = set()
for node in reversed(self._data_flow_graph.flow_nodes):
if any(
self._is_gradient(*i) or i in used_for_gradient
for i in node.outputs.items()
):
used_for_gradient.update(
(key, version) for key, (_, version) in node.inputs.items()
)
candidate_parameters.intersection_update(used_for_gradient)
# and depends on a gradient.
parameter_keys = {key.id for key, _ in candidate_parameters}
parameter_keys &= self._any_version_depends_on_gradient()
for key, _ in snapshot:
if key.id in parameter_keys:
self._categories.set_by_id(key, Category.PARAMETER)
def _set_activations(self) -> None:
"""Flood the graph to identify activations."""
required = {Category.INPUT, Category.ACTIVATION}
also_allowed = {Category.PARAMETER, Category.TEMPORARY}
for node in self._data_flow_graph.flow_nodes:
inputs = {(key, value) for key, (_, value) in node.inputs.items()}
input_categories = {self._categories.get(*i) for i in inputs}
if (
(input_categories & required)
and not (input_categories - (required | also_allowed))
#
# Stop filling when we reach the backward pass.
and RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
):
for i in node.outputs.items():
self._categories.setdefault_by_version(*i, Category.ACTIVATION)
def _set_optimizer_state(self) -> None:
for event in self._op_tree.dfs():
if event.typed[0] == _EventType.PyCall and event.typed[1].optimizer:
parameters = event.typed[1].optimizer.parameters
for _, t in it.chain.from_iterable(
(state for _, _, state in parameters)
):
key = TensorKey.from_tensor(t)
if key is not None:
self._categories.set_by_id(key, Category.OPTIMIZER_STATE)
def _set_autograd_detail(self) -> None:
prior = {None, Category.AUTOGRAD_DETAIL}
for node in self._data_flow_graph.flow_nodes:
if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
for key, version in node.outputs.items():
if version == 0 or self._categories.get(key, version - 1) in prior:
self._categories.setdefault_by_version(
key, version, Category.AUTOGRAD_DETAIL
)
| MemoryProfile |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Robot_arm/DDPG.py | {
"start": 4403,
"end": 7453
} | class ____(object):
def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_):
self.sess = sess
self.s_dim = state_dim
self.a_dim = action_dim
self.lr = learning_rate
self.gamma = gamma
self.t_replace_iter = t_replace_iter
self.t_replace_counter = 0
with tf.variable_scope('Critic'):
# Input (s, a), output q
self.a = a
self.q = self._build_net(S, self.a, 'eval_net', trainable=True)
# Input (s_, a_), output q_ for q_target
self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net
self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net')
self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net')
with tf.variable_scope('target_q'):
self.target_q = R + self.gamma * self.q_
with tf.variable_scope('TD_error'):
self.loss = tf.reduce_mean(tf.squared_difference(self.target_q, self.q))
with tf.variable_scope('C_train'):
self.train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)
with tf.variable_scope('a_grad'):
self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim)
self.replace = [tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]
def _build_net(self, s, a, scope, trainable):
with tf.variable_scope(scope):
init_w = tf.contrib.layers.xavier_initializer()
init_b = tf.constant_initializer(0.01)
with tf.variable_scope('l1'):
n_l1 = 200
w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable)
w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable)
b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable)
net = tf.nn.relu6(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1)
net = tf.layers.dense(net, 200, activation=tf.nn.relu6,
kernel_initializer=init_w, bias_initializer=init_b, name='l2',
trainable=trainable)
net = tf.layers.dense(net, 10, activation=tf.nn.relu,
kernel_initializer=init_w, bias_initializer=init_b, name='l3',
trainable=trainable)
with tf.variable_scope('q'):
q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a)
return q
def learn(self, s, a, r, s_):
self.sess.run(self.train_op, feed_dict={S: s, self.a: a, R: r, S_: s_})
if self.t_replace_counter % self.t_replace_iter == 0:
self.sess.run(self.replace)
self.t_replace_counter += 1
| Critic |
python | Pylons__pyramid | src/pyramid/response.py | {
"start": 269,
"end": 307
} | class ____(_Response):
pass
| Response |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 3750,
"end": 5266
} | class ____(Qwen2_5OmniAudioEncoderConfig):
def __init__(
self,
num_mel_bins: Optional[int] = 128,
encoder_layers: Optional[int] = 32,
encoder_attention_heads: Optional[int] = 20,
encoder_ffn_dim: Optional[int] = 5120,
d_model: Optional[int] = 1280,
dropout: Optional[int] = 0,
attention_dropout: Optional[int] = 0,
activation_function: Optional[int] = "gelu",
activation_dropout: Optional[int] = 0,
scale_embedding: Optional[int] = False,
initializer_range: Optional[int] = 0.02,
max_source_positions: Optional[int] = 1500,
n_window: Optional[int] = 100,
output_dim: Optional[int] = 3584,
n_window_infer: Optional[int] = 400,
conv_chunksize: Optional[int] = 500,
downsample_hidden_size: Optional[int] = 480,
**kwargs,
):
super().__init__(
num_mel_bins,
encoder_layers,
encoder_attention_heads,
encoder_ffn_dim,
d_model,
dropout,
attention_dropout,
activation_function,
activation_dropout,
scale_embedding,
initializer_range,
max_source_positions,
n_window,
output_dim,
**kwargs,
)
self.n_window_infer = n_window_infer
self.conv_chunksize = conv_chunksize
self.downsample_hidden_size = downsample_hidden_size
| Qwen3OmniMoeAudioEncoderConfig |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 200,
"end": 1606
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
client_id: str,
client_secret: str,
refresh_token: str,
athlete_id: int,
start_date: str,
auth_type: Optional[str] = None,
):
"""Airbyte Source for Strava.
Documentation can be found at https://docs.airbyte.com/integrations/sources/strava
Args:
name (str): The name of the destination.
client_id (str): The Client ID of your Strava developer application.
client_secret (str): The Client Secret of your Strava developer application.
refresh_token (str): The Refresh Token with the activity: read_all permissions.
athlete_id (int): The Athlete ID of your Strava developer application.
start_date (str): UTC date and time. Any data before this date will not be replicated.
"""
self.auth_type = check.opt_str_param(auth_type, "auth_type")
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client_secret, "client_secret")
self.refresh_token = check.str_param(refresh_token, "refresh_token")
self.athlete_id = check.int_param(athlete_id, "athlete_id")
self.start_date = check.str_param(start_date, "start_date")
super().__init__("Strava", name)
| StravaSource |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-orchestrate/test_flow_routing.py | {
"start": 2512,
"end": 4273
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@requests(on='/index')
def index(self, docs: DocumentArray, **kwargs):
docs.append(Document(text='added'))
return docs
@requests(on='/search')
def search(self, docs: DocumentArray, **kwargs):
docs.append(Document(text='added'))
return docs
@requests(on='/custom')
def custom(self, docs: DocumentArray, **kwargs):
docs.append(Document(text='added'))
return docs
@pytest.mark.parametrize('polling', ['any', 'all'])
def test_flow_default_polling_endpoints(polling):
f = Flow().add(uses=DynamicPollingExecutorDefaultNames, shards=2, polling=polling)
with f:
docs_index = f.post(on='/index', inputs=[Document(text='1')])
docs_search = f.post(on='/search', inputs=[Document(text='1')])
docs_custom = f.post(on='/custom', inputs=[Document(text='1')])
assert len(docs_index) == 2
assert len(docs_search) == 3
assert len(docs_custom) == 3 if polling == 'all' else 2
@pytest.mark.parametrize('polling', ['any', 'all'])
def test_flow_default_custom_polling_endpoints(polling):
custom_polling_config = {'/custom': 'ALL', '/search': 'ANY', '*': polling}
f = Flow().add(
uses=DynamicPollingExecutorDefaultNames,
shards=2,
polling=custom_polling_config,
)
with f:
docs_index = f.post(on='/index', inputs=[Document(text='1')])
docs_search = f.post(on='/search', inputs=[Document(text='1')])
docs_custom = f.post(on='/custom', inputs=[Document(text='1')])
assert len(docs_index) == 2
assert len(docs_search) == 2
assert len(docs_custom) == 3
| DynamicPollingExecutorDefaultNames |
python | huggingface__transformers | src/transformers/models/vitmatte/modeling_vitmatte.py | {
"start": 3388,
"end": 4605
} | class ____(nn.Module):
"""
Simple ConvStream containing a series of basic conv3x3 layers to extract detail features.
"""
def __init__(self, config):
super().__init__()
# We use a default in-case there isn't a backbone config set. This is for backwards compatibility and
# to enable loading HF backbone models.
in_channels = 4
if config.backbone_config is not None:
in_channels = config.backbone_config.num_channels
out_channels = config.convstream_hidden_sizes
self.convs = nn.ModuleList()
self.conv_chans = [in_channels] + out_channels
for i in range(len(self.conv_chans) - 1):
in_chan_ = self.conv_chans[i]
out_chan_ = self.conv_chans[i + 1]
self.convs.append(VitMatteBasicConv3x3(config, in_chan_, out_chan_))
def forward(self, pixel_values):
out_dict = {"detailed_feature_map_0": pixel_values}
embeddings = pixel_values
for i in range(len(self.convs)):
embeddings = self.convs[i](embeddings)
name_ = "detailed_feature_map_" + str(i + 1)
out_dict[name_] = embeddings
return out_dict
| VitMatteConvStream |
python | ansible__ansible | lib/ansible/modules/apt_repository.py | {
"start": 7573,
"end": 15900
} | class ____(object):
def __init__(self, module):
self.module = module
self.files = {} # group sources by file
self.files_mapping = {} # internal DS for tracking symlinks
# Repositories that we're adding -- used to implement mode param
self.new_repos = set()
self.default_file = apt_pkg.config.find_file('Dir::Etc::sourcelist')
# read sources.list if it exists
if os.path.isfile(self.default_file):
self.load(self.default_file)
# read sources.list.d
self.sources_dir = apt_pkg.config.find_dir('Dir::Etc::sourceparts')
for file in glob.iglob(f'{self.sources_dir}/*.list'):
if os.path.islink(file):
self.files_mapping[file] = os.readlink(file)
self.load(file)
def __iter__(self):
"""Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped."""
for file, sources in self.files.items():
for n, valid, enabled, source, comment in sources:
if valid:
yield file, n, enabled, source, comment
def _expand_path(self, filename):
if '/' in filename:
return filename
else:
return os.path.abspath(os.path.join(self.sources_dir, filename))
def _suggest_filename(self, line):
def _cleanup_filename(s):
filename = self.module.params['filename']
if filename is not None:
return filename
return '_'.join(re.sub('[^a-zA-Z0-9]', ' ', s).split())
def _strip_username_password(s):
if '@' in s:
s = s.split('@', 1)
s = s[-1]
return s
# Drop options and protocols.
line = re.sub(r'\[[^\]]+\]', '', line)
line = re.sub(r'\w+://', '', line)
# split line into valid keywords
parts = [part for part in line.split() if part not in VALID_SOURCE_TYPES]
# Drop usernames and passwords
parts[0] = _strip_username_password(parts[0])
return '%s.list' % _cleanup_filename(' '.join(parts[:1]))
def _parse(self, line, raise_if_invalid_or_disabled=False):
valid = False
enabled = True
source = ''
comment = ''
line = line.strip()
if line.startswith('#'):
enabled = False
line = line[1:]
# Check for another "#" in the line and treat a part after it as a comment.
i = line.find('#')
if i > 0:
comment = line[i + 1:].strip()
line = line[:i]
# Split a source into substring to make sure that it is source spec.
# Duplicated whitespaces in a valid source spec will be removed.
source = line.strip()
if source:
chunks = source.split()
if chunks[0] in VALID_SOURCE_TYPES:
valid = True
source = ' '.join(chunks)
if raise_if_invalid_or_disabled and (not valid or not enabled):
raise InvalidSource(line)
return valid, enabled, source, comment
def load(self, file):
group = []
f = open(file, 'r')
for n, line in enumerate(f):
valid, enabled, source, comment = self._parse(line)
group.append((n, valid, enabled, source, comment))
self.files[file] = group
def save(self):
for filename, sources in list(self.files.items()):
if sources:
d, fn = os.path.split(filename)
try:
os.makedirs(d)
except OSError as ex:
if not os.path.isdir(d):
self.module.fail_json("Failed to create directory %s: %s" % (d, to_native(ex)))
try:
fd, tmp_path = tempfile.mkstemp(prefix=".%s-" % fn, dir=d)
except OSError as ex:
raise Exception(f'Unable to create temp file at {d!r} for apt source.') from ex
f = os.fdopen(fd, 'w')
for n, valid, enabled, source, comment in sources:
chunks = []
if not enabled:
chunks.append('# ')
chunks.append(source)
if comment:
chunks.append(' # ')
chunks.append(comment)
chunks.append('\n')
line = ''.join(chunks)
try:
f.write(line)
except OSError as ex:
raise Exception(f"Failed to write to file {tmp_path!r}.") from ex
if filename in self.files_mapping:
# Write to symlink target instead of replacing symlink as a normal file
self.module.atomic_move(tmp_path, self.files_mapping[filename])
else:
self.module.atomic_move(tmp_path, filename)
# allow the user to override the default mode
if filename in self.new_repos:
this_mode = self.module.params.get('mode', DEFAULT_SOURCES_PERM)
self.module.set_mode_if_different(filename, this_mode, False)
else:
del self.files[filename]
if os.path.exists(filename):
os.remove(filename)
def dump(self):
dumpstruct = {}
for filename, sources in self.files.items():
if sources:
lines = []
for n, valid, enabled, source, comment in sources:
chunks = []
if not enabled:
chunks.append('# ')
chunks.append(source)
if comment:
chunks.append(' # ')
chunks.append(comment)
chunks.append('\n')
lines.append(''.join(chunks))
dumpstruct[filename] = ''.join(lines)
return dumpstruct
def _choice(self, new, old):
if new is None:
return old
return new
def modify(self, file, n, enabled=None, source=None, comment=None):
"""
This function to be used with iterator, so we don't care of invalid sources.
If source, enabled, or comment is None, original value from line ``n`` will be preserved.
"""
valid, enabled_old, source_old, comment_old = self.files[file][n][1:]
self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old))
def _add_valid_source(self, source_new, comment_new, file):
# We'll try to reuse disabled source if we have it.
# If we have more than one entry, we will enable them all - no advanced logic, remember.
self.module.log('adding source file: %s | %s | %s' % (source_new, comment_new, file))
found = False
for filename, n, enabled, source, comment in self:
if source == source_new:
self.modify(filename, n, enabled=True)
found = True
if not found:
if file is None:
file = self.default_file
else:
file = self._expand_path(file)
if file not in self.files:
self.files[file] = []
files = self.files[file]
files.append((len(files), True, True, source_new, comment_new))
self.new_repos.add(file)
def add_source(self, line, comment='', file=None):
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
# Prefer separate files for new sources.
self._add_valid_source(source, comment, file=file or self._suggest_filename(source))
def _remove_valid_source(self, source):
# If we have more than one entry, we will remove them all (not comment, remove!)
for filename, n, enabled, src, comment in self:
if source == src and enabled:
self.files[filename].pop(n)
def remove_source(self, line):
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
self._remove_valid_source(source)
| SourcesList |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 25869,
"end": 26096
} | class ____(Structure):
_fields_ = (("flavor", p_uint32), ("count", p_uint32))
def describe(self):
s = {}
s["flavor"] = int(self.flavor)
s["count"] = int(self.count)
return s
| thread_command |
python | pytorch__pytorch | torch/testing/_internal/autocast_test_lists.py | {
"start": 180,
"end": 14863
} | class ____:
def _rnn_cell_args(self, n, num_chunks, is_lstm, dev, dtype):
input = (torch.randn((n, n), device=dev, dtype=torch.float32),)
hx = ((torch.randn((n, n), device=dev, dtype=torch.float32),
torch.randn((n, n), device=dev, dtype=torch.float32)) if is_lstm else
torch.randn((n, n), device=dev, dtype=torch.float32),)
weights = (torch.randn((num_chunks * n, n), device=dev, dtype=torch.float32), # weight_ih
torch.randn((num_chunks * n, n), device=dev, dtype=torch.float32), # weight_hh
torch.randn((num_chunks * n), device=dev, dtype=torch.float32), # bias_ih
torch.randn((num_chunks * n), device=dev, dtype=torch.float32)) # bias_hh
# returns args as a tuple
return input + hx + weights
# Supplies ops and arguments for test_autocast_* in test/test_cuda.py
def __init__(self, dev):
super().__init__()
n = 8
# Utility arguments, created as one-element tuples
pointwise0_fp16 = (torch.randn(n, dtype=torch.float16, device=dev),)
pointwise1_fp16 = (torch.randn(n, dtype=torch.float16, device=dev),)
pointwise2_fp16 = (torch.randn(n, dtype=torch.float16, device=dev),)
mat0_fp16 = (torch.randn((n, n), dtype=torch.float16, device=dev),)
mat1_fp16 = (torch.randn((n, n), dtype=torch.float16, device=dev),)
mat2_fp16 = (torch.randn((n, n), dtype=torch.float16, device=dev),)
dimsets = ((n, n, n), (n, n, n, n), (n, n, n, n, n))
conv_args_fp32 = [(torch.randn(dimset, dtype=torch.float32, device=dev),
torch.randn(dimset, dtype=torch.float32, device=dev))
for dimset in dimsets]
bias_fp32 = (torch.randn((n,), dtype=torch.float32, device=dev),)
element0_fp32 = (torch.randn(1, dtype=torch.float32, device=dev),)
pointwise0_fp32 = (torch.randn(n, dtype=torch.float32, device=dev),)
pointwise1_fp32 = (torch.randn(n, dtype=torch.float32, device=dev),)
mat0_fp32 = (torch.randn((n, n), dtype=torch.float32, device=dev),)
mat1_fp32 = (torch.randn((n, n), dtype=torch.float32, device=dev),)
mat2_fp32 = (torch.randn((n, n), dtype=torch.float32, device=dev),)
mat3_fp32 = (torch.randn((n, n), dtype=torch.float32, device=dev),)
# The lists below organize ops that autocast needs to test.
# self.list_name corresponds to test_autocast_list_name in test/test_cuda.py.
# Each op is associated with a tuple of valid arguments.
# In addition, cudnn conv ops are not supported on ROCm and hence will
# be skipped by passing TEST_WITH_ROCM flag to those ops in self.torch_fp16 list.
# Some ops implement built-in type promotion. These don't need autocasting,
# but autocasting relies on their promotion, so we include tests to double-check.
self.torch_expect_builtin_promote = [
("eq", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("ge", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("gt", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("le", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("lt", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("ne", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("add", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("div", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("mul", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("cat", (pointwise0_fp16 + pointwise1_fp32,), torch.float32),
("equal", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("stack", (pointwise0_fp16 + pointwise1_fp32,), torch.float32),
]
self.methods_expect_builtin_promote = [
("__eq__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__ge__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__gt__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__le__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__lt__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__ne__", pointwise0_fp32 + pointwise1_fp16, torch.bool),
("__add__", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("__div__", pointwise0_fp32 + pointwise1_fp16, torch.float32),
("__mul__", pointwise0_fp32 + pointwise1_fp16, torch.float32),
]
# The remaining lists organize ops that autocast treats explicitly.
self.torch_fp16 = [
# deprecated _convolution
("_convolution", conv_args_fp32[1] + bias_fp32 + ((1, 1), (0, 0), (1, 1), False,
(0, 0), 1, False, True, True)),
# the current _convolution
("_convolution", conv_args_fp32[1] + bias_fp32 + ((1, 1), (0, 0), (1, 1), False,
(0, 0), 1, False, True, True, True)),
("conv1d", conv_args_fp32[0]),
("conv2d", conv_args_fp32[1]),
("conv3d", conv_args_fp32[2]),
("conv_tbc", conv_args_fp32[0] + bias_fp32),
("conv_transpose1d", conv_args_fp32[0]),
("conv_transpose2d", conv_args_fp32[1]),
("conv_transpose3d", conv_args_fp32[2]),
("convolution", conv_args_fp32[1] + bias_fp32 + ((1, 1), (0, 0), (1, 1), False, (0, 0), 1)),
("cudnn_convolution", conv_args_fp32[1] + ((0, 0), (1, 1), (1, 1), 1, False, True, True), TEST_WITH_ROCM),
("cudnn_convolution_transpose", conv_args_fp32[1] + ((0, 0), (0, 0), (1, 1),
(1, 1), 1, False, True, True), TEST_WITH_ROCM),
("prelu", pointwise0_fp32 + element0_fp32),
("addmm", mat1_fp32 + mat2_fp32 + mat3_fp32),
("addmv", pointwise0_fp32 + mat2_fp32 + pointwise1_fp32),
("addr", mat0_fp32 + pointwise0_fp32 + pointwise1_fp32),
("matmul", mat0_fp32 + mat1_fp32),
("einsum", "bkhd,bqhd->bqkh", mat0_fp32 + mat1_fp32),
("mm", mat0_fp32 + mat1_fp32),
("mv", mat0_fp32 + pointwise0_fp32),
("chain_matmul", mat0_fp32 + mat1_fp32 + mat2_fp32),
("addbmm", mat0_fp32 + (torch.randn((n, n, n), device=dev, dtype=torch.float32),
torch.randn((n, n, n), device=dev, dtype=torch.float32))),
("baddbmm", (torch.randn((n, n, n), device=dev, dtype=torch.float32),
torch.randn((n, n, n), device=dev, dtype=torch.float32),
torch.randn((n, n, n), device=dev, dtype=torch.float32))),
("bmm", (torch.randn((n, n, n), device=dev, dtype=torch.float32),
torch.randn((n, n, n), device=dev, dtype=torch.float32))),
# _thnn_fused_lstm_cell and _thnn_fused_gru_cell are not Python-exposed as far as I can tell.
# ("_thnn_fused_lstm_cell", mat0_fp32 + mat1_fp32 + mat2_fp32 + pointwise0_fp32 + pointwise1_fp32),
# ("_thnn_fused_gru_cell", mat0_fp32 + mat1_fp32 + mat2_fp32 + pointwise0_fp32 + pointwise1_fp32),
("lstm_cell", self._rnn_cell_args(n, num_chunks=4, is_lstm=True, dev=dev, dtype=torch.float32)),
("gru_cell", self._rnn_cell_args(n, num_chunks=3, is_lstm=False, dev=dev, dtype=torch.float32)),
("rnn_tanh_cell", self._rnn_cell_args(n, num_chunks=1, is_lstm=False, dev=dev, dtype=torch.float32)),
("rnn_relu_cell", self._rnn_cell_args(n, num_chunks=1, is_lstm=False, dev=dev, dtype=torch.float32)),
]
self.torch_fp32 = [
("acos", (pointwise0_fp16[0].clamp(-.9, 0.9),)),
("asin", (pointwise0_fp16[0].clamp(-.9, 0.9),)),
("cosh", pointwise0_fp16),
("erfinv", (pointwise0_fp16[0].clamp(-.9, .9),)),
("exp", pointwise0_fp16),
("expm1", pointwise0_fp16),
("log", (pointwise0_fp16[0].clamp(0.1, 100.0),)),
("log10", (pointwise0_fp16[0].clamp(0.1, 100.0),)),
("log2", (pointwise0_fp16[0].clamp(0.1, 100.0),)),
("log1p", (pointwise0_fp16[0].clamp(-0.9, 100.0),)),
("reciprocal", pointwise0_fp16),
("rsqrt", (pointwise0_fp16[0].clamp(0.0, 100.0),)),
("sinh", pointwise0_fp16),
("tan", (pointwise0_fp16[0].clamp(-3.1 / 2, 3.1 / 2),)),
("pow", ((pointwise0_fp16[0] + 1.).clamp(0.0, 100.0),) + pointwise1_fp16),
("pow", ((pointwise0_fp16[0] + 1.).clamp(0.0, 100.0),) + (1.7,)),
# ("pow", (1.7,) + pointwise0_fp16), # This variant has a backend, but is not documented in the API.
("softmax", pointwise0_fp16 + (0,)),
("log_softmax", pointwise0_fp16 + (0,)),
("layer_norm", pointwise0_fp16 + ((pointwise0_fp16[0].numel(),),)),
("group_norm", mat0_fp16 + (1,)),
("norm", pointwise0_fp16),
("norm", pointwise0_fp16, {"dim": 0}),
# these need magma
# ("norm", mat0_fp16, {"p": "nuc"}),
# ("norm", mat0_fp16, {"p": "nuc", "dim": 0}),
("norm", pointwise0_fp16, {"p": 1}),
("norm", pointwise0_fp16, {"p": 1, "dim": 0}),
("cosine_similarity", mat0_fp16 + mat1_fp16),
("poisson_nll_loss", mat0_fp16 + mat1_fp16 + (True, False, 1.e-8, torch.nn._reduction.get_enum('mean'))),
("cosine_embedding_loss", (torch.tensor([[1, 2, 3]], device=dev, dtype=torch.float16),
torch.tensor([[1, 3, 4]], device=dev, dtype=torch.float16),
torch.tensor([1], device=dev, dtype=torch.int))),
("hinge_embedding_loss", mat0_fp16 + (torch.ones(n, device=dev, dtype=torch.int),)),
("kl_div", mat0_fp16 + (torch.rand((n, n), device=dev, dtype=torch.float16),)),
("margin_ranking_loss", mat0_fp16 + mat1_fp16 + (torch.ones((n,), device=dev, dtype=torch.float16),)),
("triplet_margin_loss", mat0_fp16 + mat1_fp16 + mat2_fp16),
("binary_cross_entropy_with_logits", mat0_fp16 + (torch.rand((n, n), device=dev, dtype=torch.float16),)),
("cumprod", pointwise0_fp16 + (0,)),
("cumsum", pointwise0_fp16 + (0,)),
("dist", pointwise0_fp16 + pointwise1_fp16),
("pdist", mat0_fp16),
("cdist", mat0_fp16 + mat1_fp16),
("prod", pointwise0_fp16),
("prod", pointwise0_fp16 + (0,)),
("renorm", mat0_fp16 + (2, 0, 1.0)),
("sum", pointwise0_fp16),
("sum", mat0_fp16 + (1,)),
("logsumexp", mat0_fp16 + (1,)),
]
self.torch_need_autocast_promote = [
("addcdiv", pointwise0_fp32 + pointwise1_fp16 + (pointwise2_fp16[0].clamp(0.1, 100),)),
("addcmul", pointwise0_fp32 + pointwise1_fp16 + pointwise2_fp16),
("atan2", pointwise0_fp32 + (pointwise1_fp16[0].clamp(0.1, 100),)),
("bilinear", (torch.randn((1, 2), dtype=torch.float16, device=dev),
torch.randn((1, 2), dtype=torch.float32, device=dev),
torch.randn((1, 2, 2), dtype=torch.float16, device=dev),
torch.randn((1,), dtype=torch.float32, device=dev))),
("cross", (torch.randn(3, dtype=torch.float32, device=dev),
torch.randn(3, dtype=torch.float16, device=dev))),
("dot", pointwise0_fp16 + pointwise1_fp32),
("vdot", pointwise0_fp16 + pointwise1_fp32),
("grid_sampler", (torch.randn((2, 3, 33, 22), dtype=torch.float16, device=dev),
torch.randn((2, 22, 11, 2), dtype=torch.float32, device=dev),
0, 0, False)),
("index_put", pointwise0_fp32 + ((torch.tensor([1], device=dev, dtype=torch.long),),
torch.randn(1, device=dev, dtype=torch.float16))),
("index_put", pointwise0_fp16 + ((torch.tensor([1], device=dev, dtype=torch.long),),
torch.randn(1, device=dev, dtype=torch.float32))),
("tensordot", (torch.randn((2, 2, 2), dtype=torch.float32, device=dev),
torch.randn((2, 2, 2), dtype=torch.float16, device=dev))),
("scatter_add", (torch.zeros(2, 2, 2, dtype=torch.float32, device=dev),
0,
torch.randint(0, 2, (2, 2, 2), device=dev),
torch.randn((2, 2, 2), dtype=torch.float16, device=dev))),
("scatter_add", (torch.zeros(2, 2, 2, dtype=torch.float16, device=dev),
0,
torch.randint(0, 2, (2, 2, 2), device=dev),
torch.randn((2, 2, 2), dtype=torch.float32, device=dev))),
]
self.nn_fp16 = [
("linear", mat0_fp32 + mat1_fp32 + mat2_fp32),
]
self.nn_fp32 = [
("softplus", pointwise0_fp16),
("nll_loss", (torch.rand((n, n), device=dev, dtype=torch.float),
torch.zeros((n,), device=dev, dtype=torch.long))),
("nll_loss2d", (torch.rand((n, n, n, n), device=dev, dtype=torch.half),
torch.zeros((n, n, n), device=dev, dtype=torch.long))),
("l1_loss", mat0_fp16 + mat1_fp16),
("smooth_l1_loss", mat0_fp16 + mat1_fp16),
("mse_loss", mat0_fp16 + mat1_fp16),
("multilabel_margin_loss", mat0_fp16 + (torch.ones((n, n), device=dev, dtype=torch.long),)),
("soft_margin_loss", mat0_fp16 + (torch.ones((n, n), device=dev, dtype=torch.long),)),
("multi_margin_loss", mat0_fp16 + (torch.ones((n,), device=dev, dtype=torch.long),)),
]
self.linalg_fp16 = [
("linalg_vecdot", mat0_fp32 + mat0_fp32),
("linalg_multi_dot", (mat0_fp32 + mat1_fp32 + mat2_fp32,)),
]
self.methods_fp16 = [
("__matmul__", mat0_fp32 + mat1_fp32)
]
self.methods_fp32 = [
("__pow__", (torch.rand(n, device=dev, dtype=torch.float16), 1.5)),
]
self.banned = [
("binary_cross_entropy", (torch.rand((n, n), device=dev, dtype=torch.float32),
torch.rand((n, n), device=dev, dtype=torch.float32)), torch._C._nn),
]
| AutocastTestLists |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/dagster_run.py | {
"start": 25926,
"end": 26539
} | class ____:
run_id: str
partition: str
status: DagsterRunStatus
start_time: Optional[float]
end_time: Optional[float]
###################################################################################################
# GRAVEYARD
#
# -|-
# |
# _-'~~~~~`-_
# .' '.
# | R I P |
# | |
# | Execution |
# | Selector |
# | |
# | |
###################################################################################################
@whitelist_for_serdes
@record
| RunPartitionData |
python | django__django | tests/model_forms/models.py | {
"start": 6534,
"end": 6655
} | class ____(models.Model):
slug = models.SlugField(unique=True)
def __str__(self):
return self.slug
| Product |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 83312,
"end": 86386
} | class ____(ASTBase):
def __init__(
self,
outer: str,
leftSpecs: ASTDeclSpecsSimple,
rightSpecs: ASTDeclSpecsSimple,
trailing: ASTTrailingTypeSpec,
) -> None:
# leftSpecs and rightSpecs are used for output
# allSpecs are used for id generation
self.outer = outer
self.leftSpecs = leftSpecs
self.rightSpecs = rightSpecs
self.allSpecs = self.leftSpecs.mergeWith(self.rightSpecs)
self.trailingTypeSpec = trailing
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTDeclSpecs):
return NotImplemented
return (
self.outer == other.outer
and self.leftSpecs == other.leftSpecs
and self.rightSpecs == other.rightSpecs
and self.trailingTypeSpec == other.trailingTypeSpec
)
def __hash__(self) -> int:
return hash((
self.outer,
self.leftSpecs,
self.rightSpecs,
self.trailingTypeSpec,
))
def get_id(self, version: int) -> str:
if version == 1:
res = [self.trailingTypeSpec.get_id(version)]
if self.allSpecs.volatile:
res.append('V')
if self.allSpecs.const:
res.append('C')
return ''.join(res)
res = []
if self.allSpecs.volatile:
res.append('V')
if self.allSpecs.const:
res.append('K')
if self.trailingTypeSpec is not None:
res.append(self.trailingTypeSpec.get_id(version))
return ''.join(res)
def _stringify(self, transform: StringifyTransform) -> str:
res: list[str] = []
l = transform(self.leftSpecs)
if len(l) > 0:
res.append(l)
if self.trailingTypeSpec:
if len(res) > 0:
res.append(' ')
res.append(transform(self.trailingTypeSpec))
r = str(self.rightSpecs)
if len(r) > 0:
if len(res) > 0:
res.append(' ')
res.append(r)
return ''.join(res)
def describe_signature(
self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
verify_description_mode(mode)
num_children = len(signode)
self.leftSpecs.describe_signature(signode, env, symbol)
add_space = len(signode) != num_children
if self.trailingTypeSpec:
if add_space:
signode += addnodes.desc_sig_space()
num_children = len(signode)
self.trailingTypeSpec.describe_signature(signode, mode, env, symbol=symbol)
add_space = len(signode) != num_children
if len(str(self.rightSpecs)) > 0:
if add_space:
signode += addnodes.desc_sig_space()
self.rightSpecs.describe_signature(signode, env, symbol)
# Declarator
################################################################################
| ASTDeclSpecs |
python | django__django | tests/template_tests/filter_tests/test_make_list.py | {
"start": 167,
"end": 1365
} | class ____(SimpleTestCase):
"""
The make_list filter can destroy existing escaping, so the results are
escaped.
"""
@setup({"make_list01": "{% autoescape off %}{{ a|make_list }}{% endautoescape %}"})
def test_make_list01(self):
output = self.engine.render_to_string("make_list01", {"a": mark_safe("&")})
self.assertEqual(output, "['&']")
@setup({"make_list02": "{{ a|make_list }}"})
def test_make_list02(self):
output = self.engine.render_to_string("make_list02", {"a": mark_safe("&")})
self.assertEqual(output, "['&']")
@setup(
{
"make_list03": (
'{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}'
"{% endautoescape %}"
)
}
)
def test_make_list03(self):
output = self.engine.render_to_string("make_list03", {"a": mark_safe("&")})
self.assertEqual(output, "['&']")
@setup({"make_list04": '{{ a|make_list|stringformat:"s"|safe }}'})
def test_make_list04(self):
output = self.engine.render_to_string("make_list04", {"a": mark_safe("&")})
self.assertEqual(output, "['&']")
| MakeListTests |
python | qdrant__qdrant-client | qdrant_client/connection.py | {
"start": 4979,
"end": 13282
} | class ____(
collections.namedtuple("_ClientCallDetails", ("method", "timeout", "metadata", "credentials")),
grpc.aio.ClientCallDetails,
):
pass
def header_adder_interceptor(
new_metadata: list[tuple[str, str]],
auth_token_provider: Optional[Callable[[], str]] = None,
) -> _GenericClientInterceptor:
def process_response(response: Any) -> Any:
if response.code() == grpc.StatusCode.RESOURCE_EXHAUSTED:
retry_after = None
for item in response.trailing_metadata():
if item.key == "retry-after":
try:
retry_after = int(item.value)
except Exception:
retry_after = None
break
reason_phrase = response.details() if response.details() else ""
if retry_after:
raise ResourceExhaustedResponse(message=reason_phrase, retry_after_s=retry_after)
return response
def intercept_call(
client_call_details: _ClientCallDetails,
request_iterator: Any,
_request_streaming: Any,
_response_streaming: Any,
) -> tuple[_ClientCallDetails, Any, Any]:
metadata = []
if client_call_details.metadata is not None:
metadata = list(client_call_details.metadata)
for header, value in new_metadata:
metadata.append(
(
header,
value,
)
)
if auth_token_provider:
if not asyncio.iscoroutinefunction(auth_token_provider):
metadata.append(("authorization", f"Bearer {auth_token_provider()}"))
else:
raise ValueError("Synchronous channel requires synchronous auth token provider.")
client_call_details = _ClientCallDetails(
client_call_details.method,
client_call_details.timeout,
metadata,
client_call_details.credentials,
)
return client_call_details, request_iterator, process_response
return create_generic_client_interceptor(intercept_call)
def header_adder_async_interceptor(
new_metadata: list[tuple[str, str]],
auth_token_provider: Optional[Union[Callable[[], str], Callable[[], Awaitable[str]]]] = None,
) -> _GenericAsyncClientInterceptor:
async def process_response(call: Any) -> Any:
try:
return await call
except grpc.aio.AioRpcError as er:
if er.code() == grpc.StatusCode.RESOURCE_EXHAUSTED:
retry_after = None
for item in er.trailing_metadata():
if item[0] == "retry-after":
try:
retry_after = int(item[1])
except Exception:
retry_after = None
break
reason_phrase = er.details() if er.details() else ""
if retry_after:
raise ResourceExhaustedResponse(
message=reason_phrase, retry_after_s=retry_after
) from er
raise
async def intercept_call(
client_call_details: grpc.aio.ClientCallDetails,
request_iterator: Any,
_request_streaming: Any,
_response_streaming: Any,
) -> tuple[_ClientAsyncCallDetails, Any, Any]:
metadata = []
if client_call_details.metadata is not None:
metadata = list(client_call_details.metadata)
for header, value in new_metadata:
metadata.append(
(
header,
value,
)
)
if auth_token_provider:
if asyncio.iscoroutinefunction(auth_token_provider):
token = await auth_token_provider()
else:
token = auth_token_provider()
metadata.append(("authorization", f"Bearer {token}"))
client_call_details = client_call_details._replace(metadata=metadata)
return client_call_details, request_iterator, process_response
return create_generic_async_client_interceptor(intercept_call)
def parse_channel_options(options: Optional[dict[str, Any]] = None) -> list[tuple[str, Any]]:
default_options: list[tuple[str, Any]] = [
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
]
if options is None:
return default_options
_options = [(option_name, option_value) for option_name, option_value in options.items()]
for option_name, option_value in default_options:
if option_name not in options:
_options.append((option_name, option_value))
return _options
def parse_ssl_credentials(options: Optional[dict[str, Any]] = None) -> dict[str, Optional[bytes]]:
"""Parse ssl credentials to create `grpc.ssl_channel_credentials` for `grpc.secure_channel`
WARN: Directly modifies input `options`
Return:
dict[str, Optional[bytes]]: dict(root_certificates=..., private_key=..., certificate_chain=...)
"""
ssl_options: dict[str, Optional[bytes]] = dict(
root_certificates=None, private_key=None, certificate_chain=None
)
if options is None:
return ssl_options
for ssl_option_name in ssl_options:
option_value: Any = options.pop(ssl_option_name, None)
if f"grpc.{ssl_option_name}" in options:
show_warning_once(
f"`{ssl_option_name}` is supposed to be used without `grpc.` prefix",
idx=f"grpc.{ssl_option_name}",
stacklevel=10,
)
if option_value is None:
continue
if not isinstance(option_value, bytes):
raise TypeError(f"{ssl_option_name} must be a byte string")
ssl_options[ssl_option_name] = option_value
return ssl_options
def get_channel(
host: str,
port: int,
ssl: bool,
metadata: Optional[list[tuple[str, str]]] = None,
options: Optional[dict[str, Any]] = None,
compression: Optional[grpc.Compression] = None,
auth_token_provider: Optional[Callable[[], str]] = None,
) -> grpc.Channel:
# Parse gRPC client options
_copied_options = (
options.copy() if options is not None else None
) # we're changing options inplace
_ssl_cred_options = parse_ssl_credentials(_copied_options)
_options = parse_channel_options(_copied_options)
metadata_interceptor = header_adder_interceptor(
new_metadata=metadata or [], auth_token_provider=auth_token_provider
)
if ssl:
ssl_creds = grpc.ssl_channel_credentials(**_ssl_cred_options)
channel = grpc.secure_channel(f"{host}:{port}", ssl_creds, _options, compression)
return grpc.intercept_channel(channel, metadata_interceptor)
else:
channel = grpc.insecure_channel(f"{host}:{port}", _options, compression)
return grpc.intercept_channel(channel, metadata_interceptor)
def get_async_channel(
host: str,
port: int,
ssl: bool,
metadata: Optional[list[tuple[str, str]]] = None,
options: Optional[dict[str, Any]] = None,
compression: Optional[grpc.Compression] = None,
auth_token_provider: Optional[Union[Callable[[], str], Callable[[], Awaitable[str]]]] = None,
) -> grpc.aio.Channel:
# Parse gRPC client options
_copied_options = (
options.copy() if options is not None else None
) # we're changing options inplace
_ssl_cred_options = parse_ssl_credentials(_copied_options)
_options = parse_channel_options(_copied_options)
# Create metadata interceptor
metadata_interceptor = header_adder_async_interceptor(
new_metadata=metadata or [], auth_token_provider=auth_token_provider
)
if ssl:
ssl_creds = grpc.ssl_channel_credentials(**_ssl_cred_options)
return grpc.aio.secure_channel(
f"{host}:{port}",
ssl_creds,
_options,
compression,
interceptors=[metadata_interceptor],
)
else:
return grpc.aio.insecure_channel(
f"{host}:{port}", _options, compression, interceptors=[metadata_interceptor]
)
| _ClientAsyncCallDetails |
python | pypa__pip | src/pip/_internal/utils/logging.py | {
"start": 7173,
"end": 7377
} | class ____(Filter):
def __init__(self, level: int) -> None:
self.level = level
def filter(self, record: logging.LogRecord) -> bool:
return record.levelno < self.level
| MaxLevelFilter |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_c.py | {
"start": 4702,
"end": 5542
} | class ____(ctypes.Structure):
"""
Structure representation of the inotify_event structure
(used in buffer size calculations)::
struct inotify_event {
__s32 wd; /* watch descriptor */
__u32 mask; /* watch mask */
__u32 cookie; /* cookie to synchronize two events */
__u32 len; /* length (including nulls) of name */
char name[0]; /* stub for possible name */
};
"""
_fields_ = [('wd', c_int),
('mask', c_uint32),
('cookie', c_uint32),
('len', c_uint32),
('name', c_char_p)]
EVENT_SIZE = ctypes.sizeof(inotify_event_struct)
DEFAULT_NUM_EVENTS = 2048
DEFAULT_EVENT_BUFFER_SIZE = DEFAULT_NUM_EVENTS * (EVENT_SIZE + 16)
| inotify_event_struct |
python | tiangolo__fastapi | tests/test_response_model_default_factory.py | {
"start": 127,
"end": 1264
} | class ____(BaseModel):
code: int = 200
message: str = Field(default_factory=lambda: "Successful operation.")
@app.get(
"/response_model_has_default_factory_return_dict",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_dict():
return {"code": 200}
@app.get(
"/response_model_has_default_factory_return_model",
response_model=ResponseModel,
)
async def response_model_has_default_factory_return_model():
return ResponseModel()
client = TestClient(app)
def test_response_model_has_default_factory_return_dict():
response = client.get("/response_model_has_default_factory_return_dict")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] == "Successful operation."
def test_response_model_has_default_factory_return_model():
response = client.get("/response_model_has_default_factory_return_model")
assert response.status_code == 200, response.text
assert response.json()["code"] == 200
assert response.json()["message"] == "Successful operation."
| ResponseModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/error_response_builder.py | {
"start": 195,
"end": 580
} | class ____:
def __init__(self, status_code: int):
self._status_code: int = status_code
@classmethod
def response_with_status(cls, status_code) -> "ErrorResponseBuilder":
return cls(status_code)
def build(self) -> HttpResponse:
return HttpResponse(json.dumps(find_template(str(self._status_code), __file__)), self._status_code)
| ErrorResponseBuilder |
python | scrapy__scrapy | scrapy/commands/check.py | {
"start": 352,
"end": 1163
} | class ____(_TextTestResult):
def printSummary(self, start: float, stop: float) -> None:
write = self.stream.write
writeln = self.stream.writeln
run = self.testsRun
plural = "s" if run != 1 else ""
writeln(self.separator2)
writeln(f"Ran {run} contract{plural} in {stop - start:.3f}s")
writeln()
infos = []
if not self.wasSuccessful():
write("FAILED")
failed, errored = map(len, (self.failures, self.errors))
if failed:
infos.append(f"failures={failed}")
if errored:
infos.append(f"errors={errored}")
else:
write("OK")
if infos:
writeln(f" ({', '.join(infos)})")
else:
write("\n")
| TextTestResult |
python | run-llama__llama_index | llama-index-core/llama_index/core/download/module.py | {
"start": 684,
"end": 9564
} | class ____(str, Enum):
LOADER = "loader"
TOOL = "tool"
LLAMAPACK = "llamapack"
DATASETS = "datasets"
def get_module_info(
local_dir_path: PATH_TYPE,
remote_dir_path: PATH_TYPE,
module_class: str,
refresh_cache: bool = False,
library_path: str = "library.json",
disable_library_cache: bool = False,
) -> Dict:
"""Get module info."""
if isinstance(local_dir_path, str):
local_dir_path = Path(local_dir_path)
local_library_path = f"{local_dir_path}/{library_path}"
module_id = None # e.g. `web/simple_web`
extra_files = [] # e.g. `web/simple_web/utils.py`
# Check cache first
if not refresh_cache and os.path.exists(local_library_path):
with open(local_library_path) as f:
library = json.load(f)
if module_class in library:
module_id = library[module_class]["id"]
extra_files = library[module_class].get("extra_files", [])
# Fetch up-to-date library from remote repo if module_id not found
if module_id is None:
library_raw_content, _ = get_file_content(
str(remote_dir_path), f"/{library_path}"
)
library = json.loads(library_raw_content)
if module_class not in library:
raise ValueError("Loader class name not found in library")
module_id = library[module_class]["id"]
extra_files = library[module_class].get("extra_files", [])
# create cache dir if needed
local_library_dir = os.path.dirname(local_library_path)
if not disable_library_cache:
if not os.path.exists(local_library_dir):
os.makedirs(local_library_dir)
# Update cache
with open(local_library_path, "w") as f:
f.write(library_raw_content)
if module_id is None:
raise ValueError("Loader class name not found in library")
return {
"module_id": module_id,
"extra_files": extra_files,
}
def download_module_and_reqs(
local_dir_path: PATH_TYPE,
remote_dir_path: PATH_TYPE,
module_id: str,
extra_files: List[str],
refresh_cache: bool = False,
use_gpt_index_import: bool = False,
base_file_name: str = "base.py",
override_path: bool = False,
) -> None:
"""Load module."""
if isinstance(local_dir_path, str):
local_dir_path = Path(local_dir_path)
if override_path:
module_path = str(local_dir_path)
else:
module_path = f"{local_dir_path}/{module_id}"
if refresh_cache or not os.path.exists(module_path):
os.makedirs(module_path, exist_ok=True)
basepy_raw_content, _ = get_file_content(
str(remote_dir_path), f"/{module_id}/{base_file_name}"
)
if use_gpt_index_import:
basepy_raw_content = basepy_raw_content.replace(
"import llama_index.core", "import llama_index.core"
)
basepy_raw_content = basepy_raw_content.replace(
"from llama_index", "from llama_index"
)
with open(f"{module_path}/{base_file_name}", "w") as f:
f.write(basepy_raw_content)
# Get content of extra files if there are any
# and write them under the loader directory
for extra_file in extra_files:
extra_file_raw_content, _ = get_file_content(
str(remote_dir_path), f"/{module_id}/{extra_file}"
)
# If the extra file is an __init__.py file, we need to
# add the exports to the __init__.py file in the modules directory
if extra_file == "__init__.py":
loader_exports = get_exports(extra_file_raw_content)
existing_exports = []
init_file_path = local_dir_path / "__init__.py"
# if the __init__.py file do not exists, we need to create it
mode = "a+" if not os.path.exists(init_file_path) else "r+"
with open(init_file_path, mode) as f:
f.write(f"from .{module_id} import {', '.join(loader_exports)}")
existing_exports = get_exports(f.read())
rewrite_exports(existing_exports + loader_exports, str(local_dir_path))
with open(f"{module_path}/{extra_file}", "w") as f:
f.write(extra_file_raw_content)
# install requirements
requirements_path = f"{local_dir_path}/requirements.txt"
if not os.path.exists(requirements_path):
# NOTE: need to check the status code
response_txt, status_code = get_file_content(
str(remote_dir_path), f"/{module_id}/requirements.txt"
)
if status_code == 200:
with open(requirements_path, "w") as f:
f.write(response_txt)
# Install dependencies if there are any and not already installed
if os.path.exists(requirements_path):
import pkg_resources
from pkg_resources import DistributionNotFound
try:
requirements = pkg_resources.parse_requirements(
Path(requirements_path).open()
)
pkg_resources.require([str(r) for r in requirements])
except DistributionNotFound:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "-r", requirements_path]
)
def download_llama_module(
module_class: str,
llama_hub_url: str = LLAMA_HUB_URL,
refresh_cache: bool = False,
custom_dir: Optional[str] = None,
custom_path: Optional[str] = None,
library_path: str = "library.json",
base_file_name: str = "base.py",
use_gpt_index_import: bool = False,
disable_library_cache: bool = False,
override_path: bool = False,
skip_load: bool = False,
) -> Any:
"""
Download a module from LlamaHub.
Can be a loader, tool, pack, or more.
Args:
loader_class: The name of the llama module class you want to download,
such as `GmailOpenAIAgentPack`.
refresh_cache: If true, the local cache will be skipped and the
loader will be fetched directly from the remote repo.
custom_dir: Custom dir name to download loader into (under parent folder).
custom_path: Custom dirpath to download loader into.
library_path: File name of the library file.
use_gpt_index_import: If true, the loader files will use
llama_index as the base dependency. By default (False),
the loader files use llama_index as the base dependency.
NOTE: this is a temporary workaround while we fully migrate all usages
to llama_index.core.
is_dataset: whether or not downloading a LlamaDataset
Returns:
A Loader, A Pack, An Agent, or A Dataset
"""
# create directory / get path
dirpath = initialize_directory(custom_path=custom_path, custom_dir=custom_dir)
# fetch info from library.json file
module_info = get_module_info(
local_dir_path=dirpath,
remote_dir_path=llama_hub_url,
module_class=module_class,
refresh_cache=refresh_cache,
library_path=library_path,
disable_library_cache=disable_library_cache,
)
module_id = module_info["module_id"]
extra_files = module_info["extra_files"]
# download the module, install requirements
download_module_and_reqs(
local_dir_path=dirpath,
remote_dir_path=llama_hub_url,
module_id=module_id,
extra_files=extra_files,
refresh_cache=refresh_cache,
use_gpt_index_import=use_gpt_index_import,
base_file_name=base_file_name,
override_path=override_path,
)
if skip_load:
return None
# loads the module into memory
if override_path:
path = f"{dirpath}/{base_file_name}"
spec = util.spec_from_file_location("custom_module", location=path)
if spec is None:
raise ValueError(f"Could not find file: {path}.")
else:
path = f"{dirpath}/{module_id}/{base_file_name}"
spec = util.spec_from_file_location("custom_module", location=path)
if spec is None:
raise ValueError(f"Could not find file: {path}.")
module = util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore
return getattr(module, module_class)
def track_download(module_class: str, module_type: str) -> None:
"""
Tracks number of downloads via Llamahub proxy.
Args:
module_class: The name of the llama module being downloaded, e.g.,`GmailOpenAIAgentPack`.
module_type: Can be "loader", "tool", "llamapack", or "datasets"
"""
try:
requests.post(
LLAMAHUB_ANALYTICS_PROXY_SERVER,
json={"type": module_type, "plugin": module_class},
)
except Exception as e:
logger.info(f"Error tracking downloads for {module_class} : {e}")
| MODULE_TYPE |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 1935,
"end": 2120
} | class ____(BaseModel):
type: Literal["logprobs.refusal.delta"]
refusal: List[ChatCompletionTokenLogprob]
snapshot: List[ChatCompletionTokenLogprob]
| LogprobsRefusalDeltaEvent |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 6964,
"end": 8463
} | class ____(BaseStrategy):
"""
This is a Redhat Hostname strategy class - it edits the
/etc/sysconfig/network file.
"""
NETWORK_FILE = '/etc/sysconfig/network'
def get_permanent_hostname(self):
try:
for line in get_file_lines(self.NETWORK_FILE):
line = to_native(line).strip()
if line.startswith('HOSTNAME'):
k, v = line.split('=')
return v.strip()
self.module.fail_json(
"Unable to locate HOSTNAME entry in %s" % self.NETWORK_FILE
)
except Exception as e:
self.module.fail_json(
msg="failed to read hostname: %s" % to_native(e))
def set_permanent_hostname(self, name):
try:
lines = []
found = False
content = get_file_content(self.NETWORK_FILE, strip=False) or ""
for line in content.splitlines(True):
line = to_native(line)
if line.strip().startswith('HOSTNAME'):
lines.append("HOSTNAME=%s\n" % name)
found = True
else:
lines.append(line)
if not found:
lines.append("HOSTNAME=%s\n" % name)
with open(self.NETWORK_FILE, 'w+') as f:
f.writelines(lines)
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" % to_native(e))
| RedHatStrategy |
python | viewflow__viewflow | viewflow/urls/model.py | {
"start": 6644,
"end": 7074
} | class ____(
ListBulkActionsMixin,
CreateViewMixin,
UpdateViewMixin,
AppMenuMixin,
BaseModelViewset,
):
"""List/Create/Update/Delete for a model."""
def get_object_url(self, request, obj):
if self.has_change_permission(request.user, obj):
return self.reverse("change", args=[obj.pk])
def get_success_url(self, request, obj=None):
return self.reverse("index")
| ModelViewset |
python | prakhar1989__Algorithms | tests/modular_exponentiation_test.py | {
"start": 137,
"end": 661
} | class ____(unittest.TestCase):
def test_modular_exponentiation(self):
self.assertEqual(me.modular_exponentiation(2, 10, 100), 24)
self.assertEqual(me.modular_exponentiation(2, 200, 10), 6)
self.assertEqual(me.modular_exponentiation(5, 20, 1), 0)
#self.assertEqual(me.modular_exponentiation(8, 1, 10), 8)
self.assertRaises(ValueError, me.modular_exponentiation, 12, -1, 10)
self.assertRaises(ValueError, me.modular_exponentiation, 12, 5, 0)
if __name__ == "__main__":
unittest.main() | TestLCS |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 222846,
"end": 225247
} | class ____(unittest.TestCase):
@unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
"SOCK_CLOEXEC not defined")
@support.requires_linux_version(2, 6, 28)
def test_SOCK_CLOEXEC(self):
with socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
self.assertEqual(s.type, socket.SOCK_STREAM)
self.assertFalse(s.get_inheritable())
def test_default_inheritable(self):
sock = socket.socket()
with sock:
self.assertEqual(sock.get_inheritable(), False)
def test_dup(self):
sock = socket.socket()
with sock:
newsock = sock.dup()
sock.close()
with newsock:
self.assertEqual(newsock.get_inheritable(), False)
def test_set_inheritable(self):
sock = socket.socket()
with sock:
sock.set_inheritable(True)
self.assertEqual(sock.get_inheritable(), True)
sock.set_inheritable(False)
self.assertEqual(sock.get_inheritable(), False)
@unittest.skipIf(fcntl is None, "need fcntl")
def test_get_inheritable_cloexec(self):
sock = socket.socket()
with sock:
fd = sock.fileno()
self.assertEqual(sock.get_inheritable(), False)
# clear FD_CLOEXEC flag
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(fd, fcntl.F_SETFD, flags)
self.assertEqual(sock.get_inheritable(), True)
@unittest.skipIf(fcntl is None, "need fcntl")
def test_set_inheritable_cloexec(self):
sock = socket.socket()
with sock:
fd = sock.fileno()
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
fcntl.FD_CLOEXEC)
sock.set_inheritable(True)
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
0)
def test_socketpair(self):
s1, s2 = socket.socketpair()
self.addCleanup(s1.close)
self.addCleanup(s2.close)
self.assertEqual(s1.get_inheritable(), False)
self.assertEqual(s2.get_inheritable(), False)
@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
"SOCK_NONBLOCK not defined")
| InheritanceTest |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 2098,
"end": 6699
} | class ____(IntegrationBase):
def test_basic(self):
res = self.testapp.get('/minimal.txt', status=200)
_assertBody(res.body, os.path.join(here, 'fixtures/minimal.txt'))
def test_hidden(self):
res = self.testapp.get('/static/.hiddenfile', status=200)
_assertBody(
res.body, os.path.join(here, 'fixtures/static/.hiddenfile')
)
if defaultlocale is not None: # pragma: no cover
# These tests are expected to fail on LANG=C systems due to decode
# errors and on non-Linux systems due to git highchar handling
# vagaries
def test_highchars_in_pathelement(self):
path = os.path.join(
here, text_('fixtures/static/héhé/index.html', 'utf-8')
)
pathdir = os.path.dirname(path)
body = b'<html>hehe</html>\n'
try:
os.makedirs(pathdir)
with open(path, 'wb') as fp:
fp.write(body)
url = quote('/static/héhé/index.html')
res = self.testapp.get(url, status=200)
self.assertEqual(res.body, body)
finally:
os.unlink(path)
os.rmdir(pathdir)
def test_highchars_in_filename(self):
path = os.path.join(
here, text_('fixtures/static/héhé.html', 'utf-8')
)
body = b'<html>hehe file</html>\n'
with open(path, 'wb') as fp:
fp.write(body)
try:
url = quote('/static/héhé.html')
res = self.testapp.get(url, status=200)
self.assertEqual(res.body, body)
finally:
os.unlink(path)
def test_not_modified(self):
self.testapp.extra_environ = {
'HTTP_IF_MODIFIED_SINCE': httpdate(fiveyrsfuture)
}
res = self.testapp.get('/minimal.txt', status=304)
self.assertEqual(res.body, b'')
def test_file_in_subdir(self):
fn = os.path.join(here, 'fixtures/static/index.html')
res = self.testapp.get('/static/index.html', status=200)
_assertBody(res.body, fn)
def test_directory_noslash_redir(self):
res = self.testapp.get('/static', status=301)
self.assertEqual(res.headers['Location'], 'http://localhost/static/')
def test_directory_noslash_redir_preserves_qs(self):
res = self.testapp.get('/static?a=1&b=2', status=301)
self.assertEqual(
res.headers['Location'], 'http://localhost/static/?a=1&b=2'
)
def test_directory_noslash_redir_with_scriptname(self):
self.testapp.extra_environ = {'SCRIPT_NAME': '/script_name'}
res = self.testapp.get('/static', status=301)
self.assertEqual(
res.headers['Location'], 'http://localhost/script_name/static/'
)
def test_directory_withslash(self):
fn = os.path.join(here, 'fixtures/static/index.html')
res = self.testapp.get('/static/', status=200)
_assertBody(res.body, fn)
def test_range_inclusive(self):
self.testapp.extra_environ = {'HTTP_RANGE': 'bytes=1-2'}
res = self.testapp.get('/static/index.html', status=206)
self.assertEqual(res.body, b'ht')
def test_range_tilend(self):
self.testapp.extra_environ = {'HTTP_RANGE': 'bytes=-5'}
res = self.testapp.get('/static/index.html', status=206)
self.assertEqual(res.body, b'html>')
def test_range_notbytes(self):
self.testapp.extra_environ = {'HTTP_RANGE': 'kHz=-5'}
res = self.testapp.get('/static/index.html', status=200)
_assertBody(res.body, os.path.join(here, 'fixtures/static/index.html'))
def test_range_multiple(self):
res = self.testapp.get(
'/static/index.html',
[('HTTP_RANGE', 'bytes=10-11,11-12')],
status=200,
)
_assertBody(res.body, os.path.join(here, 'fixtures/static/index.html'))
def test_range_oob(self):
self.testapp.extra_environ = {'HTTP_RANGE': 'bytes=1000-1002'}
self.testapp.get('/static/index.html', status=416)
def test_notfound(self):
self.testapp.get('/static/wontbefound.html', status=404)
def test_oob_dotdotslash(self):
self.testapp.get('/static/../../test_integration.py', status=404)
def test_oob_dotdotslash_encoded(self):
self.testapp.get('/static/%2E%2E%2F/test_integration.py', status=404)
def test_oob_slash(self):
self.testapp.get('/%2F/test_integration.py', status=404)
| StaticAppBase |
python | ray-project__ray | doc/source/train/doc_code/checkpoints.py | {
"start": 10286,
"end": 16967
} | class ____(TrainerCallback):
def __init__(self):
super().__init__()
self.metrics = {}
def on_log(self, args, state, control, model=None, logs=None, **kwargs):
"""Log is called on evaluation step and logging step."""
self.metrics.update(logs)
def on_save(self, args, state, control, **kwargs):
"""Event called after a checkpoint save."""
checkpoint = None
if train.get_context().get_world_rank() == 0:
# Build a Ray Train Checkpoint from the latest checkpoint
checkpoint_path = transformers.trainer.get_last_checkpoint(args.output_dir)
checkpoint = Checkpoint.from_directory(checkpoint_path)
# Report to Ray Train with up-to-date metrics
ray.train.report(metrics=self.metrics, checkpoint=checkpoint)
# Clear the metrics buffer
self.metrics = {}
# __transformers_custom_save_example_end__
# __distributed_checkpointing_start__
from ray import train
from ray.train import Checkpoint
from ray.train.torch import TorchTrainer
def train_func(config):
...
with tempfile.TemporaryDirectory() as temp_checkpoint_dir:
rank = train.get_context().get_world_rank()
torch.save(
...,
os.path.join(temp_checkpoint_dir, f"model-rank={rank}.pt"),
)
checkpoint = Checkpoint.from_directory(temp_checkpoint_dir)
train.report(metrics, checkpoint=checkpoint)
trainer = TorchTrainer(
train_func,
scaling_config=train.ScalingConfig(num_workers=2),
run_config=train.RunConfig(storage_path="s3://bucket/"),
)
# The checkpoint in cloud storage will contain: model-rank=0.pt, model-rank=1.pt
# __distributed_checkpointing_end__
# __inspect_checkpoint_example_start__
from pathlib import Path
from ray.train import Checkpoint
# For demonstration, create a locally available directory with a `model.pt` file.
example_checkpoint_dir = Path("/tmp/test-checkpoint")
example_checkpoint_dir.mkdir()
example_checkpoint_dir.joinpath("model.pt").touch()
# Create the checkpoint, which is a reference to the directory.
checkpoint = Checkpoint.from_directory(example_checkpoint_dir)
# Inspect the checkpoint's contents with either `as_directory` or `to_directory`:
with checkpoint.as_directory() as checkpoint_dir:
assert Path(checkpoint_dir).joinpath("model.pt").exists()
checkpoint_dir = checkpoint.to_directory()
assert Path(checkpoint_dir).joinpath("model.pt").exists()
# __inspect_checkpoint_example_end__
# __inspect_transformers_checkpoint_example_start__
# After training finished
checkpoint = result.checkpoint
with checkpoint.as_directory() as checkpoint_dir:
hf_checkpoint_path = f"{checkpoint_dir}/checkpoint/"
# __inspect_transformers_checkpoint_example_end__
# __inspect_lightning_checkpoint_example_start__
# After training finished
checkpoint = result.checkpoint
with checkpoint.as_directory() as checkpoint_dir:
lightning_checkpoint_path = f"{checkpoint_dir}/checkpoint.ckpt"
# __inspect_lightning_checkpoint_example_end__
# __checkpoint_upload_mode_sync_start__
def train_fn(config):
...
metrics = {...}
with tempfile.TemporaryDirectory() as tmpdir:
... # Save checkpoint to tmpdir
checkpoint = Checkpoint.from_directory(tmpdir)
train.report(
metrics,
checkpoint=checkpoint,
checkpoint_upload_mode=train.CheckpointUploadMode.SYNC,
)
# __checkpoint_upload_mode_sync_end__
# __checkpoint_upload_mode_async_start__
def train_fn(config):
...
metrics = {...}
tmpdir = tempfile.mkdtemp()
... # Save checkpoint to tmpdir
checkpoint = Checkpoint.from_directory(tmpdir)
train.report(
metrics,
checkpoint=checkpoint,
checkpoint_upload_mode=train.CheckpointUploadMode.ASYNC,
)
# __checkpoint_upload_mode_async_end__
# __checkpoint_upload_mode_no_upload_start__
from s3torchconnector.dcp import S3StorageWriter
from torch.distributed.checkpoint.state_dict_saver import save
from torch.distributed.checkpoint.state_dict import get_state_dict
def train_fn(config):
...
for epoch in range(config["num_epochs"]):
# Directly upload checkpoint to s3 with Torch
model, optimizer = ...
storage_context = ray.train.get_context().get_storage()
checkpoint_path = (
f"s3://{storage_context.build_checkpoint_path_from_name(str(epoch))}"
)
storage_writer = S3StorageWriter(region="us-west-2", path=checkpoint_path)
model_dict, opt_dict = get_state_dict(model=model, optimizers=optimizer)
save(
{"model": model_dict, "opt": opt_dict},
storage_writer=storage_writer,
)
# Report that checkpoint to Ray Train
metrics = {...}
checkpoint = Checkpoint(checkpoint_path)
train.report(
metrics,
checkpoint=checkpoint,
checkpoint_upload_mode=train.CheckpointUploadMode.NO_UPLOAD,
)
# __checkpoint_upload_mode_no_upload_end__
# __checkpoint_upload_function_start__
from torch.distributed.checkpoint.state_dict_saver import async_save
from s3torchconnector.dcp import S3StorageWriter
from torch.distributed.checkpoint.state_dict import get_state_dict
from ray import train
from ray.train import Checkpoint
def train_fn(config):
...
for epoch in config["num_epochs"]:
# Start async checkpoint upload to s3 with Torch
model, optimizer = ...
storage_context = train.get_context().get_storage()
checkpoint_path = (
f"s3://{storage_context.build_checkpoint_path_from_name(str(epoch))}"
)
storage_writer = S3StorageWriter(region="us-west-2", path=checkpoint_path)
model_dict, opt_dict = get_state_dict(model=model, optimizers=optimizer)
ckpt_ref = async_save(
{"model": model_dict, "opt": opt_dict},
storage_writer=storage_writer,
)
def wait_async_save(checkpoint, checkpoint_dir_name):
# This function waits for checkpoint to be finalized before returning it as is
ckpt_ref.result()
return checkpoint
# Ray Train kicks off a thread that waits for the async checkpoint upload to complete
# before reporting the checkpoint
metrics = {...}
checkpoint = Checkpoint(checkpoint_path)
train.report(
metrics=metrics,
checkpoint=checkpoint,
checkpoint_upload_mode=train.CheckpointUploadMode.ASYNC,
checkpoint_upload_function=wait_async_save,
)
# __checkpoint_upload_function_end__
| MyTrainReportCallback |
python | celery__celery | celery/backends/database/models.py | {
"start": 1611,
"end": 2432
} | class ____(Task):
"""For the extend result."""
__tablename__ = 'celery_taskmeta'
__table_args__ = {'sqlite_autoincrement': True, 'extend_existing': True}
name = sa.Column(sa.String(155), nullable=True)
args = sa.Column(sa.LargeBinary, nullable=True)
kwargs = sa.Column(sa.LargeBinary, nullable=True)
worker = sa.Column(sa.String(155), nullable=True)
retries = sa.Column(sa.Integer, nullable=True)
queue = sa.Column(sa.String(155), nullable=True)
def to_dict(self):
task_dict = super().to_dict()
task_dict.update({
'name': self.name,
'args': self.args,
'kwargs': self.kwargs,
'worker': self.worker,
'retries': self.retries,
'queue': self.queue,
})
return task_dict
| TaskExtended |
python | joke2k__faker | faker/providers/phone_number/hr_HR/__init__.py | {
"start": 49,
"end": 803
} | class ____(PhoneNumberProvider):
formats = (
"01 #### ###",
"020 ### ###",
"021 ### ###",
"022 ### ###",
"023 ### ###",
"031 ### ###",
"032 ### ###",
"033 ### ###",
"034 ### ###",
"035 ### ###",
"040 ### ###",
"042 ### ###",
"043 ### ###",
"044 ### ###",
"047 ### ###",
"048 ### ###",
"049 ### ###",
"051 ### ###",
"052 ### ###",
"053 ### ###",
"060 ### ###",
"072 ### ###",
"074 ### ###",
"091 #### ###",
"092 #### ###",
"095 #### ###",
"097 #### ###",
"098 #### ###",
"099 #### ###",
"0800 ## ##",
)
| Provider |
python | sympy__sympy | sympy/polys/compatibility.py | {
"start": 12557,
"end": 71705
} | class ____(Generic[Er]):
gens: tuple[PolyElement[Er], ...]
symbols: tuple[Expr, ...]
ngens: int
domain: Domain[Er]
order: MonomialOrder
@abstractmethod
def drop(self, *gens: PolyElement[Er] | int | str) -> PolyRing[Er] | Domain[Er]: ...
@overload
def clone(
self,
symbols: Expr | list[Expr] | tuple[Expr, ...] | None = None,
domain: None = None,
order: None = None,
) -> PolyRing[Er]: ...
@overload
def clone(
self,
symbols: Expr | list[Expr] | tuple[Expr, ...] | None = None,
*,
domain: Domain[Es],
order: None = None,
) -> PolyRing[Es]: ...
@overload
def clone(
self,
symbols: Expr | list[Expr] | tuple[Expr, ...] | None = None,
*,
domain: PolyRing[Es],
order: None = None,
) -> PolyRing[PolyElement[Es]]: ...
# Ring operations and cloning
@abstractmethod
def clone(
self,
symbols: Expr | list[Expr] | tuple[Expr, ...] | None = None,
domain: PolyRing[Es] | Domain[Es] | None = None,
order: str | MonomialOrder | None = None,
) -> PolyRing[Er] | PolyRing[Es] | PolyRing[PolyElement[Es]]: ...
@overload
def __getitem__(self, key: int) -> PolyRing[Er]: ...
@overload
def __getitem__(self, key: slice) -> PolyRing[Er] | Domain[Er]: ...
@abstractmethod
def __getitem__(self, key: slice | int) -> PolyRing[Er] | Domain[Er]: ...
@abstractmethod
def to_ground(self) -> PolyRing[Any]: ...
@abstractmethod
def ground_new(self, coeff: Er | int) -> PolyElement[Er]: ...
@abstractmethod
def domain_new(self, element: Er | int) -> Er: ...
@abstractmethod
def from_dict(
self,
element: Mapping[tuple[int, ...], int | Er | Expr],
orig_domain: Domain[Er] | None = None,
) -> PolyElement[Er]: ...
def wrap(self, element: cPoly[Er]) -> PolyElement[Er]:
from sympy.polys.rings import PolyElement
if isinstance(element, PolyElement):
if element.ring == self:
return cast("PolyElement[Er]", element)
else:
raise NotImplementedError("domain conversions")
else:
return self.ground_new(element)
def to_dense(self, element: cPoly[Er]) -> dmp[Er]:
return self.wrap(element).to_dense()
def from_dense(self, element: dmp[Er]) -> PolyElement[Er]:
d = dmp_to_dict(element, self.ngens - 1, self.domain)
return self.from_dict(d)
def to_dup(self, element: cPoly[Er]) -> dup[Er]:
return self.wrap(element).to_dup()
def from_dup(self, element: dup[Er]) -> PolyElement[Er]:
return self.from_dict(dup_to_dict(element, self.domain)) # type: ignore
def dup_add_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dup(dup_add_term(self.to_dup(f), c, i, self.domain))
def dmp_add_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dense(
dmp_add_term(
self.to_dense(f),
self.wrap(c)._drop_multi(0).to_dense(),
i,
self.ngens - 1,
self.domain,
)
)
def dup_sub_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dup(dup_sub_term(self.to_dup(f), c, i, self.domain))
def dmp_sub_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dense(
dmp_sub_term(
self.to_dense(f),
self.wrap(c)._drop_multi(0).to_dense(),
i,
self.ngens - 1,
self.domain,
)
)
def dup_mul_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dup(dup_mul_term(self.to_dup(f), c, i, self.domain))
def dmp_mul_term(self, f: cPoly[Er], c: Er, i: int) -> PolyElement[Er]:
return self.from_dense(
dmp_mul_term(
self.to_dense(f),
self.wrap(c)._drop_multi(0).to_dense(),
i,
self.ngens - 1,
self.domain,
)
)
def dup_add_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dup(dup_add_ground(self.to_dup(f), c, self.domain))
def dmp_add_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dense(
dmp_add_ground(self.to_dense(f), c, self.ngens - 1, self.domain)
)
def dup_sub_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dup(dup_sub_ground(self.to_dup(f), c, self.domain))
def dmp_sub_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dense(
dmp_sub_ground(self.to_dense(f), c, self.ngens - 1, self.domain)
)
def dup_mul_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dup(dup_mul_ground(self.to_dup(f), c, self.domain))
def dmp_mul_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dense(
dmp_mul_ground(self.to_dense(f), c, self.ngens - 1, self.domain)
)
def dup_quo_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dup(dup_quo_ground(self.to_dup(f), c, self.domain))
def dmp_quo_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dense(
dmp_quo_ground(self.to_dense(f), c, self.ngens - 1, self.domain)
)
def dup_exquo_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dup(dup_exquo_ground(self.to_dup(f), c, self.domain))
def dmp_exquo_ground(self, f: cPoly[Er], c: Er) -> PolyElement[Er]:
return self.from_dense(
dmp_exquo_ground(self.to_dense(f), c, self.ngens - 1, self.domain)
)
def dup_lshift(self, f: cPoly[Er], n: int) -> PolyElement[Er]:
return self.from_dup(dup_lshift(self.to_dup(f), n, self.domain))
def dup_rshift(self, f: cPoly[Er], n: int) -> PolyElement[Er]:
return self.from_dup(dup_rshift(self.to_dup(f), n, self.domain))
def dup_abs(self, f: cPoly[Er]) -> PolyElement[Er]:
# XXX: abs not defined for all domains
return self.from_dup(dup_abs(self.to_dup(f), self.domain)) # type: ignore
def dmp_abs(self, f: cPoly[Er]) -> PolyElement[Er]:
# XXX: abs not defined for all domains
return self.from_dense(dmp_abs(self.to_dense(f), self.ngens - 1, self.domain)) # type: ignore
def dup_neg(self, f: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_neg(self.to_dup(f), self.domain))
def dmp_neg(self, f: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(dmp_neg(self.to_dense(f), self.ngens - 1, self.domain))
def dup_add(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_add(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_add(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_add(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_sub(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_sub(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_sub(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_add_mul(self, f: cPoly[Er], g: cPoly[Er], h: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(
dup_add_mul(self.to_dup(f), self.to_dup(g), self.to_dup(h), self.domain)
)
def dmp_add_mul(self, f: cPoly[Er], g: cPoly[Er], h: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_add_mul(
self.to_dense(f),
self.to_dense(g),
self.to_dense(h),
self.ngens - 1,
self.domain,
)
)
def dup_sub_mul(self, f: cPoly[Er], g: cPoly[Er], h: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(
dup_sub_mul(self.to_dup(f), self.to_dup(g), self.to_dup(h), self.domain)
)
def dmp_sub_mul(self, f: cPoly[Er], g: cPoly[Er], h: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_sub_mul(
self.to_dense(f),
self.to_dense(g),
self.to_dense(h),
self.ngens - 1,
self.domain,
)
)
def dup_mul(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_mul(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_mul(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_sqr(self, f: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_sqr(self.to_dup(f), self.domain))
def dmp_sqr(self, f: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens - 1, self.domain))
def dup_pow(self, f: cPoly[Er], n: int) -> PolyElement[Er]:
return self.from_dup(dup_pow(self.to_dup(f), n, self.domain))
def dmp_pow(self, f: cPoly[Er], n: int) -> PolyElement[Er]:
return self.from_dense(
dmp_pow(self.to_dense(f), n, self.ngens - 1, self.domain)
)
def dup_pdiv(self, f: cPoly[Er], g: cPoly[Er]):
q, r = dup_pdiv(self.to_dup(f), self.to_dup(g), self.domain)
return (self.from_dup(q), self.from_dup(r))
def dup_prem(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_prem(self.to_dup(f), self.to_dup(g), self.domain))
def dup_pquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_pquo(self.to_dup(f), self.to_dup(g), self.domain))
def dup_pexquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_pexquo(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_pdiv(
self, f: cPoly[Er], g: cPoly[Er]
) -> tuple[PolyElement[Er], PolyElement[Er]]:
q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return (self.from_dense(q), self.from_dense(r))
def dmp_prem(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dmp_pquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dmp_pexquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_rr_div(
self: IPolys[Eeuclid], f: cPoly[Eeuclid], g: cPoly[Eeuclid]
) -> tuple[PolyElement[Eeuclid], PolyElement[Eeuclid]]:
q, r = dup_rr_div(self.to_dup(f), self.to_dup(g), self.domain)
return (self.from_dup(q), self.from_dup(r))
def dmp_rr_div(
self: IPolys[Eeuclid], f: cPoly[Eeuclid], g: cPoly[Eeuclid]
) -> tuple[PolyElement[Eeuclid], PolyElement[Eeuclid]]:
q, r = dmp_rr_div(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(q), self.from_dense(r))
def dup_ff_div(
self: IPolys[Ef], f: cPoly[Ef], g: cPoly[Ef]
) -> tuple[PolyElement[Ef], PolyElement[Ef]]:
q, r = dup_ff_div(self.to_dup(f), self.to_dup(g), self.domain)
return (self.from_dup(q), self.from_dup(r))
def dmp_ff_div(
self: IPolys[Ef], f: cPoly[Ef], g: cPoly[Ef]
) -> tuple[PolyElement[Ef], PolyElement[Ef]]:
q, r = dmp_ff_div(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(q), self.from_dense(r))
def dup_div(
self, f: cPoly[Er], g: cPoly[Er]
) -> tuple[PolyElement[Er], PolyElement[Er]]:
q, r = dup_div(self.to_dup(f), self.to_dup(g), self.domain)
return (self.from_dup(q), self.from_dup(r))
def dup_rem(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_rem(self.to_dup(f), self.to_dup(g), self.domain))
def dup_quo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_quo(self.to_dup(f), self.to_dup(g), self.domain))
def dup_exquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_exquo(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_div(
self, f: cPoly[Er], g: cPoly[Er]
) -> tuple[PolyElement[Er], PolyElement[Er]]:
q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return (self.from_dense(q), self.from_dense(r))
def dmp_rem(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dmp_quo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dmp_exquo(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_max_norm(self: IPolys[Eordered], f: cPoly[Eordered]) -> Eordered:
return dup_max_norm(self.to_dup(f), self.domain)
def dmp_max_norm(self: IPolys[Eordered], f: cPoly[Eordered]) -> Eordered:
return dmp_max_norm(self.to_dense(f), self.ngens - 1, self.domain)
def dup_l1_norm(self: IPolys[Eabs], f: cPoly[Eabs]) -> Eabs:
return dup_l1_norm(self.to_dup(f), self.domain)
def dmp_l1_norm(self: IPolys[Eabs], f: cPoly[Eabs]) -> Eabs:
return dmp_l1_norm(self.to_dense(f), self.ngens - 1, self.domain)
def dup_l2_norm_squared(self, f: cPoly[Er]) -> Er:
return dup_l2_norm_squared(self.to_dup(f), self.domain)
def dmp_l2_norm_squared(self, f: cPoly[Er]) -> Er:
return dmp_l2_norm_squared(self.to_dense(f), self.ngens - 1, self.domain)
def dup_expand(self, polys: list[cPoly[Er]]) -> PolyElement[Er]:
return self.from_dup(dup_expand(list(map(self.to_dup, polys)), self.domain))
def dmp_expand(self, polys: list[cPoly[Er]]) -> PolyElement[Er]:
return self.from_dense(
dmp_expand(list(map(self.to_dense, polys)), self.ngens - 1, self.domain)
)
def dup_LC(self, f: cPoly[Er]) -> Er:
return dup_LC(self.to_dup(f), self.domain)
def dmp_LC(self, f: cPoly[Er]) -> PolyElement[Er] | Er:
LC = dmp_LC(self.to_dense(f), self.domain)
if isinstance(LC, list):
ring = cast("IPolys[Er]", self[1:])
return ring.from_dense(LC)
else:
return LC
def dup_TC(self, f: cPoly[Er]) -> Er:
return dup_TC(self.to_dup(f), self.domain)
def dmp_TC(self, f: cPoly[Er]) -> PolyElement[Er] | Er:
TC = dmp_TC(self.to_dense(f), self.domain)
if isinstance(TC, list):
ring = cast("IPolys[Er]", self[1:])
return ring.from_dense(TC)
else:
return TC
def dmp_ground_LC(self, f: cPoly[Er]) -> Er:
return dmp_ground_LC(self.to_dense(f), self.ngens - 1, self.domain)
def dmp_ground_TC(self, f: cPoly[Er]) -> Er:
return dmp_ground_TC(self.to_dense(f), self.ngens - 1, self.domain)
def dup_degree(self, f: cPoly[Er]) -> int:
return dup_degree(self.to_dup(f))
def dmp_degree(self, f: cPoly[Er]) -> int:
return dmp_degree(self.to_dense(f), self.ngens - 1)
def dmp_degree_in(self, f: cPoly[Er], j: int) -> int:
return dmp_degree_in(self.to_dense(f), j, self.ngens - 1)
def dup_integrate(self: IPolys[Ef], f: cPoly[Ef], m: int) -> PolyElement[Ef]:
return self.from_dup(
dup_integrate(self.to_dup(f), m, cast("Field[Ef]", self.domain))
)
def dmp_integrate(self: IPolys[Ef], f: cPoly[Ef], m: int) -> PolyElement[Ef]:
return self.from_dense(
dmp_integrate(
self.to_dense(f), m, self.ngens - 1, cast("Field[Ef]", self.domain)
)
)
def dup_diff(self, f: cPoly[Er], m: int) -> PolyElement[Er]:
return self.from_dup(dup_diff(self.to_dup(f), m, self.domain))
def dmp_diff(self, f: cPoly[Er], m: int) -> PolyElement[Er]:
return self.from_dense(
dmp_diff(self.to_dense(f), m, self.ngens - 1, self.domain)
)
def dmp_diff_in(self, f: cPoly[Er], m: int, j: int) -> PolyElement[Er]:
return self.from_dense(
dmp_diff_in(self.to_dense(f), m, j, self.ngens - 1, self.domain)
)
def dmp_integrate_in(
self: IPolys[Ef], f: cPoly[Ef], m: int, j: int
) -> PolyElement[Ef]:
return self.from_dense(
dmp_integrate_in(
self.to_dense(f), m, j, self.ngens - 1, cast("Field[Ef]", self.domain)
)
)
def dup_eval(self, f: cPoly[Er], a: Er) -> Er:
return dup_eval(self.to_dup(f), a, self.domain)
def dmp_eval(self, f: cPoly[Er], a: Er) -> PolyElement[Er]:
result = dmp_eval(self.to_dense(f), a, self.ngens - 1, self.domain)
if isinstance(result, list):
return cast("IPolys[Er]", self[1:]).from_dense(result)
else:
return result
def dmp_eval_in(self, f: cPoly[Er], a: Er, j: int) -> PolyElement[Er]:
result = dmp_eval_in(self.to_dense(f), a, j, self.ngens - 1, self.domain)
if isinstance(result, list):
return cast("IPolys[Er]", self.drop(j)).from_dense(result)
else:
return result
def dmp_diff_eval_in(self, f: cPoly[Er], m: int, a: Er, j: int) -> PolyElement[Er]:
result = dmp_diff_eval_in(
self.to_dense(f), m, a, j, self.ngens - 1, self.domain
)
if isinstance(result, list):
return cast("IPolys[Er]", self.drop(j)).from_dense(result)
else:
return result
def dmp_eval_tail(self, f: cPoly[Er], A: list[Er]) -> PolyElement[Er] | Er:
result = dmp_eval_tail(self.to_dense(f), A, self.ngens - 1, self.domain)
if isinstance(result, list):
return cast("IPolys[Er]", self[: -len(A)]).from_dense(result)
else:
return result
def dup_trunc(
self: IPolys[Eeuclid], f: cPoly[Eeuclid], p: Eeuclid
) -> PolyElement[Eeuclid]:
return self.from_dup(dup_trunc(self.to_dup(f), p, self.domain))
def dmp_trunc(
self: IPolys[Eeuclid], f: cPoly[Eeuclid], g: cPoly[Eeuclid]
) -> PolyElement[Eeuclid]:
return self.from_dense(
dmp_trunc(
self.to_dense(f), self[1:].to_dense(g), self.ngens - 1, self.domain # type: ignore
)
)
def dmp_ground_trunc(
self: IPolys[Eeuclid], f: cPoly[Eeuclid], p: Eeuclid
) -> PolyElement[Eeuclid]:
return self.from_dense(
dmp_ground_trunc(self.to_dense(f), p, self.ngens - 1, self.domain)
)
def dup_monic(self: IPolys[Ef], f: cPoly[Ef]) -> PolyElement[Ef]:
return self.from_dup(dup_monic(self.to_dup(f), cast("Field[Ef]", self.domain)))
def dmp_ground_monic(self: IPolys[Ef], f: cPoly[Ef]) -> PolyElement[Ef]:
return self.from_dense(
dmp_ground_monic(
self.to_dense(f), self.ngens - 1, cast("Field[Ef]", self.domain)
)
)
def dup_extract(
self, f: cPoly[Er], g: cPoly[Er]
) -> tuple[Er, PolyElement[Er], PolyElement[Er]]:
c, F, G = dup_extract(self.to_dup(f), self.to_dup(g), self.domain)
return (c, self.from_dup(F), self.from_dup(G))
def dmp_ground_extract(
self, f: cPoly[Er], g: cPoly[Er]
) -> tuple[Er, PolyElement[Er], PolyElement[Er]]:
c, F, G = dmp_ground_extract(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (c, self.from_dense(F), self.from_dense(G))
def dup_real_imag(self, f: cPoly[Er]) -> tuple[PolyElement[Er], PolyElement[Er]]:
p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain) # type: ignore
return (self.from_dense(p), self.from_dense(q))
def dup_mirror(self, f: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_mirror(self.to_dup(f), self.domain))
def dup_scale(self, f: cPoly[Er], a: Er) -> PolyElement[Er]:
return self.from_dup(dup_scale(self.to_dup(f), a, self.domain))
def dup_shift(self, f: cPoly[Er], a: Er) -> PolyElement[Er]:
return self.from_dup(dup_shift(self.to_dup(f), a, self.domain))
def dmp_shift(self, f: cPoly[Er], a: list[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_shift(self.to_dense(f), a, self.ngens - 1, self.domain)
)
def dup_transform(
self, f: cPoly[Er], p: cPoly[Er], q: cPoly[Er]
) -> PolyElement[Er]:
return self.from_dup(
dup_transform(self.to_dup(f), self.to_dup(p), self.to_dup(q), self.domain)
)
def dup_compose(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dup(dup_compose(self.to_dup(f), self.to_dup(g), self.domain))
def dmp_compose(self, f: cPoly[Er], g: cPoly[Er]) -> PolyElement[Er]:
return self.from_dense(
dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_decompose(self, f: cPoly[Er]) -> list[PolyElement[Er]]:
components = dup_decompose(self.to_dup(f), self.domain)
return list(map(self.from_dup, components))
def dmp_lift(self: IPolys[Alg], f: cPoly[Alg]) -> PolyElement[MPZ]:
result = dmp_lift(
self.to_dense(f), self.ngens - 1, cast("AlgebraicField", self.domain)
)
return self.to_ground().from_dense(result)
def dup_sign_variations(self, f: cPoly[Er]) -> int:
return dup_sign_variations(self.to_dense(f), self.domain)
def dup_clear_denoms(self, f, convert=False):
c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert)
if convert:
ring = self.clone(domain=self.domain.get_ring())
else:
ring = self
return (c, ring.from_dense(F))
def dmp_clear_denoms(self, f, convert=False):
c, F = dmp_clear_denoms(
self.to_dense(f), self.ngens - 1, self.domain, convert=convert
)
if convert:
ring = self.clone(domain=self.domain.get_ring())
else:
ring = self
return (c, ring.from_dense(F))
def dup_revert(self, f, n):
return self.from_dense(dup_revert(self.to_dense(f), n, self.domain))
def dup_half_gcdex(self, f, g):
s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(s), self.from_dense(h))
def dmp_half_gcdex(self, f, g):
s, h = dmp_half_gcdex(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(s), self.from_dense(h))
def dup_gcdex(self, f, g):
s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(s), self.from_dense(t), self.from_dense(h))
def dmp_gcdex(self, f, g):
s, t, h = dmp_gcdex(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(s), self.from_dense(t), self.from_dense(h))
def dup_invert(self, f, g):
return self.from_dense(
dup_invert(self.to_dense(f), self.to_dense(g), self.domain)
)
def dmp_invert(self, f, g):
return self.from_dense(
dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
)
def dup_euclidean_prs(self, f, g):
prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain)
return list(map(self.from_dense, prs))
def dmp_euclidean_prs(self, f, g):
prs = dmp_euclidean_prs(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return list(map(self.from_dense, prs))
def dup_primitive_prs(self, f, g):
prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain)
return list(map(self.from_dense, prs))
def dmp_primitive_prs(self, f, g):
prs = dmp_primitive_prs(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return list(map(self.from_dense, prs))
def dup_inner_subresultants(self, f, g):
prs, sres = dup_inner_subresultants(
self.to_dense(f), self.to_dense(g), self.domain
)
return (list(map(self.from_dense, prs)), sres)
def dmp_inner_subresultants(self, f, g):
prs, sres = dmp_inner_subresultants(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (list(map(self.from_dense, prs)), sres)
def dup_subresultants(self, f, g):
prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain)
return list(map(self.from_dense, prs))
def dmp_subresultants(self, f, g):
prs = dmp_subresultants(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return list(map(self.from_dense, prs))
def dup_prs_resultant(self, f, g):
res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain)
return (res, list(map(self.from_dense, prs)))
def dmp_prs_resultant(self, f, g):
res, prs = dmp_prs_resultant(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self[1:].from_dense(res), list(map(self.from_dense, prs)))
def dmp_zz_modular_resultant(self, f, g, p):
res = dmp_zz_modular_resultant(
self.to_dense(f),
self.to_dense(g),
self.domain_new(p),
self.ngens - 1,
self.domain,
)
return self[1:].from_dense(res)
def dmp_zz_collins_resultant(self, f, g):
res = dmp_zz_collins_resultant(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return self[1:].from_dense(res)
def dmp_qq_collins_resultant(self, f, g):
res = dmp_qq_collins_resultant(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return self[1:].from_dense(res)
def dup_resultant(self, f, g): # , includePRS=False):
return dup_resultant(
self.to_dense(f), self.to_dense(g), self.domain
) # , includePRS=includePRS)
def dmp_resultant(self, f, g): # , includePRS=False):
res = dmp_resultant(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
) # , includePRS=includePRS)
if isinstance(res, list):
return self[1:].from_dense(res)
else:
return res
def dup_discriminant(self, f):
return dup_discriminant(self.to_dense(f), self.domain)
def dmp_discriminant(self, f):
disc = dmp_discriminant(self.to_dense(f), self.ngens - 1, self.domain)
if isinstance(disc, list):
return self[1:].from_dense(disc)
else:
return disc
def dup_rr_prs_gcd(self, f, g):
H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dup_ff_prs_gcd(self, f, g):
H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dmp_rr_prs_gcd(self, f, g):
H, F, G = dmp_rr_prs_gcd(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dmp_ff_prs_gcd(self, f, g):
H, F, G = dmp_ff_prs_gcd(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dup_zz_heu_gcd(self, f, g):
H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dmp_zz_heu_gcd(self, f, g):
H, F, G = dmp_zz_heu_gcd(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dup_qq_heu_gcd(self, f, g):
H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dmp_qq_heu_gcd(self, f, g):
H, F, G = dmp_qq_heu_gcd(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dup_inner_gcd(self, f, g):
H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dmp_inner_gcd(self, f, g):
H, F, G = dmp_inner_gcd(
self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain
)
return (self.from_dense(H), self.from_dense(F), self.from_dense(G))
def dup_gcd(self, f, g):
H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain)
return self.from_dense(H)
def dmp_gcd(self, f, g):
H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return self.from_dense(H)
def dup_rr_lcm(self, f, g):
H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain)
return self.from_dense(H)
def dup_ff_lcm(self, f, g):
H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain)
return self.from_dense(H)
def dup_lcm(self, f, g):
H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain)
return self.from_dense(H)
def dmp_rr_lcm(self, f, g):
H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return self.from_dense(H)
def dmp_ff_lcm(self, f, g):
H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return self.from_dense(H)
def dmp_lcm(self, f, g):
H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens - 1, self.domain)
return self.from_dense(H)
def dup_content(self, f):
cont = dup_content(self.to_dense(f), self.domain)
return cont
def dup_primitive(self, f):
cont, prim = dup_primitive(self.to_dense(f), self.domain)
return cont, self.from_dense(prim)
def dmp_content(self, f):
cont = dmp_content(self.to_dense(f), self.ngens - 1, self.domain)
if isinstance(cont, list):
return self[1:].from_dense(cont)
else:
return cont
def dmp_primitive(self, f):
cont, prim = dmp_primitive(self.to_dense(f), self.ngens - 1, self.domain)
if isinstance(cont, list):
return (self[1:].from_dense(cont), self.from_dense(prim))
else:
return (cont, self.from_dense(prim))
def dmp_ground_content(self, f):
cont = dmp_ground_content(self.to_dense(f), self.ngens - 1, self.domain)
return cont
def dmp_ground_primitive(self, f):
cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens - 1, self.domain)
return (cont, self.from_dense(prim))
def dup_cancel(self, f, g, include=True):
result = dup_cancel(
self.to_dense(f), self.to_dense(g), self.domain, include=include
)
if not include:
cf, cg, F, G = result
return (cf, cg, self.from_dense(F), self.from_dense(G))
else:
F, G = result
return (self.from_dense(F), self.from_dense(G))
def dmp_cancel(self, f, g, include=True):
result = dmp_cancel(
self.to_dense(f),
self.to_dense(g),
self.ngens - 1,
self.domain,
include=include,
)
if not include:
cf, cg, F, G = result
return (cf, cg, self.from_dense(F), self.from_dense(G))
else:
F, G = result
return (self.from_dense(F), self.from_dense(G))
def dup_trial_division(self, f, factors):
factors = dup_trial_division(
self.to_dense(f), list(map(self.to_dense, factors)), self.domain
)
return [(self.from_dense(g), k) for g, k in factors]
def dmp_trial_division(self, f, factors):
factors = dmp_trial_division(
self.to_dense(f),
list(map(self.to_dense, factors)),
self.ngens - 1,
self.domain,
)
return [(self.from_dense(g), k) for g, k in factors]
def dup_zz_mignotte_bound(self, f):
return dup_zz_mignotte_bound(self.to_dense(f), self.domain)
def dmp_zz_mignotte_bound(self, f):
return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens - 1, self.domain)
def dup_zz_hensel_step(self, m, f, g, h, s, t):
D = self.to_dense
G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain)
return (
self.from_dense(G),
self.from_dense(H),
self.from_dense(S),
self.from_dense(T),
)
def dup_zz_hensel_lift(self, p, f, f_list, l):
D = self.to_dense
polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain)
return list(map(self.from_dense, polys))
def dup_zz_zassenhaus(self, f):
factors = dup_zz_zassenhaus(self.to_dense(f), self.domain)
return [(self.from_dense(g), k) for g, k in factors]
def dup_zz_irreducible_p(self, f):
return dup_zz_irreducible_p(self.to_dense(f), self.domain)
def dup_cyclotomic_p(self, f, irreducible=False):
return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible)
def dup_zz_cyclotomic_poly(self, n):
F = dup_zz_cyclotomic_poly(n, self.domain)
return self.from_dense(F)
def dup_zz_cyclotomic_factor(self, f):
result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain)
if result is None:
return result
else:
return list(map(self.from_dense, result))
# E: List[ZZ], cs: ZZ, ct: ZZ
def dmp_zz_wang_non_divisors(self, E, cs, ct):
return dmp_zz_wang_non_divisors(E, cs, ct, self.domain)
# f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ]
# def dmp_zz_wang_test_points(f, T, ct, A):
# dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain)
# f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ]
def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A):
mv = self[1:]
T = [(mv.to_dense(t), k) for t, k in T]
uv = self[:1]
H = list(map(uv.to_dense, H))
f, HH, CC = dmp_zz_wang_lead_coeffs(
self.to_dense(f), T, cs, E, H, A, self.ngens - 1, self.domain
)
return (
self.from_dense(f),
list(map(uv.from_dense, HH)),
list(map(mv.from_dense, CC)),
)
# f: List[Poly], m: int, p: ZZ
def dup_zz_diophantine(self, F, m, p):
result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain)
return list(map(self.from_dense, result))
# f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ
def dmp_zz_diophantine(self, F, c, A, d, p):
result = dmp_zz_diophantine(
list(map(self.to_dense, F)),
self.to_dense(c),
A,
d,
p,
self.ngens - 1,
self.domain,
)
return list(map(self.from_dense, result))
# f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ
def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p):
uv = self[:1]
mv = self[1:]
H = list(map(uv.to_dense, H))
LC = list(map(mv.to_dense, LC))
result = dmp_zz_wang_hensel_lifting(
self.to_dense(f), H, LC, A, p, self.ngens - 1, self.domain
)
return list(map(self.from_dense, result))
def dmp_zz_wang(self, f, mod=None, seed=None):
factors = dmp_zz_wang(
self.to_dense(f), self.ngens - 1, self.domain, mod=mod, seed=seed
)
return [self.from_dense(g) for g in factors]
def dup_zz_factor_sqf(self, f):
coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain)
return (coeff, [self.from_dense(g) for g in factors])
def dup_zz_factor(self, f):
coeff, factors = dup_zz_factor(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_zz_factor(self, f):
coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_qq_i_factor(self, f):
coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_qq_i_factor(self, f):
coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_zz_i_factor(self, f):
coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_zz_i_factor(self, f):
coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_ext_factor(self, f):
coeff, factors = dup_ext_factor(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_ext_factor(self, f):
coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_gf_factor(self, f):
coeff, factors = dup_gf_factor(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_gf_factor(self, f):
coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_factor_list(self, f):
coeff, factors = dup_factor_list(self.to_dense(f), self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_factor_list_include(self, f):
factors = dup_factor_list_include(self.to_dense(f), self.domain)
return [(self.from_dense(g), k) for g, k in factors]
def dmp_factor_list(self, f):
coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens - 1, self.domain)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_factor_list_include(self, f):
factors = dmp_factor_list_include(self.to_dense(f), self.ngens - 1, self.domain)
return [(self.from_dense(g), k) for g, k in factors]
def dup_irreducible_p(self, f):
return dup_irreducible_p(self.to_dense(f), self.domain)
def dmp_irreducible_p(self, f):
return dmp_irreducible_p(self.to_dense(f), self.ngens - 1, self.domain)
def dup_sturm(self, f):
seq = dup_sturm(self.to_dense(f), self.domain)
return list(map(self.from_dense, seq))
def dup_sqf_p(self, f):
return dup_sqf_p(self.to_dense(f), self.domain)
def dmp_sqf_p(self, f):
return dmp_sqf_p(self.to_dense(f), self.ngens - 1, self.domain)
def dmp_norm(self, f):
n = dmp_norm(self.to_dense(f), self.ngens - 1, self.domain)
return self.to_ground().from_dense(n)
def dup_sqf_norm(self, f):
s, F, R = dup_sqf_norm(self.to_dense(f), self.domain)
return (s, self.from_dense(F), self.to_ground().from_dense(R))
def dmp_sqf_norm(self, f):
s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens - 1, self.domain)
return (s, self.from_dense(F), self.to_ground().from_dense(R))
def dup_gf_sqf_part(self, f):
return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain))
def dmp_gf_sqf_part(self, f):
return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain))
def dup_sqf_part(self, f):
return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain))
def dmp_sqf_part(self, f):
return self.from_dense(
dmp_sqf_part(self.to_dense(f), self.ngens - 1, self.domain)
)
def dup_gf_sqf_list(self, f, all=False):
coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_gf_sqf_list(self, f, all=False):
coeff, factors = dmp_gf_sqf_list(
self.to_dense(f), self.ngens - 1, self.domain, all=all
)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_sqf_list(self, f, all=False):
coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dup_sqf_list_include(self, f, all=False):
factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all)
return [(self.from_dense(g), k) for g, k in factors]
def dmp_sqf_list(self, f, all=False):
coeff, factors = dmp_sqf_list(
self.to_dense(f), self.ngens - 1, self.domain, all=all
)
return (coeff, [(self.from_dense(g), k) for g, k in factors])
def dmp_sqf_list_include(self, f, all=False):
factors = dmp_sqf_list_include(
self.to_dense(f), self.ngens - 1, self.domain, all=all
)
return [(self.from_dense(g), k) for g, k in factors]
def dup_gff_list(self, f):
factors = dup_gff_list(self.to_dense(f), self.domain)
return [(self.from_dense(g), k) for g, k in factors]
def dmp_gff_list(self, f):
factors = dmp_gff_list(self.to_dense(f), self.ngens - 1, self.domain)
return [(self.from_dense(g), k) for g, k in factors]
def dup_root_upper_bound(self, f):
return dup_root_upper_bound(self.to_dense(f), self.domain)
def dup_root_lower_bound(self, f):
return dup_root_lower_bound(self.to_dense(f), self.domain)
def dup_step_refine_real_root(self, f, M, fast=False):
return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast)
def dup_inner_refine_real_root(
self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False
):
return dup_inner_refine_real_root(
self.to_dense(f),
M,
self.domain,
eps=eps,
steps=steps,
disjoint=disjoint,
fast=fast,
mobius=mobius,
)
def dup_outer_refine_real_root(
self, f, s, t, eps=None, steps=None, disjoint=None, fast=False
):
return dup_outer_refine_real_root(
self.to_dense(f),
s,
t,
self.domain,
eps=eps,
steps=steps,
disjoint=disjoint,
fast=fast,
)
def dup_refine_real_root(
self, f, s, t, eps=None, steps=None, disjoint=None, fast=False
):
return dup_refine_real_root(
self.to_dense(f),
s,
t,
self.domain,
eps=eps,
steps=steps,
disjoint=disjoint,
fast=fast,
)
def dup_inner_isolate_real_roots(self, f, eps=None, fast=False):
return dup_inner_isolate_real_roots(
self.to_dense(f), self.domain, eps=eps, fast=fast
)
def dup_inner_isolate_positive_roots(
self, f, eps=None, inf=None, sup=None, fast=False, mobius=False
):
return dup_inner_isolate_positive_roots(
self.to_dense(f),
self.domain,
eps=eps,
inf=inf,
sup=sup,
fast=fast,
mobius=mobius,
)
def dup_inner_isolate_negative_roots(
self, f, inf=None, sup=None, eps=None, fast=False, mobius=False
):
return dup_inner_isolate_negative_roots(
self.to_dense(f),
self.domain,
inf=inf,
sup=sup,
eps=eps,
fast=fast,
mobius=mobius,
)
def dup_isolate_real_roots_sqf(
self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False
):
return dup_isolate_real_roots_sqf(
self.to_dense(f),
self.domain,
eps=eps,
inf=inf,
sup=sup,
fast=fast,
blackbox=blackbox,
)
def dup_isolate_real_roots(
self, f, eps=None, inf=None, sup=None, basis=False, fast=False
):
return dup_isolate_real_roots(
self.to_dense(f),
self.domain,
eps=eps,
inf=inf,
sup=sup,
basis=basis,
fast=fast,
)
def dup_isolate_real_roots_list(
self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False
):
return dup_isolate_real_roots_list(
list(map(self.to_dense, polys)),
self.domain,
eps=eps,
inf=inf,
sup=sup,
strict=strict,
basis=basis,
fast=fast,
)
def dup_count_real_roots(self, f, inf=None, sup=None):
return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup)
def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None):
return dup_count_complex_roots(
self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude
)
def dup_isolate_complex_roots_sqf(
self, f, eps=None, inf=None, sup=None, blackbox=False
):
return dup_isolate_complex_roots_sqf(
self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox
)
def dup_isolate_all_roots_sqf(
self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False
):
return dup_isolate_all_roots_sqf(
self.to_dense(f),
self.domain,
eps=eps,
inf=inf,
sup=sup,
fast=fast,
blackbox=blackbox,
)
def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False):
return dup_isolate_all_roots(
self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast
)
def fateman_poly_F_1(self):
from sympy.polys.specialpolys import dmp_fateman_poly_F_1
return tuple(
map(self.from_dense, dmp_fateman_poly_F_1(self.ngens - 1, self.domain))
)
def fateman_poly_F_2(self):
from sympy.polys.specialpolys import dmp_fateman_poly_F_2
return tuple(
map(self.from_dense, dmp_fateman_poly_F_2(self.ngens - 1, self.domain))
)
def fateman_poly_F_3(self):
from sympy.polys.specialpolys import dmp_fateman_poly_F_3
return tuple(
map(self.from_dense, dmp_fateman_poly_F_3(self.ngens - 1, self.domain))
)
def to_gf_dense(self, element):
return gf_strip(
[
self.domain.dom.convert(c, self.domain)
for c in self.wrap(element).to_dense()
]
)
def from_gf_dense(self, element):
return self.from_dict(dmp_to_dict(element, self.ngens - 1, self.domain.dom))
def gf_degree(self, f):
return gf_degree(self.to_gf_dense(f))
def gf_LC(self, f):
return gf_LC(self.to_gf_dense(f), self.domain.dom)
def gf_TC(self, f):
return gf_TC(self.to_gf_dense(f), self.domain.dom)
def gf_strip(self, f):
return self.from_gf_dense(gf_strip(self.to_gf_dense(f)))
def gf_trunc(self, f):
return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod))
def gf_normal(self, f):
return self.from_gf_dense(
gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_from_dict(self, f):
return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom))
def gf_to_dict(self, f, symmetric=True):
return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric)
def gf_from_int_poly(self, f):
return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod))
def gf_to_int_poly(self, f, symmetric=True):
return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric)
def gf_neg(self, f):
return self.from_gf_dense(
gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_add_ground(self, f, a):
return self.from_gf_dense(
gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
)
def gf_sub_ground(self, f, a):
return self.from_gf_dense(
gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
)
def gf_mul_ground(self, f, a):
return self.from_gf_dense(
gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
)
def gf_quo_ground(self, f, a):
return self.from_gf_dense(
gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
)
def gf_add(self, f, g):
return self.from_gf_dense(
gf_add(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_sub(self, f, g):
return self.from_gf_dense(
gf_sub(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_mul(self, f, g):
return self.from_gf_dense(
gf_mul(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_sqr(self, f):
return self.from_gf_dense(
gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_add_mul(self, f, g, h):
return self.from_gf_dense(
gf_add_mul(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.to_gf_dense(h),
self.domain.mod,
self.domain.dom,
)
)
def gf_sub_mul(self, f, g, h):
return self.from_gf_dense(
gf_sub_mul(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.to_gf_dense(h),
self.domain.mod,
self.domain.dom,
)
)
def gf_expand(self, F):
return self.from_gf_dense(
gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom)
)
def gf_div(self, f, g):
q, r = gf_div(
self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom
)
return self.from_gf_dense(q), self.from_gf_dense(r)
def gf_rem(self, f, g):
return self.from_gf_dense(
gf_rem(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_quo(self, f, g):
return self.from_gf_dense(
gf_quo(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_exquo(self, f, g):
return self.from_gf_dense(
gf_exquo(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_lshift(self, f, n):
return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom))
def gf_rshift(self, f, n):
return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom))
def gf_pow(self, f, n):
return self.from_gf_dense(
gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom)
)
def gf_pow_mod(self, f, n, g):
return self.from_gf_dense(
gf_pow_mod(
self.to_gf_dense(f),
n,
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_cofactors(self, f, g):
h, cff, cfg = gf_cofactors(
self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom
)
return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg)
def gf_gcd(self, f, g):
return self.from_gf_dense(
gf_gcd(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_lcm(self, f, g):
return self.from_gf_dense(
gf_lcm(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_gcdex(self, f, g):
return self.from_gf_dense(
gf_gcdex(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_monic(self, f):
return self.from_gf_dense(
gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_diff(self, f):
return self.from_gf_dense(
gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_eval(self, f, a):
return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)
def gf_multi_eval(self, f, A):
return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom)
def gf_compose(self, f, g):
return self.from_gf_dense(
gf_compose(
self.to_gf_dense(f),
self.to_gf_dense(g),
self.domain.mod,
self.domain.dom,
)
)
def gf_compose_mod(self, g, h, f):
return self.from_gf_dense(
gf_compose_mod(
self.to_gf_dense(g),
self.to_gf_dense(h),
self.to_gf_dense(f),
self.domain.mod,
self.domain.dom,
)
)
def gf_trace_map(self, a, b, c, n, f):
a = self.to_gf_dense(a)
b = self.to_gf_dense(b)
c = self.to_gf_dense(c)
f = self.to_gf_dense(f)
U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom)
return self.from_gf_dense(U), self.from_gf_dense(V)
def gf_random(self, n):
return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom))
def gf_irreducible(self, n):
return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom))
def gf_irred_p_ben_or(self, f):
return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
def gf_irred_p_rabin(self, f):
return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
def gf_irreducible_p(self, f):
return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
def gf_sqf_p(self, f):
return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
def gf_sqf_part(self, f):
return self.from_gf_dense(
gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
)
def gf_sqf_list(self, f, all=False):
coeff, factors = gf_sqf_part(
self.to_gf_dense(f), self.domain.mod, self.domain.dom
)
return coeff, [(self.from_gf_dense(g), k) for g, k in factors]
def gf_Qmatrix(self, f):
return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
def gf_berlekamp(self, f):
factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
return [self.from_gf_dense(g) for g in factors]
def gf_ddf_zassenhaus(self, f):
factors = gf_ddf_zassenhaus(
self.to_gf_dense(f), self.domain.mod, self.domain.dom
)
return [(self.from_gf_dense(g), k) for g, k in factors]
def gf_edf_zassenhaus(self, f, n):
factors = gf_edf_zassenhaus(
self.to_gf_dense(f), self.domain.mod, self.domain.dom
)
return [self.from_gf_dense(g) for g in factors]
def gf_ddf_shoup(self, f):
factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
return [(self.from_gf_dense(g), k) for g, k in factors]
def gf_edf_shoup(self, f, n):
factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
return [self.from_gf_dense(g) for g in factors]
def gf_zassenhaus(self, f):
factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
return [self.from_gf_dense(g) for g in factors]
def gf_shoup(self, f):
factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom)
return [self.from_gf_dense(g) for g in factors]
def gf_factor_sqf(self, f, method=None):
coeff, factors = gf_factor_sqf(
self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method
)
return coeff, [self.from_gf_dense(g) for g in factors]
def gf_factor(self, f):
coeff, factors = gf_factor(
self.to_gf_dense(f), self.domain.mod, self.domain.dom
)
return coeff, [(self.from_gf_dense(g), k) for g, k in factors]
| IPolys |
python | getsentry__sentry | src/sentry/testutils/factories.py | {
"start": 14689,
"end": 91378
} | class ____:
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_organization(name=None, owner=None, region: Region | str | None = None, **kwargs):
if not name:
name = petname.generate(2, " ", letters=10).title()
with contextlib.ExitStack() as ctx:
if region is None or SiloMode.get_current_mode() == SiloMode.MONOLITH:
region_name = get_local_region().name
else:
if isinstance(region, Region):
region_name = region.name
else:
region_obj = get_region_by_name(region) # Verify it exists
region_name = region_obj.name
ctx.enter_context(
override_settings(SILO_MODE=SiloMode.REGION, SENTRY_REGION=region_name)
)
with outbox_context(flush=False):
org = Organization.objects.create(name=name, **kwargs)
with assume_test_silo_mode(SiloMode.CONTROL):
# Organization mapping creation relies on having a matching org slug reservation
OrganizationSlugReservation(
organization_id=org.id,
region_name=region_name,
user_id=owner.id if owner else -1,
slug=org.slug,
).save(unsafe_write=True)
# Manually replicate org data after adding an org slug reservation
org.handle_async_replication(org.id)
# Flush remaining organization update outboxes accumulated by org create
RegionOutbox(
shard_identifier=org.id,
shard_scope=OutboxScope.ORGANIZATION_SCOPE,
category=OutboxCategory.ORGANIZATION_UPDATE,
).drain_shard()
if owner:
Factories.create_member(organization=org, user_id=owner.id, role="owner")
return org
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_org_mapping(org=None, **kwds):
if org:
kwds.setdefault("organization_id", org.id)
kwds.setdefault("slug", org.slug)
kwds.setdefault("name", org.name)
kwds.setdefault("idempotency_key", uuid4().hex)
kwds.setdefault("region_name", "na")
return OrganizationMapping.objects.create(**kwds)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_member(teams=None, team_roles=None, **kwargs):
kwargs.setdefault("role", "member")
teamRole = kwargs.pop("teamRole", None)
# user_id will have precedence over user
user = kwargs.pop("user", None)
user_id = kwargs.pop("user_id", None)
if not user_id and user:
user_id = user.id
kwargs["user_id"] = user_id
# inviter_id will have precedence over inviter
inviter = kwargs.pop("inviter", None)
inviter_id = kwargs.pop("inviter_id", None)
if not inviter_id and inviter:
inviter_id = inviter.id
kwargs["inviter_id"] = inviter_id
om = OrganizationMember.objects.create(**kwargs)
if team_roles:
for team, role in team_roles:
Factories.create_team_membership(team=team, member=om, role=role)
elif teams:
for team in teams:
Factories.create_team_membership(team=team, member=om, role=teamRole)
return om
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_member_invite(
organization: Organization | None = None,
email: str | None = None,
**kwargs,
) -> OrganizationMemberInvite:
if organization is None:
organization = Factories.create_organization()
if email is None:
email = f"{petname.generate().title()}@email.com"
om = OrganizationMember.objects.create(organization=organization)
return OrganizationMemberInvite.objects.create(
organization=organization, organization_member_id=om.id, email=email, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_team_membership(team, member=None, user=None, role=None):
if member is None:
member, created = OrganizationMember.objects.get_or_create(
user_id=user.id if user else None,
organization=team.organization,
defaults={"role": "member"},
)
return OrganizationMemberTeam.objects.create(
team=team, organizationmember=member, is_active=True, role=role
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_api_key(organization, **kwargs) -> ApiKey:
return ApiKey.objects.create(organization_id=organization.id, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_auth_provider(**kwargs):
return AuthProvider.objects.create(**kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_auth_identity(**kwargs):
return AuthIdentity.objects.create(**kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_user_auth_token(user, scope_list: list[str] | None = None, **kwargs) -> ApiToken:
if scope_list is None:
scope_list = []
return ApiToken.objects.create(
user=user,
scope_list=scope_list,
token_type=AuthTokenType.USER,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_org_auth_token(*args, **kwargs) -> OrgAuthToken:
return OrgAuthToken.objects.create(*args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_team(organization, **kwargs):
if not kwargs.get("name"):
kwargs["name"] = petname.generate(2, " ", letters=10).title()
if not kwargs.get("slug"):
kwargs["slug"] = slugify(str(kwargs["name"]))
members = kwargs.pop("members", None)
team = Team.objects.create(organization=organization, **kwargs)
if members:
for user in members:
Factories.create_team_membership(team=team, user=user)
return team
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_environment(project, **kwargs):
name = kwargs.get("name", petname.generate(3, " ", letters=10)[:64])
organization = kwargs.get("organization")
organization_id = organization.id if organization else project.organization_id
env = Environment.objects.create(organization_id=organization_id, name=name)
env.add_project(project, is_hidden=kwargs.get("is_hidden"))
return env
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_project(
organization=None,
teams=None,
fire_project_created=False,
create_default_detectors=False,
**kwargs,
) -> Project:
from sentry.receivers.project_detectors import disable_default_detector_creation
if not kwargs.get("name"):
kwargs["name"] = petname.generate(2, " ", letters=10).title()
if not kwargs.get("slug"):
kwargs["slug"] = slugify(str(kwargs["name"]))
if not organization and teams:
organization = teams[0].organization
with (
disable_default_detector_creation()
if not create_default_detectors
else contextlib.nullcontext()
):
with transaction.atomic(router.db_for_write(Project)):
project = Project.objects.create(organization=organization, **kwargs)
if teams:
for team in teams:
project.add_team(team)
if fire_project_created:
project_created.send(
project=project, user=AnonymousUser(), default_rules=True, sender=Factories
)
return project
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_project_template(project=None, organization=None, **kwargs) -> ProjectTemplate:
if not kwargs.get("name"):
kwargs["name"] = petname.generate(2, " ", letters=10).title()
with transaction.atomic(router.db_for_write(Project)):
project_template = ProjectTemplate.objects.create(organization=organization, **kwargs)
return project_template
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_data_access_grant(**kwargs):
return DataAccessGrant.objects.create(**kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_project_bookmark(project, user):
return ProjectBookmark.objects.create(project_id=project.id, user_id=user.id)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_project_rule(
project,
action_data=None,
allow_no_action_data=False,
condition_data=None,
name="Test Alert",
action_match="all",
filter_match="all",
frequency=30,
**kwargs,
):
actions = None
if not allow_no_action_data:
action_data = action_data or [
{
"id": "sentry.rules.actions.notify_event.NotifyEventAction",
"name": "Send a notification (for all legacy integrations)",
},
{
"id": "sentry.rules.actions.notify_event_service.NotifyEventServiceAction",
"service": "mail",
"name": "Send a notification via mail",
},
]
actions = action_data
condition_data = condition_data or [
{
"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition",
"name": "A new issue is created",
},
{
"id": "sentry.rules.conditions.every_event.EveryEventCondition",
"name": "The event occurs",
},
]
data = {
"conditions": condition_data,
"action_match": action_match,
"filter_match": filter_match,
"frequency": frequency,
}
if actions:
data["actions"] = actions
return Rule.objects.create(
label=name,
project=project,
data=data,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_slack_project_rule(project, integration_id, channel_id=None, channel_name=None):
action_data = [
{
"id": "sentry.rules.actions.notify_event.SlackNotifyServiceAction",
"name": "Send a Slack notification",
"workspace": integration_id,
"channel_id": channel_id or "123453",
"channel": channel_name or "#general",
}
]
return Factories.create_project_rule(project, action_data)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_project_key(project):
return project.key_set.get_or_create()[0]
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_tempest_credentials(
project: Project,
created_by: User | None = None,
client_id: str | None = None,
client_secret: str | None = None,
message: str = "",
message_type: str | None = None,
latest_fetched_item_id: str | None = None,
):
if client_id is None:
client_id = str(uuid4())
if client_secret is None:
client_secret = str(uuid4())
if message_type is None:
message_type = TempestMessageType.ERROR
return TempestCredentials.objects.create(
project=project,
created_by_id=created_by.id if created_by else None,
client_id=client_id,
client_secret=client_secret,
message=message,
message_type=message_type,
latest_fetched_item_id=latest_fetched_item_id,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_release(
project: Project,
user: User | None = None,
version: str | None = None,
date_added: datetime | None = None,
additional_projects: Sequence[Project] | None = None,
environments: Sequence[Environment] | None = None,
date_released: datetime | None = None,
adopted: datetime | None = None,
unadopted: datetime | None = None,
status: int | None = ReleaseStatus.OPEN,
):
if version is None:
version = hexlify(os.urandom(20)).decode()
if date_added is None:
date_added = timezone.now()
if additional_projects is None:
additional_projects = []
release = Release.objects.create(
version=version,
organization_id=project.organization_id,
date_added=date_added,
date_released=date_released,
status=status,
)
release.add_project(project)
for additional_project in additional_projects:
release.add_project(additional_project)
for environment in environments or []:
ReleaseEnvironment.objects.create(
organization=project.organization, release=release, environment=environment
)
for project in [project, *additional_projects]:
ReleaseProjectEnvironment.objects.create(
project=project,
release=release,
environment=environment,
adopted=adopted,
unadopted=unadopted,
)
Activity.objects.create(
type=ActivityType.RELEASE.value,
project=project,
ident=Activity.get_version_ident(version),
user_id=user.id if user else None,
data={"version": version},
)
# add commits
if user:
author = Factories.create_commit_author(project=project, user=user)
repo = Factories.create_repo(project, name=f"organization-{project.slug}")
commit = Factories.create_commit(
project=project,
repo=repo,
author=author,
release=release,
key="deadbeef",
message="placeholder commit message",
)
release.update(authors=[str(author.id)], commit_count=1, last_commit_id=commit.id)
return release
@staticmethod
def create_group_release(project: Project, group: Group, release: Release) -> GroupRelease:
return GroupRelease.objects.create(
project_id=project.id,
group_id=group.id,
release_id=release.id,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_release_file(release_id, file=None, name=None, dist_id=None):
if file is None:
file = Factories.create_file(
name="log.txt",
size=32,
headers={"Content-Type": "text/plain"},
checksum="dc1e3f3e411979d336c3057cce64294f3420f93a",
)
if name is None:
name = file.name
organization_id = Release.objects.get(pk=release_id).organization.id
return ReleaseFile.objects.create(
organization_id=organization_id,
release_id=release_id,
name=name,
file=file,
dist_id=dist_id,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_artifact_bundle_zip(
org=None, release=None, project=None, extra_files=None, fixture_path="artifact_bundle"
):
bundle = io.BytesIO()
bundle_dir = get_fixture_path(fixture_path)
with zipfile.ZipFile(bundle, "w", zipfile.ZIP_DEFLATED) as zipf:
for path, content in (extra_files or {}).items():
zipf.writestr(path, content)
for path, _, files in os.walk(bundle_dir):
for filename in files:
fullpath = os.path.join(path, filename)
relpath = os.path.relpath(fullpath, bundle_dir)
if filename == "manifest.json":
manifest = _patch_artifact_manifest(
fullpath, org, release, project, extra_files
)
zipf.writestr(relpath, manifest)
else:
zipf.write(fullpath, relpath)
return bundle.getvalue()
@classmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_release_archive(cls, org, release: str, project=None, dist=None):
bundle = cls.create_artifact_bundle_zip(org, release, project)
file = File.objects.create(name="release-artifacts.zip")
file.putfile(ContentFile(bundle))
release_obj = Release.objects.get(organization__slug=org, version=release)
return update_artifact_index(release_obj, dist, file)
@classmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_artifact_bundle(
cls,
org,
bundle_id=None,
artifact_count=0,
fixture_path="artifact_bundle_debug_ids",
date_uploaded=None,
date_last_modified=None,
):
if date_uploaded is None:
date_uploaded = timezone.now()
bundle = cls.create_artifact_bundle_zip(org.slug, fixture_path=fixture_path)
file_ = File.objects.create(name="artifact-bundle.zip")
file_.putfile(ContentFile(bundle))
# The 'artifact_count' should correspond to the 'bundle' contents but for the purpose of tests we can also
# mock it with an arbitrary value.
artifact_bundle = ArtifactBundle.objects.create(
organization_id=org.id,
bundle_id=bundle_id or uuid4(),
file=file_,
artifact_count=artifact_count,
date_uploaded=date_uploaded,
date_last_modified=date_last_modified,
)
return artifact_bundle
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_code_mapping(project, repo=None, organization_integration=None, **kwargs):
kwargs.setdefault("stack_root", "")
kwargs.setdefault("source_root", "")
kwargs.setdefault("default_branch", "master")
if not repo:
repo = Factories.create_repo(project=project)
return RepositoryProjectPathConfig.objects.create(
project=project,
repository=repo,
organization_integration_id=organization_integration.id,
integration_id=organization_integration.integration_id,
organization_id=organization_integration.organization_id,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_repo(
project, name=None, provider=None, integration_id=None, url=None, external_id=None
):
repo, _ = Repository.objects.get_or_create(
organization_id=project.organization_id,
name=name
or "{}-{}".format(petname.generate(2, "", letters=10), random.randint(1000, 9999)),
provider=provider,
integration_id=integration_id,
url=url,
external_id=external_id,
)
return repo
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_commit(
repo, project=None, author=None, release=None, message=None, key=None, date_added=None
):
commit = Commit.objects.get_or_create(
organization_id=repo.organization_id,
repository_id=repo.id,
key=key or sha1(uuid4().hex.encode("utf-8")).hexdigest(),
defaults={
"message": message or make_sentence(),
"author": author
or Factories.create_commit_author(organization_id=repo.organization_id),
"date_added": date_added or timezone.now(),
},
)[0]
if release:
assert project
ReleaseCommit.objects.create(
organization_id=repo.organization_id,
project_id=project.id,
release=release,
commit=commit,
order=1,
)
Factories.create_commit_file_change(commit=commit, filename="/models/foo.py")
Factories.create_commit_file_change(commit=commit, filename="/worsematch/foo.py")
Factories.create_commit_file_change(commit=commit, filename="/models/other.py")
return commit
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_commit_author(organization_id=None, project=None, user=None, email=None):
if email:
user_email = email
else:
user_email = user.email if user else f"{make_word()}@example.com"
return CommitAuthor.objects.get_or_create(
organization_id=organization_id or project.organization_id,
email=user_email,
defaults={"name": user.name if user else make_word()},
)[0]
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_pull_request(
repository_id=None, organization_id=None, key=None, title=None, message=None, author=None
):
from sentry.models.pullrequest import PullRequest
return PullRequest.objects.create(
repository_id=repository_id,
organization_id=organization_id,
key=key or str(uuid4().hex[:8]),
title=title or make_sentence(),
message=message or make_sentence(),
author=author,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_pull_request_comment(
pull_request,
external_id=None,
created_at=None,
updated_at=None,
group_ids=None,
comment_type=None,
reactions=None,
):
from django.utils import timezone
from sentry.models.pullrequest import CommentType, PullRequestComment
if created_at is None:
created_at = timezone.now()
if updated_at is None:
updated_at = created_at
if group_ids is None:
group_ids = []
if comment_type is None:
comment_type = CommentType.MERGED_PR
return PullRequestComment.objects.create(
pull_request=pull_request,
external_id=external_id or uuid4().int % (10**9),
created_at=created_at,
updated_at=updated_at,
group_ids=group_ids,
comment_type=comment_type,
reactions=reactions,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_pull_request_commit(pull_request, commit):
return PullRequestCommit.objects.create(
pull_request=pull_request,
commit=commit,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_commit_file_change(commit, filename):
return CommitFileChange.objects.get_or_create(
organization_id=commit.organization_id, commit_id=commit.id, filename=filename, type="M"
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_release_commit(release, commit, order=1):
return ReleaseCommit.objects.create(
organization_id=release.organization_id,
release=release,
commit=commit,
order=order,
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_user(
email=None, is_superuser=False, is_staff=False, is_active=True, **kwargs
) -> User:
if email is None:
email = uuid4().hex + "@example.com"
kwargs.setdefault("username", email)
user = User(
email=email, is_superuser=is_superuser, is_staff=is_staff, is_active=is_active, **kwargs
)
if kwargs.get("password") is None:
user.set_password("admin")
user.save()
# UserEmail is created by a signal
assert UserEmail.objects.filter(user=user, email=email).update(is_verified=True)
return user
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_useremail(user, email=None, **kwargs):
if not email:
email = uuid4().hex + "@example.com"
kwargs.setdefault("is_verified", True)
useremail = UserEmail(user=user, email=email, **kwargs)
useremail.save()
return useremail
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_user_avatar(*args, **kwargs):
return UserAvatar.objects.create(*args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_user_role(*args, **kwargs):
return UserRole.objects.create(*args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_usersocialauth(
user: User,
provider: str | None = None,
uid: str | None = None,
extra_data: dict[str, Any] | None = None,
):
if not provider:
provider = "asana"
if not uid:
uid = "abc-123"
if extra_data is None:
extra_data = {}
usa = UserSocialAuth(user=user, provider=provider, uid=uid, extra_data=extra_data)
usa.save()
return usa
@staticmethod
def inject_performance_problems(jobs, _):
for job in jobs:
job["performance_problems"] = []
for f in job["data"]["fingerprint"]:
f_data = f.split("-", 1)
if len(f_data) < 2:
raise ValueError(
"Invalid performance fingerprint data. Format must be 'group_type-fingerprint'."
)
group_type = get_group_type_by_type_id(int(f_data[0]))
perf_fingerprint = f_data[1]
job["performance_problems"].append(
PerformanceProblem(
fingerprint=perf_fingerprint,
op="db",
desc="",
type=group_type,
parent_span_ids=None,
cause_span_ids=None,
offender_span_ids=[],
evidence_data={},
evidence_display=[],
)
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def store_event(
data,
project_id: int,
assert_no_errors: bool = True,
default_event_type: EventType | None = None,
sent_at: datetime | None = None,
) -> Event:
"""
Like `create_event`, but closer to how events are actually
ingested. Prefer to use this method over `create_event`
"""
# this creates a basic message event
if default_event_type == EventType.DEFAULT:
data.update({"stacktrace": copy.deepcopy(DEFAULT_EVENT_DATA["stacktrace"])})
# this creates an error event
elif default_event_type == EventType.ERROR:
data.update({"exception": [{"value": "BadError"}]})
manager = EventManager(data, sent_at=sent_at)
manager.normalize()
if assert_no_errors:
errors = manager.get_data().get("errors")
assert not errors, errors
normalized_data = manager.get_data()
_set_sample_rate_from_error_sampling(normalized_data)
event = None
# When fingerprint is present on transaction, inject performance problems
if (
normalized_data.get("type") == "transaction"
and normalized_data.get("fingerprint") is not None
):
with mock.patch(
"sentry.event_manager._detect_performance_problems",
Factories.inject_performance_problems,
):
event = manager.save(project_id)
else:
event = manager.save(project_id)
if event.groups:
for group in event.groups:
group.save()
if event.group:
event.group.save()
return event
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_group(project, create_open_period=True, **kwargs):
from sentry.models.group import GroupStatus
from sentry.models.groupopenperiod import GroupOpenPeriod, should_create_open_periods
from sentry.testutils.helpers.datetime import before_now
from sentry.types.group import GroupSubStatus
kwargs.setdefault("message", "Hello world")
kwargs.setdefault("data", {})
if "type" not in kwargs["data"]:
kwargs["data"].update({"type": "default", "metadata": {"title": kwargs["message"]}})
if "short_id" not in kwargs:
kwargs["short_id"] = project.next_short_id()
if "metadata" in kwargs:
metadata = kwargs.pop("metadata")
kwargs["data"].setdefault("metadata", {}).update(metadata)
if "status" not in kwargs:
kwargs["status"] = GroupStatus.UNRESOLVED
kwargs["substatus"] = GroupSubStatus.NEW
group = Group.objects.create(project=project, **kwargs)
if create_open_period and should_create_open_periods(group.type):
open_period = GroupOpenPeriod.objects.create(
group=group,
project=project,
date_started=group.first_seen or before_now(minutes=5),
)
if group.status == GroupStatus.RESOLVED:
open_period.update(
date_ended=group.resolved_at if group.resolved_at else timezone.now()
)
return group
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_group_activity(group, *args, **kwargs):
return Activity.objects.create(group=group, project=group.project, *args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_file(**kwargs):
return File.objects.create(**kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_forwarder(organization, provider, config, **kwargs):
return DataForwarder.objects.create(
organization=organization, provider=provider, config=config, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_forwarder_project(data_forwarder, project, **kwargs):
from sentry.integrations.models.data_forwarder_project import DataForwarderProject
return DataForwarderProject.objects.create(
data_forwarder=data_forwarder, project=project, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_file_from_path(path, name=None, **kwargs):
if name is None:
name = os.path.basename(path)
file = Factories.create_file(name=name, **kwargs)
with open(path) as f:
file.putfile(f)
return file
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_dif_file(
project,
debug_id=None,
object_name=None,
features=None,
data=None,
file=None,
cpu_name=None,
code_id=None,
**kwargs,
):
if debug_id is None:
debug_id = str(uuid4())
if object_name is None:
object_name = "%s.dSYM" % debug_id
if features is not None:
if data is None:
data = {}
data["features"] = features
if file is None:
file = Factories.create_file(
name=object_name,
size=42,
headers={"Content-Type": "application/x-mach-binary"},
checksum="dc1e3f3e411979d336c3057cce64294f3420f93a",
)
return ProjectDebugFile.objects.create(
debug_id=debug_id,
code_id=code_id,
project_id=project.id,
object_name=object_name,
cpu_name=cpu_name or "x86_64",
file=file,
checksum=file.checksum,
data=data,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_dif_from_path(path, object_name=None, **kwargs):
if object_name is None:
object_name = os.path.basename(path)
headers = {"Content-Type": "application/x-mach-binary"}
file = Factories.create_file_from_path(path, name=object_name, headers=headers)
return Factories.create_dif_file(file=file, object_name=object_name, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def add_user_permission(user, permission):
UserPermission.objects.create(user=user, permission=permission)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_sentry_app(**kwargs):
published = kwargs.pop("published", False)
args = Factories._sentry_app_kwargs(**kwargs)
user = args.pop("user", None)
app = SentryAppCreator(is_internal=False, **args).run(user=user, request=None)
if published:
app.update(status=SentryAppStatus.PUBLISHED)
return app
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_sentry_app_avatar(*args, **kwargs):
return SentryAppAvatar.objects.create(*args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_internal_integration(**kwargs) -> SentryApp:
args = Factories._sentry_app_kwargs(**kwargs)
args["verify_install"] = False
user = args.pop("user", None)
app = SentryAppCreator(is_internal=True, **args).run(
user=user, request=None, skip_default_auth_token=True
)
return app
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_internal_integration_token(
user,
internal_integration: SentryApp | None = None,
install: SentryAppInstallation | None = None,
request=None,
) -> ApiToken:
if internal_integration and install:
raise ValueError("Only one of internal_integration or install arg can be provided")
elif internal_integration is None and install is None:
raise ValueError("Must pass in either internal_integration or install arg")
if internal_integration is not None and install is None:
# Fetch install from provided or created internal integration
with assume_test_silo_mode(SiloMode.CONTROL):
install = SentryAppInstallation.objects.get(
sentry_app=internal_integration.id,
organization_id=internal_integration.owner_id,
)
elif install is None:
raise AssertionError("unreachable")
return SentryAppInstallationTokenCreator(sentry_app_installation=install).run(
user=user, request=request
)
@staticmethod
def _sentry_app_kwargs(**kwargs):
_kwargs = {
"user": kwargs.get("user", Factories.create_user()),
"name": kwargs.get("name", petname.generate(2, " ", letters=10).title()),
"organization_id": kwargs.get(
"organization_id", kwargs.pop("organization", Factories.create_organization()).id
),
"author": kwargs.get("author", "A Company"),
"scopes": kwargs.get("scopes", ()),
"verify_install": kwargs.get("verify_install", True),
"webhook_url": kwargs.get("webhook_url", "https://example.com/webhook"),
"events": [],
"schema": {},
}
_kwargs.update(**kwargs)
return _kwargs
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_sentry_app_installation(
organization=None,
slug=None,
user=None,
status=None,
prevent_token_exchange=False,
):
if not organization:
organization = Factories.create_organization()
Factories.create_project(organization=organization)
with assume_test_silo_mode(SiloMode.CONTROL):
install = SentryAppInstallationCreator(
slug=(slug or Factories.create_sentry_app(organization=organization).slug),
organization_id=organization.id,
).run(
user=(user or Factories.create_user()),
request=None,
)
install.status = SentryAppInstallationStatus.INSTALLED if status is None else status
install.save()
if not prevent_token_exchange and (
install.sentry_app.status != SentryAppStatus.INTERNAL
):
assert install.api_grant is not None
assert install.sentry_app.application is not None
assert install.sentry_app.proxy_user is not None
GrantExchanger(
install=install,
code=install.api_grant.code,
client_id=install.sentry_app.application.client_id,
user=install.sentry_app.proxy_user,
).run()
install = SentryAppInstallation.objects.get(id=install.id)
return install
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_sentry_app_installation_for_provider(
sentry_app_id: int,
organization_id: int,
provider: str,
) -> SentryAppInstallationForProvider:
installation = SentryAppInstallation.objects.get(
sentry_app_id=sentry_app_id, organization_id=organization_id
)
return SentryAppInstallationForProvider.objects.create(
organization_id=organization_id,
provider=provider,
sentry_app_installation=installation,
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_stacktrace_link_schema():
return {"type": "stacktrace-link", "uri": "/redirect/"}
@staticmethod
def create_issue_link_schema():
return {
"type": "issue-link",
"link": {
"uri": "/sentry/issues/link",
"required_fields": [
{
"type": "select",
"name": "assignee",
"label": "Assignee",
"uri": "/sentry/members",
}
],
},
"create": {
"uri": "/sentry/issues/create",
"required_fields": [
{"type": "text", "name": "title", "label": "Title"},
{"type": "text", "name": "summary", "label": "Summary"},
],
"optional_fields": [
{
"type": "select",
"name": "points",
"label": "Points",
"options": [["1", "1"], ["2", "2"], ["3", "3"], ["5", "5"], ["8", "8"]],
},
{
"type": "select",
"name": "assignee",
"label": "Assignee",
"uri": "/sentry/members",
},
],
},
}
@staticmethod
def create_alert_rule_action_schema():
return {
"type": "alert-rule-action",
"title": "Create Task with App",
"settings": {
"type": "alert-rule-settings",
"uri": "/sentry/alert-rule",
"required_fields": [
{"type": "text", "name": "title", "label": "Title"},
{"type": "text", "name": "summary", "label": "Summary"},
],
"optional_fields": [
{
"type": "select",
"name": "points",
"label": "Points",
"options": [["1", "1"], ["2", "2"], ["3", "3"], ["5", "5"], ["8", "8"]],
},
{
"type": "select",
"name": "assignee",
"label": "Assignee",
"uri": "/sentry/members",
},
],
},
}
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_service_hook(
actor=None, org=None, project=None, events=None, url=None, project_ids=None, **kwargs
):
if project:
if project_ids is not None:
raise ValueError("Cannot provide both project and project_ids")
project_ids = [project.id]
if not actor:
actor = Factories.create_user()
if not org:
if project:
org = project.organization
else:
org = Factories.create_organization(owner=actor)
if project_ids is None: # empty list for project_ids is valid and means no project filter
project_ids = [Factories.create_project(organization=org).id]
if events is None:
events = ["event.created"]
if not url:
url = "https://example.com/sentry/webhook"
app_id = kwargs.pop("application_id", None)
if app_id is None and "application" in kwargs:
app_id = kwargs["application"].id
installation_id = kwargs.pop("installation_id", None)
if installation_id is None and "installation" in kwargs:
installation_id = kwargs["installation"].id
hook_id = hook_service.create_service_hook(
application_id=app_id,
actor_id=actor.id,
installation_id=installation_id,
organization_id=org.id,
project_ids=project_ids,
events=events,
url=url,
).id
return ServiceHook.objects.get(id=hook_id)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_sentry_app_feature(feature=None, sentry_app=None, description=None):
if not sentry_app:
sentry_app = Factories.create_sentry_app()
integration_feature = IntegrationFeature.objects.create(
target_id=sentry_app.id,
target_type=IntegrationTypes.SENTRY_APP.value,
feature=feature or Feature.API,
)
if description:
integration_feature.update(user_description=description)
return integration_feature
@staticmethod
def _doc_integration_kwargs(**kwargs):
_kwargs = {
"name": kwargs.get("name", petname.generate(2, " ", letters=10).title()),
"author": kwargs.get("author", "me"),
"description": kwargs.get("description", "hi im a description"),
"url": kwargs.get("url", "https://sentry.io"),
"popularity": kwargs.get("popularity", 1),
"is_draft": kwargs.get("is_draft", True),
"metadata": kwargs.get("metadata", {}),
}
_kwargs["slug"] = slugify(_kwargs["name"])
_kwargs.update(**kwargs)
return _kwargs
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_doc_integration(features=None, has_avatar: bool = False, **kwargs) -> DocIntegration:
doc = DocIntegration.objects.create(**Factories._doc_integration_kwargs(**kwargs))
if features:
Factories.create_doc_integration_features(features=features, doc_integration=doc)
if has_avatar:
Factories.create_doc_integration_avatar(doc_integration=doc)
return doc
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_doc_integration_features(
features=None, doc_integration=None
) -> list[IntegrationFeature]:
if not features:
features = [Feature.API]
if not doc_integration:
doc_integration = Factories.create_doc_integration()
return IntegrationFeature.objects.bulk_create(
[
IntegrationFeature(
target_id=doc_integration.id,
target_type=IntegrationTypes.DOC_INTEGRATION.value,
feature=feature,
)
for feature in features
]
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_doc_integration_avatar(doc_integration=None, **kwargs) -> DocIntegrationAvatar:
if not doc_integration:
doc_integration = Factories.create_doc_integration()
photo = ControlFile.objects.create(name="test.png", type="avatar.file")
photo.putfile(io.BytesIO(b"imaginethiswasphotobytes"))
return DocIntegrationAvatar.objects.create(
doc_integration=doc_integration, avatar_type=0, control_file_id=photo.id
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_userreport(
project: Project, event_id: str | None = None, **kwargs: Any
) -> UserReport:
event = Factories.store_event(
data={
"timestamp": datetime.now(UTC).isoformat(),
"event_id": event_id or "a" * 32,
"message": "testing",
},
project_id=project.id,
)
assert event.group is not None
return UserReport.objects.create(
group_id=event.group.id,
event_id=event.event_id,
project_id=project.id,
name="Jane Bloggs",
email="jane@example.com",
comments="the application crashed",
**kwargs,
)
@staticmethod
def create_session():
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session.save()
return session
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_platform_external_issue(
group=None, service_type=None, display_name=None, web_url=None
):
return PlatformExternalIssue.objects.create(
group_id=group.id,
project_id=group.project_id,
service_type=service_type,
display_name=display_name,
web_url=web_url,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_integration_external_issue(group=None, integration=None, key=None, **kwargs):
external_issue = ExternalIssue.objects.create(
organization_id=group.organization.id, integration_id=integration.id, key=key, **kwargs
)
GroupLink.objects.create(
group_id=group.id,
project_id=group.project_id,
linked_type=GroupLink.LinkedType.issue,
linked_id=external_issue.id,
relationship=GroupLink.Relationship.references,
)
return external_issue
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_integration_external_project(
organization_id: int, integration_id: int, *args: Any, **kwargs: Any
) -> IntegrationExternalProject:
oi = OrganizationIntegration.objects.get(
organization_id=organization_id, integration_id=integration_id
)
return IntegrationExternalProject.objects.create(
organization_integration_id=oi.id, *args, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_incident(
organization,
projects,
detection_uuid=None,
status=1,
title=None,
query="test query",
date_started=None,
date_detected=None,
date_closed=None,
alert_rule=None,
subscription=None,
):
if not title:
title = petname.generate(2, " ", letters=10).title()
if alert_rule is None:
alert_rule = Factories.create_alert_rule(
organization, projects, query=query, time_window=1
)
incident = Incident.objects.create(
organization=organization,
detection_uuid=detection_uuid,
status=status,
title=title,
alert_rule=alert_rule,
date_started=date_started or timezone.now(),
date_detected=date_detected or timezone.now(),
date_closed=timezone.now() if date_closed is not None else date_closed,
type=IncidentType.ALERT_TRIGGERED.value,
subscription=subscription,
)
for project in projects:
IncidentProject.objects.create(incident=incident, project=project)
return incident
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_incident_activity(incident, type, comment=None, user_id=None, **kwargs):
return IncidentActivity.objects.create(
incident=incident, type=type, comment=comment, user_id=user_id, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_alert_rule(
organization,
projects,
name=None,
owner=None,
query="level:error",
aggregate="count()",
time_window=10,
threshold_period=1,
environment=None,
date_added=None,
query_type=None,
dataset=Dataset.Events,
threshold_type=AlertRuleThresholdType.ABOVE,
resolve_threshold=None,
user=None,
event_types=None,
comparison_delta=None,
description=None,
sensitivity=None,
seasonality=None,
detection_type=AlertRuleDetectionType.STATIC,
):
if not name:
name = petname.generate(2, " ", letters=10).title()
if query_type is None:
query_type = query_datasets_to_type[dataset]
alert_rule = create_alert_rule(
organization,
projects,
name,
query,
aggregate,
time_window,
threshold_type,
threshold_period,
owner=owner,
resolve_threshold=resolve_threshold,
query_type=query_type,
dataset=dataset,
environment=environment,
user=user,
event_types=event_types,
comparison_delta=comparison_delta,
description=description,
sensitivity=sensitivity,
seasonality=seasonality,
detection_type=detection_type,
)
if date_added is not None:
alert_rule.update(date_added=date_added)
return alert_rule
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_alert_rule_trigger(alert_rule, label=None, alert_threshold=100):
if not label:
label = petname.generate(2, " ", letters=10).title()
return create_alert_rule_trigger(alert_rule, label, alert_threshold)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_incident_trigger(incident, alert_rule_trigger, status=None):
if status is None:
status = TriggerStatus.ACTIVE.value
return IncidentTrigger.objects.create(
alert_rule_trigger=alert_rule_trigger, incident=incident, status=status
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_alert_rule_trigger_action(
trigger,
type=AlertRuleTriggerAction.Type.EMAIL,
target_type=AlertRuleTriggerAction.TargetType.USER,
target_identifier=None,
integration=None,
sentry_app=None,
sentry_app_config=None,
):
return create_alert_rule_trigger_action(
trigger,
type,
target_type,
target_identifier,
integration.id if integration else None,
sentry_app.id if sentry_app else None,
sentry_app_config=sentry_app_config,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_external_user(user: User, **kwargs: Any) -> ExternalActor:
kwargs.setdefault("provider", ExternalProviders.GITHUB.value)
kwargs.setdefault("external_name", "")
return ExternalActor.objects.create(user_id=user.id, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_external_team(team: Team, **kwargs: Any) -> ExternalActor:
kwargs.setdefault("provider", ExternalProviders.GITHUB.value)
kwargs.setdefault("external_name", "@getsentry/ecosystem")
return ExternalActor.objects.create(team_id=team.id, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_codeowners(project, code_mapping, **kwargs):
kwargs.setdefault("raw", "")
return ProjectCodeOwners.objects.create(
project=project, repository_project_path_config=code_mapping, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_slack_integration(
organization: Organization, external_id: str, **kwargs: Any
) -> Integration:
integration = Integration.objects.create(
provider="slack",
name="Team A",
external_id=external_id,
metadata={
"access_token": "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx",
"installation_type": "born_as_bot",
},
)
integration.add_organization(organization)
return integration
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_integration(
organization: Organization,
external_id: str,
oi_params: Mapping[str, Any] | None = None,
**integration_params: Any,
) -> Integration:
integration = Integration.objects.create(external_id=external_id, **integration_params)
with outbox_runner():
organization_integration = integration.add_organization(organization)
assert organization_integration is not None
organization_integration.update(**(oi_params or {}))
return integration
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_provider_integration(**integration_params: Any) -> Integration:
return Integration.objects.create(**integration_params)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_provider_integration_for(
organization: Organization | RpcOrganization,
user: User | RpcUser | None,
**integration_params: Any,
) -> tuple[Integration, OrganizationIntegration]:
integration = Integration.objects.create(**integration_params)
org_integration = integration.add_organization(organization, user)
assert org_integration is not None
return integration, org_integration
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_identity_integration(
user: User | RpcUser,
organization: Organization | RpcOrganization,
integration_params: Mapping[Any, Any],
identity_params: Mapping[Any, Any],
) -> tuple[Integration, OrganizationIntegration, Identity, IdentityProvider]:
# Avoid common pitfalls in tests
assert "provider" in integration_params
assert "external_id" in integration_params
assert "external_id" in identity_params
integration = Factories.create_provider_integration(**integration_params)
identity_provider = Factories.create_identity_provider(integration=integration)
identity = Factories.create_identity(
user=user, identity_provider=identity_provider, **identity_params
)
organization_integration = integration.add_organization(
organization_id=organization.id, user=user, default_auth_id=identity.id
)
assert organization_integration is not None
return integration, organization_integration, identity, identity_provider
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_organization_integration(**integration_params: Any) -> OrganizationIntegration:
return OrganizationIntegration.objects.create(**integration_params)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_identity_provider(
integration: Integration | None = None,
config: dict[str, Any] | None = None,
**kwargs: Any,
) -> IdentityProvider:
if integration is not None:
integration_values = dict(
type=integration.provider,
external_id=integration.external_id,
)
if any((key in kwargs) for key in integration_values):
raise ValueError(
"Values from integration should not be in kwargs: "
+ repr(list(integration_values.keys()))
)
kwargs.update(integration_values)
return IdentityProvider.objects.create(config=config or {}, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_identity(
user: User | RpcUser, identity_provider: IdentityProvider, external_id: str, **kwargs: Any
) -> Identity:
return Identity.objects.create(
external_id=external_id,
idp=identity_provider,
user_id=user.id,
status=IdentityStatus.VALID,
scopes=[],
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_group_history(
group: Group,
status: int,
release: Release | None = None,
user_id: int | None = None,
team_id: int | None = None,
prev_history_date: datetime | None = None,
date_added: datetime | None = None,
) -> GroupHistory:
kwargs = {}
if date_added:
kwargs["date_added"] = date_added
return GroupHistory.objects.create(
organization=group.organization,
group=group,
project=group.project,
release=release,
user_id=user_id,
team_id=team_id,
status=status,
prev_history_date=prev_history_date,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_comment(issue, project, user, text="hello world"):
data = {"text": text}
return Activity.objects.create(
project=project,
group=issue,
type=ActivityType.NOTE.value,
user_id=user.id,
data=data,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_saved_search(name: str, **kwargs):
if "owner" in kwargs:
owner = kwargs.pop("owner")
kwargs["owner_id"] = owner.id if not isinstance(owner, int) else owner
return SavedSearch.objects.create(name=name, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_notification_action(
organization: Organization | None = None,
projects: list[Project] | None = None,
**kwargs,
):
if not organization:
organization = Factories.create_organization()
if not projects:
projects = []
action_kwargs = {
"organization": organization,
"type": ActionService.SENTRY_NOTIFICATION,
"target_type": ActionTarget.USER,
"target_identifier": "1",
"target_display": "Sentry User",
"trigger_type": ActionTrigger.AUDIT_LOG,
**kwargs,
}
action = NotificationAction.objects.create(**action_kwargs)
action.projects.add(*projects)
action.save()
return action
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_notification_settings_provider(*args, **kwargs) -> NotificationSettingProvider:
return NotificationSettingProvider.objects.create(*args, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_user_option(*args, **kwargs) -> UserOption:
return UserOption.objects.create(*args, **kwargs)
@staticmethod
def create_basic_auth_header(username: str, password: str = "") -> bytes:
return b"Basic " + b64encode(f"{username}:{password}".encode())
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def snooze_rule(**kwargs):
return RuleSnooze.objects.create(**kwargs)
@staticmethod
def create_request_access(
sso_state: RpcMemberSsoState | None = None,
permissions: list | None = None,
org_context: RpcUserOrganizationContext | None = None,
scopes_upper_bound: frozenset | None = frozenset(),
) -> RpcBackedAccess:
if not sso_state:
sso_state = RpcMemberSsoState()
if not permissions:
permissions = []
if not org_context:
org_context = RpcUserOrganizationContext()
auth_state = RpcAuthState(sso_state=sso_state, permissions=permissions)
return RpcBackedAccess(
rpc_user_organization_context=org_context,
auth_state=auth_state,
scopes_upper_bound=scopes_upper_bound,
)
@staticmethod
@assume_test_silo_mode(SiloMode.CONTROL)
def create_webhook_payload(
mailbox_name: str, region_name: str | None, **kwargs
) -> WebhookPayload:
payload_kwargs = {
"request_method": "POST",
"request_path": "/extensions/github/webhook/",
"request_headers": '{"Content-Type": "application/json"}',
"request_body": "{}",
**kwargs,
}
return WebhookPayload.objects.create(
mailbox_name=mailbox_name, region_name=region_name, **payload_kwargs
)
@staticmethod
def create_uptime_subscription(
type: str,
subscription_id: str | None,
status: UptimeSubscription.Status,
url: str | None,
url_domain: str,
url_domain_suffix: str,
host_provider_id: str,
host_provider_name: str,
interval_seconds: IntervalSecondsLiteral,
timeout_ms: int,
method,
headers,
body,
date_updated: datetime,
trace_sampling: bool = False,
):
if url is None:
url = petname.generate().title()
url = f"http://{url}.com"
return UptimeSubscription.objects.create(
type=type,
subscription_id=subscription_id,
status=status.value,
url=url,
url_domain=url_domain,
url_domain_suffix=url_domain_suffix,
host_provider_id=host_provider_id,
host_provider_name=host_provider_name,
interval_seconds=interval_seconds,
timeout_ms=timeout_ms,
date_updated=date_updated,
method=method,
headers=headers,
body=body,
trace_sampling=trace_sampling,
)
@staticmethod
def create_uptime_subscription_region(
subscription: UptimeSubscription,
region_slug: str,
mode: UptimeSubscriptionRegion.RegionMode,
) -> UptimeSubscriptionRegion:
return UptimeSubscriptionRegion.objects.create(
uptime_subscription=subscription,
region_slug=region_slug,
mode=mode,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_dashboard(
organization: Organization | None = None,
title: str | None = None,
created_by: User | None = None,
**kwargs,
):
if organization is None:
organization = Factories.create_organization()
if created_by is None:
created_by = Factories.create_user()
Factories.create_member(organization=organization, user=created_by, role="owner")
if title is None:
title = petname.generate(2, " ", letters=10).title()
return Dashboard.objects.create(
organization=organization, title=title, created_by_id=created_by.id, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_dashboard_widget(
dashboard: Dashboard | None = None,
title: str | None = None,
display_type: int | None = None,
**kwargs,
):
if dashboard is None:
dashboard = Factories.create_dashboard()
if display_type is None:
display_type = DashboardWidgetDisplayTypes.AREA_CHART
if title is None:
title = petname.generate(2, " ", letters=10).title()
return DashboardWidget.objects.create(
dashboard=dashboard, title=title, display_type=display_type, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_dashboard_widget_query(
order: int,
widget: DashboardWidget | None = None,
name: str | None = None,
**kwargs,
):
if widget is None:
widget = Factories.create_dashboard_widget()
if name is None:
name = petname.generate(2, " ", letters=10).title()
return DashboardWidgetQuery.objects.create(widget=widget, name=name, order=order, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_workflow(
name: str | None = None,
organization: Organization | None = None,
config: dict[str, Any] | None = None,
**kwargs,
) -> Workflow:
if organization is None:
organization = Factories.create_organization()
if name is None:
name = petname.generate(2, " ", letters=10).title()
if config is None:
config = {}
return Workflow.objects.create(
organization=organization, name=name, config=config, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_condition_group(
organization: Organization | None = None,
**kwargs,
) -> DataConditionGroup:
if organization is None:
organization = Factories.create_organization()
return DataConditionGroup.objects.create(organization=organization, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_workflow_data_condition_group(
workflow: Workflow | None = None,
condition_group: DataConditionGroup | None = None,
**kwargs,
) -> WorkflowDataConditionGroup:
if workflow is None:
workflow = Factories.create_workflow()
if not condition_group:
condition_group = Factories.create_data_condition_group()
return WorkflowDataConditionGroup.objects.create(
workflow=workflow, condition_group=condition_group
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_condition(
condition_group: DataConditionGroup | None = None, **kwargs
) -> DataCondition:
if condition_group is None:
condition_group = Factories.create_data_condition_group()
return DataCondition.objects.create(condition_group=condition_group, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_source(
organization: Organization | None = None,
source_id: str | None = None,
type: str | None = None,
**kwargs,
) -> DataSource:
if organization is None:
organization = Factories.create_organization()
if source_id is None:
source_id = str(random.randint(1, 10000))
if type is None:
type = data_source_type_registry.get_key(QuerySubscriptionDataSourceHandler)
return DataSource.objects.create(organization=organization, source_id=source_id, type=type)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_detector(
name: str | None = None,
config: dict | None = None,
**kwargs,
) -> Detector:
if name is None:
name = petname.generate(2, " ", letters=10).title()
if config is None:
config = default_detector_config_data.get(kwargs["type"], {})
if kwargs.get("type") in (ErrorGroupType.slug, IssueStreamGroupType.slug):
detector, _ = Detector.objects.get_or_create(
type=kwargs["type"],
project=kwargs["project"],
defaults={"config": {}, "name": name},
)
detector.update(config=config, name=name, **kwargs)
return detector
return Detector.objects.create(
name=name,
config=config,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_detector_state(
detector: Detector | None = None,
**kwargs,
) -> DetectorState:
if detector is None:
detector = Factories.create_detector()
return DetectorState.objects.create(detector=detector, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_source_detector(
data_source: DataSource | None = None,
detector: Detector | None = None,
**kwargs,
) -> DataSourceDetector:
if data_source is None:
data_source = Factories.create_data_source()
if detector is None:
detector = Factories.create_detector()
return DataSourceDetector.objects.create(data_source=data_source, detector=detector)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_action(
config: dict[str, Any] | None = None,
type: Action.Type | None = None,
data: dict[str, Any] | None = None,
**kwargs,
) -> Action:
if config is None and type is None and data is None:
# Default to a slack action with nice defaults so someone can just do
# self.create_action() and have a sane default
config = {
"target_identifier": "1",
"target_display": "Sentry User",
"target_type": ActionTarget.SPECIFIC,
}
data = {"notes": "bufos are great", "tags": "bufo-bot"}
if config is None:
config = {}
if data is None:
data = {}
if type is None:
type = Action.Type.SLACK
return Action.objects.create(type=type, config=config, data=data, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_detector_workflow(
detector: Detector | None = None,
workflow: Workflow | None = None,
**kwargs,
) -> DetectorWorkflow:
if detector is None:
detector = Factories.create_detector()
if workflow is None:
workflow = Factories.create_workflow()
return DetectorWorkflow.objects.create(detector=detector, workflow=workflow, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_detector_group(
detector: Detector,
group: Group,
**kwargs,
) -> DetectorGroup:
return DetectorGroup.objects.create(detector=detector, group=group, **kwargs)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_alert_rule_workflow(
alert_rule_id: int | None = None,
rule_id: int | None = None,
workflow: Workflow | None = None,
**kwargs,
) -> AlertRuleWorkflow:
if rule_id is None and alert_rule_id is None:
raise ValueError("Either rule_id or alert_rule_id must be provided")
if rule_id is not None and alert_rule_id is not None:
raise ValueError("Only one of rule_id or alert_rule_id can be provided")
if workflow is None:
workflow = Factories.create_workflow()
return AlertRuleWorkflow.objects.create(
alert_rule_id=alert_rule_id, rule_id=rule_id, workflow=workflow, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_incident_group_open_period(
incident: Incident,
group_open_period: GroupOpenPeriod,
**kwargs,
) -> IncidentGroupOpenPeriod:
return IncidentGroupOpenPeriod.objects.create(
incident_id=incident.id,
incident_identifier=incident.identifier,
group_open_period=group_open_period,
**kwargs,
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_alert_rule_detector(
alert_rule_id: int | None = None,
rule_id: int | None = None,
detector: Detector | None = None,
**kwargs,
) -> AlertRuleDetector:
if rule_id is None and alert_rule_id is None:
raise ValueError("Either rule_id or alert_rule_id must be provided")
if rule_id is not None and alert_rule_id is not None:
raise ValueError("Only one of rule_id or alert_rule_id can be provided")
if detector is None:
detector = Factories.create_detector()
return AlertRuleDetector.objects.create(
alert_rule_id=alert_rule_id, rule_id=rule_id, detector=detector, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_action_alert_rule_trigger_action(
alert_rule_trigger_action_id: int,
action: Action | None = None,
**kwargs,
) -> ActionAlertRuleTriggerAction:
if action is None:
action = Factories.create_action()
return ActionAlertRuleTriggerAction.objects.create(
action=action, alert_rule_trigger_action_id=alert_rule_trigger_action_id
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_data_condition_group_action(
action: Action | None = None,
condition_group: DataConditionGroup | None = None,
**kwargs,
) -> DataConditionGroupAction:
if action is None:
action = Factories.create_action()
if condition_group is None:
condition_group = Factories.create_data_condition_group()
return DataConditionGroupAction.objects.create(
action=action, condition_group=condition_group, **kwargs
)
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_preprod_artifact_size_metrics(
artifact,
metrics_type=None,
state=None,
identifier=None,
min_download_size=1024 * 1024, # 1 MB
max_download_size=1024 * 1024, # 1 MB
min_install_size=2 * 1024 * 1024, # 2 MB
max_install_size=2 * 1024 * 1024, # 2 MB
):
if metrics_type is None:
metrics_type = PreprodArtifactSizeMetrics.MetricsArtifactType.MAIN_ARTIFACT
if state is None:
state = PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
return PreprodArtifactSizeMetrics.objects.create(
preprod_artifact=artifact,
metrics_artifact_type=metrics_type,
state=state,
identifier=identifier,
min_download_size=(
min_download_size
if state == PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
else None
),
max_download_size=(
max_download_size
if state == PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
else None
),
min_install_size=(
min_install_size
if state == PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
else None
),
max_install_size=(
max_install_size
if state == PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
else None
),
)
| Factories |
python | facelessuser__pymdown-extensions | pymdownx/caret.py | {
"start": 5746,
"end": 7425
} | class ____(Extension):
"""Add insert and/or superscript extension to Markdown class."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'smart_insert': [True, "Treat ^^connected^^words^^ intelligently - Default: True"],
'insert': [True, "Enable insert - Default: True"],
'superscript': [True, "Enable superscript - Default: True"]
}
super().__init__(*args, **kwargs)
def extendMarkdown(self, md):
"""Insert `<ins>test</ins>` tags as `^^test^^` and `<sup>test</sup>` tags as `^test^`."""
config = self.getConfigs()
insert = bool(config.get('insert', True))
superscript = bool(config.get('superscript', True))
smart = bool(config.get('smart_insert', True))
md.registerExtension(self)
escape_chars = []
if insert or superscript:
escape_chars.append('^')
if superscript:
escape_chars.append(' ')
util.escape_chars(md, escape_chars)
caret = None
md.inlinePatterns.register(SimpleTextInlineProcessor(NOT_CARET), 'not_tilde', 70)
if insert and superscript:
caret = CaretSmartProcessor(r'\^') if smart else CaretProcessor(r'\^')
elif insert:
caret = CaretSmartInsertProcessor(r'\^') if smart else CaretInsertProcessor(r'\^')
elif superscript:
caret = CaretSupProcessor(r'\^')
if caret is not None:
md.inlinePatterns.register(caret, "sup_ins", 65)
def makeExtension(*args, **kwargs):
"""Return extension."""
return InsertSupExtension(*args, **kwargs)
| InsertSupExtension |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/assets/model_assets.py | {
"start": 2198,
"end": 13810
} | class ____(nn.Module):
"""Improved CNN for MNIST digit classification based on research."""
def __init__(self, config: ModelConfig = None):
super().__init__()
if config is None:
config = ModelConfig()
self.config = config
# First convolutional block
self.conv1 = nn.Conv2d(
1, config.conv1_channels, kernel_size=5, padding=2
) # 5x5 kernel, maintain size
self.bn1 = nn.BatchNorm2d(config.conv1_channels) if config.use_batch_norm else nn.Identity()
self.pool1 = nn.MaxPool2d(2, 2) # 28x28 -> 14x14
# Second convolutional block
self.conv2 = nn.Conv2d(
config.conv1_channels, config.conv2_channels, kernel_size=5, padding=2
)
self.bn2 = nn.BatchNorm2d(config.conv2_channels) if config.use_batch_norm else nn.Identity()
self.pool2 = nn.MaxPool2d(2, 2) # 14x14 -> 7x7
# Third convolutional block (new)
self.conv3 = nn.Conv2d(
config.conv2_channels, config.conv3_channels, kernel_size=3, padding=1
)
self.bn3 = nn.BatchNorm2d(config.conv3_channels) if config.use_batch_norm else nn.Identity()
self.pool3 = nn.AdaptiveAvgPool2d((3, 3)) # Adaptive pooling to 3x3
# Dropout layers
self.dropout1 = nn.Dropout2d(config.dropout1_rate)
self.dropout2 = nn.Dropout(config.dropout2_rate)
# Calculate the flattened size: 3x3 * conv3_channels
conv_output_size = 3 * 3 * config.conv3_channels
# Fully connected layers
self.fc1 = nn.Linear(conv_output_size, config.hidden_size)
self.fc2 = nn.Linear(config.hidden_size, config.hidden_size // 2) # Additional FC layer
self.fc3 = nn.Linear(config.hidden_size // 2, 10)
def _conv_block(self, x, conv, bn, pool, dropout=None):
"""Apply a convolutional block: conv -> bn -> relu -> pool -> dropout (optional)."""
x = conv(x)
x = bn(x)
x = F.relu(x)
x = pool(x)
if dropout is not None:
x = dropout(x)
return x
def _fc_block(self, x, fc, dropout=None):
"""Apply a fully connected block: linear -> relu -> dropout (optional)."""
x = fc(x)
x = F.relu(x)
if dropout is not None:
x = dropout(x)
return x
def forward(self, x):
"""Forward pass through the CNN architecture.
Input: (batch_size, 1, 28, 28) - MNIST digit images
Output: (batch_size, 10) - Raw logits for 10 digit classes
Architecture flow:
1. Conv1: 28x28 -> 14x14 (5x5 kernel, 32 channels)
2. Conv2: 14x14 -> 7x7 (5x5 kernel, 64 channels) + spatial dropout
3. Conv3: 7x7 -> 3x3 (3x3 kernel, 128 channels, adaptive pooling)
4. Flatten: 3x3*128 = 1152 features
5. FC layers: 1152 -> 256 -> 128 -> 10 (with dropout)
"""
# Convolutional layers with progressive downsampling
x = self._conv_block(x, self.conv1, self.bn1, self.pool1)
x = self._conv_block(x, self.conv2, self.bn2, self.pool2, self.dropout1)
x = self._conv_block(x, self.conv3, self.bn3, self.pool3)
# Flatten spatial dimensions for fully connected layers
x = torch.flatten(x, 1) # Keep batch dimension
# Fully connected layers with progressive feature reduction
x = self._fc_block(x, self.fc1, self.dropout2)
x = self._fc_block(x, self.fc2)
x = self.fc3(x) # Final layer - no activation (raw logits)
return x # Return raw logits for CrossEntropyLoss
# end_cnn_architecture
def train_model(context, model, train_loader, val_loader, config: ModelConfig):
"""Train the digit classification model with configurable parameters."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
context.log.info(f"Training on device: {device}")
model.to(device)
# Get optimizer using utility function
optimizer = get_optimizer(config, model.parameters())
context.log.info(f"Using {config.optimizer_type} optimizer with lr={config.learning_rate}")
criterion = nn.CrossEntropyLoss()
# Add learning rate scheduler
scheduler = None
if config.use_lr_scheduler:
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=LR_STEP_SIZE, gamma=LR_GAMMA)
context.log.info(f"Using StepLR scheduler with step_size={LR_STEP_SIZE}, gamma={LR_GAMMA}")
train_losses = []
val_accuracies = []
# Early stopping variables
best_val_accuracy = 0.0
patience_counter = 0
# Log training configuration
context.log.info("Starting training with:")
context.log.info(f"- Batch size: {config.batch_size}")
context.log.info(f"- Max epochs: {config.epochs}")
context.log.info(f"- Early stopping patience: {EARLY_STOPPING_PATIENCE}")
context.log.info(f"- Model architecture:\n{model!s}")
for epoch in range(config.epochs):
# Training phase
model.train()
train_loss = 0
batch_count = 0
correct_train = 0
total_train = 0
for batch_idx, (data, target) in enumerate(train_loader):
_data, _target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(_data)
loss = criterion(output, _target)
loss.backward()
optimizer.step()
train_loss += loss.item()
batch_count += 1
# Calculate training accuracy
_, predicted = torch.max(output.data, 1)
total_train += target.size(0)
correct_train += (predicted == target).sum().item()
# Log progress every 100 batches
if (batch_idx + 1) % 100 == 0:
context.log.debug(
f"Epoch {epoch + 1}/{config.epochs} "
f"[{batch_idx + 1}/{len(train_loader)}] "
f"Loss: {loss.item():.4f}"
)
avg_train_loss = train_loss / batch_count
train_accuracy = 100 * correct_train / total_train
train_losses.append(avg_train_loss)
# Validation phase
model.eval()
val_correct = 0
val_total = 0
val_loss = 0
with torch.no_grad():
for data, target in val_loader:
_data, _target = data.to(device), target.to(device)
outputs = model(_data)
val_loss += criterion(outputs, _target).item()
_, predicted = torch.max(outputs.data, 1)
val_total += _target.size(0)
val_correct += (predicted == _target).sum().item()
val_accuracy = 100 * val_correct / val_total
avg_val_loss = val_loss / len(val_loader)
val_accuracies.append(val_accuracy)
# Log epoch results
context.log.info(
f"Epoch {epoch + 1}/{config.epochs} - "
f"Train Loss: {avg_train_loss:.4f} - "
f"Train Acc: {train_accuracy:.2f}% - "
f"Val Loss: {avg_val_loss:.4f} - "
f"Val Acc: {val_accuracy:.2f}% - "
f"LR: {optimizer.param_groups[0]['lr']:.6f}"
)
# Early stopping logic
if config.use_early_stopping:
if val_accuracy > best_val_accuracy + config.min_delta:
best_val_accuracy = val_accuracy
patience_counter = 0
context.log.info(f"New best validation accuracy: {best_val_accuracy:.2f}%")
else:
patience_counter += 1
context.log.info(
f"Validation accuracy did not improve. "
f"Best: {best_val_accuracy:.2f}% "
f"Current: {val_accuracy:.2f}% "
f"Patience: {patience_counter}/{config.patience}"
)
if patience_counter >= config.patience:
context.log.warning(
f"Early stopping triggered after {epoch + 1} epochs. "
f"Best validation accuracy: {best_val_accuracy:.2f}%"
)
break
# Step the learning rate scheduler
if scheduler is not None:
scheduler.step()
context.log.debug(f"Learning rate adjusted to: {optimizer.param_groups[0]['lr']:.6f}")
# Final training summary
context.log.info("Training completed:")
context.log.info(f"- Best validation accuracy: {best_val_accuracy:.2f}%")
context.log.info(f"- Final learning rate: {optimizer.param_groups[0]['lr']:.6f}")
context.log.info(f"- Total epochs run: {epoch + 1}")
return model, train_losses, val_accuracies
# start_training_asset
@dg.asset(
description="Train CNN digit classifier with configurable parameters",
group_name="model_pipeline",
required_resource_keys={"model_storage"},
)
def digit_classifier(
context,
processed_mnist_data: dict[str, torch.Tensor],
config: ModelConfig,
) -> DigitCNN:
"""Train a CNN to classify handwritten digits 0-9 with flexible configuration."""
context.log.info(f"Training with config: {config.model_dump()}")
train_data = processed_mnist_data["train_data"]
val_data = processed_mnist_data["val_data"]
train_labels = processed_mnist_data["train_labels"]
val_labels = processed_mnist_data["val_labels"]
# Create data loaders with configurable batch size
train_dataset = TensorDataset(train_data, train_labels)
val_dataset = TensorDataset(val_data, val_labels)
train_loader = DataLoader(train_dataset, batch_size=config.batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=config.batch_size, shuffle=False)
# Initialize model with configuration
model = DigitCNN(config)
# Train the model - pass context to train_model
trained_model, train_losses, val_accuracies = train_model(
context, model, train_loader, val_loader, config
)
final_val_accuracy = val_accuracies[-1]
# Add metadata
context.add_output_metadata(
{
"final_val_accuracy": final_val_accuracy,
"training_epochs": len(train_losses),
"configured_epochs": config.epochs,
"model_parameters": sum(p.numel() for p in trained_model.parameters()),
"final_train_loss": train_losses[-1],
"learning_rate": config.learning_rate,
"batch_size": config.batch_size,
"optimizer": config.optimizer_type,
"early_stopping_used": config.use_early_stopping,
}
)
context.log.info(
f"Model training completed. Final validation accuracy: {final_val_accuracy:.2f}%"
)
# Save model as pickle file if requested
if config.save_model:
# Create models directory if it doesn't exist
model_dir = Path(config.model_save_dir)
model_dir.mkdir(exist_ok=True)
# Create filename with timestamp and accuracy
from datetime import datetime
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
accuracy_str = f"{final_val_accuracy:.2f}".replace(".", "p")
filename = f"{config.model_name_prefix}_{timestamp}_acc{accuracy_str}.pkl"
# Save the trained model
context.log.info(f"Saving model as {filename}")
model_store = context.resources.model_storage
model_store.save_model(trained_model, filename)
context.add_output_metadata(
{"model_name": filename, "final_accuracy": final_val_accuracy},
output_name="result",
)
return trained_model
# end_training_asset
| DigitCNN |
python | huggingface__transformers | src/transformers/models/siglip2/modular_siglip2.py | {
"start": 12697,
"end": 14554
} | class ____(SiglipVisionModel):
# Update: add `spatial_shapes` and `pixel_attention_mask`
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
pixel_attention_mask: torch.Tensor,
spatial_shapes: torch.LongTensor,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
) -> BaseModelOutputWithPooling:
r"""
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
Mask to avoid performing attention on padding pixel indices.
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
Tensor containing the spatial dimensions (height, width) of the input images.
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Siglip2VisionModel
>>> model = Siglip2VisionModel.from_pretrained("google/siglip2-base-patch16-224")
>>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled features
```"""
return self.vision_model(
pixel_values=pixel_values,
attention_mask=pixel_attention_mask,
spatial_shapes=spatial_shapes,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
| Siglip2VisionModel |
python | pypa__warehouse | warehouse/subscriptions/models.py | {
"start": 601,
"end": 1114
} | class ____(StrLabelEnum):
# Name = "value", _("Label")
Active = "active", _("Active")
PastDue = "past_due", _("Past Due")
Unpaid = "unpaid", _("Unpaid")
Canceled = "canceled", _("Canceled")
Incomplete = "incomplete", _("Incomplete")
IncompleteExpired = "incomplete_expired", _("Incomplete Expired")
Trialing = "trialing", _("Trialing")
@classmethod
def has_value(cls, value):
return value in {item.value for item in StripeSubscriptionStatus}
| StripeSubscriptionStatus |
python | mitmproxy__pdoc | pdoc/web.py | {
"start": 3765,
"end": 4791
} | class ____(http.server.HTTPServer):
"""pdoc's live-reloading web server"""
all_modules: AllModules
def __init__(self, addr: tuple[str, int], specs: list[str], **kwargs):
super().__init__(addr, DocHandler, **kwargs) # type: ignore
module_names = extract.walk_specs(specs)
self.all_modules = AllModules(module_names)
@cache
def render_search_index(self) -> str:
"""Render the search index. For performance reasons this is always cached."""
# Some modules may not be importable, which means that they would raise an RuntimeError
# when accessed. We "fix" this by pre-loading all modules here and only passing the ones that work.
all_modules_safe = {}
for mod in self.all_modules:
try:
all_modules_safe[mod] = doc.Module.from_name(mod)
except RuntimeError:
warnings.warn(f"Error importing {mod!r}:\n{traceback.format_exc()}")
return render.search_index(all_modules_safe)
| DocServer |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 32556,
"end": 33164
} | class ____(_MutableSetTestBase, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
MutableSet = cls._type_fixture()
mutable_pickle = MutableSet.as_mutable(PickleType)
Table(
"foo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("skip", mutable_pickle),
Column("data", mutable_pickle),
Column("non_mutable_data", PickleType),
Column("unrelated_data", String(50)),
)
| MutableSetWithScalarPickleTest |
python | huggingface__transformers | src/transformers/models/dinov3_convnext/configuration_dinov3_convnext.py | {
"start": 939,
"end": 5695
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DINOv3ConvNextModel`]. It is used to instantiate an
DINOv3ConvNext model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the DINOv3ConvNext
[facebook/dinov3-convnext-tiny-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-convnext-tiny-pretrain-lvd1689m) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
hidden_sizes (`list[int]`, *optional*, defaults to [96, 192, 384, 768]):
Dimensionality (hidden size) at each stage.
depths (`list[int]`, *optional*, defaults to [3, 3, 9, 3]):
The number of layers for each stage.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
`"selu"` and `"gelu_new"` are supported.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
layer_scale_init_value (`float`, *optional*, defaults to 1e-06):
The initial value for the layer scale.
drop_path_rate (`float`, *optional*, defaults to 0.0):
The drop rate for stochastic depth.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of input images.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
Example:
```python
>>> from transformers import DINOv3ConvNextConfig, DINOv3ConvNextModel
>>> # Initializing a DINOv3ConvNext (tiny variant) style configuration
>>> config = DINOv3ConvNextConfig()
>>> # Initializing a model (with random weights)
>>> model = DINOv3ConvNextModel(config)
>>> # Accessing the model config
>>> config = model.config
```"""
model_type = "dinov3_convnext"
def __init__(
self,
num_channels: int = 3,
hidden_sizes: Optional[list[int]] = None,
depths: Optional[list[int]] = None,
hidden_act: str = "gelu",
initializer_range: float = 0.02,
layer_norm_eps: float = 1e-6,
layer_scale_init_value: float = 1e-6,
drop_path_rate: float = 0.0,
image_size: int = 224,
out_features: Optional[list[str]] = None,
out_indices: Optional[list[int]] = None,
**kwargs,
):
super().__init__(**kwargs)
self.num_channels = num_channels
self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
self.depths = [3, 3, 9, 3] if depths is None else depths
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.layer_scale_init_value = layer_scale_init_value
self.drop_path_rate = drop_path_rate
self.image_size = image_size
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
@property
def num_stages(self) -> int:
return len(self.hidden_sizes)
__all__ = ["DINOv3ConvNextConfig"]
| DINOv3ConvNextConfig |
python | PyCQA__pylint | tests/functional/i/inconsistent/inconsistent_mro.py | {
"start": 121,
"end": 181
} | class ____(str, Str): # [inconsistent-mro]
pass
| Inconsistent |
python | huggingface__transformers | src/transformers/processing_utils.py | {
"start": 24790,
"end": 25711
} | class ____:
"""
Dataclass that holds extra useful data for processing
multimodal data. Processors currently cannot return keys,
unless it is used in model's forward. Thus we have helper
methods that calculate and return useful data from processing
input multimodals (images/videos).
Note that this dataclass is aimed to be used only in vLLM
and we might change its API in the future.
"""
num_image_tokens: Optional[list[int]] = None
num_video_tokens: Optional[list[int]] = None
num_audio_tokens: Optional[list[int]] = None
num_image_patches: Optional[list[int]] = None
def __contains__(self, key):
return hasattr(self, key) and getattr(self, key) is not None
def __getitem__(self, key):
if hasattr(self, key):
return getattr(self, key)
raise AttributeError(f"{self.__class__.__name__} has no attribute {key}")
| MultiModalData |
python | pytorch__pytorch | torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py | {
"start": 263,
"end": 19309
} | class ____:
r"""
The Activation sparsifier class aims to sparsify/prune activations in a neural
network. The idea is to attach the sparsifier to a layer (or layers) and it
zeroes out the activations based on the mask_fn (or sparsification function)
input by the user.
The mask_fn is applied once all the inputs are aggregated and reduced i.e.
mask = mask_fn(reduce_fn(aggregate_fn(activations)))
Note::
The sparsification mask is computed on the input **before it goes through the attached layer**.
Args:
model (nn.Module):
The model whose layers will be sparsified. The layers that needs to be
sparsified should be added separately using the register_layer() function
aggregate_fn (Optional, Callable):
default aggregate_fn that is used if not specified while registering the layer.
specifies how inputs should be aggregated over time.
The aggregate_fn should usually take 2 torch tensors and return the aggregated tensor.
Example
def add_agg_fn(tensor1, tensor2): return tensor1 + tensor2
reduce_fn (Optional, Callable):
default reduce_fn that is used if not specified while registering the layer.
reduce_fn will be called on the aggregated tensor i.e. the tensor obtained after
calling agg_fn() on all inputs.
Example
def mean_reduce_fn(agg_tensor): return agg_tensor.mean(dim=0)
mask_fn (Optional, Callable):
default mask_fn that is used to create the sparsification mask using the tensor obtained after
calling the reduce_fn(). This is used by default if a custom one is passed in the
register_layer().
Note that the mask_fn() definition should contain the sparse arguments that is passed in sparse_config
arguments.
features (Optional, list):
default selected features to sparsify.
If this is non-empty, then the mask_fn will be applied for each feature of the input.
For example,
mask = [mask_fn(reduce_fn(aggregated_fn(input[feature])) for feature in features]
feature_dim (Optional, int):
default dimension of input features. Again, features along this dim will be chosen
for sparsification.
sparse_config (Dict):
Default configuration for the mask_fn. This config will be passed
with the mask_fn()
Example:
>>> # xdoctest: +SKIP
>>> model = SomeModel()
>>> act_sparsifier = ActivationSparsifier(...) # init activation sparsifier
>>> # Initialize aggregate_fn
>>> def agg_fn(x, y):
>>> return x + y
>>>
>>> # Initialize reduce_fn
>>> def reduce_fn(x):
>>> return torch.mean(x, dim=0)
>>>
>>> # Initialize mask_fn
>>> def mask_fn(data):
>>> return torch.eye(data.shape).to(data.device)
>>>
>>>
>>> act_sparsifier.register_layer(
... model.some_layer,
... aggregate_fn=agg_fn,
... reduce_fn=reduce_fn,
... mask_fn=mask_fn,
... )
>>>
>>> # start training process
>>> for _ in [...]:
>>> # epoch starts
>>> # model.forward(), compute_loss() and model.backwards()
>>> # epoch ends
>>> act_sparsifier.step()
>>> # end training process
>>> sparsifier.squash_mask()
"""
def __init__(
self,
model: nn.Module,
aggregate_fn=None,
reduce_fn=None,
mask_fn=None,
features=None,
feature_dim=None,
**sparse_config,
):
self.model = model
self.defaults: dict[str, Any] = defaultdict()
self.defaults["sparse_config"] = sparse_config
# functions
self.defaults["aggregate_fn"] = aggregate_fn
self.defaults["reduce_fn"] = reduce_fn
self.defaults["mask_fn"] = mask_fn
# default feature and feature_dim
self.defaults["features"] = features
self.defaults["feature_dim"] = feature_dim
self.data_groups: dict[str, dict] = defaultdict(
dict
) # contains all relevant info w.r.t each registered layer
self.state: dict[str, Any] = defaultdict(dict) # layer name -> mask
@staticmethod
def _safe_rail_checks(args):
"""Makes sure that some of the functions and attributes are not passed incorrectly"""
# if features are not None, then feature_dim must not be None
features, feature_dim = args["features"], args["feature_dim"]
if features is not None:
if feature_dim is None:
raise AssertionError("need feature dim to select features")
# all the *_fns should be callable
fn_keys = ["aggregate_fn", "reduce_fn", "mask_fn"]
for key in fn_keys:
fn = args[key]
if not callable(fn):
raise AssertionError(f"{fn} must be callable")
def _aggregate_hook(self, name):
"""Returns hook that computes aggregate of activations passing through."""
# gather some data
feature_dim = self.data_groups[name]["feature_dim"]
features = self.data_groups[name]["features"]
agg_fn = self.data_groups[name]["aggregate_fn"]
def hook(module, input) -> None:
input_data = input[0]
data = self.data_groups[name].get("data") # aggregated data
if features is None:
# no features associated, data should not be a list
if data is None:
data = torch.zeros_like(input_data)
self.state[name]["mask"] = torch.ones_like(input_data)
out_data = agg_fn(data, input_data)
else:
# data should be a list [aggregated over each feature only]
if data is None:
out_data = [
0 for _ in range(len(features))
] # create one in case of 1st forward
self.state[name]["mask"] = [0 for _ in range(len(features))]
else:
out_data = data # a list
# compute aggregate over each feature
for feature_idx in range(len(features)):
# each feature is either a list or scalar, convert it to torch tensor
feature_tensor = (
torch.Tensor([features[feature_idx]])
.long()
.to(input_data.device)
)
data_feature = torch.index_select(
input_data, feature_dim, feature_tensor
)
if data is None:
curr_data = torch.zeros_like(data_feature)
self.state[name]["mask"][feature_idx] = torch.ones_like(
data_feature
)
else:
curr_data = data[feature_idx]
out_data[feature_idx] = agg_fn(curr_data, data_feature)
self.data_groups[name]["data"] = out_data
return hook
def register_layer(
self,
layer: nn.Module,
aggregate_fn=None,
reduce_fn=None,
mask_fn=None,
features=None,
feature_dim=None,
**sparse_config,
):
r"""
Registers a layer for sparsification. The layer should be part of self.model.
Specifically, registers a pre-forward hook to the layer. The hook will apply the aggregate_fn
and store the aggregated activations that is input over each step.
Note::
- There is no need to pass in the name of the layer as it is automatically computed as per
the fqn convention.
- All the functions (fn) passed as argument will be called at a dim, feature level.
"""
name = module_to_fqn(self.model, layer)
if name is None:
raise AssertionError("layer not found in the model")
if name in self.data_groups: # unregister layer if already present
warnings.warn(
"layer already attached to the sparsifier, deregistering the layer and registering with new config",
stacklevel=2,
)
self.unregister_layer(name=name)
local_args = copy.deepcopy(self.defaults)
update_dict = {
"aggregate_fn": aggregate_fn,
"reduce_fn": reduce_fn,
"mask_fn": mask_fn,
"features": features,
"feature_dim": feature_dim,
"layer": layer,
}
local_args.update(
(arg, val) for arg, val in update_dict.items() if val is not None
)
local_args["sparse_config"].update(sparse_config)
self._safe_rail_checks(local_args)
self.data_groups[name] = local_args
agg_hook = layer.register_forward_pre_hook(self._aggregate_hook(name=name))
self.state[name]["mask"] = (
None # mask will be created when model forward is called.
)
# attach agg hook
self.data_groups[name]["hook"] = agg_hook
# for serialization purposes, we know whether aggregate_hook is attached
# or sparsify_hook()
self.data_groups[name]["hook_state"] = "aggregate" # aggregate hook is attached
def get_mask(self, name: str | None = None, layer: nn.Module | None = None):
"""
Returns mask associated to the layer.
The mask is
- a torch tensor is features for that layer is None.
- a list of torch tensors for each feature, otherwise
Note::
The shape of the mask is unknown until model.forward() is applied.
Hence, if get_mask() is called before model.forward(), an
error will be raised.
"""
if name is None and layer is None:
raise AssertionError("Need at least name or layer obj to retrieve mask")
if name is None:
if layer is None:
raise AssertionError("layer must be provided when name is None")
name = module_to_fqn(self.model, layer)
if name is None:
raise AssertionError("layer not found in the specified model")
if name not in self.state:
raise ValueError("Error: layer with the given name not found")
mask = self.state[name].get("mask", None)
if mask is None:
raise ValueError(
"Error: shape unknown, call layer() routine at least once to infer mask"
)
return mask
def unregister_layer(self, name):
"""Detaches the sparsifier from the layer"""
# detach any hooks attached
self.data_groups[name]["hook"].remove()
# pop from the state dict
self.state.pop(name)
# pop from the data groups
self.data_groups.pop(name)
def step(self):
"""Internally calls the update_mask() function for each layer"""
with torch.no_grad():
for name, configs in self.data_groups.items():
data = configs["data"]
self.update_mask(name, data, configs)
self.data_groups[name].pop("data") # reset the accumulated data
def update_mask(self, name, data, configs):
"""
Called for each registered layer and does the following-
1. apply reduce_fn on the aggregated activations
2. use mask_fn to compute the sparsification mask
Note:
the reduce_fn and mask_fn is called for each feature, dim over the data
"""
mask = self.get_mask(name)
sparse_config = configs["sparse_config"]
features = configs["features"]
reduce_fn = configs["reduce_fn"]
mask_fn = configs["mask_fn"]
if features is None:
data = reduce_fn(data)
mask.data = mask_fn(data, **sparse_config)
else:
for feature_idx in range(len(features)):
data_feature = reduce_fn(data[feature_idx])
mask[feature_idx].data = mask_fn(data_feature, **sparse_config)
def _sparsify_hook(self, name):
"""Returns hook that applies sparsification mask to input entering the attached layer"""
mask = self.get_mask(name)
features = self.data_groups[name]["features"]
feature_dim = self.data_groups[name]["feature_dim"]
def hook(module, input):
input_data = input[0]
if features is None:
# apply to all the features
return input_data * mask
else:
# apply per feature, feature_dim
for feature_idx in range(len(features)):
feature = (
torch.Tensor([features[feature_idx]])
.long()
.to(input_data.device)
)
sparsified = (
torch.index_select(input_data, feature_dim, feature)
* mask[feature_idx]
)
input_data.index_copy_(feature_dim, feature, sparsified)
return input_data
return hook
def squash_mask(self, attach_sparsify_hook=True, **kwargs):
"""
Unregisters aggregate hook that was applied earlier and registers sparsification hooks if
attach_sparsify_hook = True.
"""
for name, configs in self.data_groups.items():
# unhook agg hook
configs["hook"].remove()
configs.pop("hook")
self.data_groups[name]["hook_state"] = "None"
if attach_sparsify_hook:
configs["hook"] = configs["layer"].register_forward_pre_hook(
self._sparsify_hook(name)
)
configs["hook_state"] = (
"sparsify" # signals that sparsify hook is now attached
)
def _get_serializable_data_groups(self):
"""Exclude hook and layer from the config keys before serializing
TODO: Might have to treat functions (reduce_fn, mask_fn etc) in a different manner while serializing.
For time-being, functions are treated the same way as other attributes
"""
data_groups: dict[str, Any] = defaultdict()
for name, config in self.data_groups.items():
new_config = {
key: value
for key, value in config.items()
if key not in ["hook", "layer"]
}
data_groups[name] = new_config
return data_groups
def _convert_mask(self, states_dict, sparse_coo=True):
r"""Converts the mask to sparse coo or dense depending on the `sparse_coo` argument.
If `sparse_coo=True`, then the mask is stored as sparse coo else dense tensor
"""
states = copy.deepcopy(states_dict)
for state in states.values():
if state["mask"] is not None:
if isinstance(state["mask"], list):
for idx in range(len(state["mask"])):
if sparse_coo:
state["mask"][idx] = state["mask"][idx].to_sparse_coo()
else:
state["mask"][idx] = state["mask"][idx].to_dense()
else:
if sparse_coo:
state["mask"] = state["mask"].to_sparse_coo()
else:
state["mask"] = state["mask"].to_dense()
return states
def state_dict(self) -> dict[str, Any]:
r"""Returns the state of the sparsifier as a :class:`dict`.
It contains:
* state - contains name -> mask mapping.
* data_groups - a dictionary containing all config information for each
layer
* defaults - the default config while creating the constructor
"""
data_groups = self._get_serializable_data_groups()
state = self._convert_mask(self.state)
return {"state": state, "data_groups": data_groups, "defaults": self.defaults}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
r"""The load_state_dict() restores the state of the sparsifier based on the state_dict
Args:
* state_dict - the dictionary that to which the current sparsifier needs to be restored to
"""
state = state_dict["state"]
data_groups, defaults = state_dict["data_groups"], state_dict["defaults"]
self.__set_state__(
{"state": state, "data_groups": data_groups, "defaults": defaults}
)
def __get_state__(self) -> dict[str, Any]:
data_groups = self._get_serializable_data_groups()
state = self._convert_mask(self.state)
return {
"defaults": self.defaults,
"state": state,
"data_groups": data_groups,
}
def __set_state__(self, state: dict[str, Any]) -> None:
state["state"] = self._convert_mask(
state["state"], sparse_coo=False
) # convert mask to dense tensor
self.__dict__.update(state)
# need to attach layer and hook info into the data_groups
for name, config in self.data_groups.items():
# fetch layer
layer = fqn_to_module(self.model, name)
if layer is None:
raise AssertionError(f"layer {name} not found in the model")
# if agg_mode is True, then layer in aggregate mode
if "hook_state" in config and config["hook_state"] == "aggregate":
hook = layer.register_forward_pre_hook(self._aggregate_hook(name))
elif "hook_state" in config and config["hook_state"] == "sparsify":
hook = layer.register_forward_pre_hook(self._sparsify_hook(name))
config["layer"] = layer
config["hook"] = hook # type: ignore[possibly-undefined]
def __repr__(self):
format_string = self.__class__.__name__ + " ("
for name, config in self.data_groups.items():
format_string += "\n"
format_string += "\tData Group\n"
format_string += f"\t name: {name}\n"
for key in sorted(config.keys()):
if key in ["data", "hook", "reduce_fn", "mask_fn", "aggregate_fn"]:
continue
format_string += f"\t {key}: {config[key]}\n"
format_string += ")"
return format_string
| ActivationSparsifier |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.